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!");
124 this->state = I_ERROR;
125 this->OnError(I_ERR_RESOLVE);
130 strlcpy(this->IP,host,MAXBUF);
131 timeout_val = maxtime;
132 if (!this->DoConnect())
136 this->state = I_ERROR;
137 this->OnError(I_ERR_CONNECT);
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 void *)&sendbuf,sizeof(sendbuf));
156 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&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_family = AF_INET6;
194 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_family = AF_INET;
220 if (insp_aton(IP.c_str(), &n) > 0)
222 ((sockaddr_in*)s)->sin_addr = n;
223 ((sockaddr_in*)s)->sin_family = AF_INET;
233 if (bind(this->fd, s, size) < 0)
235 this->state = I_ERROR;
236 this->OnError(I_ERR_BIND);
251 bool InspSocket::DoConnect()
253 sockaddr* addr = new sockaddr[2];
254 socklen_t size = sizeof(sockaddr_in);
257 if ((!*this->host) || strchr(this->host, ':'))
262 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
263 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
265 if (!this->BindAddr(this->cbindip))
274 this->fd = socket(AF_INET, SOCK_STREAM, 0);
277 if (!this->BindAddr(this->cbindip))
285 this->fd = socket(AF_INET, SOCK_STREAM, 0);
288 if (!this->BindAddr(this->cbindip))
298 this->state = I_ERROR;
299 this->OnError(I_ERR_SOCKET);
308 if (inet_pton(AF_INET6, this->host, &addy) > 0)
310 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
311 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
312 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
313 size = sizeof(sockaddr_in6);
319 if (inet_aton(this->host, &addy) > 0)
321 ((sockaddr_in*)addr)->sin_family = AF_INET;
322 ((sockaddr_in*)addr)->sin_addr = addy;
323 ((sockaddr_in*)addr)->sin_port = htons(this->port);
328 if (inet_aton(this->host, &addy) > 0)
330 ((sockaddr_in*)addr)->sin_family = AF_INET;
331 ((sockaddr_in*)addr)->sin_addr = addy;
332 ((sockaddr_in*)addr)->sin_port = htons(this->port);
336 int flags = fcntl(this->fd, F_GETFL, 0);
337 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
339 if (connect(this->fd, (sockaddr*)addr, size) == -1)
341 if (errno != EINPROGRESS)
343 this->OnError(I_ERR_CONNECT);
345 this->state = I_ERROR;
349 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
350 this->Instance->Timers->AddTimer(this->Timeout);
352 this->state = I_CONNECTING;
355 if (!this->Instance->SE->AddFd(this))
357 this->OnError(I_ERR_NOMOREFDS);
359 this->state = I_ERROR;
362 this->SetQueues(this->fd);
368 void InspSocket::Close()
370 /* Save this, so we dont lose it,
371 * otherise on failure, error messages
372 * might be inaccurate.
377 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
381 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
383 catch (CoreException& modexcept)
385 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
389 shutdown(this->fd,2);
395 std::string InspSocket::GetIP()
400 char* InspSocket::Read()
402 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
407 if (this->IsIOHooked)
413 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
415 catch (CoreException& modexcept)
417 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
431 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
434 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
449 void InspSocket::MarkAsClosed()
453 // There are two possible outcomes to this function.
454 // It will either write all of the data, or an undefined amount.
455 // If an undefined amount is written the connection has failed
456 // and should be aborted.
457 int InspSocket::Write(const std::string &data)
459 /* Try and append the data to the back of the queue, and send it on its way
461 outbuffer.push_back(data);
462 this->Instance->SE->WantWrite(this);
463 return (!this->FlushWriteBuffer());
466 bool InspSocket::FlushWriteBuffer()
469 if ((this->fd > -1) && (this->state == I_CONNECTED))
471 if (this->IsIOHooked)
473 while (outbuffer.size() && (errno != EAGAIN))
477 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
480 if ((unsigned int)result >= outbuffer[0].length())
482 outbuffer.pop_front();
486 std::string temp = outbuffer[0].substr(result);
491 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
493 this->OnError(I_ERR_WRITE);
494 this->state = I_ERROR;
495 this->Instance->SE->DelFd(this);
500 catch (CoreException& modexcept)
502 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
509 /* If we have multiple lines, try to send them all,
510 * not just the first one -- Brain
512 while (outbuffer.size() && (errno != EAGAIN))
515 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
518 if ((unsigned int)result >= outbuffer[0].length())
520 /* The whole block was written (usually a line)
521 * Pop the block off the front of the queue,
522 * dont set errno, because we are clear of errors
523 * and want to try and write the next block too.
525 outbuffer.pop_front();
529 std::string temp = outbuffer[0].substr(result);
531 /* We didnt get the whole line out. arses.
532 * Try again next time, i guess. Set errno,
533 * because we shouldnt be writing any more now,
534 * until the socketengine says its safe to do so.
539 else if ((result == -1) && (errno != EAGAIN))
541 this->OnError(I_ERR_WRITE);
542 this->state = I_ERROR;
543 this->Instance->SE->DelFd(this);
551 if ((errno == EAGAIN) && (fd > -1))
553 this->Instance->SE->WantWrite(this);
559 void SocketTimeout::Tick(time_t now)
561 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
564 if (this->sock->state == I_CONNECTING)
566 // for non-listening sockets, the timeout can occur
567 // which causes termination of the connection after
568 // the given number of seconds without a successful
570 this->sock->OnTimeout();
571 this->sock->OnError(I_ERR_TIMEOUT);
572 this->sock->timeout = true;
573 ServerInstance->SE->DelFd(this->sock);
574 /* NOTE: We must set this AFTER DelFd, as we added
575 * this socket whilst writeable. This means that we
576 * must DELETE the socket whilst writeable too!
578 this->sock->state = I_ERROR;
585 this->sock->Timeout = NULL;
589 bool InspSocket::Poll()
591 if (this->Instance->SE->GetRef(this->fd) != this)
596 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
602 /* Our socket was in write-state, so delete it and re-add it
607 this->Instance->SE->DelFd(this);
608 this->SetState(I_CONNECTED);
609 if (!this->Instance->SE->AddFd(this))
612 if (Instance->Config->GetIOHook(this))
616 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
618 catch (CoreException& modexcept)
620 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
623 return this->OnConnected();
627 sockaddr* client = new sockaddr[2];
628 length = sizeof (sockaddr_in);
631 if ((!*this->host) || strchr(this->host, ':'))
632 length = sizeof(sockaddr_in6);
634 incoming = accept (this->fd, client, &length);
636 if ((!*this->host) || strchr(this->host, ':'))
639 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
643 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
646 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
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->Log(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 InspSocket::SetState(InspSocketState s)
683 InspSocketState InspSocket::GetState()
688 int InspSocket::GetFd()
693 bool InspSocket::OnConnected() { return true; }
694 void InspSocket::OnError(InspSocketError e) { return; }
695 int InspSocket::OnDisconnect() { return 0; }
696 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
697 bool InspSocket::OnDataReady() { return true; }
698 bool InspSocket::OnWriteReady() { return true; }
699 void InspSocket::OnTimeout() { return; }
700 void InspSocket::OnClose() { return; }
702 InspSocket::~InspSocket()
707 Instance->Timers->DelTimer(Timeout);
712 void InspSocket::HandleEvent(EventType et, int errornum)
717 this->Instance->SE->DelFd(this);
725 this->Instance->SE->DelFd(this);
732 if (this->WaitingForWriteEvent)
734 this->WaitingForWriteEvent = false;
735 if (!this->OnWriteReady())
737 this->Instance->SE->DelFd(this);
743 if (this->state == I_CONNECTING)
745 /* This might look wrong as if we should be actually calling
746 * with EVENT_WRITE, but trust me it is correct. There are some
747 * writeability-state things in the read code, because of how
748 * InspSocket used to work regarding write buffering in previous
749 * versions of InspIRCd. - Brain
751 this->HandleEvent(EVENT_READ);
756 if (this->FlushWriteBuffer())
758 this->Instance->SE->DelFd(this);