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, ServerInstance->Time());
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 = recvq.substr(0, i);
154 // TODO is this the most efficient way to split?
155 recvq = recvq.substr(i + 1);
159 void StreamSocket::DoRead()
166 rv = GetIOHook()->OnStreamSocketRead(this, recvq);
168 catch (CoreException& modexcept)
170 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
171 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
177 SetError("Read Error"); // will not overwrite a better error message
181 char* ReadBuffer = ServerInstance->GetReadBuffer();
182 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
183 if (n == ServerInstance->Config->NetBufferSize)
185 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
186 recvq.append(ReadBuffer, n);
191 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
192 recvq.append(ReadBuffer, n);
197 error = "Connection closed";
198 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
200 else if (SocketEngine::IgnoreError())
202 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
204 else if (errno == EINTR)
206 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
210 error = SocketEngine::LastError();
211 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
216 /* Don't try to prepare huge blobs of data to send to a blocked socket */
217 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
219 void StreamSocket::DoWrite()
223 if (!error.empty() || fd < 0 || fd == INT_MAX)
225 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
229 #ifndef DISABLE_WRITEV
236 while (error.empty() && !sendq.empty())
238 if (sendq.size() > 1 && sendq[0].length() < 1024)
240 // Avoid multiple repeated SSL encryption invocations
241 // This adds a single copy of the queue, but avoids
242 // much more overhead in terms of system calls invoked
245 // The length limit of 1024 is to prevent merging strings
246 // more than once when writes begin to block.
249 while (!sendq.empty() && tmp.length() < 1024)
251 tmp.append(sendq.front());
254 sendq.push_front(tmp);
256 std::string& front = sendq.front();
257 int itemlen = front.length();
260 rv = GetIOHook()->OnStreamSocketWrite(this, front);
263 // consumed the entire string, and is ready for more
264 sendq_len -= itemlen;
269 // socket has blocked. Stop trying to send data.
270 // IOHook has requested unblock notification from the socketengine
272 // Since it is possible that a partial write took place, adjust sendq_len
273 sendq_len = sendq_len - itemlen + front.length();
278 SetError("Write Error"); // will not overwrite a better error message
282 #ifdef DISABLE_WRITEV
285 rv = SocketEngine::Send(this, front.data(), itemlen, 0);
288 SetError("Connection closed");
293 if (errno == EINTR || SocketEngine::IgnoreError())
294 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
296 SetError(SocketEngine::LastError());
299 else if (rv < itemlen)
301 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
302 front = front.substr(rv);
308 sendq_len -= itemlen;
311 SocketEngine::ChangeEventMask(this, FD_WANT_EDGE_WRITE);
317 catch (CoreException& modexcept)
319 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "%s threw an exception: %s",
320 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
323 #ifndef DISABLE_WRITEV
326 // don't even try if we are known to be blocking
327 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
329 // start out optimistic - we won't need to write any more
330 int eventChange = FD_WANT_EDGE_WRITE;
331 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
333 // Prepare a writev() call to write all buffers efficiently
334 int bufcount = sendq.size();
336 // cap the number of buffers at MYIOV_MAX
337 if (bufcount > MYIOV_MAX)
339 bufcount = MYIOV_MAX;
343 iovec* iovecs = new iovec[bufcount];
344 for(int i=0; i < bufcount; i++)
346 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
347 iovecs[i].iov_len = sendq[i].length();
348 rv_max += sendq[i].length();
350 int rv = writev(fd, iovecs, bufcount);
353 if (rv == (int)sendq_len)
355 // it's our lucky day, everything got written out. Fast cleanup.
356 // This won't ever happen if the number of buffers got capped.
362 // Partial write. Clean out strings from the sendq
365 // it's going to block now
366 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
369 while (rv > 0 && !sendq.empty())
371 std::string& front = sendq.front();
372 if (front.length() <= (size_t)rv)
374 // this string got fully written out
375 rv -= front.length();
380 // stopped in the middle of this string
381 front = front.substr(rv);
388 error = "Connection closed";
390 else if (SocketEngine::IgnoreError())
392 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
394 else if (errno == EINTR)
396 // restart interrupted syscall
401 error = SocketEngine::LastError();
406 // error - kill all events
407 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
411 SocketEngine::ChangeEventMask(this, eventChange);
417 void StreamSocket::WriteData(const std::string &data)
421 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
426 /* Append the data to the back of the queue ready for writing */
427 sendq.push_back(data);
428 sendq_len += data.length();
430 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
433 bool SocketTimeout::Tick(time_t)
435 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
437 if (SocketEngine::GetRef(this->sfd) != this->sock)
443 if (this->sock->state == I_CONNECTING)
445 // for connecting sockets, the timeout can occur
446 // which causes termination of the connection after
447 // the given number of seconds without a successful
449 this->sock->OnTimeout();
450 this->sock->OnError(I_ERR_TIMEOUT);
451 this->sock->state = I_ERROR;
453 ServerInstance->GlobalCulls.AddItem(sock);
456 this->sock->Timeout = NULL;
461 void BufferedSocket::OnConnected() { }
462 void BufferedSocket::OnTimeout() { return; }
464 void BufferedSocket::DoWrite()
466 if (state == I_CONNECTING)
471 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
473 this->StreamSocket::DoWrite();
476 BufferedSocket::~BufferedSocket()
481 // The timer is removed from the TimerManager in Timer::~Timer()
486 void StreamSocket::HandleEvent(EventType et, int errornum)
490 BufferedSocketError errcode = I_ERR_OTHER;
497 SetError("Connection closed");
499 SetError(SocketEngine::GetError(errornum));
503 errcode = I_ERR_TIMEOUT;
507 errcode = I_ERR_CONNECT;
510 errcode = I_ERR_BIND;
514 errcode = I_ERR_WRITE;
531 catch (CoreException& ex)
533 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
534 fd, ex.GetReason().c_str());
535 SetError(ex.GetReason());
539 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());