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