]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
Fix REMOVE maxparams
[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 "socket.h"
16 #include "xline.h"
17 #include "../transport.h"
18 #include "../m_hash.h"
19 #include "socketengine.h"
20
21 #include "main.h"
22 #include "utils.h"
23 #include "treeserver.h"
24 #include "link.h"
25 #include "treesocket.h"
26 #include "resolvers.h"
27 #include "handshaketimer.h"
28
29 /* $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 */
30
31
32 /** Because most of the I/O gubbins are encapsulated within
33  * BufferedSocket, we just call the superclass constructor for
34  * most of the action, and append a few of our own values
35  * to it.
36  */
37 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string shost, int iport, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Module* HookMod)
38         : BufferedSocket(SI, shost, iport, maxtime, bindto), Utils(Util), Hook(HookMod)
39 {
40         age = SI->Time();
41         myhost = ServerName;
42         capab_phase = 0;
43         proto_version = 0;
44         LinkState = CONNECTING;
45         Utils->timeoutlist[this] = std::pair<std::string, int>(ServerName, maxtime);
46         if (Hook)
47                 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
48         hstimer = NULL;
49 }
50
51 /** When a listening socket gives us a new file descriptor,
52  * we must associate it with a socket without creating a new
53  * connection. This constructor is used for this purpose.
54  */
55 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
56         : BufferedSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
57 {
58         age = SI->Time();
59         LinkState = WAIT_AUTH_1;
60         capab_phase = 0;
61         proto_version = 0;
62         /* If we have a transport module hooked to the parent, hook the same module to this
63          * socket, and set a timer waiting for handshake before we send CAPAB etc.
64          */
65         if (Hook)
66                 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
67
68         hstimer = new HandshakeTimer(ServerInstance, this, &(Utils->LinkBlocks[0]), this->Utils, 1);
69         ServerInstance->Timers->AddTimer(hstimer);
70
71         /* Fix by Brain - inbound sockets need a timeout, too. 30 secs should be pleanty */
72         Utils->timeoutlist[this] = std::pair<std::string, int>("<unknown>", 30);
73 }
74
75 ServerState TreeSocket::GetLinkState()
76 {
77         return this->LinkState;
78 }
79
80 Module* TreeSocket::GetHook()
81 {
82         return this->Hook;
83 }
84
85 void TreeSocket::CleanNegotiationInfo()
86 {
87         ModuleList.clear();
88         OptModuleList.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
128                                 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
129                                 if (this->GetHook())
130                                 {
131                                         hstimer = new HandshakeTimer(ServerInstance, this, &(*x), this->Utils, 1);
132                                         ServerInstance->Timers->AddTimer(hstimer);
133                                 }
134                                 else
135                                         this->SendCapabilities(1);
136
137                                 return true;
138                         }
139                 }
140         }
141         /* There is a (remote) chance that between the /CONNECT and the connection
142          * being accepted, some muppet has removed the <link> block and rehashed.
143          * If that happens the connection hangs here until it's closed. Unlikely
144          * and rather harmless.
145          */
146         ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2 lost link tag(!)", myhost.c_str());
147         return true;
148 }
149
150 void TreeSocket::OnError(BufferedSocketError e)
151 {
152         Link* MyLink;
153
154         switch (e)
155         {
156                 case I_ERR_CONNECT:
157                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Connection to \002%s\002 refused", myhost.c_str());
158                         MyLink = Utils->FindLink(myhost);
159                         if (MyLink)
160                                 Utils->DoFailOver(MyLink);
161                 break;
162                 case I_ERR_SOCKET:
163                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Could not create socket (%s)", strerror(errno));
164                 break;
165                 case I_ERR_BIND:
166                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Error binding socket to address or port (%s)", strerror(errno));
167                 break;
168                 case I_ERR_WRITE:
169                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: I/O error on connection (%s)", errno ? strerror(errno) : "Connection closed unexpectedly");
170                 break;
171                 case I_ERR_NOMOREFDS:
172                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Operating system is out of file descriptors!");
173                 break;
174                 default:
175                         if ((errno) && (errno != EINPROGRESS) && (errno != EAGAIN))
176                                 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \002%s\002 failed with OS error: %s", myhost.c_str(), strerror(errno));
177                 break;
178         }
179 }
180
181 int TreeSocket::OnDisconnect()
182 {
183         /* For the same reason as above, we don't
184          * handle OnDisconnect()
185          */
186         return true;
187 }
188
189 void TreeSocket::SendError(const std::string &errormessage)
190 {
191         /* Display the error locally as well as sending it remotely */
192         ServerInstance->SNO->WriteToSnoMask('l', "Sent \2ERROR\2 to %s: %s", (this->InboundServerName.empty() ? this->GetIP().c_str() : this->InboundServerName.c_str()), errormessage.c_str());
193         this->WriteLine("ERROR :"+errormessage);
194         /* One last attempt to make sure the error reaches its target */
195         this->FlushWriteBuffer();
196 }
197
198 /** This function forces this server to quit, removing this server
199  * and any users on it (and servers and users below that, etc etc).
200  * It's very slow and pretty clunky, but luckily unless your network
201  * is having a REAL bad hair day, this function shouldnt be called
202  * too many times a month ;-)
203  */
204 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
205 {
206         /* recursively squit the servers attached to 'Current'.
207          * We're going backwards so we don't remove users
208          * while we still need them ;)
209          */
210         for (unsigned int q = 0; q < Current->ChildCount(); q++)
211         {
212                 TreeServer* recursive_server = Current->GetChild(q);
213                 this->SquitServer(from,recursive_server);
214         }
215         /* Now we've whacked the kids, whack self */
216         num_lost_servers++;
217         num_lost_users += Current->QuitUsers(from);
218 }
219
220 /** This is a wrapper function for SquitServer above, which
221  * does some validation first and passes on the SQUIT to all
222  * other remaining servers.
223  */
224 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
225 {
226         bool LocalSquit = false;
227
228         if ((Current) && (Current != Utils->TreeRoot))
229         {
230                 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
231                 rmode.Send(ServerInstance);
232
233                 parameterlist params;
234                 params.push_back(Current->GetName());
235                 params.push_back(":"+reason);
236                 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
237                 if (Current->GetParent() == Utils->TreeRoot)
238                 {
239                         this->ServerInstance->SNO->WriteToSnoMask('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
240                         LocalSquit = true;
241                 }
242                 else
243                 {
244                         this->ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
245                 }
246                 num_lost_servers = 0;
247                 num_lost_users = 0;
248                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
249                 SquitServer(from, Current);
250                 Current->Tidy();
251                 Current->GetParent()->DelChild(Current);
252                 delete Current;
253                 if (LocalSquit)
254                         this->ServerInstance->SNO->WriteToSnoMask('l', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
255                 else
256                         this->ServerInstance->SNO->WriteToSnoMask('L', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
257         }
258         else
259                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server");
260 }
261
262 /** This function is called when we receive data from a remote
263  * server. We buffer the data in a std::string (it doesnt stay
264  * there for long), reading using BufferedSocket::Read() which can
265  * read up to 16 kilobytes in one operation.
266  *
267  * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
268  * THE SOCKET OBJECT FOR US.
269  */
270 bool TreeSocket::OnDataReady()
271 {
272         const char* data = this->Read();
273         /* Check that the data read is a valid pointer and it has some content */
274         if (data && *data)
275         {
276                 this->in_buffer.append(data);
277                 Utils->Creator->loopCall = true;
278                 /* While there is at least one new line in the buffer,
279                  * do something useful (we hope!) with it.
280                  */
281                 while (in_buffer.find("\n") != std::string::npos)
282                 {
283                         std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
284                         in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
285                         /* Use rfind here not find, as theres more
286                          * chance of the \r being near the end of the
287                          * string, not the start.
288                          */
289                         if (ret.find("\r") != std::string::npos)
290                                 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
291                         /* Process this one, abort if it
292                          * didnt return true.
293                          */
294                         if (!this->ProcessLine(ret))
295                         {
296                                 return false;
297                         }
298                 }
299                 Utils->Creator->loopCall = false;
300                 return true;
301         }
302         /* EAGAIN returns an empty but non-NULL string, so this
303          * evaluates to TRUE for EAGAIN but to FALSE for EOF.
304          */
305         return (data && !*data);
306 }