]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/connection.cpp
cd994ea652870b469d6474a617ea01feb4b70e21
[user/henk/code/inspircd.git] / src / connection.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include <connection.h>
18 #include <unistd.h>
19 #include <fcntl.h>
20 #include <poll.h>
21 #include <sys/errno.h>
22 #include <sys/ioctl.h>
23 #include <sys/utsname.h>
24 #include <vector>
25 #include <string>
26 #include <deque>
27 #include "inspircd.h"
28 #include "modules.h"
29 #include "inspstring.h"
30
31 using namespace std;
32
33
34 extern std::vector<Module*> modules;
35 extern std::vector<ircd_module*> factory;
36
37 extern int MODCOUNT;
38
39 extern time_t TIME;
40
41 connection::connection()
42 {
43         fd = 0;
44 }
45
46
47 bool connection::CreateListener(char* newhost, int p)
48 {
49         sockaddr_in host_address;
50         int flags;
51         in_addr addy;
52         int on = 0;
53         struct linger linger = { 0 };
54         
55         this->port = p;
56         
57         fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
58         if (fd <= 0)
59         {
60                 return false;
61         }
62
63         setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
64         linger.l_onoff = 1;
65         linger.l_linger = 1;
66         setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
67         
68         // attempt to increase socket sendq and recvq as high as its possible
69         // to get them on linux.
70         int sendbuf = 32768;
71         int recvbuf = 32768;
72         setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
73         setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
74
75         memset((void*)&host_address, 0, sizeof(host_address));
76
77         host_address.sin_family = AF_INET;
78
79         if (!strcmp(newhost,""))
80         {
81                 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
82         }
83         else
84         {
85                 inet_aton(newhost,&addy);
86                 host_address.sin_addr = addy;
87         }
88
89         host_address.sin_port = htons(p);
90
91         if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
92         {
93                 return false;
94         }
95
96         // make the socket non-blocking
97         flags = fcntl(fd, F_GETFL, 0);
98         fcntl(fd, F_SETFL, flags | O_NONBLOCK);
99
100         this->port = p;
101
102         listen(this->fd,5);
103
104         return true;
105 }
106
107 char* ircd_connector::GetServerIP()
108 {
109         return this->host;
110 }
111
112 int ircd_connector::GetServerPort()
113 {
114         return this->port;
115 }
116
117 bool ircd_connector::SetHostAndPort(char* newhost, int newport)
118 {
119         strncpy(this->host,newhost,160);
120         this->port = newport;
121         return true;
122 }
123
124 bool ircd_connector::SetHostAddress(char* newhost, int newport)
125 {
126         strncpy(this->host,newhost,160);
127         this->port = newport;
128         memset((void*)&addr, 0, sizeof(addr));
129         addr.sin_family = AF_INET;
130         inet_aton(host,&addr.sin_addr);
131         addr.sin_port = htons(port);
132         return true;
133 }
134
135 void ircd_connector::SetServerPort(int p)
136 {
137         this->port = p;
138 }
139
140 void ircd_connector::AddBuffer(std::string a)
141 {
142         for (int i = 0; i < a.length(); i++)
143                 if (a[i] != '\r')
144                         ircdbuffer = ircdbuffer + a[i];
145 }
146
147 bool ircd_connector::BufferIsComplete()
148 {
149         for (int i = 0; i < ircdbuffer.length(); i++)
150                 if (ircdbuffer[i] == '\n')
151                         return true;
152         return false;
153 }
154
155 void ircd_connector::ClearBuffer()
156 {
157         while ((ircdbuffer != "") && (ircdbuffer[0] != '\n'))
158         {
159                 ircdbuffer.erase(ircdbuffer.begin());
160         }
161         if (ircdbuffer != "")
162                 ircdbuffer.erase(ircdbuffer.begin());
163 }
164
165 std::string ircd_connector::GetBuffer()
166 {
167         std::string z = "";
168         long t = 0;
169         while (ircdbuffer[t] != '\n')
170         {
171                 z = z + ircdbuffer[t];
172                 t++;
173         }
174         return z;
175 }
176
177 bool ircd_connector::MakeOutboundConnection(char* newhost, int newport)
178 {
179         log(DEBUG,"MakeOutboundConnection: Original param: %s",newhost);
180         ClearBuffer();
181         hostent* hoste = gethostbyname(newhost);
182         if (!hoste)
183         {
184                 log(DEBUG,"MakeOutboundConnection: gethostbyname was NULL, setting %s",newhost);
185                 this->SetHostAddress(newhost,newport);
186                 SetHostAndPort(newhost,newport);
187         }
188         else
189         {
190                 struct in_addr* ia = (in_addr*)hoste->h_addr;
191                 log(DEBUG,"MakeOutboundConnection: gethostbyname was valid, setting %s",inet_ntoa(*ia));
192                 this->SetHostAddress(inet_ntoa(*ia),newport);
193                 SetHostAndPort(inet_ntoa(*ia),newport);
194         }
195
196         this->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
197         if (this->fd >= 0)
198         {
199                 if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)))
200                 {
201                         WriteOpers("connect() failed for %s",host);
202                         RemoveServer(this->servername.c_str());
203                         return false;
204                 }
205                 int flags = fcntl(this->fd, F_GETFL, 0);
206                 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
207                 int sendbuf = 32768;
208                 int recvbuf = 32768;
209                 setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
210                 setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
211                 return true;
212         }
213         else
214         {
215                 WriteOpers("socket() failed!");
216                 RemoveServer(this->servername.c_str());
217         }
218
219         return false;
220 }
221
222
223 bool connection::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
224 {
225         char connect[MAXBUF];
226         
227         ircd_connector connector;
228         ircd_connector *cn = this->FindHost(servername);
229
230
231         if (cn)
232         {
233                 WriteOpers("CONNECT aborted: Server %s already exists",servername);
234                 return false;
235         }
236
237         
238         if (this->fd)
239         {
240                 if (connector.MakeOutboundConnection(targethost,newport))
241                 {
242                         // targethost has been turned into an ip...
243                         // we dont want this as the server name.
244                         connector.SetServerName(servername);
245                         snprintf(connect,MAXBUF,"S %s %s %lu %lu :%s",getservername().c_str(),password,(unsigned long)myport,(unsigned long)GetRevision(),getserverdesc().c_str());
246                         connector.SetState(STATE_NOAUTH_OUTBOUND);
247                         connector.SetHostAndPort(targethost, newport);
248                         this->connectors.push_back(connector);
249                         return this->SendPacket(connect, servername);
250                 }
251                 else
252                 {
253                         connector.SetState(STATE_DISCONNECTED);
254                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
255                 }
256         }
257         return false;
258 }
259
260 bool connection::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
261 {
262         char connect[MAXBUF];
263         
264         ircd_connector connector;
265         
266         WriteOpers("Establishing meshed link to %s:%d",servername,newport);
267
268         if (this->fd)
269         {
270                 if (connector.MakeOutboundConnection(targethost,newport))
271                 {
272                         // targethost has been turned into an ip...
273                         // we dont want this as the server name.
274                         connector.SetServerName(servername);
275                         snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
276                         connector.SetState(STATE_NOAUTH_OUTBOUND);
277                         connector.SetHostAndPort(targethost, newport);
278                         connector.SetState(STATE_CONNECTED);
279                         this->connectors.push_back(connector);
280                         return this->SendPacket(connect, servername);
281                 }
282                 else
283                 {
284                         connector.SetState(STATE_DISCONNECTED);
285                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
286                 }
287         }
288         return false;
289 }
290
291 bool connection::AddIncoming(int newfd, char* targethost, int sourceport)
292 {
293         ircd_connector connector;
294         
295         // targethost has been turned into an ip...
296         // we dont want this as the server name.
297         connector.SetServerName(targethost);
298         connector.SetDescriptor(newfd);
299         connector.SetState(STATE_NOAUTH_INBOUND);
300         int flags = fcntl(newfd, F_GETFL, 0);
301         fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
302         int sendbuf = 32768;
303         int recvbuf = 32768;
304         setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
305         setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
306         connector.SetHostAndPort(targethost, sourceport);
307         connector.SetState(STATE_NOAUTH_INBOUND);
308         log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
309         this->connectors.push_back(connector);
310         return true;
311 }
312
313 void connection::TerminateLink(char* targethost)
314 {
315         // this locates the targethost in the connection::connectors vector of the class,
316         // and terminates it by sending it an SQUIT token and closing its descriptor.
317         // TerminateLink with a null string causes a terminate of ALL links
318 }
319
320
321 // Returns a pointer to the connector for 'host'
322 ircd_connector* connection::FindHost(std::string findhost)
323 {
324         for (int i = 0; i < this->connectors.size(); i++)
325         {
326                 if (this->connectors[i].GetServerName() == findhost)
327                 {
328                         return &this->connectors[i];
329                 }
330         }
331         return NULL;
332 }
333
334 std::string ircd_connector::GetServerName()
335 {
336         return this->servername;
337 }
338
339 std::string ircd_connector::GetDescription()
340 {
341         return this->description;
342 }
343
344 void ircd_connector::SetServerName(std::string serv)
345 {
346         this->servername = serv;
347 }
348
349 void ircd_connector::SetDescription(std::string desc)
350 {
351         this->description = desc;
352 }
353
354
355 int ircd_connector::GetDescriptor()
356 {
357         return this->fd;
358 }
359
360 int ircd_connector::GetState()
361 {
362         return this->state;
363 }
364
365
366 void ircd_connector::SetState(int newstate)
367 {
368         this->state = newstate;
369         if (state == STATE_DISCONNECTED)
370         {
371                 NetSendMyRoutingTable();
372         }
373 }
374
375 void ircd_connector::CloseConnection()
376 {
377         int flags = fcntl(this->fd, F_GETFL, 0);
378         fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
379         close(this->fd);
380         flags = fcntl(this->fd, F_GETFL, 0);
381         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
382 }
383
384 void ircd_connector::SetDescriptor(int newfd)
385 {
386         this->fd = newfd;
387 }
388
389 bool connection::SendPacket(char *message, const char* sendhost)
390 {
391         if ((!message) || (!sendhost))
392                 return true;
393
394         ircd_connector* cn = this->FindHost(sendhost);
395         
396         if (!strchr(message,'\n'))
397         {
398                 strlcat(message,"\n",MAXBUF);
399         }
400
401         if (cn)
402         {
403                 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
404                 
405                 if (cn->GetState() == STATE_DISCONNECTED)
406                 {
407                         log(DEBUG,"Main route to %s is down, seeking alternative",host);
408                         // fix: can only route one hop to avoid a loop
409                         if (strncmp(message,"R ",2))
410                         {
411                                 // this route is down, we must re-route the packet through an available point in the mesh.
412                                 for (int k = 0; k < this->connectors.size(); k++)
413                                 {
414                                         // search for another point in the mesh which can 'reach' where we want to go
415                                         for (int m = 0; m < this->connectors[k].routes.size(); m++)
416                                         {
417                                                 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
418                                                 {
419                                                         log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
420                                                         char buffer[MAXBUF];
421                                                         snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
422                                                         this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
423                                                         return true;
424                                                 }
425                                         }
426                                 }
427                         }
428                         char buffer[MAXBUF];
429                         snprintf(buffer,MAXBUF,"& %s",sendhost);
430                         NetSendToAllExcept(sendhost,buffer);
431                         log(DEBUG,"There are no routes to %s, we're gonna boot the server off!",sendhost);
432                         DoSplit(sendhost);
433                         return false;
434                 }
435
436                 // returns false if the packet could not be sent (e.g. target host down)
437                 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
438                 {
439                         log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
440                         log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
441                         cn->CloseConnection();
442                         cn->SetState(STATE_DISCONNECTED);
443                         // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
444                         return this->SendPacket(message,sendhost);
445                 }
446                 return true;
447         }
448 }
449
450 // receives a packet from any where there is data waiting, first come, first served
451 // fills the message and host values with the host where the data came from.
452
453 bool connection::RecvPacket(std::deque<std::string> &messages, char* recvhost)
454 {
455         char data[4096];
456         memset(data, 0, 4096);
457         for (int i = 0; i < this->connectors.size(); i++)
458         {
459                 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
460                 {
461                         // returns false if the packet could not be sent (e.g. target host down)
462                         int rcvsize = 0;
463                         rcvsize = recv(this->connectors[i].GetDescriptor(),data,32,0);
464                         data[rcvsize] = '\0';
465                         if (rcvsize == -1)
466                         {
467                                 if (errno != EAGAIN)
468                                 {
469                                         log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
470                                         log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
471                                         this->connectors[i].CloseConnection();
472                                         this->connectors[i].SetState(STATE_DISCONNECTED);
473                                 }
474                         }
475                         if (rcvsize > 0)
476                         {
477                                 this->connectors[i].AddBuffer(data);
478                                 if (this->connectors[i].BufferIsComplete())
479                                 {
480                                         messages.push_back(this->connectors[i].GetBuffer().c_str());
481                                         strlcpy(host,this->connectors[i].GetServerName().c_str(),160);
482                                         log(DEBUG,"main: Connection::RecvPacket() got '%s' from %s",this->connectors[i].GetBuffer().c_str(),recvhost);
483                                         this->connectors[i].ClearBuffer();
484                                         return true;
485                                 }
486                         }
487                 }
488         }
489         // nothing new yet -- message and host will be undefined
490         return false;
491 }
492
493 long connection::GenKey()
494 {
495         return (random()*time(NULL));
496 }
497