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)
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, sa_size(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);
123 // Case one: If they provided an IP, try bind it
124 if (!ip_to_bind.empty())
126 // And if it fails, don't do anything.
127 return this->DoBindMagic(ip_to_bind);
130 for (int j = 0; j < Conf.Enumerate("bind"); j++)
132 // We only want to try bind to a server ip.
133 if (Conf.ReadValue("bind","type",j) != "servers")
136 // set current IP to the <bind> tag
137 std::string current_ip = Conf.ReadValue("bind","address",j);
139 // Make sure IP is nothing local
140 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
143 // Try bind, don't fail if it doesn't bind though.
144 if (this->DoBindMagic(current_ip))
148 // 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
149 // (remember, outgoing connections without binding are perfectly ok).
150 ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
154 bool BufferedSocket::DoConnect(unsigned long maxtime)
156 irc::sockets::sockaddrs addr;
157 irc::sockets::aptosa(this->host, this->port, &addr);
159 this->fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
163 this->state = I_ERROR;
164 this->OnError(I_ERR_SOCKET);
168 if (!this->BindAddr(this->cbindip))
175 ServerInstance->SE->NonBlocking(this->fd);
177 if (ServerInstance->SE->Connect(this, &addr.sa, sa_size(addr)) == -1)
179 if (errno != EINPROGRESS)
181 this->OnError(I_ERR_CONNECT);
183 this->state = I_ERROR;
187 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
188 this->ServerInstance->Timers->AddTimer(this->Timeout);
191 this->state = I_CONNECTING;
194 if (!this->ServerInstance->SE->AddFd(this))
196 this->OnError(I_ERR_NOMOREFDS);
198 this->state = I_ERROR;
204 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
209 void BufferedSocket::Close()
211 /* Save this, so we dont lose it,
212 * otherise on failure, error messages
213 * might be inaccurate.
218 if (this->GetIOHook())
222 this->GetIOHook()->OnRawSocketClose(this->fd);
224 catch (CoreException& modexcept)
226 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
229 ServerInstance->SE->Shutdown(this, 2);
230 if (ServerInstance->SE->Close(this) != -1)
233 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
234 ServerInstance->SocketCull[this] = this;
239 std::string BufferedSocket::GetIP()
244 const char* BufferedSocket::Read()
246 if (!ServerInstance->SE->BoundsCheckFd(this))
250 char* ReadBuffer = ServerInstance->GetReadBuffer();
252 if (this->GetIOHook())
258 MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
260 catch (CoreException& modexcept)
262 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
276 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
280 * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
281 * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
282 * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
283 * --w00t (july 2, 2008)
301 * This function formerly tried to flush write buffer each call.
302 * While admirable in attempting to get the data out to wherever
303 * it is going, on a full socket, it's just going to syscall write() and
304 * EAGAIN constantly, instead of waiting in the SE to know if it can write
305 * which will chew a bit of CPU.
307 * So, now this function returns void (take note) and just adds to the sendq.
309 * It'll get written at a determinate point when the socketengine tells us it can write.
310 * -- w00t (april 1, 2008)
312 void BufferedSocket::Write(const std::string &data)
314 /* Append the data to the back of the queue ready for writing */
315 outbuffer.push_back(data);
317 /* Mark ourselves as wanting write */
318 this->ServerInstance->SE->WantWrite(this);
321 bool BufferedSocket::FlushWriteBuffer()
324 if ((this->fd > -1) && (this->state == I_CONNECTED))
326 if (this->GetIOHook())
328 while (outbuffer.size() && (errno != EAGAIN))
332 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
333 * implement their own buffering mechanisms
335 this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
336 outbuffer.pop_front();
338 catch (CoreException& modexcept)
340 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
347 /* If we have multiple lines, try to send them all,
348 * not just the first one -- Brain
350 while (outbuffer.size() && (errno != EAGAIN))
353 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
357 if ((unsigned int)result >= outbuffer[0].length())
359 /* The whole block was written (usually a line)
360 * Pop the block off the front of the queue,
361 * dont set errno, because we are clear of errors
362 * and want to try and write the next block too.
364 outbuffer.pop_front();
368 std::string temp = outbuffer[0].substr(result);
370 /* We didnt get the whole line out. arses.
371 * Try again next time, i guess. Set errno,
372 * because we shouldnt be writing any more now,
373 * until the socketengine says its safe to do so.
378 else if (result == 0)
380 this->ServerInstance->SE->DelFd(this);
384 else if ((result == -1) && (errno != EAGAIN))
386 this->OnError(I_ERR_WRITE);
387 this->state = I_ERROR;
388 this->ServerInstance->SE->DelFd(this);
396 if ((errno == EAGAIN) && (fd > -1))
398 this->ServerInstance->SE->WantWrite(this);
404 void SocketTimeout::Tick(time_t)
406 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
408 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
411 if (this->sock->state == I_CONNECTING)
413 // for connecting sockets, the timeout can occur
414 // which causes termination of the connection after
415 // the given number of seconds without a successful
417 this->sock->OnTimeout();
418 this->sock->OnError(I_ERR_TIMEOUT);
420 /* NOTE: We must set this AFTER DelFd, as we added
421 * this socket whilst writeable. This means that we
422 * must DELETE the socket whilst writeable too!
424 this->sock->state = I_ERROR;
426 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
427 ServerInstance->SocketCull[this->sock] = this->sock;
430 this->sock->Timeout = NULL;
433 bool BufferedSocket::InternalMarkConnected()
435 /* Our socket was in write-state, so delete it and re-add it
438 this->SetState(I_CONNECTED);
440 if (this->GetIOHook())
442 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
445 this->GetIOHook()->OnRawSocketConnect(this->fd);
447 catch (CoreException& modexcept)
449 ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
453 return this->OnConnected();
456 void BufferedSocket::SetState(BufferedSocketState s)
461 BufferedSocketState BufferedSocket::GetState()
466 bool BufferedSocket::OnConnected() { return true; }
467 void BufferedSocket::OnError(BufferedSocketError) { return; }
468 int BufferedSocket::OnDisconnect() { return 0; }
469 bool BufferedSocket::OnDataReady() { return true; }
470 bool BufferedSocket::OnWriteReady()
472 // Default behaviour: just try write some.
473 return !this->FlushWriteBuffer();
475 void BufferedSocket::OnTimeout() { return; }
476 void BufferedSocket::OnClose() { return; }
478 BufferedSocket::~BufferedSocket()
483 ServerInstance->Timers->DelTimer(Timeout);
488 void BufferedSocket::HandleEvent(EventType et, int errornum)
497 this->OnError(I_ERR_TIMEOUT);
501 this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
504 this->OnError(I_ERR_BIND);
508 this->OnError(I_ERR_WRITE);
512 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
513 this->ServerInstance->SocketCull[this] = this;
519 if (!this->OnDataReady())
521 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
522 this->ServerInstance->SocketCull[this] = this;
529 if (this->state == I_CONNECTING)
531 if (!this->InternalMarkConnected())
533 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
534 this->ServerInstance->SocketCull[this] = this;
541 if (!this->OnWriteReady())
543 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
544 this->ServerInstance->SocketCull[this] = this;