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