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;
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;
83 if (!this->Instance->SE->AddFd(this))
86 this->state = I_ERROR;
87 this->OnError(I_ERR_NOMOREFDS);
96 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
101 if (strchr(host,':'))
104 if (inet_pton(AF_INET6, host, &n) < 1)
110 if (inet_aton(host,&n) < 1)
115 if (inet_aton(host,&n) < 1)
120 this->Instance->Log(DEBUG,"BUG: Hostname passed to InspSocket, rather than an IP address!");
123 this->state = I_ERROR;
124 this->OnError(I_ERR_RESOLVE);
129 strlcpy(this->IP,host,MAXBUF);
130 timeout_val = maxtime;
136 void InspSocket::WantWrite()
138 this->Instance->SE->WantWrite(this);
139 this->WaitingForWriteEvent = true;
142 void InspSocket::SetQueues(int nfd)
144 // attempt to increase socket sendq and recvq as high as its possible
147 setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf));
148 setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf));
151 /* Most irc servers require you to specify the ip you want to bind to.
152 * If you dont specify an IP, they rather dumbly bind to the first IP
153 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
154 * addresses we've bound server ports to, and we try and bind our outbound
155 * connections to the first usable non-loopback and non-any IP we find.
156 * This is easier to configure when you have a lot of links and a lot
157 * of servers to configure.
159 bool InspSocket::BindAddr()
161 ConfigReader Conf(this->Instance);
162 bool bindfail = false;
163 socklen_t size = sizeof(sockaddr_in);
166 /* Are we looking for a binding to fit an ipv6 host? */
167 if ((!*this->host) || strchr(this->host, ':'))
170 for (int j =0; j < Conf.Enumerate("bind"); j++)
172 std::string Type = Conf.ReadValue("bind","type",j);
173 std::string IP = Conf.ReadValue("bind","address",j);
174 if (Type == "servers")
176 if ((IP != "*") && (IP != "127.0.0.1") && (IP != "") && (IP != "::1"))
178 sockaddr* s = new sockaddr[2];
183 if (inet_pton(AF_INET6, IP.c_str(), &n) > 0)
185 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(n));
186 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
187 size = sizeof(sockaddr_in6);
195 if (inet_aton(IP.c_str(), &n) > 0)
197 ((sockaddr_in*)s)->sin_addr = n;
198 ((sockaddr_in*)s)->sin_family = AF_INET;
205 if (insp_aton(IP.c_str(), &n) > 0)
207 ((sockaddr_in*)s)->sin_addr = n;
208 ((sockaddr_in*)s)->sin_family = AF_INET;
219 if (bind(this->fd, s, size) < 0)
221 this->state = I_ERROR;
222 this->OnError(I_ERR_BIND);
236 bool InspSocket::DoConnect()
238 sockaddr* addr = new sockaddr[2];
239 socklen_t size = sizeof(sockaddr_in);
242 if ((!*this->host) || strchr(this->host, ':'))
247 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
248 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
250 if (!this->BindAddr())
259 this->fd = socket(AF_INET, SOCK_STREAM, 0);
262 this->fd = socket(AF_INET, SOCK_STREAM, 0);
267 this->state = I_ERROR;
268 this->OnError(I_ERR_SOCKET);
277 if (inet_pton(AF_INET6, this->host, &addy) > 0)
279 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
280 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
281 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
282 size = sizeof(sockaddr_in6);
288 if (inet_aton(this->host, &addy) > 0)
290 ((sockaddr_in*)addr)->sin_family = AF_INET;
291 ((sockaddr_in*)addr)->sin_addr = addy;
292 ((sockaddr_in*)addr)->sin_port = htons(this->port);
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 int flags = fcntl(this->fd, F_GETFL, 0);
306 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
308 if (connect(this->fd, (sockaddr*)addr, size) == -1)
310 if (errno != EINPROGRESS)
312 this->OnError(I_ERR_CONNECT);
314 this->state = I_ERROR;
318 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
319 this->Instance->Timers->AddTimer(this->Timeout);
321 this->state = I_CONNECTING;
324 if (!this->Instance->SE->AddFd(this))
326 this->OnError(I_ERR_NOMOREFDS);
328 this->state = I_ERROR;
331 this->SetQueues(this->fd);
337 void InspSocket::Close()
339 /* Save this, so we dont lose it,
340 * otherise on failure, error messages
341 * might be inaccurate.
346 if (this->IsIOHooked && Instance->Config->GetIOHook(this))
350 Instance->Config->GetIOHook(this)->OnRawSocketClose(this->fd);
352 catch (CoreException& modexcept)
354 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
358 shutdown(this->fd,2);
364 std::string InspSocket::GetIP()
369 char* InspSocket::Read()
371 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
376 if (this->IsIOHooked)
382 MOD_RESULT = Instance->Config->GetIOHook(this)->OnRawSocketRead(this->fd,this->ibuf,sizeof(this->ibuf),result2);
384 catch (CoreException& modexcept)
386 Instance->Log(DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
400 n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
403 if ((n > 0) && (n <= (int)sizeof(this->ibuf)))
418 void InspSocket::MarkAsClosed()
422 // There are two possible outcomes to this function.
423 // It will either write all of the data, or an undefined amount.
424 // If an undefined amount is written the connection has failed
425 // and should be aborted.
426 int InspSocket::Write(const std::string &data)
428 /* Try and append the data to the back of the queue, and send it on its way
430 outbuffer.push_back(data);
431 this->Instance->SE->WantWrite(this);
432 return (!this->FlushWriteBuffer());
435 bool InspSocket::FlushWriteBuffer()
438 if ((this->fd > -1) && (this->state == I_CONNECTED))
440 if (this->IsIOHooked)
442 while (outbuffer.size() && (errno != EAGAIN))
446 int result = Instance->Config->GetIOHook(this)->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
449 if ((unsigned int)result == outbuffer[0].length())
451 outbuffer.pop_front();
455 std::string temp = outbuffer[0].substr(result);
460 else if (((result == -1) && (errno != EAGAIN)) || (result == 0))
462 this->OnError(I_ERR_WRITE);
463 this->state = I_ERROR;
464 this->Instance->SE->DelFd(this);
469 catch (CoreException& modexcept)
471 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
478 /* If we have multiple lines, try to send them all,
479 * not just the first one -- Brain
481 while (outbuffer.size() && (errno != EAGAIN))
484 int result = write(this->fd,outbuffer[0].c_str(),outbuffer[0].length());
487 if ((unsigned int)result == outbuffer[0].length())
489 /* The whole block was written (usually a line)
490 * Pop the block off the front of the queue,
491 * dont set errno, because we are clear of errors
492 * and want to try and write the next block too.
494 outbuffer.pop_front();
498 std::string temp = outbuffer[0].substr(result);
500 /* We didnt get the whole line out. arses.
501 * Try again next time, i guess. Set errno,
502 * because we shouldnt be writing any more now,
503 * until the socketengine says its safe to do so.
508 else if ((result == -1) && (errno != EAGAIN))
510 this->OnError(I_ERR_WRITE);
511 this->state = I_ERROR;
512 this->Instance->SE->DelFd(this);
520 if ((errno == EAGAIN) && (fd > -1))
522 this->Instance->SE->WantWrite(this);
528 void SocketTimeout::Tick(time_t now)
530 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
533 if (this->sock->state == I_CONNECTING)
535 // for non-listening sockets, the timeout can occur
536 // which causes termination of the connection after
537 // the given number of seconds without a successful
539 this->sock->OnTimeout();
540 this->sock->OnError(I_ERR_TIMEOUT);
541 this->sock->timeout = true;
542 ServerInstance->SE->DelFd(this->sock);
543 /* NOTE: We must set this AFTER DelFd, as we added
544 * this socket whilst writeable. This means that we
545 * must DELETE the socket whilst writeable too!
547 this->sock->state = I_ERROR;
554 bool InspSocket::Poll()
556 if (this->Instance->SE->GetRef(this->fd) != this)
561 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
567 /* Our socket was in write-state, so delete it and re-add it
572 this->Instance->SE->DelFd(this);
573 this->SetState(I_CONNECTED);
574 if (!this->Instance->SE->AddFd(this))
577 if (Instance->Config->GetIOHook(this))
581 Instance->Config->GetIOHook(this)->OnRawSocketConnect(this->fd);
583 catch (CoreException& modexcept)
585 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
588 return this->OnConnected();
592 sockaddr* client = new sockaddr[2];
593 length = sizeof (sockaddr_in);
596 if ((!*this->host) || strchr(this->host, ':'))
597 length = sizeof(sockaddr_in6);
599 incoming = accept (this->fd, client, &length);
602 if ((!*this->host) || strchr(this->host, ':'))
605 recvip = inet_ntop(AF_INET6, &((sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
609 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
612 recvip = inet_ntoa(((sockaddr_in*)client)->sin_addr);
614 this->OnIncomingConnection(incoming, (char*)recvip.c_str());
616 if (this->IsIOHooked)
620 Instance->Config->GetIOHook(this)->OnRawSocketAccept(incoming, recvip.c_str(), this->port);
622 catch (CoreException& modexcept)
624 Instance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
628 this->SetQueues(incoming);
635 /* Process the read event */
636 return this->OnDataReady();
644 void InspSocket::SetState(InspSocketState s)
649 InspSocketState InspSocket::GetState()
654 int InspSocket::GetFd()
659 bool InspSocket::OnConnected() { return true; }
660 void InspSocket::OnError(InspSocketError e) { return; }
661 int InspSocket::OnDisconnect() { return 0; }
662 int InspSocket::OnIncomingConnection(int newfd, char* ip) { return 0; }
663 bool InspSocket::OnDataReady() { return true; }
664 bool InspSocket::OnWriteReady() { return true; }
665 void InspSocket::OnTimeout() { return; }
666 void InspSocket::OnClose() { return; }
668 InspSocket::~InspSocket()
673 Instance->Timers->DelTimer(Timeout);
678 void InspSocket::HandleEvent(EventType et, int errornum)
683 this->Instance->SE->DelFd(this);
691 this->Instance->SE->DelFd(this);
698 if (this->WaitingForWriteEvent)
700 this->WaitingForWriteEvent = false;
701 if (!this->OnWriteReady())
703 this->Instance->SE->DelFd(this);
709 if (this->state == I_CONNECTING)
711 /* This might look wrong as if we should be actually calling
712 * with EVENT_WRITE, but trust me it is correct. There are some
713 * writeability-state things in the read code, because of how
714 * InspSocket used to work regarding write buffering in previous
715 * versions of InspIRCd. - Brain
717 this->HandleEvent(EVENT_READ);
722 if (this->FlushWriteBuffer())
724 this->Instance->SE->DelFd(this);