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"
39 extern serverrec* me[32];
41 std::deque<std::string> xsums;
43 serverrec::serverrec()
48 usercount_i = usercount = opercount = version = 0;
54 strlcpy(nickserv,"",NICKMAX);
59 serverrec::~serverrec()
63 serverrec::serverrec(char* n, long ver, bool jupe)
67 usercount_i = usercount = opercount = 0;
74 strlcpy(nickserv,"",NICKMAX);
78 bool serverrec::CreateListener(char* newhost, int p)
80 sockaddr_in host_address;
84 struct linger linger = { 0 };
88 fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
94 setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
97 setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
99 // attempt to increase socket sendq and recvq as high as its possible
100 // to get them on linux.
103 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
104 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
106 memset((void*)&host_address, 0, sizeof(host_address));
108 host_address.sin_family = AF_INET;
110 if (!strcmp(newhost,""))
112 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
116 inet_aton(newhost,&addy);
117 host_address.sin_addr = addy;
120 host_address.sin_port = htons(p);
122 if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
127 // make the socket non-blocking
128 flags = fcntl(fd, F_GETFL, 0);
129 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
133 listen(this->fd, MaxConn);
139 bool serverrec::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
141 char connect[MAXBUF];
143 ircd_connector connector;
144 ircd_connector *cn = this->FindHost(servername);
149 WriteOpers("CONNECT aborted: Server %s already exists",servername);
156 if (connector.MakeOutboundConnection(targethost,newport))
158 // targethost has been turned into an ip...
159 // we dont want this as the server name.
160 connector.SetServerName(servername);
161 snprintf(connect,MAXBUF,"S %s %s %lu %s :%s",getservername().c_str(),password,(unsigned long)myport,GetRevision().c_str(),getserverdesc().c_str());
162 connector.SetState(STATE_NOAUTH_OUTBOUND);
163 connector.SetHostAndPort(targethost, newport);
164 this->connectors.push_back(connector);
165 // this packet isn't actually sent until the socket connects -- the STATE_NOAUTH_OUTBOUND state
166 // queues outbound data until the socket is polled as writeable (e.g. the connection is established)
167 return this->SendPacket(connect, servername);
171 connector.SetState(STATE_DISCONNECTED);
172 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
179 bool serverrec::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
181 char connect[MAXBUF];
183 ircd_connector connector;
185 WriteOpers("Establishing meshed link to %s:%d",servername,newport);
189 if (connector.MakeOutboundConnection(targethost,newport))
191 // targethost has been turned into an ip...
192 // we dont want this as the server name.
193 connector.SetServerName(servername);
194 snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
195 connector.SetState(STATE_NOAUTH_OUTBOUND);
196 connector.SetHostAndPort(targethost, newport);
197 this->connectors.push_back(connector);
198 return this->SendPacket(connect, servername);
202 connector.SetState(STATE_DISCONNECTED);
203 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
209 bool serverrec::AddIncoming(int newfd, char* targethost, int sourceport)
211 ircd_connector connector;
213 // targethost has been turned into an ip...
214 // we dont want this as the server name.
215 connector.SetServerName(targethost);
216 connector.SetDescriptor(newfd);
217 connector.SetState(STATE_NOAUTH_INBOUND);
218 int flags = fcntl(newfd, F_GETFL, 0);
219 fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
222 setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
223 setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
224 connector.SetHostAndPort(targethost, sourceport);
225 connector.SetState(STATE_NOAUTH_INBOUND);
226 log(DEBUG,"serverrec::AddIncoming() Added connection: %s:%d",targethost,sourceport);
227 this->connectors.push_back(connector);
231 void serverrec::TerminateLink(char* targethost)
233 // this locates the targethost in the serverrec::connectors vector of the class,
234 // and terminates it by sending it an SQUIT token and closing its descriptor.
235 // TerminateLink with a null string causes a terminate of ALL links
238 // Returns a pointer to the connector for 'host'
239 ircd_connector* serverrec::FindHost(std::string findhost)
241 for (int i = 0; i < this->connectors.size(); i++)
243 if (this->connectors[i].GetServerName() == findhost)
245 return &this->connectors[i];
252 // Checks to see if we can still reach a server at all (e.g. is it in ANY routing table?)
253 bool IsRoutable(std::string servername)
255 for (int x = 0; x < 32; x++) if (me[x])
257 ircd_connector* cn = me[x]->FindHost(servername.c_str());
260 if (cn->GetState() == STATE_DISCONNECTED)
262 for (int k = 0; k < me[x]->connectors.size(); k++)
264 for (int m = 0; m < me[x]->connectors[k].routes.size(); m++)
266 if (!strcasecmp(me[x]->connectors[k].routes[m].c_str(),servername.c_str()))
281 void serverrec::FlushWriteBuffers()
283 for (int i = 0; i < this->connectors.size(); i++)
285 // don't try and ping a NOAUTH_OUTBOUND state, its not authed yet!
286 if ((this->connectors[i].GetState() == STATE_NOAUTH_OUTBOUND) && (TIME > this->connectors[i].age+30))
288 // however if we reach this timer its connected timed out :)
289 WriteOpers("*** Connection to %s timed out",this->connectors[i].GetServerName().c_str());
290 DoSplit(this->connectors[i].GetServerName().c_str());
293 else if ((this->connectors[i].GetState() == STATE_NOAUTH_INBOUND) && (TIME > this->connectors[i].age+30))
295 WriteOpers("*** Connection from %s timed out",this->connectors[i].GetServerName().c_str());
296 DoSplit(this->connectors[i].GetServerName().c_str());
299 else if (this->connectors[i].GetState() != STATE_DISCONNECTED)
301 if (!this->connectors[i].CheckPing())
303 WriteOpers("*** Lost single connection to %s: Ping timeout",this->connectors[i].GetServerName().c_str());
304 this->connectors[i].CloseConnection();
305 this->connectors[i].SetState(STATE_DISCONNECTED);
306 if (!IsRoutable(this->connectors[i].GetServerName()))
308 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
309 DoSplit(this->connectors[i].GetServerName().c_str());
313 if (this->connectors[i].HasBufferedOutput())
315 if (!this->connectors[i].FlushWriteBuf())
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 DoSplit(this->connectors[i].GetServerName().c_str());
331 bool serverrec::SendPacket(char *message, const char* sendhost)
333 if ((!message) || (!sendhost))
336 ircd_connector* cn = this->FindHost(sendhost);
338 if (!strchr(message,'\n'))
340 strlcat(message,"\n",MAXBUF);
345 log(DEBUG,"main: serverrec::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
347 if (cn->GetState() == STATE_DISCONNECTED)
349 // fix: can only route one hop to avoid a loop
350 if (strncmp(message,"R ",2))
352 log(DEBUG,"Not a double reroute");
353 // this route is down, we must re-route the packet through an available point in the mesh.
354 for (int k = 0; k < this->connectors.size(); k++)
356 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
357 // search for another point in the mesh which can 'reach' where we want to go
358 for (int m = 0; m < this->connectors[k].routes.size(); m++)
360 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
362 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
364 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
365 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
372 snprintf(buffer,MAXBUF,"& %s",sendhost);
373 WriteOpers("*** All connections to %s lost.",sendhost);
374 NetSendToAllExcept(sendhost,buffer);
379 // returns false if the packet could not be sent (e.g. target host down)
380 if (!cn->AddWriteBuf(message))
382 // if we're here, there was an error pending, and the send cannot proceed
383 log(DEBUG,"cn->AddWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
384 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
385 cn->CloseConnection();
386 cn->SetState(STATE_DISCONNECTED);
387 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
388 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
389 return this->SendPacket(message,sendhost);
391 if (!cn->FlushWriteBuf())
393 // if we're here the write() caused an error, we cannot proceed
394 log(DEBUG,"cn->FlushWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
395 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
396 cn->CloseConnection();
397 cn->SetState(STATE_DISCONNECTED);
398 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
399 // retry the packet along a new route so either arrival OR failure are gauranteed
400 return this->SendPacket(message,sendhost);
406 bool already_have_sum(std::string sum)
408 for (int i = 0; i < xsums.size(); i++)
415 if (xsums.size() >= 128)
419 xsums.push_back(sum);
423 // receives a packet from any where there is data waiting, first come, first served
424 // fills the message and host values with the host where the data came from.
426 bool serverrec::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
429 memset(data, 0, 65536);
430 for (int i = 0; i < this->connectors.size(); i++)
432 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
434 // returns false if the packet could not be sent (e.g. target host down)
437 // check if theres any data on this socket
438 // if not, continue onwards to the next.
440 polls.fd = this->connectors[i].GetDescriptor();
441 polls.events = POLLIN;
442 int ret = poll(&polls,1,1);
443 if (ret <= 0) continue;
445 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
446 data[rcvsize] = '\0';
451 log(DEBUG,"recv() failed for serverrec::RecvPacket(): %s",strerror(errno));
452 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
453 this->connectors[i].CloseConnection();
454 this->connectors[i].SetState(STATE_DISCONNECTED);
455 if (!IsRoutable(this->connectors[i].GetServerName()))
457 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
458 DoSplit(this->connectors[i].GetServerName().c_str());
465 if (!this->connectors[i].AddBuffer(data))
467 WriteOpers("*** Read buffer for %s exceeds maximum, closing connection!",this->connectors[i].GetServerName().c_str());
468 this->connectors[i].CloseConnection();
469 this->connectors[i].SetState(STATE_DISCONNECTED);
470 if (!IsRoutable(this->connectors[i].GetServerName()))
472 WriteOpers("*** Server %s is no longer routable, disconnecting.",this->connectors[i].GetServerName().c_str());
473 DoSplit(this->connectors[i].GetServerName().c_str());
476 if (this->connectors[i].BufferIsComplete())
478 this->connectors[i].ResetPing();
479 while (this->connectors[i].BufferIsComplete())
481 std::string text = this->connectors[i].GetBuffer();
484 if ((text[0] == ':') && (text.find(" ") != std::string::npos))
486 std::string orig = text;
487 log(DEBUG,"Original: %s",text.c_str());
488 std::string sum = text.substr(1,text.find(" ")-1);
489 text = text.substr(text.find(" ")+1,text.length());
490 std::string possible_token = text.substr(1,text.find(" ")-1);
491 if (possible_token.length() > 1)
495 log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
499 log(DEBUG,"Packet sum: '%s'",sum.c_str());
500 if ((already_have_sum(sum)) && (sum != "*"))
502 // we don't accept dupes
505 sums.push_back(sum.c_str());
508 else sums.push_back("*");
509 messages.push_back(text.c_str());
510 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
511 log(DEBUG,"serverrec::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
519 // nothing new yet -- message and host will be undefined