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