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 "inspstring.h"
16 #include "socketengine.h"
19 using irc::sockets::OpenTCPSocket;
21 bool InspSocket::Readable()
23 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
26 InspSocket::InspSocket(InspIRCd* SI)
29 this->state = I_DISCONNECTED;
31 this->WaitingForWriteEvent = false;
33 this->IsIOHooked = false;
36 InspSocket::InspSocket(InspIRCd* SI, int newfd, const char* ip)
40 this->state = I_CONNECTED;
41 strlcpy(this->IP,ip,MAXBUF);
42 this->WaitingForWriteEvent = false;
44 this->IsIOHooked = false;
46 this->Instance->SE->AddFd(this);
49 InspSocket::InspSocket(InspIRCd* SI, const std::string &ipaddr, int aport, bool listening, unsigned long maxtime, const std::string &connectbindip)
51 this->cbindip = connectbindip;
54 strlcpy(host,ipaddr.c_str(),MAXBUF);
55 this->WaitingForWriteEvent = false;
56 this->IsIOHooked = false;
60 if ((this->fd = OpenTCPSocket(host)) == ERROR)
63 this->state = I_ERROR;
64 this->OnError(I_ERR_SOCKET);
69 if (!SI->BindSocket(this->fd,aport,(char*)ipaddr.c_str()))
73 this->state = I_ERROR;
74 this->OnError(I_ERR_BIND);
75 this->ClosePending = true;
80 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)
112 if (inet_aton(host,&n) < 1)
117 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
118 this->OnError(I_ERR_CONNECT);
121 this->state = I_ERROR;
126 strlcpy(this->IP,host,MAXBUF);
127 timeout_val = maxtime;
128 if (!this->DoConnect())
130 this->OnError(I_ERR_CONNECT);
133 this->state = I_ERROR;
140 void InspSocket::WantWrite()
142 this->Instance->SE->WantWrite(this);
143 this->WaitingForWriteEvent = true;
146 void InspSocket::SetQueues(int nfd)
148 // attempt to increase socket sendq and recvq as high as its possible
151 if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
152 this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
155 /* Most irc servers require you to specify the ip you want to bind to.
156 * If you dont specify an IP, they rather dumbly bind to the first IP
157 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
158 * addresses we've bound server ports to, and we try and bind our outbound
159 * connections to the first usable non-loopback and non-any IP we find.
160 * This is easier to configure when you have a lot of links and a lot
161 * of servers to configure.
163 bool InspSocket::BindAddr(const std::string &ip)
165 ConfigReader Conf(this->Instance);
166 socklen_t size = sizeof(sockaddr_in);
169 /* Are we looking for a binding to fit an ipv6 host? */
170 if ((ip.empty()) || (ip.find(':') != std::string::npos))
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.empty()) && (IP != "::1")))
181 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
182 sockaddr* s = new sockaddr[2];
187 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
189 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
190 ((sockaddr_in6*)s)->sin6_port = 0;
191 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
192 size = sizeof(sockaddr_in6);
205 if (inet_aton(IP.c_str(), &n) > 0)
207 ((sockaddr_in*)s)->sin_addr = n;
208 ((sockaddr_in*)s)->sin_port = 0;
209 ((sockaddr_in*)s)->sin_family = AF_INET;
219 if (Instance->SE->Bind(this->fd, s, size) < 0)
221 this->state = I_ERROR;
222 this->OnError(I_ERR_BIND);
237 bool InspSocket::DoConnect()
239 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
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(this->cbindip))
262 this->fd = socket(AF_INET, SOCK_STREAM, 0);
265 if (!this->BindAddr(this->cbindip))
275 this->state = I_ERROR;
276 this->OnError(I_ERR_SOCKET);
285 if (inet_pton(AF_INET6, this->host, &addy) > 0)
287 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
288 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
289 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
290 size = sizeof(sockaddr_in6);
297 if (inet_aton(this->host, &addy) > 0)
299 ((sockaddr_in*)addr)->sin_family = AF_INET;
300 ((sockaddr_in*)addr)->sin_addr = addy;
301 ((sockaddr_in*)addr)->sin_port = htons(this->port);
305 Instance->SE->NonBlocking(this->fd);
308 /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
309 Instance->SE->Blocking(this->fd);
312 if (Instance->SE->Connect(this, (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);
326 /* CRAQ SMOKING STUFF TO BE FIXED */
327 Instance->SE->NonBlocking(this->fd);
329 this->state = I_CONNECTING;
332 if (!this->Instance->SE->AddFd(this))
334 this->OnError(I_ERR_NOMOREFDS);
336 this->state = I_ERROR;
339 this->SetQueues(this->fd);
345 void InspSocket::Close()
347 /* Save this, so we dont lose it,
348 * otherise on failure, error messages
349 * might be inaccurate.
354 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
358 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
360 catch (CoreException& modexcept)
362 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
365 Instance->SE->Shutdown(this, 2);
366 if (Instance->SE->Close(this) != -1)
369 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
370 Instance->SocketCull[this] = this;
375 std::string InspSocket::GetIP()
380 char* InspSocket::Read()
382 if (!Instance->SE->BoundsCheckFd(this))
387 if (this->IsIOHooked)
393 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
395 catch (CoreException& modexcept)
397 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
411 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
414 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
429 void InspSocket::MarkAsClosed()
433 // There are two possible outcomes to this function.
434 // It will either write all of the data, or an undefined amount.
435 // If an undefined amount is written the connection has failed
436 // and should be aborted.
437 int InspSocket::Write(const std::string &data)
439 /* Try and append the data to the back of the queue, and send it on its way
441 outbuffer.push_back(data);
442 this->Instance->SE->WantWrite(this);
443 return (!this->FlushWriteBuffer());
446 bool InspSocket::FlushWriteBuffer()
449 if ((this->fd > -1) && (this->state == I_CONNECTED))
451 if (this->IsIOHooked)
453 while (outbuffer.size() && (errno != EAGAIN))
457 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
458 * implement their own buffering mechanisms
460 Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
461 outbuffer.pop_front();
463 catch (CoreException& modexcept)
465 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
472 /* If we have multiple lines, try to send them all,
473 * not just the first one -- Brain
475 while (outbuffer.size() && (errno != EAGAIN))
478 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
482 if ((unsigned int)result >= outbuffer[0].length())
484 /* The whole block was written (usually a line)
485 * Pop the block off the front of the queue,
486 * dont set errno, because we are clear of errors
487 * and want to try and write the next block too.
489 outbuffer.pop_front();
493 std::string temp = outbuffer[0].substr(result);
495 /* We didnt get the whole line out. arses.
496 * Try again next time, i guess. Set errno,
497 * because we shouldnt be writing any more now,
498 * until the socketengine says its safe to do so.
503 else if ((result == -1) && (errno != EAGAIN))
505 this->OnError(I_ERR_WRITE);
506 this->state = I_ERROR;
507 this->Instance->SE->DelFd(this);
515 if ((errno == EAGAIN) && (fd > -1))
517 this->Instance->SE->WantWrite(this);
523 void SocketTimeout::Tick(time_t now)
525 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
528 if (this->sock->state == I_CONNECTING)
530 // for non-listening sockets, the timeout can occur
531 // which causes termination of the connection after
532 // the given number of seconds without a successful
534 this->sock->OnTimeout();
535 this->sock->OnError(I_ERR_TIMEOUT);
536 this->sock->timeout = true;
538 /* NOTE: We must set this AFTER DelFd, as we added
539 * this socket whilst writeable. This means that we
540 * must DELETE the socket whilst writeable too!
542 this->sock->state = I_ERROR;
544 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
545 ServerInstance->SocketCull[this->sock] = this->sock;
548 this->sock->Timeout = NULL;
551 bool InspSocket::Poll()
556 if (!Instance->SE->BoundsCheckFd(this))
560 if (Instance->SE->GetRef(this->fd) != this)
566 /* Our socket was in write-state, so delete it and re-add it
572 this->Instance->SE->DelFd(this);
573 if (!this->Instance->SE->AddFd(this))
577 this->SetState(I_CONNECTED);
579 if (Instance->Config->GetIOHook(this))
581 Instance->Log(DEBUG,"Hook for raw connect");
584 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
586 catch (CoreException& modexcept)
588 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
591 return this->OnConnected();
595 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
596 sockaddr* client = new sockaddr[2];
597 length = sizeof (sockaddr_in);
600 if ((!*this->host) || strchr(this->host, ':'))
601 length = sizeof(sockaddr_in6);
603 incoming = Instance->SE->Accept(this, client, &length);
605 if ((!*this->host) || strchr(this->host, ':'))
608 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
612 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)
685 this->OnError(I_ERR_TIMEOUT);
689 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
692 this->OnError(I_ERR_BIND);
696 this->OnError(I_ERR_WRITE);
699 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
700 this->Instance->SocketCull[this] = this;
706 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
707 this->Instance->SocketCull[this] = this;
712 if (this->WaitingForWriteEvent)
714 this->WaitingForWriteEvent = false;
715 if (!this->OnWriteReady())
717 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
718 this->Instance->SocketCull[this] = this;
722 if (this->state == I_CONNECTING)
724 /* This might look wrong as if we should be actually calling
725 * with EVENT_WRITE, but trust me it is correct. There are some
726 * writeability-state things in the read code, because of how
727 * InspSocket used to work regarding write buffering in previous
728 * versions of InspIRCd. - Brain
730 this->HandleEvent(EVENT_READ);
735 if (this->FlushWriteBuffer())
737 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
738 this->Instance->SocketCull[this] = this;