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 BufferedSocket::BufferedSocket()
34 BufferedSocket::BufferedSocket(int newfd)
38 this->state = I_CONNECTED;
40 SocketEngine::AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
43 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
45 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
46 if (err != I_ERR_NONE)
49 SetError(SocketEngine::LastError());
54 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
56 irc::sockets::sockaddrs addr, bind;
57 if (!irc::sockets::aptosa(ipaddr, aport, addr))
59 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
63 bind.sa.sa_family = 0;
64 if (!connectbindip.empty())
66 if (!irc::sockets::aptosa(connectbindip, 0, bind))
72 return BeginConnect(addr, bind, maxtime);
75 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
78 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
83 if (bind.sa.sa_family != 0)
85 if (SocketEngine::Bind(fd, bind) < 0)
89 SocketEngine::NonBlocking(fd);
91 if (SocketEngine::Connect(this, &dest.sa, dest.sa_size()) == -1)
93 if (errno != EINPROGRESS)
97 this->state = I_CONNECTING;
99 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
100 return I_ERR_NOMOREFDS;
102 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
103 ServerInstance->Timers.AddTimer(this->Timeout);
105 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
109 void StreamSocket::Close()
113 // final chance, dump as much of the sendq as we can
119 GetIOHook()->OnStreamSocketClose(this);
121 catch (CoreException& modexcept)
123 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
124 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
129 SocketEngine::Shutdown(this, 2);
130 SocketEngine::Close(this);
134 CullResult StreamSocket::cull()
137 return EventHandler::cull();
140 bool StreamSocket::GetNextLine(std::string& line, char delim)
142 std::string::size_type i = recvq.find(delim);
143 if (i == std::string::npos)
145 line.assign(recvq, 0, i);
146 recvq.erase(0, i + 1);
150 void StreamSocket::DoRead()
157 rv = GetIOHook()->OnStreamSocketRead(this, recvq);
159 catch (CoreException& modexcept)
161 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
162 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
168 SetError("Read Error"); // will not overwrite a better error message
172 char* ReadBuffer = ServerInstance->GetReadBuffer();
173 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
174 if (n == ServerInstance->Config->NetBufferSize)
176 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
177 recvq.append(ReadBuffer, n);
182 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
183 recvq.append(ReadBuffer, n);
188 error = "Connection closed";
189 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
191 else if (SocketEngine::IgnoreError())
193 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
195 else if (errno == EINTR)
197 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
201 error = SocketEngine::LastError();
202 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
207 /* Don't try to prepare huge blobs of data to send to a blocked socket */
208 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
210 void StreamSocket::DoWrite()
214 if (!error.empty() || fd < 0)
216 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
220 #ifndef DISABLE_WRITEV
227 while (error.empty() && !sendq.empty())
229 if (sendq.size() > 1 && sendq[0].length() < 1024)
231 // Avoid multiple repeated SSL encryption invocations
232 // This adds a single copy of the queue, but avoids
233 // much more overhead in terms of system calls invoked
236 // The length limit of 1024 is to prevent merging strings
237 // more than once when writes begin to block.
240 while (!sendq.empty() && tmp.length() < 1024)
242 tmp.append(sendq.front());
245 sendq.push_front(tmp);
247 std::string& front = sendq.front();
248 int itemlen = front.length();
251 rv = GetIOHook()->OnStreamSocketWrite(this, front);
254 // consumed the entire string, and is ready for more
255 sendq_len -= itemlen;
260 // socket has blocked. Stop trying to send data.
261 // IOHook has requested unblock notification from the socketengine
263 // Since it is possible that a partial write took place, adjust sendq_len
264 sendq_len = sendq_len - itemlen + front.length();
269 SetError("Write Error"); // will not overwrite a better error message
273 #ifdef DISABLE_WRITEV
276 rv = SocketEngine::Send(this, front.data(), itemlen, 0);
279 SetError("Connection closed");
284 if (errno == EINTR || SocketEngine::IgnoreError())
285 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
287 SetError(SocketEngine::LastError());
290 else if (rv < itemlen)
292 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
299 sendq_len -= itemlen;
302 SocketEngine::ChangeEventMask(this, FD_WANT_EDGE_WRITE);
308 catch (CoreException& modexcept)
310 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "%s threw an exception: %s",
311 modexcept.GetSource().c_str(), modexcept.GetReason().c_str());
314 #ifndef DISABLE_WRITEV
317 // don't even try if we are known to be blocking
318 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
320 // start out optimistic - we won't need to write any more
321 int eventChange = FD_WANT_EDGE_WRITE;
322 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
324 // Prepare a writev() call to write all buffers efficiently
325 int bufcount = sendq.size();
327 // cap the number of buffers at MYIOV_MAX
328 if (bufcount > MYIOV_MAX)
330 bufcount = MYIOV_MAX;
336 iovec iovecs[MYIOV_MAX];
337 for (int i = 0; i < bufcount; i++)
339 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
340 iovecs[i].iov_len = sendq[i].length();
341 rv_max += sendq[i].length();
343 rv = SocketEngine::WriteV(this, iovecs, bufcount);
346 if (rv == (int)sendq_len)
348 // it's our lucky day, everything got written out. Fast cleanup.
349 // This won't ever happen if the number of buffers got capped.
355 // Partial write. Clean out strings from the sendq
358 // it's going to block now
359 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
362 while (rv > 0 && !sendq.empty())
364 std::string& front = sendq.front();
365 if (front.length() <= (size_t)rv)
367 // this string got fully written out
368 rv -= front.length();
373 // stopped in the middle of this string
381 error = "Connection closed";
383 else if (SocketEngine::IgnoreError())
385 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
387 else if (errno == EINTR)
389 // restart interrupted syscall
394 error = SocketEngine::LastError();
399 // error - kill all events
400 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
404 SocketEngine::ChangeEventMask(this, eventChange);
410 void StreamSocket::WriteData(const std::string &data)
414 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
419 /* Append the data to the back of the queue ready for writing */
420 sendq.push_back(data);
421 sendq_len += data.length();
423 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
426 bool SocketTimeout::Tick(time_t)
428 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
430 if (SocketEngine::GetRef(this->sfd) != this->sock)
436 if (this->sock->state == I_CONNECTING)
438 // for connecting sockets, the timeout can occur
439 // which causes termination of the connection after
440 // the given number of seconds without a successful
442 this->sock->OnTimeout();
443 this->sock->OnError(I_ERR_TIMEOUT);
444 this->sock->state = I_ERROR;
446 ServerInstance->GlobalCulls.AddItem(sock);
449 this->sock->Timeout = NULL;
454 void BufferedSocket::OnConnected() { }
455 void BufferedSocket::OnTimeout() { return; }
457 void BufferedSocket::DoWrite()
459 if (state == I_CONNECTING)
464 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
466 this->StreamSocket::DoWrite();
469 BufferedSocket::~BufferedSocket()
472 // The timer is removed from the TimerManager in Timer::~Timer()
476 void StreamSocket::HandleEvent(EventType et, int errornum)
480 BufferedSocketError errcode = I_ERR_OTHER;
487 SetError("Connection closed");
489 SetError(SocketEngine::GetError(errornum));
493 errcode = I_ERR_TIMEOUT;
497 errcode = I_ERR_CONNECT;
500 errcode = I_ERR_BIND;
504 errcode = I_ERR_WRITE;
521 catch (CoreException& ex)
523 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
524 fd, ex.GetReason().c_str());
525 SetError(ex.GetReason());
529 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());