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