]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
d0db01dec87292e3e2c1e2a7f6f8bcd30ac39218
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket1.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "commands/cmd_whois.h"
16 #include "commands/cmd_stats.h"
17 #include "socket.h"
18 #include "xline.h"
19 #include "transport.h"
20 #include "m_hash.h"
21 #include "socketengine.h"
22
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"
30
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 */
32
33
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
37  * to it.
38  */
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)
41 {
42         myhost = ServerName;
43         theirchallenge.clear();
44         ourchallenge.clear();
45         this->LinkState = CONNECTING;
46         Utils->timeoutlist[this] = std::pair<std::string, int>(ServerName, maxtime);
47         if (Hook)
48                 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
49         hstimer = NULL;
50 }
51
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.
55  */
56 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
57         : BufferedSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
58 {
59         this->LinkState = WAIT_AUTH_1;
60         theirchallenge.clear();
61         ourchallenge.clear();
62         sentcapab = false;
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.
65          */
66         if (Hook)
67                 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
68
69         hstimer = new HandshakeTimer(ServerInstance, this, &(Utils->LinkBlocks[0]), this->Utils, 1);
70         ServerInstance->Timers->AddTimer(hstimer);
71
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);
74 }
75
76 ServerState TreeSocket::GetLinkState()
77 {
78         return this->LinkState;
79 }
80
81 Module* TreeSocket::GetHook()
82 {
83         return this->Hook;
84 }
85
86 TreeSocket::~TreeSocket()
87 {
88         if (Hook)
89                 BufferedSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
90         if (hstimer)
91                 ServerInstance->Timers->DelTimer(hstimer);
92         Utils->timeoutlist.erase(this);
93 }
94
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.
100  */
101 bool TreeSocket::OnConnected()
102 {
103         if (this->LinkState == CONNECTING)
104         {
105                 /* we do not need to change state here. */
106                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
107                 {
108                         if (x->Name == this->myhost)
109                         {
110                                 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()));
111                                 if (Hook)
112                                 {
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()),
115                                                         x->Hook.c_str());
116                                 }
117                                 this->OutboundPass = x->SendPass;
118                                 sentcapab = false;
119
120                                 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
121                                 if (this->GetHook())
122                                 {
123                                         hstimer = new HandshakeTimer(ServerInstance, this, &(*x), this->Utils, 1);
124                                         ServerInstance->Timers->AddTimer(hstimer);
125                                 }
126                                 else
127                                         this->SendCapabilities();
128
129                                 return true;
130                         }
131                 }
132         }
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.
137          */
138         ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2 lost link tag(!)", myhost.c_str());
139         return true;
140 }
141
142 void TreeSocket::OnError(BufferedSocketError e)
143 {
144         Link* MyLink;
145
146         switch (e)
147         {
148                 case I_ERR_CONNECT:
149                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Connection to \002%s\002 refused", myhost.c_str());
150                         MyLink = Utils->FindLink(myhost);
151                         if (MyLink)
152                                 Utils->DoFailOver(MyLink);
153                 break;
154                 case I_ERR_SOCKET:
155                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Could not create socket (%s)", strerror(errno));
156                 break;
157                 case I_ERR_BIND:
158                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Error binding socket to address or port (%s)", strerror(errno));
159                 break;
160                 case I_ERR_WRITE:
161                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: I/O error on connection (%s)", errno ? strerror(errno) : "Connection closed unexpectedly");
162                 break;
163                 case I_ERR_NOMOREFDS:
164                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Operating system is out of file descriptors!");
165                 break;
166                 default:
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));
169                 break;
170         }
171 }
172
173 int TreeSocket::OnDisconnect()
174 {
175         /* For the same reason as above, we don't
176          * handle OnDisconnect()
177          */
178         return true;
179 }
180
181 void TreeSocket::SendError(const std::string &errormessage)
182 {
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();
188 }
189
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 ;-)
195  */
196 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
197 {
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 ;)
201          */
202         for (unsigned int q = 0; q < Current->ChildCount(); q++)
203         {
204                 TreeServer* recursive_server = Current->GetChild(q);
205                 this->SquitServer(from,recursive_server);
206         }
207         /* Now we've whacked the kids, whack self */
208         num_lost_servers++;
209         num_lost_users += Current->QuitUsers(from);
210 }
211
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.
215  */
216 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
217 {
218         bool LocalSquit = false;
219
220         if ((Current) && (Current != Utils->TreeRoot))
221         {
222                 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
223                 rmode.Send(ServerInstance);
224
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)
230                 {
231                         this->ServerInstance->SNO->WriteToSnoMask('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
232                         LocalSquit = true;
233                 }
234                 else
235                 {
236                         this->ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
237                 }
238                 num_lost_servers = 0;
239                 num_lost_users = 0;
240                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
241                 SquitServer(from, Current);
242                 Current->Tidy();
243                 Current->GetParent()->DelChild(Current);
244                 delete Current;
245                 if (LocalSquit)
246                         this->ServerInstance->SNO->WriteToSnoMask('l', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
247                 else
248                         this->ServerInstance->SNO->WriteToSnoMask('L', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
249         }
250         else
251                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server");
252 }
253
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.
258  *
259  * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
260  * THE SOCKET OBJECT FOR US.
261  */
262 bool TreeSocket::OnDataReady()
263 {
264         const char* data = this->Read();
265         /* Check that the data read is a valid pointer and it has some content */
266         if (data && *data)
267         {
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.
272                  */
273                 while (in_buffer.find("\n") != std::string::npos)
274                 {
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.
280                          */
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
284                          * didnt return true.
285                          */
286                         if (!this->ProcessLine(ret))
287                         {
288                                 return false;
289                         }
290                 }
291                 Utils->Creator->loopCall = false;
292                 return true;
293         }
294         /* EAGAIN returns an empty but non-NULL string, so this
295          * evaluates to TRUE for EAGAIN but to FALSE for EOF.
296          */
297         return (data && !*data);
298 }