]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
3c838177d11ceb4c0ba68740c8337c3a4e482a9a
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket1.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2007 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22
23 #include "inspircd.h"
24 #include "iohook.h"
25
26 #include "main.h"
27 #include "modules/spanningtree.h"
28 #include "utils.h"
29 #include "treeserver.h"
30 #include "link.h"
31 #include "treesocket.h"
32 #include "commands.h"
33
34 /** Because most of the I/O gubbins are encapsulated within
35  * BufferedSocket, we just call the superclass constructor for
36  * most of the action, and append a few of our own values
37  * to it.
38  */
39 TreeSocket::TreeSocket(Link* link, Autoconnect* myac, const std::string& ipaddr)
40         : linkID(assign(link->Name)), LinkState(CONNECTING), MyRoot(NULL), proto_version(0), ConnectionFailureShown(false)
41         , age(ServerInstance->Time())
42 {
43         capab = new CapabData;
44         capab->link = link;
45         capab->ac = myac;
46         capab->capab_phase = 0;
47         if (!link->Hook.empty())
48         {
49                 ServiceProvider* prov = ServerInstance->Modules->FindService(SERVICE_IOHOOK, link->Hook);
50                 if (!prov)
51                 {
52                         SetError("Could not find hook '" + link->Hook + "' for connection to " + linkID);
53                         return;
54                 }
55                 AddIOHook(static_cast<IOHook*>(prov));
56         }
57         DoConnect(ipaddr, link->Port, link->Timeout, link->Bind);
58         Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, link->Timeout);
59         SendCapabilities(1);
60 }
61
62 /** When a listening socket gives us a new file descriptor,
63  * we must associate it with a socket without creating a new
64  * connection. This constructor is used for this purpose.
65  */
66 TreeSocket::TreeSocket(int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
67         : BufferedSocket(newfd)
68         , linkID("inbound from " + client->addr()), LinkState(WAIT_AUTH_1), MyRoot(NULL), proto_version(0)
69         , ConnectionFailureShown(false), age(ServerInstance->Time())
70 {
71         capab = new CapabData;
72         capab->capab_phase = 0;
73
74         FOREACH_MOD(OnHookIO, (this, via));
75         if (GetIOHook())
76                 GetIOHook()->OnStreamSocketAccept(this, client, server);
77         SendCapabilities(1);
78
79         Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, 30);
80 }
81
82 ServerState TreeSocket::GetLinkState()
83 {
84         return this->LinkState;
85 }
86
87 void TreeSocket::CleanNegotiationInfo()
88 {
89         // connect is good, reset the autoconnect block (if used)
90         if (capab->ac)
91                 capab->ac->position = -1;
92         delete capab;
93         capab = NULL;
94 }
95
96 CullResult TreeSocket::cull()
97 {
98         Utils->timeoutlist.erase(this);
99         if (capab && capab->ac)
100                 Utils->Creator->ConnectServer(capab->ac, false);
101         return this->BufferedSocket::cull();
102 }
103
104 TreeSocket::~TreeSocket()
105 {
106         delete capab;
107 }
108
109 /** When an outbound connection finishes connecting, we receive
110  * this event, and must send our SERVER string to the other
111  * side. If the other side is happy, as outlined in the server
112  * to server docs on the inspircd.org site, the other side
113  * will then send back its own server string.
114  */
115 void TreeSocket::OnConnected()
116 {
117         if (this->LinkState == CONNECTING)
118         {
119                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to \2%s\2[%s] started.", linkID.c_str(),
120                         (capab->link->HiddenFromStats ? "<hidden>" : capab->link->IPAddr.c_str()));
121                 this->SendCapabilities(1);
122         }
123 }
124
125 void TreeSocket::OnError(BufferedSocketError e)
126 {
127         ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\002%s\002' failed with error: %s",
128                 linkID.c_str(), getError().c_str());
129         LinkState = DYING;
130 }
131
132 void TreeSocket::SendError(const std::string &errormessage)
133 {
134         WriteLine("ERROR :"+errormessage);
135         DoWrite();
136         LinkState = DYING;
137         SetError(errormessage);
138 }
139
140 /** This function forces this server to quit, removing this server
141  * and any users on it (and servers and users below that, etc etc).
142  * It's very slow and pretty clunky, but luckily unless your network
143  * is having a REAL bad hair day, this function shouldnt be called
144  * too many times a month ;-)
145  */
146 void TreeSocket::SquitServer(std::string &from, TreeServer* Current, int& num_lost_servers, int& num_lost_users)
147 {
148         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "SquitServer for %s from %s", Current->GetName().c_str(), from.c_str());
149         /* recursively squit the servers attached to 'Current'.
150          * We're going backwards so we don't remove users
151          * while we still need them ;)
152          */
153         const TreeServer::ChildServers& children = Current->GetChildren();
154         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
155         {
156                 TreeServer* recursive_server = *i;
157                 this->SquitServer(from,recursive_server, num_lost_servers, num_lost_users);
158         }
159         /* Now we've whacked the kids, whack self */
160         num_lost_servers++;
161         num_lost_users += Current->QuitUsers(from);
162 }
163
164 /** This is a wrapper function for SquitServer above, which
165  * does some validation first and passes on the SQUIT to all
166  * other remaining servers.
167  */
168 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
169 {
170         bool LocalSquit = false;
171
172         if (!Current->IsRoot())
173         {
174                 DelServerEvent(Utils->Creator, Current->GetName());
175
176                 if (Current->IsLocal())
177                 {
178                         ServerInstance->SNO->WriteGlobalSno('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
179                         LocalSquit = true;
180                         if (Current->GetSocket()->Introduced())
181                         {
182                                 CmdBuilder params("SQUIT");
183                                 params.push_back(Current->GetID());
184                                 params.push_last(reason);
185                                 params.Broadcast();
186                         }
187                 }
188                 else
189                 {
190                         ServerInstance->SNO->WriteGlobalSno('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
191                 }
192                 int num_lost_servers = 0;
193                 int num_lost_users = 0;
194                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
195                 SquitServer(from, Current, num_lost_servers, num_lost_users);
196                 ServerInstance->SNO->WriteToSnoMask(LocalSquit ? 'l' : 'L', "Netsplit complete, lost \002%d\002 user%s on \002%d\002 server%s.",
197                         num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : "");
198                 Current->Tidy();
199                 Current->GetParent()->DelChild(Current);
200                 Current->cull();
201                 delete Current;
202                 if (Current == MyRoot)
203                 {
204                         MyRoot = NULL;
205                         Close();
206                 }
207         }
208 }
209
210 CmdResult CommandSQuit::HandleServer(TreeServer* server, std::vector<std::string>& params)
211 {
212         TreeServer* quitting = Utils->FindServer(params[0]);
213         if (!quitting)
214         {
215                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Squit from unknown server");
216                 return CMD_FAILURE;
217         }
218
219         TreeSocket* sock = server->GetSocket();
220         sock->Squit(quitting, params[1]);
221
222         // XXX: Return CMD_FAILURE when servers SQUIT themselves (i.e. :00S SQUIT 00S :Shutting down)
223         // to avoid RouteCommand() being called. RouteCommand() requires a valid command source but we
224         // do not have one because the server user is deleted when its TreeServer is destructed.
225         // We generate a SQUIT in TreeSocket::Squit(), with our sid as the source and send it to the
226         // remaining servers.
227         return ((quitting == server) ? CMD_FAILURE : CMD_SUCCESS);
228 }
229
230 /** This function is called when we receive data from a remote
231  * server.
232  */
233 void TreeSocket::OnDataReady()
234 {
235         Utils->Creator->loopCall = true;
236         std::string line;
237         while (GetNextLine(line))
238         {
239                 std::string::size_type rline = line.find('\r');
240                 if (rline != std::string::npos)
241                         line = line.substr(0,rline);
242                 if (line.find('\0') != std::string::npos)
243                 {
244                         SendError("Read null character from socket");
245                         break;
246                 }
247                 ProcessLine(line);
248                 if (!getError().empty())
249                         break;
250         }
251         if (LinkState != CONNECTED && recvq.length() > 4096)
252                 SendError("RecvQ overrun (line too long)");
253         Utils->Creator->loopCall = false;
254 }
255
256 bool TreeSocket::Introduced()
257 {
258         return (capab == NULL);
259 }