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"
31 #ifndef DISABLE_WRITEV
39 BufferedSocket::BufferedSocket()
45 BufferedSocket::BufferedSocket(int newfd)
49 this->state = I_CONNECTED;
51 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
54 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
56 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
57 if (err != I_ERR_NONE)
60 SetError(SocketEngine::LastError());
65 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
67 irc::sockets::sockaddrs addr, bind;
68 if (!irc::sockets::aptosa(ipaddr, aport, addr))
70 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
74 bind.sa.sa_family = 0;
75 if (!connectbindip.empty())
77 if (!irc::sockets::aptosa(connectbindip, 0, bind))
83 return BeginConnect(addr, bind, maxtime);
86 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
89 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
94 if (bind.sa.sa_family != 0)
96 if (ServerInstance->SE->Bind(fd, bind) < 0)
100 ServerInstance->SE->NonBlocking(fd);
102 if (ServerInstance->SE->Connect(this, &dest.sa, dest.sa_size()) == -1)
104 if (errno != EINPROGRESS)
105 return I_ERR_CONNECT;
108 this->state = I_CONNECTING;
110 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
111 return I_ERR_NOMOREFDS;
113 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
114 ServerInstance->Timers->AddTimer(this->Timeout);
116 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
120 void StreamSocket::Close()
124 // final chance, dump as much of the sendq as we can
130 GetIOHook()->OnStreamSocketClose(this);
132 catch (CoreException& modexcept)
134 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
135 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
139 ServerInstance->SE->Shutdown(this, 2);
140 ServerInstance->SE->DelFd(this);
141 ServerInstance->SE->Close(this);
146 CullResult StreamSocket::cull()
149 return EventHandler::cull();
152 bool StreamSocket::GetNextLine(std::string& line, char delim)
154 std::string::size_type i = recvq.find(delim);
155 if (i == std::string::npos)
157 line = recvq.substr(0, i);
158 // TODO is this the most efficient way to split?
159 recvq = recvq.substr(i + 1);
163 void StreamSocket::DoRead()
170 rv = GetIOHook()->OnStreamSocketRead(this, recvq);
172 catch (CoreException& modexcept)
174 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
175 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
181 SetError("Read Error"); // will not overwrite a better error message
185 char* ReadBuffer = ServerInstance->GetReadBuffer();
186 int n = ServerInstance->SE->Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
187 if (n == ServerInstance->Config->NetBufferSize)
189 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
190 recvq.append(ReadBuffer, n);
195 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
196 recvq.append(ReadBuffer, n);
201 error = "Connection closed";
202 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
204 else if (SocketEngine::IgnoreError())
206 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
208 else if (errno == EINTR)
210 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
214 error = SocketEngine::LastError();
215 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
220 /* Don't try to prepare huge blobs of data to send to a blocked socket */
221 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
223 void StreamSocket::DoWrite()
227 if (!error.empty() || fd < 0 || fd == INT_MAX)
229 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
233 #ifndef DISABLE_WRITEV
240 while (error.empty() && !sendq.empty())
242 if (sendq.size() > 1 && sendq[0].length() < 1024)
244 // Avoid multiple repeated SSL encryption invocations
245 // This adds a single copy of the queue, but avoids
246 // much more overhead in terms of system calls invoked
249 // The length limit of 1024 is to prevent merging strings
250 // more than once when writes begin to block.
253 while (!sendq.empty() && tmp.length() < 1024)
255 tmp.append(sendq.front());
258 sendq.push_front(tmp);
260 std::string& front = sendq.front();
261 int itemlen = front.length();
264 rv = GetIOHook()->OnStreamSocketWrite(this, front);
267 // consumed the entire string, and is ready for more
268 sendq_len -= itemlen;
273 // socket has blocked. Stop trying to send data.
274 // IOHook has requested unblock notification from the socketengine
276 // Since it is possible that a partial write took place, adjust sendq_len
277 sendq_len = sendq_len - itemlen + front.length();
282 SetError("Write Error"); // will not overwrite a better error message
286 #ifdef DISABLE_WRITEV
289 rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
292 SetError("Connection closed");
297 if (errno == EINTR || SocketEngine::IgnoreError())
298 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
300 SetError(SocketEngine::LastError());
303 else if (rv < itemlen)
305 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
306 front = front.substr(rv);
312 sendq_len -= itemlen;
315 ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
321 catch (CoreException& modexcept)
323 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "%s threw an exception: %s",
324 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
327 #ifndef DISABLE_WRITEV
330 // don't even try if we are known to be blocking
331 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
333 // start out optimistic - we won't need to write any more
334 int eventChange = FD_WANT_EDGE_WRITE;
335 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
337 // Prepare a writev() call to write all buffers efficiently
338 int bufcount = sendq.size();
340 // cap the number of buffers at MYIOV_MAX
341 if (bufcount > MYIOV_MAX)
343 bufcount = MYIOV_MAX;
347 iovec* iovecs = new iovec[bufcount];
348 for(int i=0; i < bufcount; i++)
350 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
351 iovecs[i].iov_len = sendq[i].length();
352 rv_max += sendq[i].length();
354 int rv = writev(fd, iovecs, bufcount);
357 if (rv == (int)sendq_len)
359 // it's our lucky day, everything got written out. Fast cleanup.
360 // This won't ever happen if the number of buffers got capped.
366 // Partial write. Clean out strings from the sendq
369 // it's going to block now
370 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
373 while (rv > 0 && !sendq.empty())
375 std::string& front = sendq.front();
376 if (front.length() <= (size_t)rv)
378 // this string got fully written out
379 rv -= front.length();
384 // stopped in the middle of this string
385 front = front.substr(rv);
392 error = "Connection closed";
394 else if (SocketEngine::IgnoreError())
396 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
398 else if (errno == EINTR)
400 // restart interrupted syscall
405 error = SocketEngine::LastError();
410 // error - kill all events
411 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
415 ServerInstance->SE->ChangeEventMask(this, eventChange);
421 void StreamSocket::WriteData(const std::string &data)
425 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
430 /* Append the data to the back of the queue ready for writing */
431 sendq.push_back(data);
432 sendq_len += data.length();
434 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
437 bool SocketTimeout::Tick(time_t)
439 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
441 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
444 if (this->sock->state == I_CONNECTING)
446 // for connecting sockets, the timeout can occur
447 // which causes termination of the connection after
448 // the given number of seconds without a successful
450 this->sock->OnTimeout();
451 this->sock->OnError(I_ERR_TIMEOUT);
452 this->sock->state = I_ERROR;
454 ServerInstance->GlobalCulls.AddItem(sock);
457 this->sock->Timeout = NULL;
461 void BufferedSocket::OnConnected() { }
462 void BufferedSocket::OnTimeout() { return; }
464 void BufferedSocket::DoWrite()
466 if (state == I_CONNECTING)
471 GetIOHook()->OnStreamSocketConnect(this);
473 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
475 this->StreamSocket::DoWrite();
478 BufferedSocket::~BufferedSocket()
483 // The timer is removed from the TimerManager in Timer::~Timer()
488 void StreamSocket::HandleEvent(EventType et, int errornum)
492 BufferedSocketError errcode = I_ERR_OTHER;
499 SetError("Connection closed");
501 SetError(SocketEngine::GetError(errornum));
505 errcode = I_ERR_TIMEOUT;
509 errcode = I_ERR_CONNECT;
512 errcode = I_ERR_BIND;
516 errcode = I_ERR_WRITE;
533 catch (CoreException& ex)
535 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
536 fd, ex.GetReason().c_str());
537 SetError(ex.GetReason());
541 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());