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 "configreader.h"
16 #include "inspstring.h"
17 #include "socketengine.h"
20 using irc::sockets::OpenTCPSocket;
22 bool InspSocket::Readable()
24 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
27 InspSocket::InspSocket(InspIRCd* SI)
30 this->state = I_DISCONNECTED;
32 this->WaitingForWriteEvent = false;
34 this->IsIOHooked = false;
37 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
41 this->state = I_CONNECTED;
42 strlcpy(this->IP,ip,MAXBUF);
43 this->WaitingForWriteEvent = false;
45 this->IsIOHooked = false;
47 this->Instance->SE->AddFd(this);
50 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime, const std::string &connectbindip)
52 this->cbindip = connectbindip;
55 strlcpy(host,ipaddr.c_str(),MAXBUF);
56 this->WaitingForWriteEvent = false;
57 this->IsIOHooked = false;
61 if ((this->fd = OpenTCPSocket(host)) == ERROR)
64 this->state = I_ERROR;
65 this->OnError(I_ERR_SOCKET);
70 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
74 this->state = I_ERROR;
75 this->OnError(I_ERR_BIND);
76 this->ClosePending = true;
81 this->state = I_LISTENING;
85 if (!this->Instance->SE->AddFd(this))
88 this->state = I_ERROR;
89 this->OnError(I_ERR_NOMOREFDS);
98 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
103 if (strchr(host,':'))
106 if (inet_pton(AF_INET6, host, &n) < 1)
113 if (inet_aton(host,&n) < 1)
118 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
119 this->OnError(I_ERR_CONNECT);
122 this->state = I_ERROR;
127 strlcpy(this->IP,host,MAXBUF);
128 timeout_val = maxtime;
129 if (!this->DoConnect())
131 this->OnError(I_ERR_CONNECT);
134 this->state = I_ERROR;
141 void InspSocket::WantWrite()
143 this->Instance->SE->WantWrite(this);
144 this->WaitingForWriteEvent = true;
147 void InspSocket::SetQueues(int nfd)
149 // attempt to increase socket sendq and recvq as high as its possible
152 if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
153 this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
156 /* Most irc servers require you to specify the ip you want to bind to.
157 * If you dont specify an IP, they rather dumbly bind to the first IP
158 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
159 * addresses we've bound server ports to, and we try and bind our outbound
160 * connections to the first usable non-loopback and non-any IP we find.
161 * This is easier to configure when you have a lot of links and a lot
162 * of servers to configure.
164 bool InspSocket::BindAddr(const std::string &ip)
166 ConfigReader Conf(this->Instance);
167 socklen_t size = sizeof(sockaddr_in);
170 /* Are we looking for a binding to fit an ipv6 host? */
171 if ((ip.empty()) || (ip.find(':') != std::string::npos))
175 while (j < Conf.Enumerate("bind") || (!ip.empty()))
177 std::string IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
178 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
180 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (!IP.empty()) && (IP != "::1")))
182 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
183 sockaddr* s = new sockaddr[2];
188 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
190 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
191 ((sockaddr_in6*)s)->sin6_port = 0;
192 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
193 size = sizeof(sockaddr_in6);
206 if (inet_aton(IP.c_str(), &n) > 0)
208 ((sockaddr_in*)s)->sin_addr = n;
209 ((sockaddr_in*)s)->sin_port = 0;
210 ((sockaddr_in*)s)->sin_family = AF_INET;
220 if (bind(this->fd, s, size) < 0)
222 this->state = I_ERROR;
223 this->OnError(I_ERR_BIND);
238 bool InspSocket::DoConnect()
240 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
241 sockaddr* addr = new sockaddr[2];
242 socklen_t size = sizeof(sockaddr_in);
245 if ((!*this->host) || strchr(this->host, ':'))
250 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
251 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
253 if (!this->BindAddr(this->cbindip))
263 this->fd = socket(AF_INET, SOCK_STREAM, 0);
266 if (!this->BindAddr(this->cbindip))
276 this->state = I_ERROR;
277 this->OnError(I_ERR_SOCKET);
286 if (inet_pton(AF_INET6, this->host, &addy) > 0)
288 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
289 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
290 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
291 size = sizeof(sockaddr_in6);
298 if (inet_aton(this->host, &addy) > 0)
300 ((sockaddr_in*)addr)->sin_family = AF_INET;
301 ((sockaddr_in*)addr)->sin_addr = addy;
302 ((sockaddr_in*)addr)->sin_port = htons(this->port);
306 int flags = fcntl(this->fd, F_GETFL, 0);
307 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
309 unsigned long flags = 0;
310 ioctlsocket(this->fd, FIONBIO, &flags);
312 if (connect(this->fd, (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 /* Set nonblocking mode after the connect() call */
328 ioctlsocket(this->fd, FIONBIO, &flags);
330 this->state = I_CONNECTING;
333 if (!this->Instance->SE->AddFd(this))
335 this->OnError(I_ERR_NOMOREFDS);
337 this->state = I_ERROR;
340 this->SetQueues(this->fd);
346 void InspSocket::Close()
348 /* Save this, so we dont lose it,
349 * otherise on failure, error messages
350 * might be inaccurate.
355 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
359 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
361 catch (CoreException& modexcept)
363 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
366 shutdown(this->fd,2);
367 if (close(this->fd) != -1)
370 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
371 Instance->SocketCull[this] = this;
376 std::string InspSocket::GetIP()
381 char* InspSocket::Read()
383 if (!Instance->SE->BoundsCheckFd(this))
388 if (this->IsIOHooked)
394 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
396 catch (CoreException& modexcept)
398 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
412 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
415 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
430 void InspSocket::MarkAsClosed()
434 // There are two possible outcomes to this function.
435 // It will either write all of the data, or an undefined amount.
436 // If an undefined amount is written the connection has failed
437 // and should be aborted.
438 int InspSocket::Write(const std::string &data)
440 /* Try and append the data to the back of the queue, and send it on its way
442 outbuffer.push_back(data);
443 this->Instance->SE->WantWrite(this);
444 return (!this->FlushWriteBuffer());
447 bool InspSocket::FlushWriteBuffer()
450 if ((this->fd > -1) && (this->state == I_CONNECTED))
452 if (this->IsIOHooked)
454 while (outbuffer.size() && (errno != EAGAIN))
458 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
459 * implement their own buffering mechanisms
461 Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
462 outbuffer.pop_front();
464 catch (CoreException& modexcept)
466 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
473 /* If we have multiple lines, try to send them all,
474 * not just the first one -- Brain
476 while (outbuffer.size() && (errno != EAGAIN))
480 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
482 int result = send(this->fd,outbuffer[0].c_str(),outbuffer[0].length(), 0);
486 if ((unsigned int)result >= outbuffer[0].length())
488 /* The whole block was written (usually a line)
489 * Pop the block off the front of the queue,
490 * dont set errno, because we are clear of errors
491 * and want to try and write the next block too.
493 outbuffer.pop_front();
497 std::string temp = outbuffer[0].substr(result);
499 /* We didnt get the whole line out. arses.
500 * Try again next time, i guess. Set errno,
501 * because we shouldnt be writing any more now,
502 * until the socketengine says its safe to do so.
507 else if ((result == -1) && (errno != EAGAIN))
509 this->OnError(I_ERR_WRITE);
510 this->state = I_ERROR;
511 this->Instance->SE->DelFd(this);
519 if ((errno == EAGAIN) && (fd > -1))
521 this->Instance->SE->WantWrite(this);
527 void SocketTimeout::Tick(time_t now)
529 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
532 if (this->sock->state == I_CONNECTING)
534 // for non-listening sockets, the timeout can occur
535 // which causes termination of the connection after
536 // the given number of seconds without a successful
538 this->sock->OnTimeout();
539 this->sock->OnError(I_ERR_TIMEOUT);
540 this->sock->timeout = true;
542 /* NOTE: We must set this AFTER DelFd, as we added
543 * this socket whilst writeable. This means that we
544 * must DELETE the socket whilst writeable too!
546 this->sock->state = I_ERROR;
548 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
549 ServerInstance->SocketCull[this->sock] = this->sock;
552 this->sock->Timeout = NULL;
555 bool InspSocket::Poll()
560 if (!Instance->SE->BoundsCheckFd(this))
564 if (Instance->SE->GetRef(this->fd) != this)
570 /* Our socket was in write-state, so delete it and re-add it
576 this->Instance->SE->DelFd(this);
577 if (!this->Instance->SE->AddFd(this))
581 this->SetState(I_CONNECTED);
583 if (Instance->Config->GetIOHook(this))
585 Instance->Log(DEBUG,"Hook for raw connect");
588 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
590 catch (CoreException& modexcept)
592 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
595 return this->OnConnected();
599 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
600 sockaddr* client = new sockaddr[2];
601 length = sizeof (sockaddr_in);
604 if ((!*this->host) || strchr(this->host, ':'))
605 length = sizeof(sockaddr_in6);
607 void* m_acceptEvent = NULL;
608 GetExt("windows_acceptevent", m_acceptEvent);
609 incoming = _accept (this->fd, client, &length);
611 if ((!*this->host) || strchr(this->host, ':'))
614 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
618 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
619 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
621 if (this->IsIOHooked)
625 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
627 catch (CoreException& modexcept)
629 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
633 this->SetQueues(incoming);
640 /* Process the read event */
641 return this->OnDataReady();
649 void InspSocket::SetState(InspSocketState s)
654 InspSocketState InspSocket::GetState()
659 int InspSocket::GetFd()
664 bool InspSocket::OnConnected() { return true; }
665 void InspSocket::OnError(InspSocketError e) { return; }
666 int InspSocket::OnDisconnect() { return 0; }
667 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
668 bool InspSocket::OnDataReady() { return true; }
669 bool InspSocket::OnWriteReady() { return true; }
670 void InspSocket::OnTimeout() { return; }
671 void InspSocket::OnClose() { return; }
673 InspSocket::~InspSocket()
678 Instance->Timers->DelTimer(Timeout);
683 void InspSocket::HandleEvent(EventType et, int errornum)
691 this->OnError(I_ERR_TIMEOUT);
695 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
698 this->OnError(I_ERR_BIND);
702 this->OnError(I_ERR_WRITE);
705 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
706 this->Instance->SocketCull[this] = this;
712 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
713 this->Instance->SocketCull[this] = this;
718 if (this->WaitingForWriteEvent)
720 this->WaitingForWriteEvent = false;
721 if (!this->OnWriteReady())
723 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
724 this->Instance->SocketCull[this] = this;
728 if (this->state == I_CONNECTING)
730 /* This might look wrong as if we should be actually calling
731 * with EVENT_WRITE, but trust me it is correct. There are some
732 * writeability-state things in the read code, because of how
733 * InspSocket used to work regarding write buffering in previous
734 * versions of InspIRCd. - Brain
736 this->HandleEvent(EVENT_READ);
741 if (this->FlushWriteBuffer())
743 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
744 this->Instance->SocketCull[this] = this;