1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "commands/cmd_whois.h"
16 #include "commands/cmd_stats.h"
19 #include "transport.h"
21 #include "socketengine.h"
23 #include "m_spanningtree/main.h"
24 #include "m_spanningtree/utils.h"
25 #include "m_spanningtree/treeserver.h"
26 #include "m_spanningtree/link.h"
27 #include "m_spanningtree/treesocket.h"
28 #include "m_spanningtree/resolvers.h"
29 #include "m_spanningtree/handshaketimer.h"
31 /* $ModDep: m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h m_hash.h m_spanningtree/handshaketimer.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(SpanningTreeUtilities* Util, InspIRCd* SI, std::string shost, int iport, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Module* HookMod)
40 : BufferedSocket(SI, shost, iport, maxtime, bindto), Utils(Util), Hook(HookMod)
43 theirchallenge.clear();
45 this->LinkState = CONNECTING;
46 Utils->timeoutlist[this] = std::pair<std::string, int>(ServerName, maxtime);
48 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
52 /** When a listening socket gives us a new file descriptor,
53 * we must associate it with a socket without creating a new
54 * connection. This constructor is used for this purpose.
56 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
57 : BufferedSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
59 this->LinkState = WAIT_AUTH_1;
60 theirchallenge.clear();
63 /* If we have a transport module hooked to the parent, hook the same module to this
64 * socket, and set a timer waiting for handshake before we send CAPAB etc.
67 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
69 hstimer = new HandshakeTimer(ServerInstance, this, &(Utils->LinkBlocks[0]), this->Utils, 1);
70 ServerInstance->Timers->AddTimer(hstimer);
72 /* Fix by Brain - inbound sockets need a timeout, too. 30 secs should be pleanty */
73 Utils->timeoutlist[this] = std::pair<std::string, int>("<unknown>", 30);
76 ServerState TreeSocket::GetLinkState()
78 return this->LinkState;
81 Module* TreeSocket::GetHook()
86 TreeSocket::~TreeSocket()
89 BufferedSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
91 ServerInstance->Timers->DelTimer(hstimer);
92 Utils->timeoutlist.erase(this);
95 /** When an outbound connection finishes connecting, we receive
96 * this event, and must send our SERVER string to the other
97 * side. If the other side is happy, as outlined in the server
98 * to server docs on the inspircd.org site, the other side
99 * will then send back its own server string.
101 bool TreeSocket::OnConnected()
103 if (this->LinkState == CONNECTING)
105 /* we do not need to change state here. */
106 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
108 if (x->Name == this->myhost)
110 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()));
113 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
114 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2[%s] using transport \2%s\2", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()),
117 this->OutboundPass = x->SendPass;
120 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
123 hstimer = new HandshakeTimer(ServerInstance, this, &(*x), this->Utils, 1);
124 ServerInstance->Timers->AddTimer(hstimer);
127 this->SendCapabilities();
133 /* There is a (remote) chance that between the /CONNECT and the connection
134 * being accepted, some muppet has removed the <link> block and rehashed.
135 * If that happens the connection hangs here until it's closed. Unlikely
136 * and rather harmless.
138 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2 lost link tag(!)", myhost.c_str());
142 void TreeSocket::OnError(BufferedSocketError e)
149 ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Connection to \002%s\002 refused", myhost.c_str());
150 MyLink = Utils->FindLink(myhost);
152 Utils->DoFailOver(MyLink);
155 ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Could not create socket (%s)", strerror(errno));
158 ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Error binding socket to address or port (%s)", strerror(errno));
161 ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: I/O error on connection (%s)", errno ? strerror(errno) : "Connection closed unexpectedly");
163 case I_ERR_NOMOREFDS:
164 ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Operating system is out of file descriptors!");
167 if ((errno) && (errno != EINPROGRESS) && (errno != EAGAIN))
168 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \002%s\002 failed with OS error: %s", myhost.c_str(), strerror(errno));
173 int TreeSocket::OnDisconnect()
175 /* For the same reason as above, we don't
176 * handle OnDisconnect()
181 void TreeSocket::SendError(const std::string &errormessage)
183 /* Display the error locally as well as sending it remotely */
184 ServerInstance->SNO->WriteToSnoMask('l', "Sent \2ERROR\2 to %s: %s", (this->InboundServerName.empty() ? this->GetIP().c_str() : this->InboundServerName.c_str()), errormessage.c_str());
185 this->WriteLine("ERROR :"+errormessage);
186 /* One last attempt to make sure the error reaches its target */
187 this->FlushWriteBuffer();
190 /** This function forces this server to quit, removing this server
191 * and any users on it (and servers and users below that, etc etc).
192 * It's very slow and pretty clunky, but luckily unless your network
193 * is having a REAL bad hair day, this function shouldnt be called
194 * too many times a month ;-)
196 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
198 /* recursively squit the servers attached to 'Current'.
199 * We're going backwards so we don't remove users
200 * while we still need them ;)
202 for (unsigned int q = 0; q < Current->ChildCount(); q++)
204 TreeServer* recursive_server = Current->GetChild(q);
205 this->SquitServer(from,recursive_server);
207 /* Now we've whacked the kids, whack self */
209 num_lost_users += Current->QuitUsers(from);
212 /** This is a wrapper function for SquitServer above, which
213 * does some validation first and passes on the SQUIT to all
214 * other remaining servers.
216 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
218 bool LocalSquit = false;
220 if ((Current) && (Current != Utils->TreeRoot))
222 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
223 rmode.Send(ServerInstance);
225 std::deque<std::string> params;
226 params.push_back(Current->GetName());
227 params.push_back(":"+reason);
228 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
229 if (Current->GetParent() == Utils->TreeRoot)
231 this->ServerInstance->SNO->WriteToSnoMask('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
236 this->ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
238 num_lost_servers = 0;
240 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
241 SquitServer(from, Current);
243 Current->GetParent()->DelChild(Current);
246 this->ServerInstance->SNO->WriteToSnoMask('l', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
248 this->ServerInstance->SNO->WriteToSnoMask('L', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
251 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server");
254 /** This function is called when we receive data from a remote
255 * server. We buffer the data in a std::string (it doesnt stay
256 * there for long), reading using BufferedSocket::Read() which can
257 * read up to 16 kilobytes in one operation.
259 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
260 * THE SOCKET OBJECT FOR US.
262 bool TreeSocket::OnDataReady()
264 const char* data = this->Read();
265 /* Check that the data read is a valid pointer and it has some content */
268 this->in_buffer.append(data);
269 Utils->Creator->loopCall = true;
270 /* While there is at least one new line in the buffer,
271 * do something useful (we hope!) with it.
273 while (in_buffer.find("\n") != std::string::npos)
275 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
276 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
277 /* Use rfind here not find, as theres more
278 * chance of the \r being near the end of the
279 * string, not the start.
281 if (ret.find("\r") != std::string::npos)
282 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
283 /* Process this one, abort if it
286 if (!this->ProcessLine(ret))
291 Utils->Creator->loopCall = false;
294 /* EAGAIN returns an empty but non-NULL string, so this
295 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
297 return (data && !*data);