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