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