]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
f15907b13e8dc43a059514e210bd06a5e388fd94
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket2.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5  *   Copyright (C) 2013, 2018-2020 Sadie Powell <sadie@witchery.services>
6  *   Copyright (C) 2013 Adam <Adam@anope.org>
7  *   Copyright (C) 2012-2016 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
10  *   Copyright (C) 2008, 2012 Robin Burchell <robin+git@viroteck.net>
11  *   Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
12  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13  *
14  * This file is part of InspIRCd.  InspIRCd is free software: you can
15  * redistribute it and/or modify it under the terms of the GNU General Public
16  * License as published by the Free Software Foundation, version 2.
17  *
18  * This program is distributed in the hope that it will be useful, but WITHOUT
19  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  */
26
27
28 #include "inspircd.h"
29
30 #include "main.h"
31 #include "utils.h"
32 #include "treeserver.h"
33 #include "treesocket.h"
34 #include "resolvers.h"
35 #include "commands.h"
36
37 /* Handle ERROR command */
38 void TreeSocket::Error(CommandBase::Params& params)
39 {
40         std::string msg = params.size() ? params[0] : "";
41         SetError("received ERROR " + msg);
42 }
43
44 void TreeSocket::Split(const std::string& line, std::string& tags, std::string& prefix, std::string& command, CommandBase::Params& params)
45 {
46         std::string token;
47         irc::tokenstream tokens(line);
48
49         if (!tokens.GetMiddle(token))
50                 return;
51
52         if (token[0] == '@')
53         {
54                 if (token.length() <= 1)
55                 {
56                         this->SendError("BUG: Received a message with empty tags: " + line);
57                         return;
58                 }
59
60                 tags.assign(token, 1, std::string::npos);
61                 if (!tokens.GetMiddle(token))
62                 {
63                         this->SendError("BUG: Received a message with no command: " + line);
64                         return;
65                 }
66         }
67
68         if (token[0] == ':')
69         {
70                 if (token.length() <= 1)
71                 {
72                         this->SendError("BUG: Received a message with an empty prefix: " + line);
73                         return;
74                 }
75
76                 prefix.assign(token, 1, std::string::npos);
77                 if (!tokens.GetMiddle(token))
78                 {
79                         this->SendError("BUG: Received a message with no command: " + line);
80                         return;
81                 }
82         }
83
84         command.assign(token);
85         while (tokens.GetTrailing(token))
86                 params.push_back(token);
87 }
88
89 void TreeSocket::ProcessLine(std::string &line)
90 {
91         std::string tags;
92         std::string prefix;
93         std::string command;
94         CommandBase::Params params;
95
96         ServerInstance->Logs->Log(MODNAME, LOG_RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
97
98         Split(line, tags, prefix, command, params);
99
100         if (command.empty())
101                 return;
102
103         switch (this->LinkState)
104         {
105                 case WAIT_AUTH_1:
106                         /*
107                          * State WAIT_AUTH_1:
108                          *  Waiting for SERVER command from remote server. Server initiating
109                          *  the connection sends the first SERVER command, listening server
110                          *  replies with theirs if its happy, then if the initiator is happy,
111                          *  it starts to send its net sync, which starts the merge, otherwise
112                          *  it sends an ERROR.
113                          */
114                         if (command == "PASS")
115                         {
116                                 /*
117                                  * Ignore this silently. Some services packages insist on sending PASS, even
118                                  * when it is not required (i.e. by us). We have to ignore this here, otherwise
119                                  * as it's an unknown command (effectively), it will cause the connection to be
120                                  * closed, which probably isn't what people want. -- w00t
121                                  */
122                         }
123                         else if (command == "SERVER")
124                         {
125                                 this->Inbound_Server(params);
126                         }
127                         else if (command == "ERROR")
128                         {
129                                 this->Error(params);
130                         }
131                         else if (command == "USER")
132                         {
133                                 this->SendError("Client connections to this port are prohibited.");
134                         }
135                         else if (command == "CAPAB")
136                         {
137                                 this->Capab(params);
138                         }
139                         else
140                         {
141                                 this->SendError("Invalid command in negotiation phase: " + command);
142                         }
143                 break;
144                 case WAIT_AUTH_2:
145                         /*
146                          * State WAIT_AUTH_2:
147                          *  We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
148                          *  The other option at this stage of things, of course, is for them to close our connection thanks
149                          *  to invalid credentials.. -- w
150                          */
151                         if (command == "SERVER")
152                         {
153                                 /*
154                                  * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
155                                  * Both of these aren't allowable, so block them here. -- w
156                                  */
157                                 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
158                         }
159                         else if (command == "BURST")
160                         {
161                                 if (!params.empty())
162                                 {
163                                         time_t them = ConvToNum<time_t>(params[0]);
164                                         time_t delta = them - ServerInstance->Time();
165                                         if ((delta < -60) || (delta > 60))
166                                         {
167                                                 ServerInstance->SNO->WriteGlobalSno('l', "\002ERROR\002: Your clocks are off by %ld seconds (this is more than one minute). Link aborted, \002PLEASE SYNC YOUR CLOCKS!\002", labs((long)delta));
168                                                 SendError("Your clocks are out by "+ConvToStr(labs((long)delta))+" seconds (this is more than one minute). Link aborted, PLEASE SYNC YOUR CLOCKS!");
169                                                 return;
170                                         }
171                                         else if ((delta < -15) || (delta > 15))
172                                         {
173                                                 ServerInstance->SNO->WriteGlobalSno('l', "\002WARNING\002: Your clocks are off by %ld seconds. Please consider syncing your clocks.", labs((long)delta));
174                                         }
175                                 }
176
177                                 // Check for duplicate server name/sid again, it's possible that a new
178                                 // server was introduced while we were waiting for them to send BURST.
179                                 // (we do not reserve their server name/sid when they send SERVER, we do it now)
180                                 if (!CheckDuplicate(capab->name, capab->sid))
181                                         return;
182
183                                 FinishAuth(capab->name, capab->sid, capab->description, capab->hidden);
184                         }
185                         else if (command == "ERROR")
186                         {
187                                 this->Error(params);
188                         }
189                         else if (command == "CAPAB")
190                         {
191                                 this->Capab(params);
192                         }
193
194                 break;
195                 case CONNECTING:
196                         /*
197                          * State CONNECTING:
198                          *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
199                          *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
200                          *  + our netburst, which will put them into CONNECTED state. -- w
201                          */
202                         if (command == "SERVER")
203                         {
204                                 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
205                                 this->Outbound_Reply_Server(params);
206                         }
207                         else if (command == "ERROR")
208                         {
209                                 this->Error(params);
210                         }
211                         else if (command == "CAPAB")
212                         {
213                                 this->Capab(params);
214                         }
215                 break;
216                 case CONNECTED:
217                         /*
218                          * State CONNECTED:
219                          *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
220                          *  Anything from here on should be accepted a little more reasonably.
221                          */
222                         this->ProcessConnectedLine(tags, prefix, command, params);
223                 break;
224                 case DYING:
225                 break;
226         }
227 }
228
229 User* TreeSocket::FindSource(const std::string& prefix, const std::string& command)
230 {
231         // Empty prefix means the source is the directly connected server that sent this command
232         if (prefix.empty())
233                 return MyRoot->ServerUser;
234
235         if (prefix.size() == 3)
236         {
237                 // Prefix looks like a sid
238                 TreeServer* server = Utils->FindServerID(prefix);
239                 if (server)
240                         return server->ServerUser;
241         }
242         else
243         {
244                 // If the prefix string is a uuid FindUUID() returns the appropriate User object
245                 User* user = ServerInstance->FindUUID(prefix);
246                 if (user)
247                         return user;
248         }
249
250         // Some implementations wrongly send a server name as prefix occasionally, handle that too for now
251         TreeServer* const server = Utils->FindServer(prefix);
252         if (server)
253                 return server->ServerUser;
254
255         /* It is important that we don't close the link here, unknown prefix can occur
256          * due to various race conditions such as the KILL message for a user somehow
257          * crossing the users QUIT further upstream from the server. Thanks jilles!
258          */
259
260         if ((prefix.length() == UIDGenerator::UUID_LENGTH) && (isdigit(prefix[0])) &&
261                 ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE")))
262         {
263                 /* Special case, we cannot drop these commands as they've been committed already on a
264                  * part of the network by the time we receive them, so in this scenario pretend the
265                  * command came from a server to avoid desync.
266                  */
267
268                 TreeServer* const usersserver = Utils->FindServerID(prefix.substr(0, 3));
269                 if (usersserver)
270                         return usersserver->ServerUser;
271                 return this->MyRoot->ServerUser;
272         }
273
274         // Unknown prefix
275         return NULL;
276 }
277
278 void TreeSocket::ProcessTag(User* source, const std::string& tag, ClientProtocol::TagMap& tags)
279 {
280         std::string tagkey;
281         std::string tagval;
282         const std::string::size_type p = tag.find('=');
283         if (p != std::string::npos)
284         {
285                 // Tag has a value
286                 tagkey.assign(tag, 0, p);
287                 tagval.assign(tag, p + 1, std::string::npos);
288         }
289         else
290         {
291                 tagkey.assign(tag);
292         }
293
294         const Events::ModuleEventProvider::SubscriberList& list = Utils->Creator->tagevprov.GetSubscribers();
295         for (Events::ModuleEventProvider::SubscriberList::const_iterator i = list.begin(); i != list.end(); ++i)
296         {
297                 ClientProtocol::MessageTagProvider* const tagprov = static_cast<ClientProtocol::MessageTagProvider*>(*i);
298                 const ModResult res = tagprov->OnProcessTag(source, tagkey, tagval);
299                 if (res == MOD_RES_ALLOW)
300                         tags.insert(std::make_pair(tagkey, ClientProtocol::MessageTagData(tagprov, tagval)));
301                 else if (res == MOD_RES_DENY)
302                         break;
303         }
304 }
305
306 void TreeSocket::ProcessConnectedLine(std::string& taglist, std::string& prefix, std::string& command, CommandBase::Params& params)
307 {
308         User* who = FindSource(prefix, command);
309         if (!who)
310         {
311                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.", command.c_str(), prefix.c_str());
312                 return;
313         }
314
315         /*
316          * Check for fake direction here, and drop any instances that are found.
317          * What is fake direction? Imagine the following server setup:
318          *    0AA <-> 0AB <-> 0AC
319          * Fake direction would be 0AC sending a message to 0AB claiming to be from
320          * 0AA, or something similar. Basically, a message taking a path that *cannot*
321          * be correct.
322          *
323          * When would this be seen?
324          * Well, hopefully never. It could be caused by race conditions, bugs, or
325          * "miscreant" servers, though, so let's check anyway. -- w
326          *
327          * We also check here for totally invalid prefixes (prefixes that are neither
328          * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
329          * to the higher level functions. -- B
330          */
331         TreeServer* const server = TreeServer::Get(who);
332         if (server->GetSocket() != this)
333         {
334                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Protocol violation: Fake direction '%s' from connection '%s'", prefix.c_str(), linkID.c_str());
335                 return;
336         }
337
338         // Translate commands coming from servers using an older protocol
339         if (proto_version < PROTO_NEWEST)
340         {
341                 if (!PreProcessOldProtocolMessage(who, command, params))
342                         return;
343         }
344
345         ServerCommand* scmd = Utils->Creator->CmdManager.GetHandler(command);
346         CommandBase* cmdbase = scmd;
347         Command* cmd = NULL;
348         if (!scmd)
349         {
350                 // Not a special server-to-server command
351                 cmd = ServerInstance->Parser.GetHandler(command);
352                 if (!cmd)
353                 {
354                         if (command == "ERROR")
355                         {
356                                 this->Error(params);
357                                 return;
358                         }
359                         else if (command == "BURST")
360                         {
361                                 // This is sent even when there is no need for it, drop it here for now
362                                 return;
363                         }
364
365                         throw ProtocolException("Unknown command: " + command);
366                 }
367                 cmdbase = cmd;
368         }
369
370         if (params.size() < cmdbase->min_params)
371                 throw ProtocolException("Insufficient parameters");
372
373         if ((!params.empty()) && (params.back().empty()) && (!cmdbase->allow_empty_last_param))
374         {
375                 // the last param is empty and the command handler doesn't allow that, check if there will be enough params if we drop the last
376                 if (params.size()-1 < cmdbase->min_params)
377                         return;
378                 params.pop_back();
379         }
380
381         CmdResult res;
382         ClientProtocol::TagMap tags;
383         std::string tag;
384         irc::sepstream tagstream(taglist, ';');
385         while (tagstream.GetToken(tag))
386                 ProcessTag(who, tag, tags);
387
388         CommandBase::Params newparams(params, tags);
389
390         if (scmd)
391                 res = scmd->Handle(who, newparams);
392         else
393         {
394                 res = cmd->Handle(who, newparams);
395                 if (res == CMD_INVALID)
396                         throw ProtocolException("Error in command handler");
397         }
398
399         if (res == CMD_SUCCESS)
400                 Utils->RouteCommand(server->GetRoute(), cmdbase, newparams, who);
401 }
402
403 void TreeSocket::OnTimeout()
404 {
405         ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
406 }
407
408 void TreeSocket::Close()
409 {
410         if (!HasFd())
411                 return;
412
413         ServerInstance->GlobalCulls.AddItem(this);
414         this->BufferedSocket::Close();
415         SetError("Remote host closed connection");
416
417         // Connection closed.
418         // If the connection is fully up (state CONNECTED)
419         // then propagate a netsplit to all peers.
420         if (MyRoot)
421                 MyRoot->SQuit(getError(), true);
422
423         ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\002%s\002' failed.", linkID.c_str());
424
425         time_t server_uptime = ServerInstance->Time() - this->age;
426         if (server_uptime)
427         {
428                 std::string timestr = InspIRCd::DurationString(server_uptime);
429                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\002%s\002' was established for %s", linkID.c_str(), timestr.c_str());
430         }
431 }
432
433 void TreeSocket::FinishAuth(const std::string& remotename, const std::string& remotesid, const std::string& remotedesc, bool hidden)
434 {
435         this->LinkState = CONNECTED;
436         Utils->timeoutlist.erase(this);
437
438         linkID = remotename;
439
440         MyRoot = new TreeServer(remotename, remotedesc, remotesid, Utils->TreeRoot, this, hidden);
441
442         // Mark the server as bursting
443         MyRoot->BeginBurst();
444         this->DoBurst(MyRoot);
445
446         CommandServer::Builder(MyRoot).Forward(MyRoot);
447 }