1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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 using irc::sockets::OpenTCPSocket;
23 bool BufferedSocket::Readable()
25 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
28 BufferedSocket::BufferedSocket(InspIRCd* SI)
31 this->state = I_DISCONNECTED;
33 this->WaitingForWriteEvent = false;
37 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
41 this->state = I_CONNECTED;
42 strlcpy(this->IP,ip,MAXBUF);
43 this->WaitingForWriteEvent = false;
46 this->Instance->SE->AddFd(this);
49 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime, const std::string &connectbindip)
51 this->cbindip = connectbindip;
54 strlcpy(host,ipaddr.c_str(),MAXBUF);
55 this->WaitingForWriteEvent = false;
59 if ((this->fd = OpenTCPSocket(host)) == ERROR)
62 this->state = I_ERROR;
63 this->OnError(I_ERR_SOCKET);
68 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
72 this->state = I_ERROR;
73 this->OnError(I_ERR_BIND);
74 this->ClosePending = true;
79 this->state = I_LISTENING;
83 if (!this->Instance->SE->AddFd(this))
86 this->state = I_ERROR;
87 this->OnError(I_ERR_NOMOREFDS);
96 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
101 if (strchr(host,':'))
104 if (inet_pton(AF_INET6, host, &n) < 1)
111 if (inet_aton(host,&n) < 1)
116 this->Instance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
117 this->OnError(I_ERR_CONNECT);
120 this->state = I_ERROR;
125 strlcpy(this->IP,host,MAXBUF);
126 timeout_val = maxtime;
127 if (!this->DoConnect())
129 this->OnError(I_ERR_CONNECT);
132 this->state = I_ERROR;
139 void BufferedSocket::WantWrite()
141 this->Instance->SE->WantWrite(this);
142 this->WaitingForWriteEvent = true;
145 void BufferedSocket::SetQueues(int nfd)
147 // attempt to increase socket sendq and recvq as high as its possible
150 if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
152 //this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
153 ; // 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.
157 /* Most irc servers require you to specify the ip you want to bind to.
158 * If you dont specify an IP, they rather dumbly bind to the first IP
159 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
160 * addresses we've bound server ports to, and we try and bind our outbound
161 * connections to the first usable non-loopback and non-any IP we find.
162 * This is easier to configure when you have a lot of links and a lot
163 * of servers to configure.
165 bool BufferedSocket::BindAddr(const std::string &ip)
167 ConfigReader Conf(this->Instance);
168 socklen_t size = sizeof(sockaddr_in);
171 /* Are we looking for a binding to fit an ipv6 host? */
172 if ((ip.empty()) || (ip.find(':') != std::string::npos))
176 while (j < Conf.Enumerate("bind") || (!ip.empty()))
178 std::string sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
179 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
181 if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::1")))
183 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
184 sockaddr* s = new sockaddr[2];
189 if (inet_pton(AF_INET6, sIP.c_str(), &n) > 0)
191 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
192 ((sockaddr_in6*)s)->sin6_port = 0;
193 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
194 size = sizeof(sockaddr_in6);
207 if (inet_aton(sIP.c_str(), &n) > 0)
209 ((sockaddr_in*)s)->sin_addr = n;
210 ((sockaddr_in*)s)->sin_port = 0;
211 ((sockaddr_in*)s)->sin_family = AF_INET;
221 if (Instance->SE->Bind(this->fd, s, size) < 0)
223 this->state = I_ERROR;
224 this->OnError(I_ERR_BIND);
236 Instance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
240 bool BufferedSocket::DoConnect()
242 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
243 sockaddr* addr = new sockaddr[2];
244 socklen_t size = sizeof(sockaddr_in);
247 if ((!*this->host) || strchr(this->host, ':'))
252 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
253 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
255 if (!this->BindAddr(this->cbindip))
265 this->fd = socket(AF_INET, SOCK_STREAM, 0);
268 if (!this->BindAddr(this->cbindip))
278 this->state = I_ERROR;
279 this->OnError(I_ERR_SOCKET);
288 if (inet_pton(AF_INET6, this->host, &addy) > 0)
290 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
291 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
292 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
293 size = sizeof(sockaddr_in6);
300 if (inet_aton(this->host, &addy) > 0)
302 ((sockaddr_in*)addr)->sin_family = AF_INET;
303 ((sockaddr_in*)addr)->sin_addr = addy;
304 ((sockaddr_in*)addr)->sin_port = htons(this->port);
308 Instance->SE->NonBlocking(this->fd);
311 /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
312 Instance->SE->Blocking(this->fd);
315 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
317 if (errno != EINPROGRESS)
319 this->OnError(I_ERR_CONNECT);
321 this->state = I_ERROR;
325 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
326 this->Instance->Timers->AddTimer(this->Timeout);
329 /* CRAQ SMOKING STUFF TO BE FIXED */
330 Instance->SE->NonBlocking(this->fd);
332 this->state = I_CONNECTING;
335 if (!this->Instance->SE->AddFd(this))
337 this->OnError(I_ERR_NOMOREFDS);
339 this->state = I_ERROR;
342 this->SetQueues(this->fd);
345 Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
350 void BufferedSocket::Close()
352 /* Save this, so we dont lose it,
353 * otherise on failure, error messages
354 * might be inaccurate.
359 if (this->GetIOHook())
363 if (this->state != I_LISTENING)
364 this->GetIOHook()->OnRawSocketClose(this->fd);
366 catch (CoreException& modexcept)
368 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
371 Instance->SE->Shutdown(this, 2);
372 if (Instance->SE->Close(this) != -1)
375 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
376 Instance->SocketCull[this] = this;
381 std::string BufferedSocket::GetIP()
386 const char* BufferedSocket::Read()
388 if (!Instance->SE->BoundsCheckFd(this))
392 char* ReadBuffer = Instance->GetReadBuffer();
394 if (this->GetIOHook())
400 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
402 catch (CoreException& modexcept)
404 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
418 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
422 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
423 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
424 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
425 * --w00t (july 2, 2008)
443 * This function formerly tried to flush write buffer each call.
444 * While admirable in attempting to get the data out to wherever
445 * it is going, on a full socket, it's just going to syscall write() and
446 * EAGAIN constantly, instead of waiting in the SE to know if it can write
447 * which will chew a bit of CPU.
449 * So, now this function returns void (take note) and just adds to the sendq.
451 * It'll get written at a determinate point when the socketengine tells us it can write.
452 * -- w00t (april 1, 2008)
454 void BufferedSocket::Write(const std::string &data)
456 /* Append the data to the back of the queue ready for writing */
457 outbuffer.push_back(data);
459 /* Mark ourselves as wanting write */
460 this->Instance->SE->WantWrite(this);
463 bool BufferedSocket::FlushWriteBuffer()
466 if ((this->fd > -1) && (this->state == I_CONNECTED))
468 if (this->GetIOHook())
470 while (outbuffer.size() && (errno != EAGAIN))
474 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
475 * implement their own buffering mechanisms
477 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
478 outbuffer.pop_front();
480 catch (CoreException& modexcept)
482 Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
489 /* If we have multiple lines, try to send them all,
490 * not just the first one -- Brain
492 while (outbuffer.size() && (errno != EAGAIN))
495 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
499 if ((unsigned int)result >= outbuffer[0].length())
501 /* The whole block was written (usually a line)
502 * Pop the block off the front of the queue,
503 * dont set errno, because we are clear of errors
504 * and want to try and write the next block too.
506 outbuffer.pop_front();
510 std::string temp = outbuffer[0].substr(result);
512 /* We didnt get the whole line out. arses.
513 * Try again next time, i guess. Set errno,
514 * because we shouldnt be writing any more now,
515 * until the socketengine says its safe to do so.
520 else if (result == 0)
522 this->Instance->SE->DelFd(this);
526 else if ((result == -1) && (errno != EAGAIN))
528 this->OnError(I_ERR_WRITE);
529 this->state = I_ERROR;
530 this->Instance->SE->DelFd(this);
538 if ((errno == EAGAIN) && (fd > -1))
540 this->Instance->SE->WantWrite(this);
546 void SocketTimeout::Tick(time_t)
548 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
550 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
553 if (this->sock->state == I_CONNECTING)
555 // for non-listening sockets, the timeout can occur
556 // which causes termination of the connection after
557 // the given number of seconds without a successful
559 this->sock->OnTimeout();
560 this->sock->OnError(I_ERR_TIMEOUT);
561 this->sock->timeout = true;
563 /* NOTE: We must set this AFTER DelFd, as we added
564 * this socket whilst writeable. This means that we
565 * must DELETE the socket whilst writeable too!
567 this->sock->state = I_ERROR;
569 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
570 ServerInstance->SocketCull[this->sock] = this->sock;
573 this->sock->Timeout = NULL;
576 bool BufferedSocket::Poll()
581 if (!Instance->SE->BoundsCheckFd(this))
585 if (Instance->SE->GetRef(this->fd) != this)
591 /* Our socket was in write-state, so delete it and re-add it
597 this->Instance->SE->DelFd(this);
598 if (!this->Instance->SE->AddFd(this))
602 this->SetState(I_CONNECTED);
604 if (this->GetIOHook())
606 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
609 this->GetIOHook()->OnRawSocketConnect(this->fd);
611 catch (CoreException& modexcept)
613 Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
616 return this->OnConnected();
620 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
621 sockaddr* client = new sockaddr[2];
622 length = sizeof (sockaddr_in);
625 if ((!*this->host) || strchr(this->host, ':'))
626 length = sizeof(sockaddr_in6);
628 incoming = Instance->SE->Accept(this, client, &length);
630 if ((!*this->host) || strchr(this->host, ':'))
633 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
638 // FIX: we were doing this for IPv6 connections as well, which was fucking recvip..
639 // Add brackets to make this a bit clearer. -- w00t (Jan 15, 2008)
640 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
643 Instance->SE->NonBlocking(incoming);
645 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
647 if (this->GetIOHook())
651 this->GetIOHook()->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
653 catch (CoreException& modexcept)
655 Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
659 this->SetQueues(incoming);
666 /* Process the read event */
667 return this->OnDataReady();
675 void BufferedSocket::SetState(BufferedSocketState s)
680 BufferedSocketState BufferedSocket::GetState()
685 int BufferedSocket::GetFd()
690 bool BufferedSocket::OnConnected() { return true; }
691 void BufferedSocket::OnError(BufferedSocketError) { return; }
692 int BufferedSocket::OnDisconnect() { return 0; }
693 int BufferedSocket::OnIncomingConnection(int, char*) { return 0; }
694 bool BufferedSocket::OnDataReady() { return true; }
695 bool BufferedSocket::OnWriteReady() { return true; }
696 void BufferedSocket::OnTimeout() { return; }
697 void BufferedSocket::OnClose() { return; }
699 BufferedSocket::~BufferedSocket()
704 Instance->Timers->DelTimer(Timeout);
709 void BufferedSocket::HandleEvent(EventType et, int errornum)
717 this->OnError(I_ERR_TIMEOUT);
721 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
724 this->OnError(I_ERR_BIND);
728 this->OnError(I_ERR_WRITE);
731 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
732 this->Instance->SocketCull[this] = this;
738 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
739 this->Instance->SocketCull[this] = this;
744 if (this->WaitingForWriteEvent)
746 this->WaitingForWriteEvent = false;
747 if (!this->OnWriteReady())
749 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
750 this->Instance->SocketCull[this] = this;
754 if (this->state == I_CONNECTING)
756 /* This might look wrong as if we should be actually calling
757 * with EVENT_WRITE, but trust me it is correct. There are some
758 * writeability-state things in the read code, because of how
759 * BufferedSocket used to work regarding write buffering in previous
760 * versions of InspIRCd. - Brain
762 this->HandleEvent(EVENT_READ);
767 if (this->FlushWriteBuffer())
769 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
770 this->Instance->SocketCull[this] = this;