]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/connection.cpp
Missing debug symbols?!
[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         ircdbuffer = stream.str();
151 }
152
153 bool ircd_connector::BufferIsComplete()
154 {
155         for (int i = 0; i < ircdbuffer.length(); i++)
156                 if (ircdbuffer[i] == '\n')
157                         return true;
158         return false;
159 }
160
161 void ircd_connector::ClearBuffer()
162 {
163         ircdbuffer = "";
164 }
165
166 std::string ircd_connector::GetBuffer()
167 {
168         char* line = (char*)ircdbuffer.c_str();
169         char ret[MAXBUF];
170         std::stringstream* stream = new std::stringstream(std::stringstream::in | std::stringstream::out);
171         *stream << ircdbuffer;
172         stream->getline(ret,MAXBUF);
173         while ((*line != '\n') && (strlen(line)))
174                 line++;
175         if ((*line == '\n') || (*line == '\r'))
176                 line++;
177         ircdbuffer = line;
178         delete stream;
179         return ret;
180 }
181
182 bool ircd_connector::MakeOutboundConnection(char* newhost, int newport)
183 {
184         log(DEBUG,"MakeOutboundConnection: Original param: %s",newhost);
185         ClearBuffer();
186         hostent* hoste = gethostbyname(newhost);
187         if (!hoste)
188         {
189                 log(DEBUG,"MakeOutboundConnection: gethostbyname was NULL, setting %s",newhost);
190                 this->SetHostAddress(newhost,newport);
191                 SetHostAndPort(newhost,newport);
192         }
193         else
194         {
195                 struct in_addr* ia = (in_addr*)hoste->h_addr;
196                 log(DEBUG,"MakeOutboundConnection: gethostbyname was valid, setting %s",inet_ntoa(*ia));
197                 this->SetHostAddress(inet_ntoa(*ia),newport);
198                 SetHostAndPort(inet_ntoa(*ia),newport);
199         }
200
201         this->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
202         if (this->fd >= 0)
203         {
204                 if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)))
205                 {
206                         WriteOpers("connect() failed for %s",host);
207                         RemoveServer(this->servername.c_str());
208                         return false;
209                 }
210                 int flags = fcntl(this->fd, F_GETFL, 0);
211                 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
212                 int sendbuf = 32768;
213                 int recvbuf = 32768;
214                 setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
215                 setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
216                 return true;
217         }
218         else
219         {
220                 WriteOpers("socket() failed!");
221                 RemoveServer(this->servername.c_str());
222         }
223
224         return false;
225 }
226
227
228 bool connection::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
229 {
230         char connect[MAXBUF];
231         
232         ircd_connector connector;
233         ircd_connector *cn = this->FindHost(servername);
234
235
236         if (cn)
237         {
238                 WriteOpers("CONNECT aborted: Server %s already exists",servername);
239                 return false;
240         }
241
242         
243         if (this->fd)
244         {
245                 if (connector.MakeOutboundConnection(targethost,newport))
246                 {
247                         // targethost has been turned into an ip...
248                         // we dont want this as the server name.
249                         connector.SetServerName(servername);
250                         snprintf(connect,MAXBUF,"S %s %s %lu %lu :%s",getservername().c_str(),password,(unsigned long)myport,(unsigned long)GetRevision(),getserverdesc().c_str());
251                         connector.SetState(STATE_NOAUTH_OUTBOUND);
252                         connector.SetHostAndPort(targethost, newport);
253                         this->connectors.push_back(connector);
254                         return this->SendPacket(connect, servername);
255                 }
256                 else
257                 {
258                         connector.SetState(STATE_DISCONNECTED);
259                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
260                 }
261         }
262         return false;
263 }
264
265 bool connection::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
266 {
267         char connect[MAXBUF];
268         
269         ircd_connector connector;
270         
271         WriteOpers("Establishing meshed link to %s:%d",servername,newport);
272
273         if (this->fd)
274         {
275                 if (connector.MakeOutboundConnection(targethost,newport))
276                 {
277                         // targethost has been turned into an ip...
278                         // we dont want this as the server name.
279                         connector.SetServerName(servername);
280                         snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
281                         connector.SetState(STATE_NOAUTH_OUTBOUND);
282                         connector.SetHostAndPort(targethost, newport);
283                         connector.SetState(STATE_CONNECTED);
284                         this->connectors.push_back(connector);
285                         return this->SendPacket(connect, servername);
286                 }
287                 else
288                 {
289                         connector.SetState(STATE_DISCONNECTED);
290                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
291                 }
292         }
293         return false;
294 }
295
296 bool connection::AddIncoming(int newfd, char* targethost, int sourceport)
297 {
298         ircd_connector connector;
299         
300         // targethost has been turned into an ip...
301         // we dont want this as the server name.
302         connector.SetServerName(targethost);
303         connector.SetDescriptor(newfd);
304         connector.SetState(STATE_NOAUTH_INBOUND);
305         int flags = fcntl(newfd, F_GETFL, 0);
306         fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
307         int sendbuf = 32768;
308         int recvbuf = 32768;
309         setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf)); 
310         setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
311         connector.SetHostAndPort(targethost, sourceport);
312         connector.SetState(STATE_NOAUTH_INBOUND);
313         log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
314         this->connectors.push_back(connector);
315         return true;
316 }
317
318 void connection::TerminateLink(char* targethost)
319 {
320         // this locates the targethost in the connection::connectors vector of the class,
321         // and terminates it by sending it an SQUIT token and closing its descriptor.
322         // TerminateLink with a null string causes a terminate of ALL links
323 }
324
325
326 // Returns a pointer to the connector for 'host'
327 ircd_connector* connection::FindHost(std::string findhost)
328 {
329         for (int i = 0; i < this->connectors.size(); i++)
330         {
331                 if (this->connectors[i].GetServerName() == findhost)
332                 {
333                         return &this->connectors[i];
334                 }
335         }
336         return NULL;
337 }
338
339 std::string ircd_connector::GetServerName()
340 {
341         return this->servername;
342 }
343
344 std::string ircd_connector::GetDescription()
345 {
346         return this->description;
347 }
348
349 void ircd_connector::SetServerName(std::string serv)
350 {
351         this->servername = serv;
352 }
353
354 void ircd_connector::SetDescription(std::string desc)
355 {
356         this->description = desc;
357 }
358
359
360 int ircd_connector::GetDescriptor()
361 {
362         return this->fd;
363 }
364
365 int ircd_connector::GetState()
366 {
367         return this->state;
368 }
369
370
371 void ircd_connector::SetState(int newstate)
372 {
373         this->state = newstate;
374         if (state == STATE_DISCONNECTED)
375         {
376                 NetSendMyRoutingTable();
377         }
378 }
379
380 void ircd_connector::CloseConnection()
381 {
382         int flags = fcntl(this->fd, F_GETFL, 0);
383         fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
384         close(this->fd);
385         flags = fcntl(this->fd, F_GETFL, 0);
386         fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
387 }
388
389 void ircd_connector::SetDescriptor(int newfd)
390 {
391         this->fd = newfd;
392 }
393
394 bool connection::SendPacket(char *message, const char* sendhost)
395 {
396         if ((!message) || (!sendhost))
397                 return true;
398
399         ircd_connector* cn = this->FindHost(sendhost);
400         
401         if (!strchr(message,'\n'))
402         {
403                 strlcat(message,"\n",MAXBUF);
404         }
405
406         if (cn)
407         {
408                 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
409                 
410                 if (cn->GetState() == STATE_DISCONNECTED)
411                 {
412                         log(DEBUG,"Main route to %s is down, seeking alternative",host);
413                         // fix: can only route one hop to avoid a loop
414                         if (!strncmp(message,"R ",2))
415                         {
416                                 // this route is down, we must re-route the packet through an available point in the mesh.
417                                 for (int k = 0; k < this->connectors.size(); k++)
418                                 {
419                                         // search for another point in the mesh which can 'reach' where we want to go
420                                         for (int m = 0; m < this->connectors[k].routes.size(); m++)
421                                         {
422                                                 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
423                                                 {
424                                                         log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
425                                                         char buffer[MAXBUF];
426                                                         snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
427                                                         this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
428                                                         return true;
429                                                 }
430                                         }
431                                 }
432                         }
433                         char buffer[MAXBUF];
434                         snprintf(buffer,MAXBUF,"& %s",sendhost);
435                         NetSendToAllExcept(sendhost,buffer);
436                         log(DEBUG,"There are no routes to %s, we're gonna boot the server off!",sendhost);
437                         DoSplit(sendhost);
438                         return false;
439                 }
440
441                 // returns false if the packet could not be sent (e.g. target host down)
442                 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
443                 {
444                         log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
445                         log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
446                         cn->CloseConnection();
447                         cn->SetState(STATE_DISCONNECTED);
448                         // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
449                         return this->SendPacket(message,sendhost);
450                 }
451                 return true;
452         }
453 }
454
455 // receives a packet from any where there is data waiting, first come, first served
456 // fills the message and host values with the host where the data came from.
457
458 bool connection::RecvPacket(std::deque<std::string> &messages, char* recvhost)
459 {
460         char data[4096];
461         memset(data, 0, 4096);
462         for (int i = 0; i < this->connectors.size(); i++)
463         {
464                 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
465                 {
466                         // returns false if the packet could not be sent (e.g. target host down)
467                         int rcvsize = 0;
468                         rcvsize = recv(this->connectors[i].GetDescriptor(),data,4096,0);
469                         data[rcvsize] = '\0';
470                         if (rcvsize == -1)
471                         {
472                                 if (errno != EAGAIN)
473                                 {
474                                         log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
475                                         log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
476                                         this->connectors[i].CloseConnection();
477                                         this->connectors[i].SetState(STATE_DISCONNECTED);
478                                 }
479                         }
480                         int pushed = 0;
481                         if (rcvsize > 0)
482                         {
483                                 this->connectors[i].AddBuffer(data);
484                                 if (this->connectors[i].BufferIsComplete())
485                                 {
486                                         while (this->connectors[i].BufferIsComplete())
487                                         {
488                                                 std::string text = this->connectors[i].GetBuffer();
489                                                 messages.push_back(text.c_str());
490                                                 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
491                                                 log(DEBUG,"main: Connection::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str()); 
492                                         }
493                                         return true;
494                                 }
495                         }
496                 }
497         }
498         // nothing new yet -- message and host will be undefined
499         return false;
500 }
501
502 long connection::GenKey()
503 {
504         return (random()*time(NULL));
505 }
506