]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
Remove superfluous std::string()s
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket2.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2007-2008, 2012 Robin Burchell <robin+git@viroteck.net>
5  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6  *   Copyright (C) 2007-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #include "inspircd.h"
26 #include "socket.h"
27 #include "xline.h"
28 #include "socketengine.h"
29
30 #include "main.h"
31 #include "utils.h"
32 #include "treeserver.h"
33 #include "link.h"
34 #include "treesocket.h"
35 #include "resolvers.h"
36
37 /* Handle ERROR command */
38 void TreeSocket::Error(parameterlist &params)
39 {
40         std::string msg = params.size() ? params[0] : "";
41         SetError("received ERROR " + msg);
42 }
43
44 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, parameterlist& params)
45 {
46         irc::tokenstream tokens(line);
47
48         if (!tokens.GetToken(prefix))
49                 return;
50         
51         if (prefix[0] == ':')
52         {
53                 prefix = prefix.substr(1);
54
55                 if (prefix.empty())
56                 {
57                         this->SendError("BUG (?) Empty prefix received: " + line);
58                         return;
59                 }
60                 if (!tokens.GetToken(command))
61                 {
62                         this->SendError("BUG (?) Empty command received: " + line);
63                         return;
64                 }
65         }
66         else
67         {
68                 command = prefix;
69                 prefix.clear();
70         }
71         if (command.empty())
72                 this->SendError("BUG (?) Empty command received: " + line);
73
74         std::string param;
75         while (tokens.GetToken(param))
76         {
77                 params.push_back(param);
78         }
79 }
80
81 void TreeSocket::ProcessLine(std::string &line)
82 {
83         std::string prefix;
84         std::string command;
85         parameterlist params;
86
87         ServerInstance->Logs->Log("m_spanningtree", RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
88
89         Split(line, prefix, command, params);
90
91         if (command.empty())
92                 return;
93
94         switch (this->LinkState)
95         {
96                 case WAIT_AUTH_1:
97                         /*
98                          * State WAIT_AUTH_1:
99                          *  Waiting for SERVER command from remote server. Server initiating
100                          *  the connection sends the first SERVER command, listening server
101                          *  replies with theirs if its happy, then if the initiator is happy,
102                          *  it starts to send its net sync, which starts the merge, otherwise
103                          *  it sends an ERROR.
104                          */
105                         if (command == "PASS")
106                         {
107                                 /*
108                                  * Ignore this silently. Some services packages insist on sending PASS, even
109                                  * when it is not required (i.e. by us). We have to ignore this here, otherwise
110                                  * as it's an unknown command (effectively), it will cause the connection to be
111                                  * closed, which probably isn't what people want. -- w00t
112                                  */
113                         }
114                         else if (command == "SERVER")
115                         {
116                                 this->Inbound_Server(params);
117                         }
118                         else if (command == "ERROR")
119                         {
120                                 this->Error(params);
121                         }
122                         else if (command == "USER")
123                         {
124                                 this->SendError("Client connections to this port are prohibited.");
125                         }
126                         else if (command == "CAPAB")
127                         {
128                                 this->Capab(params);
129                         }
130                         else
131                         {
132                                 this->SendError("Invalid command in negotiation phase: " + command);
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                         }
150                         else if (command == "BURST")
151                         {
152                                 if (params.size())
153                                 {
154                                         time_t them = atoi(params[0].c_str());
155                                         time_t delta = them - ServerInstance->Time();
156                                         if ((delta < -600) || (delta > 600))
157                                         {
158                                                 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));
159                                                 SendError("Your clocks are out by "+ConvToStr(abs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
160                                                 return;
161                                         }
162                                         else if ((delta < -30) || (delta > 30))
163                                         {
164                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %d seconds. Please consider synching your clocks.", abs((long)delta));
165                                         }
166                                 }
167                                 this->LinkState = CONNECTED;
168                                 Utils->timeoutlist.erase(this);
169
170                                 MyRoot->bursting = true;
171                                 this->DoBurst(MyRoot);
172
173                                 parameterlist sparams;
174                                 sparams.push_back(MyRoot->GetName());
175                                 sparams.push_back("*");
176                                 sparams.push_back("0");
177                                 sparams.push_back(MyRoot->GetID());
178                                 sparams.push_back(":" + MyRoot->GetDesc());
179                                 Utils->DoOneToAllButSender(ServerInstance->Config->GetSID(), "SERVER", sparams, MyRoot->GetName());
180                                 Utils->DoOneToAllButSender(MyRoot->GetID(), "BURST", params, MyRoot->GetName());
181                         }
182                         else if (command == "ERROR")
183                         {
184                                 this->Error(params);
185                         }
186                         else if (command == "CAPAB")
187                         {
188                                 this->Capab(params);
189                         }
190
191                 break;
192                 case CONNECTING:
193                         /*
194                          * State CONNECTING:
195                          *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
196                          *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
197                          *  + our netburst, which will put them into CONNECTED state. -- w
198                          */
199                         if (command == "SERVER")
200                         {
201                                 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
202                                 this->Outbound_Reply_Server(params);
203                         }
204                         else if (command == "ERROR")
205                         {
206                                 this->Error(params);
207                         }
208                         else if (command == "CAPAB")
209                         {
210                                 this->Capab(params);
211                         }
212                 break;
213                 case CONNECTED:
214                         /*
215                          * State CONNECTED:
216                          *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
217                          *  Anything from here on should be accepted a little more reasonably.
218                          */
219                         this->ProcessConnectedLine(prefix, command, params);
220                 break;
221                 case DYING:
222                 break;
223         }
224 }
225
226 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, parameterlist& params)
227 {
228         User* who = ServerInstance->FindUUID(prefix);
229         std::string direction;
230
231         if (!who)
232         {
233                 TreeServer* ServerSource = Utils->FindServer(prefix);
234                 if (prefix.empty())
235                         ServerSource = MyRoot;
236
237                 if (ServerSource)
238                 {
239                         who = ServerSource->ServerUser;
240                 }
241                 else
242                 {
243                         /* It is important that we don't close the link here, unknown prefix can occur
244                          * due to various race conditions such as the KILL message for a user somehow
245                          * crossing the users QUIT further upstream from the server. Thanks jilles!
246                          */
247                         ServerInstance->Logs->Log("m_spanningtree", DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.",
248                                 command.c_str(), prefix.c_str());
249                         return;
250                 }
251         }
252
253         // Make sure prefix is still good
254         direction = who->server;
255         prefix = who->uuid;
256
257         /*
258          * Check for fake direction here, and drop any instances that are found.
259          * What is fake direction? Imagine the following server setup:
260          *    0AA <-> 0AB <-> 0AC
261          * Fake direction would be 0AC sending a message to 0AB claiming to be from
262          * 0AA, or something similar. Basically, a message taking a path that *cannot*
263          * be correct.
264          *
265          * When would this be seen?
266          * Well, hopefully never. It could be caused by race conditions, bugs, or
267          * "miscreant" servers, though, so let's check anyway. -- w
268          *
269          * We also check here for totally invalid prefixes (prefixes that are neither
270          * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
271          * to the higher level functions. -- B
272          */
273         TreeServer* route_back_again = Utils->BestRouteTo(direction);
274         if ((!route_back_again) || (route_back_again->GetSocket() != this))
275         {
276                 if (route_back_again)
277                         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"Protocol violation: Fake direction '%s' from connection '%s'",
278                                 prefix.c_str(),linkID.c_str());
279                 return;
280         }
281
282         /*
283          * First up, check for any malformed commands (e.g. MODE without a timestamp)
284          * and rewrite commands where necessary (SVSMODE -> MODE for services). -- w
285          */
286         if (command == "SVSMODE") // This isn't in an "else if" so we still force FMODE for changes on channels.
287                 command = "MODE";
288
289         // TODO move all this into Commands
290         if (command == "MAP")
291         {
292                 Utils->Creator->HandleMap(params, who);
293         }
294         else if (command == "SERVER")
295         {
296                 this->RemoteServer(prefix,params);
297         }
298         else if (command == "ERROR")
299         {
300                 this->Error(params);
301         }
302         else if (command == "AWAY")
303         {
304                 this->Away(prefix,params);
305         }
306         else if (command == "PING")
307         {
308                 this->LocalPing(prefix,params);
309         }
310         else if (command == "PONG")
311         {
312                 TreeServer *s = Utils->FindServer(prefix);
313                 if (s && s->bursting)
314                 {
315                         ServerInstance->SNO->WriteGlobalSno('l',"Server \002%s\002 has not finished burst, forcing end of burst (send ENDBURST!)", prefix.c_str());
316                         s->FinishBurst();
317                 }
318                 this->LocalPong(prefix,params);
319         }
320         else if (command == "VERSION")
321         {
322                 this->ServerVersion(prefix,params);
323         }
324         else if (command == "ADDLINE")
325         {
326                 this->AddLine(prefix,params);
327         }
328         else if (command == "DELLINE")
329         {
330                 this->DelLine(prefix,params);
331         }
332         else if (command == "SAVE")
333         {
334                 this->ForceNick(prefix,params);
335         }
336         else if (command == "OPERQUIT")
337         {
338                 this->OperQuit(prefix,params);
339         }
340         else if (command == "IDLE")
341         {
342                 this->Whois(prefix,params);
343         }
344         else if (command == "PUSH")
345         {
346                 this->Push(prefix,params);
347         }
348         else if (command == "SQUIT")
349         {
350                 if (params.size() == 2)
351                 {
352                         this->Squit(Utils->FindServer(params[0]),params[1]);
353                 }
354         }
355         else if (command == "SNONOTICE")
356         {
357                 if (params.size() >= 2)
358                 {
359                         ServerInstance->SNO->WriteToSnoMask(params[0][0], "From " + who->nick + ": "+ params[1]);
360                         params[1] = ":" + params[1];
361                         Utils->DoOneToAllButSender(prefix, command, params, prefix);
362                 }
363         }
364         else if (command == "BURST")
365         {
366                 // Set prefix server as bursting
367                 TreeServer* ServerSource = Utils->FindServer(prefix);
368                 if (!ServerSource)
369                 {
370                         ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got BURST from a non-server(?): %s", prefix.c_str());
371                         return;
372                 }
373
374                 ServerSource->bursting = true;
375                 Utils->DoOneToAllButSender(prefix, command, params, prefix);
376         }
377         else if (command == "ENDBURST")
378         {
379                 TreeServer* ServerSource = Utils->FindServer(prefix);
380                 if (!ServerSource)
381                 {
382                         ServerInstance->SNO->WriteGlobalSno('l', "WTF: Got ENDBURST from a non-server(?): %s", prefix.c_str());
383                         return;
384                 }
385
386                 ServerSource->FinishBurst();
387                 Utils->DoOneToAllButSender(prefix, command, params, prefix);
388         }
389         else if (command == "ENCAP")
390         {
391                 this->Encap(who, params);
392         }
393         else if (command == "NICK")
394         {
395                 if (params.size() != 2)
396                 {
397                         SendError("Protocol violation: NICK message without TS - :"+who->uuid+" NICK "+params[0]);
398                         return;
399                 }
400
401                 if (IS_SERVER(who))
402                 {
403                         SendError("Protocol violation: Server changing nick");
404                         return;
405                 }
406
407                 /* Update timestamp on user when they change nicks */
408                 who->age = atoi(params[1].c_str());
409
410                 /*
411                  * On nick messages, check that the nick doesnt already exist here.
412                  * If it does, perform collision logic.
413                  */
414                 User* x = ServerInstance->FindNickOnly(params[0]);
415                 if ((x) && (x != who))
416                 {
417                         int collideret = 0;
418                         /* x is local, who is remote */
419                         collideret = this->DoCollision(x, who->age, who->ident, who->GetIPString(), who->uuid);
420                         if (collideret != 1)
421                         {
422                                 /*
423                                  * Remote client lost, or both lost, parsing or passing on this
424                                  * nickchange would be pointless, as the incoming client's server will
425                                  * soon recieve SVSNICK to change its nick to its UID. :) -- w00t
426                                  */
427                                 return;
428                         }
429                 }
430                 who->ForceNickChange(params[0].c_str());
431                 Utils->RouteCommand(route_back_again, command, params, who);
432         }
433         else
434         {
435                 Command* cmd = ServerInstance->Parser->GetHandler(command);
436                 
437                 if (!cmd)
438                 {
439                         irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
440                         ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Unrecognised S2S command :%s %s %s",
441                                 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
442                         SendError("Unrecognised command '" + command + "' -- possibly loaded mismatched modules");
443                         return;
444                 }
445
446                 if (params.size() < cmd->min_params)
447                 {
448                         irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
449                         ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Insufficient parameters for S2S command :%s %s %s",
450                                 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
451                         SendError("Insufficient parameters for command '" + command + "'");
452                         return;
453                 }
454
455                 CmdResult res = cmd->Handle(params, who);
456
457                 if (res == CMD_INVALID)
458                 {
459                         irc::stringjoiner pmlist(" ", params, 0, params.size() - 1);
460                         ServerInstance->Logs->Log("m_spanningtree", SPARSE, "Error handling S2S command :%s %s %s",
461                                 who->uuid.c_str(), command.c_str(), pmlist.GetJoined().c_str());
462                         SendError("Error handling '" + command + "' -- possibly loaded mismatched modules");
463                 }
464                 else if (res == CMD_SUCCESS)
465                         Utils->RouteCommand(route_back_again, command, params, who);
466         }
467 }
468
469 void TreeSocket::OnTimeout()
470 {
471         ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
472 }
473
474 void TreeSocket::Close()
475 {
476         if (fd != -1)
477                 ServerInstance->GlobalCulls.AddItem(this);
478         this->BufferedSocket::Close();
479         SetError("Remote host closed connection");
480
481         // Connection closed.
482         // If the connection is fully up (state CONNECTED)
483         // then propogate a netsplit to all peers.
484         if (MyRoot)
485                 Squit(MyRoot,getError());
486
487         if (!ConnectionFailureShown)
488         {
489                 ConnectionFailureShown = true;
490                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str());
491
492                 time_t server_uptime = ServerInstance->Time() - this->age;
493                 if (server_uptime)
494                 {
495                         std::string timestr = Utils->Creator->TimeToStr(server_uptime);
496                         ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str());
497                 }
498         }
499 }