1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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;
31 this->ServerInstance = SI;
34 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
38 this->state = I_CONNECTED;
39 strlcpy(this->IP,ip,MAXBUF);
40 this->ServerInstance = SI;
42 this->ServerInstance->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;
49 this->ServerInstance = SI;
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->ServerInstance->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::SetQueues()
96 // attempt to increase socket sendq and recvq as high as its possible
99 if(setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
101 //this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
102 ; // 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.
106 /* Most irc servers require you to specify the ip you want to bind to.
107 * If you dont specify an IP, they rather dumbly bind to the first IP
108 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
109 * addresses we've bound server ports to, and we try and bind our outbound
110 * connections to the first usable non-loopback and non-any IP we find.
111 * This is easier to configure when you have a lot of links and a lot
112 * of servers to configure.
114 bool BufferedSocket::BindAddr(const std::string &ip)
116 ConfigReader Conf(this->ServerInstance);
117 socklen_t size = sizeof(sockaddr_in);
120 /* Are we looking for a binding to fit an ipv6 host? */
121 if ((ip.empty()) || (ip.find(':') != std::string::npos))
125 while (j < Conf.Enumerate("bind") || (!ip.empty()))
127 std::string sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
128 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
130 if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::1")))
132 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
133 sockaddr* s = new sockaddr[2];
138 if (inet_pton(AF_INET6, sIP.c_str(), &n) > 0)
140 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
141 ((sockaddr_in6*)s)->sin6_port = 0;
142 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
143 size = sizeof(sockaddr_in6);
156 if (inet_aton(sIP.c_str(), &n) > 0)
158 ((sockaddr_in*)s)->sin_addr = n;
159 ((sockaddr_in*)s)->sin_port = 0;
160 ((sockaddr_in*)s)->sin_family = AF_INET;
170 if (ServerInstance->SE->Bind(this->fd, s, size) < 0)
172 this->state = I_ERROR;
173 this->OnError(I_ERR_BIND);
185 ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
189 bool BufferedSocket::DoConnect(unsigned long maxtime)
191 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
192 sockaddr* addr = new sockaddr[2];
193 socklen_t size = sizeof(sockaddr_in);
196 if ((!*this->host) || strchr(this->host, ':'))
201 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
202 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
204 if (!this->BindAddr(this->cbindip))
214 this->fd = socket(AF_INET, SOCK_STREAM, 0);
217 if (!this->BindAddr(this->cbindip))
227 this->state = I_ERROR;
228 this->OnError(I_ERR_SOCKET);
237 if (inet_pton(AF_INET6, this->host, &addy) > 0)
239 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
240 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
241 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
242 size = sizeof(sockaddr_in6);
249 if (inet_aton(this->host, &addy) > 0)
251 ((sockaddr_in*)addr)->sin_family = AF_INET;
252 ((sockaddr_in*)addr)->sin_addr = addy;
253 ((sockaddr_in*)addr)->sin_port = htons(this->port);
257 ServerInstance->SE->NonBlocking(this->fd);
259 if (ServerInstance->SE->Connect(this, (sockaddr*)addr, size) == -1)
261 if (errno != EINPROGRESS)
263 this->OnError(I_ERR_CONNECT);
265 this->state = I_ERROR;
270 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
271 this->ServerInstance->Timers->AddTimer(this->Timeout);
274 this->state = I_CONNECTING;
278 if (!this->ServerInstance->SE->AddFd(this))
280 this->OnError(I_ERR_NOMOREFDS);
282 this->state = I_ERROR;
288 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
293 void BufferedSocket::Close()
295 /* Save this, so we dont lose it,
296 * otherise on failure, error messages
297 * might be inaccurate.
302 if (this->GetIOHook())
306 this->GetIOHook()->OnRawSocketClose(this->fd);
308 catch (CoreException& modexcept)
310 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
313 ServerInstance->SE->Shutdown(this, 2);
314 if (ServerInstance->SE->Close(this) != -1)
317 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
318 ServerInstance->SocketCull[this] = this;
323 std::string BufferedSocket::GetIP()
328 const char* BufferedSocket::Read()
330 if (!ServerInstance->SE->BoundsCheckFd(this))
334 char* ReadBuffer = ServerInstance->GetReadBuffer();
336 if (this->GetIOHook())
342 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
344 catch (CoreException& modexcept)
346 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
360 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
364 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
365 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
366 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
367 * --w00t (july 2, 2008)
385 * This function formerly tried to flush write buffer each call.
386 * While admirable in attempting to get the data out to wherever
387 * it is going, on a full socket, it's just going to syscall write() and
388 * EAGAIN constantly, instead of waiting in the SE to know if it can write
389 * which will chew a bit of CPU.
391 * So, now this function returns void (take note) and just adds to the sendq.
393 * It'll get written at a determinate point when the socketengine tells us it can write.
394 * -- w00t (april 1, 2008)
396 void BufferedSocket::Write(const std::string &data)
398 /* Append the data to the back of the queue ready for writing */
399 outbuffer.push_back(data);
401 /* Mark ourselves as wanting write */
402 this->ServerInstance->SE->WantWrite(this);
405 bool BufferedSocket::FlushWriteBuffer()
408 if ((this->fd > -1) && (this->state == I_CONNECTED))
410 if (this->GetIOHook())
412 while (outbuffer.size() && (errno != EAGAIN))
416 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
417 * implement their own buffering mechanisms
419 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
420 outbuffer.pop_front();
422 catch (CoreException& modexcept)
424 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
431 /* If we have multiple lines, try to send them all,
432 * not just the first one -- Brain
434 while (outbuffer.size() && (errno != EAGAIN))
437 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
441 if ((unsigned int)result >= outbuffer[0].length())
443 /* The whole block was written (usually a line)
444 * Pop the block off the front of the queue,
445 * dont set errno, because we are clear of errors
446 * and want to try and write the next block too.
448 outbuffer.pop_front();
452 std::string temp = outbuffer[0].substr(result);
454 /* We didnt get the whole line out. arses.
455 * Try again next time, i guess. Set errno,
456 * because we shouldnt be writing any more now,
457 * until the socketengine says its safe to do so.
462 else if (result == 0)
464 this->ServerInstance->SE->DelFd(this);
468 else if ((result == -1) && (errno != EAGAIN))
470 this->OnError(I_ERR_WRITE);
471 this->state = I_ERROR;
472 this->ServerInstance->SE->DelFd(this);
480 if ((errno == EAGAIN) && (fd > -1))
482 this->ServerInstance->SE->WantWrite(this);
488 void SocketTimeout::Tick(time_t)
490 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
492 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
495 if (this->sock->state == I_CONNECTING)
497 // for connecting sockets, the timeout can occur
498 // which causes termination of the connection after
499 // the given number of seconds without a successful
501 this->sock->OnTimeout();
502 this->sock->OnError(I_ERR_TIMEOUT);
504 /* NOTE: We must set this AFTER DelFd, as we added
505 * this socket whilst writeable. This means that we
506 * must DELETE the socket whilst writeable too!
508 this->sock->state = I_ERROR;
510 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
511 ServerInstance->SocketCull[this->sock] = this->sock;
514 this->sock->Timeout = NULL;
517 bool BufferedSocket::InternalMarkConnected()
519 /* Our socket was in write-state, so delete it and re-add it
522 this->SetState(I_CONNECTED);
524 if (this->GetIOHook())
526 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
529 this->GetIOHook()->OnRawSocketConnect(this->fd);
531 catch (CoreException& modexcept)
533 ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
537 return this->OnConnected();
540 void BufferedSocket::SetState(BufferedSocketState s)
545 BufferedSocketState BufferedSocket::GetState()
550 bool BufferedSocket::OnConnected() { return true; }
551 void BufferedSocket::OnError(BufferedSocketError) { return; }
552 int BufferedSocket::OnDisconnect() { return 0; }
553 bool BufferedSocket::OnDataReady() { return true; }
554 bool BufferedSocket::OnWriteReady()
556 // Default behaviour: just try write some.
557 return !this->FlushWriteBuffer();
559 void BufferedSocket::OnTimeout() { return; }
560 void BufferedSocket::OnClose() { return; }
562 BufferedSocket::~BufferedSocket()
567 ServerInstance->Timers->DelTimer(Timeout);
572 void BufferedSocket::HandleEvent(EventType et, int errornum)
581 this->OnError(I_ERR_TIMEOUT);
585 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
588 this->OnError(I_ERR_BIND);
592 this->OnError(I_ERR_WRITE);
596 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
597 this->ServerInstance->SocketCull[this] = this;
603 if (!this->OnDataReady())
605 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
606 this->ServerInstance->SocketCull[this] = this;
613 if (this->state == I_CONNECTING)
615 if (!this->InternalMarkConnected())
617 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
618 this->ServerInstance->SocketCull[this] = this;
625 if (!this->OnWriteReady())
627 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
628 this->ServerInstance->SocketCull[this] = this;