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 static void IncreaseOSBuffers(int fd)
87 // attempt to increase socket sendq and recvq as high as its possible
90 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
91 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(recvbuf));
92 // on failure, do nothing. I'm a little sick of people trying to interpret this message as a result of why their incorrect setups don't work.
95 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
98 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
103 if (bind.sa.sa_family != 0)
105 if (ServerInstance->SE->Bind(fd, bind) < 0)
109 ServerInstance->SE->NonBlocking(fd);
111 if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
113 if (errno != EINPROGRESS)
114 return I_ERR_CONNECT;
117 this->state = I_CONNECTING;
119 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
120 return I_ERR_NOMOREFDS;
122 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
123 ServerInstance->Timers->AddTimer(this->Timeout);
125 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
129 void StreamSocket::Close()
133 // final chance, dump as much of the sendq as we can
139 IOHook->OnStreamSocketClose(this);
141 catch (CoreException& modexcept)
143 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
144 modexcept.GetSource(), modexcept.GetReason());
148 ServerInstance->SE->Shutdown(this, 2);
149 ServerInstance->SE->DelFd(this);
150 ServerInstance->SE->Close(this);
155 CullResult StreamSocket::cull()
158 return EventHandler::cull();
161 bool StreamSocket::GetNextLine(std::string& line, char delim)
163 std::string::size_type i = recvq.find(delim);
164 if (i == std::string::npos)
166 line = recvq.substr(0, i);
167 // TODO is this the most efficient way to split?
168 recvq = recvq.substr(i + 1);
172 void StreamSocket::DoRead()
179 rv = IOHook->OnStreamSocketRead(this, recvq);
181 catch (CoreException& modexcept)
183 ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
184 modexcept.GetSource(), modexcept.GetReason());
190 SetError("Read Error"); // will not overwrite a better error message
194 char* ReadBuffer = ServerInstance->GetReadBuffer();
195 int n = ServerInstance->SE->Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
196 if (n == ServerInstance->Config->NetBufferSize)
198 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
199 recvq.append(ReadBuffer, n);
204 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
205 recvq.append(ReadBuffer, n);
210 error = "Connection closed";
211 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
213 else if (errno == EAGAIN)
215 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
217 else if (errno == EINTR)
219 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
223 error = strerror(errno);
224 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
229 /* Don't try to prepare huge blobs of data to send to a blocked socket */
230 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
232 void StreamSocket::DoWrite()
236 if (!error.empty() || fd < 0 || fd == INT_MAX)
238 ServerInstance->Logs->Log("SOCKET", DEBUG, "DoWrite on errored or closed socket");
242 #ifndef DISABLE_WRITEV
249 while (error.empty() && !sendq.empty())
251 if (sendq.size() > 1 && sendq[0].length() < 1024)
253 // Avoid multiple repeated SSL encryption invocations
254 // This adds a single copy of the queue, but avoids
255 // much more overhead in terms of system calls invoked
258 // The length limit of 1024 is to prevent merging strings
259 // more than once when writes begin to block.
261 tmp.reserve(sendq_len);
262 for(unsigned int i=0; i < sendq.size(); i++)
263 tmp.append(sendq[i]);
265 sendq.push_back(tmp);
267 std::string& front = sendq.front();
268 int itemlen = front.length();
271 rv = IOHook->OnStreamSocketWrite(this, front);
274 // consumed the entire string, and is ready for more
275 sendq_len -= itemlen;
280 // socket has blocked. Stop trying to send data.
281 // IOHook has requested unblock notification from the socketengine
283 // Since it is possible that a partial write took place, adjust sendq_len
284 sendq_len = sendq_len - itemlen + front.length();
289 SetError("Write Error"); // will not overwrite a better error message
293 #ifdef DISABLE_WRITEV
296 rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
299 SetError("Connection closed");
304 if (errno == EAGAIN || errno == EINTR)
305 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
307 SetError(strerror(errno));
310 else if (rv < itemlen)
312 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
313 front = front.substr(itemlen - rv);
319 sendq_len -= itemlen;
322 ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
328 catch (CoreException& modexcept)
330 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
331 modexcept.GetSource(), modexcept.GetReason());
334 #ifndef DISABLE_WRITEV
337 // don't even try if we are known to be blocking
338 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
340 // start out optimistic - we won't need to write any more
341 int eventChange = FD_WANT_EDGE_WRITE;
342 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
344 // Prepare a writev() call to write all buffers efficiently
345 int bufcount = sendq.size();
347 // cap the number of buffers at MYIOV_MAX
348 if (bufcount > MYIOV_MAX)
350 bufcount = MYIOV_MAX;
354 iovec* iovecs = new iovec[bufcount];
355 for(int i=0; i < bufcount; i++)
357 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
358 iovecs[i].iov_len = sendq[i].length();
359 rv_max += sendq[i].length();
361 int rv = writev(fd, iovecs, bufcount);
364 if (rv == (int)sendq_len)
366 // it's our lucky day, everything got written out. Fast cleanup.
367 // This won't ever happen if the number of buffers got capped.
373 // Partial write. Clean out strings from the sendq
376 // it's going to block now
377 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
380 while (rv > 0 && !sendq.empty())
382 std::string& front = sendq.front();
383 if (front.length() <= (size_t)rv)
385 // this string got fully written out
386 rv -= front.length();
391 // stopped in the middle of this string
392 front = front.substr(rv);
399 error = "Connection closed";
401 else if (errno == EAGAIN)
403 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
405 else if (errno == EINTR)
407 // restart interrupted syscall
412 error = strerror(errno);
417 // error - kill all events
418 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
422 ServerInstance->SE->ChangeEventMask(this, eventChange);
428 void StreamSocket::WriteData(const std::string &data)
432 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
437 /* Append the data to the back of the queue ready for writing */
438 sendq.push_back(data);
439 sendq_len += data.length();
441 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
444 void SocketTimeout::Tick(time_t)
446 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
448 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
451 if (this->sock->state == I_CONNECTING)
453 // for connecting sockets, the timeout can occur
454 // which causes termination of the connection after
455 // the given number of seconds without a successful
457 this->sock->OnTimeout();
458 this->sock->OnError(I_ERR_TIMEOUT);
459 this->sock->state = I_ERROR;
461 ServerInstance->GlobalCulls.AddItem(sock);
464 this->sock->Timeout = NULL;
467 void BufferedSocket::OnConnected() { }
468 void BufferedSocket::OnTimeout() { return; }
470 void BufferedSocket::DoWrite()
472 if (state == I_CONNECTING)
477 GetIOHook()->OnStreamSocketConnect(this);
479 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
481 this->StreamSocket::DoWrite();
484 BufferedSocket::~BufferedSocket()
489 ServerInstance->Timers->DelTimer(Timeout);
494 void StreamSocket::HandleEvent(EventType et, int errornum)
498 BufferedSocketError errcode = I_ERR_OTHER;
505 SetError("Connection closed");
507 SetError(strerror(errornum));
511 errcode = I_ERR_TIMEOUT;
515 errcode = I_ERR_CONNECT;
518 errcode = I_ERR_BIND;
522 errcode = I_ERR_WRITE;
539 catch (CoreException& ex)
541 ServerInstance->Logs->Log("SOCKET", DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
543 SetError(ex.GetReason());
547 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());