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());
140 ServerInstance->SE->Shutdown(this, 2);
141 ServerInstance->SE->DelFd(this);
142 ServerInstance->SE->Close(this);
147 CullResult StreamSocket::cull()
150 return EventHandler::cull();
153 bool StreamSocket::GetNextLine(std::string& line, char delim)
155 std::string::size_type i = recvq.find(delim);
156 if (i == std::string::npos)
158 line = recvq.substr(0, i);
159 // TODO is this the most efficient way to split?
160 recvq = recvq.substr(i + 1);
164 void StreamSocket::DoRead()
171 rv = GetIOHook()->OnStreamSocketRead(this, recvq);
173 catch (CoreException& modexcept)
175 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
176 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
182 SetError("Read Error"); // will not overwrite a better error message
186 char* ReadBuffer = ServerInstance->GetReadBuffer();
187 int n = ServerInstance->SE->Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
188 if (n == ServerInstance->Config->NetBufferSize)
190 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
191 recvq.append(ReadBuffer, n);
196 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
197 recvq.append(ReadBuffer, n);
202 error = "Connection closed";
203 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
205 else if (SocketEngine::IgnoreError())
207 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
209 else if (errno == EINTR)
211 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
215 error = SocketEngine::LastError();
216 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
221 /* Don't try to prepare huge blobs of data to send to a blocked socket */
222 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
224 void StreamSocket::DoWrite()
228 if (!error.empty() || fd < 0 || fd == INT_MAX)
230 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
234 #ifndef DISABLE_WRITEV
241 while (error.empty() && !sendq.empty())
243 if (sendq.size() > 1 && sendq[0].length() < 1024)
245 // Avoid multiple repeated SSL encryption invocations
246 // This adds a single copy of the queue, but avoids
247 // much more overhead in terms of system calls invoked
250 // The length limit of 1024 is to prevent merging strings
251 // more than once when writes begin to block.
254 while (!sendq.empty() && tmp.length() < 1024)
256 tmp.append(sendq.front());
259 sendq.push_front(tmp);
261 std::string& front = sendq.front();
262 int itemlen = front.length();
265 rv = GetIOHook()->OnStreamSocketWrite(this, front);
268 // consumed the entire string, and is ready for more
269 sendq_len -= itemlen;
274 // socket has blocked. Stop trying to send data.
275 // IOHook has requested unblock notification from the socketengine
277 // Since it is possible that a partial write took place, adjust sendq_len
278 sendq_len = sendq_len - itemlen + front.length();
283 SetError("Write Error"); // will not overwrite a better error message
287 #ifdef DISABLE_WRITEV
290 rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
293 SetError("Connection closed");
298 if (errno == EINTR || SocketEngine::IgnoreError())
299 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
301 SetError(SocketEngine::LastError());
304 else if (rv < itemlen)
306 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
307 front = front.substr(rv);
313 sendq_len -= itemlen;
316 ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
322 catch (CoreException& modexcept)
324 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "%s threw an exception: %s",
325 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
328 #ifndef DISABLE_WRITEV
331 // don't even try if we are known to be blocking
332 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
334 // start out optimistic - we won't need to write any more
335 int eventChange = FD_WANT_EDGE_WRITE;
336 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
338 // Prepare a writev() call to write all buffers efficiently
339 int bufcount = sendq.size();
341 // cap the number of buffers at MYIOV_MAX
342 if (bufcount > MYIOV_MAX)
344 bufcount = MYIOV_MAX;
348 iovec* iovecs = new iovec[bufcount];
349 for(int i=0; i < bufcount; i++)
351 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
352 iovecs[i].iov_len = sendq[i].length();
353 rv_max += sendq[i].length();
355 int rv = writev(fd, iovecs, bufcount);
358 if (rv == (int)sendq_len)
360 // it's our lucky day, everything got written out. Fast cleanup.
361 // This won't ever happen if the number of buffers got capped.
367 // Partial write. Clean out strings from the sendq
370 // it's going to block now
371 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
374 while (rv > 0 && !sendq.empty())
376 std::string& front = sendq.front();
377 if (front.length() <= (size_t)rv)
379 // this string got fully written out
380 rv -= front.length();
385 // stopped in the middle of this string
386 front = front.substr(rv);
393 error = "Connection closed";
395 else if (SocketEngine::IgnoreError())
397 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
399 else if (errno == EINTR)
401 // restart interrupted syscall
406 error = SocketEngine::LastError();
411 // error - kill all events
412 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
416 ServerInstance->SE->ChangeEventMask(this, eventChange);
422 void StreamSocket::WriteData(const std::string &data)
426 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
431 /* Append the data to the back of the queue ready for writing */
432 sendq.push_back(data);
433 sendq_len += data.length();
435 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
438 bool SocketTimeout::Tick(time_t)
440 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
442 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
445 if (this->sock->state == I_CONNECTING)
447 // for connecting sockets, the timeout can occur
448 // which causes termination of the connection after
449 // the given number of seconds without a successful
451 this->sock->OnTimeout();
452 this->sock->OnError(I_ERR_TIMEOUT);
453 this->sock->state = I_ERROR;
455 ServerInstance->GlobalCulls.AddItem(sock);
458 this->sock->Timeout = NULL;
462 void BufferedSocket::OnConnected() { }
463 void BufferedSocket::OnTimeout() { return; }
465 void BufferedSocket::DoWrite()
467 if (state == I_CONNECTING)
472 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
474 this->StreamSocket::DoWrite();
477 BufferedSocket::~BufferedSocket()
482 // The timer is removed from the TimerManager in Timer::~Timer()
487 void StreamSocket::HandleEvent(EventType et, int errornum)
491 BufferedSocketError errcode = I_ERR_OTHER;
498 SetError("Connection closed");
500 SetError(SocketEngine::GetError(errornum));
504 errcode = I_ERR_TIMEOUT;
508 errcode = I_ERR_CONNECT;
511 errcode = I_ERR_BIND;
515 errcode = I_ERR_WRITE;
532 catch (CoreException& ex)
534 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
535 fd, ex.GetReason().c_str());
536 SetError(ex.GetReason());
540 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());