]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
e98246a3559de58c5b2fe03dfc2d1aa604ffc6e2
[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 "main.h"
24 #include "utils.h"
25 #include "treeserver.h"
26 #include "link.h"
27 #include "treesocket.h"
28 #include "resolvers.h"
29 #include "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 void TreeSocket::CleanNegotiationInfo()
87 {
88         ModuleList.clear();
89         CapKeys.clear();
90         ourchallenge.clear();
91         theirchallenge.clear();
92         OutboundPass.clear();
93 }
94
95 TreeSocket::~TreeSocket()
96 {
97         if (Hook)
98                 BufferedSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
99         if (hstimer)
100                 ServerInstance->Timers->DelTimer(hstimer);
101         Utils->timeoutlist.erase(this);
102 }
103
104 /** When an outbound connection finishes connecting, we receive
105  * this event, and must send our SERVER string to the other
106  * side. If the other side is happy, as outlined in the server
107  * to server docs on the inspircd.org site, the other side
108  * will then send back its own server string.
109  */
110 bool TreeSocket::OnConnected()
111 {
112         if (this->LinkState == CONNECTING)
113         {
114                 /* we do not need to change state here. */
115                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
116                 {
117                         if (x->Name == this->myhost)
118                         {
119                                 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()));
120                                 if (Hook)
121                                 {
122                                         BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
123                                         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()),
124                                                         x->Hook.c_str());
125                                 }
126                                 this->OutboundPass = x->SendPass;
127                                 sentcapab = false;
128
129                                 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
130                                 if (this->GetHook())
131                                 {
132                                         hstimer = new HandshakeTimer(ServerInstance, this, &(*x), this->Utils, 1);
133                                         ServerInstance->Timers->AddTimer(hstimer);
134                                 }
135                                 else
136                                         this->SendCapabilities();
137
138                                 return true;
139                         }
140                 }
141         }
142         /* There is a (remote) chance that between the /CONNECT and the connection
143          * being accepted, some muppet has removed the <link> block and rehashed.
144          * If that happens the connection hangs here until it's closed. Unlikely
145          * and rather harmless.
146          */
147         ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2 lost link tag(!)", myhost.c_str());
148         return true;
149 }
150
151 void TreeSocket::OnError(BufferedSocketError e)
152 {
153         Link* MyLink;
154
155         switch (e)
156         {
157                 case I_ERR_CONNECT:
158                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Connection to \002%s\002 refused", myhost.c_str());
159                         MyLink = Utils->FindLink(myhost);
160                         if (MyLink)
161                                 Utils->DoFailOver(MyLink);
162                 break;
163                 case I_ERR_SOCKET:
164                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Could not create socket (%s)", strerror(errno));
165                 break;
166                 case I_ERR_BIND:
167                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Error binding socket to address or port (%s)", strerror(errno));
168                 break;
169                 case I_ERR_WRITE:
170                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: I/O error on connection (%s)", errno ? strerror(errno) : "Connection closed unexpectedly");
171                 break;
172                 case I_ERR_NOMOREFDS:
173                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Operating system is out of file descriptors!");
174                 break;
175                 default:
176                         if ((errno) && (errno != EINPROGRESS) && (errno != EAGAIN))
177                                 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \002%s\002 failed with OS error: %s", myhost.c_str(), strerror(errno));
178                 break;
179         }
180 }
181
182 int TreeSocket::OnDisconnect()
183 {
184         /* For the same reason as above, we don't
185          * handle OnDisconnect()
186          */
187         return true;
188 }
189
190 void TreeSocket::SendError(const std::string &errormessage)
191 {
192         /* Display the error locally as well as sending it remotely */
193         ServerInstance->SNO->WriteToSnoMask('l', "Sent \2ERROR\2 to %s: %s", (this->InboundServerName.empty() ? this->GetIP().c_str() : this->InboundServerName.c_str()), errormessage.c_str());
194         this->WriteLine("ERROR :"+errormessage);
195         /* One last attempt to make sure the error reaches its target */
196         this->FlushWriteBuffer();
197 }
198
199 /** This function forces this server to quit, removing this server
200  * and any users on it (and servers and users below that, etc etc).
201  * It's very slow and pretty clunky, but luckily unless your network
202  * is having a REAL bad hair day, this function shouldnt be called
203  * too many times a month ;-)
204  */
205 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
206 {
207         /* recursively squit the servers attached to 'Current'.
208          * We're going backwards so we don't remove users
209          * while we still need them ;)
210          */
211         for (unsigned int q = 0; q < Current->ChildCount(); q++)
212         {
213                 TreeServer* recursive_server = Current->GetChild(q);
214                 this->SquitServer(from,recursive_server);
215         }
216         /* Now we've whacked the kids, whack self */
217         num_lost_servers++;
218         num_lost_users += Current->QuitUsers(from);
219 }
220
221 /** This is a wrapper function for SquitServer above, which
222  * does some validation first and passes on the SQUIT to all
223  * other remaining servers.
224  */
225 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
226 {
227         bool LocalSquit = false;
228
229         if ((Current) && (Current != Utils->TreeRoot))
230         {
231                 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
232                 rmode.Send(ServerInstance);
233
234                 std::deque<std::string> params;
235                 params.push_back(Current->GetName());
236                 params.push_back(":"+reason);
237                 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
238                 if (Current->GetParent() == Utils->TreeRoot)
239                 {
240                         this->ServerInstance->SNO->WriteToSnoMask('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
241                         LocalSquit = true;
242                 }
243                 else
244                 {
245                         this->ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
246                 }
247                 num_lost_servers = 0;
248                 num_lost_users = 0;
249                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
250                 SquitServer(from, Current);
251                 Current->Tidy();
252                 Current->GetParent()->DelChild(Current);
253                 delete Current;
254                 if (LocalSquit)
255                         this->ServerInstance->SNO->WriteToSnoMask('l', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
256                 else
257                         this->ServerInstance->SNO->WriteToSnoMask('L', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
258         }
259         else
260                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server");
261 }
262
263 /** This function is called when we receive data from a remote
264  * server. We buffer the data in a std::string (it doesnt stay
265  * there for long), reading using BufferedSocket::Read() which can
266  * read up to 16 kilobytes in one operation.
267  *
268  * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
269  * THE SOCKET OBJECT FOR US.
270  */
271 bool TreeSocket::OnDataReady()
272 {
273         const char* data = this->Read();
274         /* Check that the data read is a valid pointer and it has some content */
275         if (data && *data)
276         {
277                 this->in_buffer.append(data);
278                 Utils->Creator->loopCall = true;
279                 /* While there is at least one new line in the buffer,
280                  * do something useful (we hope!) with it.
281                  */
282                 while (in_buffer.find("\n") != std::string::npos)
283                 {
284                         std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
285                         in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
286                         /* Use rfind here not find, as theres more
287                          * chance of the \r being near the end of the
288                          * string, not the start.
289                          */
290                         if (ret.find("\r") != std::string::npos)
291                                 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
292                         /* Process this one, abort if it
293                          * didnt return true.
294                          */
295                         if (!this->ProcessLine(ret))
296                         {
297                                 return false;
298                         }
299                 }
300                 Utils->Creator->loopCall = false;
301                 return true;
302         }
303         /* EAGAIN returns an empty but non-NULL string, so this
304          * evaluates to TRUE for EAGAIN but to FALSE for EOF.
305          */
306         return (data && !*data);
307 }