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