]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
Revert automated conversion by Special, as it (unfortunately) neglects some details...
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket1.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/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 "wildcard.h"
19 #include "xline.h"
20 #include "transport.h"
21 #include "m_hash.h"
22 #include "socketengine.h"
23
24 #include "m_spanningtree/main.h"
25 #include "m_spanningtree/utils.h"
26 #include "m_spanningtree/treeserver.h"
27 #include "m_spanningtree/link.h"
28 #include "m_spanningtree/treesocket.h"
29 #include "m_spanningtree/resolvers.h"
30 #include "m_spanningtree/handshaketimer.h"
31
32 /* $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 */
33
34
35 /** Because most of the I/O gubbins are encapsulated within
36  * BufferedSocket, we just call the superclass constructor for
37  * most of the action, and append a few of our own values
38  * to it.
39  */
40 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string shost, int iport, bool listening, unsigned long maxtime, Module* HookMod)
41         : BufferedSocket(SI, shost, iport, listening, maxtime), Utils(Util), Hook(HookMod)
42 {
43         myhost = host;
44         this->LinkState = LISTENER;
45         theirchallenge.clear();
46         ourchallenge.clear();
47         if (listening && Hook)
48                 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
49 }
50
51 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string shost, int iport, bool listening, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Module* HookMod)
52         : BufferedSocket(SI, shost, iport, listening, maxtime, bindto), Utils(Util), Hook(HookMod)
53 {
54         myhost = ServerName;
55         theirchallenge.clear();
56         ourchallenge.clear();
57         this->LinkState = CONNECTING;
58         if (Hook)
59                 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
60 }
61
62 /** When a listening socket gives us a new file descriptor,
63  * we must associate it with a socket without creating a new
64  * connection. This constructor is used for this purpose.
65  */
66 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
67         : BufferedSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
68 {
69         this->LinkState = WAIT_AUTH_1;
70         theirchallenge.clear();
71         ourchallenge.clear();
72         sentcapab = false;
73         /* If we have a transport module hooked to the parent, hook the same module to this
74          * socket, and set a timer waiting for handshake before we send CAPAB etc.
75          */
76         if (Hook)
77                 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
78
79         Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils, 1));
80 }
81
82 ServerState TreeSocket::GetLinkState()
83 {
84         return this->LinkState;
85 }
86
87 Module* TreeSocket::GetHook()
88 {
89         return this->Hook;
90 }
91
92 TreeSocket::~TreeSocket()
93 {
94         if (Hook)
95                 BufferedSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
96 }
97
98 /** When an outbound connection finishes connecting, we receive
99  * this event, and must send our SERVER string to the other
100  * side. If the other side is happy, as outlined in the server
101  * to server docs on the inspircd.org site, the other side
102  * will then send back its own server string.
103  */
104 bool TreeSocket::OnConnected()
105 {
106         if (this->LinkState == CONNECTING)
107         {
108                 /* we do not need to change state here. */
109                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
110                 {
111                         if (x->Name == this->myhost)
112                         {
113                                 Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()));
114                                 if (Hook)
115                                 {
116                                         BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
117                                         Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2[%s] using transport \2%s\2", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()),
118                                                         x->Hook.c_str());
119                                 }
120                                 this->OutboundPass = x->SendPass;
121                                 sentcapab = false;
122
123                                 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
124                                 if (this->GetHook())
125                                         Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils, 1));
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         this->Utils->Creator->RemoteMessage(NULL,"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         if (this->LinkState == LISTENER)
147                 return;
148
149         switch (e)
150         {
151                 case I_ERR_CONNECT:
152                         Utils->Creator->RemoteMessage(NULL,"Connection failed: Connection to \002%s\002 refused", myhost.c_str());
153                         MyLink = Utils->FindLink(myhost);
154                         if (MyLink)
155                                 Utils->DoFailOver(MyLink);
156                 break;
157                 case I_ERR_SOCKET:
158                         Utils->Creator->RemoteMessage(NULL,"Connection failed: Could not create socket (%s)", strerror(errno));
159                 break;
160                 case I_ERR_BIND:
161                         Utils->Creator->RemoteMessage(NULL,"Connection failed: Error binding socket to address or port (%s)", strerror(errno));
162                 break;
163                 case I_ERR_WRITE:
164                         Utils->Creator->RemoteMessage(NULL,"Connection failed: I/O error on connection (%s)", strerror(errno));
165                 break;
166                 case I_ERR_NOMOREFDS:
167                         Utils->Creator->RemoteMessage(NULL,"Connection failed: Operating system is out of file descriptors!");
168                 break;
169                 default:
170                         if ((errno) && (errno != EINPROGRESS) && (errno != EAGAIN))
171                                 Utils->Creator->RemoteMessage(NULL,"Connection to \002%s\002 failed with OS error: %s", myhost.c_str(), strerror(errno));
172                 break;
173         }
174 }
175
176 int TreeSocket::OnDisconnect()
177 {
178         /* For the same reason as above, we don't
179          * handle OnDisconnect()
180          */
181         return true;
182 }
183
184 void TreeSocket::SendError(const std::string &errormessage)
185 {
186         /* Display the error locally as well as sending it remotely */
187         Utils->Creator->RemoteMessage(NULL, "Sent \2ERROR\2 to %s: %s", (this->InboundServerName.empty() ? this->GetIP().c_str() : this->InboundServerName.c_str()), errormessage.c_str());
188         this->WriteLine("ERROR :"+errormessage);
189         /* One last attempt to make sure the error reaches its target */
190         this->FlushWriteBuffer();
191 }
192
193 /** This function forces this server to quit, removing this server
194  * and any users on it (and servers and users below that, etc etc).
195  * It's very slow and pretty clunky, but luckily unless your network
196  * is having a REAL bad hair day, this function shouldnt be called
197  * too many times a month ;-)
198  */
199 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
200 {
201         /* recursively squit the servers attached to 'Current'.
202          * We're going backwards so we don't remove users
203          * while we still need them ;)
204          */
205         for (unsigned int q = 0; q < Current->ChildCount(); q++)
206         {
207                 TreeServer* recursive_server = Current->GetChild(q);
208                 this->SquitServer(from,recursive_server);
209         }
210         /* Now we've whacked the kids, whack self */
211         num_lost_servers++;
212         num_lost_users += Current->QuitUsers(from);
213 }
214
215 /** This is a wrapper function for SquitServer above, which
216  * does some validation first and passes on the SQUIT to all
217  * other remaining servers.
218  */
219 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
220 {
221         if ((Current) && (Current != Utils->TreeRoot))
222         {
223                 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
224                 rmode.Send(Instance);
225
226                 std::deque<std::string> params;
227                 params.push_back(Current->GetName());
228                 params.push_back(":"+reason);
229                 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
230                 if (Current->GetParent() == Utils->TreeRoot)
231                 {
232                         this->Instance->SNO->WriteToSnoMask('l',"Server \002"+Current->GetName()+"\002 split: "+reason);
233                 }
234                 else
235                 {
236                         this->Instance->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                 this->Instance->SNO->WriteToSnoMask('l',"Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
246         }
247         else
248                 Instance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server");
249 }
250
251 /** This function is called when we receive data from a remote
252  * server. We buffer the data in a std::string (it doesnt stay
253  * there for long), reading using BufferedSocket::Read() which can
254  * read up to 16 kilobytes in one operation.
255  *
256  * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
257  * THE SOCKET OBJECT FOR US.
258  */
259 bool TreeSocket::OnDataReady()
260 {
261         const char* data = this->Read();
262         /* Check that the data read is a valid pointer and it has some content */
263         if (data && *data)
264         {
265                 this->in_buffer.append(data);
266                 /* While there is at least one new line in the buffer,
267                  * do something useful (we hope!) with it.
268                  */
269                 while (in_buffer.find("\n") != std::string::npos)
270                 {
271                         std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
272                         in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
273                         /* Use rfind here not find, as theres more
274                          * chance of the \r being near the end of the
275                          * string, not the start.
276                          */
277                         if (ret.find("\r") != std::string::npos)
278                                 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
279                         /* Process this one, abort if it
280                          * didnt return true.
281                          */
282                         if (!this->ProcessLine(ret))
283                         {
284                                 return false;
285                         }
286                 }
287                 return true;
288         }
289         /* EAGAIN returns an empty but non-NULL string, so this
290          * evaluates to TRUE for EAGAIN but to FALSE for EOF.
291          */
292         return (data && !*data);
293 }