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;
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)
111 if (inet_aton(host,&n) < 1)
116 if (inet_aton(host,&n) < 1)
121 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
122 this->OnError(I_ERR_CONNECT);
125 this->state = I_ERROR;
130 strlcpy(this->IP,host,MAXBUF);
131 timeout_val = maxtime;
132 if (!this->DoConnect())
134 this->OnError(I_ERR_CONNECT);
137 this->state = I_ERROR;
144 void InspSocket::WantWrite()
146 this->Instance->SE->WantWrite(this);
147 this->WaitingForWriteEvent = true;
150 void InspSocket::SetQueues(int nfd)
152 // attempt to increase socket sendq and recvq as high as its possible
155 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
156 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf));
159 /* Most irc servers require you to specify the ip you want to bind to.
160 * If you dont specify an IP, they rather dumbly bind to the first IP
161 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
162 * addresses we've bound server ports to, and we try and bind our outbound
163 * connections to the first usable non-loopback and non-any IP we find.
164 * This is easier to configure when you have a lot of links and a lot
165 * of servers to configure.
167 bool InspSocket::BindAddr(const std::string &ip)
169 ConfigReader Conf(this->Instance);
170 socklen_t size = sizeof(sockaddr_in);
173 /* Are we looking for a binding to fit an ipv6 host? */
174 if ((ip.empty()) || (ip.find(':') != std::string::npos))
178 while (j < Conf.Enumerate("bind") || (!ip.empty()))
180 std::string IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
181 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
183 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (IP != "") && (IP != "::1")))
185 sockaddr* s = new sockaddr[2];
190 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
192 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
193 ((sockaddr_in6*)s)->sin6_port = 0;
194 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
195 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;
222 if (insp_aton(IP.c_str(), &n) > 0)
224 ((sockaddr_in*)s)->sin_addr = n;
225 ((sockaddr_in*)s)->sin_port = 0;
226 ((sockaddr_in*)s)->sin_family = AF_INET;
236 if (bind(this->fd, s, size) < 0)
238 this->state = I_ERROR;
239 this->OnError(I_ERR_BIND);
254 bool InspSocket::DoConnect()
256 sockaddr* addr = new sockaddr[2];
257 socklen_t size = sizeof(sockaddr_in);
260 if ((!*this->host) || strchr(this->host, ':'))
265 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
266 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
268 if (!this->BindAddr(this->cbindip))
277 this->fd = socket(AF_INET, SOCK_STREAM, 0);
280 if (!this->BindAddr(this->cbindip))
288 this->fd = socket(AF_INET, SOCK_STREAM, 0);
291 if (!this->BindAddr(this->cbindip))
301 this->state = I_ERROR;
302 this->OnError(I_ERR_SOCKET);
311 if (inet_pton(AF_INET6, this->host, &addy) > 0)
313 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
314 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
315 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
316 size = sizeof(sockaddr_in6);
322 if (inet_aton(this->host, &addy) > 0)
324 ((sockaddr_in*)addr)->sin_family = AF_INET;
325 ((sockaddr_in*)addr)->sin_addr = addy;
326 ((sockaddr_in*)addr)->sin_port = htons(this->port);
331 if (inet_aton(this->host, &addy) > 0)
333 ((sockaddr_in*)addr)->sin_family = AF_INET;
334 ((sockaddr_in*)addr)->sin_addr = addy;
335 ((sockaddr_in*)addr)->sin_port = htons(this->port);
339 int flags = fcntl(this->fd, F_GETFL, 0);
340 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
342 unsigned long flags = 0;
343 ioctlsocket(this->fd, FIONBIO, &flags);
345 if (connect(this->fd, (sockaddr*)addr, size) == -1)
347 if (errno != EINPROGRESS)
349 this->OnError(I_ERR_CONNECT);
351 this->state = I_ERROR;
355 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
356 this->Instance->Timers->AddTimer(this->Timeout);
358 this->state = I_CONNECTING;
361 if (!this->Instance->SE->AddFd(this))
363 this->OnError(I_ERR_NOMOREFDS);
365 this->state = I_ERROR;
368 this->SetQueues(this->fd);
374 void InspSocket::Close()
376 /* Save this, so we dont lose it,
377 * otherise on failure, error messages
378 * might be inaccurate.
383 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
387 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
389 catch (CoreException& modexcept)
391 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
395 shutdown(this->fd,2);
401 std::string InspSocket::GetIP()
406 char* InspSocket::Read()
409 if ((fd < 0) || (m_internalFd > MAX_DESCRIPTORS))
411 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
417 if (this->IsIOHooked)
423 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
425 catch (CoreException& modexcept)
427 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
441 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
444 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
459 void InspSocket::MarkAsClosed()
463 // There are two possible outcomes to this function.
464 // It will either write all of the data, or an undefined amount.
465 // If an undefined amount is written the connection has failed
466 // and should be aborted.
467 int InspSocket::Write(const std::string &data)
469 /* Try and append the data to the back of the queue, and send it on its way
471 outbuffer.push_back(data);
472 this->Instance->SE->WantWrite(this);
473 return (!this->FlushWriteBuffer());
476 bool InspSocket::FlushWriteBuffer()
479 if ((this->fd > -1) && (this->state == I_CONNECTED))
481 if (this->IsIOHooked)
483 while (outbuffer.size() && (errno != EAGAIN))
487 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
490 if ((unsigned int)result >= outbuffer[0].length())
492 outbuffer.pop_front();
496 std::string temp = outbuffer[0].substr(result);
501 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
503 this->OnError(I_ERR_WRITE);
504 this->state = I_ERROR;
505 this->Instance->SE->DelFd(this);
510 catch (CoreException& modexcept)
512 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
519 /* If we have multiple lines, try to send them all,
520 * not just the first one -- Brain
522 while (outbuffer.size() && (errno != EAGAIN))
526 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
528 int result = send(this->fd,outbuffer[0].c_str(),outbuffer[0].length(), 0);
532 if ((unsigned int)result >= outbuffer[0].length())
534 /* The whole block was written (usually a line)
535 * Pop the block off the front of the queue,
536 * dont set errno, because we are clear of errors
537 * and want to try and write the next block too.
539 outbuffer.pop_front();
543 std::string temp = outbuffer[0].substr(result);
545 /* We didnt get the whole line out. arses.
546 * Try again next time, i guess. Set errno,
547 * because we shouldnt be writing any more now,
548 * until the socketengine says its safe to do so.
553 else if ((result == -1) && (errno != EAGAIN))
555 this->OnError(I_ERR_WRITE);
556 this->state = I_ERROR;
557 this->Instance->SE->DelFd(this);
565 if ((errno == EAGAIN) && (fd > -1))
567 this->Instance->SE->WantWrite(this);
573 void SocketTimeout::Tick(time_t now)
575 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
578 if (this->sock->state == I_CONNECTING)
580 // for non-listening sockets, the timeout can occur
581 // which causes termination of the connection after
582 // the given number of seconds without a successful
584 this->sock->OnTimeout();
585 this->sock->OnError(I_ERR_TIMEOUT);
586 this->sock->timeout = true;
588 /* NOTE: We must set this AFTER DelFd, as we added
589 * this socket whilst writeable. This means that we
590 * must DELETE the socket whilst writeable too!
592 this->sock->state = I_ERROR;
594 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
595 ServerInstance->SocketCull[this->sock] = this->sock;
598 this->sock->Timeout = NULL;
601 bool InspSocket::Poll()
604 if(Instance->SE->GetRef(this->fd) != this)
608 if (this->Instance->SE->GetRef(this->fd) != this)
613 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
619 /* Our socket was in write-state, so delete it and re-add it
625 this->Instance->SE->DelFd(this);
626 this->SetState(I_CONNECTED);
627 if (!this->Instance->SE->AddFd(this))
631 this->SetState(I_CONNECTED);
633 if (Instance->Config->GetIOHook(this))
637 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
639 catch (CoreException& modexcept)
641 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
644 return this->OnConnected();
648 sockaddr* client = new sockaddr[2];
649 length = sizeof (sockaddr_in);
652 if ((!*this->host) || strchr(this->host, ':'))
653 length = sizeof(sockaddr_in6);
655 incoming = _accept (this->fd, client, &length);
657 if ((!*this->host) || strchr(this->host, ':'))
660 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
664 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
667 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
669 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
671 if (this->IsIOHooked)
675 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
677 catch (CoreException& modexcept)
679 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
683 this->SetQueues(incoming);
690 /* Process the read event */
691 return this->OnDataReady();
699 void InspSocket::SetState(InspSocketState s)
704 InspSocketState InspSocket::GetState()
709 int InspSocket::GetFd()
714 bool InspSocket::OnConnected() { return true; }
715 void InspSocket::OnError(InspSocketError e) { return; }
716 int InspSocket::OnDisconnect() { return 0; }
717 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
718 bool InspSocket::OnDataReady() { return true; }
719 bool InspSocket::OnWriteReady() { return true; }
720 void InspSocket::OnTimeout() { return; }
721 void InspSocket::OnClose() { return; }
723 InspSocket::~InspSocket()
728 Instance->Timers->DelTimer(Timeout);
733 void InspSocket::HandleEvent(EventType et, int errornum)
741 this->OnError(I_ERR_TIMEOUT);
745 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
748 this->OnError(I_ERR_BIND);
752 this->OnError(I_ERR_WRITE);
755 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
756 this->Instance->SocketCull[this] = this;
762 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
763 this->Instance->SocketCull[this] = this;
768 if (this->WaitingForWriteEvent)
770 this->WaitingForWriteEvent = false;
771 if (!this->OnWriteReady())
773 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
774 this->Instance->SocketCull[this] = this;
778 if (this->state == I_CONNECTING)
780 /* This might look wrong as if we should be actually calling
781 * with EVENT_WRITE, but trust me it is correct. There are some
782 * writeability-state things in the read code, because of how
783 * InspSocket used to work regarding write buffering in previous
784 * versions of InspIRCd. - Brain
786 this->HandleEvent(EVENT_READ);
791 if (this->FlushWriteBuffer())
793 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
794 this->Instance->SocketCull[this] = this;