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