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);
182 bool serverrec::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
184 char connect[MAXBUF];
186 ircd_connector connector;
188 WriteOpers("Establishing meshed link to %s:%d",servername,newport);
192 if (connector.MakeOutboundConnection(targethost,newport))
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);
205 connector.SetState(STATE_DISCONNECTED);
206 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
212 bool serverrec::AddIncoming(int newfd, char* targethost, int sourceport)
214 ircd_connector connector;
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);
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);
234 void serverrec::TerminateLink(char* targethost)
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
241 // Returns a pointer to the connector for 'host'
242 ircd_connector* serverrec::FindHost(std::string findhost)
244 for (int i = 0; i < this->connectors.size(); i++)
246 if (this->connectors[i].GetServerName() == findhost)
248 return &this->connectors[i];
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)
259 for (int x = 0; x < 32; x++)
262 for (int i = 0; i < me[x]->connectors.size(); i++)
264 if ((me[x]->connectors[i].GetServerName() == servername) && (me[x]->connectors[i].GetState() != STATE_DISCONNECTED))
274 void serverrec::FlushWriteBuffers()
276 for (int i = 0; i < this->connectors.size(); i++)
278 // don't try and ping a NOAUTH_OUTBOUND state, its not authed yet!
279 if ((this->connectors[i].GetState() == STATE_NOAUTH_OUTBOUND) && (TIME > this->connectors[i].age+30))
281 // however if we reach this timer its connected timed out :)
282 WriteOpers("*** Connection to %s timed out",this->connectors[i].GetServerName().c_str());
283 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
284 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
285 DoSplit(this->connectors[i].GetServerName().c_str());
288 if ((this->connectors[i].GetState() == STATE_NOAUTH_INBOUND) && (TIME > this->connectors[i].age+30))
290 WriteOpers("*** Connection from %s timed out",this->connectors[i].GetServerName().c_str());
291 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
292 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
293 DoSplit(this->connectors[i].GetServerName().c_str());
296 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
298 if (!this->connectors[i].CheckPing())
300 WriteOpers("*** Lost single connection to %s: Ping timeout",this->connectors[i].GetServerName().c_str());
301 this->connectors[i].CloseConnection();
302 this->connectors[i].SetState(STATE_DISCONNECTED);
303 if (!IsRoutable(this->connectors[i].GetServerName()))
305 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
306 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
307 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
308 DoSplit(this->connectors[i].GetServerName().c_str());
310 has_been_netsplit = true;
313 if ((this->connectors[i].GetWriteError() !="") && (this->connectors[i].GetState() != STATE_DISCONNECTED))
315 // if we're here the write() caused an error, we cannot proceed
316 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",this->connectors[i].GetServerName().c_str(),this->connectors[i].GetWriteError().c_str());
317 this->connectors[i].CloseConnection();
318 this->connectors[i].SetState(STATE_DISCONNECTED);
319 if (!IsRoutable(this->connectors[i].GetServerName()))
321 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
322 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
323 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
324 DoSplit(this->connectors[i].GetServerName().c_str());
326 has_been_netsplit = true;
328 if (this->connectors[i].HasBufferedOutput())
330 if (!this->connectors[i].FlushWriteBuf())
332 // if we're here the write() caused an error, we cannot proceed
333 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",this->connectors[i].GetServerName().c_str(),this->connectors[i].GetWriteError().c_str());
334 this->connectors[i].CloseConnection();
335 this->connectors[i].SetState(STATE_DISCONNECTED);
336 if (!IsRoutable(this->connectors[i].GetServerName()))
338 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
339 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
340 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
341 DoSplit(this->connectors[i].GetServerName().c_str());
343 has_been_netsplit = true;
349 bool serverrec::SendPacket(char *message, const char* sendhost)
351 if ((!message) || (!sendhost))
354 ircd_connector* cn = this->FindHost(sendhost);
356 if (!strchr(message,'\n'))
358 strlcat(message,"\n",MAXBUF);
363 log(DEBUG,"main: serverrec::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
365 if (cn->GetState() == STATE_DISCONNECTED)
367 // fix: can only route one hop to avoid a loop
368 if (strncmp(message,"R ",2))
370 log(DEBUG,"Not a double reroute");
371 // this route is down, we must re-route the packet through an available point in the mesh.
372 for (int k = 0; k < this->connectors.size(); k++)
374 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
375 // search for another point in the mesh which can 'reach' where we want to go
376 for (int m = 0; m < this->connectors[k].routes.size(); m++)
378 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
380 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
382 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
383 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
390 snprintf(buffer,MAXBUF,"& %s",sendhost);
391 WriteOpers("*** All connections to %s lost.",sendhost);
392 NetSendToAllExcept(sendhost,buffer);
397 // returns false if the packet could not be sent (e.g. target host down)
398 if (!cn->AddWriteBuf(message))
400 // if we're here, there was an error pending, and the send cannot proceed
401 log(DEBUG,"cn->AddWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
402 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
403 cn->CloseConnection();
404 cn->SetState(STATE_DISCONNECTED);
405 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
406 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
407 return this->SendPacket(message,sendhost);
409 if (!cn->FlushWriteBuf())
411 // if we're here the write() caused an error, we cannot proceed
412 log(DEBUG,"cn->FlushWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
413 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
414 cn->CloseConnection();
415 cn->SetState(STATE_DISCONNECTED);
416 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
417 // retry the packet along a new route so either arrival OR failure are gauranteed
418 return this->SendPacket(message,sendhost);
424 bool already_have_sum(std::string sum)
426 for (int i = 0; i < xsums.size(); i++)
433 if (xsums.size() >= 128)
437 xsums.push_back(sum);
441 // receives a packet from any where there is data waiting, first come, first served
442 // fills the message and host values with the host where the data came from.
444 bool serverrec::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
446 char data[65536],buffer[MAXBUF];
447 memset(data, 0, 65536);
448 for (int i = 0; i < this->connectors.size(); i++)
450 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
452 // returns false if the packet could not be sent (e.g. target host down)
455 // check if theres any data on this socket
456 // if not, continue onwards to the next.
458 polls.fd = this->connectors[i].GetDescriptor();
459 polls.events = POLLIN;
460 int ret = poll(&polls,1,1);
461 if (ret <= 0) continue;
463 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
464 data[rcvsize] = '\0';
467 log(DEBUG,"recv() failed for serverrec::RecvPacket(): EOF");
468 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
469 this->connectors[i].CloseConnection();
470 this->connectors[i].SetState(STATE_DISCONNECTED);
471 if (!IsRoutable(this->connectors[i].GetServerName()))
473 WriteOpers("*** Server %s is no longer routable, disconnecting (EOF)",this->connectors[i].GetServerName().c_str());
474 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
475 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
476 DoSplit(this->connectors[i].GetServerName().c_str());
478 has_been_netsplit = true;
484 log(DEBUG,"recv() failed for serverrec::RecvPacket(): %s",strerror(errno));
485 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
486 this->connectors[i].CloseConnection();
487 this->connectors[i].SetState(STATE_DISCONNECTED);
488 if (!IsRoutable(this->connectors[i].GetServerName()))
490 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
491 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
492 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
493 DoSplit(this->connectors[i].GetServerName().c_str());
495 has_been_netsplit = true;
501 if (!this->connectors[i].AddBuffer(data))
503 WriteOpers("*** Read buffer for %s exceeds maximum, closing connection!",this->connectors[i].GetServerName().c_str());
504 this->connectors[i].CloseConnection();
505 this->connectors[i].SetState(STATE_DISCONNECTED);
506 if (!IsRoutable(this->connectors[i].GetServerName()))
508 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
509 snprintf(buffer,MAXBUF,"& %s",this->connectors[i].GetServerName().c_str());
510 NetSendToAllExcept(this->connectors[i].GetServerName().c_str(),buffer);
511 DoSplit(this->connectors[i].GetServerName().c_str());
513 has_been_netsplit = true;
515 if (this->connectors[i].BufferIsComplete())
517 this->connectors[i].ResetPing();
518 while (this->connectors[i].BufferIsComplete())
520 std::string text = this->connectors[i].GetBuffer();
523 if ((text[0] == ':') && (text.find(" ") != std::string::npos))
525 std::string orig = text;
526 log(DEBUG,"Original: %s",text.c_str());
527 std::string sum = text.substr(1,text.find(" ")-1);
528 text = text.substr(text.find(" ")+1,text.length());
529 std::string possible_token = text.substr(1,text.find(" ")-1);
530 if (possible_token.length() > 1)
534 log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
538 log(DEBUG,"Packet sum: '%s'",sum.c_str());
539 if ((already_have_sum(sum)) && (sum != "*"))
541 // we don't accept dupes
544 sums.push_back(sum.c_str());
547 else sums.push_back("*");
548 messages.push_back(text.c_str());
549 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
550 log(DEBUG,"serverrec::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
558 // nothing new yet -- message and host will be undefined