]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/servers.cpp
Fixed fd_Setsize in cygwin
[user/henk/code/inspircd.git] / src / servers.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 using namespace std;
18
19 #include "inspircd_config.h" 
20 #include "servers.h"
21 #include "inspircd.h"
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <poll.h>
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
28 #include <vector>
29 #include <string>
30 #include <deque>
31 #include <sstream>
32 #include <map>
33 #include "inspstring.h"
34 #include "helperfuncs.h"
35 #include "connection.h"
36
37 extern time_t TIME;
38 extern int MaxConn;
39
40 extern serverrec* me[32];
41
42 extern bool has_been_netsplit;
43
44 std::deque<std::string> xsums;
45
46 serverrec::serverrec()
47 {
48         strlcpy(name,"",256);
49         pingtime = 0;
50         lastping = TIME;
51         usercount_i = usercount = opercount = version = 0;
52         hops_away = 1;
53         signon = TIME;
54         jupiter = false;
55         fd = 0;
56         sync_soon = false;
57         strlcpy(nickserv,"",NICKMAX);
58         connectors.clear();
59 }
60
61  
62 serverrec::~serverrec()
63 {
64 }
65
66 serverrec::serverrec(char* n, long ver, bool jupe)
67 {
68         strlcpy(name,n,256);
69         lastping = TIME;
70         usercount_i = usercount = opercount = 0;
71         version = ver;
72         hops_away = 1;
73         signon = TIME;
74         jupiter = jupe;
75         fd = 0;
76         sync_soon = false;
77         strlcpy(nickserv,"",NICKMAX);
78         connectors.clear();
79 }
80
81 bool serverrec::CreateListener(char* newhost, int p)
82 {
83         sockaddr_in host_address;
84         int flags;
85         in_addr addy;
86         int on = 0;
87         struct linger linger = { 0 };
88
89         this->port = p;
90
91         fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
92         if (fd <= 0)
93         {
94                 return false;
95         }
96
97         setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
98         linger.l_onoff = 1;
99         linger.l_linger = 1;
100         setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
101
102         // attempt to increase socket sendq and recvq as high as its possible
103         // to get them on linux.
104         int sendbuf = 32768;
105         int recvbuf = 32768;
106         setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
107         setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
108
109         memset((void*)&host_address, 0, sizeof(host_address));
110
111         host_address.sin_family = AF_INET;
112
113         if (!strcmp(newhost,""))
114         {
115                 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
116         }
117         else
118         {
119                 inet_aton(newhost,&addy);
120                 host_address.sin_addr = addy;
121         }
122
123         host_address.sin_port = htons(p);
124
125         if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
126         {
127                 return false;
128         }
129
130         // make the socket non-blocking
131         flags = fcntl(fd, F_GETFL, 0);
132         fcntl(fd, F_SETFL, flags | O_NONBLOCK);
133
134         this->port = p;
135
136         listen(this->fd, MaxConn);
137
138         return true;
139 }
140
141
142 bool serverrec::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
143 {
144         char connect[MAXBUF];
145
146         ircd_connector connector;
147         ircd_connector *cn = this->FindHost(servername);
148
149
150         if (cn)
151         {
152                 WriteOpers("CONNECT aborted: Server %s already exists",servername);
153                 return false;
154         }
155
156
157         if (this->fd)
158         {
159                 if (connector.MakeOutboundConnection(targethost,newport))
160                 {
161                         // targethost has been turned into an ip...
162                         // we dont want this as the server name.
163                         connector.SetServerName(servername);
164                         snprintf(connect,MAXBUF,"S %s %s %lu %s :%s",getservername().c_str(),password,(unsigned long)myport,GetRevision().c_str(),getserverdesc().c_str());
165                         connector.SetState(STATE_NOAUTH_OUTBOUND);
166                         connector.SetHostAndPort(targethost, newport);
167                         this->connectors.push_back(connector);
168                         // this packet isn't actually sent until the socket connects -- the STATE_NOAUTH_OUTBOUND state
169                         // queues outbound data until the socket is polled as writeable (e.g. the connection is established)
170                         return this->SendPacket(connect, servername);
171                 }
172                 else
173                 {
174                         connector.SetState(STATE_DISCONNECTED);
175                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
176                 }
177         }
178         return false;
179 }
180
181
182 bool serverrec::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
183 {
184         char connect[MAXBUF];
185
186         ircd_connector connector;
187
188         WriteOpers("Establishing meshed link to %s:%d",servername,newport);
189
190         if (this->fd)
191         {
192                 if (connector.MakeOutboundConnection(targethost,newport))
193                 {
194                         // targethost has been turned into an ip...
195                         // we dont want this as the server name.
196                         connector.SetServerName(servername);
197                         snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
198                         connector.SetState(STATE_NOAUTH_OUTBOUND);
199                         connector.SetHostAndPort(targethost, newport);
200                         this->connectors.push_back(connector);
201                         return this->SendPacket(connect, servername);
202                 }
203                 else
204                 {
205                         connector.SetState(STATE_DISCONNECTED);
206                         WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
207                 }
208         }
209         return false;
210 }
211
212 bool serverrec::AddIncoming(int newfd, char* targethost, int sourceport)
213 {
214         ircd_connector connector;
215
216         // targethost has been turned into an ip...
217         // we dont want this as the server name.
218         connector.SetServerName(targethost);
219         connector.SetDescriptor(newfd);
220         connector.SetState(STATE_NOAUTH_INBOUND);
221         int flags = fcntl(newfd, F_GETFL, 0);
222         fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
223         int sendbuf = 32768;
224         int recvbuf = 32768;
225         setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
226         setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
227         connector.SetHostAndPort(targethost, sourceport);
228         connector.SetState(STATE_NOAUTH_INBOUND);
229         log(DEBUG,"serverrec::AddIncoming() Added connection: %s:%d",targethost,sourceport);
230         this->connectors.push_back(connector);
231         return true;
232 }
233
234 void serverrec::TerminateLink(char* targethost)
235 {
236         // this locates the targethost in the serverrec::connectors vector of the class,
237        // and terminates it by sending it an SQUIT token and closing its descriptor.
238         // TerminateLink with a null string causes a terminate of ALL links
239 }
240
241 // Returns a pointer to the connector for 'host'
242 ircd_connector* serverrec::FindHost(std::string findhost)
243 {
244         for (int i = 0; i < this->connectors.size(); i++)
245         {
246                 if (this->connectors[i].GetServerName() == findhost)
247                 {
248                         return &this->connectors[i];
249                 }
250         }
251         return NULL;
252 }
253
254
255 // Checks to see if we can still reach a server at all (e.g. is it in ANY routing table?)
256 bool IsRoutable(std::string servername)
257 {
258         for (int x = 0; x < 32; x++) if (me[x])
259         {
260                 ircd_connector* cn = me[x]->FindHost(servername.c_str());
261                 if (cn)
262                 {
263                         if (cn->GetState() == STATE_DISCONNECTED)
264                         {
265                                 for (int k = 0; k < me[x]->connectors.size(); k++)
266                                 {
267                                         for (int m = 0; m < me[x]->connectors[k].routes.size(); m++)
268                                         {
269                                                 if (!strcasecmp(me[x]->connectors[k].routes[m].c_str(),servername.c_str()))
270                                                 {
271                                                         return true;
272                                                 }
273                                         }
274                                 }
275                                 return false;
276                         }
277                         else return true;
278                 }
279         }
280         return false;
281 }
282
283
284 void serverrec::FlushWriteBuffers()
285 {
286         for (int i = 0; i < this->connectors.size(); i++)
287         {
288                 // don't try and ping a NOAUTH_OUTBOUND state, its not authed yet!
289                 if ((this->connectors[i].GetState() == STATE_NOAUTH_OUTBOUND) && (TIME > this->connectors[i].age+30))
290                 {
291                         // however if we reach this timer its connected timed out :)
292                         WriteOpers("*** Connection to %s timed out",this->connectors[i].GetServerName().c_str());
293                         DoSplit(this->connectors[i].GetServerName().c_str());
294                         return;
295                 }
296                 else if ((this->connectors[i].GetState() == STATE_NOAUTH_INBOUND) && (TIME > this->connectors[i].age+30))
297                 {
298                         WriteOpers("*** Connection from %s timed out",this->connectors[i].GetServerName().c_str());
299                         DoSplit(this->connectors[i].GetServerName().c_str());
300                         return;
301                 }
302                 else if (this->connectors[i].GetState() != STATE_DISCONNECTED)
303                 {
304                         if (!this->connectors[i].CheckPing())
305                         {
306                                 WriteOpers("*** Lost single connection to %s: Ping timeout",this->connectors[i].GetServerName().c_str());
307                                 this->connectors[i].CloseConnection();
308                                 this->connectors[i].SetState(STATE_DISCONNECTED);
309                                 if (!IsRoutable(this->connectors[i].GetServerName()))
310                                 {
311                                         WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
312                                         DoSplit(this->connectors[i].GetServerName().c_str());
313                                 }
314                                 has_been_netsplit = true;
315                         }
316                 }
317                 if (this->connectors[i].HasBufferedOutput())
318                 {
319                         if (!this->connectors[i].FlushWriteBuf())
320                         {
321                                 // if we're here the write() caused an error, we cannot proceed
322                                 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",this->connectors[i].GetServerName().c_str(),this->connectors[i].GetWriteError().c_str());
323                                 this->connectors[i].CloseConnection();
324                                 this->connectors[i].SetState(STATE_DISCONNECTED);
325                                 if (!IsRoutable(this->connectors[i].GetServerName()))
326                                 {
327                                         WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
328                                         DoSplit(this->connectors[i].GetServerName().c_str());
329                                 }
330                                 has_been_netsplit = true;
331                         }
332                 }
333         }
334 }
335
336 bool serverrec::SendPacket(char *message, const char* sendhost)
337 {
338         if ((!message) || (!sendhost))
339                 return true;
340
341         ircd_connector* cn = this->FindHost(sendhost);
342
343         if (!strchr(message,'\n'))
344         {
345                 strlcat(message,"\n",MAXBUF);
346         }
347
348         if (cn)
349         {
350                 log(DEBUG,"main: serverrec::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
351
352                 if (cn->GetState() == STATE_DISCONNECTED)
353                 {
354                         // fix: can only route one hop to avoid a loop
355                         if (strncmp(message,"R ",2))
356                         {
357                                 log(DEBUG,"Not a double reroute");
358                                 // this route is down, we must re-route the packet through an available point in the mesh.
359                                 for (int k = 0; k < this->connectors.size(); k++)
360                                 {
361                                         log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
362                                         // search for another point in the mesh which can 'reach' where we want to go
363                                         for (int m = 0; m < this->connectors[k].routes.size(); m++)
364                                         {
365                                                 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
366                                                 {
367                                                         log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
368                                                         char buffer[MAXBUF];
369                                                         snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
370                                                         this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
371                                                         return true;
372                                                 }
373                                         }
374                                 }
375                         }
376                         char buffer[MAXBUF];
377                         snprintf(buffer,MAXBUF,"& %s",sendhost);
378                         WriteOpers("*** All connections to %s lost.",sendhost);
379                         NetSendToAllExcept(sendhost,buffer);
380                         DoSplit(sendhost);
381                         return false;
382                 }
383
384                 // returns false if the packet could not be sent (e.g. target host down)
385                 if (!cn->AddWriteBuf(message))
386                 {
387                         // if we're here, there was an error pending, and the send cannot proceed
388                         log(DEBUG,"cn->AddWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
389                         log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
390                         cn->CloseConnection();
391                         cn->SetState(STATE_DISCONNECTED);
392                         WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
393                         // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
394                         return this->SendPacket(message,sendhost);
395                 }
396                 if (!cn->FlushWriteBuf())
397                 {
398                         // if we're here the write() caused an error, we cannot proceed
399                         log(DEBUG,"cn->FlushWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
400                         log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
401                         cn->CloseConnection();
402                         cn->SetState(STATE_DISCONNECTED);
403                         WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
404                         // retry the packet along a new route so either arrival OR failure are gauranteed
405                         return this->SendPacket(message,sendhost);
406                 }
407                 return true;
408         }
409 }
410
411 bool already_have_sum(std::string sum)
412 {
413         for (int i = 0; i < xsums.size(); i++)
414         {
415                 if (xsums[i] == sum)
416                 {
417                         return true;
418                 }
419         }
420         if (xsums.size() >= 128)
421         {
422                 xsums.pop_front();
423         }
424         xsums.push_back(sum);
425         return false;
426 }
427
428 // receives a packet from any where there is data waiting, first come, first served
429 // fills the message and host values with the host where the data came from.
430
431 bool serverrec::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
432 {
433         char data[65536];
434         memset(data, 0, 65536);
435         for (int i = 0; i < this->connectors.size(); i++)
436         {
437                 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
438                 {
439                         // returns false if the packet could not be sent (e.g. target host down)
440                         int rcvsize = 0;
441
442                         // check if theres any data on this socket
443                         // if not, continue onwards to the next.
444                         pollfd polls;
445                         polls.fd = this->connectors[i].GetDescriptor();
446                         polls.events = POLLIN;
447                         int ret = poll(&polls,1,1);
448                         if (ret <= 0) continue;
449
450                         rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
451                         data[rcvsize] = '\0';
452                         if (rcvsize == -1)
453                         {
454                                 if (errno != EAGAIN)
455                                 {
456                                         log(DEBUG,"recv() failed for serverrec::RecvPacket(): %s",strerror(errno));
457                                         log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
458                                         this->connectors[i].CloseConnection();
459                                         this->connectors[i].SetState(STATE_DISCONNECTED);
460                                         if (!IsRoutable(this->connectors[i].GetServerName()))
461                                         {
462                                                 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
463                                                 DoSplit(this->connectors[i].GetServerName().c_str());
464                                         }
465                                         has_been_netsplit = true;
466                                 }
467                         }
468                         int pushed = 0;
469                         if (rcvsize > 0)
470                         {
471                                 if (!this->connectors[i].AddBuffer(data))
472                                 {
473                                         WriteOpers("*** Read buffer for %s exceeds maximum, closing connection!",this->connectors[i].GetServerName().c_str());
474                                         this->connectors[i].CloseConnection();
475                                         this->connectors[i].SetState(STATE_DISCONNECTED);
476                                         if (!IsRoutable(this->connectors[i].GetServerName()))
477                                         {
478                                                 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
479                                                 DoSplit(this->connectors[i].GetServerName().c_str());
480                                         }
481                                         has_been_netsplit = true;
482                                 }
483                                 if (this->connectors[i].BufferIsComplete())
484                                 {
485                                         this->connectors[i].ResetPing();
486                                         while (this->connectors[i].BufferIsComplete())
487                                         {
488                                                 std::string text = this->connectors[i].GetBuffer();
489                                                 if (text != "")
490                                                 {
491                                                         if ((text[0] == ':') && (text.find(" ") != std::string::npos))
492                                                         {
493                                                                 std::string orig = text;
494                                                                 log(DEBUG,"Original: %s",text.c_str());
495                                                                 std::string sum = text.substr(1,text.find(" ")-1);
496                                                                 text = text.substr(text.find(" ")+1,text.length());
497                                                                 std::string possible_token = text.substr(1,text.find(" ")-1);
498                                                                 if (possible_token.length() > 1)
499                                                                 {
500                                                                         sums.push_back("*");
501                                                                         text = orig;
502                                                                         log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
503                                                                 }
504                                                                 else
505                                                                 {
506                                                                         log(DEBUG,"Packet sum: '%s'",sum.c_str());
507                                                                         if ((already_have_sum(sum)) && (sum != "*"))
508                                                                         {
509                                                                                 // we don't accept dupes
510                                                                                 continue;
511                                                                         }
512                                                                         sums.push_back(sum.c_str());
513                                                                 }
514                                                         }
515                                                         else sums.push_back("*");
516                                                         messages.push_back(text.c_str());
517                                                         strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
518                                                         log(DEBUG,"serverrec::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
519                                                 }
520                                         }
521                                         return true;
522                                 }
523                         }
524                 }
525         }
526         // nothing new yet -- message and host will be undefined
527         return false;
528 }
529