]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
144f30bf8f20abc89a8fdf40f46b342f1e0a628b
[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 void TreeSocket::Error(parameterlist &params)
28 {
29         std::string msg = params.size() ? params[0] : "";
30         SetError("received ERROR " + msg);
31 }
32
33 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
34 {
35         irc::tokenstream tokens(line);
36
37         if (!tokens.GetToken(prefix))
38                 return;
39         
40         if (prefix[0] == ':')
41         {
42                 prefix = prefix.substr(1);
43
44                 if (prefix.empty())
45                 {
46                         this->SendError("BUG (?) Empty prefix received: " + line);
47                         return;
48                 }
49                 if (!tokens.GetToken(command))
50                 {
51                         this->SendError("BUG (?) Empty command received: " + line);
52                         return;
53                 }
54         }
55         else
56         {
57                 command = prefix;
58                 prefix.clear();
59         }
60         if (command.empty())
61                 this->SendError("BUG (?) Empty command received: " + line);
62
63         std::string param;
64         while (tokens.GetToken(param))
65         {
66                 params.push_back(param);
67         }
68 }
69
70 void TreeSocket::ProcessLine(std::string &line)
71 {
72         std::string prefix;
73         std::string command;
74         parameterlist params;
75
76         ServerInstance->Logs->Log("m_spanningtree",DEBUG, "S[%d] I %s", this->GetFd(), line.c_str());
77
78         Split(line, prefix, command, params);
79
80         if (command.empty())
81                 return;
82
83         switch (this->LinkState)
84         {
85                 TreeServer* Node;
86
87                 case WAIT_AUTH_1:
88                         /*
89                          * State WAIT_AUTH_1:
90                          *  Waiting for SERVER command from remote server. Server initiating
91                          *  the connection sends the first SERVER command, listening server
92                          *  replies with theirs if its happy, then if the initiator is happy,
93                          *  it starts to send its net sync, which starts the merge, otherwise
94                          *  it sends an ERROR.
95                          */
96                         if (command == "PASS")
97                         {
98                                 /*
99                                  * Ignore this silently. Some services packages insist on sending PASS, even
100                                  * when it is not required (i.e. by us). We have to ignore this here, otherwise
101                                  * as it's an unknown command (effectively), it will cause the connection to be
102                                  * closed, which probably isn't what people want. -- w00t
103                                  */
104                         }
105                         else if (command == "SERVER")
106                         {
107                                 this->Inbound_Server(params);
108                         }
109                         else if (command == "ERROR")
110                         {
111                                 this->Error(params);
112                         }
113                         else if (command == "USER")
114                         {
115                                 this->SendError("Client connections to this port are prohibited.");
116                         }
117                         else if (command == "CAPAB")
118                         {
119                                 this->Capab(params);
120                         }
121                         else
122                         {
123                                 this->SendError(std::string("Invalid command in negotiation phase: ") + command.c_str());
124                         }
125                 break;
126                 case WAIT_AUTH_2:
127                         /*
128                          * State WAIT_AUTH_2:
129                          *  We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
130                          *  The other option at this stage of things, of course, is for them to close our connection thanks
131                          *  to invalid credentials.. -- w
132                          */
133                         if (command == "SERVER")
134                         {
135                                 /*
136                                  * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
137                                  * Both of these aren't allowable, so block them here. -- w
138                                  */
139                                 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
140                         }
141                         else if (command == "BURST")
142                         {
143                                 if (params.size())
144                                 {
145                                         time_t them = atoi(params[0].c_str());
146                                         time_t delta = them - ServerInstance->Time();
147                                         if ((delta < -600) || (delta > 600))
148                                         {
149                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than five minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs((long)delta));
150                                                 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
151                                                 return;
152                                         }
153                                         else if ((delta < -30) || (delta > 30))
154                                         {
155                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
156                                         }
157                                 }
158                                 this->LinkState = CONNECTED;
159
160                                 Utils->timeoutlist.erase(this);
161                                 if (myautoconnect)
162                                 {
163                                         myautoconnect->position = -1;
164                                         myautoconnect = NULL;
165                                 }
166
167                                 Link* lnk = Utils->FindLink(InboundServerName);
168
169                                 Node = new TreeServer(this->Utils, InboundServerName, InboundDescription, InboundSID, Utils->TreeRoot, this, lnk ? lnk->Hidden : false);
170
171                                 Utils->TreeRoot->AddChild(Node);
172                                 parameterlist sparams;
173                                 sparams.push_back(InboundServerName);
174                                 sparams.push_back("*");
175                                 sparams.push_back("1");
176                                 sparams.push_back(InboundSID);
177                                 sparams.push_back(":"+InboundDescription);
178                                 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(),"SERVER",sparams,InboundServerName);
179                                 Utils->DoOneToAllButSender(prefix, "BURST", params, InboundServerName);
180                                 Node->bursting = true;
181                                 this->DoBurst(Node);
182                         }
183                         else if (command == "ERROR")
184                         {
185                                 this->Error(params);
186                         }
187                         else if (command == "CAPAB")
188                         {
189                                 this->Capab(params);
190                         }
191
192                 break;
193                 case CONNECTING:
194                         /*
195                          * State CONNECTING:
196                          *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
197                          *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
198                          *  + our netburst, which will put them into CONNECTED state. -- w
199                          */
200                         if (command == "SERVER")
201                         {
202                                 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
203                                 this->Outbound_Reply_Server(params);
204                         }
205                         else if (command == "ERROR")
206                         {
207                                 this->Error(params);
208                         }
209                         else if (command == "CAPAB")
210                         {
211                                 this->Capab(params);
212                         }
213                 break;
214                 case CONNECTED:
215                         /*
216                          * State CONNECTED:
217                          *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
218                          *  Anything from here on should be accepted a little more reasonably.
219                          */
220                         this->ProcessConnectedLine(prefix, command, params);
221                 break;
222         }
223 }
224
225 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
226 {
227         User* who = ServerInstance->FindUUID(prefix);
228         std::string direction;
229
230         if (who)
231         {
232                 direction = who->server;
233         }
234         else
235         {
236                 TreeServer* ServerSource = Utils->FindServer(prefix);
237                 if (prefix.empty())
238                         ServerSource = Utils->FindServer(GetName());
239
240                 if (ServerSource)
241                 {
242                         who = ServerSource->ServerUser;
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(who,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(who,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->WriteGlobalSno('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 == "SAVE")
384         {
385                 this->ForceNick(prefix,params);
386         }
387         else if (command == "OPERQUIT")
388         {
389                 this->OperQuit(prefix,params);
390         }
391         else if (command == "IDLE")
392         {
393                 this->Whois(prefix,params);
394         }
395         else if (command == "PUSH")
396         {
397                 this->Push(prefix,params);
398         }
399         else if (command == "TIME")
400         {
401                 this->Time(prefix,params);
402         }
403         else if (command == "SQUIT")
404         {
405                 if (params.size() == 2)
406                 {
407                         this->Squit(Utils->FindServer(params[0]),params[1]);
408                 }
409         }
410         else if (command == "SNONOTICE")
411         {
412                 if (params.size() >= 2)
413                 {
414                         ServerInstance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + who->nick + ": "+ params[1]);
415                         Utils->DoOneToAllButSender(prefix, command, params, prefix);
416                 }
417         }
418         else if (command == "BURST")
419         {
420                 // Set prefix server as bursting
421                 TreeServer* ServerSource = Utils->FindServer(prefix);
422                 if (!ServerSource)
423                 {
424                         ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
425                         return;
426                 }
427
428                 ServerSource->bursting = true;
429                 Utils->DoOneToAllButSender(prefix, command, params, prefix);
430         }
431         else if (command == "ENDBURST")
432         {
433                 TreeServer* ServerSource = Utils->FindServer(prefix);
434                 if (!ServerSource)
435                 {
436                         ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
437                         return;
438                 }
439
440                 ServerSource->FinishBurst();
441                 Utils->DoOneToAllButSender(prefix, command, params, prefix);
442         }
443         else if (command == "ENCAP")
444         {
445                 this->Encap(who, params);
446         }
447         else if (command == "NICK")
448         {
449                 if (params.size() != 2)
450                 {
451                         SendError("Protocol violation: NICK message without TS - :"+std::string(who->uuid)+" NICK "+params[0]);
452                         return;
453                 }
454
455                 if (IS_SERVER(who))
456                 {
457                         SendError("Protocol violation: Server changing nick");
458                         return;
459                 }
460
461                 /* Update timestamp on user when they change nicks */
462                 who->age = atoi(params[1].c_str());
463
464                 /*
465                  * On nick messages, check that the nick doesnt already exist here.
466                  * If it does, perform collision logic.
467                  */
468                 User* x = ServerInstance->FindNickOnly(params[0]);
469                 if ((x) && (x != who))
470                 {
471                         int collideret = 0;
472                         /* x is local, who is remote */
473                         collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
474                         if (collideret != 1)
475                         {
476                                 /*
477                                  * Remote client lost, or both lost, parsing or passing on this
478                                  * nickchange would be pointless, as the incoming client's server will
479                                  * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
480                                  */
481                                 return;
482                         }
483                 }
484                 who->ForceNickChange(params[0].c_str());
485                 Utils->RouteCommand(route_back_again, command, params, who);
486         }
487         else
488         {
489                 Command* cmd = ServerInstance->Parser->GetHandler(command);
490                 CmdResult res = CMD_INVALID;
491                 if (cmd && params.size() >= cmd->min_params)
492                 {
493                         res = cmd->Handle(params, who);
494                 }
495
496                 if (res == CMD_INVALID)
497                         SendError("Unrecognised or malformed command '" + command + "' -- possibly loaded mismatched modules");
498                 if (res == CMD_SUCCESS)
499                         Utils->RouteCommand(route_back_again, command, params, who);
500         }
501 }
502
503 std::string TreeSocket::GetName()
504 {
505         std::string sourceserv = this->myhost;
506         if (!this->InboundServerName.empty())
507         {
508                 sourceserv = this->InboundServerName;
509         }
510         return sourceserv;
511 }
512
513 void TreeSocket::OnTimeout()
514 {
515         if (this->LinkState == CONNECTING)
516         {
517                 ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", myhost.c_str());
518         }
519 }
520
521 void TreeSocket::Close()
522 {
523         this->BufferedSocket::Close();
524
525         // Test fix for big fuckup
526         if (this->LinkState != CONNECTED)
527                 return;
528
529         // Connection closed.
530         // If the connection is fully up (state CONNECTED)
531         // then propogate a netsplit to all peers.
532         std::string quitserver = this->myhost;
533         if (!this->InboundServerName.empty())
534         {
535                 quitserver = this->InboundServerName;
536         }
537         TreeServer* s = Utils->FindServer(quitserver);
538         if (s)
539         {
540                 Squit(s,"Remote host closed the connection");
541         }
542
543         if (!quitserver.empty())
544         {
545                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",quitserver.c_str());
546
547                 time_t server_uptime = ServerInstance->Time() - this->age;
548                 if (server_uptime)
549                                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", quitserver.c_str(), Utils->Creator->TimeToStr(server_uptime).c_str());
550         }
551 }