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 * ---------------------------------------------------
15 #include "inspstring.h"
16 #include "socketengine.h"
19 using irc::sockets::OpenTCPSocket;
21 bool BufferedSocket::Readable()
23 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
29 this->state = I_DISCONNECTED;
31 this->WaitingForWriteEvent = false;
33 this->IsIOHooked = false;
36 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
40 this->state = I_CONNECTED;
41 strlcpy(this->IP,ip,MAXBUF);
42 this->WaitingForWriteEvent = false;
44 this->IsIOHooked = 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;
56 this->IsIOHooked = false;
60 if ((this->fd = OpenTCPSocket(host)) == ERROR)
63 this->state = I_ERROR;
64 this->OnError(I_ERR_SOCKET);
69 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
73 this->state = I_ERROR;
74 this->OnError(I_ERR_BIND);
75 this->ClosePending = true;
80 this->state = I_LISTENING;
84 if (!this->Instance->SE->AddFd(this))
87 this->state = I_ERROR;
88 this->OnError(I_ERR_NOMOREFDS);
97 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
102 if (strchr(host,':'))
105 if (inet_pton(AF_INET6, host, &n) < 1)
112 if (inet_aton(host,&n) < 1)
117 this->Instance->Log(DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
118 this->OnError(I_ERR_CONNECT);
121 this->state = I_ERROR;
126 strlcpy(this->IP,host,MAXBUF);
127 timeout_val = maxtime;
128 if (!this->DoConnect())
130 this->OnError(I_ERR_CONNECT);
133 this->state = I_ERROR;
140 void BufferedSocket::WantWrite()
142 this->Instance->SE->WantWrite(this);
143 this->WaitingForWriteEvent = true;
146 void BufferedSocket::SetQueues(int nfd)
148 // attempt to increase socket sendq and recvq as high as its possible
151 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());
155 /* Most irc servers require you to specify the ip you want to bind to.
156 * If you dont specify an IP, they rather dumbly bind to the first IP
157 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
158 * addresses we've bound server ports to, and we try and bind our outbound
159 * connections to the first usable non-loopback and non-any IP we find.
160 * This is easier to configure when you have a lot of links and a lot
161 * of servers to configure.
163 bool BufferedSocket::BindAddr(const std::string &ip)
165 ConfigReader Conf(this->Instance);
166 socklen_t size = sizeof(sockaddr_in);
169 /* Are we looking for a binding to fit an ipv6 host? */
170 if ((ip.empty()) || (ip.find(':') != std::string::npos))
174 while (j < Conf.Enumerate("bind") || (!ip.empty()))
176 std::string IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
177 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
179 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (!IP.empty()) && (IP != "::1")))
181 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
182 sockaddr* s = new sockaddr[2];
187 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
189 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
190 ((sockaddr_in6*)s)->sin6_port = 0;
191 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
192 size = sizeof(sockaddr_in6);
205 if (inet_aton(IP.c_str(), &n) > 0)
207 ((sockaddr_in*)s)->sin_addr = n;
208 ((sockaddr_in*)s)->sin_port = 0;
209 ((sockaddr_in*)s)->sin_family = AF_INET;
219 if (Instance->SE->Bind(this->fd, s, size) < 0)
221 this->state = I_ERROR;
222 this->OnError(I_ERR_BIND);
237 bool BufferedSocket::DoConnect()
239 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
240 sockaddr* addr = new sockaddr[2];
241 socklen_t size = sizeof(sockaddr_in);
244 if ((!*this->host) || strchr(this->host, ':'))
249 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
250 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
252 if (!this->BindAddr(this->cbindip))
262 this->fd = socket(AF_INET, SOCK_STREAM, 0);
265 if (!this->BindAddr(this->cbindip))
275 this->state = I_ERROR;
276 this->OnError(I_ERR_SOCKET);
285 if (inet_pton(AF_INET6, this->host, &addy) > 0)
287 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
288 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
289 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
290 size = sizeof(sockaddr_in6);
297 if (inet_aton(this->host, &addy) > 0)
299 ((sockaddr_in*)addr)->sin_family = AF_INET;
300 ((sockaddr_in*)addr)->sin_addr = addy;
301 ((sockaddr_in*)addr)->sin_port = htons(this->port);
305 Instance->SE->NonBlocking(this->fd);
308 /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
309 Instance->SE->Blocking(this->fd);
312 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
314 if (errno != EINPROGRESS)
316 this->OnError(I_ERR_CONNECT);
318 this->state = I_ERROR;
322 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
323 this->Instance->Timers->AddTimer(this->Timeout);
326 /* CRAQ SMOKING STUFF TO BE FIXED */
327 Instance->SE->NonBlocking(this->fd);
329 this->state = I_CONNECTING;
332 if (!this->Instance->SE->AddFd(this))
334 this->OnError(I_ERR_NOMOREFDS);
336 this->state = I_ERROR;
339 this->SetQueues(this->fd);
345 void BufferedSocket::Close()
347 /* Save this, so we dont lose it,
348 * otherise on failure, error messages
349 * might be inaccurate.
354 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
358 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
360 catch (CoreException& modexcept)
362 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
365 Instance->SE->Shutdown(this, 2);
366 if (Instance->SE->Close(this) != -1)
369 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
370 Instance->SocketCull[this] = this;
375 std::string BufferedSocket::GetIP()
380 char* BufferedSocket::Read()
382 if (!Instance->SE->BoundsCheckFd(this))
387 if (this->IsIOHooked)
393 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
395 catch (CoreException& modexcept)
397 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
411 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
414 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
429 void BufferedSocket::MarkAsClosed()
433 // There are two possible outcomes to this function.
434 // It will either write all of the data, or an undefined amount.
435 // If an undefined amount is written the connection has failed
436 // and should be aborted.
437 int BufferedSocket::Write(const std::string &data)
439 /* Try and append the data to the back of the queue, and send it on its way
441 outbuffer.push_back(data);
442 this->Instance->SE->WantWrite(this);
443 return (!this->FlushWriteBuffer());
446 bool BufferedSocket::FlushWriteBuffer()
449 if ((this->fd > -1) && (this->state == I_CONNECTED))
451 if (this->IsIOHooked)
453 while (outbuffer.size() && (errno != EAGAIN))
457 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
458 * implement their own buffering mechanisms
460 Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
461 outbuffer.pop_front();
463 catch (CoreException& modexcept)
465 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
472 /* If we have multiple lines, try to send them all,
473 * not just the first one -- Brain
475 while (outbuffer.size() && (errno != EAGAIN))
478 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
482 if ((unsigned int)result >= outbuffer[0].length())
484 /* The whole block was written (usually a line)
485 * Pop the block off the front of the queue,
486 * dont set errno, because we are clear of errors
487 * and want to try and write the next block too.
489 outbuffer.pop_front();
493 std::string temp = outbuffer[0].substr(result);
495 /* We didnt get the whole line out. arses.
496 * Try again next time, i guess. Set errno,
497 * because we shouldnt be writing any more now,
498 * until the socketengine says its safe to do so.
503 else if (result == 0)
505 this->Instance->SE->DelFd(this);
509 else if ((result == -1) && (errno != EAGAIN))
511 this->OnError(I_ERR_WRITE);
512 this->state = I_ERROR;
513 this->Instance->SE->DelFd(this);
521 if ((errno == EAGAIN) && (fd > -1))
523 this->Instance->SE->WantWrite(this);
529 void SocketTimeout::Tick(time_t now)
531 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
534 if (this->sock->state == I_CONNECTING)
536 // for non-listening sockets, the timeout can occur
537 // which causes termination of the connection after
538 // the given number of seconds without a successful
540 this->sock->OnTimeout();
541 this->sock->OnError(I_ERR_TIMEOUT);
542 this->sock->timeout = true;
544 /* NOTE: We must set this AFTER DelFd, as we added
545 * this socket whilst writeable. This means that we
546 * must DELETE the socket whilst writeable too!
548 this->sock->state = I_ERROR;
550 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
551 ServerInstance->SocketCull[this->sock] = this->sock;
554 this->sock->Timeout = NULL;
557 bool BufferedSocket::Poll()
562 if (!Instance->SE->BoundsCheckFd(this))
566 if (Instance->SE->GetRef(this->fd) != this)
572 /* Our socket was in write-state, so delete it and re-add it
578 this->Instance->SE->DelFd(this);
579 if (!this->Instance->SE->AddFd(this))
583 this->SetState(I_CONNECTED);
585 if (Instance->Config->GetIOHook(this))
587 Instance->Log(DEBUG,"Hook for raw connect");
590 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
592 catch (CoreException& modexcept)
594 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
597 return this->OnConnected();
601 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
602 sockaddr* client = new sockaddr[2];
603 length = sizeof (sockaddr_in);
606 if ((!*this->host) || strchr(this->host, ':'))
607 length = sizeof(sockaddr_in6);
609 incoming = Instance->SE->Accept(this, client, &length);
611 if ((!*this->host) || strchr(this->host, ':'))
614 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
618 Instance->SE->NonBlocking(incoming);
620 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
621 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
623 if (this->IsIOHooked)
627 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
629 catch (CoreException& modexcept)
631 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
635 this->SetQueues(incoming);
642 /* Process the read event */
643 return this->OnDataReady();
651 void BufferedSocket::SetState(BufferedSocketState s)
656 BufferedSocketState BufferedSocket::GetState()
661 int BufferedSocket::GetFd()
666 bool BufferedSocket::OnConnected() { return true; }
667 void BufferedSocket::OnError(BufferedSocketError e) { return; }
668 int BufferedSocket::OnDisconnect() { return 0; }
669 int BufferedSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
670 bool BufferedSocket::OnDataReady() { return true; }
671 bool BufferedSocket::OnWriteReady() { return true; }
672 void BufferedSocket::OnTimeout() { return; }
673 void BufferedSocket::OnClose() { return; }
675 BufferedSocket::~BufferedSocket()
680 Instance->Timers->DelTimer(Timeout);
685 void BufferedSocket::HandleEvent(EventType et, int errornum)
693 this->OnError(I_ERR_TIMEOUT);
697 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
700 this->OnError(I_ERR_BIND);
704 this->OnError(I_ERR_WRITE);
707 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
708 this->Instance->SocketCull[this] = this;
714 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
715 this->Instance->SocketCull[this] = this;
720 if (this->WaitingForWriteEvent)
722 this->WaitingForWriteEvent = false;
723 if (!this->OnWriteReady())
725 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
726 this->Instance->SocketCull[this] = this;
730 if (this->state == I_CONNECTING)
732 /* This might look wrong as if we should be actually calling
733 * with EVENT_WRITE, but trust me it is correct. There are some
734 * writeability-state things in the read code, because of how
735 * BufferedSocket used to work regarding write buffering in previous
736 * versions of InspIRCd. - Brain
738 this->HandleEvent(EVENT_READ);
743 if (this->FlushWriteBuffer())
745 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
746 this->Instance->SocketCull[this] = this;