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