1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
17 #include "inspstring.h"
18 #include "socketengine.h"
21 bool BufferedSocket::Readable()
23 return (this->state != I_CONNECTING);
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
29 this->state = I_DISCONNECTED;
31 this->ServerInstance = SI;
34 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
38 this->state = I_CONNECTED;
39 strlcpy(this->IP,ip,MAXBUF);
40 this->ServerInstance = SI;
42 this->ServerInstance->SE->AddFd(this);
45 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
47 this->cbindip = connectbindip;
49 this->ServerInstance = SI;
50 strlcpy(host,ipaddr.c_str(),MAXBUF);
53 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
61 if (inet_pton(AF_INET6, host, &n) < 1)
68 if (inet_aton(host,&n) < 1)
73 this->ServerInstance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
74 this->OnError(I_ERR_CONNECT);
77 this->state = I_ERROR;
82 strlcpy(this->IP,host,MAXBUF);
83 if (!this->DoConnect(maxtime))
85 this->OnError(I_ERR_CONNECT);
88 this->state = I_ERROR;
94 void BufferedSocket::SetQueues()
96 // attempt to increase socket sendq and recvq as high as its possible
99 if(setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
101 //this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
102 ; // do nothing. I'm a little sick of people trying to interpret this message as a result of why their incorrect setups don't work.
106 bool BufferedSocket::DoBindMagic(const std::string ¤t_ip, bool v6)
108 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
109 socklen_t size = sizeof(sockaddr_in);
110 sockaddr* s = new sockaddr[2];
115 if (inet_pton(AF_INET6, current_ip.c_str(), &n) > 0)
117 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
118 ((sockaddr_in6*)s)->sin6_port = 0;
119 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
120 size = sizeof(sockaddr_in6);
124 // Well, this is as good as it's gonna get.
125 errno = EADDRNOTAVAIL;
134 if (inet_aton(current_ip.c_str(), &n) > 0)
136 ((sockaddr_in*)s)->sin_addr = n;
137 ((sockaddr_in*)s)->sin_port = 0;
138 ((sockaddr_in*)s)->sin_family = AF_INET;
142 // Well, this is as good as it's gonna get.
143 errno = EADDRNOTAVAIL;
149 if (ServerInstance->SE->Bind(this->fd, s, size) < 0)
151 this->state = I_ERROR;
152 this->OnError(I_ERR_BIND);
161 /* Most irc servers require you to specify the ip you want to bind to.
162 * If you dont specify an IP, they rather dumbly bind to the first IP
163 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
164 * addresses we've bound server ports to, and we try and bind our outbound
165 * connections to the first usable non-loopback and non-any IP we find.
166 * This is easier to configure when you have a lot of links and a lot
167 * of servers to configure.
169 bool BufferedSocket::BindAddr(const std::string &ip_to_bind)
171 ConfigReader Conf(this->ServerInstance);
174 // Case one: If they provided an IP, try bind it
175 if (!ip_to_bind.empty())
178 // Check whether or not they are binding to an IPv6 IP..
179 if (ip_to_bind.find(':') != std::string::npos)
182 // And if it fails, don't do anything.
183 return this->DoBindMagic(ip_to_bind, v6);
186 for (int j = 0; j < Conf.Enumerate("bind"); j++)
188 // We only want to try bind to a server ip.
189 if (Conf.ReadValue("bind","type",j) != "servers")
192 // set current IP to the <bind> tag
193 std::string current_ip = Conf.ReadValue("bind","address",j);
196 // Check whether this <bind> is for an ipv6 address
197 if (current_ip.find(':') != std::string::npos)
203 // Make sure IP is nothing local
204 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
207 // Try bind, don't fail if it doesn't bind though.
208 if (this->DoBindMagic(current_ip, v6))
212 // NOTE: You may wonder WTF we are returning *true* here, but that is because there were no custom binds setup, and so we have nothing to do
213 // (remember, outgoing connections without binding are perfectly ok).
214 ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
218 bool BufferedSocket::DoConnect(unsigned long maxtime)
220 irc::sockets::sockaddrs addr;
221 irc::sockets::aptosa(this->host, this->port, &addr);
223 this->fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
227 this->state = I_ERROR;
228 this->OnError(I_ERR_SOCKET);
232 if (!this->BindAddr(this->cbindip))
239 ServerInstance->SE->NonBlocking(this->fd);
241 if (ServerInstance->SE->Connect(this, &addr.sa, sa_size(addr)) == -1)
243 if (errno != EINPROGRESS)
245 this->OnError(I_ERR_CONNECT);
247 this->state = I_ERROR;
251 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
252 this->ServerInstance->Timers->AddTimer(this->Timeout);
255 this->state = I_CONNECTING;
258 if (!this->ServerInstance->SE->AddFd(this))
260 this->OnError(I_ERR_NOMOREFDS);
262 this->state = I_ERROR;
268 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
273 void BufferedSocket::Close()
275 /* Save this, so we dont lose it,
276 * otherise on failure, error messages
277 * might be inaccurate.
282 if (this->GetIOHook())
286 this->GetIOHook()->OnRawSocketClose(this->fd);
288 catch (CoreException& modexcept)
290 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
293 ServerInstance->SE->Shutdown(this, 2);
294 if (ServerInstance->SE->Close(this) != -1)
297 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
298 ServerInstance->SocketCull[this] = this;
303 std::string BufferedSocket::GetIP()
308 const char* BufferedSocket::Read()
310 if (!ServerInstance->SE->BoundsCheckFd(this))
314 char* ReadBuffer = ServerInstance->GetReadBuffer();
316 if (this->GetIOHook())
322 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
324 catch (CoreException& modexcept)
326 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
340 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
344 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
345 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
346 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
347 * --w00t (july 2, 2008)
365 * This function formerly tried to flush write buffer each call.
366 * While admirable in attempting to get the data out to wherever
367 * it is going, on a full socket, it's just going to syscall write() and
368 * EAGAIN constantly, instead of waiting in the SE to know if it can write
369 * which will chew a bit of CPU.
371 * So, now this function returns void (take note) and just adds to the sendq.
373 * It'll get written at a determinate point when the socketengine tells us it can write.
374 * -- w00t (april 1, 2008)
376 void BufferedSocket::Write(const std::string &data)
378 /* Append the data to the back of the queue ready for writing */
379 outbuffer.push_back(data);
381 /* Mark ourselves as wanting write */
382 this->ServerInstance->SE->WantWrite(this);
385 bool BufferedSocket::FlushWriteBuffer()
388 if ((this->fd > -1) && (this->state == I_CONNECTED))
390 if (this->GetIOHook())
392 while (outbuffer.size() && (errno != EAGAIN))
396 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
397 * implement their own buffering mechanisms
399 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
400 outbuffer.pop_front();
402 catch (CoreException& modexcept)
404 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
411 /* If we have multiple lines, try to send them all,
412 * not just the first one -- Brain
414 while (outbuffer.size() && (errno != EAGAIN))
417 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
421 if ((unsigned int)result >= outbuffer[0].length())
423 /* The whole block was written (usually a line)
424 * Pop the block off the front of the queue,
425 * dont set errno, because we are clear of errors
426 * and want to try and write the next block too.
428 outbuffer.pop_front();
432 std::string temp = outbuffer[0].substr(result);
434 /* We didnt get the whole line out. arses.
435 * Try again next time, i guess. Set errno,
436 * because we shouldnt be writing any more now,
437 * until the socketengine says its safe to do so.
442 else if (result == 0)
444 this->ServerInstance->SE->DelFd(this);
448 else if ((result == -1) && (errno != EAGAIN))
450 this->OnError(I_ERR_WRITE);
451 this->state = I_ERROR;
452 this->ServerInstance->SE->DelFd(this);
460 if ((errno == EAGAIN) && (fd > -1))
462 this->ServerInstance->SE->WantWrite(this);
468 void SocketTimeout::Tick(time_t)
470 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
472 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
475 if (this->sock->state == I_CONNECTING)
477 // for connecting sockets, the timeout can occur
478 // which causes termination of the connection after
479 // the given number of seconds without a successful
481 this->sock->OnTimeout();
482 this->sock->OnError(I_ERR_TIMEOUT);
484 /* NOTE: We must set this AFTER DelFd, as we added
485 * this socket whilst writeable. This means that we
486 * must DELETE the socket whilst writeable too!
488 this->sock->state = I_ERROR;
490 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
491 ServerInstance->SocketCull[this->sock] = this->sock;
494 this->sock->Timeout = NULL;
497 bool BufferedSocket::InternalMarkConnected()
499 /* Our socket was in write-state, so delete it and re-add it
502 this->SetState(I_CONNECTED);
504 if (this->GetIOHook())
506 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
509 this->GetIOHook()->OnRawSocketConnect(this->fd);
511 catch (CoreException& modexcept)
513 ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
517 return this->OnConnected();
520 void BufferedSocket::SetState(BufferedSocketState s)
525 BufferedSocketState BufferedSocket::GetState()
530 bool BufferedSocket::OnConnected() { return true; }
531 void BufferedSocket::OnError(BufferedSocketError) { return; }
532 int BufferedSocket::OnDisconnect() { return 0; }
533 bool BufferedSocket::OnDataReady() { return true; }
534 bool BufferedSocket::OnWriteReady()
536 // Default behaviour: just try write some.
537 return !this->FlushWriteBuffer();
539 void BufferedSocket::OnTimeout() { return; }
540 void BufferedSocket::OnClose() { return; }
542 BufferedSocket::~BufferedSocket()
547 ServerInstance->Timers->DelTimer(Timeout);
552 void BufferedSocket::HandleEvent(EventType et, int errornum)
561 this->OnError(I_ERR_TIMEOUT);
565 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
568 this->OnError(I_ERR_BIND);
572 this->OnError(I_ERR_WRITE);
576 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
577 this->ServerInstance->SocketCull[this] = this;
583 if (!this->OnDataReady())
585 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
586 this->ServerInstance->SocketCull[this] = this;
593 if (this->state == I_CONNECTING)
595 if (!this->InternalMarkConnected())
597 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
598 this->ServerInstance->SocketCull[this] = this;
605 if (!this->OnWriteReady())
607 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
608 this->ServerInstance->SocketCull[this] = this;