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 if (!this->DoConnect(maxtime))
85 this->OnError(I_ERR_CONNECT);
88 this->state = I_ERROR;
94 void BufferedSocket::WantWrite()
96 this->Instance->SE->WantWrite(this);
99 void BufferedSocket::SetQueues(int nfd)
101 // attempt to increase socket sendq and recvq as high as its possible
104 if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
106 //this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
107 ; // 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.
111 /* Most irc servers require you to specify the ip you want to bind to.
112 * If you dont specify an IP, they rather dumbly bind to the first IP
113 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
114 * addresses we've bound server ports to, and we try and bind our outbound
115 * connections to the first usable non-loopback and non-any IP we find.
116 * This is easier to configure when you have a lot of links and a lot
117 * of servers to configure.
119 bool BufferedSocket::BindAddr(const std::string &ip)
121 ConfigReader Conf(this->Instance);
122 socklen_t size = sizeof(sockaddr_in);
125 /* Are we looking for a binding to fit an ipv6 host? */
126 if ((ip.empty()) || (ip.find(':') != std::string::npos))
130 while (j < Conf.Enumerate("bind") || (!ip.empty()))
132 std::string sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
133 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
135 if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::1")))
137 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
138 sockaddr* s = new sockaddr[2];
143 if (inet_pton(AF_INET6, sIP.c_str(), &n) > 0)
145 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
146 ((sockaddr_in6*)s)->sin6_port = 0;
147 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
148 size = sizeof(sockaddr_in6);
161 if (inet_aton(sIP.c_str(), &n) > 0)
163 ((sockaddr_in*)s)->sin_addr = n;
164 ((sockaddr_in*)s)->sin_port = 0;
165 ((sockaddr_in*)s)->sin_family = AF_INET;
175 if (Instance->SE->Bind(this->fd, s, size) < 0)
177 this->state = I_ERROR;
178 this->OnError(I_ERR_BIND);
190 Instance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
194 bool BufferedSocket::DoConnect(unsigned long maxtime)
196 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
197 sockaddr* addr = new sockaddr[2];
198 socklen_t size = sizeof(sockaddr_in);
201 if ((!*this->host) || strchr(this->host, ':'))
206 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
207 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
209 if (!this->BindAddr(this->cbindip))
219 this->fd = socket(AF_INET, SOCK_STREAM, 0);
222 if (!this->BindAddr(this->cbindip))
232 this->state = I_ERROR;
233 this->OnError(I_ERR_SOCKET);
242 if (inet_pton(AF_INET6, this->host, &addy) > 0)
244 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
245 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
246 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
247 size = sizeof(sockaddr_in6);
254 if (inet_aton(this->host, &addy) > 0)
256 ((sockaddr_in*)addr)->sin_family = AF_INET;
257 ((sockaddr_in*)addr)->sin_addr = addy;
258 ((sockaddr_in*)addr)->sin_port = htons(this->port);
262 Instance->SE->NonBlocking(this->fd);
264 if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
266 if (errno != EINPROGRESS)
268 this->OnError(I_ERR_CONNECT);
270 this->state = I_ERROR;
274 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, maxtime, this->Instance->Time());
275 this->Instance->Timers->AddTimer(this->Timeout);
278 this->state = I_CONNECTING;
281 if (!this->Instance->SE->AddFd(this))
283 this->OnError(I_ERR_NOMOREFDS);
285 this->state = I_ERROR;
288 this->SetQueues(this->fd);
291 Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
296 void BufferedSocket::Close()
298 /* Save this, so we dont lose it,
299 * otherise on failure, error messages
300 * might be inaccurate.
305 if (this->GetIOHook())
309 this->GetIOHook()->OnRawSocketClose(this->fd);
311 catch (CoreException& modexcept)
313 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
316 Instance->SE->Shutdown(this, 2);
317 if (Instance->SE->Close(this) != -1)
320 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
321 Instance->SocketCull[this] = this;
326 std::string BufferedSocket::GetIP()
331 const char* BufferedSocket::Read()
333 if (!Instance->SE->BoundsCheckFd(this))
337 char* ReadBuffer = Instance->GetReadBuffer();
339 if (this->GetIOHook())
345 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
347 catch (CoreException& modexcept)
349 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
363 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
367 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
368 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
369 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
370 * --w00t (july 2, 2008)
388 * This function formerly tried to flush write buffer each call.
389 * While admirable in attempting to get the data out to wherever
390 * it is going, on a full socket, it's just going to syscall write() and
391 * EAGAIN constantly, instead of waiting in the SE to know if it can write
392 * which will chew a bit of CPU.
394 * So, now this function returns void (take note) and just adds to the sendq.
396 * It'll get written at a determinate point when the socketengine tells us it can write.
397 * -- w00t (april 1, 2008)
399 void BufferedSocket::Write(const std::string &data)
401 /* Append the data to the back of the queue ready for writing */
402 outbuffer.push_back(data);
404 /* Mark ourselves as wanting write */
405 this->Instance->SE->WantWrite(this);
408 bool BufferedSocket::FlushWriteBuffer()
411 if ((this->fd > -1) && (this->state == I_CONNECTED))
413 if (this->GetIOHook())
415 while (outbuffer.size() && (errno != EAGAIN))
419 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
420 * implement their own buffering mechanisms
422 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
423 outbuffer.pop_front();
425 catch (CoreException& modexcept)
427 Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
434 /* If we have multiple lines, try to send them all,
435 * not just the first one -- Brain
437 while (outbuffer.size() && (errno != EAGAIN))
440 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
444 if ((unsigned int)result >= outbuffer[0].length())
446 /* The whole block was written (usually a line)
447 * Pop the block off the front of the queue,
448 * dont set errno, because we are clear of errors
449 * and want to try and write the next block too.
451 outbuffer.pop_front();
455 std::string temp = outbuffer[0].substr(result);
457 /* We didnt get the whole line out. arses.
458 * Try again next time, i guess. Set errno,
459 * because we shouldnt be writing any more now,
460 * until the socketengine says its safe to do so.
465 else if (result == 0)
467 this->Instance->SE->DelFd(this);
471 else if ((result == -1) && (errno != EAGAIN))
473 this->OnError(I_ERR_WRITE);
474 this->state = I_ERROR;
475 this->Instance->SE->DelFd(this);
483 if ((errno == EAGAIN) && (fd > -1))
485 this->Instance->SE->WantWrite(this);
491 void SocketTimeout::Tick(time_t)
493 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
495 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
498 if (this->sock->state == I_CONNECTING)
500 // for connecting sockets, the timeout can occur
501 // which causes termination of the connection after
502 // the given number of seconds without a successful
504 this->sock->OnTimeout();
505 this->sock->OnError(I_ERR_TIMEOUT);
507 /* NOTE: We must set this AFTER DelFd, as we added
508 * this socket whilst writeable. This means that we
509 * must DELETE the socket whilst writeable too!
511 this->sock->state = I_ERROR;
513 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
514 ServerInstance->SocketCull[this->sock] = this->sock;
517 this->sock->Timeout = NULL;
520 bool BufferedSocket::Poll()
523 if (!Instance->SE->BoundsCheckFd(this))
527 if (Instance->SE->GetRef(this->fd) != this)
533 /* Our socket was in write-state, so delete it and re-add it
539 this->Instance->SE->DelFd(this);
540 if (!this->Instance->SE->AddFd(this))
544 this->SetState(I_CONNECTED);
546 if (this->GetIOHook())
548 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
551 this->GetIOHook()->OnRawSocketConnect(this->fd);
553 catch (CoreException& modexcept)
555 Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
558 return this->OnConnected();
561 /* Process the read event */
562 return this->OnDataReady();
570 void BufferedSocket::SetState(BufferedSocketState s)
575 BufferedSocketState BufferedSocket::GetState()
580 bool BufferedSocket::OnConnected() { return true; }
581 void BufferedSocket::OnError(BufferedSocketError) { return; }
582 int BufferedSocket::OnDisconnect() { return 0; }
583 bool BufferedSocket::OnDataReady() { return true; }
584 bool BufferedSocket::OnWriteReady()
586 // Default behaviour: just try write some.
587 return !this->FlushWriteBuffer();
589 void BufferedSocket::OnTimeout() { return; }
590 void BufferedSocket::OnClose() { return; }
592 BufferedSocket::~BufferedSocket()
597 Instance->Timers->DelTimer(Timeout);
602 void BufferedSocket::HandleEvent(EventType et, int errornum)
610 this->OnError(I_ERR_TIMEOUT);
614 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
617 this->OnError(I_ERR_BIND);
621 this->OnError(I_ERR_WRITE);
624 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
625 this->Instance->SocketCull[this] = this;
631 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
632 this->Instance->SocketCull[this] = this;
637 if (this->state == I_CONNECTING)
639 /* This might look wrong as if we should be actually calling
640 * with EVENT_WRITE, but trust me it is correct. There are some
641 * writeability-state things in the read code, because of how
642 * BufferedSocket used to work regarding write buffering in previous
643 * versions of InspIRCd. - Brain
645 this->HandleEvent(EVENT_READ);
650 if (!this->OnWriteReady())
652 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
653 this->Instance->SocketCull[this] = this;