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)
31 this->state = I_DISCONNECTED;
33 this->WaitingForWriteEvent = false;
35 this->IsIOHooked = false;
38 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)
54 strlcpy(host,ipaddr.c_str(),MAXBUF);
55 this->WaitingForWriteEvent = false;
56 this->IsIOHooked = false;
59 if ((this->fd = OpenTCPSocket(host)) == ERROR)
62 this->state = I_ERROR;
63 this->OnError(I_ERR_SOCKET);
68 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
72 this->state = I_ERROR;
73 this->OnError(I_ERR_BIND);
74 this->ClosePending = true;
79 this->state = I_LISTENING;
82 if (!this->Instance->SE->AddFd(this))
85 this->state = I_ERROR;
86 this->OnError(I_ERR_NOMOREFDS);
95 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
100 if (strchr(host,':'))
103 if (inet_pton(AF_INET6, host, &n) < 1)
109 if (inet_aton(host,&n) < 1)
114 if (inet_aton(host,&n) < 1)
119 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
122 this->state = I_ERROR;
123 this->OnError(I_ERR_RESOLVE);
128 strlcpy(this->IP,host,MAXBUF);
129 timeout_val = maxtime;
135 void InspSocket::WantWrite()
137 this->Instance->SE->WantWrite(this);
138 this->WaitingForWriteEvent = true;
141 void InspSocket::SetQueues(int nfd)
143 // attempt to increase socket sendq and recvq as high as its possible
146 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
147 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
150 /* Most irc servers require you to specify the ip you want to bind to.
151 * If you dont specify an IP, they rather dumbly bind to the first IP
152 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
153 * addresses we've bound server ports to, and we try and bind our outbound
154 * connections to the first usable non-loopback and non-any IP we find.
155 * This is easier to configure when you have a lot of links and a lot
156 * of servers to configure.
158 bool InspSocket::BindAddr()
160 ConfigReader Conf(this->Instance);
161 bool bindfail = false;
162 socklen_t size = sizeof(sockaddr_in);
165 /* Are we looking for a binding to fit an ipv6 host? */
166 if ((!*this->host) || strchr(this->host, ':'))
169 for (int j =0; j < Conf.Enumerate("bind"); j++)
171 std::string Type = Conf.ReadValue("bind","type",j);
172 std::string IP = Conf.ReadValue("bind","address",j);
173 if (Type == "servers")
175 if ((IP != "*") && (IP != "127.0.0.1") && (IP != "") && (IP != "::1"))
177 sockaddr* s = new sockaddr[2];
182 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
184 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
185 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
186 size = sizeof(sockaddr_in6);
194 if (inet_aton(IP.c_str(), &n) > 0)
196 ((sockaddr_in*)s)->sin_addr = n;
197 ((sockaddr_in*)s)->sin_family = AF_INET;
204 if (insp_aton(IP.c_str(), &n) > 0)
206 ((sockaddr_in*)s)->sin_addr = n;
207 ((sockaddr_in*)s)->sin_family = AF_INET;
218 if (bind(this->fd, s, size) < 0)
220 this->state = I_ERROR;
221 this->OnError(I_ERR_BIND);
235 bool InspSocket::DoConnect()
237 sockaddr* addr = new sockaddr[2];
238 socklen_t size = sizeof(sockaddr_in);
241 if ((!*this->host) || strchr(this->host, ':'))
246 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
247 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
249 if (!this->BindAddr())
258 this->fd = socket(AF_INET, SOCK_STREAM, 0);
261 this->fd = socket(AF_INET, SOCK_STREAM, 0);
266 this->state = I_ERROR;
267 this->OnError(I_ERR_SOCKET);
276 if (inet_pton(AF_INET6, this->host, &addy) > 0)
278 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
279 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
280 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
281 size = sizeof(sockaddr_in6);
287 if (inet_aton(this->host, &addy) > 0)
289 ((sockaddr_in*)addr)->sin_family = AF_INET;
290 ((sockaddr_in*)addr)->sin_addr = addy;
291 ((sockaddr_in*)addr)->sin_port = htons(this->port);
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 if (connect(this->fd, (sockaddr*)addr, size) == -1)
309 if (errno != EINPROGRESS)
311 this->OnError(I_ERR_CONNECT);
313 this->state = I_ERROR;
317 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
318 this->Instance->Timers->AddTimer(this->Timeout);
320 this->state = I_CONNECTING;
323 if (!this->Instance->SE->AddFd(this))
325 this->OnError(I_ERR_NOMOREFDS);
327 this->state = I_ERROR;
330 this->SetQueues(this->fd);
336 void InspSocket::Close()
338 /* Save this, so we dont lose it,
339 * otherise on failure, error messages
340 * might be inaccurate.
345 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
349 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
351 catch (CoreException& modexcept)
353 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
357 shutdown(this->fd,2);
363 std::string InspSocket::GetIP()
368 char* InspSocket::Read()
370 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
375 if (this->IsIOHooked)
381 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
383 catch (CoreException& modexcept)
385 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
399 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
402 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
417 void InspSocket::MarkAsClosed()
421 // There are two possible outcomes to this function.
422 // It will either write all of the data, or an undefined amount.
423 // If an undefined amount is written the connection has failed
424 // and should be aborted.
425 int InspSocket::Write(const std::string &data)
427 /* Try and append the data to the back of the queue, and send it on its way
429 outbuffer.push_back(data);
430 this->Instance->SE->WantWrite(this);
431 return (!this->FlushWriteBuffer());
434 bool InspSocket::FlushWriteBuffer()
437 if ((this->fd > -1) && (this->state == I_CONNECTED))
439 if (this->IsIOHooked)
441 while (outbuffer.size() && (errno != EAGAIN))
445 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
448 if ((unsigned int)result == outbuffer[0].length())
450 outbuffer.pop_front();
454 std::string temp = outbuffer[0].substr(result);
459 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
461 this->OnError(I_ERR_WRITE);
462 this->state = I_ERROR;
463 this->Instance->SE->DelFd(this);
468 catch (CoreException& modexcept)
470 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
477 /* If we have multiple lines, try to send them all,
478 * not just the first one -- Brain
480 while (outbuffer.size() && (errno != EAGAIN))
483 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
486 if ((unsigned int)result == outbuffer[0].length())
488 /* The whole block was written (usually a line)
489 * Pop the block off the front of the queue,
490 * dont set errno, because we are clear of errors
491 * and want to try and write the next block too.
493 outbuffer.pop_front();
497 std::string temp = outbuffer[0].substr(result);
499 /* We didnt get the whole line out. arses.
500 * Try again next time, i guess. Set errno,
501 * because we shouldnt be writing any more now,
502 * until the socketengine says its safe to do so.
507 else if ((result == -1) && (errno != EAGAIN))
509 this->OnError(I_ERR_WRITE);
510 this->state = I_ERROR;
511 this->Instance->SE->DelFd(this);
519 if ((errno == EAGAIN) && (fd > -1))
521 this->Instance->SE->WantWrite(this);
527 void SocketTimeout::Tick(time_t now)
529 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
532 if (this->sock->state == I_CONNECTING)
534 // for non-listening sockets, the timeout can occur
535 // which causes termination of the connection after
536 // the given number of seconds without a successful
538 this->sock->OnTimeout();
539 this->sock->OnError(I_ERR_TIMEOUT);
540 this->sock->timeout = true;
541 ServerInstance->SE->DelFd(this->sock);
542 /* NOTE: We must set this AFTER DelFd, as we added
543 * this socket whilst writeable. This means that we
544 * must DELETE the socket whilst writeable too!
546 this->sock->state = I_ERROR;
553 bool InspSocket::Poll()
555 if (this->Instance->SE->GetRef(this->fd) != this)
560 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
566 /* Our socket was in write-state, so delete it and re-add it
571 this->Instance->SE->DelFd(this);
572 this->SetState(I_CONNECTED);
573 if (!this->Instance->SE->AddFd(this))
576 if (Instance->Config->GetIOHook(this))
580 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
582 catch (CoreException& modexcept)
584 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
587 return this->OnConnected();
591 sockaddr* client = new sockaddr[2];
592 length = sizeof (sockaddr_in);
595 if ((!*this->host) || strchr(this->host, ':'))
596 length = sizeof(sockaddr_in6);
598 incoming = accept (this->fd, client, &length);
601 if ((!*this->host) || strchr(this->host, ':'))
604 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
608 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
611 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
613 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
615 if (this->IsIOHooked)
619 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
621 catch (CoreException& modexcept)
623 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
627 this->SetQueues(incoming);
634 /* Process the read event */
635 return this->OnDataReady();
643 void InspSocket::SetState(InspSocketState s)
648 InspSocketState InspSocket::GetState()
653 int InspSocket::GetFd()
658 bool InspSocket::OnConnected() { return true; }
659 void InspSocket::OnError(InspSocketError e) { return; }
660 int InspSocket::OnDisconnect() { return 0; }
661 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
662 bool InspSocket::OnDataReady() { return true; }
663 bool InspSocket::OnWriteReady() { return true; }
664 void InspSocket::OnTimeout() { return; }
665 void InspSocket::OnClose() { return; }
667 InspSocket::~InspSocket()
672 Instance->Timers->DelTimer(Timeout);
677 void InspSocket::HandleEvent(EventType et, int errornum)
682 this->Instance->SE->DelFd(this);
690 this->Instance->SE->DelFd(this);
697 if (this->WaitingForWriteEvent)
699 this->WaitingForWriteEvent = false;
700 if (!this->OnWriteReady())
702 this->Instance->SE->DelFd(this);
708 if (this->state == I_CONNECTING)
710 /* This might look wrong as if we should be actually calling
711 * with EVENT_WRITE, but trust me it is correct. There are some
712 * writeability-state things in the read code, because of how
713 * InspSocket used to work regarding write buffering in previous
714 * versions of InspIRCd. - Brain
716 this->HandleEvent(EVENT_READ);
721 if (this->FlushWriteBuffer())
723 this->Instance->SE->DelFd(this);