1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/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 bool BufferedSocket::DoBindMagic(const std::string ¤t_ip, bool v6)
108 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
109 socklen_t size = sizeof(sockaddr_in);
110 sockaddr* s = new sockaddr[2];
115 if (inet_pton(AF_INET6, current_ip.c_str(), &n) > 0)
117 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
118 ((sockaddr_in6*)s)->sin6_port = 0;
119 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
120 size = sizeof(sockaddr_in6);
124 // Well, this is as good as it's gonna get.
125 errno = EADDRNOTAVAIL;
134 if (inet_aton(current_ip.c_str(), &n) > 0)
136 ((sockaddr_in*)s)->sin_addr = n;
137 ((sockaddr_in*)s)->sin_port = 0;
138 ((sockaddr_in*)s)->sin_family = AF_INET;
142 // Well, this is as good as it's gonna get.
143 errno = EADDRNOTAVAIL;
149 if (ServerInstance->SE->Bind(this->fd, s, size) < 0)
151 this->state = I_ERROR;
152 this->OnError(I_ERR_BIND);
161 /* Most irc servers require you to specify the ip you want to bind to.
162 * If you dont specify an IP, they rather dumbly bind to the first IP
163 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
164 * addresses we've bound server ports to, and we try and bind our outbound
165 * connections to the first usable non-loopback and non-any IP we find.
166 * This is easier to configure when you have a lot of links and a lot
167 * of servers to configure.
169 bool BufferedSocket::BindAddr(const std::string &ip_to_bind)
171 ConfigReader Conf(this->ServerInstance);
174 /* Are we looking for a binding to fit an ipv6 host? */
175 if ((ip_to_bind.empty()) || (ip_to_bind.find(':') != std::string::npos))
179 // Case one: If they provided an IP, try bind it
180 if (!ip_to_bind.empty())
182 // And if it fails, don't do anything.
183 return this->DoBindMagic(ip_to_bind, v6);
186 for (int j = 0; j < Conf.Enumerate("bind"); j++)
188 // We only want to try bind to a server ip.
189 if (Conf.ReadValue("bind","type",j) != "servers")
192 // set current IP to the <bind> tag
193 std::string current_ip = Conf.ReadValue("bind","address",j);
195 // Make sure IP is nothing local
196 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
199 // Try bind, don't fail if it doesn't bind though.
200 if (this->DoBindMagic(current_ip, v6))
204 // NOTE: You may wonder WTF we are returning *true* here, but that is because there were no custom binds setup, and so we have nothing to do
205 // (remember, outgoing connections without binding are perfectly ok).
206 ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
210 bool BufferedSocket::DoConnect(unsigned long maxtime)
212 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
213 sockaddr* addr = new sockaddr[2];
214 socklen_t size = sizeof(sockaddr_in);
217 if ((!*this->host) || strchr(this->host, ':'))
222 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
223 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
225 if (!this->BindAddr(this->cbindip))
237 this->fd = socket(AF_INET, SOCK_STREAM, 0);
240 if (!this->BindAddr(this->cbindip))
252 this->state = I_ERROR;
253 this->OnError(I_ERR_SOCKET);
262 if (inet_pton(AF_INET6, this->host, &addy) > 0)
264 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
265 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
266 ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
267 size = sizeof(sockaddr_in6);
274 if (inet_aton(this->host, &addy) > 0)
276 ((sockaddr_in*)addr)->sin_family = AF_INET;
277 ((sockaddr_in*)addr)->sin_addr = addy;
278 ((sockaddr_in*)addr)->sin_port = htons(this->port);
282 ServerInstance->SE->NonBlocking(this->fd);
284 if (ServerInstance->SE->Connect(this, (sockaddr*)addr, size) == -1)
286 if (errno != EINPROGRESS)
288 this->OnError(I_ERR_CONNECT);
290 this->state = I_ERROR;
295 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
296 this->ServerInstance->Timers->AddTimer(this->Timeout);
299 this->state = I_CONNECTING;
303 if (!this->ServerInstance->SE->AddFd(this))
305 this->OnError(I_ERR_NOMOREFDS);
307 this->state = I_ERROR;
313 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
318 void BufferedSocket::Close()
320 /* Save this, so we dont lose it,
321 * otherise on failure, error messages
322 * might be inaccurate.
327 if (this->GetIOHook())
331 this->GetIOHook()->OnRawSocketClose(this->fd);
333 catch (CoreException& modexcept)
335 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
338 ServerInstance->SE->Shutdown(this, 2);
339 if (ServerInstance->SE->Close(this) != -1)
342 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
343 ServerInstance->SocketCull[this] = this;
348 std::string BufferedSocket::GetIP()
353 const char* BufferedSocket::Read()
355 if (!ServerInstance->SE->BoundsCheckFd(this))
359 char* ReadBuffer = ServerInstance->GetReadBuffer();
361 if (this->GetIOHook())
367 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
369 catch (CoreException& modexcept)
371 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
385 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
389 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
390 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
391 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
392 * --w00t (july 2, 2008)
410 * This function formerly tried to flush write buffer each call.
411 * While admirable in attempting to get the data out to wherever
412 * it is going, on a full socket, it's just going to syscall write() and
413 * EAGAIN constantly, instead of waiting in the SE to know if it can write
414 * which will chew a bit of CPU.
416 * So, now this function returns void (take note) and just adds to the sendq.
418 * It'll get written at a determinate point when the socketengine tells us it can write.
419 * -- w00t (april 1, 2008)
421 void BufferedSocket::Write(const std::string &data)
423 /* Append the data to the back of the queue ready for writing */
424 outbuffer.push_back(data);
426 /* Mark ourselves as wanting write */
427 this->ServerInstance->SE->WantWrite(this);
430 bool BufferedSocket::FlushWriteBuffer()
433 if ((this->fd > -1) && (this->state == I_CONNECTED))
435 if (this->GetIOHook())
437 while (outbuffer.size() && (errno != EAGAIN))
441 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
442 * implement their own buffering mechanisms
444 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
445 outbuffer.pop_front();
447 catch (CoreException& modexcept)
449 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
456 /* If we have multiple lines, try to send them all,
457 * not just the first one -- Brain
459 while (outbuffer.size() && (errno != EAGAIN))
462 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
466 if ((unsigned int)result >= outbuffer[0].length())
468 /* The whole block was written (usually a line)
469 * Pop the block off the front of the queue,
470 * dont set errno, because we are clear of errors
471 * and want to try and write the next block too.
473 outbuffer.pop_front();
477 std::string temp = outbuffer[0].substr(result);
479 /* We didnt get the whole line out. arses.
480 * Try again next time, i guess. Set errno,
481 * because we shouldnt be writing any more now,
482 * until the socketengine says its safe to do so.
487 else if (result == 0)
489 this->ServerInstance->SE->DelFd(this);
493 else if ((result == -1) && (errno != EAGAIN))
495 this->OnError(I_ERR_WRITE);
496 this->state = I_ERROR;
497 this->ServerInstance->SE->DelFd(this);
505 if ((errno == EAGAIN) && (fd > -1))
507 this->ServerInstance->SE->WantWrite(this);
513 void SocketTimeout::Tick(time_t)
515 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
517 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
520 if (this->sock->state == I_CONNECTING)
522 // for connecting sockets, the timeout can occur
523 // which causes termination of the connection after
524 // the given number of seconds without a successful
526 this->sock->OnTimeout();
527 this->sock->OnError(I_ERR_TIMEOUT);
529 /* NOTE: We must set this AFTER DelFd, as we added
530 * this socket whilst writeable. This means that we
531 * must DELETE the socket whilst writeable too!
533 this->sock->state = I_ERROR;
535 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
536 ServerInstance->SocketCull[this->sock] = this->sock;
539 this->sock->Timeout = NULL;
542 bool BufferedSocket::InternalMarkConnected()
544 /* Our socket was in write-state, so delete it and re-add it
547 this->SetState(I_CONNECTED);
549 if (this->GetIOHook())
551 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
554 this->GetIOHook()->OnRawSocketConnect(this->fd);
556 catch (CoreException& modexcept)
558 ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
562 return this->OnConnected();
565 void BufferedSocket::SetState(BufferedSocketState s)
570 BufferedSocketState BufferedSocket::GetState()
575 bool BufferedSocket::OnConnected() { return true; }
576 void BufferedSocket::OnError(BufferedSocketError) { return; }
577 int BufferedSocket::OnDisconnect() { return 0; }
578 bool BufferedSocket::OnDataReady() { return true; }
579 bool BufferedSocket::OnWriteReady()
581 // Default behaviour: just try write some.
582 return !this->FlushWriteBuffer();
584 void BufferedSocket::OnTimeout() { return; }
585 void BufferedSocket::OnClose() { return; }
587 BufferedSocket::~BufferedSocket()
592 ServerInstance->Timers->DelTimer(Timeout);
597 void BufferedSocket::HandleEvent(EventType et, int errornum)
606 this->OnError(I_ERR_TIMEOUT);
610 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
613 this->OnError(I_ERR_BIND);
617 this->OnError(I_ERR_WRITE);
621 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
622 this->ServerInstance->SocketCull[this] = this;
628 if (!this->OnDataReady())
630 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
631 this->ServerInstance->SocketCull[this] = this;
638 if (this->state == I_CONNECTING)
640 if (!this->InternalMarkConnected())
642 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
643 this->ServerInstance->SocketCull[this] = this;
650 if (!this->OnWriteReady())
652 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
653 this->ServerInstance->SocketCull[this] = this;