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 <connection.h>
23 #include <sys/errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/utsname.h>
32 #include "inspstring.h"
33 #include "helperfuncs.h"
36 extern std::vector<Module*> modules;
37 extern std::vector<ircd_module*> factory;
39 std::deque<std::string> xsums;
47 * The InspIRCd mesh network is maintained by a tree of objects which reference *themselves*.
48 * Every local server has an array of 32 *serverrecs, known as me[]. Each of these represents
49 * a local listening port, and is not null if the user has opened a listening port on the server.
50 * It is assumed nobody will ever want to open more than 32 listening server ports at any one
51 * time (i mean come on, why would you want more, the ircd works fine with ONE).
52 * Each me[] entry has multiple classes within it of type ircd_connector. These are stored in a vector
53 * and each represents a server linked via this socket. If the connection was created outbound,
54 * the connection is bound to the default ip address by using me[defaultRoute] (defaultRoute being
55 * a global variable which indicates the default server to make connections on). If the connection
56 * was created inbound, it is attached to the port the connection came in on. There may be as many
57 * ircd_connector objects as needed in each me[] entry. Each ircd_connector implements the specifics
58 * of an ircd connection in the mesh, however each ircd may have multiple ircd_connector connections
59 * to it, to maintain the mesh link.
62 char* xsumtable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
64 // creates a random id for a line for detection of duplicate messages
65 std::string CreateSum()
70 for(int q = 1; q < 8; q++)
71 sum[q] = xsumtable[rand()%52];
75 connection::connection()
81 bool connection::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,SOMAXCONN);
141 char* ircd_connector::GetServerIP()
146 int ircd_connector::GetServerPort()
151 bool ircd_connector::SetHostAndPort(char* newhost, int newport)
153 strncpy(this->host,newhost,160);
154 this->port = newport;
158 bool ircd_connector::SetHostAddress(char* newhost, int newport)
160 strncpy(this->host,newhost,160);
161 this->port = newport;
162 memset((void*)&addr, 0, sizeof(addr));
163 addr.sin_family = AF_INET;
164 inet_aton(host,&addr.sin_addr);
165 addr.sin_port = htons(port);
169 void ircd_connector::SetServerPort(int p)
174 void ircd_connector::AddBuffer(std::string a)
177 for (int i = 0; i < a.length(); i++)
181 std::stringstream stream(ircdbuffer);
183 log(DEBUG,"AddBuffer: %s",b.c_str());
184 ircdbuffer = stream.str();
187 bool ircd_connector::BufferIsComplete()
189 for (int i = 0; i < ircdbuffer.length(); i++)
190 if (ircdbuffer[i] == '\n')
195 void ircd_connector::ClearBuffer()
200 std::string ircd_connector::GetBuffer()
202 // Fix by Brain 28th Apr 2005
203 // seems my stringstream code isnt liked by linux
204 // EVEN THOUGH IT IS CORRECT! Fixed by using a different
205 // (SLOWER) algorithm...
206 char* line = (char*)ircdbuffer.c_str();
207 std::string ret = "";
208 while ((*line != '\n') && (strlen(line)))
213 if ((*line == '\n') || (*line == '\r'))
219 bool ircd_connector::MakeOutboundConnection(char* newhost, int newport)
221 log(DEBUG,"MakeOutboundConnection: Original param: %s",newhost);
223 hostent* hoste = gethostbyname(newhost);
226 log(DEBUG,"MakeOutboundConnection: gethostbyname was NULL, setting %s",newhost);
227 this->SetHostAddress(newhost,newport);
228 SetHostAndPort(newhost,newport);
232 struct in_addr* ia = (in_addr*)hoste->h_addr;
233 log(DEBUG,"MakeOutboundConnection: gethostbyname was valid, setting %s",inet_ntoa(*ia));
234 this->SetHostAddress(inet_ntoa(*ia),newport);
235 SetHostAndPort(inet_ntoa(*ia),newport);
238 this->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
241 if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)))
243 WriteOpers("connect() failed for %s",host);
244 RemoveServer(this->servername.c_str());
247 int flags = fcntl(this->fd, F_GETFL, 0);
248 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
251 setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
252 setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
257 WriteOpers("socket() failed!");
258 RemoveServer(this->servername.c_str());
265 bool connection::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
267 char connect[MAXBUF];
269 ircd_connector connector;
270 ircd_connector *cn = this->FindHost(servername);
275 WriteOpers("CONNECT aborted: Server %s already exists",servername);
282 if (connector.MakeOutboundConnection(targethost,newport))
284 // targethost has been turned into an ip...
285 // we dont want this as the server name.
286 connector.SetServerName(servername);
287 snprintf(connect,MAXBUF,"S %s %s %lu %lu :%s",getservername().c_str(),password,(unsigned long)myport,(unsigned long)GetRevision(),getserverdesc().c_str());
288 connector.SetState(STATE_NOAUTH_OUTBOUND);
289 connector.SetHostAndPort(targethost, newport);
290 this->connectors.push_back(connector);
291 return this->SendPacket(connect, servername);
295 connector.SetState(STATE_DISCONNECTED);
296 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
302 void ircd_connector::SetVersionString(std::string newversion)
304 log(DEBUG,"Set version of %s to %s",this->servername.c_str(),newversion.c_str());
305 this->version = newversion;
308 std::string ircd_connector::GetVersionString()
310 return this->version;
313 bool connection::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
315 char connect[MAXBUF];
317 ircd_connector connector;
319 WriteOpers("Establishing meshed link to %s:%d",servername,newport);
323 if (connector.MakeOutboundConnection(targethost,newport))
325 // targethost has been turned into an ip...
326 // we dont want this as the server name.
327 connector.SetServerName(servername);
328 snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
329 connector.SetState(STATE_NOAUTH_OUTBOUND);
330 connector.SetHostAndPort(targethost, newport);
331 connector.SetState(STATE_CONNECTED);
332 this->connectors.push_back(connector);
333 return this->SendPacket(connect, servername);
337 connector.SetState(STATE_DISCONNECTED);
338 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
344 bool connection::AddIncoming(int newfd, char* targethost, int sourceport)
346 ircd_connector connector;
348 // targethost has been turned into an ip...
349 // we dont want this as the server name.
350 connector.SetServerName(targethost);
351 connector.SetDescriptor(newfd);
352 connector.SetState(STATE_NOAUTH_INBOUND);
353 int flags = fcntl(newfd, F_GETFL, 0);
354 fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
357 setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
358 setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
359 connector.SetHostAndPort(targethost, sourceport);
360 connector.SetState(STATE_NOAUTH_INBOUND);
361 log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
362 this->connectors.push_back(connector);
366 void connection::TerminateLink(char* targethost)
368 // this locates the targethost in the connection::connectors vector of the class,
369 // and terminates it by sending it an SQUIT token and closing its descriptor.
370 // TerminateLink with a null string causes a terminate of ALL links
374 // Returns a pointer to the connector for 'host'
375 ircd_connector* connection::FindHost(std::string findhost)
377 for (int i = 0; i < this->connectors.size(); i++)
379 if (this->connectors[i].GetServerName() == findhost)
381 return &this->connectors[i];
387 std::string ircd_connector::GetServerName()
389 return this->servername;
392 std::string ircd_connector::GetDescription()
394 return this->description;
397 void ircd_connector::SetServerName(std::string serv)
399 this->servername = serv;
402 void ircd_connector::SetDescription(std::string desc)
404 this->description = desc;
408 int ircd_connector::GetDescriptor()
413 int ircd_connector::GetState()
419 void ircd_connector::SetState(int newstate)
421 this->state = newstate;
422 if (state == STATE_DISCONNECTED)
424 NetSendMyRoutingTable();
428 void ircd_connector::CloseConnection()
430 int flags = fcntl(this->fd, F_GETFL, 0);
431 fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
433 flags = fcntl(this->fd, F_GETFL, 0);
434 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
437 void ircd_connector::SetDescriptor(int newfd)
442 bool connection::SendPacket(char *message, const char* sendhost)
444 if ((!message) || (!sendhost))
447 ircd_connector* cn = this->FindHost(sendhost);
449 if (!strchr(message,'\n'))
451 strlcat(message,"\n",MAXBUF);
456 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
458 if (cn->GetState() == STATE_DISCONNECTED)
460 log(DEBUG,"\n\n\n\nMain route to %s is down, seeking alternative\n\n\n\n",sendhost);
461 // fix: can only route one hop to avoid a loop
462 if (strncmp(message,"R ",2))
464 log(DEBUG,"Not a double reroute");
465 // this route is down, we must re-route the packet through an available point in the mesh.
466 for (int k = 0; k < this->connectors.size(); k++)
468 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
469 // search for another point in the mesh which can 'reach' where we want to go
470 for (int m = 0; m < this->connectors[k].routes.size(); m++)
472 log(DEBUG,"Check connector %d: %s route %s",k,this->connectors[k].GetServerName().c_str(),this->connectors[k].routes[m].c_str());
473 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
475 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
477 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
478 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
485 snprintf(buffer,MAXBUF,"& %s",sendhost);
486 NetSendToAllExcept(sendhost,buffer);
487 log(DEBUG,"\n\nThere are no routes to %s, we're gonna boot the server off!\n\n",sendhost);
492 // returns false if the packet could not be sent (e.g. target host down)
493 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
495 log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
496 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
497 cn->CloseConnection();
498 cn->SetState(STATE_DISCONNECTED);
499 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
500 return this->SendPacket(message,sendhost);
506 bool already_have_sum(std::string sum)
508 for (int i = 0; i < xsums.size(); i++)
515 if (xsums.size() >= 128)
519 xsums.push_back(sum);
523 // receives a packet from any where there is data waiting, first come, first served
524 // fills the message and host values with the host where the data came from.
526 bool connection::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
529 memset(data, 0, 65536);
530 for (int i = 0; i < this->connectors.size(); i++)
532 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
534 // returns false if the packet could not be sent (e.g. target host down)
537 // check if theres any data on this socket
538 // if not, continue onwards to the next.
540 polls.fd = this->connectors[i].GetDescriptor();
541 polls.events = POLLIN;
542 int ret = poll(&polls,1,1);
543 if (ret <= 0) continue;
545 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
546 data[rcvsize] = '\0';
551 log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
552 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
553 this->connectors[i].CloseConnection();
554 this->connectors[i].SetState(STATE_DISCONNECTED);
560 this->connectors[i].AddBuffer(data);
561 if (this->connectors[i].BufferIsComplete())
563 while (this->connectors[i].BufferIsComplete())
565 std::string text = this->connectors[i].GetBuffer();
568 if ((text[0] == ':') && (text.find(" ") != std::string::npos))
570 std::string orig = text;
571 log(DEBUG,"Original: %s",text.c_str());
572 std::string sum = text.substr(1,text.find(" ")-1);
573 text = text.substr(text.find(" ")+1,text.length());
574 std::string possible_token = text.substr(1,text.find(" ")-1);
575 if (possible_token.length() > 1)
579 log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
583 log(DEBUG,"Packet sum: '%s'",sum.c_str());
584 if ((already_have_sum(sum)) && (sum != "*"))
586 // we don't accept dupes
587 log(DEBUG,"Duplicate packet sum %s from server %s dropped",sum.c_str(),this->connectors[i].GetServerName().c_str());
590 sums.push_back(sum.c_str());
593 else sums.push_back("*");
594 messages.push_back(text.c_str());
595 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
596 log(DEBUG,"Connection::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
604 // nothing new yet -- message and host will be undefined