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