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