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)
112 if (inet_aton(host,&n) < 1)
117 if (inet_aton(host,&n) < 1)
122 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
123 this->OnError(I_ERR_CONNECT);
126 this->state = I_ERROR;
131 strlcpy(this->IP,host,MAXBUF);
132 timeout_val = maxtime;
133 if (!this->DoConnect())
135 this->OnError(I_ERR_CONNECT);
138 this->state = I_ERROR;
145 void InspSocket::WantWrite()
147 this->Instance->SE->WantWrite(this);
148 this->WaitingForWriteEvent = true;
151 void InspSocket::SetQueues(int nfd)
153 // attempt to increase socket sendq and recvq as high as its possible
156 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
157 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf));
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 InspSocket::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 IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
182 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
184 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (IP != "") && (IP != "::1")))
186 sockaddr* s = new sockaddr[2];
191 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
193 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
194 ((sockaddr_in6*)s)->sin6_port = 0;
195 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
196 size = sizeof(sockaddr_in6);
208 if (inet_aton(IP.c_str(), &n) > 0)
210 ((sockaddr_in*)s)->sin_addr = n;
211 ((sockaddr_in*)s)->sin_port = 0;
212 ((sockaddr_in*)s)->sin_family = AF_INET;
223 if (insp_aton(IP.c_str(), &n) > 0)
225 ((sockaddr_in*)s)->sin_addr = n;
226 ((sockaddr_in*)s)->sin_port = 0;
227 ((sockaddr_in*)s)->sin_family = AF_INET;
237 if (bind(this->fd, s, size) < 0)
239 this->state = I_ERROR;
240 this->OnError(I_ERR_BIND);
255 bool InspSocket::DoConnect()
257 sockaddr* addr = new sockaddr[2];
258 socklen_t size = sizeof(sockaddr_in);
261 if ((!*this->host) || strchr(this->host, ':'))
266 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
267 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
269 if (!this->BindAddr(this->cbindip))
278 this->fd = socket(AF_INET, SOCK_STREAM, 0);
281 if (!this->BindAddr(this->cbindip))
289 this->fd = socket(AF_INET, SOCK_STREAM, 0);
292 if (!this->BindAddr(this->cbindip))
302 this->state = I_ERROR;
303 this->OnError(I_ERR_SOCKET);
312 if (inet_pton(AF_INET6, this->host, &addy) > 0)
314 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
315 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
316 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
317 size = sizeof(sockaddr_in6);
323 if (inet_aton(this->host, &addy) > 0)
325 ((sockaddr_in*)addr)->sin_family = AF_INET;
326 ((sockaddr_in*)addr)->sin_addr = addy;
327 ((sockaddr_in*)addr)->sin_port = htons(this->port);
332 if (inet_aton(this->host, &addy) > 0)
334 ((sockaddr_in*)addr)->sin_family = AF_INET;
335 ((sockaddr_in*)addr)->sin_addr = addy;
336 ((sockaddr_in*)addr)->sin_port = htons(this->port);
340 int flags = fcntl(this->fd, F_GETFL, 0);
341 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
343 unsigned long flags = 0;
344 ioctlsocket(this->fd, FIONBIO, &flags);
346 if (connect(this->fd, (sockaddr*)addr, size) == -1)
348 if (errno != EINPROGRESS)
350 this->OnError(I_ERR_CONNECT);
352 this->state = I_ERROR;
356 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
357 this->Instance->Timers->AddTimer(this->Timeout);
359 this->state = I_CONNECTING;
362 if (!this->Instance->SE->AddFd(this))
364 this->OnError(I_ERR_NOMOREFDS);
366 this->state = I_ERROR;
369 this->SetQueues(this->fd);
375 void InspSocket::Close()
377 /* Save this, so we dont lose it,
378 * otherise on failure, error messages
379 * might be inaccurate.
384 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
388 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
390 catch (CoreException& modexcept)
392 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
396 shutdown(this->fd,2);
402 std::string InspSocket::GetIP()
407 char* InspSocket::Read()
410 if ((fd < 0) || (m_internalFd > MAX_DESCRIPTORS))
412 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
418 if (this->IsIOHooked)
424 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
426 catch (CoreException& modexcept)
428 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
442 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
445 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
460 void InspSocket::MarkAsClosed()
464 // There are two possible outcomes to this function.
465 // It will either write all of the data, or an undefined amount.
466 // If an undefined amount is written the connection has failed
467 // and should be aborted.
468 int InspSocket::Write(const std::string &data)
470 /* Try and append the data to the back of the queue, and send it on its way
472 outbuffer.push_back(data);
473 this->Instance->SE->WantWrite(this);
474 return (!this->FlushWriteBuffer());
477 bool InspSocket::FlushWriteBuffer()
480 if ((this->fd > -1) && (this->state == I_CONNECTED))
482 if (this->IsIOHooked)
484 while (outbuffer.size() && (errno != EAGAIN))
488 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
491 if ((unsigned int)result >= outbuffer[0].length())
493 outbuffer.pop_front();
497 std::string temp = outbuffer[0].substr(result);
502 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
504 this->OnError(I_ERR_WRITE);
505 this->state = I_ERROR;
506 this->Instance->SE->DelFd(this);
511 catch (CoreException& modexcept)
513 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
520 /* If we have multiple lines, try to send them all,
521 * not just the first one -- Brain
523 while (outbuffer.size() && (errno != EAGAIN))
527 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
529 int result = send(this->fd,outbuffer[0].c_str(),outbuffer[0].length(), 0);
533 if ((unsigned int)result >= outbuffer[0].length())
535 /* The whole block was written (usually a line)
536 * Pop the block off the front of the queue,
537 * dont set errno, because we are clear of errors
538 * and want to try and write the next block too.
540 outbuffer.pop_front();
544 std::string temp = outbuffer[0].substr(result);
546 /* We didnt get the whole line out. arses.
547 * Try again next time, i guess. Set errno,
548 * because we shouldnt be writing any more now,
549 * until the socketengine says its safe to do so.
554 else if ((result == -1) && (errno != EAGAIN))
556 this->OnError(I_ERR_WRITE);
557 this->state = I_ERROR;
558 this->Instance->SE->DelFd(this);
566 if ((errno == EAGAIN) && (fd > -1))
568 this->Instance->SE->WantWrite(this);
574 void SocketTimeout::Tick(time_t now)
576 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
579 if (this->sock->state == I_CONNECTING)
581 // for non-listening sockets, the timeout can occur
582 // which causes termination of the connection after
583 // the given number of seconds without a successful
585 this->sock->OnTimeout();
586 this->sock->OnError(I_ERR_TIMEOUT);
587 this->sock->timeout = true;
589 /* NOTE: We must set this AFTER DelFd, as we added
590 * this socket whilst writeable. This means that we
591 * must DELETE the socket whilst writeable too!
593 this->sock->state = I_ERROR;
595 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
596 ServerInstance->SocketCull[this->sock] = this->sock;
599 this->sock->Timeout = NULL;
602 bool InspSocket::Poll()
605 if(Instance->SE->GetRef(this->fd) != this)
609 if (this->Instance->SE->GetRef(this->fd) != this)
614 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
620 /* Our socket was in write-state, so delete it and re-add it
626 this->Instance->SE->DelFd(this);
627 this->SetState(I_CONNECTED);
628 if (!this->Instance->SE->AddFd(this))
632 this->SetState(I_CONNECTED);
634 if (Instance->Config->GetIOHook(this))
638 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
640 catch (CoreException& modexcept)
642 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
645 return this->OnConnected();
649 sockaddr* client = new sockaddr[2];
650 length = sizeof (sockaddr_in);
653 if ((!*this->host) || strchr(this->host, ':'))
654 length = sizeof(sockaddr_in6);
656 incoming = _accept (this->fd, client, &length);
658 if ((!*this->host) || strchr(this->host, ':'))
661 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
665 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
668 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
670 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
672 if (this->IsIOHooked)
676 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
678 catch (CoreException& modexcept)
680 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
684 this->SetQueues(incoming);
691 /* Process the read event */
692 return this->OnDataReady();
700 void InspSocket::SetState(InspSocketState s)
705 InspSocketState InspSocket::GetState()
710 int InspSocket::GetFd()
715 bool InspSocket::OnConnected() { return true; }
716 void InspSocket::OnError(InspSocketError e) { return; }
717 int InspSocket::OnDisconnect() { return 0; }
718 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
719 bool InspSocket::OnDataReady() { return true; }
720 bool InspSocket::OnWriteReady() { return true; }
721 void InspSocket::OnTimeout() { return; }
722 void InspSocket::OnClose() { return; }
724 InspSocket::~InspSocket()
729 Instance->Timers->DelTimer(Timeout);
734 void InspSocket::HandleEvent(EventType et, int errornum)
742 this->OnError(I_ERR_TIMEOUT);
746 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
749 this->OnError(I_ERR_BIND);
753 this->OnError(I_ERR_WRITE);
756 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
757 this->Instance->SocketCull[this] = this;
763 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
764 this->Instance->SocketCull[this] = this;
769 if (this->WaitingForWriteEvent)
771 this->WaitingForWriteEvent = false;
772 if (!this->OnWriteReady())
774 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
775 this->Instance->SocketCull[this] = this;
779 if (this->state == I_CONNECTING)
781 /* This might look wrong as if we should be actually calling
782 * with EVENT_WRITE, but trust me it is correct. There are some
783 * writeability-state things in the read code, because of how
784 * InspSocket used to work regarding write buffering in previous
785 * versions of InspIRCd. - Brain
787 this->HandleEvent(EVENT_READ);
792 if (this->FlushWriteBuffer())
794 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
795 this->Instance->SocketCull[this] = this;