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 * ---------------------------------------------------
17 #include <connection.h>
21 #include <sys/errno.h>
22 #include <sys/ioctl.h>
23 #include <sys/utsname.h>
30 #include "inspstring.h"
35 extern std::vector<Module*> modules;
36 extern std::vector<ircd_module*> factory;
38 std::deque<std::string> xsums;
46 * The InspIRCd mesh network is maintained by a tree of objects which reference *themselves*.
47 * Every local server has an array of 32 *serverrecs, known as me[]. Each of these represents
48 * a local listening port, and is not null if the user has opened a listening port on the server.
49 * It is assumed nobody will ever want to open more than 32 listening server ports at any one
50 * time (i mean come on, why would you want more, the ircd works fine with ONE).
51 * Each me[] entry has multiple classes within it of type ircd_connector. These are stored in a vector
52 * and each represents a server linked via this socket. If the connection was created outbound,
53 * the connection is bound to the default ip address by using me[defaultRoute] (defaultRoute being
54 * a global variable which indicates the default server to make connections on). If the connection
55 * was created inbound, it is attached to the port the connection came in on. There may be as many
56 * ircd_connector objects as needed in each me[] entry. Each ircd_connector implements the specifics
57 * of an ircd connection in the mesh, however each ircd may have multiple ircd_connector connections
58 * to it, to maintain the mesh link.
61 char* xsumtable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
63 // creates a random id for a line for detection of duplicate messages
64 std::string CreateSum()
69 for(int q = 1; q < 8; q++)
70 sum[q] = xsumtable[rand()%52];
74 connection::connection()
80 bool connection::CreateListener(char* newhost, int p)
82 sockaddr_in host_address;
86 struct linger linger = { 0 };
90 fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
96 setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
99 setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
101 // attempt to increase socket sendq and recvq as high as its possible
102 // to get them on linux.
105 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
106 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
108 memset((void*)&host_address, 0, sizeof(host_address));
110 host_address.sin_family = AF_INET;
112 if (!strcmp(newhost,""))
114 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
118 inet_aton(newhost,&addy);
119 host_address.sin_addr = addy;
122 host_address.sin_port = htons(p);
124 if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
129 // make the socket non-blocking
130 flags = fcntl(fd, F_GETFL, 0);
131 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
140 char* ircd_connector::GetServerIP()
145 int ircd_connector::GetServerPort()
150 bool ircd_connector::SetHostAndPort(char* newhost, int newport)
152 strncpy(this->host,newhost,160);
153 this->port = newport;
157 bool ircd_connector::SetHostAddress(char* newhost, int newport)
159 strncpy(this->host,newhost,160);
160 this->port = newport;
161 memset((void*)&addr, 0, sizeof(addr));
162 addr.sin_family = AF_INET;
163 inet_aton(host,&addr.sin_addr);
164 addr.sin_port = htons(port);
168 void ircd_connector::SetServerPort(int p)
173 void ircd_connector::AddBuffer(std::string a)
176 for (int i = 0; i < a.length(); i++)
180 std::stringstream stream(ircdbuffer);
182 log(DEBUG,"AddBuffer: %s",b.c_str());
183 ircdbuffer = stream.str();
186 bool ircd_connector::BufferIsComplete()
188 for (int i = 0; i < ircdbuffer.length(); i++)
189 if (ircdbuffer[i] == '\n')
194 void ircd_connector::ClearBuffer()
199 std::string ircd_connector::GetBuffer()
201 // Fix by Brain 28th Apr 2005
202 // seems my stringstream code isnt liked by linux
203 // EVEN THOUGH IT IS CORRECT! Fixed by using a different
204 // (SLOWER) algorithm...
205 char* line = (char*)ircdbuffer.c_str();
206 std::string ret = "";
207 while ((*line != '\n') && (strlen(line)))
212 if ((*line == '\n') || (*line == '\r'))
218 bool ircd_connector::MakeOutboundConnection(char* newhost, int newport)
220 log(DEBUG,"MakeOutboundConnection: Original param: %s",newhost);
222 hostent* hoste = gethostbyname(newhost);
225 log(DEBUG,"MakeOutboundConnection: gethostbyname was NULL, setting %s",newhost);
226 this->SetHostAddress(newhost,newport);
227 SetHostAndPort(newhost,newport);
231 struct in_addr* ia = (in_addr*)hoste->h_addr;
232 log(DEBUG,"MakeOutboundConnection: gethostbyname was valid, setting %s",inet_ntoa(*ia));
233 this->SetHostAddress(inet_ntoa(*ia),newport);
234 SetHostAndPort(inet_ntoa(*ia),newport);
237 this->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
240 if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)))
242 WriteOpers("connect() failed for %s",host);
243 RemoveServer(this->servername.c_str());
246 int flags = fcntl(this->fd, F_GETFL, 0);
247 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
250 setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
251 setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
256 WriteOpers("socket() failed!");
257 RemoveServer(this->servername.c_str());
264 bool connection::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
266 char connect[MAXBUF];
268 ircd_connector connector;
269 ircd_connector *cn = this->FindHost(servername);
274 WriteOpers("CONNECT aborted: Server %s already exists",servername);
281 if (connector.MakeOutboundConnection(targethost,newport))
283 // targethost has been turned into an ip...
284 // we dont want this as the server name.
285 connector.SetServerName(servername);
286 snprintf(connect,MAXBUF,"S %s %s %lu %lu :%s",getservername().c_str(),password,(unsigned long)myport,(unsigned long)GetRevision(),getserverdesc().c_str());
287 connector.SetState(STATE_NOAUTH_OUTBOUND);
288 connector.SetHostAndPort(targethost, newport);
289 this->connectors.push_back(connector);
290 return this->SendPacket(connect, servername);
294 connector.SetState(STATE_DISCONNECTED);
295 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
301 void ircd_connector::SetVersionString(std::string newversion)
303 log(DEBUG,"Set version of %s to %s",this->servername.c_str(),newversion.c_str());
304 this->version = newversion;
307 std::string ircd_connector::GetVersionString()
309 return this->version;
312 bool connection::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
314 char connect[MAXBUF];
316 ircd_connector connector;
318 WriteOpers("Establishing meshed link to %s:%d",servername,newport);
322 if (connector.MakeOutboundConnection(targethost,newport))
324 // targethost has been turned into an ip...
325 // we dont want this as the server name.
326 connector.SetServerName(servername);
327 snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
328 connector.SetState(STATE_NOAUTH_OUTBOUND);
329 connector.SetHostAndPort(targethost, newport);
330 connector.SetState(STATE_CONNECTED);
331 this->connectors.push_back(connector);
332 return this->SendPacket(connect, servername);
336 connector.SetState(STATE_DISCONNECTED);
337 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
343 bool connection::AddIncoming(int newfd, char* targethost, int sourceport)
345 ircd_connector connector;
347 // targethost has been turned into an ip...
348 // we dont want this as the server name.
349 connector.SetServerName(targethost);
350 connector.SetDescriptor(newfd);
351 connector.SetState(STATE_NOAUTH_INBOUND);
352 int flags = fcntl(newfd, F_GETFL, 0);
353 fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
356 setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
357 setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
358 connector.SetHostAndPort(targethost, sourceport);
359 connector.SetState(STATE_NOAUTH_INBOUND);
360 log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
361 this->connectors.push_back(connector);
365 void connection::TerminateLink(char* targethost)
367 // this locates the targethost in the connection::connectors vector of the class,
368 // and terminates it by sending it an SQUIT token and closing its descriptor.
369 // TerminateLink with a null string causes a terminate of ALL links
373 // Returns a pointer to the connector for 'host'
374 ircd_connector* connection::FindHost(std::string findhost)
376 for (int i = 0; i < this->connectors.size(); i++)
378 if (this->connectors[i].GetServerName() == findhost)
380 return &this->connectors[i];
386 std::string ircd_connector::GetServerName()
388 return this->servername;
391 std::string ircd_connector::GetDescription()
393 return this->description;
396 void ircd_connector::SetServerName(std::string serv)
398 this->servername = serv;
401 void ircd_connector::SetDescription(std::string desc)
403 this->description = desc;
407 int ircd_connector::GetDescriptor()
412 int ircd_connector::GetState()
418 void ircd_connector::SetState(int newstate)
420 this->state = newstate;
421 if (state == STATE_DISCONNECTED)
423 NetSendMyRoutingTable();
427 void ircd_connector::CloseConnection()
429 int flags = fcntl(this->fd, F_GETFL, 0);
430 fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
432 flags = fcntl(this->fd, F_GETFL, 0);
433 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
436 void ircd_connector::SetDescriptor(int newfd)
441 bool connection::SendPacket(char *message, const char* sendhost)
443 if ((!message) || (!sendhost))
446 ircd_connector* cn = this->FindHost(sendhost);
448 if (!strchr(message,'\n'))
450 strlcat(message,"\n",MAXBUF);
455 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
457 if (cn->GetState() == STATE_DISCONNECTED)
459 log(DEBUG,"\n\n\n\nMain route to %s is down, seeking alternative\n\n\n\n",sendhost);
460 // fix: can only route one hop to avoid a loop
461 if (strncmp(message,"R ",2))
463 log(DEBUG,"Not a double reroute");
464 // this route is down, we must re-route the packet through an available point in the mesh.
465 for (int k = 0; k < this->connectors.size(); k++)
467 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
468 // search for another point in the mesh which can 'reach' where we want to go
469 for (int m = 0; m < this->connectors[k].routes.size(); m++)
471 log(DEBUG,"Check connector %d: %s route %s",k,this->connectors[k].GetServerName().c_str(),this->connectors[k].routes[m].c_str());
472 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
474 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
476 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
477 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
484 snprintf(buffer,MAXBUF,"& %s",sendhost);
485 NetSendToAllExcept(sendhost,buffer);
486 log(DEBUG,"\n\nThere are no routes to %s, we're gonna boot the server off!\n\n",sendhost);
491 // returns false if the packet could not be sent (e.g. target host down)
492 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
494 log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
495 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
496 cn->CloseConnection();
497 cn->SetState(STATE_DISCONNECTED);
498 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
499 return this->SendPacket(message,sendhost);
505 bool already_have_sum(std::string sum)
507 for (int i = 0; i < xsums.size(); i++)
514 if (xsums.size() >= 128)
518 xsums.push_back(sum);
522 // receives a packet from any where there is data waiting, first come, first served
523 // fills the message and host values with the host where the data came from.
525 bool connection::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
528 memset(data, 0, 65536);
529 for (int i = 0; i < this->connectors.size(); i++)
531 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
533 // returns false if the packet could not be sent (e.g. target host down)
536 // check if theres any data on this socket
537 // if not, continue onwards to the next.
539 polls.fd = this->connectors[i].GetDescriptor();
540 polls.events = POLLIN;
541 int ret = poll(&polls,1,1);
542 if (ret <= 0) continue;
544 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
545 data[rcvsize] = '\0';
550 log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
551 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
552 this->connectors[i].CloseConnection();
553 this->connectors[i].SetState(STATE_DISCONNECTED);
559 this->connectors[i].AddBuffer(data);
560 if (this->connectors[i].BufferIsComplete())
562 while (this->connectors[i].BufferIsComplete())
564 std::string text = this->connectors[i].GetBuffer();
567 if ((text[0] == ':') && (text.find(" ") != std::string::npos))
569 std::string orig = text;
570 log(DEBUG,"Original: %s",text.c_str());
571 std::string sum = text.substr(1,text.find(" ")-1);
572 text = text.substr(text.find(" ")+1,text.length());
573 std::string possible_token = text.substr(1,text.find(" ")-1);
574 if (possible_token.length() > 1)
578 log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
582 log(DEBUG,"Packet sum: '%s'",sum.c_str());
583 if ((already_have_sum(sum)) && (sum != "*"))
585 // we don't accept dupes
586 log(DEBUG,"Duplicate packet sum %s from server %s dropped",sum.c_str(),this->connectors[i].GetServerName().c_str());
589 sums.push_back(sum.c_str());
592 else sums.push_back("*");
593 messages.push_back(text.c_str());
594 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
595 log(DEBUG,"Connection::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
603 // nothing new yet -- message and host will be undefined