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"
30 #ifndef DISABLE_WRITEV
38 BufferedSocket::BufferedSocket()
44 BufferedSocket::BufferedSocket(int newfd)
48 this->state = I_CONNECTED;
50 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
53 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
55 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
56 if (err != I_ERR_NONE)
59 SetError(strerror(errno));
64 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
66 irc::sockets::sockaddrs addr, bind;
67 if (!irc::sockets::aptosa(ipaddr, aport, addr))
69 ServerInstance->Logs->Log("SOCKET", DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
73 bind.sa.sa_family = 0;
74 if (!connectbindip.empty())
76 if (!irc::sockets::aptosa(connectbindip, 0, bind))
82 return BeginConnect(addr, bind, maxtime);
85 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
88 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
93 if (bind.sa.sa_family != 0)
95 if (ServerInstance->SE->Bind(fd, bind) < 0)
99 ServerInstance->SE->NonBlocking(fd);
101 if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
103 if (errno != EINPROGRESS)
104 return I_ERR_CONNECT;
107 this->state = I_CONNECTING;
109 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
110 return I_ERR_NOMOREFDS;
112 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
113 ServerInstance->Timers->AddTimer(this->Timeout);
115 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
119 void StreamSocket::Close()
123 // final chance, dump as much of the sendq as we can
129 IOHook->OnStreamSocketClose(this);
131 catch (CoreException& modexcept)
133 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
134 modexcept.GetSource(), modexcept.GetReason());
138 ServerInstance->SE->Shutdown(this, 2);
139 ServerInstance->SE->DelFd(this);
140 ServerInstance->SE->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 = IOHook->OnStreamSocketRead(this, recvq);
171 catch (CoreException& modexcept)
173 ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
174 modexcept.GetSource(), modexcept.GetReason());
180 SetError("Read Error"); // will not overwrite a better error message
184 char* ReadBuffer = ServerInstance->GetReadBuffer();
185 int n = ServerInstance->SE->Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
186 if (n == ServerInstance->Config->NetBufferSize)
188 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
189 recvq.append(ReadBuffer, n);
194 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
195 recvq.append(ReadBuffer, n);
200 error = "Connection closed";
201 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
203 else if (errno == EAGAIN)
205 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
207 else if (errno == EINTR)
209 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
213 error = strerror(errno);
214 ServerInstance->SE->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", 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.
251 tmp.reserve(sendq_len);
252 for(unsigned int i=0; i < sendq.size(); i++)
253 tmp.append(sendq[i]);
255 sendq.push_back(tmp);
257 std::string& front = sendq.front();
258 int itemlen = front.length();
261 rv = IOHook->OnStreamSocketWrite(this, front);
264 // consumed the entire string, and is ready for more
265 sendq_len -= itemlen;
270 // socket has blocked. Stop trying to send data.
271 // IOHook has requested unblock notification from the socketengine
273 // Since it is possible that a partial write took place, adjust sendq_len
274 sendq_len = sendq_len - itemlen + front.length();
279 SetError("Write Error"); // will not overwrite a better error message
283 #ifdef DISABLE_WRITEV
286 rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
289 SetError("Connection closed");
294 if (errno == EAGAIN || errno == EINTR)
295 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
297 SetError(strerror(errno));
300 else if (rv < itemlen)
302 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
303 front = front.substr(rv);
309 sendq_len -= itemlen;
312 ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
318 catch (CoreException& modexcept)
320 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
321 modexcept.GetSource(), modexcept.GetReason());
324 #ifndef DISABLE_WRITEV
327 // don't even try if we are known to be blocking
328 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
330 // start out optimistic - we won't need to write any more
331 int eventChange = FD_WANT_EDGE_WRITE;
332 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
334 // Prepare a writev() call to write all buffers efficiently
335 int bufcount = sendq.size();
337 // cap the number of buffers at MYIOV_MAX
338 if (bufcount > MYIOV_MAX)
340 bufcount = MYIOV_MAX;
344 iovec* iovecs = new iovec[bufcount];
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 int 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
382 front = front.substr(rv);
389 error = "Connection closed";
391 else if (errno == EAGAIN)
393 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
395 else if (errno == EINTR)
397 // restart interrupted syscall
402 error = strerror(errno);
407 // error - kill all events
408 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
412 ServerInstance->SE->ChangeEventMask(this, eventChange);
418 void StreamSocket::WriteData(const std::string &data)
422 ServerInstance->Logs->Log("SOCKET", 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 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
434 void SocketTimeout::Tick(time_t)
436 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
438 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
441 if (this->sock->state == I_CONNECTING)
443 // for connecting sockets, the timeout can occur
444 // which causes termination of the connection after
445 // the given number of seconds without a successful
447 this->sock->OnTimeout();
448 this->sock->OnError(I_ERR_TIMEOUT);
449 this->sock->state = I_ERROR;
451 ServerInstance->GlobalCulls.AddItem(sock);
454 this->sock->Timeout = NULL;
457 void BufferedSocket::OnConnected() { }
458 void BufferedSocket::OnTimeout() { return; }
460 void BufferedSocket::DoWrite()
462 if (state == I_CONNECTING)
467 GetIOHook()->OnStreamSocketConnect(this);
469 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
471 this->StreamSocket::DoWrite();
474 BufferedSocket::~BufferedSocket()
479 ServerInstance->Timers->DelTimer(Timeout);
484 void StreamSocket::HandleEvent(EventType et, int errornum)
488 BufferedSocketError errcode = I_ERR_OTHER;
495 SetError("Connection closed");
497 SetError(strerror(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", DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
533 SetError(ex.GetReason());
537 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());