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