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;
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;
269 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
270 this->ServerInstance->Timers->AddTimer(this->Timeout);
273 this->state = I_CONNECTING;
276 if (!this->ServerInstance->SE->AddFd(this))
278 this->OnError(I_ERR_NOMOREFDS);
280 this->state = I_ERROR;
286 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
291 void BufferedSocket::Close()
293 /* Save this, so we dont lose it,
294 * otherise on failure, error messages
295 * might be inaccurate.
300 if (this->GetIOHook())
304 this->GetIOHook()->OnRawSocketClose(this->fd);
306 catch (CoreException& modexcept)
308 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
311 ServerInstance->SE->Shutdown(this, 2);
312 if (ServerInstance->SE->Close(this) != -1)
315 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
316 ServerInstance->SocketCull[this] = this;
321 std::string BufferedSocket::GetIP()
326 const char* BufferedSocket::Read()
328 if (!ServerInstance->SE->BoundsCheckFd(this))
332 char* ReadBuffer = ServerInstance->GetReadBuffer();
334 if (this->GetIOHook())
340 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
342 catch (CoreException& modexcept)
344 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
358 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
362 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
363 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
364 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
365 * --w00t (july 2, 2008)
383 * This function formerly tried to flush write buffer each call.
384 * While admirable in attempting to get the data out to wherever
385 * it is going, on a full socket, it's just going to syscall write() and
386 * EAGAIN constantly, instead of waiting in the SE to know if it can write
387 * which will chew a bit of CPU.
389 * So, now this function returns void (take note) and just adds to the sendq.
391 * It'll get written at a determinate point when the socketengine tells us it can write.
392 * -- w00t (april 1, 2008)
394 void BufferedSocket::Write(const std::string &data)
396 /* Append the data to the back of the queue ready for writing */
397 outbuffer.push_back(data);
399 /* Mark ourselves as wanting write */
400 this->ServerInstance->SE->WantWrite(this);
403 bool BufferedSocket::FlushWriteBuffer()
406 if ((this->fd > -1) && (this->state == I_CONNECTED))
408 if (this->GetIOHook())
410 while (outbuffer.size() && (errno != EAGAIN))
414 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
415 * implement their own buffering mechanisms
417 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
418 outbuffer.pop_front();
420 catch (CoreException& modexcept)
422 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
429 /* If we have multiple lines, try to send them all,
430 * not just the first one -- Brain
432 while (outbuffer.size() && (errno != EAGAIN))
435 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
439 if ((unsigned int)result >= outbuffer[0].length())
441 /* The whole block was written (usually a line)
442 * Pop the block off the front of the queue,
443 * dont set errno, because we are clear of errors
444 * and want to try and write the next block too.
446 outbuffer.pop_front();
450 std::string temp = outbuffer[0].substr(result);
452 /* We didnt get the whole line out. arses.
453 * Try again next time, i guess. Set errno,
454 * because we shouldnt be writing any more now,
455 * until the socketengine says its safe to do so.
460 else if (result == 0)
462 this->ServerInstance->SE->DelFd(this);
466 else if ((result == -1) && (errno != EAGAIN))
468 this->OnError(I_ERR_WRITE);
469 this->state = I_ERROR;
470 this->ServerInstance->SE->DelFd(this);
478 if ((errno == EAGAIN) && (fd > -1))
480 this->ServerInstance->SE->WantWrite(this);
486 void SocketTimeout::Tick(time_t)
488 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
490 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
493 if (this->sock->state == I_CONNECTING)
495 // for connecting sockets, the timeout can occur
496 // which causes termination of the connection after
497 // the given number of seconds without a successful
499 this->sock->OnTimeout();
500 this->sock->OnError(I_ERR_TIMEOUT);
502 /* NOTE: We must set this AFTER DelFd, as we added
503 * this socket whilst writeable. This means that we
504 * must DELETE the socket whilst writeable too!
506 this->sock->state = I_ERROR;
508 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
509 ServerInstance->SocketCull[this->sock] = this->sock;
512 this->sock->Timeout = NULL;
515 bool BufferedSocket::InternalMarkConnected()
517 /* Our socket was in write-state, so delete it and re-add it
520 this->SetState(I_CONNECTED);
522 if (this->GetIOHook())
524 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
527 this->GetIOHook()->OnRawSocketConnect(this->fd);
529 catch (CoreException& modexcept)
531 ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
535 return this->OnConnected();
538 void BufferedSocket::SetState(BufferedSocketState s)
543 BufferedSocketState BufferedSocket::GetState()
548 bool BufferedSocket::OnConnected() { return true; }
549 void BufferedSocket::OnError(BufferedSocketError) { return; }
550 int BufferedSocket::OnDisconnect() { return 0; }
551 bool BufferedSocket::OnDataReady() { return true; }
552 bool BufferedSocket::OnWriteReady()
554 // Default behaviour: just try write some.
555 return !this->FlushWriteBuffer();
557 void BufferedSocket::OnTimeout() { return; }
558 void BufferedSocket::OnClose() { return; }
560 BufferedSocket::~BufferedSocket()
565 ServerInstance->Timers->DelTimer(Timeout);
570 void BufferedSocket::HandleEvent(EventType et, int errornum)
579 this->OnError(I_ERR_TIMEOUT);
583 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
586 this->OnError(I_ERR_BIND);
590 this->OnError(I_ERR_WRITE);
594 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
595 this->ServerInstance->SocketCull[this] = this;
601 if (!this->OnDataReady())
603 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
604 this->ServerInstance->SocketCull[this] = this;
611 if (this->state == I_CONNECTING)
613 if (!this->InternalMarkConnected())
615 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
616 this->ServerInstance->SocketCull[this] = this;
623 if (!this->OnWriteReady())
625 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
626 this->ServerInstance->SocketCull[this] = this;