]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
26171ee7297e818572bc1c902ef2064edb8addcb
[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 "socket.h"
25 #include "xline.h"
26 #include "socketengine.h"
27
28 #include "main.h"
29 #include "../spanningtree.h"
30 #include "utils.h"
31 #include "treeserver.h"
32 #include "link.h"
33 #include "treesocket.h"
34 #include "resolvers.h"
35
36 /** Because most of the I/O gubbins are encapsulated within
37  * BufferedSocket, we just call the superclass constructor for
38  * most of the action, and append a few of our own values
39  * to it.
40  */
41 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, Link* link, Autoconnect* myac, const std::string& ipaddr)
42         : Utils(Util)
43 {
44         age = ServerInstance->Time();
45         linkID = assign(link->Name);
46         capab = new CapabData;
47         capab->link = link;
48         capab->ac = myac;
49         capab->capab_phase = 0;
50         MyRoot = NULL;
51         proto_version = 0;
52         ConnectionFailureShown = false;
53         LinkState = CONNECTING;
54         if (!link->Hook.empty())
55         {
56                 ServiceProvider* prov = ServerInstance->Modules->FindService(SERVICE_IOHOOK, link->Hook);
57                 if (!prov)
58                 {
59                         SetError("Could not find hook '" + link->Hook + "' for connection to " + linkID);
60                         return;
61                 }
62                 AddIOHook(prov->creator);
63         }
64         DoConnect(ipaddr, link->Port, link->Timeout, link->Bind);
65         Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, link->Timeout);
66         SendCapabilities(1);
67 }
68
69 /** When a listening socket gives us a new file descriptor,
70  * we must associate it with a socket without creating a new
71  * connection. This constructor is used for this purpose.
72  */
73 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
74         : BufferedSocket(newfd), Utils(Util)
75 {
76         capab = new CapabData;
77         capab->capab_phase = 0;
78         MyRoot = NULL;
79         age = ServerInstance->Time();
80         LinkState = WAIT_AUTH_1;
81         proto_version = 0;
82         ConnectionFailureShown = false;
83         linkID = "inbound from " + client->addr();
84
85         FOREACH_MOD(I_OnHookIO, OnHookIO(this, via));
86         if (GetIOHook())
87                 GetIOHook()->OnStreamSocketAccept(this, client, server);
88         SendCapabilities(1);
89
90         Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, 30);
91 }
92
93 ServerState TreeSocket::GetLinkState()
94 {
95         return this->LinkState;
96 }
97
98 void TreeSocket::CleanNegotiationInfo()
99 {
100         // connect is good, reset the autoconnect block (if used)
101         if (capab->ac)
102                 capab->ac->position = -1;
103         delete capab;
104         capab = NULL;
105 }
106
107 CullResult TreeSocket::cull()
108 {
109         Utils->timeoutlist.erase(this);
110         if (capab && capab->ac)
111                 Utils->Creator->ConnectServer(capab->ac, false);
112         return this->BufferedSocket::cull();
113 }
114
115 TreeSocket::~TreeSocket()
116 {
117         if (capab)
118                 delete capab;
119 }
120
121 /** When an outbound connection finishes connecting, we receive
122  * this event, and must send our SERVER string to the other
123  * side. If the other side is happy, as outlined in the server
124  * to server docs on the inspircd.org site, the other side
125  * will then send back its own server string.
126  */
127 void TreeSocket::OnConnected()
128 {
129         if (this->LinkState == CONNECTING)
130         {
131                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to \2%s\2[%s] started.", linkID.c_str(),
132                         (capab->link->HiddenFromStats ? "<hidden>" : capab->link->IPAddr.c_str()));
133                 this->SendCapabilities(1);
134         }
135 }
136
137 void TreeSocket::OnError(BufferedSocketError e)
138 {
139         ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\002%s\002' failed with error: %s",
140                 linkID.c_str(), getError().c_str());
141         LinkState = DYING;
142 }
143
144 void TreeSocket::SendError(const std::string &errormessage)
145 {
146         WriteLine("ERROR :"+errormessage);
147         DoWrite();
148         LinkState = DYING;
149         SetError(errormessage);
150 }
151
152 /** This function forces this server to quit, removing this server
153  * and any users on it (and servers and users below that, etc etc).
154  * It's very slow and pretty clunky, but luckily unless your network
155  * is having a REAL bad hair day, this function shouldnt be called
156  * too many times a month ;-)
157  */
158 void TreeSocket::SquitServer(std::string &from, TreeServer* Current, int& num_lost_servers, int& num_lost_users)
159 {
160         std::string servername = Current->GetName();
161         ServerInstance->Logs->Log("m_spanningtree",LOG_DEBUG,"SquitServer for %s from %s",
162                 servername.c_str(), from.c_str());
163         /* recursively squit the servers attached to 'Current'.
164          * We're going backwards so we don't remove users
165          * while we still need them ;)
166          */
167         for (unsigned int q = 0; q < Current->ChildCount(); q++)
168         {
169                 TreeServer* recursive_server = Current->GetChild(q);
170                 this->SquitServer(from,recursive_server, num_lost_servers, num_lost_users);
171         }
172         /* Now we've whacked the kids, whack self */
173         num_lost_servers++;
174         num_lost_users += Current->QuitUsers(from);
175 }
176
177 /** This is a wrapper function for SquitServer above, which
178  * does some validation first and passes on the SQUIT to all
179  * other remaining servers.
180  */
181 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
182 {
183         bool LocalSquit = false;
184
185         if ((Current) && (Current != Utils->TreeRoot))
186         {
187                 DelServerEvent(Utils->Creator, Current->GetName());
188
189                 if (!Current->GetSocket() || Current->GetSocket()->Introduced())
190                 {
191                         parameterlist params;
192                         params.push_back(Current->GetName());
193                         params.push_back(":"+reason);
194                         Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
195                 }
196
197                 if (Current->GetParent() == Utils->TreeRoot)
198                 {
199                         ServerInstance->SNO->WriteGlobalSno('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
200                         LocalSquit = true;
201                 }
202                 else
203                 {
204                         ServerInstance->SNO->WriteGlobalSno('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
205                 }
206                 int num_lost_servers = 0;
207                 int num_lost_users = 0;
208                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
209                 SquitServer(from, Current, num_lost_servers, num_lost_users);
210                 ServerInstance->SNO->WriteToSnoMask(LocalSquit ? 'l' : 'L', "Netsplit complete, lost \002%d\002 user%s on \002%d\002 server%s.",
211                         num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : "");
212                 Current->Tidy();
213                 Current->GetParent()->DelChild(Current);
214                 Current->cull();
215                 delete Current;
216                 if (Current == MyRoot)
217                 {
218                         MyRoot = NULL;
219                         Close();
220                 }
221         }
222         else
223                 ServerInstance->Logs->Log("m_spanningtree",LOG_DEFAULT,"Squit from unknown server");
224 }
225
226 /** This function is called when we receive data from a remote
227  * server.
228  */
229 void TreeSocket::OnDataReady()
230 {
231         Utils->Creator->loopCall = true;
232         std::string line;
233         while (GetNextLine(line))
234         {
235                 std::string::size_type rline = line.find('\r');
236                 if (rline != std::string::npos)
237                         line = line.substr(0,rline);
238                 if (line.find('\0') != std::string::npos)
239                 {
240                         SendError("Read null character from socket");
241                         break;
242                 }
243                 ProcessLine(line);
244                 if (!getError().empty())
245                         break;
246         }
247         if (LinkState != CONNECTED && recvq.length() > 4096)
248                 SendError("RecvQ overrun (line too long)");
249         Utils->Creator->loopCall = false;
250 }
251
252 bool TreeSocket::Introduced()
253 {
254         return (capab == NULL);
255 }