2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
27 #include "modules/spanningtree.h"
29 #include "treeserver.h"
31 #include "treesocket.h"
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
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())
43 capab = new CapabData;
46 capab->capab_phase = 0;
48 DoConnect(ipaddr, link->Port, link->Timeout, link->Bind);
49 Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, link->Timeout);
53 /** When a listening socket gives us a new file descriptor,
54 * we must associate it with a socket without creating a new
55 * connection. This constructor is used for this purpose.
57 TreeSocket::TreeSocket(int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
58 : BufferedSocket(newfd)
59 , linkID("inbound from " + client->addr()), LinkState(WAIT_AUTH_1), MyRoot(NULL), proto_version(0)
60 , ConnectionFailureShown(false), age(ServerInstance->Time())
62 capab = new CapabData;
63 capab->capab_phase = 0;
66 via->iohookprov->OnAccept(this, client, server);
69 Utils->timeoutlist[this] = std::pair<std::string, int>(linkID, 30);
72 ServerState TreeSocket::GetLinkState()
74 return this->LinkState;
77 void TreeSocket::CleanNegotiationInfo()
79 // connect is good, reset the autoconnect block (if used)
81 capab->ac->position = -1;
86 CullResult TreeSocket::cull()
88 Utils->timeoutlist.erase(this);
89 if (capab && capab->ac)
90 Utils->Creator->ConnectServer(capab->ac, false);
91 return this->BufferedSocket::cull();
94 TreeSocket::~TreeSocket()
99 /** When an outbound connection finishes connecting, we receive
100 * this event, and must send our SERVER string to the other
101 * side. If the other side is happy, as outlined in the server
102 * to server docs on the inspircd.org site, the other side
103 * will then send back its own server string.
105 void TreeSocket::OnConnected()
107 if (this->LinkState == CONNECTING)
109 if (!capab->link->Hook.empty())
111 ServiceProvider* prov = ServerInstance->Modules->FindService(SERVICE_IOHOOK, capab->link->Hook);
114 SetError("Could not find hook '" + capab->link->Hook + "' for connection to " + linkID);
117 static_cast<IOHookProvider*>(prov)->OnConnect(this);
120 ServerInstance->SNO->WriteGlobalSno('l', "Connection to \2%s\2[%s] started.", linkID.c_str(),
121 (capab->link->HiddenFromStats ? "<hidden>" : capab->link->IPAddr.c_str()));
122 this->SendCapabilities(1);
126 void TreeSocket::OnError(BufferedSocketError e)
128 ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\002%s\002' failed with error: %s",
129 linkID.c_str(), getError().c_str());
133 void TreeSocket::SendError(const std::string &errormessage)
135 WriteLine("ERROR :"+errormessage);
138 SetError(errormessage);
141 /** This function forces this server to quit, removing this server
142 * and any users on it (and servers and users below that, etc etc).
143 * It's very slow and pretty clunky, but luckily unless your network
144 * is having a REAL bad hair day, this function shouldnt be called
145 * too many times a month ;-)
147 void TreeSocket::SquitServer(std::string &from, TreeServer* Current, int& num_lost_servers, int& num_lost_users)
149 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "SquitServer for %s from %s", Current->GetName().c_str(), from.c_str());
150 /* recursively squit the servers attached to 'Current'.
151 * We're going backwards so we don't remove users
152 * while we still need them ;)
154 const TreeServer::ChildServers& children = Current->GetChildren();
155 for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
157 TreeServer* recursive_server = *i;
158 this->SquitServer(from,recursive_server, num_lost_servers, num_lost_users);
160 /* Now we've whacked the kids, whack self */
162 num_lost_users += Current->QuitUsers(from);
165 /** This is a wrapper function for SquitServer above, which
166 * does some validation first and passes on the SQUIT to all
167 * other remaining servers.
169 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
171 bool LocalSquit = false;
173 if (!Current->IsRoot())
175 DelServerEvent(Utils->Creator, Current->GetName());
177 if (Current->IsLocal())
179 ServerInstance->SNO->WriteGlobalSno('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
181 if (Current->GetSocket()->Introduced())
183 CmdBuilder params("SQUIT");
184 params.push_back(Current->GetID());
185 params.push_last(reason);
191 ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
193 int num_lost_servers = 0;
194 int num_lost_users = 0;
195 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
197 ModuleSpanningTree* st = Utils->Creator;
198 st->SplitInProgress = true;
199 SquitServer(from, Current, num_lost_servers, num_lost_users);
200 st->SplitInProgress = false;
202 ServerInstance->SNO->WriteToSnoMask(LocalSquit ? 'l' : 'L', "Netsplit complete, lost \002%d\002 user%s on \002%d\002 server%s.",
203 num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : "");
205 Current->GetParent()->DelChild(Current);
207 const bool ismyroot = (Current == MyRoot);
217 CmdResult CommandSQuit::HandleServer(TreeServer* server, std::vector<std::string>& params)
219 TreeServer* quitting = Utils->FindServer(params[0]);
222 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Squit from unknown server");
226 TreeSocket* sock = server->GetSocket();
227 sock->Squit(quitting, params[1]);
229 // XXX: Return CMD_FAILURE when servers SQUIT themselves (i.e. :00S SQUIT 00S :Shutting down)
230 // to avoid RouteCommand() being called. RouteCommand() requires a valid command source but we
231 // do not have one because the server user is deleted when its TreeServer is destructed.
232 // We generate a SQUIT in TreeSocket::Squit(), with our sid as the source and send it to the
233 // remaining servers.
234 return ((quitting == server) ? CMD_FAILURE : CMD_SUCCESS);
237 /** This function is called when we receive data from a remote
240 void TreeSocket::OnDataReady()
242 Utils->Creator->loopCall = true;
244 while (GetNextLine(line))
246 std::string::size_type rline = line.find('\r');
247 if (rline != std::string::npos)
248 line = line.substr(0,rline);
249 if (line.find('\0') != std::string::npos)
251 SendError("Read null character from socket");
259 catch (CoreException& ex)
261 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Error while processing: " + line);
262 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, ex.GetReason());
263 SendError(ex.GetReason() + " - check the log file for details");
266 if (!getError().empty())
269 if (LinkState != CONNECTED && recvq.length() > 4096)
270 SendError("RecvQ overrun (line too long)");
271 Utils->Creator->loopCall = false;
274 bool TreeSocket::Introduced()
276 return (capab == NULL);