]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
Merge pull request #495 from SaberUK/master+fix-libcpp
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket2.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2007-2008, 2012 Robin Burchell <robin+git@viroteck.net>
5  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6  *   Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #include "inspircd.h"
26
27 #include "main.h"
28 #include "utils.h"
29 #include "treeserver.h"
30 #include "treesocket.h"
31 #include "resolvers.h"
32
33 /* Handle ERROR command */
34 void TreeSocket::Error(parameterlist &params)
35 {
36         std::string msg = params.size() ? params[0] : "";
37         SetError("received ERROR " + msg);
38 }
39
40 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
41 {
42         irc::tokenstream tokens(line);
43
44         if (!tokens.GetToken(prefix))
45                 return;
46
47         if (prefix[0] == ':')
48         {
49                 prefix = prefix.substr(1);
50
51                 if (prefix.empty())
52                 {
53                         this->SendError("BUG (?) Empty prefix received: " + line);
54                         return;
55                 }
56                 if (!tokens.GetToken(command))
57                 {
58                         this->SendError("BUG (?) Empty command received: " + line);
59                         return;
60                 }
61         }
62         else
63         {
64                 command = prefix;
65                 prefix.clear();
66         }
67         if (command.empty())
68                 this->SendError("BUG (?) Empty command received: " + line);
69
70         std::string param;
71         while (tokens.GetToken(param))
72         {
73                 params.push_back(param);
74         }
75 }
76
77 void TreeSocket::ProcessLine(std::string &line)
78 {
79         std::string prefix;
80         std::string command;
81         parameterlist params;
82
83         ServerInstance->Logs->Log("m_spanningtree", LOG_RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
84
85         Split(line, prefix, command, params);
86
87         if (command.empty())
88                 return;
89
90         switch (this->LinkState)
91         {
92                 case WAIT_AUTH_1:
93                         /*
94                          * State WAIT_AUTH_1:
95                          *  Waiting for SERVER command from remote server. Server initiating
96                          *  the connection sends the first SERVER command, listening server
97                          *  replies with theirs if its happy, then if the initiator is happy,
98                          *  it starts to send its net sync, which starts the merge, otherwise
99                          *  it sends an ERROR.
100                          */
101                         if (command == "PASS")
102                         {
103                                 /*
104                                  * Ignore this silently. Some services packages insist on sending PASS, even
105                                  * when it is not required (i.e. by us). We have to ignore this here, otherwise
106                                  * as it's an unknown command (effectively), it will cause the connection to be
107                                  * closed, which probably isn't what people want. -- w00t
108                                  */
109                         }
110                         else if (command == "SERVER")
111                         {
112                                 this->Inbound_Server(params);
113                         }
114                         else if (command == "ERROR")
115                         {
116                                 this->Error(params);
117                         }
118                         else if (command == "USER")
119                         {
120                                 this->SendError("Client connections to this port are prohibited.");
121                         }
122                         else if (command == "CAPAB")
123                         {
124                                 this->Capab(params);
125                         }
126                         else
127                         {
128                                 this->SendError("Invalid command in negotiation phase: " + command);
129                         }
130                 break;
131                 case WAIT_AUTH_2:
132                         /*
133                          * State WAIT_AUTH_2:
134                          *  We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
135                          *  The other option at this stage of things, of course, is for them to close our connection thanks
136                          *  to invalid credentials.. -- w
137                          */
138                         if (command == "SERVER")
139                         {
140                                 /*
141                                  * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
142                                  * Both of these aren't allowable, so block them here. -- w
143                                  */
144                                 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
145                         }
146                         else if (command == "BURST")
147                         {
148                                 if (params.size())
149                                 {
150                                         time_t them = ConvToInt(params[0]);
151                                         time_t delta = them - ServerInstance->Time();
152                                         if ((delta < -600) || (delta > 600))
153                                         {
154                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than five minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs((long)delta));
155                                                 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
156                                                 return;
157                                         }
158                                         else if ((delta < -30) || (delta > 30))
159                                         {
160                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
161                                         }
162                                 }
163                                 this->LinkState = CONNECTED;
164                                 Utils->timeoutlist.erase(this);
165
166                                 MyRoot->bursting = true;
167                                 this->DoBurst(MyRoot);
168
169                                 parameterlist sparams;
170                                 sparams.push_back(MyRoot->GetName());
171                                 sparams.push_back("*");
172                                 sparams.push_back("0");
173                                 sparams.push_back(MyRoot->GetID());
174                                 sparams.push_back(":" + MyRoot->GetDesc());
175                                 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(), "SERVER", sparams, MyRoot->GetName());
176                                 Utils->DoOneToAllButSender(MyRoot->GetID(), "BURST", params, MyRoot->GetName());
177                         }
178                         else if (command == "ERROR")
179                         {
180                                 this->Error(params);
181                         }
182                         else if (command == "CAPAB")
183                         {
184                                 this->Capab(params);
185                         }
186
187                 break;
188                 case CONNECTING:
189                         /*
190                          * State CONNECTING:
191                          *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
192                          *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
193                          *  + our netburst, which will put them into CONNECTED state. -- w
194                          */
195                         if (command == "SERVER")
196                         {
197                                 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
198                                 this->Outbound_Reply_Server(params);
199                         }
200                         else if (command == "ERROR")
201                         {
202                                 this->Error(params);
203                         }
204                         else if (command == "CAPAB")
205                         {
206                                 this->Capab(params);
207                         }
208                 break;
209                 case CONNECTED:
210                         /*
211                          * State CONNECTED:
212                          *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
213                          *  Anything from here on should be accepted a little more reasonably.
214                          */
215                         this->ProcessConnectedLine(prefix, command, params);
216                 break;
217                 case DYING:
218                 break;
219         }
220 }
221
222 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
223 {
224         User* who = ServerInstance->FindUUID(prefix);
225         std::string direction;
226
227         if (!who)
228         {
229                 TreeServer* ServerSource = Utils->FindServer(prefix);
230                 if (prefix.empty())
231                         ServerSource = MyRoot;
232
233                 if (ServerSource)
234                 {
235                         who = ServerSource->ServerUser;
236                 }
237                 else
238                 {
239                         /* It is important that we don't close the link here, unknown prefix can occur
240                          * due to various race conditions such as the KILL message for a user somehow
241                          * crossing the users QUIT further upstream from the server. Thanks jilles!
242                          */
243
244                         if ((prefix.length() == UIDGenerator::UUID_LENGTH) && (isdigit(prefix[0])) &&
245                                 ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE")))
246                         {
247                                 /* Special case, we cannot drop these commands as they've been committed already on a
248                                  * part of the network by the time we receive them, so in this scenario pretend the
249                                  * command came from a server to avoid desync.
250                                  */
251
252                                 who = ServerInstance->FindUUID(prefix.substr(0, 3));
253                                 if (!who)
254                                         who = this->MyRoot->ServerUser;
255                         }
256                         else
257                         {
258                                 ServerInstance->Logs->Log("m_spanningtree", LOG_DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
259                                         command.c_str(), prefix.c_str());
260                                 return;
261                         }
262                 }
263         }
264
265         // Make sure prefix is still good
266         direction = who->server;
267         prefix = who->uuid;
268
269         /*
270          * Check for fake direction here, and drop any instances that are found.
271          * What is fake direction? Imagine the following server setup:
272          *    0AA <-> 0AB <-> 0AC
273          * Fake direction would be 0AC sending a message to 0AB claiming to be from
274          * 0AA, or something similar. Basically, a message taking a path that *cannot*
275          * be correct.
276          *
277          * When would this be seen?
278          * Well, hopefully never. It could be caused by race conditions, bugs, or
279          * "miscreant" servers, though, so let's check anyway. -- w
280          *
281          * We also check here for totally invalid prefixes (prefixes that are neither
282          * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
283          * to the higher level functions. -- B
284          */
285         TreeServer* route_back_again = Utils->BestRouteTo(direction);
286         if ((!route_back_again) || (route_back_again->GetSocket() != this))
287         {
288                 if (route_back_again)
289                         ServerInstance->Logs->Log("m_spanningtree",LOG_DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'",
290                                 prefix.c_str(),linkID.c_str());
291                 return;
292         }
293
294         /*
295          * First up, check for any malformed commands (e.g. MODE without a timestamp)
296          * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
297          */
298         if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
299                 command = "MODE";
300
301         if (proto_version < ProtocolVersion)
302         {
303                 if (!PreProcessOldProtocolMessage(who, command, params))
304                         return;
305         }
306
307         // TODO move all this into Commands
308         if (command == "MAP")
309         {
310                 Utils->Creator->HandleMap(params, who);
311         }
312         else if (command == "SERVER")
313         {
314                 this->RemoteServer(prefix,params);
315         }
316         else if (command == "ERROR")
317         {
318                 this->Error(params);
319         }
320         else if (command == "AWAY")
321         {
322                 this->Away(prefix,params);
323         }
324         else if (command == "PING")
325         {
326                 this->LocalPing(prefix,params);
327         }
328         else if (command == "PONG")
329         {
330                 TreeServer *s = Utils->FindServer(prefix);
331                 if (s && s->bursting)
332                 {
333                         ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
334                         s->FinishBurst();
335                 }
336                 this->LocalPong(prefix,params);
337         }
338         else if (command == "VERSION")
339         {
340                 this->ServerVersion(prefix,params);
341         }
342         else if (command == "ADDLINE")
343         {
344                 this->AddLine(prefix,params);
345         }
346         else if (command == "DELLINE")
347         {
348                 this->DelLine(prefix,params);
349         }
350         else if (command == "SAVE")
351         {
352                 this->ForceNick(prefix,params);
353         }
354         else if (command == "OPERQUIT")
355         {
356                 this->OperQuit(prefix,params);
357         }
358         else if (command == "IDLE")
359         {
360                 this->Whois(prefix,params);
361         }
362         else if (command == "PUSH")
363         {
364                 this->Push(prefix,params);
365         }
366         else if (command == "SQUIT")
367         {
368                 if (params.size() == 2)
369                 {
370                         this->Squit(Utils->FindServer(params[0]),params[1]);
371                 }
372         }
373         else if (command == "SNONOTICE")
374         {
375                 if (params.size() >= 2)
376                 {
377                         ServerInstance->SNO->WriteToSnoMask(params[0][0], "From " + who->nick + ": "+ params[1]);
378                         params[1] = ":" + params[1];
379                         Utils->DoOneToAllButSender(prefix, command, params, prefix);
380                 }
381         }
382         else if (command == "BURST")
383         {
384                 // Set prefix server as bursting
385                 TreeServer* ServerSource = Utils->FindServer(prefix);
386                 if (!ServerSource)
387                 {
388                         ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
389                         return;
390                 }
391
392                 ServerSource->bursting = true;
393                 Utils->DoOneToAllButSender(prefix, command, params, prefix);
394         }
395         else if (command == "ENDBURST")
396         {
397                 TreeServer* ServerSource = Utils->FindServer(prefix);
398                 if (!ServerSource)
399                 {
400                         ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
401                         return;
402                 }
403
404                 ServerSource->FinishBurst();
405                 Utils->DoOneToAllButSender(prefix, command, params, prefix);
406         }
407         else if (command == "ENCAP")
408         {
409                 this->Encap(who, params);
410         }
411         else if (command == "NICK")
412         {
413                 if (params.size() != 2)
414                 {
415                         SendError("Protocol violation: Wrong number of parameters for NICK message");
416                         return;
417                 }
418
419                 if (IS_SERVER(who))
420                 {
421                         SendError("Protocol violation: Server changing nick");
422                         return;
423                 }
424
425                 if ((isdigit(params[0][0])) && (params[0] != who->uuid))
426                 {
427                         SendError("Protocol violation: User changing nick to an invalid UID - " + params[0]);
428                         return;
429                 }
430
431                 /* Update timestamp on user when they change nicks */
432                 who->age = ConvToInt(params[1]);
433
434                 /*
435                  * On nick messages, check that the nick doesnt already exist here.
436                  * If it does, perform collision logic.
437                  */
438                 User* x = ServerInstance->FindNickOnly(params[0]);
439                 if ((x) && (x != who))
440                 {
441                         int collideret = 0;
442                         /* x is local, who is remote */
443                         collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
444                         if (collideret != 1)
445                         {
446                                 /*
447                                  * Remote client lost, or both lost, parsing or passing on this
448                                  * nickchange would be pointless, as the incoming client's server will
449                                  * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
450                                  */
451                                 return;
452                         }
453                 }
454                 who->ForceNickChange(params[0].c_str());
455                 Utils->RouteCommand(route_back_again, command, params, who);
456         }
457         else
458         {
459                 Command* cmd = ServerInstance->Parser->GetHandler(command);
460
461                 if (!cmd)
462                 {
463                         irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
464                         ServerInstance->Logs->Log("m_spanningtree", LOG_SPARSE, "Unrecognised S2S command :%s %s %s",
465                                 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
466                         SendError("Unrecognised command '" + command + "' -- possibly loaded mismatched modules");
467                         return;
468                 }
469
470                 if (params.size() < cmd->min_params)
471                 {
472                         irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
473                         ServerInstance->Logs->Log("m_spanningtree", LOG_SPARSE, "Insufficient parameters for S2S command :%s %s %s",
474                                 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
475                         SendError("Insufficient parameters for command '" + command + "'");
476                         return;
477                 }
478
479                 if ((!params.empty()) && (params.back().empty()) && (!cmd->allow_empty_last_param))
480                 {
481                         // 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
482                         if (params.size()-1 < cmd->min_params)
483                                 return;
484                         params.pop_back();
485                 }
486
487                 CmdResult res = cmd->Handle(params, who);
488
489                 if (res == CMD_INVALID)
490                 {
491                         irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
492                         ServerInstance->Logs->Log("m_spanningtree", LOG_SPARSE, "Error handling S2S command :%s %s %s",
493                                 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
494                         SendError("Error handling '" + command + "' -- possibly loaded mismatched modules");
495                 }
496                 else if (res == CMD_SUCCESS)
497                         Utils->RouteCommand(route_back_again, command, params, who);
498         }
499 }
500
501 void TreeSocket::OnTimeout()
502 {
503         ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
504 }
505
506 void TreeSocket::Close()
507 {
508         if (fd != -1)
509                 ServerInstance->GlobalCulls.AddItem(this);
510         this->BufferedSocket::Close();
511         SetError("Remote host closed connection");
512
513         // Connection closed.
514         // If the connection is fully up (state CONNECTED)
515         // then propogate a netsplit to all peers.
516         if (MyRoot)
517                 Squit(MyRoot,getError());
518
519         if (!ConnectionFailureShown)
520         {
521                 ConnectionFailureShown = true;
522                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str());
523
524                 time_t server_uptime = ServerInstance->Time() - this->age;
525                 if (server_uptime)
526                 {
527                         std::string timestr = Utils->Creator->TimeToStr(server_uptime);
528                         ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str());
529                 }
530         }
531 }