2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
7 * Copyright (C) 2006-2007 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "inspstring.h"
28 #include "socketengine.h"
30 #ifndef DISABLE_WRITEV
38 BufferedSocket::BufferedSocket()
44 BufferedSocket::BufferedSocket(int newfd)
48 this->state = I_CONNECTED;
50 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
53 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
55 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
56 if (err != I_ERR_NONE)
59 SetError(strerror(errno));
64 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
66 irc::sockets::sockaddrs addr, bind;
67 if (!irc::sockets::aptosa(ipaddr, aport, addr))
69 ServerInstance->Logs->Log("SOCKET", DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
73 bind.sa.sa_family = 0;
74 if (!connectbindip.empty())
76 if (!irc::sockets::aptosa(connectbindip, 0, bind))
82 return BeginConnect(addr, bind, maxtime);
85 static void IncreaseOSBuffers(int fd)
87 // attempt to increase socket sendq and recvq as high as its possible
90 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
91 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(recvbuf));
92 // on failure, 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.
95 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
98 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
103 if (bind.sa.sa_family != 0)
105 if (ServerInstance->SE->Bind(fd, bind) < 0)
109 ServerInstance->SE->NonBlocking(fd);
111 if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
113 if (errno != EINPROGRESS)
114 return I_ERR_CONNECT;
117 this->state = I_CONNECTING;
119 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
120 return I_ERR_NOMOREFDS;
122 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
123 ServerInstance->Timers->AddTimer(this->Timeout);
125 IncreaseOSBuffers(fd);
127 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
131 void StreamSocket::Close()
135 // final chance, dump as much of the sendq as we can
141 IOHook->OnStreamSocketClose(this);
143 catch (CoreException& modexcept)
145 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
146 modexcept.GetSource(), modexcept.GetReason());
150 ServerInstance->SE->Shutdown(this, 2);
151 ServerInstance->SE->DelFd(this);
152 ServerInstance->SE->Close(this);
157 CullResult StreamSocket::cull()
160 return EventHandler::cull();
163 bool StreamSocket::GetNextLine(std::string& line, char delim)
165 std::string::size_type i = recvq.find(delim);
166 if (i == std::string::npos)
168 line = recvq.substr(0, i);
169 // TODO is this the most efficient way to split?
170 recvq = recvq.substr(i + 1);
174 void StreamSocket::DoRead()
181 rv = IOHook->OnStreamSocketRead(this, recvq);
183 catch (CoreException& modexcept)
185 ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
186 modexcept.GetSource(), modexcept.GetReason());
192 SetError("Read Error"); // will not overwrite a better error message
196 char* ReadBuffer = ServerInstance->GetReadBuffer();
197 int n = ServerInstance->SE->Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
198 if (n == ServerInstance->Config->NetBufferSize)
200 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
201 recvq.append(ReadBuffer, n);
206 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
207 recvq.append(ReadBuffer, n);
212 error = "Connection closed";
213 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
215 else if (errno == EAGAIN)
217 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
219 else if (errno == EINTR)
221 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
225 error = strerror(errno);
226 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
231 /* Don't try to prepare huge blobs of data to send to a blocked socket */
232 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
234 void StreamSocket::DoWrite()
238 if (!error.empty() || fd < 0 || fd == INT_MAX)
240 ServerInstance->Logs->Log("SOCKET", DEBUG, "DoWrite on errored or closed socket");
244 #ifndef DISABLE_WRITEV
251 while (error.empty() && !sendq.empty())
253 if (sendq.size() > 1 && sendq[0].length() < 1024)
255 // Avoid multiple repeated SSL encryption invocations
256 // This adds a single copy of the queue, but avoids
257 // much more overhead in terms of system calls invoked
260 // The length limit of 1024 is to prevent merging strings
261 // more than once when writes begin to block.
263 tmp.reserve(sendq_len);
264 for(unsigned int i=0; i < sendq.size(); i++)
265 tmp.append(sendq[i]);
267 sendq.push_back(tmp);
269 std::string& front = sendq.front();
270 int itemlen = front.length();
273 rv = IOHook->OnStreamSocketWrite(this, front);
276 // consumed the entire string, and is ready for more
277 sendq_len -= itemlen;
282 // socket has blocked. Stop trying to send data.
283 // IOHook has requested unblock notification from the socketengine
285 // Since it is possible that a partial write took place, adjust sendq_len
286 sendq_len = sendq_len - itemlen + front.length();
291 SetError("Write Error"); // will not overwrite a better error message
295 #ifdef DISABLE_WRITEV
298 rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
301 SetError("Connection closed");
306 if (errno == EAGAIN || errno == EINTR)
307 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
309 SetError(strerror(errno));
312 else if (rv < itemlen)
314 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
315 front = front.substr(itemlen - rv);
321 sendq_len -= itemlen;
324 ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
330 catch (CoreException& modexcept)
332 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
333 modexcept.GetSource(), modexcept.GetReason());
336 #ifndef DISABLE_WRITEV
339 // don't even try if we are known to be blocking
340 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
342 // start out optimistic - we won't need to write any more
343 int eventChange = FD_WANT_EDGE_WRITE;
344 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
346 // Prepare a writev() call to write all buffers efficiently
347 int bufcount = sendq.size();
349 // cap the number of buffers at MYIOV_MAX
350 if (bufcount > MYIOV_MAX)
352 bufcount = MYIOV_MAX;
356 iovec* iovecs = new iovec[bufcount];
357 for(int i=0; i < bufcount; i++)
359 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
360 iovecs[i].iov_len = sendq[i].length();
361 rv_max += sendq[i].length();
363 int rv = writev(fd, iovecs, bufcount);
366 if (rv == (int)sendq_len)
368 // it's our lucky day, everything got written out. Fast cleanup.
369 // This won't ever happen if the number of buffers got capped.
375 // Partial write. Clean out strings from the sendq
378 // it's going to block now
379 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
382 while (rv > 0 && !sendq.empty())
384 std::string& front = sendq.front();
385 if (front.length() <= (size_t)rv)
387 // this string got fully written out
388 rv -= front.length();
393 // stopped in the middle of this string
394 front = front.substr(rv);
401 error = "Connection closed";
403 else if (errno == EAGAIN)
405 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
407 else if (errno == EINTR)
409 // restart interrupted syscall
414 error = strerror(errno);
419 // error - kill all events
420 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
424 ServerInstance->SE->ChangeEventMask(this, eventChange);
430 void StreamSocket::WriteData(const std::string &data)
434 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
439 /* Append the data to the back of the queue ready for writing */
440 sendq.push_back(data);
441 sendq_len += data.length();
443 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
446 void SocketTimeout::Tick(time_t)
448 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
450 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
453 if (this->sock->state == I_CONNECTING)
455 // for connecting sockets, the timeout can occur
456 // which causes termination of the connection after
457 // the given number of seconds without a successful
459 this->sock->OnTimeout();
460 this->sock->OnError(I_ERR_TIMEOUT);
461 this->sock->state = I_ERROR;
463 ServerInstance->GlobalCulls.AddItem(sock);
466 this->sock->Timeout = NULL;
469 void BufferedSocket::OnConnected() { }
470 void BufferedSocket::OnTimeout() { return; }
472 void BufferedSocket::DoWrite()
474 if (state == I_CONNECTING)
479 GetIOHook()->OnStreamSocketConnect(this);
481 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
483 this->StreamSocket::DoWrite();
486 BufferedSocket::~BufferedSocket()
491 ServerInstance->Timers->DelTimer(Timeout);
496 void StreamSocket::HandleEvent(EventType et, int errornum)
500 BufferedSocketError errcode = I_ERR_OTHER;
507 SetError("Connection closed");
509 SetError(strerror(errornum));
513 errcode = I_ERR_TIMEOUT;
517 errcode = I_ERR_CONNECT;
520 errcode = I_ERR_BIND;
524 errcode = I_ERR_WRITE;
541 catch (CoreException& ex)
543 ServerInstance->Logs->Log("SOCKET", DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
545 SetError(ex.GetReason());
549 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());