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)))
154 this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
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 IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
179 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
181 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (!IP.empty()) && (IP != "::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, IP.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(IP.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);
239 bool BufferedSocket::DoConnect()
241 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
242 sockaddr* addr = new sockaddr[2];
243 socklen_t size = sizeof(sockaddr_in);
246 if ((!*this->host) || strchr(this->host, ':'))
251 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
252 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
254 if (!this->BindAddr(this->cbindip))
264 this->fd = socket(AF_INET, SOCK_STREAM, 0);
267 if (!this->BindAddr(this->cbindip))
277 this->state = I_ERROR;
278 this->OnError(I_ERR_SOCKET);
287 if (inet_pton(AF_INET6, this->host, &addy) > 0)
289 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
290 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
291 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
292 size = sizeof(sockaddr_in6);
299 if (inet_aton(this->host, &addy) > 0)
301 ((sockaddr_in*)addr)->sin_family = AF_INET;
302 ((sockaddr_in*)addr)->sin_addr = addy;
303 ((sockaddr_in*)addr)->sin_port = htons(this->port);
307 Instance->SE->NonBlocking(this->fd);
310 /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
311 Instance->SE->Blocking(this->fd);
314 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
316 if (errno != EINPROGRESS)
318 this->OnError(I_ERR_CONNECT);
320 this->state = I_ERROR;
324 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
325 this->Instance->Timers->AddTimer(this->Timeout);
328 /* CRAQ SMOKING STUFF TO BE FIXED */
329 Instance->SE->NonBlocking(this->fd);
331 this->state = I_CONNECTING;
334 if (!this->Instance->SE->AddFd(this))
336 this->OnError(I_ERR_NOMOREFDS);
338 this->state = I_ERROR;
341 this->SetQueues(this->fd);
347 void BufferedSocket::Close()
349 /* Save this, so we dont lose it,
350 * otherise on failure, error messages
351 * might be inaccurate.
356 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
360 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
362 catch (CoreException& modexcept)
364 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
367 Instance->SE->Shutdown(this, 2);
368 if (Instance->SE->Close(this) != -1)
371 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
372 Instance->SocketCull[this] = this;
377 std::string BufferedSocket::GetIP()
382 char* BufferedSocket::Read()
384 if (!Instance->SE->BoundsCheckFd(this))
389 if (this->IsIOHooked)
395 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
397 catch (CoreException& modexcept)
399 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
413 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
416 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
431 void BufferedSocket::MarkAsClosed()
435 // There are two possible outcomes to this function.
436 // It will either write all of the data, or an undefined amount.
437 // If an undefined amount is written the connection has failed
438 // and should be aborted.
439 int BufferedSocket::Write(const std::string &data)
441 /* Try and append the data to the back of the queue, and send it on its way
443 outbuffer.push_back(data);
444 this->Instance->SE->WantWrite(this);
445 return (!this->FlushWriteBuffer());
448 bool BufferedSocket::FlushWriteBuffer()
451 if ((this->fd > -1) && (this->state == I_CONNECTED))
453 if (this->IsIOHooked)
455 while (outbuffer.size() && (errno != EAGAIN))
459 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
460 * implement their own buffering mechanisms
462 Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
463 outbuffer.pop_front();
465 catch (CoreException& modexcept)
467 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
474 /* If we have multiple lines, try to send them all,
475 * not just the first one -- Brain
477 while (outbuffer.size() && (errno != EAGAIN))
480 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
484 if ((unsigned int)result >= outbuffer[0].length())
486 /* The whole block was written (usually a line)
487 * Pop the block off the front of the queue,
488 * dont set errno, because we are clear of errors
489 * and want to try and write the next block too.
491 outbuffer.pop_front();
495 std::string temp = outbuffer[0].substr(result);
497 /* We didnt get the whole line out. arses.
498 * Try again next time, i guess. Set errno,
499 * because we shouldnt be writing any more now,
500 * until the socketengine says its safe to do so.
505 else if (result == 0)
507 this->Instance->SE->DelFd(this);
511 else if ((result == -1) && (errno != EAGAIN))
513 this->OnError(I_ERR_WRITE);
514 this->state = I_ERROR;
515 this->Instance->SE->DelFd(this);
523 if ((errno == EAGAIN) && (fd > -1))
525 this->Instance->SE->WantWrite(this);
531 void SocketTimeout::Tick(time_t now)
533 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
536 if (this->sock->state == I_CONNECTING)
538 // for non-listening sockets, the timeout can occur
539 // which causes termination of the connection after
540 // the given number of seconds without a successful
542 this->sock->OnTimeout();
543 this->sock->OnError(I_ERR_TIMEOUT);
544 this->sock->timeout = true;
546 /* NOTE: We must set this AFTER DelFd, as we added
547 * this socket whilst writeable. This means that we
548 * must DELETE the socket whilst writeable too!
550 this->sock->state = I_ERROR;
552 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
553 ServerInstance->SocketCull[this->sock] = this->sock;
556 this->sock->Timeout = NULL;
559 bool BufferedSocket::Poll()
564 if (!Instance->SE->BoundsCheckFd(this))
568 if (Instance->SE->GetRef(this->fd) != this)
574 /* Our socket was in write-state, so delete it and re-add it
580 this->Instance->SE->DelFd(this);
581 if (!this->Instance->SE->AddFd(this))
585 this->SetState(I_CONNECTED);
587 if (Instance->Config->GetIOHook(this))
589 Instance->Log(DEBUG,"Hook for raw connect");
592 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
594 catch (CoreException& modexcept)
596 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
599 return this->OnConnected();
603 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
604 sockaddr* client = new sockaddr[2];
605 length = sizeof (sockaddr_in);
608 if ((!*this->host) || strchr(this->host, ':'))
609 length = sizeof(sockaddr_in6);
611 incoming = Instance->SE->Accept(this, client, &length);
613 if ((!*this->host) || strchr(this->host, ':'))
616 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
620 Instance->SE->NonBlocking(incoming);
622 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
623 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
625 if (this->IsIOHooked)
629 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
631 catch (CoreException& modexcept)
633 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
637 this->SetQueues(incoming);
644 /* Process the read event */
645 return this->OnDataReady();
653 void BufferedSocket::SetState(BufferedSocketState s)
658 BufferedSocketState BufferedSocket::GetState()
663 int BufferedSocket::GetFd()
668 bool BufferedSocket::OnConnected() { return true; }
669 void BufferedSocket::OnError(BufferedSocketError e) { return; }
670 int BufferedSocket::OnDisconnect() { return 0; }
671 int BufferedSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
672 bool BufferedSocket::OnDataReady() { return true; }
673 bool BufferedSocket::OnWriteReady() { return true; }
674 void BufferedSocket::OnTimeout() { return; }
675 void BufferedSocket::OnClose() { return; }
677 BufferedSocket::~BufferedSocket()
682 Instance->Timers->DelTimer(Timeout);
687 void BufferedSocket::HandleEvent(EventType et, int errornum)
695 this->OnError(I_ERR_TIMEOUT);
699 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
702 this->OnError(I_ERR_BIND);
706 this->OnError(I_ERR_WRITE);
709 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
710 this->Instance->SocketCull[this] = this;
716 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
717 this->Instance->SocketCull[this] = this;
722 if (this->WaitingForWriteEvent)
724 this->WaitingForWriteEvent = false;
725 if (!this->OnWriteReady())
727 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
728 this->Instance->SocketCull[this] = this;
732 if (this->state == I_CONNECTING)
734 /* This might look wrong as if we should be actually calling
735 * with EVENT_WRITE, but trust me it is correct. There are some
736 * writeability-state things in the read code, because of how
737 * BufferedSocket used to work regarding write buffering in previous
738 * versions of InspIRCd. - Brain
740 this->HandleEvent(EVENT_READ);
745 if (this->FlushWriteBuffer())
747 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
748 this->Instance->SocketCull[this] = this;