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