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