1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
14 /* $Core: libIRCDinspsocket */
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;
35 this->IsIOHooked = false;
38 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
42 this->state = I_CONNECTED;
43 strlcpy(this->IP,ip,MAXBUF);
44 this->WaitingForWriteEvent = false;
46 this->IsIOHooked = false;
48 this->Instance->SE->AddFd(this);
51 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime, const std::string &connectbindip)
53 this->cbindip = connectbindip;
56 strlcpy(host,ipaddr.c_str(),MAXBUF);
57 this->WaitingForWriteEvent = false;
58 this->IsIOHooked = false;
62 if ((this->fd = OpenTCPSocket(host)) == ERROR)
65 this->state = I_ERROR;
66 this->OnError(I_ERR_SOCKET);
71 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
75 this->state = I_ERROR;
76 this->OnError(I_ERR_BIND);
77 this->ClosePending = true;
82 this->state = I_LISTENING;
86 if (!this->Instance->SE->AddFd(this))
89 this->state = I_ERROR;
90 this->OnError(I_ERR_NOMOREFDS);
99 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
104 if (strchr(host,':'))
107 if (inet_pton(AF_INET6, host, &n) < 1)
114 if (inet_aton(host,&n) < 1)
119 this->Instance->Log(DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
120 this->OnError(I_ERR_CONNECT);
123 this->state = I_ERROR;
128 strlcpy(this->IP,host,MAXBUF);
129 timeout_val = maxtime;
130 if (!this->DoConnect())
132 this->OnError(I_ERR_CONNECT);
135 this->state = I_ERROR;
142 void BufferedSocket::WantWrite()
144 this->Instance->SE->WantWrite(this);
145 this->WaitingForWriteEvent = true;
148 void BufferedSocket::SetQueues(int nfd)
150 // attempt to increase socket sendq and recvq as high as its possible
153 if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
155 //this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
156 ; // 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.
160 /* Most irc servers require you to specify the ip you want to bind to.
161 * If you dont specify an IP, they rather dumbly bind to the first IP
162 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
163 * addresses we've bound server ports to, and we try and bind our outbound
164 * connections to the first usable non-loopback and non-any IP we find.
165 * This is easier to configure when you have a lot of links and a lot
166 * of servers to configure.
168 bool BufferedSocket::BindAddr(const std::string &ip)
170 ConfigReader Conf(this->Instance);
171 socklen_t size = sizeof(sockaddr_in);
174 /* Are we looking for a binding to fit an ipv6 host? */
175 if ((ip.empty()) || (ip.find(':') != std::string::npos))
179 while (j < Conf.Enumerate("bind") || (!ip.empty()))
181 std::string IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
182 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
184 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (!IP.empty()) && (IP != "::1")))
186 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
187 sockaddr* s = new sockaddr[2];
192 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
194 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
195 ((sockaddr_in6*)s)->sin6_port = 0;
196 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
197 size = sizeof(sockaddr_in6);
210 if (inet_aton(IP.c_str(), &n) > 0)
212 ((sockaddr_in*)s)->sin_addr = n;
213 ((sockaddr_in*)s)->sin_port = 0;
214 ((sockaddr_in*)s)->sin_family = AF_INET;
224 if (Instance->SE->Bind(this->fd, s, size) < 0)
226 this->state = I_ERROR;
227 this->OnError(I_ERR_BIND);
242 bool BufferedSocket::DoConnect()
244 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
245 sockaddr* addr = new sockaddr[2];
246 socklen_t size = sizeof(sockaddr_in);
249 if ((!*this->host) || strchr(this->host, ':'))
254 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
255 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
257 if (!this->BindAddr(this->cbindip))
267 this->fd = socket(AF_INET, SOCK_STREAM, 0);
270 if (!this->BindAddr(this->cbindip))
280 this->state = I_ERROR;
281 this->OnError(I_ERR_SOCKET);
290 if (inet_pton(AF_INET6, this->host, &addy) > 0)
292 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
293 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
294 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
295 size = sizeof(sockaddr_in6);
302 if (inet_aton(this->host, &addy) > 0)
304 ((sockaddr_in*)addr)->sin_family = AF_INET;
305 ((sockaddr_in*)addr)->sin_addr = addy;
306 ((sockaddr_in*)addr)->sin_port = htons(this->port);
310 Instance->SE->NonBlocking(this->fd);
313 /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
314 Instance->SE->Blocking(this->fd);
317 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
319 if (errno != EINPROGRESS)
321 this->OnError(I_ERR_CONNECT);
323 this->state = I_ERROR;
327 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
328 this->Instance->Timers->AddTimer(this->Timeout);
331 /* CRAQ SMOKING STUFF TO BE FIXED */
332 Instance->SE->NonBlocking(this->fd);
334 this->state = I_CONNECTING;
337 if (!this->Instance->SE->AddFd(this))
339 this->OnError(I_ERR_NOMOREFDS);
341 this->state = I_ERROR;
344 this->SetQueues(this->fd);
347 Instance->Log(DEBUG,"BufferedSocket::DoConnect success");
352 void BufferedSocket::Close()
354 /* Save this, so we dont lose it,
355 * otherise on failure, error messages
356 * might be inaccurate.
361 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
365 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
367 catch (CoreException& modexcept)
369 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
372 Instance->SE->Shutdown(this, 2);
373 if (Instance->SE->Close(this) != -1)
376 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
377 Instance->SocketCull[this] = this;
382 std::string BufferedSocket::GetIP()
387 char* BufferedSocket::Read()
389 if (!Instance->SE->BoundsCheckFd(this))
394 if (this->IsIOHooked)
400 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
402 catch (CoreException& modexcept)
404 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
418 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
421 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
436 void BufferedSocket::MarkAsClosed()
440 // There are two possible outcomes to this function.
441 // It will either write all of the data, or an undefined amount.
442 // If an undefined amount is written the connection has failed
443 // and should be aborted.
444 int BufferedSocket::Write(const std::string &data)
446 /* Try and append the data to the back of the queue, and send it on its way
448 outbuffer.push_back(data);
449 this->Instance->SE->WantWrite(this);
450 return (!this->FlushWriteBuffer());
453 bool BufferedSocket::FlushWriteBuffer()
456 if ((this->fd > -1) && (this->state == I_CONNECTED))
458 if (this->IsIOHooked)
460 while (outbuffer.size() && (errno != EAGAIN))
464 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
465 * implement their own buffering mechanisms
467 Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
468 outbuffer.pop_front();
470 catch (CoreException& modexcept)
472 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
479 /* If we have multiple lines, try to send them all,
480 * not just the first one -- Brain
482 while (outbuffer.size() && (errno != EAGAIN))
485 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
489 if ((unsigned int)result >= outbuffer[0].length())
491 /* The whole block was written (usually a line)
492 * Pop the block off the front of the queue,
493 * dont set errno, because we are clear of errors
494 * and want to try and write the next block too.
496 outbuffer.pop_front();
500 std::string temp = outbuffer[0].substr(result);
502 /* We didnt get the whole line out. arses.
503 * Try again next time, i guess. Set errno,
504 * because we shouldnt be writing any more now,
505 * until the socketengine says its safe to do so.
510 else if (result == 0)
512 this->Instance->SE->DelFd(this);
516 else if ((result == -1) && (errno != EAGAIN))
518 this->OnError(I_ERR_WRITE);
519 this->state = I_ERROR;
520 this->Instance->SE->DelFd(this);
528 if ((errno == EAGAIN) && (fd > -1))
530 this->Instance->SE->WantWrite(this);
536 void SocketTimeout::Tick(time_t)
538 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
541 if (this->sock->state == I_CONNECTING)
543 // for non-listening sockets, the timeout can occur
544 // which causes termination of the connection after
545 // the given number of seconds without a successful
547 this->sock->OnTimeout();
548 this->sock->OnError(I_ERR_TIMEOUT);
549 this->sock->timeout = true;
551 /* NOTE: We must set this AFTER DelFd, as we added
552 * this socket whilst writeable. This means that we
553 * must DELETE the socket whilst writeable too!
555 this->sock->state = I_ERROR;
557 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
558 ServerInstance->SocketCull[this->sock] = this->sock;
561 this->sock->Timeout = NULL;
564 bool BufferedSocket::Poll()
569 if (!Instance->SE->BoundsCheckFd(this))
573 if (Instance->SE->GetRef(this->fd) != this)
579 /* Our socket was in write-state, so delete it and re-add it
585 this->Instance->SE->DelFd(this);
586 if (!this->Instance->SE->AddFd(this))
590 this->SetState(I_CONNECTED);
592 if (Instance->Config->GetIOHook(this))
594 Instance->Log(DEBUG,"Hook for raw connect");
597 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
599 catch (CoreException& modexcept)
601 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
604 return this->OnConnected();
608 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
609 sockaddr* client = new sockaddr[2];
610 length = sizeof (sockaddr_in);
613 if ((!*this->host) || strchr(this->host, ':'))
614 length = sizeof(sockaddr_in6);
616 incoming = Instance->SE->Accept(this, client, &length);
618 if ((!*this->host) || strchr(this->host, ':'))
621 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
625 Instance->SE->NonBlocking(incoming);
627 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
628 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
630 if (this->IsIOHooked)
634 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
636 catch (CoreException& modexcept)
638 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
642 this->SetQueues(incoming);
649 /* Process the read event */
650 return this->OnDataReady();
658 void BufferedSocket::SetState(BufferedSocketState s)
663 BufferedSocketState BufferedSocket::GetState()
668 int BufferedSocket::GetFd()
673 bool BufferedSocket::OnConnected() { return true; }
674 void BufferedSocket::OnError(BufferedSocketError) { return; }
675 int BufferedSocket::OnDisconnect() { return 0; }
676 int BufferedSocket::OnIncomingConnection(int, char*) { return 0; }
677 bool BufferedSocket::OnDataReady() { return true; }
678 bool BufferedSocket::OnWriteReady() { return true; }
679 void BufferedSocket::OnTimeout() { return; }
680 void BufferedSocket::OnClose() { return; }
682 BufferedSocket::~BufferedSocket()
687 Instance->Timers->DelTimer(Timeout);
692 void BufferedSocket::HandleEvent(EventType et, int errornum)
700 this->OnError(I_ERR_TIMEOUT);
704 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
707 this->OnError(I_ERR_BIND);
711 this->OnError(I_ERR_WRITE);
714 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
715 this->Instance->SocketCull[this] = this;
721 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
722 this->Instance->SocketCull[this] = this;
727 if (this->WaitingForWriteEvent)
729 this->WaitingForWriteEvent = false;
730 if (!this->OnWriteReady())
732 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
733 this->Instance->SocketCull[this] = this;
737 if (this->state == I_CONNECTING)
739 /* This might look wrong as if we should be actually calling
740 * with EVENT_WRITE, but trust me it is correct. There are some
741 * writeability-state things in the read code, because of how
742 * BufferedSocket used to work regarding write buffering in previous
743 * versions of InspIRCd. - Brain
745 this->HandleEvent(EVENT_READ);
750 if (this->FlushWriteBuffer())
752 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
753 this->Instance->SocketCull[this] = this;