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;
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->Logs->Log("SOCKET", 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 sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
182 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
184 if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::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, sIP.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(sIP.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);
239 Instance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
243 bool BufferedSocket::DoConnect()
245 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
246 sockaddr* addr = new sockaddr[2];
247 socklen_t size = sizeof(sockaddr_in);
250 if ((!*this->host) || strchr(this->host, ':'))
255 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
256 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
258 if (!this->BindAddr(this->cbindip))
268 this->fd = socket(AF_INET, SOCK_STREAM, 0);
271 if (!this->BindAddr(this->cbindip))
281 this->state = I_ERROR;
282 this->OnError(I_ERR_SOCKET);
291 if (inet_pton(AF_INET6, this->host, &addy) > 0)
293 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
294 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
295 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
296 size = sizeof(sockaddr_in6);
303 if (inet_aton(this->host, &addy) > 0)
305 ((sockaddr_in*)addr)->sin_family = AF_INET;
306 ((sockaddr_in*)addr)->sin_addr = addy;
307 ((sockaddr_in*)addr)->sin_port = htons(this->port);
311 Instance->SE->NonBlocking(this->fd);
314 /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
315 Instance->SE->Blocking(this->fd);
318 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
320 if (errno != EINPROGRESS)
322 this->OnError(I_ERR_CONNECT);
324 this->state = I_ERROR;
328 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
329 this->Instance->Timers->AddTimer(this->Timeout);
332 /* CRAQ SMOKING STUFF TO BE FIXED */
333 Instance->SE->NonBlocking(this->fd);
335 this->state = I_CONNECTING;
338 if (!this->Instance->SE->AddFd(this))
340 this->OnError(I_ERR_NOMOREFDS);
342 this->state = I_ERROR;
345 this->SetQueues(this->fd);
348 Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
353 void BufferedSocket::Close()
355 /* Save this, so we dont lose it,
356 * otherise on failure, error messages
357 * might be inaccurate.
362 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
366 if (this->state != I_LISTENING)
367 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
369 catch (CoreException& modexcept)
371 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
374 Instance->SE->Shutdown(this, 2);
375 if (Instance->SE->Close(this) != -1)
378 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
379 Instance->SocketCull[this] = this;
384 std::string BufferedSocket::GetIP()
389 const char* BufferedSocket::Read()
391 if (!Instance->SE->BoundsCheckFd(this))
395 char* ReadBuffer = Instance->GetReadBuffer();
397 if (this->IsIOHooked)
403 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
405 catch (CoreException& modexcept)
407 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
421 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
425 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
426 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
427 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
428 * --w00t (july 2, 2008)
446 * This function formerly tried to flush write buffer each call.
447 * While admirable in attempting to get the data out to wherever
448 * it is going, on a full socket, it's just going to syscall write() and
449 * EAGAIN constantly, instead of waiting in the SE to know if it can write
450 * which will chew a bit of CPU.
452 * So, now this function returns void (take note) and just adds to the sendq.
454 * It'll get written at a determinate point when the socketengine tells us it can write.
455 * -- w00t (april 1, 2008)
457 void BufferedSocket::Write(const std::string &data)
459 /* Append the data to the back of the queue ready for writing */
460 outbuffer.push_back(data);
462 /* Mark ourselves as wanting write */
463 this->Instance->SE->WantWrite(this);
466 bool BufferedSocket::FlushWriteBuffer()
469 if ((this->fd > -1) && (this->state == I_CONNECTED))
471 if (this->IsIOHooked)
473 while (outbuffer.size() && (errno != EAGAIN))
477 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
478 * implement their own buffering mechanisms
480 Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
481 outbuffer.pop_front();
483 catch (CoreException& modexcept)
485 Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
492 /* If we have multiple lines, try to send them all,
493 * not just the first one -- Brain
495 while (outbuffer.size() && (errno != EAGAIN))
498 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
502 if ((unsigned int)result >= outbuffer[0].length())
504 /* The whole block was written (usually a line)
505 * Pop the block off the front of the queue,
506 * dont set errno, because we are clear of errors
507 * and want to try and write the next block too.
509 outbuffer.pop_front();
513 std::string temp = outbuffer[0].substr(result);
515 /* We didnt get the whole line out. arses.
516 * Try again next time, i guess. Set errno,
517 * because we shouldnt be writing any more now,
518 * until the socketengine says its safe to do so.
523 else if (result == 0)
525 this->Instance->SE->DelFd(this);
529 else if ((result == -1) && (errno != EAGAIN))
531 this->OnError(I_ERR_WRITE);
532 this->state = I_ERROR;
533 this->Instance->SE->DelFd(this);
541 if ((errno == EAGAIN) && (fd > -1))
543 this->Instance->SE->WantWrite(this);
549 void SocketTimeout::Tick(time_t)
551 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
553 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
556 if (this->sock->state == I_CONNECTING)
558 // for non-listening sockets, the timeout can occur
559 // which causes termination of the connection after
560 // the given number of seconds without a successful
562 this->sock->OnTimeout();
563 this->sock->OnError(I_ERR_TIMEOUT);
564 this->sock->timeout = true;
566 /* NOTE: We must set this AFTER DelFd, as we added
567 * this socket whilst writeable. This means that we
568 * must DELETE the socket whilst writeable too!
570 this->sock->state = I_ERROR;
572 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
573 ServerInstance->SocketCull[this->sock] = this->sock;
576 this->sock->Timeout = NULL;
579 bool BufferedSocket::Poll()
584 if (!Instance->SE->BoundsCheckFd(this))
588 if (Instance->SE->GetRef(this->fd) != this)
594 /* Our socket was in write-state, so delete it and re-add it
600 this->Instance->SE->DelFd(this);
601 if (!this->Instance->SE->AddFd(this))
605 this->SetState(I_CONNECTED);
607 if (Instance->Config->GetIOHook(this))
609 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
612 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
614 catch (CoreException& modexcept)
616 Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
619 return this->OnConnected();
623 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
624 sockaddr* client = new sockaddr[2];
625 length = sizeof (sockaddr_in);
628 if ((!*this->host) || strchr(this->host, ':'))
629 length = sizeof(sockaddr_in6);
631 incoming = Instance->SE->Accept(this, client, &length);
633 if ((!*this->host) || strchr(this->host, ':'))
636 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
641 // FIX: we were doing this for IPv6 connections as well, which was fucking recvip..
642 // Add brackets to make this a bit clearer. -- w00t (Jan 15, 2008)
643 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
646 Instance->SE->NonBlocking(incoming);
648 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
650 if (this->IsIOHooked)
654 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
656 catch (CoreException& modexcept)
658 Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
662 this->SetQueues(incoming);
669 /* Process the read event */
670 return this->OnDataReady();
678 void BufferedSocket::SetState(BufferedSocketState s)
683 BufferedSocketState BufferedSocket::GetState()
688 int BufferedSocket::GetFd()
693 bool BufferedSocket::OnConnected() { return true; }
694 void BufferedSocket::OnError(BufferedSocketError) { return; }
695 int BufferedSocket::OnDisconnect() { return 0; }
696 int BufferedSocket::OnIncomingConnection(int, char*) { return 0; }
697 bool BufferedSocket::OnDataReady() { return true; }
698 bool BufferedSocket::OnWriteReady() { return true; }
699 void BufferedSocket::OnTimeout() { return; }
700 void BufferedSocket::OnClose() { return; }
702 BufferedSocket::~BufferedSocket()
707 Instance->Timers->DelTimer(Timeout);
712 void BufferedSocket::HandleEvent(EventType et, int errornum)
720 this->OnError(I_ERR_TIMEOUT);
724 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
727 this->OnError(I_ERR_BIND);
731 this->OnError(I_ERR_WRITE);
734 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
735 this->Instance->SocketCull[this] = this;
741 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
742 this->Instance->SocketCull[this] = this;
747 if (this->WaitingForWriteEvent)
749 this->WaitingForWriteEvent = false;
750 if (!this->OnWriteReady())
752 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
753 this->Instance->SocketCull[this] = this;
757 if (this->state == I_CONNECTING)
759 /* This might look wrong as if we should be actually calling
760 * with EVENT_WRITE, but trust me it is correct. There are some
761 * writeability-state things in the read code, because of how
762 * BufferedSocket used to work regarding write buffering in previous
763 * versions of InspIRCd. - Brain
765 this->HandleEvent(EVENT_READ);
770 if (this->FlushWriteBuffer())
772 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
773 this->Instance->SocketCull[this] = this;