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);
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
29 this->state = I_DISCONNECTED;
34 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
38 this->state = I_CONNECTED;
39 strlcpy(this->IP,ip,MAXBUF);
42 this->Instance->SE->AddFd(this);
45 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
47 this->cbindip = connectbindip;
50 strlcpy(host,ipaddr.c_str(),MAXBUF);
53 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
61 if (inet_pton(AF_INET6, host, &n) < 1)
68 if (inet_aton(host,&n) < 1)
73 this->Instance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
74 this->OnError(I_ERR_CONNECT);
77 this->state = I_ERROR;
82 strlcpy(this->IP,host,MAXBUF);
83 timeout_val = maxtime;
84 if (!this->DoConnect())
86 this->OnError(I_ERR_CONNECT);
89 this->state = I_ERROR;
95 void BufferedSocket::WantWrite()
97 this->Instance->SE->WantWrite(this);
100 void BufferedSocket::SetQueues(int nfd)
102 // attempt to increase socket sendq and recvq as high as its possible
105 if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
107 //this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
108 ; // 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.
112 /* Most irc servers require you to specify the ip you want to bind to.
113 * If you dont specify an IP, they rather dumbly bind to the first IP
114 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
115 * addresses we've bound server ports to, and we try and bind our outbound
116 * connections to the first usable non-loopback and non-any IP we find.
117 * This is easier to configure when you have a lot of links and a lot
118 * of servers to configure.
120 bool BufferedSocket::BindAddr(const std::string &ip)
122 ConfigReader Conf(this->Instance);
123 socklen_t size = sizeof(sockaddr_in);
126 /* Are we looking for a binding to fit an ipv6 host? */
127 if ((ip.empty()) || (ip.find(':') != std::string::npos))
131 while (j < Conf.Enumerate("bind") || (!ip.empty()))
133 std::string sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
134 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
136 if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::1")))
138 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
139 sockaddr* s = new sockaddr[2];
144 if (inet_pton(AF_INET6, sIP.c_str(), &n) > 0)
146 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
147 ((sockaddr_in6*)s)->sin6_port = 0;
148 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
149 size = sizeof(sockaddr_in6);
162 if (inet_aton(sIP.c_str(), &n) > 0)
164 ((sockaddr_in*)s)->sin_addr = n;
165 ((sockaddr_in*)s)->sin_port = 0;
166 ((sockaddr_in*)s)->sin_family = AF_INET;
176 if (Instance->SE->Bind(this->fd, s, size) < 0)
178 this->state = I_ERROR;
179 this->OnError(I_ERR_BIND);
191 Instance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
195 bool BufferedSocket::DoConnect()
197 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
198 sockaddr* addr = new sockaddr[2];
199 socklen_t size = sizeof(sockaddr_in);
202 if ((!*this->host) || strchr(this->host, ':'))
207 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
208 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
210 if (!this->BindAddr(this->cbindip))
220 this->fd = socket(AF_INET, SOCK_STREAM, 0);
223 if (!this->BindAddr(this->cbindip))
233 this->state = I_ERROR;
234 this->OnError(I_ERR_SOCKET);
243 if (inet_pton(AF_INET6, this->host, &addy) > 0)
245 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
246 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
247 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
248 size = sizeof(sockaddr_in6);
255 if (inet_aton(this->host, &addy) > 0)
257 ((sockaddr_in*)addr)->sin_family = AF_INET;
258 ((sockaddr_in*)addr)->sin_addr = addy;
259 ((sockaddr_in*)addr)->sin_port = htons(this->port);
263 Instance->SE->NonBlocking(this->fd);
265 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
267 if (errno != EINPROGRESS)
269 this->OnError(I_ERR_CONNECT);
271 this->state = I_ERROR;
275 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
276 this->Instance->Timers->AddTimer(this->Timeout);
279 this->state = I_CONNECTING;
282 if (!this->Instance->SE->AddFd(this))
284 this->OnError(I_ERR_NOMOREFDS);
286 this->state = I_ERROR;
289 this->SetQueues(this->fd);
292 Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
297 void BufferedSocket::Close()
299 /* Save this, so we dont lose it,
300 * otherise on failure, error messages
301 * might be inaccurate.
306 if (this->GetIOHook())
310 this->GetIOHook()->OnRawSocketClose(this->fd);
312 catch (CoreException& modexcept)
314 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
317 Instance->SE->Shutdown(this, 2);
318 if (Instance->SE->Close(this) != -1)
321 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
322 Instance->SocketCull[this] = this;
327 std::string BufferedSocket::GetIP()
332 const char* BufferedSocket::Read()
334 if (!Instance->SE->BoundsCheckFd(this))
338 char* ReadBuffer = Instance->GetReadBuffer();
340 if (this->GetIOHook())
346 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
348 catch (CoreException& modexcept)
350 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
364 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
368 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
369 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
370 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
371 * --w00t (july 2, 2008)
389 * This function formerly tried to flush write buffer each call.
390 * While admirable in attempting to get the data out to wherever
391 * it is going, on a full socket, it's just going to syscall write() and
392 * EAGAIN constantly, instead of waiting in the SE to know if it can write
393 * which will chew a bit of CPU.
395 * So, now this function returns void (take note) and just adds to the sendq.
397 * It'll get written at a determinate point when the socketengine tells us it can write.
398 * -- w00t (april 1, 2008)
400 void BufferedSocket::Write(const std::string &data)
402 /* Append the data to the back of the queue ready for writing */
403 outbuffer.push_back(data);
405 /* Mark ourselves as wanting write */
406 this->Instance->SE->WantWrite(this);
409 bool BufferedSocket::FlushWriteBuffer()
412 if ((this->fd > -1) && (this->state == I_CONNECTED))
414 if (this->GetIOHook())
416 while (outbuffer.size() && (errno != EAGAIN))
420 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
421 * implement their own buffering mechanisms
423 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
424 outbuffer.pop_front();
426 catch (CoreException& modexcept)
428 Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
435 /* If we have multiple lines, try to send them all,
436 * not just the first one -- Brain
438 while (outbuffer.size() && (errno != EAGAIN))
441 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
445 if ((unsigned int)result >= outbuffer[0].length())
447 /* The whole block was written (usually a line)
448 * Pop the block off the front of the queue,
449 * dont set errno, because we are clear of errors
450 * and want to try and write the next block too.
452 outbuffer.pop_front();
456 std::string temp = outbuffer[0].substr(result);
458 /* We didnt get the whole line out. arses.
459 * Try again next time, i guess. Set errno,
460 * because we shouldnt be writing any more now,
461 * until the socketengine says its safe to do so.
466 else if (result == 0)
468 this->Instance->SE->DelFd(this);
472 else if ((result == -1) && (errno != EAGAIN))
474 this->OnError(I_ERR_WRITE);
475 this->state = I_ERROR;
476 this->Instance->SE->DelFd(this);
484 if ((errno == EAGAIN) && (fd > -1))
486 this->Instance->SE->WantWrite(this);
492 void SocketTimeout::Tick(time_t)
494 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
496 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
499 if (this->sock->state == I_CONNECTING)
501 // for connecting sockets, the timeout can occur
502 // which causes termination of the connection after
503 // the given number of seconds without a successful
505 this->sock->OnTimeout();
506 this->sock->OnError(I_ERR_TIMEOUT);
507 this->sock->timeout = true;
509 /* NOTE: We must set this AFTER DelFd, as we added
510 * this socket whilst writeable. This means that we
511 * must DELETE the socket whilst writeable too!
513 this->sock->state = I_ERROR;
515 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
516 ServerInstance->SocketCull[this->sock] = this->sock;
519 this->sock->Timeout = NULL;
522 bool BufferedSocket::Poll()
525 if (!Instance->SE->BoundsCheckFd(this))
529 if (Instance->SE->GetRef(this->fd) != this)
535 /* Our socket was in write-state, so delete it and re-add it
541 this->Instance->SE->DelFd(this);
542 if (!this->Instance->SE->AddFd(this))
546 this->SetState(I_CONNECTED);
548 if (this->GetIOHook())
550 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
553 this->GetIOHook()->OnRawSocketConnect(this->fd);
555 catch (CoreException& modexcept)
557 Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
560 return this->OnConnected();
563 /* Process the read event */
564 return this->OnDataReady();
572 void BufferedSocket::SetState(BufferedSocketState s)
577 BufferedSocketState BufferedSocket::GetState()
582 bool BufferedSocket::OnConnected() { return true; }
583 void BufferedSocket::OnError(BufferedSocketError) { return; }
584 int BufferedSocket::OnDisconnect() { return 0; }
585 bool BufferedSocket::OnDataReady() { return true; }
586 bool BufferedSocket::OnWriteReady()
588 // Default behaviour: just try write some.
589 return !this->FlushWriteBuffer();
591 void BufferedSocket::OnTimeout() { return; }
592 void BufferedSocket::OnClose() { return; }
594 BufferedSocket::~BufferedSocket()
599 Instance->Timers->DelTimer(Timeout);
604 void BufferedSocket::HandleEvent(EventType et, int errornum)
612 this->OnError(I_ERR_TIMEOUT);
616 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
619 this->OnError(I_ERR_BIND);
623 this->OnError(I_ERR_WRITE);
626 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
627 this->Instance->SocketCull[this] = this;
633 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
634 this->Instance->SocketCull[this] = this;
639 if (this->state == I_CONNECTING)
641 /* This might look wrong as if we should be actually calling
642 * with EVENT_WRITE, but trust me it is correct. There are some
643 * writeability-state things in the read code, because of how
644 * BufferedSocket used to work regarding write buffering in previous
645 * versions of InspIRCd. - Brain
647 this->HandleEvent(EVENT_READ);
652 if (!this->OnWriteReady())
654 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
655 this->Instance->SocketCull[this] = this;