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