]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
085f141171d50efef76e64887c1b5c0dc0b2e4b0
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket2.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "commands/cmd_whois.h"
16 #include "commands/cmd_stats.h"
17 #include "socket.h"
18 #include "xline.h"
19 #include "../transport.h"
20 #include "socketengine.h"
21
22 #include "main.h"
23 #include "utils.h"
24 #include "treeserver.h"
25 #include "link.h"
26 #include "treesocket.h"
27 #include "resolvers.h"
28 #include "handshaketimer.h"
29
30 /* $ModDep: m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h m_spanningtree/handshaketimer.h */
31
32 /* Handle ERROR command */
33 bool TreeSocket::Error(parameterlist &params)
34 {
35         if (params.size() < 1)
36                 return false;
37         this->ServerInstance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(!InboundServerName.empty() ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
38         /* we will return false to cause the socket to close. */
39         return false;
40 }
41
42 void TreeSocket::Split(const std::string &line, parameterlist &n)
43 {
44         n.clear();
45         irc::tokenstream tokens(line);
46         std::string param;
47         while (tokens.GetToken(param))
48         {
49                 n.push_back(param);
50         }
51         return;
52 }
53
54 bool TreeSocket::ProcessLine(std::string &line)
55 {
56         parameterlist params;
57         irc::string command;
58         std::string prefix;
59
60         line = line.substr(0, line.find_first_of("\r\n"));
61
62         if (line.empty())
63                 return true;
64
65         ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
66
67         this->Split(line.c_str(),params);
68
69         if (params.empty())
70                 return true;
71
72         if ((params[0][0] == ':') && (params.size() > 1))
73         {
74                 prefix = params[0].substr(1);
75
76                 if (prefix.empty())
77                 {
78                         this->SendError("BUG (?) Empty prefix recieved: " + line);
79                         return false;
80                 }
81                 command = params[1].c_str();
82                 params.erase(params.begin(), params.begin() + 2);
83         }
84         else
85         {
86                 command = params[0].c_str();
87                 params.erase(params.begin());
88         }
89
90         switch (this->LinkState)
91         {
92                 TreeServer* Node;
93
94                 case WAIT_AUTH_1:
95                         /*
96                          * State WAIT_AUTH_1:
97                          *  Waiting for SERVER command from remote server. Server initiating
98                          *  the connection sends the first SERVER command, listening server
99                          *  replies with theirs if its happy, then if the initiator is happy,
100                          *  it starts to send its net sync, which starts the merge, otherwise
101                          *  it sends an ERROR.
102                          */
103                         if (command == "PASS")
104                         {
105                                 /*
106                                  * Ignore this silently. Some services packages insist on sending PASS, even
107                                  * when it is not required (i.e. by us). We have to ignore this here, otherwise
108                                  * as it's an unknown command (effectively), it will cause the connection to be
109                                  * closed, which probably isn't what people want. -- w00t
110                                  */
111                         }
112                         else if (command == "SERVER")
113                         {
114                                 return this->Inbound_Server(params);
115                         }
116                         else if (command == "ERROR")
117                         {
118                                 return this->Error(params);
119                         }
120                         else if (command == "USER")
121                         {
122                                 this->SendError("Client connections to this port are prohibited.");
123                                 return false;
124                         }
125                         else if (command == "CAPAB")
126                         {
127                                 return this->Capab(params);
128                         }
129                         else
130                         {
131                                 // XXX ...wtf.
132                                 irc::string error = "Invalid command in negotiation phase: " + command;
133                                 this->SendError(assign(error));
134                                 return false;
135                         }
136                 break;
137                 case WAIT_AUTH_2:
138                         /*
139                          * State WAIT_AUTH_2:
140                          *  We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
141                          *  The other option at this stage of things, of course, is for them to close our connection thanks
142                          *  to invalid credentials.. -- w
143                          */
144                         if (command == "SERVER")
145                         {
146                                 /*
147                                  * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
148                                  * Both of these aren't allowable, so block them here. -- w
149                                  */
150                                 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
151                                 return true;
152                         }
153                         else if (command == "BURST")
154                         {
155                                 if (params.size())
156                                 {
157                                         time_t them = atoi(params[0].c_str());
158                                         time_t delta = them - ServerInstance->Time();
159                                         if ((delta < -600) || (delta > 600))
160                                         {
161                                                 ServerInstance->SNO->WriteToSnoMask('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));
162                                                 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
163                                                 return false;
164                                         }
165                                         else if ((delta < -30) || (delta > 30))
166                                         {
167                                                 ServerInstance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
168                                         }
169                                 }
170                                 this->LinkState = CONNECTED;
171
172                                 Utils->timeoutlist.erase(this);
173
174                                 Link* lnk = Utils->FindLink(InboundServerName);
175
176                                 Node = new TreeServer(this->Utils, this->ServerInstance, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
177
178                                 Utils->TreeRoot->AddChild(Node);
179                                 parameterlist sparams;
180                                 sparams.push_back(InboundServerName);
181                                 sparams.push_back("*");
182                                 sparams.push_back("1");
183                                 sparams.push_back(InboundSID);
184                                 sparams.push_back(":"+InboundDescription);
185                                 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",sparams,InboundServerName);
186                                 Utils->DoOneToAllButSenderRaw(line, InboundServerName, prefix, command, params);
187                                 Node->bursting = true;
188                                 this->DoBurst(Node);
189                         }
190                         else if (command == "ERROR")
191                         {
192                                 return this->Error(params);
193                         }
194                         else if (command == "CAPAB")
195                         {
196                                 return this->Capab(params);
197                         }
198
199                 break;
200                 case CONNECTING:
201                         /*
202                          * State CONNECTING:
203                          *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
204                          *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
205                          *  + our netburst, which will put them into CONNECTED state. -- w
206                          */
207                         if (command == "SERVER")
208                         {
209                                 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
210                                 return this->Outbound_Reply_Server(params);
211                         }
212                         else if (command == "ERROR")
213                         {
214                                 return this->Error(params);
215                         }
216                         else if (command == "CAPAB")
217                         {
218                                 return this->Capab(params);
219                         }
220                 break;
221                 case CONNECTED:
222                         /*
223                         * State CONNECTED:
224                          *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
225                          *  Anything from here on should be accepted a little more reasonably.
226                          */
227                         if (!prefix.empty())
228                         {
229                                 /*
230                                  * Check for fake direction here, and drop any instances that are found.
231                                  * What is fake direction? Imagine the following server setup:
232                                  *    0AA <-> 0AB <-> 0AC
233                                  * Fake direction would be 0AC sending a message to 0AB claiming to be from
234                                  * 0AA, or something similar. Basically, a message taking a path that *cannot*
235                                  * be correct.
236                                  *
237                                  * When would this be seen?
238                                  * Well, hopefully never. It could be caused by race conditions, bugs, or
239                                  * "miscreant" servers, though, so let's check anyway. -- w
240                                  *
241                                  * We also check here for totally invalid prefixes (prefixes that are neither
242                                  * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
243                                  * to the higher level functions. -- B
244                                  */
245                                 std::string direction = prefix;
246
247                                 User *t = this->ServerInstance->FindUUID(prefix);
248                                 if (t)
249                                 {
250                                         /* Find UID */
251                                         direction = t->server;
252                                 }
253                                 else if (!this->Utils->FindServer(direction))
254                                 {
255                                         /* Find SID */
256                                         ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Protocol violation: Invalid prefix '%s' from connection '%s'", direction.c_str(), this->GetName().c_str());
257                                         return true;
258                                 }
259
260                                 TreeServer* route_back_again = Utils->BestRouteTo(direction);
261                                 if ((!route_back_again) || (route_back_again->GetSocket() != this))
262                                 {
263                                         if (route_back_again)
264                                                 ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
265                                         return true;
266                                 }
267                         }
268                         else
269                         {
270                                 /*
271                                  * Empty prefix from a server to server link:
272                                  *  This is somewhat bad/naughty, so let's set the prefix
273                                  *  to be the link that we got it from, so we don't break anything. -- w
274                                  */
275                                 TreeServer* n = Utils->FindServer(GetName());
276                                 if (n)
277                                         prefix = n->GetID();
278                                 else
279                                         prefix = GetName();
280                         }
281
282                         /*
283                          * First up, check for any malformed commands (e.g. MODE without a timestamp)
284                          * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
285                          */
286                         if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
287                                 command = "MODE";
288
289                         /*
290                          * Now, check for (and parse) commands as appropriate. -- w
291                          */
292
293                         /* Find the server that this command originated from, used in the handlers below */
294                         TreeServer *ServerSource = Utils->FindServer(prefix);
295                         if (ServerSource)
296                         {
297                                 Utils->ServerUser->SetFakeServer(ServerSource->GetName());
298                                 Utils->ServerUser->uuid = ServerSource->GetID();
299                         }
300
301                         /* Find the link we just got this from so we don't bounce it back incorrectly */
302                         std::string sourceserv = this->myhost;
303                         if (!this->InboundServerName.empty())
304                         {
305                                 sourceserv = this->InboundServerName;
306                         }
307
308                         /*
309                          * XXX one of these days, this needs to be moved into class Commands.
310                          */
311                         if (command == "UID")
312                         {
313                                 return this->ParseUID(prefix, params);
314                         }
315                         else if (command == "FJOIN")
316                         {
317                                 return this->ForceJoin(prefix,params);
318                         }
319                         else if ((command == "NOTICE" || command == "PRIVMSG") && (Utils->IsServer(prefix)))
320                         {
321                                 return this->ServerMessage(assign(command), prefix, params, sourceserv);
322                         }
323                         else if (command == "STATS")
324                         {
325                                 return this->Stats(prefix, params);
326                         }
327                         else if (command == "MOTD")
328                         {
329                                 return this->Motd(prefix, params);
330                         }
331                         else if (command == "KILL" && ServerSource)
332                         {
333                                 // Kill from a server
334                                 return this->RemoteKill(prefix,params);
335                         }
336                         else if (command == "MODULES")
337                         {
338                                 return this->Modules(prefix, params);
339                         }
340                         else if (command == "ADMIN")
341                         {
342                                 return this->Admin(prefix, params);
343                         }
344                         else if (command == "MAP")
345                         {
346                                 User* user = ServerInstance->FindNick(prefix);
347                                 if (user)
348                                 {
349                                         return Utils->Creator->HandleMap(params, user);
350                                 }
351                         }
352                         else if (command == "SERVER")
353                         {
354                                 return this->RemoteServer(prefix,params);
355                         }
356                         else if (command == "ERROR")
357                         {
358                                 return this->Error(params);
359                         }
360                         else if (command == "OPERTYPE")
361                         {
362                                 return this->OperType(prefix,params);
363                         }
364                         else if (command == "FMODE")
365                         {
366                                 return this->ForceMode(prefix,params);
367                         }
368                         else if (command == "FTOPIC")
369                         {
370                                 return this->ForceTopic(prefix,params);
371                         }
372                         else if (command == "METADATA")
373                         {
374                                 return this->MetaData(prefix,params);
375                         }
376                         else if (command == "PING")
377                         {
378                                 return this->LocalPing(prefix,params);
379                         }
380                         else if (command == "PONG")
381                         {
382                                 TreeServer *s = Utils->FindServer(prefix);
383                                 if (s && s->bursting)
384                                 {
385                                         ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
386                                         s->FinishBurst();
387                                 }
388                                 return this->LocalPong(prefix,params);
389                         }
390                         else if (command == "VERSION")
391                         {
392                                 return this->ServerVersion(prefix,params);
393                         }
394                         else if (command == "FHOST")
395                         {
396                                 return this->ChangeHost(prefix,params);
397                         }
398                         else if (command == "FNAME")
399                         {
400                                 return this->ChangeName(prefix,params);
401                         }
402                         else if (command == "FIDENT")
403                         {
404                                 return this->ChangeIdent(prefix,params);
405                         }
406                         else if (command == "ADDLINE")
407                         {
408                                 return this->AddLine(prefix,params);
409                         }
410                         else if (command == "DELLINE")
411                         {
412                                 return this->DelLine(prefix,params);
413                         }
414                         else if (command == "SVSNICK")
415                         {
416                                 return this->ForceNick(prefix,params);
417                         }
418                         else if (command == "OPERQUIT")
419                         {
420                                 return this->OperQuit(prefix,params);
421                         }
422                         else if (command == "IDLE")
423                         {
424                                 return this->Whois(prefix,params);
425                         }
426                         else if (command == "PUSH")
427                         {
428                                 return this->Push(prefix,params);
429                         }
430                         else if (command == "TIME")
431                         {
432                                 return this->Time(prefix,params);
433                         }
434                         else if (command == "SVSJOIN")
435                         {
436                                 return this->ServiceJoin(prefix,params);
437                         }
438                         else if (command == "SVSPART")
439                         {
440                                 return this->ServicePart(prefix,params);
441                         }
442                         else if (command == "SQUIT")
443                         {
444                                 if (params.size() == 2)
445                                 {
446                                         this->Squit(Utils->FindServer(params[0]),params[1]);
447                                 }
448                                 return true;
449                         }
450                         else if (command == "MODENOTICE")
451                         {
452                                 if (params.size() >= 2)
453                                 {
454                                         if (ServerSource)
455                                                 ServerInstance->Users->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()), params[1].c_str());
456                                 }
457                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
458                         }
459                         else if (command == "SNONOTICE")
460                         {
461                                 if (params.size() >= 2)
462                                 {
463                                         std::string oldprefix;
464                                         if (!ServerSource)
465                                         {
466                                                 oldprefix = prefix;
467                                                 User *u = ServerInstance->FindNick(prefix);
468                                                 if (!u)
469                                                         return true;
470                                                 prefix = u->nick;
471                                         }
472
473                                         ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + (ServerSource ? ServerSource->GetName().c_str() : prefix) + ": "+ params[1]);
474                                         prefix = oldprefix;
475                                         return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
476                                 }
477
478                         }
479                         else if (command == "BURST")
480                         {
481                                 // Set prefix server as bursting
482                                 if (!ServerSource)
483                                 {
484                                         this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got BURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
485                                         return false;
486                                 }
487
488                                 ServerSource->bursting = true;
489                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
490                         }
491                         else if (command == "ENDBURST")
492                         {
493                                 if (!ServerSource)
494                                 {
495                                         this->ServerInstance->SNO->WriteToSnoMask('l', "WTF: Got ENDBURST from a nonexistant server(?): %s", (ServerSource ? ServerSource->GetName().c_str() : prefix.c_str()));
496                                         return false;
497                                 }
498
499                                 ServerSource->FinishBurst();
500                                 return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
501                         }
502                         else if (command == "ENCAP")
503                         {
504                                 return this->Encap(prefix, params);
505                         }
506                         else
507                         {
508                                 /*
509                                  * Not a special s2s command. Emulate the user doing it.
510                                  * This saves us having a huge ugly command parser again.
511                                  */
512                                 User* who = this->ServerInstance->FindUUID(prefix);
513
514                                 if (ServerSource)
515                                 {
516                                         who = Utils->ServerUser;
517                                 }
518                                 else if (!who)
519                                 {
520                                         /* this looks ugly because command is an irc::string
521                                          * It is important that we dont close the link here, unknown prefix can occur
522                                          * due to various race conditions such as the KILL message for a user somehow
523                                          * crossing the users QUIT further upstream from the server. Thanks jilles!
524                                          */
525                                         ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command " + std::string(command.c_str()) + " from unknown prefix " + prefix + "! Dropping entire command.");
526                                         return true;
527                                 }
528
529                                 if (command == "NICK")
530                                 {
531                                         if (params.size() != 2)
532                                         {
533                                                 SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
534                                                 return false;
535                                         }
536                                         /* Update timestamp on user when they change nicks */
537                                         who->age = atoi(params[1].c_str());
538
539                                         /*
540                                          * On nick messages, check that the nick doesnt already exist here.
541                                          * If it does, perform collision logic.
542                                          */
543                                         User* x = this->ServerInstance->FindNickOnly(params[0]);
544                                         if ((x) && (x != who))
545                                         {
546                                                 int collideret = 0;
547                                                 /* x is local, who is remote */
548                                                 collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
549                                                 if (collideret != 1)
550                                                 {
551                                                         /*
552                                                          * Remote client lost, or both lost, parsing or passing on this
553                                                          * nickchange would be pointless, as the incoming client's server will
554                                                          * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
555                                                          */
556                                                         return true;
557                                                 }
558                                         }
559                                 }
560
561                                 switch (this->ServerInstance->CallCommandHandler(command.c_str(), params, who))
562                                 {
563                                         case CMD_INVALID:
564                                                 /*
565                                                  * XXX: command is irc::string, hence ugliness
566                                                  */
567                                                 this->SendError("Unrecognised or malformed command '" + std::string(command.c_str()) + "' -- possibly loaded mismatched modules");
568                                                 return false;
569                                                 break;
570                                         case CMD_FAILURE:
571                                                 /*
572                                                  * CMD_LOCALONLY is aliased to CMD_FAILURE, so this won't go out onto the network.
573                                                  */
574                                                 return true;
575                                                 break;
576                                         default:
577                                                 /* CMD_SUCCESS falls through here */
578                                                 break;
579                                 }
580
581                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
582
583                         }
584                         return true;
585                         break; // end of state CONNECTED (phew).
586         }
587         return true;
588 }
589
590 std::string TreeSocket::GetName()
591 {
592         std::string sourceserv = this->myhost;
593         if (!this->InboundServerName.empty())
594         {
595                 sourceserv = this->InboundServerName;
596         }
597         return sourceserv;
598 }
599
600 void TreeSocket::OnTimeout()
601 {
602         if (this->LinkState == CONNECTING)
603         {
604                 this->ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
605                 Link* MyLink = Utils->FindLink(myhost);
606                 if (MyLink)
607                         Utils->DoFailOver(MyLink);
608         }
609 }
610
611 void TreeSocket::OnClose()
612 {
613         // Test fix for big fuckup
614         if (this->LinkState != CONNECTED)
615                 return;
616
617         // Connection closed.
618         // If the connection is fully up (state CONNECTED)
619         // then propogate a netsplit to all peers.
620         std::string quitserver = this->myhost;
621         if (!this->InboundServerName.empty())
622         {
623                 quitserver = this->InboundServerName;
624         }
625         TreeServer* s = Utils->FindServer(quitserver);
626         if (s)
627         {
628                 Squit(s,"Remote host closed the connection");
629         }
630
631         if (!quitserver.empty())
632         {
633                 this->ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
634
635                 time_t server_uptime = ServerInstance->Time() - this->age;
636                 if (server_uptime)
637                                 this->ServerInstance->SNO->WriteToSnoMask('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
638         }
639 }