]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/connection.cpp
Services speedups for stupid buffered i/o uplinks
[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* host, 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(host,""))
80         {
81                 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
82         }
83         else
84         {
85                 inet_aton(host,&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* host, int port)
118 {
119         strncpy(this->host,host,160);
120         this->port = port;
121         return true;
122 }
123
124 bool ircd_connector::SetHostAddress(char* host, int port)
125 {
126         strncpy(this->host,host,160);
127         this->port = port;
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* host, int port)
178 {
179         log(DEBUG,"MakeOutboundConnection: Original param: %s",host);
180         ClearBuffer();
181         hostent* hoste = gethostbyname(host);
182         if (!hoste)
183         {
184                 log(DEBUG,"MakeOutboundConnection: gethostbyname was NULL, setting %s",host);
185                 this->SetHostAddress(host,port);
186                 SetHostAndPort(host,port);
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),port);
193                 SetHostAndPort(inet_ntoa(*ia),port);
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 port, 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,port))
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 %d %d :%s",getservername().c_str(),password,myport,GetRevision(),getserverdesc().c_str());
246                         connector.SetState(STATE_NOAUTH_OUTBOUND);
247                         connector.SetHostAndPort(targethost, port);
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,port);
255                 }
256         }
257         return false;
258 }
259
260 bool connection::MeshCookie(char* targethost, int port, long cookie, char* servername)
261 {
262         char connect[MAXBUF];
263         
264         ircd_connector connector;
265         
266         WriteOpers("Establishing meshed link to %s:%d",servername,port);
267
268         if (this->fd)
269         {
270                 if (connector.MakeOutboundConnection(targethost,port))
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,"- %d %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
276                         connector.SetState(STATE_NOAUTH_OUTBOUND);
277                         connector.SetHostAndPort(targethost, port);
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,port);
286                 }
287         }
288         return false;
289 }
290
291 bool connection::AddIncoming(int fd, char* targethost, int sourceport)
292 {
293         char connect[MAXBUF];
294         
295         ircd_connector connector;
296         
297         // targethost has been turned into an ip...
298         // we dont want this as the server name.
299         connector.SetServerName(targethost);
300         connector.SetDescriptor(fd);
301         connector.SetState(STATE_NOAUTH_INBOUND);
302         int flags = fcntl(fd, F_GETFL, 0);
303         fcntl(fd, F_SETFL, flags | O_NONBLOCK);
304         int sendbuf = 32768;
305         int recvbuf = 32768;
306         setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
307         setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
308         connector.SetHostAndPort(targethost, sourceport);
309         connector.SetState(STATE_NOAUTH_INBOUND);
310         log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
311         this->connectors.push_back(connector);
312         return true;
313 }
314
315 void connection::TerminateLink(char* targethost)
316 {
317         // this locates the targethost in the connection::connectors vector of the class,
318         // and terminates it by sending it an SQUIT token and closing its descriptor.
319         // TerminateLink with a null string causes a terminate of ALL links
320 }
321
322
323 // Returns a pointer to the connector for 'host'
324 ircd_connector* connection::FindHost(std::string host)
325 {
326         for (int i = 0; i < this->connectors.size(); i++)
327         {
328                 if (this->connectors[i].GetServerName() == host)
329                 {
330                         return &this->connectors[i];
331                 }
332         }
333         return NULL;
334 }
335
336 std::string ircd_connector::GetServerName()
337 {
338         return this->servername;
339 }
340
341 std::string ircd_connector::GetDescription()
342 {
343         return this->description;
344 }
345
346 void ircd_connector::SetServerName(std::string serv)
347 {
348         this->servername = serv;
349 }
350
351 void ircd_connector::SetDescription(std::string desc)
352 {
353         this->description = desc;
354 }
355
356
357 int ircd_connector::GetDescriptor()
358 {
359         return this->fd;
360 }
361
362 int ircd_connector::GetState()
363 {
364         return this->state;
365 }
366
367
368 void ircd_connector::SetState(int state)
369 {
370         this->state = state;
371         if (state == STATE_DISCONNECTED)
372         {
373                 NetSendMyRoutingTable();
374         }
375 }
376
377 void ircd_connector::CloseConnection()
378 {
379         int flags = fcntl(this->fd, F_GETFL, 0);
380         fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
381         close(this->fd);
382         flags = fcntl(this->fd, F_GETFL, 0);
383         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
384 }
385
386 void ircd_connector::SetDescriptor(int fd)
387 {
388         this->fd = fd;
389 }
390
391 bool connection::SendPacket(char *message, const char* host)
392 {
393         if ((!message) || (!host))
394                 return true;
395
396         ircd_connector* cn = this->FindHost(host);
397         
398         if (!strchr(message,'\n'))
399         {
400                 strlcat(message,"\n",MAXBUF);
401         }
402
403         if (cn)
404         {
405                 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
406                 
407                 if (cn->GetState() == STATE_DISCONNECTED)
408                 {
409                         log(DEBUG,"Main route to %s is down, seeking alternative",host);
410                         // fix: can only route one hop to avoid a loop
411                         if (strlcat(message,"R ",2))
412                         {
413                                 // this route is down, we must re-route the packet through an available point in the mesh.
414                                 for (int k = 0; k < this->connectors.size(); k++)
415                                 {
416                                         // search for another point in the mesh which can 'reach' where we want to go
417                                         for (int m = 0; m < this->connectors[k].routes.size(); m++)
418                                         {
419                                                 if (!strcasecmp(this->connectors[k].routes[m].c_str(),host))
420                                                 {
421                                                         log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
422                                                         char buffer[MAXBUF];
423                                                         snprintf(buffer,MAXBUF,"R %s %s",host,message);
424                                                         this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
425                                                         return true;
426                                                 }
427                                         }
428                                 }
429                         }
430                         char buffer[MAXBUF];
431                         snprintf(buffer,MAXBUF,"& %s",host);
432                         NetSendToAllExcept(host,buffer);
433                         log(DEBUG,"There are no routes to %s, we're gonna boot the server off!",host);
434                         DoSplit(host);
435                         return false;
436                 }
437
438                 // returns false if the packet could not be sent (e.g. target host down)
439                 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
440                 {
441                         log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
442                         log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
443                         cn->CloseConnection();
444                         cn->SetState(STATE_DISCONNECTED);
445                         // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
446                         return this->SendPacket(message,host);
447                 }
448                 return true;
449         }
450 }
451
452 // receives a packet from any where there is data waiting, first come, first served
453 // fills the message and host values with the host where the data came from.
454
455 bool connection::RecvPacket(std::deque<std::string> &messages, char* host)
456 {
457         char data[4096];
458         memset(data, 0, 4096);
459         for (int i = 0; i < this->connectors.size(); i++)
460         {
461                 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
462                 {
463                         // returns false if the packet could not be sent (e.g. target host down)
464                         int rcvsize = 0;
465                         rcvsize = recv(this->connectors[i].GetDescriptor(),data,32,0);
466                         data[rcvsize] == '\0';
467                         if (rcvsize == -1)
468                         {
469                                 if (errno != EAGAIN)
470                                 {
471                                         log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
472                                         log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
473                                         this->connectors[i].CloseConnection();
474                                         this->connectors[i].SetState(STATE_DISCONNECTED);
475                                 }
476                         }
477                         if (rcvsize > 0)
478                         {
479                                 this->connectors[i].AddBuffer(data);
480                                 if (this->connectors[i].BufferIsComplete())
481                                 {
482                                         messages.push_back(this->connectors[i].GetBuffer().c_str());
483                                         strlcpy(host,this->connectors[i].GetServerName().c_str(),160);
484                                         log(DEBUG,"main: Connection::RecvPacket() got '%s' from %s",this->connectors[i].GetBuffer().c_str(),host);
485                                         this->connectors[i].ClearBuffer();
486                                         return true;
487                                 }
488                         }
489                 }
490         }
491         // nothing new yet -- message and host will be undefined
492         return false;
493 }
494
495 long connection::GenKey()
496 {
497         return (random()*time(NULL));
498 }
499