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