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