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);
56 irc::sockets::sockaddrs testaddr;
57 if (!irc::sockets::aptosa(host, aport, &testaddr))
59 this->ServerInstance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
60 this->OnError(I_ERR_CONNECT);
63 this->state = I_ERROR;
68 strlcpy(this->IP,host,MAXBUF);
69 if (!this->DoConnect(maxtime))
71 this->OnError(I_ERR_CONNECT);
74 this->state = I_ERROR;
80 void BufferedSocket::SetQueues()
82 // attempt to increase socket sendq and recvq as high as its possible
85 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)))
87 //this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
88 ; // 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.
92 bool BufferedSocket::DoBindMagic(const std::string ¤t_ip, bool v6)
94 irc::sockets::sockaddrs s;
95 if (!irc::sockets::aptosa(current_ip.c_str(), 0, &s))
97 errno = EADDRNOTAVAIL;
101 if (ServerInstance->SE->Bind(this->fd, &s.sa, sizeof(s)) < 0)
103 this->state = I_ERROR;
104 this->OnError(I_ERR_BIND);
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_to_bind)
121 ConfigReader Conf(this->ServerInstance);
124 // Case one: If they provided an IP, try bind it
125 if (!ip_to_bind.empty())
128 // Check whether or not they are binding to an IPv6 IP..
129 if (ip_to_bind.find(':') != std::string::npos)
132 // And if it fails, don't do anything.
133 return this->DoBindMagic(ip_to_bind, v6);
136 for (int j = 0; j < Conf.Enumerate("bind"); j++)
138 // We only want to try bind to a server ip.
139 if (Conf.ReadValue("bind","type",j) != "servers")
142 // set current IP to the <bind> tag
143 std::string current_ip = Conf.ReadValue("bind","address",j);
146 // Check whether this <bind> is for an ipv6 address
147 if (current_ip.find(':') != std::string::npos)
153 // Make sure IP is nothing local
154 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
157 // Try bind, don't fail if it doesn't bind though.
158 if (this->DoBindMagic(current_ip, v6))
162 // 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
163 // (remember, outgoing connections without binding are perfectly ok).
164 ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
168 bool BufferedSocket::DoConnect(unsigned long maxtime)
170 irc::sockets::sockaddrs addr;
171 irc::sockets::aptosa(this->host, this->port, &addr);
173 this->fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
177 this->state = I_ERROR;
178 this->OnError(I_ERR_SOCKET);
182 if (!this->BindAddr(this->cbindip))
189 ServerInstance->SE->NonBlocking(this->fd);
191 if (ServerInstance->SE->Connect(this, &addr.sa, sa_size(addr)) == -1)
193 if (errno != EINPROGRESS)
195 this->OnError(I_ERR_CONNECT);
197 this->state = I_ERROR;
201 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
202 this->ServerInstance->Timers->AddTimer(this->Timeout);
205 this->state = I_CONNECTING;
208 if (!this->ServerInstance->SE->AddFd(this))
210 this->OnError(I_ERR_NOMOREFDS);
212 this->state = I_ERROR;
218 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
223 void BufferedSocket::Close()
225 /* Save this, so we dont lose it,
226 * otherise on failure, error messages
227 * might be inaccurate.
232 if (this->GetIOHook())
236 this->GetIOHook()->OnRawSocketClose(this->fd);
238 catch (CoreException& modexcept)
240 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
243 ServerInstance->SE->Shutdown(this, 2);
244 if (ServerInstance->SE->Close(this) != -1)
247 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
248 ServerInstance->SocketCull[this] = this;
253 std::string BufferedSocket::GetIP()
258 const char* BufferedSocket::Read()
260 if (!ServerInstance->SE->BoundsCheckFd(this))
264 char* ReadBuffer = ServerInstance->GetReadBuffer();
266 if (this->GetIOHook())
272 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
274 catch (CoreException& modexcept)
276 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
290 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
294 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
295 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
296 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
297 * --w00t (july 2, 2008)
315 * This function formerly tried to flush write buffer each call.
316 * While admirable in attempting to get the data out to wherever
317 * it is going, on a full socket, it's just going to syscall write() and
318 * EAGAIN constantly, instead of waiting in the SE to know if it can write
319 * which will chew a bit of CPU.
321 * So, now this function returns void (take note) and just adds to the sendq.
323 * It'll get written at a determinate point when the socketengine tells us it can write.
324 * -- w00t (april 1, 2008)
326 void BufferedSocket::Write(const std::string &data)
328 /* Append the data to the back of the queue ready for writing */
329 outbuffer.push_back(data);
331 /* Mark ourselves as wanting write */
332 this->ServerInstance->SE->WantWrite(this);
335 bool BufferedSocket::FlushWriteBuffer()
338 if ((this->fd > -1) && (this->state == I_CONNECTED))
340 if (this->GetIOHook())
342 while (outbuffer.size() && (errno != EAGAIN))
346 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
347 * implement their own buffering mechanisms
349 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
350 outbuffer.pop_front();
352 catch (CoreException& modexcept)
354 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
361 /* If we have multiple lines, try to send them all,
362 * not just the first one -- Brain
364 while (outbuffer.size() && (errno != EAGAIN))
367 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
371 if ((unsigned int)result >= outbuffer[0].length())
373 /* The whole block was written (usually a line)
374 * Pop the block off the front of the queue,
375 * dont set errno, because we are clear of errors
376 * and want to try and write the next block too.
378 outbuffer.pop_front();
382 std::string temp = outbuffer[0].substr(result);
384 /* We didnt get the whole line out. arses.
385 * Try again next time, i guess. Set errno,
386 * because we shouldnt be writing any more now,
387 * until the socketengine says its safe to do so.
392 else if (result == 0)
394 this->ServerInstance->SE->DelFd(this);
398 else if ((result == -1) && (errno != EAGAIN))
400 this->OnError(I_ERR_WRITE);
401 this->state = I_ERROR;
402 this->ServerInstance->SE->DelFd(this);
410 if ((errno == EAGAIN) && (fd > -1))
412 this->ServerInstance->SE->WantWrite(this);
418 void SocketTimeout::Tick(time_t)
420 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
422 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
425 if (this->sock->state == I_CONNECTING)
427 // for connecting sockets, the timeout can occur
428 // which causes termination of the connection after
429 // the given number of seconds without a successful
431 this->sock->OnTimeout();
432 this->sock->OnError(I_ERR_TIMEOUT);
434 /* NOTE: We must set this AFTER DelFd, as we added
435 * this socket whilst writeable. This means that we
436 * must DELETE the socket whilst writeable too!
438 this->sock->state = I_ERROR;
440 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
441 ServerInstance->SocketCull[this->sock] = this->sock;
444 this->sock->Timeout = NULL;
447 bool BufferedSocket::InternalMarkConnected()
449 /* Our socket was in write-state, so delete it and re-add it
452 this->SetState(I_CONNECTED);
454 if (this->GetIOHook())
456 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
459 this->GetIOHook()->OnRawSocketConnect(this->fd);
461 catch (CoreException& modexcept)
463 ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
467 return this->OnConnected();
470 void BufferedSocket::SetState(BufferedSocketState s)
475 BufferedSocketState BufferedSocket::GetState()
480 bool BufferedSocket::OnConnected() { return true; }
481 void BufferedSocket::OnError(BufferedSocketError) { return; }
482 int BufferedSocket::OnDisconnect() { return 0; }
483 bool BufferedSocket::OnDataReady() { return true; }
484 bool BufferedSocket::OnWriteReady()
486 // Default behaviour: just try write some.
487 return !this->FlushWriteBuffer();
489 void BufferedSocket::OnTimeout() { return; }
490 void BufferedSocket::OnClose() { return; }
492 BufferedSocket::~BufferedSocket()
497 ServerInstance->Timers->DelTimer(Timeout);
502 void BufferedSocket::HandleEvent(EventType et, int errornum)
511 this->OnError(I_ERR_TIMEOUT);
515 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
518 this->OnError(I_ERR_BIND);
522 this->OnError(I_ERR_WRITE);
526 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
527 this->ServerInstance->SocketCull[this] = this;
533 if (!this->OnDataReady())
535 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
536 this->ServerInstance->SocketCull[this] = this;
543 if (this->state == I_CONNECTING)
545 if (!this->InternalMarkConnected())
547 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
548 this->ServerInstance->SocketCull[this] = this;
555 if (!this->OnWriteReady())
557 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
558 this->ServerInstance->SocketCull[this] = this;