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 * ---------------------------------------------------
16 #include "inspstring.h"
17 #include "socketengine.h"
19 bool BufferedSocket::Readable()
21 return (this->state != I_CONNECTING);
24 BufferedSocket::BufferedSocket(InspIRCd* SI)
27 this->state = I_DISCONNECTED;
29 this->ServerInstance = SI;
32 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
36 this->state = I_CONNECTED;
37 strlcpy(this->IP,ip,MAXBUF);
38 this->ServerInstance = SI;
40 this->ServerInstance->SE->AddFd(this);
43 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
45 this->cbindip = connectbindip;
47 this->ServerInstance = SI;
48 strlcpy(host,ipaddr.c_str(),MAXBUF);
51 strlcpy(this->host,ipaddr.c_str(),MAXBUF);
54 irc::sockets::sockaddrs testaddr;
55 if (!irc::sockets::aptosa(host, aport, &testaddr))
57 this->ServerInstance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
58 this->OnError(I_ERR_CONNECT);
61 this->state = I_ERROR;
66 strlcpy(this->IP,host,MAXBUF);
67 if (!this->DoConnect(maxtime))
69 this->OnError(I_ERR_CONNECT);
72 this->state = I_ERROR;
78 void BufferedSocket::SetQueues()
80 // attempt to increase socket sendq and recvq as high as its possible
83 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)))
85 //this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
86 ; // 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.
90 bool BufferedSocket::DoBindMagic(const std::string ¤t_ip)
92 irc::sockets::sockaddrs s;
93 if (!irc::sockets::aptosa(current_ip.c_str(), 0, &s))
95 errno = EADDRNOTAVAIL;
99 if (ServerInstance->SE->Bind(this->fd, &s.sa, sa_size(s)) < 0)
101 this->state = I_ERROR;
102 this->OnError(I_ERR_BIND);
109 /* Most irc servers require you to specify the ip you want to bind to.
110 * If you dont specify an IP, they rather dumbly bind to the first IP
111 * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
112 * addresses we've bound server ports to, and we try and bind our outbound
113 * connections to the first usable non-loopback and non-any IP we find.
114 * This is easier to configure when you have a lot of links and a lot
115 * of servers to configure.
117 bool BufferedSocket::BindAddr(const std::string &ip_to_bind)
119 ConfigReader Conf(this->ServerInstance);
121 // Case one: If they provided an IP, try bind it
122 if (!ip_to_bind.empty())
124 // And if it fails, don't do anything.
125 return this->DoBindMagic(ip_to_bind);
128 for (int j = 0; j < Conf.Enumerate("bind"); j++)
130 // We only want to try bind to a server ip.
131 if (Conf.ReadValue("bind","type",j) != "servers")
134 // set current IP to the <bind> tag
135 std::string current_ip = Conf.ReadValue("bind","address",j);
137 // Make sure IP is nothing local
138 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
141 // Try bind, don't fail if it doesn't bind though.
142 if (this->DoBindMagic(current_ip))
146 // 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
147 // (remember, outgoing connections without binding are perfectly ok).
148 ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
152 bool BufferedSocket::DoConnect(unsigned long maxtime)
154 irc::sockets::sockaddrs addr;
155 irc::sockets::aptosa(this->host, this->port, &addr);
157 this->fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
161 this->state = I_ERROR;
162 this->OnError(I_ERR_SOCKET);
166 if (!this->BindAddr(this->cbindip))
173 ServerInstance->SE->NonBlocking(this->fd);
175 if (ServerInstance->SE->Connect(this, &addr.sa, sa_size(addr)) == -1)
177 if (errno != EINPROGRESS)
179 this->OnError(I_ERR_CONNECT);
181 this->state = I_ERROR;
185 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
186 this->ServerInstance->Timers->AddTimer(this->Timeout);
189 this->state = I_CONNECTING;
192 if (!this->ServerInstance->SE->AddFd(this))
194 this->OnError(I_ERR_NOMOREFDS);
196 this->state = I_ERROR;
202 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
207 void BufferedSocket::Close()
209 /* Save this, so we dont lose it,
210 * otherise on failure, error messages
211 * might be inaccurate.
216 if (this->GetIOHook())
220 this->GetIOHook()->OnRawSocketClose(this->fd);
222 catch (CoreException& modexcept)
224 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
227 ServerInstance->SE->Shutdown(this, 2);
228 if (ServerInstance->SE->Close(this) != -1)
231 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
232 ServerInstance->SocketCull[this] = this;
237 std::string BufferedSocket::GetIP()
242 const char* BufferedSocket::Read()
244 if (!ServerInstance->SE->BoundsCheckFd(this))
248 char* ReadBuffer = ServerInstance->GetReadBuffer();
250 if (this->GetIOHook())
256 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
258 catch (CoreException& modexcept)
260 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
274 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
278 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
279 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
280 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
281 * --w00t (july 2, 2008)
299 * This function formerly tried to flush write buffer each call.
300 * While admirable in attempting to get the data out to wherever
301 * it is going, on a full socket, it's just going to syscall write() and
302 * EAGAIN constantly, instead of waiting in the SE to know if it can write
303 * which will chew a bit of CPU.
305 * So, now this function returns void (take note) and just adds to the sendq.
307 * It'll get written at a determinate point when the socketengine tells us it can write.
308 * -- w00t (april 1, 2008)
310 void BufferedSocket::Write(const std::string &data)
312 /* Append the data to the back of the queue ready for writing */
313 outbuffer.push_back(data);
315 /* Mark ourselves as wanting write */
316 this->ServerInstance->SE->WantWrite(this);
319 bool BufferedSocket::FlushWriteBuffer()
322 if ((this->fd > -1) && (this->state == I_CONNECTED))
324 if (this->GetIOHook())
326 while (outbuffer.size() && (errno != EAGAIN))
330 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
331 * implement their own buffering mechanisms
333 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
334 outbuffer.pop_front();
336 catch (CoreException& modexcept)
338 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
345 /* If we have multiple lines, try to send them all,
346 * not just the first one -- Brain
348 while (outbuffer.size() && (errno != EAGAIN))
351 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
355 if ((unsigned int)result >= outbuffer[0].length())
357 /* The whole block was written (usually a line)
358 * Pop the block off the front of the queue,
359 * dont set errno, because we are clear of errors
360 * and want to try and write the next block too.
362 outbuffer.pop_front();
366 std::string temp = outbuffer[0].substr(result);
368 /* We didnt get the whole line out. arses.
369 * Try again next time, i guess. Set errno,
370 * because we shouldnt be writing any more now,
371 * until the socketengine says its safe to do so.
376 else if (result == 0)
378 this->ServerInstance->SE->DelFd(this);
382 else if ((result == -1) && (errno != EAGAIN))
384 this->OnError(I_ERR_WRITE);
385 this->state = I_ERROR;
386 this->ServerInstance->SE->DelFd(this);
394 if ((errno == EAGAIN) && (fd > -1))
396 this->ServerInstance->SE->WantWrite(this);
402 void SocketTimeout::Tick(time_t)
404 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
406 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
409 if (this->sock->state == I_CONNECTING)
411 // for connecting sockets, the timeout can occur
412 // which causes termination of the connection after
413 // the given number of seconds without a successful
415 this->sock->OnTimeout();
416 this->sock->OnError(I_ERR_TIMEOUT);
418 /* NOTE: We must set this AFTER DelFd, as we added
419 * this socket whilst writeable. This means that we
420 * must DELETE the socket whilst writeable too!
422 this->sock->state = I_ERROR;
424 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
425 ServerInstance->SocketCull[this->sock] = this->sock;
428 this->sock->Timeout = NULL;
431 bool BufferedSocket::InternalMarkConnected()
433 /* Our socket was in write-state, so delete it and re-add it
436 this->SetState(I_CONNECTED);
438 if (this->GetIOHook())
440 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
443 this->GetIOHook()->OnRawSocketConnect(this->fd);
445 catch (CoreException& modexcept)
447 ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
451 return this->OnConnected();
454 void BufferedSocket::SetState(BufferedSocketState s)
459 BufferedSocketState BufferedSocket::GetState()
464 bool BufferedSocket::OnConnected() { return true; }
465 void BufferedSocket::OnError(BufferedSocketError) { return; }
466 int BufferedSocket::OnDisconnect() { return 0; }
467 bool BufferedSocket::OnDataReady() { return true; }
468 bool BufferedSocket::OnWriteReady()
470 // Default behaviour: just try write some.
471 return !this->FlushWriteBuffer();
473 void BufferedSocket::OnTimeout() { return; }
474 void BufferedSocket::OnClose() { return; }
476 BufferedSocket::~BufferedSocket()
481 ServerInstance->Timers->DelTimer(Timeout);
486 void BufferedSocket::HandleEvent(EventType et, int errornum)
495 this->OnError(I_ERR_TIMEOUT);
499 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
502 this->OnError(I_ERR_BIND);
506 this->OnError(I_ERR_WRITE);
510 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
511 this->ServerInstance->SocketCull[this] = this;
517 if (!this->OnDataReady())
519 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
520 this->ServerInstance->SocketCull[this] = this;
527 if (this->state == I_CONNECTING)
529 if (!this->InternalMarkConnected())
531 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
532 this->ServerInstance->SocketCull[this] = this;
539 if (!this->OnWriteReady())
541 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
542 this->ServerInstance->SocketCull[this] = this;