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/>.
28 #ifndef DISABLE_WRITEV
36 BufferedSocket::BufferedSocket()
42 BufferedSocket::BufferedSocket(int newfd)
46 this->state = I_CONNECTED;
48 SocketEngine::AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
51 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
53 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
54 if (err != I_ERR_NONE)
57 SetError(SocketEngine::LastError());
62 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
64 irc::sockets::sockaddrs addr, bind;
65 if (!irc::sockets::aptosa(ipaddr, aport, addr))
67 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
71 bind.sa.sa_family = 0;
72 if (!connectbindip.empty())
74 if (!irc::sockets::aptosa(connectbindip, 0, bind))
80 return BeginConnect(addr, bind, maxtime);
83 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
86 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
91 if (bind.sa.sa_family != 0)
93 if (SocketEngine::Bind(fd, bind) < 0)
97 SocketEngine::NonBlocking(fd);
99 if (SocketEngine::Connect(this, &dest.sa, dest.sa_size()) == -1)
101 if (errno != EINPROGRESS)
102 return I_ERR_CONNECT;
105 this->state = I_CONNECTING;
107 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
108 return I_ERR_NOMOREFDS;
110 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
111 ServerInstance->Timers.AddTimer(this->Timeout);
113 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
117 void StreamSocket::Close()
121 // final chance, dump as much of the sendq as we can
127 GetIOHook()->OnStreamSocketClose(this);
129 catch (CoreException& modexcept)
131 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
132 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
137 SocketEngine::Shutdown(this, 2);
138 SocketEngine::Close(this);
142 CullResult StreamSocket::cull()
145 return EventHandler::cull();
148 bool StreamSocket::GetNextLine(std::string& line, char delim)
150 std::string::size_type i = recvq.find(delim);
151 if (i == std::string::npos)
153 line.assign(recvq, 0, i);
154 recvq.erase(0, i + 1);
158 void StreamSocket::DoRead()
165 rv = GetIOHook()->OnStreamSocketRead(this, recvq);
167 catch (CoreException& modexcept)
169 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
170 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
176 SetError("Read Error"); // will not overwrite a better error message
180 char* ReadBuffer = ServerInstance->GetReadBuffer();
181 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
182 if (n == ServerInstance->Config->NetBufferSize)
184 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
185 recvq.append(ReadBuffer, n);
190 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
191 recvq.append(ReadBuffer, n);
196 error = "Connection closed";
197 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
199 else if (SocketEngine::IgnoreError())
201 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
203 else if (errno == EINTR)
205 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
209 error = SocketEngine::LastError();
210 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
215 /* Don't try to prepare huge blobs of data to send to a blocked socket */
216 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
218 void StreamSocket::DoWrite()
222 if (!error.empty() || fd < 0)
224 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
228 #ifndef DISABLE_WRITEV
235 while (error.empty() && !sendq.empty())
237 if (sendq.size() > 1 && sendq[0].length() < 1024)
239 // Avoid multiple repeated SSL encryption invocations
240 // This adds a single copy of the queue, but avoids
241 // much more overhead in terms of system calls invoked
244 // The length limit of 1024 is to prevent merging strings
245 // more than once when writes begin to block.
248 while (!sendq.empty() && tmp.length() < 1024)
250 tmp.append(sendq.front());
253 sendq.push_front(tmp);
255 std::string& front = sendq.front();
256 int itemlen = front.length();
259 rv = GetIOHook()->OnStreamSocketWrite(this, front);
262 // consumed the entire string, and is ready for more
263 sendq_len -= itemlen;
268 // socket has blocked. Stop trying to send data.
269 // IOHook has requested unblock notification from the socketengine
271 // Since it is possible that a partial write took place, adjust sendq_len
272 sendq_len = sendq_len - itemlen + front.length();
277 SetError("Write Error"); // will not overwrite a better error message
281 #ifdef DISABLE_WRITEV
284 rv = SocketEngine::Send(this, front.data(), itemlen, 0);
287 SetError("Connection closed");
292 if (errno == EINTR || SocketEngine::IgnoreError())
293 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
295 SetError(SocketEngine::LastError());
298 else if (rv < itemlen)
300 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
307 sendq_len -= itemlen;
310 SocketEngine::ChangeEventMask(this, FD_WANT_EDGE_WRITE);
316 catch (CoreException& modexcept)
318 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "%s threw an exception: %s",
319 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
322 #ifndef DISABLE_WRITEV
325 // don't even try if we are known to be blocking
326 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
328 // start out optimistic - we won't need to write any more
329 int eventChange = FD_WANT_EDGE_WRITE;
330 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
332 // Prepare a writev() call to write all buffers efficiently
333 int bufcount = sendq.size();
335 // cap the number of buffers at MYIOV_MAX
336 if (bufcount > MYIOV_MAX)
338 bufcount = MYIOV_MAX;
344 iovec iovecs[MYIOV_MAX];
345 for (int i = 0; i < bufcount; i++)
347 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
348 iovecs[i].iov_len = sendq[i].length();
349 rv_max += sendq[i].length();
351 rv = writev(fd, iovecs, bufcount);
354 if (rv == (int)sendq_len)
356 // it's our lucky day, everything got written out. Fast cleanup.
357 // This won't ever happen if the number of buffers got capped.
363 // Partial write. Clean out strings from the sendq
366 // it's going to block now
367 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
370 while (rv > 0 && !sendq.empty())
372 std::string& front = sendq.front();
373 if (front.length() <= (size_t)rv)
375 // this string got fully written out
376 rv -= front.length();
381 // stopped in the middle of this string
389 error = "Connection closed";
391 else if (SocketEngine::IgnoreError())
393 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
395 else if (errno == EINTR)
397 // restart interrupted syscall
402 error = SocketEngine::LastError();
407 // error - kill all events
408 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
412 SocketEngine::ChangeEventMask(this, eventChange);
418 void StreamSocket::WriteData(const std::string &data)
422 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
427 /* Append the data to the back of the queue ready for writing */
428 sendq.push_back(data);
429 sendq_len += data.length();
431 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
434 bool SocketTimeout::Tick(time_t)
436 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
438 if (SocketEngine::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;
462 void BufferedSocket::OnConnected() { }
463 void BufferedSocket::OnTimeout() { return; }
465 void BufferedSocket::DoWrite()
467 if (state == I_CONNECTING)
472 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
474 this->StreamSocket::DoWrite();
477 BufferedSocket::~BufferedSocket()
480 // The timer is removed from the TimerManager in Timer::~Timer()
484 void StreamSocket::HandleEvent(EventType et, int errornum)
488 BufferedSocketError errcode = I_ERR_OTHER;
495 SetError("Connection closed");
497 SetError(SocketEngine::GetError(errornum));
501 errcode = I_ERR_TIMEOUT;
505 errcode = I_ERR_CONNECT;
508 errcode = I_ERR_BIND;
512 errcode = I_ERR_WRITE;
529 catch (CoreException& ex)
531 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
532 fd, ex.GetReason().c_str());
533 SetError(ex.GetReason());
537 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());