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