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 std::deque<std::string> xsums;
42 serverrec::serverrec()
47 usercount_i = usercount = opercount = version = 0;
53 strlcpy(nickserv,"",NICKMAX);
58 serverrec::~serverrec()
62 serverrec::serverrec(char* n, long ver, bool jupe)
66 usercount_i = usercount = opercount = 0;
73 strlcpy(nickserv,"",NICKMAX);
77 bool serverrec::CreateListener(char* newhost, int p)
79 sockaddr_in host_address;
83 struct linger linger = { 0 };
87 fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
93 setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char*)&on,sizeof(on));
96 setsockopt(fd,SOL_SOCKET,SO_LINGER,(const char*)&linger,sizeof(linger));
98 // attempt to increase socket sendq and recvq as high as its possible
99 // to get them on linux.
102 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
103 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
105 memset((void*)&host_address, 0, sizeof(host_address));
107 host_address.sin_family = AF_INET;
109 if (!strcmp(newhost,""))
111 host_address.sin_addr.s_addr = htonl(INADDR_ANY);
115 inet_aton(newhost,&addy);
116 host_address.sin_addr = addy;
119 host_address.sin_port = htons(p);
121 if (bind(fd,(sockaddr*)&host_address,sizeof(host_address))<0)
126 // make the socket non-blocking
127 flags = fcntl(fd, F_GETFL, 0);
128 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
132 listen(this->fd, MaxConn);
138 bool serverrec::BeginLink(char* targethost, int newport, char* password, char* servername, int myport)
140 char connect[MAXBUF];
142 ircd_connector connector;
143 ircd_connector *cn = this->FindHost(servername);
148 WriteOpers("CONNECT aborted: Server %s already exists",servername);
155 if (connector.MakeOutboundConnection(targethost,newport))
157 // targethost has been turned into an ip...
158 // we dont want this as the server name.
159 connector.SetServerName(servername);
160 snprintf(connect,MAXBUF,"S %s %s %lu %s :%s",getservername().c_str(),password,(unsigned long)myport,GetRevision().c_str(),getserverdesc().c_str());
161 connector.SetState(STATE_NOAUTH_OUTBOUND);
162 connector.SetHostAndPort(targethost, newport);
163 this->connectors.push_back(connector);
164 // this packet isn't actually sent until the socket connects -- the STATE_NOAUTH_OUTBOUND state
165 // queues outbound data until the socket is polled as writeable (e.g. the connection is established)
166 return this->SendPacket(connect, servername);
170 connector.SetState(STATE_DISCONNECTED);
171 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
178 bool serverrec::MeshCookie(char* targethost, int newport, unsigned long cookie, char* servername)
180 char connect[MAXBUF];
182 ircd_connector connector;
184 WriteOpers("Establishing meshed link to %s:%d",servername,newport);
188 if (connector.MakeOutboundConnection(targethost,newport))
190 // targethost has been turned into an ip...
191 // we dont want this as the server name.
192 connector.SetServerName(servername);
193 snprintf(connect,MAXBUF,"- %lu %s :%s",cookie,getservername().c_str(),getserverdesc().c_str());
194 connector.SetState(STATE_NOAUTH_OUTBOUND);
195 connector.SetHostAndPort(targethost, newport);
196 connector.SetState(STATE_CONNECTED);
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];
251 void serverrec::FlushWriteBuffers()
253 for (int i = 0; i < this->connectors.size(); i++)
255 // don't try and ping a NOAUTH_OUTBOUND state, its not authed yet!
256 if ((this->connectors[i].GetState() == STATE_NOAUTH_OUTBOUND) && (TIME > this->connectors[i].age+30))
258 // however if we reach this timer its connected timed out :)
259 WriteOpers("*** Connection to %s timed out",this->connectors[i].GetServerName().c_str());
260 DoSplit(this->connectors[i].GetServerName().c_str());
263 else if ((this->connectors[i].GetState() == STATE_NOAUTH_INBOUND) && (TIME > this->connectors[i].age+30))
265 WriteOpers("*** Connection from %s timed out",this->connectors[i].GetServerName().c_str());
266 DoSplit(this->connectors[i].GetServerName().c_str());
269 else if (this->connectors[i].GetState() != STATE_DISCONNECTED)
271 if (!this->connectors[i].CheckPing())
273 WriteOpers("*** Lost single connection to %s: Ping timeout",this->connectors[i].GetServerName().c_str());
274 this->connectors[i].CloseConnection();
275 this->connectors[i].SetState(STATE_DISCONNECTED);
278 if (this->connectors[i].HasBufferedOutput())
280 if (!this->connectors[i].FlushWriteBuf())
282 // if we're here the write() caused an error, we cannot proceed
283 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",this->connectors[i].GetServerName().c_str(),this->connectors[i].GetWriteError().c_str());
284 this->connectors[i].CloseConnection();
285 this->connectors[i].SetState(STATE_DISCONNECTED);
291 bool serverrec::SendPacket(char *message, const char* sendhost)
293 if ((!message) || (!sendhost))
296 ircd_connector* cn = this->FindHost(sendhost);
298 if (!strchr(message,'\n'))
300 strlcat(message,"\n",MAXBUF);
305 log(DEBUG,"main: serverrec::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
307 if (cn->GetState() == STATE_DISCONNECTED)
309 // fix: can only route one hop to avoid a loop
310 if (strncmp(message,"R ",2))
312 log(DEBUG,"Not a double reroute");
313 // this route is down, we must re-route the packet through an available point in the mesh.
314 for (int k = 0; k < this->connectors.size(); k++)
316 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
317 // search for another point in the mesh which can 'reach' where we want to go
318 for (int m = 0; m < this->connectors[k].routes.size(); m++)
320 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
322 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
324 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
325 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
332 snprintf(buffer,MAXBUF,"& %s",sendhost);
333 WriteOpers("*** All connections to %s lost.",sendhost);
334 NetSendToAllExcept(sendhost,buffer);
339 // returns false if the packet could not be sent (e.g. target host down)
340 if (!cn->AddWriteBuf(message))
342 // if we're here, there was an error pending, and the send cannot proceed
343 log(DEBUG,"cn->AddWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
344 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
345 cn->CloseConnection();
346 cn->SetState(STATE_DISCONNECTED);
347 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
348 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
349 return this->SendPacket(message,sendhost);
351 if (!cn->FlushWriteBuf())
353 // if we're here the write() caused an error, we cannot proceed
354 log(DEBUG,"cn->FlushWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
355 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
356 cn->CloseConnection();
357 cn->SetState(STATE_DISCONNECTED);
358 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
359 // retry the packet along a new route so either arrival OR failure are gauranteed
360 return this->SendPacket(message,sendhost);
366 bool already_have_sum(std::string sum)
368 for (int i = 0; i < xsums.size(); i++)
375 if (xsums.size() >= 128)
379 xsums.push_back(sum);
383 // receives a packet from any where there is data waiting, first come, first served
384 // fills the message and host values with the host where the data came from.
386 bool serverrec::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
389 memset(data, 0, 65536);
390 for (int i = 0; i < this->connectors.size(); i++)
392 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
394 // returns false if the packet could not be sent (e.g. target host down)
397 // check if theres any data on this socket
398 // if not, continue onwards to the next.
400 polls.fd = this->connectors[i].GetDescriptor();
401 polls.events = POLLIN;
402 int ret = poll(&polls,1,1);
403 if (ret <= 0) continue;
405 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
406 data[rcvsize] = '\0';
411 log(DEBUG,"recv() failed for serverrec::RecvPacket(): %s",strerror(errno));
412 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
413 this->connectors[i].CloseConnection();
414 this->connectors[i].SetState(STATE_DISCONNECTED);
420 if (!this->connectors[i].AddBuffer(data))
422 WriteOpers("*** Read buffer for %s exceeds maximum, closing connection!",this->connectors[i].GetServerName().c_str());
423 this->connectors[i].CloseConnection();
424 this->connectors[i].SetState(STATE_DISCONNECTED);
426 if (this->connectors[i].BufferIsComplete())
428 this->connectors[i].ResetPing();
429 while (this->connectors[i].BufferIsComplete())
431 std::string text = this->connectors[i].GetBuffer();
434 if ((text[0] == ':') && (text.find(" ") != std::string::npos))
436 std::string orig = text;
437 log(DEBUG,"Original: %s",text.c_str());
438 std::string sum = text.substr(1,text.find(" ")-1);
439 text = text.substr(text.find(" ")+1,text.length());
440 std::string possible_token = text.substr(1,text.find(" ")-1);
441 if (possible_token.length() > 1)
445 log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
449 log(DEBUG,"Packet sum: '%s'",sum.c_str());
450 if ((already_have_sum(sum)) && (sum != "*"))
452 // we don't accept dupes
455 sums.push_back(sum.c_str());
458 else sums.push_back("*");
459 messages.push_back(text.c_str());
460 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
461 log(DEBUG,"serverrec::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
469 // nothing new yet -- message and host will be undefined