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 SocketEngine::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 (SocketEngine::Bind(fd, bind) < 0)
100 SocketEngine::NonBlocking(fd);
102 if (SocketEngine::Connect(this, &dest.sa, dest.sa_size()) == -1)
104 if (errno != EINPROGRESS)
105 return I_ERR_CONNECT;
108 this->state = I_CONNECTING;
110 if (!SocketEngine::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 SocketEngine::Shutdown(this, 2);
141 SocketEngine::Close(this);
145 CullResult StreamSocket::cull()
148 return EventHandler::cull();
151 bool StreamSocket::GetNextLine(std::string& line, char delim)
153 std::string::size_type i = recvq.find(delim);
154 if (i == std::string::npos)
156 line = recvq.substr(0, i);
157 // TODO is this the most efficient way to split?
158 recvq = recvq.substr(i + 1);
162 void StreamSocket::DoRead()
169 rv = GetIOHook()->OnStreamSocketRead(this, recvq);
171 catch (CoreException& modexcept)
173 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
174 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
180 SetError("Read Error"); // will not overwrite a better error message
184 char* ReadBuffer = ServerInstance->GetReadBuffer();
185 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
186 if (n == ServerInstance->Config->NetBufferSize)
188 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
189 recvq.append(ReadBuffer, n);
194 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
195 recvq.append(ReadBuffer, n);
200 error = "Connection closed";
201 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
203 else if (SocketEngine::IgnoreError())
205 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
207 else if (errno == EINTR)
209 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
213 error = SocketEngine::LastError();
214 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
219 /* Don't try to prepare huge blobs of data to send to a blocked socket */
220 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
222 void StreamSocket::DoWrite()
226 if (!error.empty() || fd < 0 || fd == INT_MAX)
228 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
232 #ifndef DISABLE_WRITEV
239 while (error.empty() && !sendq.empty())
241 if (sendq.size() > 1 && sendq[0].length() < 1024)
243 // Avoid multiple repeated SSL encryption invocations
244 // This adds a single copy of the queue, but avoids
245 // much more overhead in terms of system calls invoked
248 // The length limit of 1024 is to prevent merging strings
249 // more than once when writes begin to block.
252 while (!sendq.empty() && tmp.length() < 1024)
254 tmp.append(sendq.front());
257 sendq.push_front(tmp);
259 std::string& front = sendq.front();
260 int itemlen = front.length();
263 rv = GetIOHook()->OnStreamSocketWrite(this, front);
266 // consumed the entire string, and is ready for more
267 sendq_len -= itemlen;
272 // socket has blocked. Stop trying to send data.
273 // IOHook has requested unblock notification from the socketengine
275 // Since it is possible that a partial write took place, adjust sendq_len
276 sendq_len = sendq_len - itemlen + front.length();
281 SetError("Write Error"); // will not overwrite a better error message
285 #ifdef DISABLE_WRITEV
288 rv = SocketEngine::Send(this, front.data(), itemlen, 0);
291 SetError("Connection closed");
296 if (errno == EINTR || SocketEngine::IgnoreError())
297 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
299 SetError(SocketEngine::LastError());
302 else if (rv < itemlen)
304 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
305 front = front.substr(rv);
311 sendq_len -= itemlen;
314 SocketEngine::ChangeEventMask(this, FD_WANT_EDGE_WRITE);
320 catch (CoreException& modexcept)
322 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "%s threw an exception: %s",
323 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
326 #ifndef DISABLE_WRITEV
329 // don't even try if we are known to be blocking
330 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
332 // start out optimistic - we won't need to write any more
333 int eventChange = FD_WANT_EDGE_WRITE;
334 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
336 // Prepare a writev() call to write all buffers efficiently
337 int bufcount = sendq.size();
339 // cap the number of buffers at MYIOV_MAX
340 if (bufcount > MYIOV_MAX)
342 bufcount = MYIOV_MAX;
346 iovec* iovecs = new iovec[bufcount];
347 for(int i=0; i < bufcount; i++)
349 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
350 iovecs[i].iov_len = sendq[i].length();
351 rv_max += sendq[i].length();
353 int rv = writev(fd, iovecs, bufcount);
356 if (rv == (int)sendq_len)
358 // it's our lucky day, everything got written out. Fast cleanup.
359 // This won't ever happen if the number of buffers got capped.
365 // Partial write. Clean out strings from the sendq
368 // it's going to block now
369 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
372 while (rv > 0 && !sendq.empty())
374 std::string& front = sendq.front();
375 if (front.length() <= (size_t)rv)
377 // this string got fully written out
378 rv -= front.length();
383 // stopped in the middle of this string
384 front = front.substr(rv);
391 error = "Connection closed";
393 else if (SocketEngine::IgnoreError())
395 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
397 else if (errno == EINTR)
399 // restart interrupted syscall
404 error = SocketEngine::LastError();
409 // error - kill all events
410 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
414 SocketEngine::ChangeEventMask(this, eventChange);
420 void StreamSocket::WriteData(const std::string &data)
424 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
429 /* Append the data to the back of the queue ready for writing */
430 sendq.push_back(data);
431 sendq_len += data.length();
433 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
436 bool SocketTimeout::Tick(time_t)
438 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
440 if (SocketEngine::GetRef(this->sfd) != this->sock)
446 if (this->sock->state == I_CONNECTING)
448 // for connecting sockets, the timeout can occur
449 // which causes termination of the connection after
450 // the given number of seconds without a successful
452 this->sock->OnTimeout();
453 this->sock->OnError(I_ERR_TIMEOUT);
454 this->sock->state = I_ERROR;
456 ServerInstance->GlobalCulls.AddItem(sock);
459 this->sock->Timeout = NULL;
464 void BufferedSocket::OnConnected() { }
465 void BufferedSocket::OnTimeout() { return; }
467 void BufferedSocket::DoWrite()
469 if (state == I_CONNECTING)
474 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
476 this->StreamSocket::DoWrite();
479 BufferedSocket::~BufferedSocket()
484 // The timer is removed from the TimerManager in Timer::~Timer()
489 void StreamSocket::HandleEvent(EventType et, int errornum)
493 BufferedSocketError errcode = I_ERR_OTHER;
500 SetError("Connection closed");
502 SetError(SocketEngine::GetError(errornum));
506 errcode = I_ERR_TIMEOUT;
510 errcode = I_ERR_CONNECT;
513 errcode = I_ERR_BIND;
517 errcode = I_ERR_WRITE;
534 catch (CoreException& ex)
536 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
537 fd, ex.GetReason().c_str());
538 SetError(ex.GetReason());
542 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());