1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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"
20 #include "transport.h"
22 #include "socketengine.h"
24 #include "m_spanningtree/main.h"
25 #include "m_spanningtree/utils.h"
26 #include "m_spanningtree/treeserver.h"
27 #include "m_spanningtree/link.h"
28 #include "m_spanningtree/treesocket.h"
29 #include "m_spanningtree/resolvers.h"
30 #include "m_spanningtree/handshaketimer.h"
32 /* $ModDep: m_spanningtree/timesynctimer.h 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 */
35 /** Because most of the I/O gubbins are encapsulated within
36 * BufferedSocket, we just call the superclass constructor for
37 * most of the action, and append a few of our own values
40 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string shost, int iport, bool listening, unsigned long maxtime, Module* HookMod)
41 : BufferedSocket(SI, shost, iport, listening, maxtime), Utils(Util), Hook(HookMod)
44 this->LinkState = LISTENER;
45 theirchallenge.clear();
47 if (listening && Hook)
48 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
51 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string shost, int iport, bool listening, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Module* HookMod)
52 : BufferedSocket(SI, shost, iport, listening, maxtime, bindto), Utils(Util), Hook(HookMod)
55 theirchallenge.clear();
57 this->LinkState = CONNECTING;
59 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
62 /** When a listening socket gives us a new file descriptor,
63 * we must associate it with a socket without creating a new
64 * connection. This constructor is used for this purpose.
66 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
67 : BufferedSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
69 this->LinkState = WAIT_AUTH_1;
70 theirchallenge.clear();
73 /* If we have a transport module hooked to the parent, hook the same module to this
74 * socket, and set a timer waiting for handshake before we send CAPAB etc.
77 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
79 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils, 1));
82 ServerState TreeSocket::GetLinkState()
84 return this->LinkState;
87 Module* TreeSocket::GetHook()
92 TreeSocket::~TreeSocket()
95 BufferedSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
98 /** When an outbound connection finishes connecting, we receive
99 * this event, and must send our SERVER string to the other
100 * side. If the other side is happy, as outlined in the server
101 * to server docs on the inspircd.org site, the other side
102 * will then send back its own server string.
104 bool TreeSocket::OnConnected()
106 if (this->LinkState == CONNECTING)
108 /* we do not need to change state here. */
109 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
111 if (x->Name == this->myhost)
113 Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()));
116 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
117 Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2[%s] using transport \2%s\2", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()),
120 this->OutboundPass = x->SendPass;
123 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
125 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils, 1));
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 this->Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2 lost link tag(!)", myhost.c_str());
142 void TreeSocket::OnError(BufferedSocketError e)
146 if (this->LinkState == LISTENER)
152 Utils->Creator->RemoteMessage(NULL,"Connection failed: Connection to \002%s\002 refused", myhost.c_str());
153 MyLink = Utils->FindLink(myhost);
155 Utils->DoFailOver(MyLink);
158 Utils->Creator->RemoteMessage(NULL,"Connection failed: Could not create socket");
161 Utils->Creator->RemoteMessage(NULL,"Connection failed: Error binding socket to address or port");
164 Utils->Creator->RemoteMessage(NULL,"Connection failed: I/O error on connection");
166 case I_ERR_NOMOREFDS:
167 Utils->Creator->RemoteMessage(NULL,"Connection failed: Operating system is out of file descriptors!");
170 if ((errno) && (errno != EINPROGRESS) && (errno != EAGAIN))
171 Utils->Creator->RemoteMessage(NULL,"Connection to \002%s\002 failed with OS error: %s", myhost.c_str(), strerror(errno));
176 int TreeSocket::OnDisconnect()
178 /* For the same reason as above, we don't
179 * handle OnDisconnect()
184 void TreeSocket::SendError(const std::string &errormessage)
186 /* Display the error locally as well as sending it remotely */
187 Utils->Creator->RemoteMessage(NULL, "Sent \2ERROR\2 to %s: %s", (this->InboundServerName.empty() ? "<unknown>" : this->InboundServerName.c_str()), errormessage.c_str());
188 this->WriteLine("ERROR :"+errormessage);
189 /* One last attempt to make sure the error reaches its target */
190 this->FlushWriteBuffer();
193 /** This function forces this server to quit, removing this server
194 * and any users on it (and servers and users below that, etc etc).
195 * It's very slow and pretty clunky, but luckily unless your network
196 * is having a REAL bad hair day, this function shouldnt be called
197 * too many times a month ;-)
199 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
201 /* recursively squit the servers attached to 'Current'.
202 * We're going backwards so we don't remove users
203 * while we still need them ;)
205 for (unsigned int q = 0; q < Current->ChildCount(); q++)
207 TreeServer* recursive_server = Current->GetChild(q);
208 this->SquitServer(from,recursive_server);
210 /* Now we've whacked the kids, whack self */
212 num_lost_users += Current->QuitUsers(from);
215 /** This is a wrapper function for SquitServer above, which
216 * does some validation first and passes on the SQUIT to all
217 * other remaining servers.
219 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
221 if ((Current) && (Current != Utils->TreeRoot))
223 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
224 rmode.Send(Instance);
226 std::deque<std::string> params;
227 params.push_back(Current->GetName());
228 params.push_back(":"+reason);
229 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
230 if (Current->GetParent() == Utils->TreeRoot)
232 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+Current->GetName()+"\002 split: "+reason);
236 this->Instance->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);
245 this->Instance->SNO->WriteToSnoMask('l',"Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
248 Instance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server");
251 /** This function is called when we receive data from a remote
252 * server. We buffer the data in a std::string (it doesnt stay
253 * there for long), reading using BufferedSocket::Read() which can
254 * read up to 16 kilobytes in one operation.
256 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
257 * THE SOCKET OBJECT FOR US.
259 bool TreeSocket::OnDataReady()
261 const char* data = this->Read();
262 /* Check that the data read is a valid pointer and it has some content */
265 this->in_buffer.append(data);
266 /* While there is at least one new line in the buffer,
267 * do something useful (we hope!) with it.
269 while (in_buffer.find("\n") != std::string::npos)
271 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
272 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
273 /* Use rfind here not find, as theres more
274 * chance of the \r being near the end of the
275 * string, not the start.
277 if (ret.find("\r") != std::string::npos)
278 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
279 /* Process this one, abort if it
282 if (!this->ProcessLine(ret))
289 /* EAGAIN returns an empty but non-NULL string, so this
290 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
292 return (data && !*data);