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;
21 using irc::sockets::insp_inaddr;
22 using irc::sockets::insp_sockaddr;
24 bool InspSocket::Readable()
26 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
29 InspSocket::InspSocket(InspIRCd* SI)
32 this->state = I_DISCONNECTED;
34 this->WaitingForWriteEvent = false;
36 this->IsIOHooked = false;
39 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
43 this->state = I_CONNECTED;
44 strlcpy(this->IP,ip,MAXBUF);
45 this->WaitingForWriteEvent = false;
47 this->IsIOHooked = false;
49 this->Instance->SE->AddFd(this);
52 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime, const std::string &connectbindip)
54 this->cbindip = connectbindip;
57 strlcpy(host,ipaddr.c_str(),MAXBUF);
58 this->WaitingForWriteEvent = false;
59 this->IsIOHooked = false;
63 if ((this->fd = OpenTCPSocket(host)) == ERROR)
66 this->state = I_ERROR;
67 this->OnError(I_ERR_SOCKET);
72 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
76 this->state = I_ERROR;
77 this->OnError(I_ERR_BIND);
78 this->ClosePending = true;
83 this->state = I_LISTENING;
86 if (!this->Instance->SE->AddFd(this))
89 this->state = I_ERROR;
90 this->OnError(I_ERR_NOMOREFDS);
99 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
104 if (strchr(host,':'))
107 if (inet_pton(AF_INET6, host, &n) < 1)
113 if (inet_aton(host,&n) < 1)
118 if (inet_aton(host,&n) < 1)
123 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
126 this->state = I_ERROR;
127 this->OnError(I_ERR_RESOLVE);
132 strlcpy(this->IP,host,MAXBUF);
133 timeout_val = maxtime;
139 void InspSocket::WantWrite()
141 this->Instance->SE->WantWrite(this);
142 this->WaitingForWriteEvent = true;
145 void InspSocket::SetQueues(int nfd)
147 // attempt to increase socket sendq and recvq as high as its possible
150 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
151 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
154 /* Most irc servers require you to specify the ip you want to bind to.
155 * If you dont specify an IP, they rather dumbly bind to the first IP
156 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
157 * addresses we've bound server ports to, and we try and bind our outbound
158 * connections to the first usable non-loopback and non-any IP we find.
159 * This is easier to configure when you have a lot of links and a lot
160 * of servers to configure.
162 bool InspSocket::BindAddr(const std::string &ip)
164 ConfigReader Conf(this->Instance);
165 bool bindfail = false;
166 socklen_t size = sizeof(sockaddr_in);
169 /* Are we looking for a binding to fit an ipv6 host? */
170 if ((!*this->host) || strchr(this->host, ':'))
174 while ((j < Conf.Enumerate("bind")) && (!ip.empty()))
176 std::string IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
177 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
179 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (IP != "") && (IP != "::1")))
181 sockaddr* s = new sockaddr[2];
186 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
188 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
189 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
190 size = sizeof(sockaddr_in6);
198 if (inet_aton(IP.c_str(), &n) > 0)
200 ((sockaddr_in*)s)->sin_addr = n;
201 ((sockaddr_in*)s)->sin_family = AF_INET;
208 if (insp_aton(IP.c_str(), &n) > 0)
210 ((sockaddr_in*)s)->sin_addr = n;
211 ((sockaddr_in*)s)->sin_family = AF_INET;
222 if (bind(this->fd, s, size) < 0)
224 this->state = I_ERROR;
225 this->OnError(I_ERR_BIND);
240 bool InspSocket::DoConnect()
242 sockaddr* addr = new sockaddr[2];
243 socklen_t size = sizeof(sockaddr_in);
246 if ((!*this->host) || strchr(this->host, ':'))
251 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
252 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
254 if (!this->BindAddr(this->cbindip))
263 this->fd = socket(AF_INET, SOCK_STREAM, 0);
266 this->fd = socket(AF_INET, SOCK_STREAM, 0);
271 this->state = I_ERROR;
272 this->OnError(I_ERR_SOCKET);
281 if (inet_pton(AF_INET6, this->host, &addy) > 0)
283 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
284 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
285 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
286 size = sizeof(sockaddr_in6);
292 if (inet_aton(this->host, &addy) > 0)
294 ((sockaddr_in*)addr)->sin_family = AF_INET;
295 ((sockaddr_in*)addr)->sin_addr = addy;
296 ((sockaddr_in*)addr)->sin_port = htons(this->port);
301 if (inet_aton(this->host, &addy) > 0)
303 ((sockaddr_in*)addr)->sin_family = AF_INET;
304 ((sockaddr_in*)addr)->sin_addr = addy;
305 ((sockaddr_in*)addr)->sin_port = htons(this->port);
309 int flags = fcntl(this->fd, F_GETFL, 0);
310 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
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);
325 this->state = I_CONNECTING;
328 if (!this->Instance->SE->AddFd(this))
330 this->OnError(I_ERR_NOMOREFDS);
332 this->state = I_ERROR;
335 this->SetQueues(this->fd);
341 void InspSocket::Close()
343 /* Save this, so we dont lose it,
344 * otherise on failure, error messages
345 * might be inaccurate.
350 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
354 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
356 catch (CoreException& modexcept)
358 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
362 shutdown(this->fd,2);
368 std::string InspSocket::GetIP()
373 char* InspSocket::Read()
375 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
380 if (this->IsIOHooked)
386 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
388 catch (CoreException& modexcept)
390 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
404 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
407 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
422 void InspSocket::MarkAsClosed()
426 // There are two possible outcomes to this function.
427 // It will either write all of the data, or an undefined amount.
428 // If an undefined amount is written the connection has failed
429 // and should be aborted.
430 int InspSocket::Write(const std::string &data)
432 /* Try and append the data to the back of the queue, and send it on its way
434 outbuffer.push_back(data);
435 this->Instance->SE->WantWrite(this);
436 return (!this->FlushWriteBuffer());
439 bool InspSocket::FlushWriteBuffer()
442 if ((this->fd > -1) && (this->state == I_CONNECTED))
444 if (this->IsIOHooked)
446 while (outbuffer.size() && (errno != EAGAIN))
450 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
453 if ((unsigned int)result == outbuffer[0].length())
455 outbuffer.pop_front();
459 std::string temp = outbuffer[0].substr(result);
464 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
466 this->OnError(I_ERR_WRITE);
467 this->state = I_ERROR;
468 this->Instance->SE->DelFd(this);
473 catch (CoreException& modexcept)
475 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
482 /* If we have multiple lines, try to send them all,
483 * not just the first one -- Brain
485 while (outbuffer.size() && (errno != EAGAIN))
488 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
491 if ((unsigned int)result == outbuffer[0].length())
493 /* The whole block was written (usually a line)
494 * Pop the block off the front of the queue,
495 * dont set errno, because we are clear of errors
496 * and want to try and write the next block too.
498 outbuffer.pop_front();
502 std::string temp = outbuffer[0].substr(result);
504 /* We didnt get the whole line out. arses.
505 * Try again next time, i guess. Set errno,
506 * because we shouldnt be writing any more now,
507 * until the socketengine says its safe to do so.
512 else if ((result == -1) && (errno != EAGAIN))
514 this->OnError(I_ERR_WRITE);
515 this->state = I_ERROR;
516 this->Instance->SE->DelFd(this);
524 if ((errno == EAGAIN) && (fd > -1))
526 this->Instance->SE->WantWrite(this);
532 void SocketTimeout::Tick(time_t now)
534 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
537 if (this->sock->state == I_CONNECTING)
539 // for non-listening sockets, the timeout can occur
540 // which causes termination of the connection after
541 // the given number of seconds without a successful
543 this->sock->OnTimeout();
544 this->sock->OnError(I_ERR_TIMEOUT);
545 this->sock->timeout = true;
546 ServerInstance->SE->DelFd(this->sock);
547 /* NOTE: We must set this AFTER DelFd, as we added
548 * this socket whilst writeable. This means that we
549 * must DELETE the socket whilst writeable too!
551 this->sock->state = I_ERROR;
558 this->sock->Timeout = NULL;
562 bool InspSocket::Poll()
564 if (this->Instance->SE->GetRef(this->fd) != this)
569 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
575 /* Our socket was in write-state, so delete it and re-add it
580 this->Instance->SE->DelFd(this);
581 this->SetState(I_CONNECTED);
582 if (!this->Instance->SE->AddFd(this))
585 if (Instance->Config->GetIOHook(this))
589 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
591 catch (CoreException& modexcept)
593 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
596 return this->OnConnected();
600 sockaddr* client = new sockaddr[2];
601 length = sizeof (sockaddr_in);
604 if ((!*this->host) || strchr(this->host, ':'))
605 length = sizeof(sockaddr_in6);
607 incoming = accept (this->fd, client, &length);
609 if ((!*this->host) || strchr(this->host, ':'))
612 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
616 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
619 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
621 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
623 if (this->IsIOHooked)
627 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
629 catch (CoreException& modexcept)
631 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
635 this->SetQueues(incoming);
642 /* Process the read event */
643 return this->OnDataReady();
651 void InspSocket::SetState(InspSocketState s)
656 InspSocketState InspSocket::GetState()
661 int InspSocket::GetFd()
666 bool InspSocket::OnConnected() { return true; }
667 void InspSocket::OnError(InspSocketError e) { return; }
668 int InspSocket::OnDisconnect() { return 0; }
669 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
670 bool InspSocket::OnDataReady() { return true; }
671 bool InspSocket::OnWriteReady() { return true; }
672 void InspSocket::OnTimeout() { return; }
673 void InspSocket::OnClose() { return; }
675 InspSocket::~InspSocket()
680 Instance->Timers->DelTimer(Timeout);
685 void InspSocket::HandleEvent(EventType et, int errornum)
690 this->Instance->SE->DelFd(this);
698 this->Instance->SE->DelFd(this);
705 if (this->WaitingForWriteEvent)
707 this->WaitingForWriteEvent = false;
708 if (!this->OnWriteReady())
710 this->Instance->SE->DelFd(this);
716 if (this->state == I_CONNECTING)
718 /* This might look wrong as if we should be actually calling
719 * with EVENT_WRITE, but trust me it is correct. There are some
720 * writeability-state things in the read code, because of how
721 * InspSocket used to work regarding write buffering in previous
722 * versions of InspIRCd. - Brain
724 this->HandleEvent(EVENT_READ);
729 if (this->FlushWriteBuffer())
731 this->Instance->SE->DelFd(this);