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 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
153 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf));
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 != "") && (IP != "::1")))
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(n));
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 (bind(this->fd, s, size) < 0)
221 this->state = I_ERROR;
222 this->OnError(I_ERR_BIND);
237 bool InspSocket::DoConnect()
239 sockaddr* addr = new sockaddr[2];
240 socklen_t size = sizeof(sockaddr_in);
243 if ((!*this->host) || strchr(this->host, ':'))
248 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
249 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
251 if (!this->BindAddr(this->cbindip))
261 this->fd = socket(AF_INET, SOCK_STREAM, 0);
264 if (!this->BindAddr(this->cbindip))
274 this->state = I_ERROR;
275 this->OnError(I_ERR_SOCKET);
284 if (inet_pton(AF_INET6, this->host, &addy) > 0)
286 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
287 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
288 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
289 size = sizeof(sockaddr_in6);
296 if (inet_aton(this->host, &addy) > 0)
298 ((sockaddr_in*)addr)->sin_family = AF_INET;
299 ((sockaddr_in*)addr)->sin_addr = addy;
300 ((sockaddr_in*)addr)->sin_port = htons(this->port);
304 int flags = fcntl(this->fd, F_GETFL, 0);
305 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
307 unsigned long flags = 0;
308 ioctlsocket(this->fd, FIONBIO, &flags);
310 if (connect(this->fd, (sockaddr*)addr, size) == -1)
312 if (errno != EINPROGRESS)
314 this->OnError(I_ERR_CONNECT);
316 this->state = I_ERROR;
320 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
321 this->Instance->Timers->AddTimer(this->Timeout);
323 this->state = I_CONNECTING;
326 if (!this->Instance->SE->AddFd(this))
328 this->OnError(I_ERR_NOMOREFDS);
330 this->state = I_ERROR;
333 this->SetQueues(this->fd);
339 void InspSocket::Close()
341 /* Save this, so we dont lose it,
342 * otherise on failure, error messages
343 * might be inaccurate.
348 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
352 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
354 catch (CoreException& modexcept)
356 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
360 shutdown(this->fd,2);
366 std::string InspSocket::GetIP()
371 char* InspSocket::Read()
374 if ((fd < 0) || (m_internalFd > MAX_DESCRIPTORS))
376 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
382 if (this->IsIOHooked)
388 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
390 catch (CoreException& modexcept)
392 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
406 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
409 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
424 void InspSocket::MarkAsClosed()
428 // There are two possible outcomes to this function.
429 // It will either write all of the data, or an undefined amount.
430 // If an undefined amount is written the connection has failed
431 // and should be aborted.
432 int InspSocket::Write(const std::string &data)
434 /* Try and append the data to the back of the queue, and send it on its way
436 outbuffer.push_back(data);
437 this->Instance->SE->WantWrite(this);
438 return (!this->FlushWriteBuffer());
441 bool InspSocket::FlushWriteBuffer()
444 if ((this->fd > -1) && (this->state == I_CONNECTED))
446 if (this->IsIOHooked)
448 while (outbuffer.size() && (errno != EAGAIN))
452 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
455 if ((unsigned int)result >= outbuffer[0].length())
457 outbuffer.pop_front();
461 std::string temp = outbuffer[0].substr(result);
466 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
468 this->OnError(I_ERR_WRITE);
469 this->state = I_ERROR;
470 this->Instance->SE->DelFd(this);
475 catch (CoreException& modexcept)
477 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
484 /* If we have multiple lines, try to send them all,
485 * not just the first one -- Brain
487 while (outbuffer.size() && (errno != EAGAIN))
491 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
493 int result = send(this->fd,outbuffer[0].c_str(),outbuffer[0].length(), 0);
497 if ((unsigned int)result >= outbuffer[0].length())
499 /* The whole block was written (usually a line)
500 * Pop the block off the front of the queue,
501 * dont set errno, because we are clear of errors
502 * and want to try and write the next block too.
504 outbuffer.pop_front();
508 std::string temp = outbuffer[0].substr(result);
510 /* We didnt get the whole line out. arses.
511 * Try again next time, i guess. Set errno,
512 * because we shouldnt be writing any more now,
513 * until the socketengine says its safe to do so.
518 else if ((result == -1) && (errno != EAGAIN))
520 this->OnError(I_ERR_WRITE);
521 this->state = I_ERROR;
522 this->Instance->SE->DelFd(this);
530 if ((errno == EAGAIN) && (fd > -1))
532 this->Instance->SE->WantWrite(this);
538 void SocketTimeout::Tick(time_t now)
540 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
543 if (this->sock->state == I_CONNECTING)
545 // for non-listening sockets, the timeout can occur
546 // which causes termination of the connection after
547 // the given number of seconds without a successful
549 this->sock->OnTimeout();
550 this->sock->OnError(I_ERR_TIMEOUT);
551 this->sock->timeout = true;
553 /* NOTE: We must set this AFTER DelFd, as we added
554 * this socket whilst writeable. This means that we
555 * must DELETE the socket whilst writeable too!
557 this->sock->state = I_ERROR;
559 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
560 ServerInstance->SocketCull[this->sock] = this->sock;
563 this->sock->Timeout = NULL;
566 bool InspSocket::Poll()
569 if(Instance->SE->GetRef(this->fd) != this)
573 if (this->Instance->SE->GetRef(this->fd) != this)
578 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
584 /* Our socket was in write-state, so delete it and re-add it
590 this->Instance->SE->DelFd(this);
591 this->SetState(I_CONNECTED);
592 if (!this->Instance->SE->AddFd(this))
596 this->SetState(I_CONNECTED);
598 if (Instance->Config->GetIOHook(this))
602 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
604 catch (CoreException& modexcept)
606 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
609 return this->OnConnected();
613 sockaddr* client = new sockaddr[2];
614 length = sizeof (sockaddr_in);
617 if ((!*this->host) || strchr(this->host, ':'))
618 length = sizeof(sockaddr_in6);
620 incoming = _accept (this->fd, client, &length);
622 if ((!*this->host) || strchr(this->host, ':'))
625 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
629 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
630 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
632 if (this->IsIOHooked)
636 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
638 catch (CoreException& modexcept)
640 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
644 this->SetQueues(incoming);
651 /* Process the read event */
652 return this->OnDataReady();
660 void InspSocket::SetState(InspSocketState s)
665 InspSocketState InspSocket::GetState()
670 int InspSocket::GetFd()
675 bool InspSocket::OnConnected() { return true; }
676 void InspSocket::OnError(InspSocketError e) { return; }
677 int InspSocket::OnDisconnect() { return 0; }
678 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
679 bool InspSocket::OnDataReady() { return true; }
680 bool InspSocket::OnWriteReady() { return true; }
681 void InspSocket::OnTimeout() { return; }
682 void InspSocket::OnClose() { return; }
684 InspSocket::~InspSocket()
689 Instance->Timers->DelTimer(Timeout);
694 void InspSocket::HandleEvent(EventType et, int errornum)
702 this->OnError(I_ERR_TIMEOUT);
706 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
709 this->OnError(I_ERR_BIND);
713 this->OnError(I_ERR_WRITE);
716 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
717 this->Instance->SocketCull[this] = this;
723 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
724 this->Instance->SocketCull[this] = this;
729 if (this->WaitingForWriteEvent)
731 this->WaitingForWriteEvent = false;
732 if (!this->OnWriteReady())
734 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
735 this->Instance->SocketCull[this] = this;
739 if (this->state == I_CONNECTING)
741 /* This might look wrong as if we should be actually calling
742 * with EVENT_WRITE, but trust me it is correct. There are some
743 * writeability-state things in the read code, because of how
744 * InspSocket used to work regarding write buffering in previous
745 * versions of InspIRCd. - Brain
747 this->HandleEvent(EVENT_READ);
752 if (this->FlushWriteBuffer())
754 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
755 this->Instance->SocketCull[this] = this;