]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/connection.cpp
b627c24945d8926b66538d4adaa3291d92b5358d
[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 using namespace std;
18
19 #include <connection.h>
20 #include <unistd.h>
21 #include <fcntl.h>
22 #include <poll.h>
23 #include <sys/errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/utsname.h>
26 #include <vector>
27 #include <string>
28 #include <deque>
29 #include <sstream>
30 #include "inspircd.h"
31 #include "modules.h"
32 #include "inspstring.h"
33 #include "helperfuncs.h"
34
35
36 extern std::vector<Module*, __single_client_alloc> modules;
37 extern std::vector<ircd_module*, __single_client_alloc> factory;
38
39 std::deque<std::string, __single_client_alloc> xsums;
40
41 extern int MODCOUNT;
42
43 extern time_t TIME;
44
45
46 /**
47  * The InspIRCd mesh network is maintained by a tree of objects which reference *themselves*.
48  * Every local server has an array of 32 *serverrecs, known as me[]. Each of these represents
49  * a local listening port, and is not null if the user has opened a listening port on the server.
50  * It is assumed nobody will ever want to open more than 32 listening server ports at any one
51  * time (i mean come on, why would you want more, the ircd works fine with ONE).
52  * Each me[] entry has multiple classes within it of type ircd_connector. These are stored in a vector
53  * and each represents a server linked via this socket. If the connection was created outbound,
54  * the connection is bound to the default ip address by using me[defaultRoute] (defaultRoute being
55  * a global variable which indicates the default server to make connections on). If the connection
56  * was created inbound, it is attached to the port the connection came in on. There may be as many
57  * ircd_connector objects as needed in each me[] entry. Each ircd_connector implements the specifics
58  * of an ircd connection in the mesh, however each ircd may have multiple ircd_connector connections
59  * to it, to maintain the mesh link.
60  */
61
62 char* xsumtable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
63
64 // creates a random id for a line for detection of duplicate messages
65 std::string CreateSum()
66 {
67         char sum[9];
68         sum[0] = ':';
69         sum[8] = '\0';
70         for(int q = 1; q < 8; q++)
71                 sum[q] = xsumtable[rand()%52];
72         return sum;
73 }
74
75 connection::connection()
76 {
77         fd = 0;
78 }
79
80
81 bool connection::CreateListener(char* newhost, int p)
82 {
83         sockaddr_in host_address;
84         int flags;
85         in_addr addy;
86         int on = 0;
87         struct linger linger = { 0 };
88         
89         this->port = p;
90         
91         fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
92         if (fd <= 0)
93         {
94                 return false;
95         }
96
97         setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
98         linger.l_onoff = 1;
99         linger.l_linger = 1;
100         setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
101         
102         // attempt to increase socket sendq and recvq as high as its possible
103         // to get them on linux.
104         int sendbuf = 32768;
105         int recvbuf = 32768;
106         setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
107         setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
108
109         memset((void*)&host_address, 0, sizeof(host_address));
110
111         host_address.sin_family = AF_INET;
112
113         if (!strcmp(newhost,""))
114         {
115                 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
116         }
117         else
118         {
119                 inet_aton(newhost,&addy);
120                 host_address.sin_addr = addy;
121         }
122
123         host_address.sin_port = htons(p);
124
125         if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
126         {
127                 return false;
128         }
129
130         // make the socket non-blocking
131         flags = fcntl(fd, F_GETFL, 0);
132         fcntl(fd, F_SETFL, flags | O_NONBLOCK);
133
134         this->port = p;
135
136         listen(this->fd,5);
137
138         return true;
139 }
140
141 char* ircd_connector::GetServerIP()
142 {
143         return this->host;
144 }
145
146 int ircd_connector::GetServerPort()
147 {
148         return this->port;
149 }
150
151 bool ircd_connector::SetHostAndPort(char* newhost, int newport)
152 {
153         strncpy(this->host,newhost,160);
154         this->port = newport;
155         return true;
156 }
157
158 bool ircd_connector::SetHostAddress(char* newhost, int newport)
159 {
160         strncpy(this->host,newhost,160);
161         this->port = newport;
162         memset((void*)&addr, 0, sizeof(addr));
163         addr.sin_family = AF_INET;
164         inet_aton(host,&addr.sin_addr);
165         addr.sin_port = htons(port);
166         return true;
167 }
168
169 void ircd_connector::SetServerPort(int p)
170 {
171         this->port = p;
172 }
173
174 void ircd_connector::AddBuffer(std::string a)
175 {
176         std::string b = "";
177         for (int i = 0; i < a.length(); i++)
178                 if (a[i] != '\r')
179                         b = b + a[i];
180
181         std::stringstream stream(ircdbuffer);
182         stream << b;
183         log(DEBUG,"AddBuffer: %s",b.c_str());
184         ircdbuffer = stream.str();
185 }
186
187 bool ircd_connector::BufferIsComplete()
188 {
189         for (int i = 0; i < ircdbuffer.length(); i++)
190                 if (ircdbuffer[i] == '\n')
191                         return true;
192         return false;
193 }
194
195 void ircd_connector::ClearBuffer()
196 {
197         ircdbuffer = "";
198 }
199
200 std::string ircd_connector::GetBuffer()
201 {
202         // Fix by Brain 28th Apr 2005
203         // seems my stringstream code isnt liked by linux
204         // EVEN THOUGH IT IS CORRECT! Fixed by using a different
205         // (SLOWER) algorithm...
206         char* line = (char*)ircdbuffer.c_str();
207         std::string ret = "";
208         while ((*line != '\n') && (strlen(line)))
209         {
210                 ret = ret + *line;
211                 line++;
212         }
213         if ((*line == '\n') || (*line == '\r'))
214                 line++;
215         ircdbuffer = line;
216         return ret;
217 }
218
219 bool ircd_connector::MakeOutboundConnection(char* newhost, int newport)
220 {
221         log(DEBUG,"MakeOutboundConnection: Original param: %s",newhost);
222         ClearBuffer();
223         hostent* hoste = gethostbyname(newhost);
224         if (!hoste)
225         {
226                 log(DEBUG,"MakeOutboundConnection: gethostbyname was NULL, setting %s",newhost);
227                 this->SetHostAddress(newhost,newport);
228                 SetHostAndPort(newhost,newport);
229         }
230         else
231         {
232                 struct in_addr* ia = (in_addr*)hoste->h_addr;
233                 log(DEBUG,"MakeOutboundConnection: gethostbyname was valid, setting %s",inet_ntoa(*ia));
234                 this->SetHostAddress(inet_ntoa(*ia),newport);
235                 SetHostAndPort(inet_ntoa(*ia),newport);
236         }
237
238         this->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
239         if (this->fd >= 0)
240         {
241                 if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)))
242                 {
243                         WriteOpers("connect() failed for %s",host);
244                         RemoveServer(this->servername.c_str());
245                         return false;
246                 }
247                 int flags = fcntl(this->fd, F_GETFL, 0);
248                 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
249                 int sendbuf = 32768;
250                 int recvbuf = 32768;
251                 setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
252                 setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
253                 return true;
254         }
255         else
256         {
257                 WriteOpers("socket() failed!");
258                 RemoveServer(this->servername.c_str());
259         }
260
261         return false;
262 }
263
264
265 bool connection::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
266 {
267         char connect[MAXBUF];
268         
269         ircd_connector connector;
270         ircd_connector *cn = this->FindHost(servername);
271
272
273         if (cn)
274         {
275                 WriteOpers("CONNECT aborted: Server %s already exists",servername);
276                 return false;
277         }
278
279         
280         if (this->fd)
281         {
282                 if (connector.MakeOutboundConnection(targethost,newport))
283                 {
284                         // targethost has been turned into an ip...
285                         // we dont want this as the server name.
286                         connector.SetServerName(servername);
287                         snprintf(connect,MAXBUF,"S %s %s %lu %lu :%s",getservername().c_str(),password,(unsigned long)myport,(unsigned long)GetRevision(),getserverdesc().c_str());
288                         connector.SetState(STATE_NOAUTH_OUTBOUND);
289                         connector.SetHostAndPort(targethost, newport);
290                         this->connectors.push_back(connector);
291                         return this->SendPacket(connect, servername);
292                 }
293                 else
294                 {
295                         connector.SetState(STATE_DISCONNECTED);
296                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
297                 }
298         }
299         return false;
300 }
301
302 void ircd_connector::SetVersionString(std::string newversion)
303 {
304         log(DEBUG,"Set version of %s to %s",this->servername.c_str(),newversion.c_str());
305         this->version = newversion;
306 }
307
308 std::string ircd_connector::GetVersionString()
309 {
310         return this->version;
311 }
312
313 bool connection::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
314 {
315         char connect[MAXBUF];
316         
317         ircd_connector connector;
318         
319         WriteOpers("Establishing meshed link to %s:%d",servername,newport);
320
321         if (this->fd)
322         {
323                 if (connector.MakeOutboundConnection(targethost,newport))
324                 {
325                         // targethost has been turned into an ip...
326                         // we dont want this as the server name.
327                         connector.SetServerName(servername);
328                         snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
329                         connector.SetState(STATE_NOAUTH_OUTBOUND);
330                         connector.SetHostAndPort(targethost, newport);
331                         connector.SetState(STATE_CONNECTED);
332                         this->connectors.push_back(connector);
333                         return this->SendPacket(connect, servername);
334                 }
335                 else
336                 {
337                         connector.SetState(STATE_DISCONNECTED);
338                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
339                 }
340         }
341         return false;
342 }
343
344 bool connection::AddIncoming(int newfd, char* targethost, int sourceport)
345 {
346         ircd_connector connector;
347         
348         // targethost has been turned into an ip...
349         // we dont want this as the server name.
350         connector.SetServerName(targethost);
351         connector.SetDescriptor(newfd);
352         connector.SetState(STATE_NOAUTH_INBOUND);
353         int flags = fcntl(newfd, F_GETFL, 0);
354         fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
355         int sendbuf = 32768;
356         int recvbuf = 32768;
357         setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
358         setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
359         connector.SetHostAndPort(targethost, sourceport);
360         connector.SetState(STATE_NOAUTH_INBOUND);
361         log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
362         this->connectors.push_back(connector);
363         return true;
364 }
365
366 void connection::TerminateLink(char* targethost)
367 {
368         // this locates the targethost in the connection::connectors vector of the class,
369         // and terminates it by sending it an SQUIT token and closing its descriptor.
370         // TerminateLink with a null string causes a terminate of ALL links
371 }
372
373
374 // Returns a pointer to the connector for 'host'
375 ircd_connector* connection::FindHost(std::string findhost)
376 {
377         for (int i = 0; i < this->connectors.size(); i++)
378         {
379                 if (this->connectors[i].GetServerName() == findhost)
380                 {
381                         return &this->connectors[i];
382                 }
383         }
384         return NULL;
385 }
386
387 std::string ircd_connector::GetServerName()
388 {
389         return this->servername;
390 }
391
392 std::string ircd_connector::GetDescription()
393 {
394         return this->description;
395 }
396
397 void ircd_connector::SetServerName(std::string serv)
398 {
399         this->servername = serv;
400 }
401
402 void ircd_connector::SetDescription(std::string desc)
403 {
404         this->description = desc;
405 }
406
407
408 int ircd_connector::GetDescriptor()
409 {
410         return this->fd;
411 }
412
413 int ircd_connector::GetState()
414 {
415         return this->state;
416 }
417
418
419 void ircd_connector::SetState(int newstate)
420 {
421         this->state = newstate;
422         if (state == STATE_DISCONNECTED)
423         {
424                 NetSendMyRoutingTable();
425         }
426 }
427
428 void ircd_connector::CloseConnection()
429 {
430         int flags = fcntl(this->fd, F_GETFL, 0);
431         fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
432         close(this->fd);
433         flags = fcntl(this->fd, F_GETFL, 0);
434         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
435 }
436
437 void ircd_connector::SetDescriptor(int newfd)
438 {
439         this->fd = newfd;
440 }
441
442 bool connection::SendPacket(char *message, const char* sendhost)
443 {
444         if ((!message) || (!sendhost))
445                 return true;
446
447         ircd_connector* cn = this->FindHost(sendhost);
448         
449         if (!strchr(message,'\n'))
450         {
451                 strlcat(message,"\n",MAXBUF);
452         }
453
454         if (cn)
455         {
456                 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
457                 
458                 if (cn->GetState() == STATE_DISCONNECTED)
459                 {
460                         log(DEBUG,"\n\n\n\nMain route to %s is down, seeking alternative\n\n\n\n",sendhost);
461                         // fix: can only route one hop to avoid a loop
462                         if (strncmp(message,"R ",2))
463                         {
464                                 log(DEBUG,"Not a double reroute");
465                                 // this route is down, we must re-route the packet through an available point in the mesh.
466                                 for (int k = 0; k < this->connectors.size(); k++)
467                                 {
468                                         log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
469                                         // search for another point in the mesh which can 'reach' where we want to go
470                                         for (int m = 0; m < this->connectors[k].routes.size(); m++)
471                                         {
472                                                 log(DEBUG,"Check connector %d: %s route %s",k,this->connectors[k].GetServerName().c_str(),this->connectors[k].routes[m].c_str());
473                                                 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
474                                                 {
475                                                         log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
476                                                         char buffer[MAXBUF];
477                                                         snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
478                                                         this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
479                                                         return true;
480                                                 }
481                                         }
482                                 }
483                         }
484                         char buffer[MAXBUF];
485                         snprintf(buffer,MAXBUF,"& %s",sendhost);
486                         NetSendToAllExcept(sendhost,buffer);
487                         log(DEBUG,"\n\nThere are no routes to %s, we're gonna boot the server off!\n\n",sendhost);
488                         DoSplit(sendhost);
489                         return false;
490                 }
491
492                 // returns false if the packet could not be sent (e.g. target host down)
493                 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
494                 {
495                         log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
496                         log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
497                         cn->CloseConnection();
498                         cn->SetState(STATE_DISCONNECTED);
499                         // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
500                         return this->SendPacket(message,sendhost);
501                 }
502                 return true;
503         }
504 }
505
506 bool already_have_sum(std::string sum)
507 {
508         for (int i = 0; i < xsums.size(); i++)
509         {
510                 if (xsums[i] == sum)
511                 {
512                         return true;
513                 }
514         }
515         if (xsums.size() >= 128)
516         {
517                 xsums.pop_front();
518         }
519         xsums.push_back(sum);
520         return false;
521 }
522
523 // receives a packet from any where there is data waiting, first come, first served
524 // fills the message and host values with the host where the data came from.
525
526 bool connection::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
527 {
528         char data[65536];
529         memset(data, 0, 65536);
530         for (int i = 0; i < this->connectors.size(); i++)
531         {
532                 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
533                 {
534                         // returns false if the packet could not be sent (e.g. target host down)
535                         int rcvsize = 0;
536
537                         // check if theres any data on this socket
538                         // if not, continue onwards to the next.
539                         pollfd polls;
540                         polls.fd = this->connectors[i].GetDescriptor();
541                         polls.events = POLLIN;
542                         int ret = poll(&polls,1,1);
543                         if (ret <= 0) continue;
544
545                         rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
546                         data[rcvsize] = '\0';
547                         if (rcvsize == -1)
548                         {
549                                 if (errno != EAGAIN)
550                                 {
551                                         log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
552                                         log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
553                                         this->connectors[i].CloseConnection();
554                                         this->connectors[i].SetState(STATE_DISCONNECTED);
555                                 }
556                         }
557                         int pushed = 0;
558                         if (rcvsize > 0)
559                         {
560                                 this->connectors[i].AddBuffer(data);
561                                 if (this->connectors[i].BufferIsComplete())
562                                 {
563                                         while (this->connectors[i].BufferIsComplete())
564                                         {
565                                                 std::string text = this->connectors[i].GetBuffer();
566                                                 if (text != "")
567                                                 {
568                                                         if ((text[0] == ':') && (text.find(" ") != std::string::npos))
569                                                         {
570                                                                 std::string orig = text;
571                                                                 log(DEBUG,"Original: %s",text.c_str());
572                                                                 std::string sum = text.substr(1,text.find(" ")-1);
573                                                                 text = text.substr(text.find(" ")+1,text.length());
574                                                                 std::string possible_token = text.substr(1,text.find(" ")-1);
575                                                                 if (possible_token.length() > 1)
576                                                                 {
577                                                                         sums.push_back("*");
578                                                                         text = orig;
579                                                                         log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
580                                                                 }
581                                                                 else
582                                                                 {
583                                                                         log(DEBUG,"Packet sum: '%s'",sum.c_str());
584                                                                         if ((already_have_sum(sum)) && (sum != "*"))
585                                                                         {
586                                                                                 // we don't accept dupes
587                                                                                 log(DEBUG,"Duplicate packet sum %s from server %s dropped",sum.c_str(),this->connectors[i].GetServerName().c_str());
588                                                                                 continue;
589                                                                         }
590                                                                         sums.push_back(sum.c_str());
591                                                                 }
592                                                         }
593                                                         else sums.push_back("*");
594                                                         messages.push_back(text.c_str());
595                                                         strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
596                                                         log(DEBUG,"Connection::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str()); 
597                                                 }
598                                         }
599                                         return true;
600                                 }
601                         }
602                 }
603         }
604         // nothing new yet -- message and host will be undefined
605         return false;
606 }
607