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