]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket1.cpp
fcd6871e1a06533b182221512070eb729ffdb7b6
[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         if (!hook.empty())
42         {
43                 modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
44                 if (ml)
45                 {
46                         for(modulelist::iterator i = ml->begin(); i != ml->end(); ++i)
47                         {
48                                 std::string name = (**i).ModuleSourceFile;
49                                 int a = name.rfind('_');
50                                 int b = name.rfind('.');
51                                 name = name.substr(a+1, b-a-1);
52                                 if (name == hook)
53                                 {
54                                         AddIOHook(*i);
55                                         goto found;
56                                 }
57                         }
58                 }
59                 SetError("Could not find hook '" + hook + "' for connection to " + ServerName);
60                 return;
61         }
62 found:
63         DoConnect(shost, iport, maxtime, bindto);
64         Utils->timeoutlist[this] = std::pair<std::string, int>(ServerName, maxtime);
65         SendCapabilities(1);
66 }
67
68 /** When a listening socket gives us a new file descriptor,
69  * we must associate it with a socket without creating a new
70  * connection. This constructor is used for this purpose.
71  */
72 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
73         : BufferedSocket(newfd), Utils(Util)
74 {
75         IP = client->addr();
76         age = ServerInstance->Time();
77         LinkState = WAIT_AUTH_1;
78         capab_phase = 0;
79         proto_version = 0;
80         myhost = "inbound from " + IP;
81
82         FOREACH_MOD(I_OnHookIO, OnHookIO(this, via));
83         if (GetIOHook())
84                 GetIOHook()->OnStreamSocketAccept(this, client, server);
85         SendCapabilities(1);
86
87         Utils->timeoutlist[this] = std::pair<std::string, int>(myhost, 30);
88 }
89
90 ServerState TreeSocket::GetLinkState()
91 {
92         return this->LinkState;
93 }
94
95 void TreeSocket::CleanNegotiationInfo()
96 {
97         ModuleList.clear();
98         OptModuleList.clear();
99         CapKeys.clear();
100         ourchallenge.clear();
101         theirchallenge.clear();
102         OutboundPass.clear();
103 }
104
105 CullResult TreeSocket::cull()
106 {
107         Utils->timeoutlist.erase(this);
108         if (myautoconnect)
109                 Utils->Creator->ConnectServer(myautoconnect, false);
110         return this->BufferedSocket::cull();
111 }
112
113 TreeSocket::~TreeSocket()
114 {
115 }
116
117 /** When an outbound connection finishes connecting, we receive
118  * this event, and must send our SERVER string to the other
119  * side. If the other side is happy, as outlined in the server
120  * to server docs on the inspircd.org site, the other side
121  * will then send back its own server string.
122  */
123 void TreeSocket::OnConnected()
124 {
125         if (this->LinkState == CONNECTING)
126         {
127                 /* we do not need to change state here. */
128                 for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); ++i)
129                 {
130                         Link* x = *i;
131                         if (x->Name == this->myhost)
132                         {
133                                 ServerInstance->SNO->WriteGlobalSno('l', "Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->IP.c_str()));
134                                 this->OutboundPass = x->SendPass;
135                                 this->SendCapabilities(1);
136                                 return;
137                         }
138                 }
139         }
140         /* There is a (remote) chance that between the /CONNECT and the connection
141          * being accepted, some muppet has removed the <link> block and rehashed.
142          * If that happens the connection hangs here until it's closed. Unlikely
143          * and rather harmless.
144          */
145         ServerInstance->SNO->WriteGlobalSno('l', "Connection to \2%s\2 lost link tag(!)", myhost.c_str());
146 }
147
148 void TreeSocket::OnError(BufferedSocketError e)
149 {
150         ServerInstance->SNO->WriteGlobalSno('l', "Connection to \002%s\002 failed with error: %s",
151                 myhost.c_str(), getError().c_str());
152 }
153
154 void TreeSocket::SendError(const std::string &errormessage)
155 {
156         WriteLine("ERROR :"+errormessage);
157         SetError(errormessage);
158 }
159
160 /** This function forces this server to quit, removing this server
161  * and any users on it (and servers and users below that, etc etc).
162  * It's very slow and pretty clunky, but luckily unless your network
163  * is having a REAL bad hair day, this function shouldnt be called
164  * too many times a month ;-)
165  */
166 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
167 {
168         ServerInstance->Logs->Log("m_spanningtree",DEBUG,"SquitServer for %s from %s",
169                 Current->GetName().c_str(), from.c_str());
170         /* recursively squit the servers attached to 'Current'.
171          * We're going backwards so we don't remove users
172          * while we still need them ;)
173          */
174         for (unsigned int q = 0; q < Current->ChildCount(); q++)
175         {
176                 TreeServer* recursive_server = Current->GetChild(q);
177                 this->SquitServer(from,recursive_server);
178         }
179         /* Now we've whacked the kids, whack self */
180         num_lost_servers++;
181         num_lost_users += Current->QuitUsers(from);
182 }
183
184 /** This is a wrapper function for SquitServer above, which
185  * does some validation first and passes on the SQUIT to all
186  * other remaining servers.
187  */
188 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
189 {
190         bool LocalSquit = false;
191
192         if ((Current) && (Current != Utils->TreeRoot))
193         {
194                 DelServerEvent(Utils->Creator, Current->GetName());
195
196                 parameterlist params;
197                 params.push_back(Current->GetName());
198                 params.push_back(":"+reason);
199                 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
200                 if (Current->GetParent() == Utils->TreeRoot)
201                 {
202                         ServerInstance->SNO->WriteGlobalSno('l', "Server \002"+Current->GetName()+"\002 split: "+reason);
203                         LocalSquit = true;
204                 }
205                 else
206                 {
207                         ServerInstance->SNO->WriteGlobalSno('L', "Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
208                 }
209                 num_lost_servers = 0;
210                 num_lost_users = 0;
211                 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
212                 SquitServer(from, Current);
213                 Current->Tidy();
214                 Current->GetParent()->DelChild(Current);
215                 Current->cull();
216                 delete Current;
217                 if (LocalSquit)
218                         ServerInstance->SNO->WriteToSnoMask('l', "Netsplit complete, lost \002%d\002 user%s on \002%d\002 server%s.", num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : "");
219                 else
220                         ServerInstance->SNO->WriteToSnoMask('L', "Netsplit complete, lost \002%d\002 user%s on \002%d\002 server%s.", num_lost_users, num_lost_users != 1 ? "s" : "", num_lost_servers, num_lost_servers != 1 ? "s" : "");
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 }