]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/connection.cpp
Fixed dodgy poll()
[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 bool connection::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
270 {
271         char connect[MAXBUF];
272         
273         ircd_connector connector;
274         
275         WriteOpers("Establishing meshed link to %s:%d",servername,newport);
276
277         if (this->fd)
278         {
279                 if (connector.MakeOutboundConnection(targethost,newport))
280                 {
281                         // targethost has been turned into an ip...
282                         // we dont want this as the server name.
283                         connector.SetServerName(servername);
284                         snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
285                         connector.SetState(STATE_NOAUTH_OUTBOUND);
286                         connector.SetHostAndPort(targethost, newport);
287                         connector.SetState(STATE_CONNECTED);
288                         this->connectors.push_back(connector);
289                         return this->SendPacket(connect, servername);
290                 }
291                 else
292                 {
293                         connector.SetState(STATE_DISCONNECTED);
294                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
295                 }
296         }
297         return false;
298 }
299
300 bool connection::AddIncoming(int newfd, char* targethost, int sourceport)
301 {
302         ircd_connector connector;
303         
304         // targethost has been turned into an ip...
305         // we dont want this as the server name.
306         connector.SetServerName(targethost);
307         connector.SetDescriptor(newfd);
308         connector.SetState(STATE_NOAUTH_INBOUND);
309         int flags = fcntl(newfd, F_GETFL, 0);
310         fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
311         int sendbuf = 32768;
312         int recvbuf = 32768;
313         setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
314         setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
315         connector.SetHostAndPort(targethost, sourceport);
316         connector.SetState(STATE_NOAUTH_INBOUND);
317         log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
318         this->connectors.push_back(connector);
319         return true;
320 }
321
322 void connection::TerminateLink(char* targethost)
323 {
324         // this locates the targethost in the connection::connectors vector of the class,
325         // and terminates it by sending it an SQUIT token and closing its descriptor.
326         // TerminateLink with a null string causes a terminate of ALL links
327 }
328
329
330 // Returns a pointer to the connector for 'host'
331 ircd_connector* connection::FindHost(std::string findhost)
332 {
333         for (int i = 0; i < this->connectors.size(); i++)
334         {
335                 if (this->connectors[i].GetServerName() == findhost)
336                 {
337                         return &this->connectors[i];
338                 }
339         }
340         return NULL;
341 }
342
343 std::string ircd_connector::GetServerName()
344 {
345         return this->servername;
346 }
347
348 std::string ircd_connector::GetDescription()
349 {
350         return this->description;
351 }
352
353 void ircd_connector::SetServerName(std::string serv)
354 {
355         this->servername = serv;
356 }
357
358 void ircd_connector::SetDescription(std::string desc)
359 {
360         this->description = desc;
361 }
362
363
364 int ircd_connector::GetDescriptor()
365 {
366         return this->fd;
367 }
368
369 int ircd_connector::GetState()
370 {
371         return this->state;
372 }
373
374
375 void ircd_connector::SetState(int newstate)
376 {
377         this->state = newstate;
378         if (state == STATE_DISCONNECTED)
379         {
380                 NetSendMyRoutingTable();
381         }
382 }
383
384 void ircd_connector::CloseConnection()
385 {
386         int flags = fcntl(this->fd, F_GETFL, 0);
387         fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
388         close(this->fd);
389         flags = fcntl(this->fd, F_GETFL, 0);
390         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
391 }
392
393 void ircd_connector::SetDescriptor(int newfd)
394 {
395         this->fd = newfd;
396 }
397
398 bool connection::SendPacket(char *message, const char* sendhost)
399 {
400         if ((!message) || (!sendhost))
401                 return true;
402
403         ircd_connector* cn = this->FindHost(sendhost);
404         
405         if (!strchr(message,'\n'))
406         {
407                 strlcat(message,"\n",MAXBUF);
408         }
409
410         if (cn)
411         {
412                 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
413                 
414                 if (cn->GetState() == STATE_DISCONNECTED)
415                 {
416                         log(DEBUG,"\n\n\n\nMain route to %s is down, seeking alternative\n\n\n\n",sendhost);
417                         // fix: can only route one hop to avoid a loop
418                         if (strncmp(message,"R ",2))
419                         {
420                                 log(DEBUG,"Not a double reroute");
421                                 // this route is down, we must re-route the packet through an available point in the mesh.
422                                 for (int k = 0; k < this->connectors.size(); k++)
423                                 {
424                                         log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
425                                         // search for another point in the mesh which can 'reach' where we want to go
426                                         for (int m = 0; m < this->connectors[k].routes.size(); m++)
427                                         {
428                                                 log(DEBUG,"Check connector %d: %s route %s",k,this->connectors[k].GetServerName().c_str(),this->connectors[k].routes[m].c_str());
429                                                 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
430                                                 {
431                                                         log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
432                                                         char buffer[MAXBUF];
433                                                         snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
434                                                         this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
435                                                         return true;
436                                                 }
437                                         }
438                                 }
439                         }
440                         char buffer[MAXBUF];
441                         snprintf(buffer,MAXBUF,"& %s",sendhost);
442                         NetSendToAllExcept(sendhost,buffer);
443                         log(DEBUG,"\n\nThere are no routes to %s, we're gonna boot the server off!\n\n",sendhost);
444                         DoSplit(sendhost);
445                         return false;
446                 }
447
448                 // returns false if the packet could not be sent (e.g. target host down)
449                 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
450                 {
451                         log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
452                         log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
453                         cn->CloseConnection();
454                         cn->SetState(STATE_DISCONNECTED);
455                         // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
456                         return this->SendPacket(message,sendhost);
457                 }
458                 return true;
459         }
460 }
461
462 // receives a packet from any where there is data waiting, first come, first served
463 // fills the message and host values with the host where the data came from.
464
465 bool connection::RecvPacket(std::deque<std::string> &messages, char* recvhost)
466 {
467         char data[4096];
468         memset(data, 0, 4096);
469         for (int i = 0; i < this->connectors.size(); i++)
470         {
471                 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
472                 {
473                         // returns false if the packet could not be sent (e.g. target host down)
474                         int rcvsize = 0;
475
476                         // check if theres any data on this socket
477                         // if not, continue onwards to the next.
478                         pollfd polls;
479                         polls.fd = this->connectors[i].GetDescriptor();
480                         polls.events = POLLIN;
481                         int ret = poll(&polls,1,1);
482                         if (ret <= 0) continue;
483
484                         rcvsize = recv(this->connectors[i].GetDescriptor(),data,4096,0);
485                         data[rcvsize] = '\0';
486                         if (rcvsize == -1)
487                         {
488                                 if (errno != EAGAIN)
489                                 {
490                                         log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
491                                         log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
492                                         this->connectors[i].CloseConnection();
493                                         this->connectors[i].SetState(STATE_DISCONNECTED);
494                                 }
495                         }
496                         int pushed = 0;
497                         if (rcvsize > 0)
498                         {
499                                 this->connectors[i].AddBuffer(data);
500                                 if (this->connectors[i].BufferIsComplete())
501                                 {
502                                         while (this->connectors[i].BufferIsComplete())
503                                         {
504                                                 std::string text = this->connectors[i].GetBuffer();
505                                                 if (text != "")
506                                                 {
507                                                         messages.push_back(text.c_str());
508                                                         strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
509                                                         log(DEBUG,"main: Connection::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str()); 
510                                                 }
511                                         }
512                                         return true;
513                                 }
514                         }
515                 }
516         }
517         // nothing new yet -- message and host will be undefined
518         return false;
519 }
520
521 long connection::GenKey()
522 {
523         return (random()*time(NULL));
524 }
525