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