]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
Allow multiple autoconnects in a single <autoconnect> tag, fix infinite failover
[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 "socket.h"
16 #include "xline.h"
17 #include "../transport.h"
18 #include "../m_hash.h"
19 #include "socketengine.h"
20
21 #include "main.h"
22 #include "utils.h"
23 #include "treeserver.h"
24 #include "link.h"
25 #include "treesocket.h"
26 #include "resolvers.h"
27 #include "handshaketimer.h"
28
29 /* $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 */
30
31
32 /** Because most of the I/O gubbins are encapsulated within
33  * BufferedSocket, we just call the superclass constructor for
34  * most of the action, and append a few of our own values
35  * to it.
36  */
37 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, std::string shost, int iport, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Autoconnect* myac, Module* HookMod)
38         : Utils(Util), IP(shost), myautoconnect(myac)
39 {
40         age = ServerInstance->Time();
41         myhost = ServerName;
42         capab_phase = 0;
43         proto_version = 0;
44         LinkState = CONNECTING;
45         DoConnect(shost, iport, maxtime, bindto);
46         Utils->timeoutlist[this] = std::pair<std::string, int>(ServerName, maxtime);
47         if (HookMod)
48                 BufferedSocketHookRequest(this, Utils->Creator, HookMod).Send();
49         hstimer = NULL;
50 }
51
52 /** When a listening socket gives us a new file descriptor,
53  * we must associate it with a socket without creating a new
54  * connection. This constructor is used for this purpose.
55  */
56 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, int newfd, char* ip, Autoconnect* myac, Module* HookMod)
57         : BufferedSocket(newfd), Utils(Util), IP(ip), myautoconnect(myac)
58 {
59         age = ServerInstance->Time();
60         LinkState = WAIT_AUTH_1;
61         capab_phase = 0;
62         proto_version = 0;
63         /* If we have a transport module hooked to the parent, hook the same module to this
64          * socket, and set a timer waiting for handshake before we send CAPAB etc.
65          */
66         if (HookMod)
67                 BufferedSocketHookRequest(this, Utils->Creator, HookMod).Send();
68
69         hstimer = new HandshakeTimer(this, Utils->LinkBlocks[0], this->Utils, 1);
70         ServerInstance->Timers->AddTimer(hstimer);
71
72         /* Fix by Brain - inbound sockets need a timeout, too. 30 secs should be pleanty */
73         Utils->timeoutlist[this] = std::pair<std::string, int>("<unknown>", 30);
74 }
75
76 ServerState TreeSocket::GetLinkState()
77 {
78         return this->LinkState;
79 }
80
81 void TreeSocket::CleanNegotiationInfo()
82 {
83         ModuleList.clear();
84         OptModuleList.clear();
85         CapKeys.clear();
86         ourchallenge.clear();
87         theirchallenge.clear();
88         OutboundPass.clear();
89 }
90
91 TreeSocket::~TreeSocket()
92 {
93         if (GetIOHook())
94                 BufferedSocketUnhookRequest(this, Utils->Creator, GetIOHook()).Send();
95         if (hstimer)
96                 ServerInstance->Timers->DelTimer(hstimer);
97         Utils->timeoutlist.erase(this);
98 }
99
100 /** When an outbound connection finishes connecting, we receive
101  * this event, and must send our SERVER string to the other
102  * side. If the other side is happy, as outlined in the server
103  * to server docs on the inspircd.org site, the other side
104  * will then send back its own server string.
105  */
106 void TreeSocket::OnConnected()
107 {
108         if (this->LinkState == CONNECTING)
109         {
110                 /* we do not need to change state here. */
111                 for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); ++i)
112                 {
113                         Link* x = *i;
114                         if (x->Name == this->myhost)
115                         {
116                                 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->IP.c_str()));
117                                 this->OutboundPass = x->SendPass;
118                                 if (GetIOHook())
119                                 {
120                                         ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2[%s] using transport \2%s\2", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->IP.c_str()), x->Hook.c_str());
121                                         hstimer = new HandshakeTimer(this, &(*x), this->Utils, 1);
122                                         ServerInstance->Timers->AddTimer(hstimer);
123                                 }
124                                 else
125                                         this->SendCapabilities(1);
126                                 return;
127                         }
128                 }
129         }
130         /* There is a (remote) chance that between the /CONNECT and the connection
131          * being accepted, some muppet has removed the <link> block and rehashed.
132          * If that happens the connection hangs here until it's closed. Unlikely
133          * and rather harmless.
134          */
135         ServerInstance->SNO->WriteToSnoMask('l', "Connection to \2%s\2 lost link tag(!)", myhost.c_str());
136 }
137
138 void TreeSocket::OnError(BufferedSocketError e)
139 {
140         switch (e)
141         {
142                 case I_ERR_CONNECT:
143                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Connection to \002%s\002 refused", myhost.c_str());
144                         Utils->Creator->ConnectServer(myautoconnect);
145                 break;
146                 case I_ERR_SOCKET:
147                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Could not create socket (%s)", strerror(errno));
148                 break;
149                 case I_ERR_BIND:
150                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Error binding socket to address or port (%s)", strerror(errno));
151                 break;
152                 case I_ERR_WRITE:
153                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: I/O error on connection (%s)", errno ? strerror(errno) : "Connection closed unexpectedly");
154                 break;
155                 case I_ERR_NOMOREFDS:
156                         ServerInstance->SNO->WriteToSnoMask('l', "Connection failed: Operating system is out of file descriptors!");
157                 break;
158                 default:
159                         if ((errno) && (errno != EINPROGRESS) && (errno != EAGAIN))
160                                 ServerInstance->SNO->WriteToSnoMask('l', "Connection to \002%s\002 failed with OS error: %s", myhost.c_str(), strerror(errno));
161                 break;
162         }
163 }
164
165 void TreeSocket::SendError(const std::string &errormessage)
166 {
167         /* Display the error locally as well as sending it remotely */
168         ServerInstance->SNO->WriteToSnoMask('l', "Sent \2ERROR\2 to %s: %s", (this->InboundServerName.empty() ? this->IP.c_str() : this->InboundServerName.c_str()), errormessage.c_str());
169         WriteLine("ERROR :"+errormessage);
170 }
171
172 /** This function forces this server to quit, removing this server
173  * and any users on it (and servers and users below that, etc etc).
174  * It's very slow and pretty clunky, but luckily unless your network
175  * is having a REAL bad hair day, this function shouldnt be called
176  * too many times a month ;-)
177  */
178 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
179 {
180         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"SquitServer for %s from %s",
181                 Current->GetName().c_str(), from.c_str());
182         /* recursively squit the servers attached to 'Current'.
183          * We're going backwards so we don't remove users
184          * while we still need them ;)
185          */
186         for (unsigned int q = 0; q < Current->ChildCount(); q++)
187         {
188                 TreeServer* recursive_server = Current->GetChild(q);
189                 this->SquitServer(from,recursive_server);
190         }
191         /* Now we've whacked the kids, whack self */
192         num_lost_servers++;
193         num_lost_users += Current->QuitUsers(from);
194 }
195
196 /** This is a wrapper function for SquitServer above, which
197  * does some validation first and passes on the SQUIT to all
198  * other remaining servers.
199  */
200 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
201 {
202         bool LocalSquit = false;
203
204         if ((Current) && (Current != Utils->TreeRoot))
205         {
206                 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
207                 rmode.Send();
208
209                 parameterlist params;
210                 params.push_back(Current->GetName());
211                 params.push_back(":"+reason);
212                 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
213                 if (Current->GetParent() == Utils->TreeRoot)
214                 {
215                         ServerInstance->SNO->WriteToSnoMask('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
216                         LocalSquit = true;
217                 }
218                 else
219                 {
220                         ServerInstance->SNO->WriteToSnoMask('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
221                 }
222                 num_lost_servers = 0;
223                 num_lost_users = 0;
224                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
225                 SquitServer(from, Current);
226                 Current->Tidy();
227                 Current->GetParent()->DelChild(Current);
228                 delete Current;
229                 if (LocalSquit)
230                         ServerInstance->SNO->WriteToSnoMask('l', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
231                 else
232                         ServerInstance->SNO->WriteToSnoMask('L', "Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
233         }
234         else
235                 ServerInstance->Logs->Log("m_spanningtree",DEFAULT,"Squit from unknown server");
236 }
237
238 /** This function is called when we receive data from a remote
239  * server.
240  */
241 void TreeSocket::OnDataReady()
242 {
243         Utils->Creator->loopCall = true;
244         /* While there is at least one new line in the buffer,
245          * do something useful (we hope!) with it.
246          */
247         while (recvq.find("\n") != std::string::npos)
248         {
249                 std::string ret = recvq.substr(0,recvq.find("\n")-1);
250                 recvq = recvq.substr(recvq.find("\n")+1,recvq.length()-recvq.find("\n"));
251                 /* Use rfind here not find, as theres more
252                  * chance of the \r being near the end of the
253                  * string, not the start.
254                  */
255                 if (ret.find("\r") != std::string::npos)
256                         ret = recvq.substr(0,recvq.find("\r")-1);
257                 /* Process this one, abort if it
258                  * didnt return true.
259                  */
260                 if (!this->ProcessLine(ret))
261                 {
262                         SetError("ProcessLine returned false");
263                         break;
264                 }
265         }
266         Utils->Creator->loopCall = false;
267 }