1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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 * ---------------------------------------------------
17 #include "inspstring.h"
18 #include "socketengine.h"
21 bool BufferedSocket::Readable()
23 return ((this->state != I_CONNECTING) && (this->WaitingForWriteEvent == false));
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
29 this->state = I_DISCONNECTED;
31 this->WaitingForWriteEvent = false;
35 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
39 this->state = I_CONNECTED;
40 strlcpy(this->IP,ip,MAXBUF);
41 this->WaitingForWriteEvent = false;
44 this->Instance->SE->AddFd(this);
47 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
49 this->cbindip = connectbindip;
52 strlcpy(host,ipaddr.c_str(),MAXBUF);
53 this->WaitingForWriteEvent = false;
56 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
64 if (inet_pton(AF_INET6, host, &n) < 1)
71 if (inet_aton(host,&n) < 1)
76 this->Instance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
77 this->OnError(I_ERR_CONNECT);
80 this->state = I_ERROR;
85 strlcpy(this->IP,host,MAXBUF);
86 timeout_val = maxtime;
87 if (!this->DoConnect())
89 this->OnError(I_ERR_CONNECT);
92 this->state = I_ERROR;
98 void BufferedSocket::WantWrite()
100 this->Instance->SE->WantWrite(this);
101 this->WaitingForWriteEvent = true;
104 void BufferedSocket::SetQueues(int nfd)
106 // attempt to increase socket sendq and recvq as high as its possible
109 if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
111 //this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
112 ; // do nothing. I'm a little sick of people trying to interpret this message as a result of why their incorrect setups don't work.
116 /* Most irc servers require you to specify the ip you want to bind to.
117 * If you dont specify an IP, they rather dumbly bind to the first IP
118 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
119 * addresses we've bound server ports to, and we try and bind our outbound
120 * connections to the first usable non-loopback and non-any IP we find.
121 * This is easier to configure when you have a lot of links and a lot
122 * of servers to configure.
124 bool BufferedSocket::BindAddr(const std::string &ip)
126 ConfigReader Conf(this->Instance);
127 socklen_t size = sizeof(sockaddr_in);
130 /* Are we looking for a binding to fit an ipv6 host? */
131 if ((ip.empty()) || (ip.find(':') != std::string::npos))
135 while (j < Conf.Enumerate("bind") || (!ip.empty()))
137 std::string sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
138 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
140 if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::1")))
142 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
143 sockaddr* s = new sockaddr[2];
148 if (inet_pton(AF_INET6, sIP.c_str(), &n) > 0)
150 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
151 ((sockaddr_in6*)s)->sin6_port = 0;
152 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
153 size = sizeof(sockaddr_in6);
166 if (inet_aton(sIP.c_str(), &n) > 0)
168 ((sockaddr_in*)s)->sin_addr = n;
169 ((sockaddr_in*)s)->sin_port = 0;
170 ((sockaddr_in*)s)->sin_family = AF_INET;
180 if (Instance->SE->Bind(this->fd, s, size) < 0)
182 this->state = I_ERROR;
183 this->OnError(I_ERR_BIND);
195 Instance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
199 bool BufferedSocket::DoConnect()
201 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
202 sockaddr* addr = new sockaddr[2];
203 socklen_t size = sizeof(sockaddr_in);
206 if ((!*this->host) || strchr(this->host, ':'))
211 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
212 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
214 if (!this->BindAddr(this->cbindip))
224 this->fd = socket(AF_INET, SOCK_STREAM, 0);
227 if (!this->BindAddr(this->cbindip))
237 this->state = I_ERROR;
238 this->OnError(I_ERR_SOCKET);
247 if (inet_pton(AF_INET6, this->host, &addy) > 0)
249 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
250 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
251 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
252 size = sizeof(sockaddr_in6);
259 if (inet_aton(this->host, &addy) > 0)
261 ((sockaddr_in*)addr)->sin_family = AF_INET;
262 ((sockaddr_in*)addr)->sin_addr = addy;
263 ((sockaddr_in*)addr)->sin_port = htons(this->port);
267 Instance->SE->NonBlocking(this->fd);
270 /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
271 Instance->SE->Blocking(this->fd);
274 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
276 if (errno != EINPROGRESS)
278 this->OnError(I_ERR_CONNECT);
280 this->state = I_ERROR;
284 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
285 this->Instance->Timers->AddTimer(this->Timeout);
288 /* CRAQ SMOKING STUFF TO BE FIXED */
289 Instance->SE->NonBlocking(this->fd);
291 this->state = I_CONNECTING;
294 if (!this->Instance->SE->AddFd(this))
296 this->OnError(I_ERR_NOMOREFDS);
298 this->state = I_ERROR;
301 this->SetQueues(this->fd);
304 Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
309 void BufferedSocket::Close()
311 /* Save this, so we dont lose it,
312 * otherise on failure, error messages
313 * might be inaccurate.
318 if (this->GetIOHook())
322 this->GetIOHook()->OnRawSocketClose(this->fd);
324 catch (CoreException& modexcept)
326 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
329 Instance->SE->Shutdown(this, 2);
330 if (Instance->SE->Close(this) != -1)
333 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
334 Instance->SocketCull[this] = this;
339 std::string BufferedSocket::GetIP()
344 const char* BufferedSocket::Read()
346 if (!Instance->SE->BoundsCheckFd(this))
350 char* ReadBuffer = Instance->GetReadBuffer();
352 if (this->GetIOHook())
358 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
360 catch (CoreException& modexcept)
362 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
376 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
380 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
381 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
382 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
383 * --w00t (july 2, 2008)
401 * This function formerly tried to flush write buffer each call.
402 * While admirable in attempting to get the data out to wherever
403 * it is going, on a full socket, it's just going to syscall write() and
404 * EAGAIN constantly, instead of waiting in the SE to know if it can write
405 * which will chew a bit of CPU.
407 * So, now this function returns void (take note) and just adds to the sendq.
409 * It'll get written at a determinate point when the socketengine tells us it can write.
410 * -- w00t (april 1, 2008)
412 void BufferedSocket::Write(const std::string &data)
414 /* Append the data to the back of the queue ready for writing */
415 outbuffer.push_back(data);
417 /* Mark ourselves as wanting write */
418 this->Instance->SE->WantWrite(this);
421 bool BufferedSocket::FlushWriteBuffer()
424 if ((this->fd > -1) && (this->state == I_CONNECTED))
426 if (this->GetIOHook())
428 while (outbuffer.size() && (errno != EAGAIN))
432 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
433 * implement their own buffering mechanisms
435 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
436 outbuffer.pop_front();
438 catch (CoreException& modexcept)
440 Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
447 /* If we have multiple lines, try to send them all,
448 * not just the first one -- Brain
450 while (outbuffer.size() && (errno != EAGAIN))
453 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
457 if ((unsigned int)result >= outbuffer[0].length())
459 /* The whole block was written (usually a line)
460 * Pop the block off the front of the queue,
461 * dont set errno, because we are clear of errors
462 * and want to try and write the next block too.
464 outbuffer.pop_front();
468 std::string temp = outbuffer[0].substr(result);
470 /* We didnt get the whole line out. arses.
471 * Try again next time, i guess. Set errno,
472 * because we shouldnt be writing any more now,
473 * until the socketengine says its safe to do so.
478 else if (result == 0)
480 this->Instance->SE->DelFd(this);
484 else if ((result == -1) && (errno != EAGAIN))
486 this->OnError(I_ERR_WRITE);
487 this->state = I_ERROR;
488 this->Instance->SE->DelFd(this);
496 if ((errno == EAGAIN) && (fd > -1))
498 this->Instance->SE->WantWrite(this);
504 void SocketTimeout::Tick(time_t)
506 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
508 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
511 if (this->sock->state == I_CONNECTING)
513 // for connecting sockets, the timeout can occur
514 // which causes termination of the connection after
515 // the given number of seconds without a successful
517 this->sock->OnTimeout();
518 this->sock->OnError(I_ERR_TIMEOUT);
519 this->sock->timeout = true;
521 /* NOTE: We must set this AFTER DelFd, as we added
522 * this socket whilst writeable. This means that we
523 * must DELETE the socket whilst writeable too!
525 this->sock->state = I_ERROR;
527 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
528 ServerInstance->SocketCull[this->sock] = this->sock;
531 this->sock->Timeout = NULL;
534 bool BufferedSocket::Poll()
537 if (!Instance->SE->BoundsCheckFd(this))
541 if (Instance->SE->GetRef(this->fd) != this)
547 /* Our socket was in write-state, so delete it and re-add it
553 this->Instance->SE->DelFd(this);
554 if (!this->Instance->SE->AddFd(this))
558 this->SetState(I_CONNECTED);
560 if (this->GetIOHook())
562 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
565 this->GetIOHook()->OnRawSocketConnect(this->fd);
567 catch (CoreException& modexcept)
569 Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
572 return this->OnConnected();
575 /* Process the read event */
576 return this->OnDataReady();
584 void BufferedSocket::SetState(BufferedSocketState s)
589 BufferedSocketState BufferedSocket::GetState()
594 int BufferedSocket::GetFd()
599 bool BufferedSocket::OnConnected() { return true; }
600 void BufferedSocket::OnError(BufferedSocketError) { return; }
601 int BufferedSocket::OnDisconnect() { return 0; }
602 bool BufferedSocket::OnDataReady() { return true; }
603 bool BufferedSocket::OnWriteReady() { return true; }
604 void BufferedSocket::OnTimeout() { return; }
605 void BufferedSocket::OnClose() { return; }
607 BufferedSocket::~BufferedSocket()
612 Instance->Timers->DelTimer(Timeout);
617 void BufferedSocket::HandleEvent(EventType et, int errornum)
625 this->OnError(I_ERR_TIMEOUT);
629 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
632 this->OnError(I_ERR_BIND);
636 this->OnError(I_ERR_WRITE);
639 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
640 this->Instance->SocketCull[this] = this;
646 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
647 this->Instance->SocketCull[this] = this;
652 if (this->WaitingForWriteEvent)
654 this->WaitingForWriteEvent = false;
655 if (!this->OnWriteReady())
657 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
658 this->Instance->SocketCull[this] = this;
662 if (this->state == I_CONNECTING)
664 /* This might look wrong as if we should be actually calling
665 * with EVENT_WRITE, but trust me it is correct. There are some
666 * writeability-state things in the read code, because of how
667 * BufferedSocket used to work regarding write buffering in previous
668 * versions of InspIRCd. - Brain
670 this->HandleEvent(EVENT_READ);
675 if (this->FlushWriteBuffer())
677 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
678 this->Instance->SocketCull[this] = this;