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 Instance->Log(DEBUG,"BindAddr(%s)", ip.c_str());
170 ConfigReader Conf(this->Instance);
171 bool bindfail = false;
172 socklen_t size = sizeof(sockaddr_in);
175 /* Are we looking for a binding to fit an ipv6 host? */
176 if ((!*this->host) || strchr(this->host, ':'))
180 while (j < Conf.Enumerate("bind") || (!ip.empty()))
182 std::string IP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
183 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
185 if (!ip.empty() || ((IP != "*") && (IP != "127.0.0.1") && (IP != "") && (IP != "::1")))
187 sockaddr* s = new sockaddr[2];
192 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
194 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
195 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
196 size = sizeof(sockaddr_in6);
204 if (inet_aton(IP.c_str(), &n) > 0)
206 ((sockaddr_in*)s)->sin_addr = n;
207 ((sockaddr_in*)s)->sin_family = AF_INET;
214 if (insp_aton(IP.c_str(), &n) > 0)
216 ((sockaddr_in*)s)->sin_addr = n;
217 ((sockaddr_in*)s)->sin_family = AF_INET;
228 if (bind(this->fd, s, size) < 0)
230 this->state = I_ERROR;
231 this->OnError(I_ERR_BIND);
246 bool InspSocket::DoConnect()
248 sockaddr* addr = new sockaddr[2];
249 socklen_t size = sizeof(sockaddr_in);
252 if ((!*this->host) || strchr(this->host, ':'))
257 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
258 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
260 if (!this->BindAddr(this->cbindip))
269 this->fd = socket(AF_INET, SOCK_STREAM, 0);
272 if (!this->BindAddr(this->cbindip))
280 this->fd = socket(AF_INET, SOCK_STREAM, 0);
283 if (!this->BindAddr(this->cbindip))
293 this->state = I_ERROR;
294 this->OnError(I_ERR_SOCKET);
303 if (inet_pton(AF_INET6, this->host, &addy) > 0)
305 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
306 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
307 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
308 size = sizeof(sockaddr_in6);
314 if (inet_aton(this->host, &addy) > 0)
316 ((sockaddr_in*)addr)->sin_family = AF_INET;
317 ((sockaddr_in*)addr)->sin_addr = addy;
318 ((sockaddr_in*)addr)->sin_port = htons(this->port);
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);
331 int flags = fcntl(this->fd, F_GETFL, 0);
332 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
334 if (connect(this->fd, (sockaddr*)addr, size) == -1)
336 if (errno != EINPROGRESS)
338 this->OnError(I_ERR_CONNECT);
340 this->state = I_ERROR;
344 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
345 this->Instance->Timers->AddTimer(this->Timeout);
347 this->state = I_CONNECTING;
350 if (!this->Instance->SE->AddFd(this))
352 this->OnError(I_ERR_NOMOREFDS);
354 this->state = I_ERROR;
357 this->SetQueues(this->fd);
363 void InspSocket::Close()
365 /* Save this, so we dont lose it,
366 * otherise on failure, error messages
367 * might be inaccurate.
372 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
376 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
378 catch (CoreException& modexcept)
380 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
384 shutdown(this->fd,2);
390 std::string InspSocket::GetIP()
395 char* InspSocket::Read()
397 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
402 if (this->IsIOHooked)
408 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
410 catch (CoreException& modexcept)
412 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
426 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
429 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
444 void InspSocket::MarkAsClosed()
448 // There are two possible outcomes to this function.
449 // It will either write all of the data, or an undefined amount.
450 // If an undefined amount is written the connection has failed
451 // and should be aborted.
452 int InspSocket::Write(const std::string &data)
454 /* Try and append the data to the back of the queue, and send it on its way
456 outbuffer.push_back(data);
457 this->Instance->SE->WantWrite(this);
458 return (!this->FlushWriteBuffer());
461 bool InspSocket::FlushWriteBuffer()
464 if ((this->fd > -1) && (this->state == I_CONNECTED))
466 if (this->IsIOHooked)
468 while (outbuffer.size() && (errno != EAGAIN))
472 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
475 if ((unsigned int)result == outbuffer[0].length())
477 outbuffer.pop_front();
481 std::string temp = outbuffer[0].substr(result);
486 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
488 this->OnError(I_ERR_WRITE);
489 this->state = I_ERROR;
490 this->Instance->SE->DelFd(this);
495 catch (CoreException& modexcept)
497 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
504 /* If we have multiple lines, try to send them all,
505 * not just the first one -- Brain
507 while (outbuffer.size() && (errno != EAGAIN))
510 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
513 if ((unsigned int)result == outbuffer[0].length())
515 /* The whole block was written (usually a line)
516 * Pop the block off the front of the queue,
517 * dont set errno, because we are clear of errors
518 * and want to try and write the next block too.
520 outbuffer.pop_front();
524 std::string temp = outbuffer[0].substr(result);
526 /* We didnt get the whole line out. arses.
527 * Try again next time, i guess. Set errno,
528 * because we shouldnt be writing any more now,
529 * until the socketengine says its safe to do so.
534 else if ((result == -1) && (errno != EAGAIN))
536 this->OnError(I_ERR_WRITE);
537 this->state = I_ERROR;
538 this->Instance->SE->DelFd(this);
546 if ((errno == EAGAIN) && (fd > -1))
548 this->Instance->SE->WantWrite(this);
554 void SocketTimeout::Tick(time_t now)
556 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
559 if (this->sock->state == I_CONNECTING)
561 // for non-listening sockets, the timeout can occur
562 // which causes termination of the connection after
563 // the given number of seconds without a successful
565 this->sock->OnTimeout();
566 this->sock->OnError(I_ERR_TIMEOUT);
567 this->sock->timeout = true;
568 ServerInstance->SE->DelFd(this->sock);
569 /* NOTE: We must set this AFTER DelFd, as we added
570 * this socket whilst writeable. This means that we
571 * must DELETE the socket whilst writeable too!
573 this->sock->state = I_ERROR;
580 this->sock->Timeout = NULL;
584 bool InspSocket::Poll()
586 if (this->Instance->SE->GetRef(this->fd) != this)
591 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
597 /* Our socket was in write-state, so delete it and re-add it
602 this->Instance->SE->DelFd(this);
603 this->SetState(I_CONNECTED);
604 if (!this->Instance->SE->AddFd(this))
607 if (Instance->Config->GetIOHook(this))
611 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
613 catch (CoreException& modexcept)
615 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
618 return this->OnConnected();
622 sockaddr* client = new sockaddr[2];
623 length = sizeof (sockaddr_in);
626 if ((!*this->host) || strchr(this->host, ':'))
627 length = sizeof(sockaddr_in6);
629 incoming = accept (this->fd, client, &length);
631 if ((!*this->host) || strchr(this->host, ':'))
634 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
638 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
641 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
643 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
645 if (this->IsIOHooked)
649 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
651 catch (CoreException& modexcept)
653 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
657 this->SetQueues(incoming);
664 /* Process the read event */
665 return this->OnDataReady();
673 void InspSocket::SetState(InspSocketState s)
678 InspSocketState InspSocket::GetState()
683 int InspSocket::GetFd()
688 bool InspSocket::OnConnected() { return true; }
689 void InspSocket::OnError(InspSocketError e) { return; }
690 int InspSocket::OnDisconnect() { return 0; }
691 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
692 bool InspSocket::OnDataReady() { return true; }
693 bool InspSocket::OnWriteReady() { return true; }
694 void InspSocket::OnTimeout() { return; }
695 void InspSocket::OnClose() { return; }
697 InspSocket::~InspSocket()
702 Instance->Timers->DelTimer(Timeout);
707 void InspSocket::HandleEvent(EventType et, int errornum)
712 this->Instance->SE->DelFd(this);
720 this->Instance->SE->DelFd(this);
727 if (this->WaitingForWriteEvent)
729 this->WaitingForWriteEvent = false;
730 if (!this->OnWriteReady())
732 this->Instance->SE->DelFd(this);
738 if (this->state == I_CONNECTING)
740 /* This might look wrong as if we should be actually calling
741 * with EVENT_WRITE, but trust me it is correct. There are some
742 * writeability-state things in the read code, because of how
743 * InspSocket used to work regarding write buffering in previous
744 * versions of InspIRCd. - Brain
746 this->HandleEvent(EVENT_READ);
751 if (this->FlushWriteBuffer())
753 this->Instance->SE->DelFd(this);