]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket2.cpp
3bc1fc71a0042cffcdf3bfda82703cb914988e6d
[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
27 #include "main.h"
28 #include "utils.h"
29 #include "treeserver.h"
30 #include "treesocket.h"
31 #include "resolvers.h"
32 #include "commands.h"
33
34 /* Handle ERROR command */
35 void TreeSocket::Error(CommandBase::Params& params)
36 {
37         std::string msg = params.size() ? params[0] : "";
38         SetError("received ERROR " + msg);
39 }
40
41 void TreeSocket::Split(const std::string& line, std::string& prefix, std::string& command, CommandBase::Params& params)
42 {
43         irc::tokenstream tokens(line);
44
45         if (!tokens.GetMiddle(prefix))
46                 return;
47
48         if (prefix[0] == ':')
49         {
50                 prefix.erase(prefix.begin());
51
52                 if (prefix.empty())
53                 {
54                         this->SendError("BUG (?) Empty prefix received: " + line);
55                         return;
56                 }
57                 if (!tokens.GetMiddle(command))
58                 {
59                         this->SendError("BUG (?) Empty command received: " + line);
60                         return;
61                 }
62         }
63         else
64         {
65                 command = prefix;
66                 prefix.clear();
67         }
68         if (command.empty())
69                 this->SendError("BUG (?) Empty command received: " + line);
70
71         std::string param;
72         while (tokens.GetTrailing(param))
73         {
74                 params.push_back(param);
75         }
76 }
77
78 void TreeSocket::ProcessLine(std::string &line)
79 {
80         std::string prefix;
81         std::string command;
82         CommandBase::Params params;
83
84         ServerInstance->Logs->Log(MODNAME, LOG_RAWIO, "S[%d] I %s", this->GetFd(), line.c_str());
85
86         Split(line, prefix, command, params);
87
88         if (command.empty())
89                 return;
90
91         switch (this->LinkState)
92         {
93                 case WAIT_AUTH_1:
94                         /*
95                          * State WAIT_AUTH_1:
96                          *  Waiting for SERVER command from remote server. Server initiating
97                          *  the connection sends the first SERVER command, listening server
98                          *  replies with theirs if its happy, then if the initiator is happy,
99                          *  it starts to send its net sync, which starts the merge, otherwise
100                          *  it sends an ERROR.
101                          */
102                         if (command == "PASS")
103                         {
104                                 /*
105                                  * Ignore this silently. Some services packages insist on sending PASS, even
106                                  * when it is not required (i.e. by us). We have to ignore this here, otherwise
107                                  * as it's an unknown command (effectively), it will cause the connection to be
108                                  * closed, which probably isn't what people want. -- w00t
109                                  */
110                         }
111                         else if (command == "SERVER")
112                         {
113                                 this->Inbound_Server(params);
114                         }
115                         else if (command == "ERROR")
116                         {
117                                 this->Error(params);
118                         }
119                         else if (command == "USER")
120                         {
121                                 this->SendError("Client connections to this port are prohibited.");
122                         }
123                         else if (command == "CAPAB")
124                         {
125                                 this->Capab(params);
126                         }
127                         else
128                         {
129                                 this->SendError("Invalid command in negotiation phase: " + command);
130                         }
131                 break;
132                 case WAIT_AUTH_2:
133                         /*
134                          * State WAIT_AUTH_2:
135                          *  We have sent SERVER to the other side of the connection. Now we're waiting for them to start BURST.
136                          *  The other option at this stage of things, of course, is for them to close our connection thanks
137                          *  to invalid credentials.. -- w
138                          */
139                         if (command == "SERVER")
140                         {
141                                 /*
142                                  * Connection is either attempting to re-auth itself (stupid) or sending netburst without sending BURST.
143                                  * Both of these aren't allowable, so block them here. -- w
144                                  */
145                                 this->SendError("You may not re-authenticate or commence netburst without sending BURST.");
146                         }
147                         else if (command == "BURST")
148                         {
149                                 if (params.size())
150                                 {
151                                         time_t them = ConvToInt(params[0]);
152                                         time_t delta = them - ServerInstance->Time();
153                                         if ((delta < -600) || (delta > 600))
154                                         {
155                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2ERROR\2: Your clocks are out by %ld seconds (this is more than five minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",labs((long)delta));
156                                                 SendError("Your clocks are out by "+ConvToStr(labs((long)delta))+" seconds (this is more than five minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
157                                                 return;
158                                         }
159                                         else if ((delta < -30) || (delta > 30))
160                                         {
161                                                 ServerInstance->SNO->WriteGlobalSno('l',"\2WARNING\2: Your clocks are out by %ld seconds. Please consider synching your clocks.", labs((long)delta));
162                                         }
163                                 }
164
165                                 // Check for duplicate server name/sid again, it's possible that a new
166                                 // server was introduced while we were waiting for them to send BURST.
167                                 // (we do not reserve their server name/sid when they send SERVER, we do it now)
168                                 if (!CheckDuplicate(capab->name, capab->sid))
169                                         return;
170
171                                 FinishAuth(capab->name, capab->sid, capab->description, capab->hidden);
172                         }
173                         else if (command == "ERROR")
174                         {
175                                 this->Error(params);
176                         }
177                         else if (command == "CAPAB")
178                         {
179                                 this->Capab(params);
180                         }
181
182                 break;
183                 case CONNECTING:
184                         /*
185                          * State CONNECTING:
186                          *  We're connecting (OUTGOING) to another server. They are in state WAIT_AUTH_1 until they verify
187                          *  our credentials, when they proceed into WAIT_AUTH_2 and send SERVER to us. We then send BURST
188                          *  + our netburst, which will put them into CONNECTED state. -- w
189                          */
190                         if (command == "SERVER")
191                         {
192                                 // Our credentials have been accepted, send netburst. (this puts US into the CONNECTED state)
193                                 this->Outbound_Reply_Server(params);
194                         }
195                         else if (command == "ERROR")
196                         {
197                                 this->Error(params);
198                         }
199                         else if (command == "CAPAB")
200                         {
201                                 this->Capab(params);
202                         }
203                 break;
204                 case CONNECTED:
205                         /*
206                          * State CONNECTED:
207                          *  Credentials have been exchanged, we've gotten their 'BURST' (or sent ours).
208                          *  Anything from here on should be accepted a little more reasonably.
209                          */
210                         this->ProcessConnectedLine(prefix, command, params);
211                 break;
212                 case DYING:
213                 break;
214         }
215 }
216
217 User* TreeSocket::FindSource(const std::string& prefix, const std::string& command)
218 {
219         // Empty prefix means the source is the directly connected server that sent this command
220         if (prefix.empty())
221                 return MyRoot->ServerUser;
222
223         if (prefix.size() == 3)
224         {
225                 // Prefix looks like a sid
226                 TreeServer* server = Utils->FindServerID(prefix);
227                 if (server)
228                         return server->ServerUser;
229         }
230         else
231         {
232                 // If the prefix string is a uuid FindUUID() returns the appropriate User object
233                 User* user = ServerInstance->FindUUID(prefix);
234                 if (user)
235                         return user;
236         }
237
238         // Some implementations wrongly send a server name as prefix occasionally, handle that too for now
239         TreeServer* const server = Utils->FindServer(prefix);
240         if (server)
241                 return server->ServerUser;
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
248         if ((prefix.length() == UIDGenerator::UUID_LENGTH) && (isdigit(prefix[0])) &&
249                 ((command == "FMODE") || (command == "MODE") || (command == "KICK") || (command == "TOPIC") || (command == "KILL") || (command == "ADDLINE") || (command == "DELLINE")))
250         {
251                 /* Special case, we cannot drop these commands as they've been committed already on a
252                  * part of the network by the time we receive them, so in this scenario pretend the
253                  * command came from a server to avoid desync.
254                  */
255
256                 TreeServer* const usersserver = Utils->FindServerID(prefix.substr(0, 3));
257                 if (usersserver)
258                         return usersserver->ServerUser;
259                 return this->MyRoot->ServerUser;
260         }
261
262         // Unknown prefix
263         return NULL;
264 }
265
266 void TreeSocket::ProcessConnectedLine(std::string& prefix, std::string& command, CommandBase::Params& params)
267 {
268         User* who = FindSource(prefix, command);
269         if (!who)
270         {
271                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Command '%s' from unknown prefix '%s'! Dropping entire command.", command.c_str(), prefix.c_str());
272                 return;
273         }
274
275         /*
276          * Check for fake direction here, and drop any instances that are found.
277          * What is fake direction? Imagine the following server setup:
278          *    0AA <-> 0AB <-> 0AC
279          * Fake direction would be 0AC sending a message to 0AB claiming to be from
280          * 0AA, or something similar. Basically, a message taking a path that *cannot*
281          * be correct.
282          *
283          * When would this be seen?
284          * Well, hopefully never. It could be caused by race conditions, bugs, or
285          * "miscreant" servers, though, so let's check anyway. -- w
286          *
287          * We also check here for totally invalid prefixes (prefixes that are neither
288          * a valid SID or a valid UUID, so that invalid UUID or SID never makes it
289          * to the higher level functions. -- B
290          */
291         TreeServer* const server = TreeServer::Get(who);
292         if (server->GetSocket() != this)
293         {
294                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Protocol violation: Fake direction '%s' from connection '%s'", prefix.c_str(), linkID.c_str());
295                 return;
296         }
297
298         // Translate commands coming from servers using an older protocol
299         if (proto_version < ProtocolVersion)
300         {
301                 if (!PreProcessOldProtocolMessage(who, command, params))
302                         return;
303         }
304
305         ServerCommand* scmd = Utils->Creator->CmdManager.GetHandler(command);
306         CommandBase* cmdbase = scmd;
307         Command* cmd = NULL;
308         if (!scmd)
309         {
310                 // Not a special server-to-server command
311                 cmd = ServerInstance->Parser.GetHandler(command);
312                 if (!cmd)
313                 {
314                         if (command == "ERROR")
315                         {
316                                 this->Error(params);
317                                 return;
318                         }
319                         else if (command == "BURST")
320                         {
321                                 // This is sent even when there is no need for it, drop it here for now
322                                 return;
323                         }
324
325                         throw ProtocolException("Unknown command");
326                 }
327                 cmdbase = cmd;
328         }
329
330         if (params.size() < cmdbase->min_params)
331                 throw ProtocolException("Insufficient parameters");
332
333         if ((!params.empty()) && (params.back().empty()) && (!cmdbase->allow_empty_last_param))
334         {
335                 // the last param is empty and the command handler doesn't allow that, check if there will be enough params if we drop the last
336                 if (params.size()-1 < cmdbase->min_params)
337                         return;
338                 params.pop_back();
339         }
340
341         CmdResult res;
342         if (scmd)
343                 res = scmd->Handle(who, params);
344         else
345         {
346                 res = cmd->Handle(who, params);
347                 if (res == CMD_INVALID)
348                         throw ProtocolException("Error in command handler");
349         }
350
351         if (res == CMD_SUCCESS)
352                 Utils->RouteCommand(server->GetRoute(), cmdbase, params, who);
353 }
354
355 void TreeSocket::OnTimeout()
356 {
357         ServerInstance->SNO->WriteGlobalSno('l', "CONNECT: Connection to \002%s\002 timed out.", linkID.c_str());
358 }
359
360 void TreeSocket::Close()
361 {
362         if (fd < 0)
363                 return;
364
365         ServerInstance->GlobalCulls.AddItem(this);
366         this->BufferedSocket::Close();
367         SetError("Remote host closed connection");
368
369         // Connection closed.
370         // If the connection is fully up (state CONNECTED)
371         // then propogate a netsplit to all peers.
372         if (MyRoot)
373                 MyRoot->SQuit(getError());
374
375         ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' failed.",linkID.c_str());
376
377         time_t server_uptime = ServerInstance->Time() - this->age;
378         if (server_uptime)
379         {
380                 std::string timestr = ModuleSpanningTree::TimeToStr(server_uptime);
381                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\2%s\2' was established for %s", linkID.c_str(), timestr.c_str());
382         }
383 }
384
385 void TreeSocket::FinishAuth(const std::string& remotename, const std::string& remotesid, const std::string& remotedesc, bool hidden)
386 {
387         this->LinkState = CONNECTED;
388         Utils->timeoutlist.erase(this);
389
390         linkID = remotename;
391
392         MyRoot = new TreeServer(remotename, remotedesc, remotesid, Utils->TreeRoot, this, hidden);
393
394         // Mark the server as bursting
395         MyRoot->BeginBurst();
396         this->DoBurst(MyRoot);
397
398         CommandServer::Builder(MyRoot).Forward(MyRoot);
399 }