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)
56 strlcpy(host,ipaddr.c_str(),MAXBUF);
57 this->WaitingForWriteEvent = false;
58 this->IsIOHooked = false;
62 if ((this->fd = OpenTCPSocket(host)) == ERROR)
65 this->state = I_ERROR;
66 this->OnError(I_ERR_SOCKET);
71 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
75 this->state = I_ERROR;
76 this->OnError(I_ERR_BIND);
77 this->ClosePending = true;
82 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!");
125 this->state = I_ERROR;
126 this->OnError(I_ERR_RESOLVE);
131 strlcpy(this->IP,host,MAXBUF);
132 timeout_val = maxtime;
138 void InspSocket::WantWrite()
140 this->Instance->SE->WantWrite(this);
141 this->WaitingForWriteEvent = true;
144 void InspSocket::SetQueues(int nfd)
146 // attempt to increase socket sendq and recvq as high as its possible
149 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
150 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
153 /* Most irc servers require you to specify the ip you want to bind to.
154 * If you dont specify an IP, they rather dumbly bind to the first IP
155 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
156 * addresses we've bound server ports to, and we try and bind our outbound
157 * connections to the first usable non-loopback and non-any IP we find.
158 * This is easier to configure when you have a lot of links and a lot
159 * of servers to configure.
161 bool InspSocket::BindAddr()
163 ConfigReader Conf(this->Instance);
164 bool bindfail = false;
165 socklen_t size = sizeof(sockaddr_in);
168 /* Are we looking for a binding to fit an ipv6 host? */
169 if ((!*this->host) || strchr(this->host, ':'))
172 for (int j =0; j < Conf.Enumerate("bind"); j++)
174 std::string Type = Conf.ReadValue("bind","type",j);
175 std::string IP = Conf.ReadValue("bind","address",j);
176 if (Type == "servers")
178 if ((IP != "*") && (IP != "127.0.0.1") && (IP != "") && (IP != "::1"))
180 sockaddr* s = new sockaddr[2];
185 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
187 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
188 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
189 size = sizeof(sockaddr_in6);
197 if (inet_aton(IP.c_str(), &n) > 0)
199 ((sockaddr_in*)s)->sin_addr = n;
200 ((sockaddr_in*)s)->sin_family = AF_INET;
207 if (insp_aton(IP.c_str(), &n) > 0)
209 ((sockaddr_in*)s)->sin_addr = n;
210 ((sockaddr_in*)s)->sin_family = AF_INET;
221 if (bind(this->fd, s, size) < 0)
223 this->state = I_ERROR;
224 this->OnError(I_ERR_BIND);
238 bool InspSocket::DoConnect()
240 sockaddr* addr = new sockaddr[2];
241 socklen_t size = sizeof(sockaddr_in);
244 if ((!*this->host) || strchr(this->host, ':'))
249 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
250 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
252 if (!this->BindAddr())
261 this->fd = socket(AF_INET, SOCK_STREAM, 0);
264 this->fd = socket(AF_INET, SOCK_STREAM, 0);
269 this->state = I_ERROR;
270 this->OnError(I_ERR_SOCKET);
279 if (inet_pton(AF_INET6, this->host, &addy) > 0)
281 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
282 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
283 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
284 size = sizeof(sockaddr_in6);
290 if (inet_aton(this->host, &addy) > 0)
292 ((sockaddr_in*)addr)->sin_family = AF_INET;
293 ((sockaddr_in*)addr)->sin_addr = addy;
294 ((sockaddr_in*)addr)->sin_port = htons(this->port);
299 if (inet_aton(this->host, &addy) > 0)
301 ((sockaddr_in*)addr)->sin_family = AF_INET;
302 ((sockaddr_in*)addr)->sin_addr = addy;
303 ((sockaddr_in*)addr)->sin_port = htons(this->port);
307 int flags = fcntl(this->fd, F_GETFL, 0);
308 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
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()
373 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
378 if (this->IsIOHooked)
384 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
386 catch (CoreException& modexcept)
388 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
402 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
405 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
420 void InspSocket::MarkAsClosed()
424 // There are two possible outcomes to this function.
425 // It will either write all of the data, or an undefined amount.
426 // If an undefined amount is written the connection has failed
427 // and should be aborted.
428 int InspSocket::Write(const std::string &data)
430 /* Try and append the data to the back of the queue, and send it on its way
432 outbuffer.push_back(data);
433 this->Instance->SE->WantWrite(this);
434 return (!this->FlushWriteBuffer());
437 bool InspSocket::FlushWriteBuffer()
440 if ((this->fd > -1) && (this->state == I_CONNECTED))
442 if (this->IsIOHooked)
444 while (outbuffer.size() && (errno != EAGAIN))
448 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
451 if ((unsigned int)result == outbuffer[0].length())
453 outbuffer.pop_front();
457 std::string temp = outbuffer[0].substr(result);
462 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
464 this->OnError(I_ERR_WRITE);
465 this->state = I_ERROR;
466 this->Instance->SE->DelFd(this);
471 catch (CoreException& modexcept)
473 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
480 /* If we have multiple lines, try to send them all,
481 * not just the first one -- Brain
483 while (outbuffer.size() && (errno != EAGAIN))
486 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
489 if ((unsigned int)result == outbuffer[0].length())
491 /* The whole block was written (usually a line)
492 * Pop the block off the front of the queue,
493 * dont set errno, because we are clear of errors
494 * and want to try and write the next block too.
496 outbuffer.pop_front();
500 std::string temp = outbuffer[0].substr(result);
502 /* We didnt get the whole line out. arses.
503 * Try again next time, i guess. Set errno,
504 * because we shouldnt be writing any more now,
505 * until the socketengine says its safe to do so.
510 else if ((result == -1) && (errno != EAGAIN))
512 this->OnError(I_ERR_WRITE);
513 this->state = I_ERROR;
514 this->Instance->SE->DelFd(this);
522 if ((errno == EAGAIN) && (fd > -1))
524 this->Instance->SE->WantWrite(this);
530 void SocketTimeout::Tick(time_t now)
532 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
535 if (this->sock->state == I_CONNECTING)
537 // for non-listening sockets, the timeout can occur
538 // which causes termination of the connection after
539 // the given number of seconds without a successful
541 this->sock->OnTimeout();
542 this->sock->OnError(I_ERR_TIMEOUT);
543 this->sock->timeout = true;
544 ServerInstance->SE->DelFd(this->sock);
545 /* NOTE: We must set this AFTER DelFd, as we added
546 * this socket whilst writeable. This means that we
547 * must DELETE the socket whilst writeable too!
549 this->sock->state = I_ERROR;
556 this->sock->Timeout = NULL;
560 bool InspSocket::Poll()
562 if (this->Instance->SE->GetRef(this->fd) != this)
567 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
573 /* Our socket was in write-state, so delete it and re-add it
578 this->Instance->SE->DelFd(this);
579 this->SetState(I_CONNECTED);
580 if (!this->Instance->SE->AddFd(this))
583 if (Instance->Config->GetIOHook(this))
587 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
589 catch (CoreException& modexcept)
591 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
594 return this->OnConnected();
598 Instance->Log(DEBUG,"InspSocket listen event");
599 sockaddr* client = new sockaddr[2];
600 length = sizeof (sockaddr_in);
603 if ((!*this->host) || strchr(this->host, ':'))
604 length = sizeof(sockaddr_in6);
606 incoming = accept (this->fd, client, &length);
608 Instance->Log(DEBUG,"Accepted socket, sockaddr length %d fd %d", length, incoming);
611 if ((!*this->host) || strchr(this->host, ':'))
614 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
618 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
621 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
623 Instance->Log(DEBUG,"Call OnIncomingConnection, recvip=%s", recvip.c_str());
624 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
626 if (this->IsIOHooked)
630 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
632 catch (CoreException& modexcept)
634 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
638 this->SetQueues(incoming);
645 /* Process the read event */
646 return this->OnDataReady();
654 void InspSocket::SetState(InspSocketState s)
659 InspSocketState InspSocket::GetState()
664 int InspSocket::GetFd()
669 bool InspSocket::OnConnected() { return true; }
670 void InspSocket::OnError(InspSocketError e) { return; }
671 int InspSocket::OnDisconnect() { return 0; }
672 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
673 bool InspSocket::OnDataReady() { return true; }
674 bool InspSocket::OnWriteReady() { return true; }
675 void InspSocket::OnTimeout() { return; }
676 void InspSocket::OnClose() { return; }
678 InspSocket::~InspSocket()
683 Instance->Timers->DelTimer(Timeout);
688 void InspSocket::HandleEvent(EventType et, int errornum)
693 this->Instance->SE->DelFd(this);
701 this->Instance->SE->DelFd(this);
708 if (this->WaitingForWriteEvent)
710 this->WaitingForWriteEvent = false;
711 if (!this->OnWriteReady())
713 this->Instance->SE->DelFd(this);
719 if (this->state == I_CONNECTING)
721 /* This might look wrong as if we should be actually calling
722 * with EVENT_WRITE, but trust me it is correct. There are some
723 * writeability-state things in the read code, because of how
724 * InspSocket used to work regarding write buffering in previous
725 * versions of InspIRCd. - Brain
727 this->HandleEvent(EVENT_READ);
732 if (this->FlushWriteBuffer())
734 this->Instance->SE->DelFd(this);