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;
44 * The InspIRCd mesh network is maintained by a tree of objects which reference *themselves*.
45 * Every local server has an array of 32 *serverrecs, known as me[]. Each of these represents
46 * a local listening port, and is not null if the user has opened a listening port on the server.
47 * It is assumed nobody will ever want to open more than 32 listening server ports at any one
48 * time (i mean come on, why would you want more, the ircd works fine with ONE).
49 * Each me[] entry has multiple classes within it of type ircd_connector. These are stored in a vector
50 * and each represents a server linked via this socket. If the connection was created outbound,
51 * the connection is bound to the default ip address by using me[defaultRoute] (defaultRoute being
52 * a global variable which indicates the default server to make connections on). If the connection
53 * was created inbound, it is attached to the port the connection came in on. There may be as many
54 * ircd_connector objects as needed in each me[] entry. Each ircd_connector implements the specifics
55 * of an ircd connection in the mesh, however each ircd may have multiple ircd_connector connections
56 * to it, to maintain the mesh link.
59 connection::connection()
65 bool connection::CreateListener(char* newhost, int p)
67 sockaddr_in host_address;
71 struct linger linger = { 0 };
75 fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
81 setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
84 setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
86 // attempt to increase socket sendq and recvq as high as its possible
87 // to get them on linux.
90 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
91 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
93 memset((void*)&host_address, 0, sizeof(host_address));
95 host_address.sin_family = AF_INET;
97 if (!strcmp(newhost,""))
99 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
103 inet_aton(newhost,&addy);
104 host_address.sin_addr = addy;
107 host_address.sin_port = htons(p);
109 if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
114 // make the socket non-blocking
115 flags = fcntl(fd, F_GETFL, 0);
116 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
125 char* ircd_connector::GetServerIP()
130 int ircd_connector::GetServerPort()
135 bool ircd_connector::SetHostAndPort(char* newhost, int newport)
137 strncpy(this->host,newhost,160);
138 this->port = newport;
142 bool ircd_connector::SetHostAddress(char* newhost, int newport)
144 strncpy(this->host,newhost,160);
145 this->port = newport;
146 memset((void*)&addr, 0, sizeof(addr));
147 addr.sin_family = AF_INET;
148 inet_aton(host,&addr.sin_addr);
149 addr.sin_port = htons(port);
153 void ircd_connector::SetServerPort(int p)
158 void ircd_connector::AddBuffer(std::string a)
161 for (int i = 0; i < a.length(); i++)
165 std::stringstream stream(ircdbuffer);
167 log(DEBUG,"AddBuffer: %s",b.c_str());
168 ircdbuffer = stream.str();
171 bool ircd_connector::BufferIsComplete()
173 for (int i = 0; i < ircdbuffer.length(); i++)
174 if (ircdbuffer[i] == '\n')
179 void ircd_connector::ClearBuffer()
184 std::string ircd_connector::GetBuffer()
186 // Fix by Brain 28th Apr 2005
187 // seems my stringstream code isnt liked by linux
188 // EVEN THOUGH IT IS CORRECT! Fixed by using a different
189 // (SLOWER) algorithm...
190 char* line = (char*)ircdbuffer.c_str();
191 std::string ret = "";
192 while ((*line != '\n') && (strlen(line)))
197 if ((*line == '\n') || (*line == '\r'))
203 bool ircd_connector::MakeOutboundConnection(char* newhost, int newport)
205 log(DEBUG,"MakeOutboundConnection: Original param: %s",newhost);
207 hostent* hoste = gethostbyname(newhost);
210 log(DEBUG,"MakeOutboundConnection: gethostbyname was NULL, setting %s",newhost);
211 this->SetHostAddress(newhost,newport);
212 SetHostAndPort(newhost,newport);
216 struct in_addr* ia = (in_addr*)hoste->h_addr;
217 log(DEBUG,"MakeOutboundConnection: gethostbyname was valid, setting %s",inet_ntoa(*ia));
218 this->SetHostAddress(inet_ntoa(*ia),newport);
219 SetHostAndPort(inet_ntoa(*ia),newport);
222 this->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
225 if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)))
227 WriteOpers("connect() failed for %s",host);
228 RemoveServer(this->servername.c_str());
231 int flags = fcntl(this->fd, F_GETFL, 0);
232 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
235 setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
236 setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
241 WriteOpers("socket() failed!");
242 RemoveServer(this->servername.c_str());
249 bool connection::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
251 char connect[MAXBUF];
253 ircd_connector connector;
254 ircd_connector *cn = this->FindHost(servername);
259 WriteOpers("CONNECT aborted: Server %s already exists",servername);
266 if (connector.MakeOutboundConnection(targethost,newport))
268 // targethost has been turned into an ip...
269 // we dont want this as the server name.
270 connector.SetServerName(servername);
271 snprintf(connect,MAXBUF,"S %s %s %lu %lu :%s",getservername().c_str(),password,(unsigned long)myport,(unsigned long)GetRevision(),getserverdesc().c_str());
272 connector.SetState(STATE_NOAUTH_OUTBOUND);
273 connector.SetHostAndPort(targethost, newport);
274 this->connectors.push_back(connector);
275 return this->SendPacket(connect, servername);
279 connector.SetState(STATE_DISCONNECTED);
280 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
286 void ircd_connector::SetVersionString(std::string newversion)
288 log(DEBUG,"Set version of %s to %s",this->servername.c_str(),newversion.c_str());
289 this->version = newversion;
292 std::string ircd_connector::GetVersionString()
294 return this->version;
297 bool connection::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
299 char connect[MAXBUF];
301 ircd_connector connector;
303 WriteOpers("Establishing meshed link to %s:%d",servername,newport);
307 if (connector.MakeOutboundConnection(targethost,newport))
309 // targethost has been turned into an ip...
310 // we dont want this as the server name.
311 connector.SetServerName(servername);
312 snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
313 connector.SetState(STATE_NOAUTH_OUTBOUND);
314 connector.SetHostAndPort(targethost, newport);
315 connector.SetState(STATE_CONNECTED);
316 this->connectors.push_back(connector);
317 return this->SendPacket(connect, servername);
321 connector.SetState(STATE_DISCONNECTED);
322 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
328 bool connection::AddIncoming(int newfd, char* targethost, int sourceport)
330 ircd_connector connector;
332 // targethost has been turned into an ip...
333 // we dont want this as the server name.
334 connector.SetServerName(targethost);
335 connector.SetDescriptor(newfd);
336 connector.SetState(STATE_NOAUTH_INBOUND);
337 int flags = fcntl(newfd, F_GETFL, 0);
338 fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
341 setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
342 setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
343 connector.SetHostAndPort(targethost, sourceport);
344 connector.SetState(STATE_NOAUTH_INBOUND);
345 log(DEBUG,"connection::AddIncoming() Added connection: %s:%d",targethost,sourceport);
346 this->connectors.push_back(connector);
350 void connection::TerminateLink(char* targethost)
352 // this locates the targethost in the connection::connectors vector of the class,
353 // and terminates it by sending it an SQUIT token and closing its descriptor.
354 // TerminateLink with a null string causes a terminate of ALL links
358 // Returns a pointer to the connector for 'host'
359 ircd_connector* connection::FindHost(std::string findhost)
361 for (int i = 0; i < this->connectors.size(); i++)
363 if (this->connectors[i].GetServerName() == findhost)
365 return &this->connectors[i];
371 std::string ircd_connector::GetServerName()
373 return this->servername;
376 std::string ircd_connector::GetDescription()
378 return this->description;
381 void ircd_connector::SetServerName(std::string serv)
383 this->servername = serv;
386 void ircd_connector::SetDescription(std::string desc)
388 this->description = desc;
392 int ircd_connector::GetDescriptor()
397 int ircd_connector::GetState()
403 void ircd_connector::SetState(int newstate)
405 this->state = newstate;
406 if (state == STATE_DISCONNECTED)
408 NetSendMyRoutingTable();
412 void ircd_connector::CloseConnection()
414 int flags = fcntl(this->fd, F_GETFL, 0);
415 fcntl(this->fd, F_SETFL, flags ^ O_NONBLOCK);
417 flags = fcntl(this->fd, F_GETFL, 0);
418 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
421 void ircd_connector::SetDescriptor(int newfd)
426 bool connection::SendPacket(char *message, const char* sendhost)
428 if ((!message) || (!sendhost))
431 ircd_connector* cn = this->FindHost(sendhost);
433 if (!strchr(message,'\n'))
435 strlcat(message,"\n",MAXBUF);
440 log(DEBUG,"main: Connection::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
442 if (cn->GetState() == STATE_DISCONNECTED)
444 log(DEBUG,"\n\n\n\nMain route to %s is down, seeking alternative\n\n\n\n",sendhost);
445 // fix: can only route one hop to avoid a loop
446 if (strncmp(message,"R ",2))
448 log(DEBUG,"Not a double reroute");
449 // this route is down, we must re-route the packet through an available point in the mesh.
450 for (int k = 0; k < this->connectors.size(); k++)
452 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
453 // search for another point in the mesh which can 'reach' where we want to go
454 for (int m = 0; m < this->connectors[k].routes.size(); m++)
456 log(DEBUG,"Check connector %d: %s route %s",k,this->connectors[k].GetServerName().c_str(),this->connectors[k].routes[m].c_str());
457 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
459 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
461 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
462 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
469 snprintf(buffer,MAXBUF,"& %s",sendhost);
470 NetSendToAllExcept(sendhost,buffer);
471 log(DEBUG,"\n\nThere are no routes to %s, we're gonna boot the server off!\n\n",sendhost);
476 // returns false if the packet could not be sent (e.g. target host down)
477 if (send(cn->GetDescriptor(),message,strlen(message),0)<0)
479 log(DEBUG,"send() failed for Connection::SendPacket(): %s",strerror(errno));
480 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
481 cn->CloseConnection();
482 cn->SetState(STATE_DISCONNECTED);
483 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
484 return this->SendPacket(message,sendhost);
490 // receives a packet from any where there is data waiting, first come, first served
491 // fills the message and host values with the host where the data came from.
493 bool connection::RecvPacket(std::deque<std::string> &messages, char* recvhost)
496 memset(data, 0, 65536);
497 for (int i = 0; i < this->connectors.size(); i++)
499 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
501 // returns false if the packet could not be sent (e.g. target host down)
504 // check if theres any data on this socket
505 // if not, continue onwards to the next.
507 polls.fd = this->connectors[i].GetDescriptor();
508 polls.events = POLLIN;
509 int ret = poll(&polls,1,1);
510 if (ret <= 0) continue;
512 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
513 data[rcvsize] = '\0';
518 log(DEBUG,"recv() failed for Connection::RecvPacket(): %s",strerror(errno));
519 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
520 this->connectors[i].CloseConnection();
521 this->connectors[i].SetState(STATE_DISCONNECTED);
527 this->connectors[i].AddBuffer(data);
528 if (this->connectors[i].BufferIsComplete())
530 while (this->connectors[i].BufferIsComplete())
532 std::string text = this->connectors[i].GetBuffer();
535 messages.push_back(text.c_str());
536 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
537 log(DEBUG,"main: Connection::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
545 // nothing new yet -- message and host will be undefined