1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
19 #include "inspircd_config.h"
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
33 #include "inspstring.h"
34 #include "helperfuncs.h"
35 #include "connection.h"
40 extern serverrec* me[32];
42 extern bool has_been_netsplit;
44 std::deque<std::string> xsums;
46 serverrec::serverrec()
51 usercount_i = usercount = opercount = version = 0;
57 strlcpy(nickserv,"",NICKMAX);
62 serverrec::~serverrec()
66 serverrec::serverrec(char* n, long ver, bool jupe)
70 usercount_i = usercount = opercount = 0;
77 strlcpy(nickserv,"",NICKMAX);
81 bool serverrec::CreateListener(char* newhost, int p)
83 sockaddr_in host_address;
87 struct linger linger = { 0 };
91 fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
97 setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
100 setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
102 // attempt to increase socket sendq and recvq as high as its possible
103 // to get them on linux.
106 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
107 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
109 memset((void*)&host_address, 0, sizeof(host_address));
111 host_address.sin_family = AF_INET;
113 if (!strcmp(newhost,""))
115 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
119 inet_aton(newhost,&addy);
120 host_address.sin_addr = addy;
123 host_address.sin_port = htons(p);
125 if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
130 // make the socket non-blocking
131 flags = fcntl(fd, F_GETFL, 0);
132 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
136 listen(this->fd, MaxConn);
142 bool serverrec::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
144 char connect[MAXBUF];
146 ircd_connector connector;
147 ircd_connector *cn = this->FindHost(servername);
152 WriteOpers("CONNECT aborted: Server %s already exists",servername);
159 if (connector.MakeOutboundConnection(targethost,newport))
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);
174 connector.SetState(STATE_DISCONNECTED);
175 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
183 bool serverrec::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
185 char connect[MAXBUF];
187 ircd_connector connector;
189 WriteOpers("Establishing meshed link to %s:%d",servername,newport);
193 if (connector.MakeOutboundConnection(targethost,newport))
195 // targethost has been turned into an ip...
196 // we dont want this as the server name.
197 connector.SetServerName(servername);
198 snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
199 connector.SetState(STATE_COOKIE_OUTBOUND);
200 connector.SetHostAndPort(targethost, newport);
201 this->connectors.push_back(connector);
202 return this->SendPacket(connect, servername);
206 connector.SetState(STATE_DISCONNECTED);
207 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
213 bool serverrec::AddIncoming(int newfd, char* targethost, int sourceport)
215 ircd_connector connector;
217 // targethost has been turned into an ip...
218 // we dont want this as the server name.
219 connector.SetServerName(targethost);
220 connector.SetDescriptor(newfd);
221 connector.SetState(STATE_NOAUTH_INBOUND);
222 int flags = fcntl(newfd, F_GETFL, 0);
223 fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
226 setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
227 setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
228 connector.SetHostAndPort(targethost, sourceport);
229 connector.SetState(STATE_NOAUTH_INBOUND);
230 log(DEBUG,"serverrec::AddIncoming() Added connection: %s:%d",targethost,sourceport);
231 this->connectors.push_back(connector);
235 void serverrec::TerminateLink(char* targethost)
237 // this locates the targethost in the serverrec::connectors vector of the class,
238 // and terminates it by sending it an SQUIT token and closing its descriptor.
239 // TerminateLink with a null string causes a terminate of ALL links
242 // Returns a pointer to the connector for 'host'
243 ircd_connector* serverrec::FindHost(std::string findhost)
245 for (unsigned int i = 0; i < this->connectors.size(); i++)
247 if (this->connectors[i].GetServerName() == findhost)
249 return &this->connectors[i];
256 // Checks to see if we can still reach a server at all (e.g. is it in ANY routing table?)
257 bool IsRoutable(std::string servername)
260 for (int x = 0; x < 32; x++)
263 for (unsigned int i = 0; i < me[x]->connectors.size(); i++)
265 if ((me[x]->connectors[i].GetServerName() == servername) && (me[x]->connectors[i].GetState() != STATE_DISCONNECTED))
275 void serverrec::FlushWriteBuffers()
278 for (unsigned int i = 0; i < this->connectors.size(); i++)
280 // don't try and ping a NOAUTH_OUTBOUND state, its not authed yet!
281 if ((this->connectors[i].GetState() == STATE_NOAUTH_OUTBOUND) && (TIME > this->connectors[i].age+30))
283 // however if we reach this timer its connected timed out :)
284 WriteOpers("*** Connection to %s timed out",this->connectors[i].GetServerName().c_str());
285 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
286 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
287 DoSplit(this->connectors[i].GetServerName().c_str());
290 if ((this->connectors[i].GetState() == STATE_NOAUTH_INBOUND) && (TIME > this->connectors[i].age+30))
292 WriteOpers("*** Connection from %s timed out",this->connectors[i].GetServerName().c_str());
293 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
294 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
295 DoSplit(this->connectors[i].GetServerName().c_str());
298 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
300 if (!this->connectors[i].CheckPing())
302 WriteOpers("*** Lost single connection to %s: Ping timeout",this->connectors[i].GetServerName().c_str());
303 this->connectors[i].CloseConnection();
304 this->connectors[i].SetState(STATE_DISCONNECTED);
305 if (!IsRoutable(this->connectors[i].GetServerName()))
307 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
308 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
309 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
310 DoSplit(this->connectors[i].GetServerName().c_str());
312 has_been_netsplit = true;
315 if ((this->connectors[i].GetWriteError() !="") && (this->connectors[i].GetState() != STATE_DISCONNECTED))
317 // if we're here the write() caused an error, we cannot proceed
318 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",this->connectors[i].GetServerName().c_str(),this->connectors[i].GetWriteError().c_str());
319 this->connectors[i].CloseConnection();
320 this->connectors[i].SetState(STATE_DISCONNECTED);
321 if (!IsRoutable(this->connectors[i].GetServerName()))
323 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
324 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
325 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
326 DoSplit(this->connectors[i].GetServerName().c_str());
328 has_been_netsplit = true;
330 if ((this->connectors[i].HasBufferedOutput()) && (this->connectors[i].GetState() != STATE_DISCONNECTED))
332 if (!this->connectors[i].FlushWriteBuf())
334 // if we're here the write() caused an error, we cannot proceed
335 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",this->connectors[i].GetServerName().c_str(),this->connectors[i].GetWriteError().c_str());
336 this->connectors[i].CloseConnection();
337 this->connectors[i].SetState(STATE_DISCONNECTED);
338 if (!IsRoutable(this->connectors[i].GetServerName()))
340 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
341 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
342 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
343 DoSplit(this->connectors[i].GetServerName().c_str());
345 has_been_netsplit = true;
351 bool serverrec::SendPacket(char *message, const char* sendhost)
353 if ((!message) || (!sendhost))
356 ircd_connector* cn = this->FindHost(sendhost);
358 if (!strchr(message,'\n'))
360 strlcat(message,"\n",MAXBUF);
365 log(DEBUG,"main: serverrec::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
367 if (cn->GetState() == STATE_DISCONNECTED)
369 // fix: can only route one hop to avoid a loop
370 if (strncmp(message,"R ",2))
372 log(DEBUG,"Not a double reroute");
373 // this route is down, we must re-route the packet through an available point in the mesh.
374 for (unsigned int k = 0; k < this->connectors.size(); k++)
376 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
377 // search for another point in the mesh which can 'reach' where we want to go
378 for (unsigned int m = 0; m < this->connectors[k].routes.size(); m++)
380 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
382 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
384 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
385 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
392 snprintf(buffer,MAXBUF,"& %s",sendhost);
393 WriteOpers("*** All connections to %s lost.",sendhost);
394 NetSendToAllExcept(sendhost,buffer);
399 // returns false if the packet could not be sent (e.g. target host down)
400 if (!cn->AddWriteBuf(message))
402 // if we're here, there was an error pending, and the send cannot proceed
403 log(DEBUG,"cn->AddWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
404 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
405 cn->CloseConnection();
406 cn->SetState(STATE_DISCONNECTED);
407 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
408 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
409 return this->SendPacket(message,sendhost);
411 if (!cn->FlushWriteBuf())
413 // if we're here the write() caused an error, we cannot proceed
414 log(DEBUG,"cn->FlushWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
415 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
416 cn->CloseConnection();
417 cn->SetState(STATE_DISCONNECTED);
418 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
419 // retry the packet along a new route so either arrival OR failure are gauranteed
420 return this->SendPacket(message,sendhost);
427 bool already_have_sum(std::string sum)
429 for (unsigned int i = 0; i < xsums.size(); i++)
436 if (xsums.size() >= 128)
440 xsums.push_back(sum);
444 // receives a packet from any where there is data waiting, first come, first served
445 // fills the message and host values with the host where the data came from.
447 bool serverrec::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
449 char data[65536],buffer[MAXBUF];
450 memset(data, 0, 65536);
451 for (unsigned int i = 0; i < this->connectors.size(); i++)
453 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
455 // returns false if the packet could not be sent (e.g. target host down)
458 // check if theres any data on this socket
459 // if not, continue onwards to the next.
461 polls.fd = this->connectors[i].GetDescriptor();
462 polls.events = POLLIN;
463 int ret = poll(&polls,1,1);
464 if (ret <= 0) continue;
466 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
467 data[rcvsize] = '\0';
470 log(DEBUG,"recv() failed for serverrec::RecvPacket(): EOF");
471 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
472 this->connectors[i].CloseConnection();
473 this->connectors[i].SetState(STATE_DISCONNECTED);
474 if (!IsRoutable(this->connectors[i].GetServerName()))
476 WriteOpers("*** Server %s is no longer routable, disconnecting (EOF)",this->connectors[i].GetServerName().c_str());
477 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
478 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
479 DoSplit(this->connectors[i].GetServerName().c_str());
481 has_been_netsplit = true;
487 log(DEBUG,"recv() failed for serverrec::RecvPacket(): %s",strerror(errno));
488 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
489 this->connectors[i].CloseConnection();
490 this->connectors[i].SetState(STATE_DISCONNECTED);
491 if (!IsRoutable(this->connectors[i].GetServerName()))
493 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
494 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
495 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
496 DoSplit(this->connectors[i].GetServerName().c_str());
498 has_been_netsplit = true;
504 if (!this->connectors[i].AddBuffer(data))
506 WriteOpers("*** Read buffer for %s exceeds maximum, closing connection!",this->connectors[i].GetServerName().c_str());
507 this->connectors[i].CloseConnection();
508 this->connectors[i].SetState(STATE_DISCONNECTED);
509 if (!IsRoutable(this->connectors[i].GetServerName()))
511 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
512 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
513 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
514 DoSplit(this->connectors[i].GetServerName().c_str());
516 has_been_netsplit = true;
518 if (this->connectors[i].BufferIsComplete())
520 this->connectors[i].ResetPing();
521 while (this->connectors[i].BufferIsComplete())
523 std::string text = this->connectors[i].GetBuffer();
526 if ((text[0] == ':') && (text.find(" ") != std::string::npos))
528 std::string orig = text;
529 log(DEBUG,"Original: %s",text.c_str());
530 std::string sum = text.substr(1,text.find(" ")-1);
531 text = text.substr(text.find(" ")+1,text.length());
532 std::string possible_token = text.substr(1,text.find(" ")-1);
533 if (possible_token.length() > 1)
537 log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
541 log(DEBUG,"Packet sum: '%s'",sum.c_str());
542 if ((already_have_sum(sum)) && (sum != "*"))
544 // we don't accept dupes
547 sums.push_back(sum.c_str());
550 else sums.push_back("*");
551 messages.push_back(text.c_str());
552 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
553 log(DEBUG,"serverrec::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
561 // nothing new yet -- message and host will be undefined