1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include "inspstring.h"
17 #include "socketengine.h"
19 #ifndef DISABLE_WRITEV
27 BufferedSocket::BufferedSocket()
33 BufferedSocket::BufferedSocket(int newfd)
37 this->state = I_CONNECTED;
39 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
42 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
44 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
45 if (err != I_ERR_NONE)
48 SetError(strerror(errno));
53 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
55 irc::sockets::sockaddrs addr, bind;
56 if (!irc::sockets::aptosa(ipaddr, aport, addr))
58 ServerInstance->Logs->Log("SOCKET", DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
62 bind.sa.sa_family = 0;
63 if (!connectbindip.empty())
65 if (!irc::sockets::aptosa(connectbindip, 0, bind))
71 return BeginConnect(addr, bind, maxtime);
74 static void IncreaseOSBuffers(int fd)
76 // attempt to increase socket sendq and recvq as high as its possible
79 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
80 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(recvbuf));
81 // 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.
84 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
87 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
92 if (bind.sa.sa_family != 0)
94 if (ServerInstance->SE->Bind(fd, bind) < 0)
98 ServerInstance->SE->NonBlocking(fd);
100 if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
102 if (errno != EINPROGRESS)
103 return I_ERR_CONNECT;
106 this->state = I_CONNECTING;
108 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
109 return I_ERR_NOMOREFDS;
111 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
112 ServerInstance->Timers->AddTimer(this->Timeout);
114 IncreaseOSBuffers(fd);
116 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
120 void StreamSocket::Close()
124 // final chance, dump as much of the sendq as we can
130 IOHook->OnStreamSocketClose(this);
132 catch (CoreException& modexcept)
134 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
135 modexcept.GetSource(), modexcept.GetReason());
139 ServerInstance->SE->Shutdown(this, 2);
140 ServerInstance->SE->DelFd(this);
141 ServerInstance->SE->Close(this);
146 CullResult StreamSocket::cull()
149 return EventHandler::cull();
152 bool StreamSocket::GetNextLine(std::string& line, char delim)
154 std::string::size_type i = recvq.find(delim);
155 if (i == std::string::npos)
157 line = recvq.substr(0, i);
158 // TODO is this the most efficient way to split?
159 recvq = recvq.substr(i + 1);
163 void StreamSocket::DoRead()
170 rv = IOHook->OnStreamSocketRead(this, recvq);
172 catch (CoreException& modexcept)
174 ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
175 modexcept.GetSource(), modexcept.GetReason());
181 SetError("Read Error"); // will not overwrite a better error message
185 char* ReadBuffer = ServerInstance->GetReadBuffer();
186 int n = recv(fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
187 if (n == ServerInstance->Config->NetBufferSize)
189 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
190 recvq.append(ReadBuffer, n);
195 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
196 recvq.append(ReadBuffer, n);
201 error = "Connection closed";
202 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
204 else if (errno == EAGAIN)
206 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
208 else if (errno == EINTR)
210 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
214 error = strerror(errno);
215 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
220 /* Don't try to prepare huge blobs of data to send to a blocked socket */
221 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
223 void StreamSocket::DoWrite()
227 if (!error.empty() || fd < 0 || fd == INT_MAX)
229 ServerInstance->Logs->Log("SOCKET", DEBUG, "DoWrite on errored or closed socket");
233 #ifndef DISABLE_WRITEV
240 while (error.empty() && !sendq.empty())
242 if (sendq.size() > 1 && sendq[0].length() < 1024)
244 // Avoid multiple repeated SSL encryption invocations
245 // This adds a single copy of the queue, but avoids
246 // much more overhead in terms of system calls invoked
249 // The length limit of 1024 is to prevent merging strings
250 // more than once when writes begin to block.
252 tmp.reserve(sendq_len);
253 for(unsigned int i=0; i < sendq.size(); i++)
254 tmp.append(sendq[i]);
256 sendq.push_back(tmp);
258 std::string& front = sendq.front();
259 int itemlen = front.length();
262 rv = IOHook->OnStreamSocketWrite(this, front);
265 // consumed the entire string, and is ready for more
266 sendq_len -= itemlen;
271 // socket has blocked. Stop trying to send data.
272 // IOHook has requested unblock notification from the socketengine
274 // Since it is possible that a partial write took place, adjust sendq_len
275 sendq_len = sendq_len - itemlen + front.length();
280 SetError("Write Error"); // will not overwrite a better error message
284 #ifdef DISABLE_WRITEV
287 rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
290 SetError("Connection closed");
295 if (errno == EAGAIN || errno == EINTR)
296 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
298 SetError(strerror(errno));
301 else if (rv < itemlen)
303 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
304 front = front.substr(itemlen - rv);
310 sendq_len -= itemlen;
313 ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
319 catch (CoreException& modexcept)
321 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
322 modexcept.GetSource(), modexcept.GetReason());
325 #ifndef DISABLE_WRITEV
328 // don't even try if we are known to be blocking
329 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
331 // start out optimistic - we won't need to write any more
332 int eventChange = FD_WANT_EDGE_WRITE;
333 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
335 // Prepare a writev() call to write all buffers efficiently
336 int bufcount = sendq.size();
338 // cap the number of buffers at MYIOV_MAX
339 if (bufcount > MYIOV_MAX)
341 bufcount = MYIOV_MAX;
345 iovec* iovecs = new iovec[bufcount];
346 for(int i=0; i < bufcount; i++)
348 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
349 iovecs[i].iov_len = sendq[i].length();
350 rv_max += sendq[i].length();
352 int rv = writev(fd, iovecs, bufcount);
355 if (rv == (int)sendq_len)
357 // it's our lucky day, everything got written out. Fast cleanup.
358 // This won't ever happen if the number of buffers got capped.
364 // Partial write. Clean out strings from the sendq
367 // it's going to block now
368 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
371 while (rv > 0 && !sendq.empty())
373 std::string& front = sendq.front();
374 if (front.length() <= (size_t)rv)
376 // this string got fully written out
377 rv -= front.length();
382 // stopped in the middle of this string
383 front = front.substr(rv);
390 error = "Connection closed";
392 else if (errno == EAGAIN)
394 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
396 else if (errno == EINTR)
398 // restart interrupted syscall
403 error = strerror(errno);
408 // error - kill all events
409 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
413 ServerInstance->SE->ChangeEventMask(this, eventChange);
419 void StreamSocket::WriteData(const std::string &data)
423 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
428 /* Append the data to the back of the queue ready for writing */
429 sendq.push_back(data);
430 sendq_len += data.length();
432 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
435 void SocketTimeout::Tick(time_t)
437 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
439 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
442 if (this->sock->state == I_CONNECTING)
444 // for connecting sockets, the timeout can occur
445 // which causes termination of the connection after
446 // the given number of seconds without a successful
448 this->sock->OnTimeout();
449 this->sock->OnError(I_ERR_TIMEOUT);
450 this->sock->state = I_ERROR;
452 ServerInstance->GlobalCulls.AddItem(sock);
455 this->sock->Timeout = NULL;
458 void BufferedSocket::OnConnected() { }
459 void BufferedSocket::OnTimeout() { return; }
461 void BufferedSocket::DoWrite()
463 if (state == I_CONNECTING)
468 GetIOHook()->OnStreamSocketConnect(this);
470 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
472 this->StreamSocket::DoWrite();
475 BufferedSocket::~BufferedSocket()
480 ServerInstance->Timers->DelTimer(Timeout);
485 void StreamSocket::HandleEvent(EventType et, int errornum)
489 BufferedSocketError errcode = I_ERR_OTHER;
496 SetError("Connection closed");
498 SetError(strerror(errornum));
502 errcode = I_ERR_TIMEOUT;
506 errcode = I_ERR_CONNECT;
509 errcode = I_ERR_BIND;
513 errcode = I_ERR_WRITE;
530 catch (CoreException& ex)
532 ServerInstance->Logs->Log("SOCKET", DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
534 SetError(ex.GetReason());
538 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());