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 this->connectors.push_back(connector);
197 return this->SendPacket(connect, servername);
201 connector.SetState(STATE_DISCONNECTED);
202 WriteOpers("Could not create outbound connection to %s:%d",targethost,newport);
208 bool serverrec::AddIncoming(int newfd, char* targethost, int sourceport)
210 ircd_connector connector;
212 // targethost has been turned into an ip...
213 // we dont want this as the server name.
214 connector.SetServerName(targethost);
215 connector.SetDescriptor(newfd);
216 connector.SetState(STATE_NOAUTH_INBOUND);
217 int flags = fcntl(newfd, F_GETFL, 0);
218 fcntl(newfd, F_SETFL, flags | O_NONBLOCK);
221 setsockopt(newfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
222 setsockopt(newfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
223 connector.SetHostAndPort(targethost, sourceport);
224 connector.SetState(STATE_NOAUTH_INBOUND);
225 log(DEBUG,"serverrec::AddIncoming() Added connection: %s:%d",targethost,sourceport);
226 this->connectors.push_back(connector);
230 void serverrec::TerminateLink(char* targethost)
232 // this locates the targethost in the serverrec::connectors vector of the class,
233 // and terminates it by sending it an SQUIT token and closing its descriptor.
234 // TerminateLink with a null string causes a terminate of ALL links
237 // Returns a pointer to the connector for 'host'
238 ircd_connector* serverrec::FindHost(std::string findhost)
240 for (int i = 0; i < this->connectors.size(); i++)
242 if (this->connectors[i].GetServerName() == findhost)
244 return &this->connectors[i];
250 void serverrec::FlushWriteBuffers()
252 for (int i = 0; i < this->connectors.size(); i++)
254 // don't try and ping a NOAUTH_OUTBOUND state, its not authed yet!
255 if ((this->connectors[i].GetState() == STATE_NOAUTH_OUTBOUND) && (TIME > this->connectors[i].age+30))
257 // however if we reach this timer its connected timed out :)
258 WriteOpers("*** Connection to %s timed out",this->connectors[i].GetServerName().c_str());
259 DoSplit(this->connectors[i].GetServerName().c_str());
262 else if ((this->connectors[i].GetState() == STATE_NOAUTH_INBOUND) && (TIME > this->connectors[i].age+30))
264 WriteOpers("*** Connection from %s timed out",this->connectors[i].GetServerName().c_str());
265 DoSplit(this->connectors[i].GetServerName().c_str());
268 else if (this->connectors[i].GetState() != STATE_DISCONNECTED)
270 if (!this->connectors[i].CheckPing())
272 WriteOpers("*** Lost single connection to %s: Ping timeout",this->connectors[i].GetServerName().c_str());
273 this->connectors[i].CloseConnection();
274 this->connectors[i].SetState(STATE_DISCONNECTED);
277 if (this->connectors[i].HasBufferedOutput())
279 if (!this->connectors[i].FlushWriteBuf())
281 // if we're here the write() caused an error, we cannot proceed
282 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",this->connectors[i].GetServerName().c_str(),this->connectors[i].GetWriteError().c_str());
283 this->connectors[i].CloseConnection();
284 this->connectors[i].SetState(STATE_DISCONNECTED);
290 bool serverrec::SendPacket(char *message, const char* sendhost)
292 if ((!message) || (!sendhost))
295 ircd_connector* cn = this->FindHost(sendhost);
297 if (!strchr(message,'\n'))
299 strlcat(message,"\n",MAXBUF);
304 log(DEBUG,"main: serverrec::SendPacket() sent '%s' to %s",message,cn->GetServerName().c_str());
306 if (cn->GetState() == STATE_DISCONNECTED)
308 // fix: can only route one hop to avoid a loop
309 if (strncmp(message,"R ",2))
311 log(DEBUG,"Not a double reroute");
312 // this route is down, we must re-route the packet through an available point in the mesh.
313 for (int k = 0; k < this->connectors.size(); k++)
315 log(DEBUG,"Check connector %d: %s",k,this->connectors[k].GetServerName().c_str());
316 // search for another point in the mesh which can 'reach' where we want to go
317 for (int m = 0; m < this->connectors[k].routes.size(); m++)
319 if (!strcasecmp(this->connectors[k].routes[m].c_str(),sendhost))
321 log(DEBUG,"Found alternative route for packet: %s",this->connectors[k].GetServerName().c_str());
323 snprintf(buffer,MAXBUF,"R %s %s",sendhost,message);
324 this->SendPacket(buffer,this->connectors[k].GetServerName().c_str());
331 snprintf(buffer,MAXBUF,"& %s",sendhost);
332 WriteOpers("*** All connections to %s lost.",sendhost);
333 NetSendToAllExcept(sendhost,buffer);
338 // returns false if the packet could not be sent (e.g. target host down)
339 if (!cn->AddWriteBuf(message))
341 // if we're here, there was an error pending, and the send cannot proceed
342 log(DEBUG,"cn->AddWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
343 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
344 cn->CloseConnection();
345 cn->SetState(STATE_DISCONNECTED);
346 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
347 // retry the packet along a new route so either arrival OR failure are gauranteed (bugfix)
348 return this->SendPacket(message,sendhost);
350 if (!cn->FlushWriteBuf())
352 // if we're here the write() caused an error, we cannot proceed
353 log(DEBUG,"cn->FlushWriteBuf() failed for serverrec::SendPacket(): %s",cn->GetWriteError().c_str());
354 log(DEBUG,"Disabling connector: %s",cn->GetServerName().c_str());
355 cn->CloseConnection();
356 cn->SetState(STATE_DISCONNECTED);
357 WriteOpers("*** Lost single connection to %s, link inactive and retrying: %s",cn->GetServerName().c_str(),cn->GetWriteError().c_str());
358 // retry the packet along a new route so either arrival OR failure are gauranteed
359 return this->SendPacket(message,sendhost);
365 bool already_have_sum(std::string sum)
367 for (int i = 0; i < xsums.size(); i++)
374 if (xsums.size() >= 128)
378 xsums.push_back(sum);
382 // receives a packet from any where there is data waiting, first come, first served
383 // fills the message and host values with the host where the data came from.
385 bool serverrec::RecvPacket(std::deque<std::string> &messages, char* recvhost,std::deque<std::string> &sums)
388 memset(data, 0, 65536);
389 for (int i = 0; i < this->connectors.size(); i++)
391 if (this->connectors[i].GetState() != STATE_DISCONNECTED)
393 // returns false if the packet could not be sent (e.g. target host down)
396 // check if theres any data on this socket
397 // if not, continue onwards to the next.
399 polls.fd = this->connectors[i].GetDescriptor();
400 polls.events = POLLIN;
401 int ret = poll(&polls,1,1);
402 if (ret <= 0) continue;
404 rcvsize = recv(this->connectors[i].GetDescriptor(),data,65000,0);
405 data[rcvsize] = '\0';
410 log(DEBUG,"recv() failed for serverrec::RecvPacket(): %s",strerror(errno));
411 log(DEBUG,"Disabling connector: %s",this->connectors[i].GetServerName().c_str());
412 this->connectors[i].CloseConnection();
413 this->connectors[i].SetState(STATE_DISCONNECTED);
419 if (!this->connectors[i].AddBuffer(data))
421 WriteOpers("*** Read buffer for %s exceeds maximum, closing connection!",this->connectors[i].GetServerName().c_str());
422 this->connectors[i].CloseConnection();
423 this->connectors[i].SetState(STATE_DISCONNECTED);
425 if (this->connectors[i].BufferIsComplete())
427 this->connectors[i].ResetPing();
428 while (this->connectors[i].BufferIsComplete())
430 std::string text = this->connectors[i].GetBuffer();
433 if ((text[0] == ':') && (text.find(" ") != std::string::npos))
435 std::string orig = text;
436 log(DEBUG,"Original: %s",text.c_str());
437 std::string sum = text.substr(1,text.find(" ")-1);
438 text = text.substr(text.find(" ")+1,text.length());
439 std::string possible_token = text.substr(1,text.find(" ")-1);
440 if (possible_token.length() > 1)
444 log(DEBUG,"Non-mesh, non-tokenized string passed up the chain");
448 log(DEBUG,"Packet sum: '%s'",sum.c_str());
449 if ((already_have_sum(sum)) && (sum != "*"))
451 // we don't accept dupes
454 sums.push_back(sum.c_str());
457 else sums.push_back("*");
458 messages.push_back(text.c_str());
459 strlcpy(recvhost,this->connectors[i].GetServerName().c_str(),160);
460 log(DEBUG,"serverrec::RecvPacket() %d:%s->%s",pushed++,recvhost,text.c_str());
468 // nothing new yet -- message and host will be undefined