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
26 BufferedSocket::BufferedSocket()
32 BufferedSocket::BufferedSocket(int newfd)
36 this->state = I_CONNECTED;
38 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
41 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
43 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
44 if (err != I_ERR_NONE)
47 SetError(strerror(errno));
52 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
54 irc::sockets::sockaddrs addr, bind;
55 if (!irc::sockets::aptosa(ipaddr, aport, addr))
57 ServerInstance->Logs->Log("SOCKET", DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
61 bind.sa.sa_family = 0;
62 if (!connectbindip.empty())
64 if (!irc::sockets::aptosa(connectbindip, 0, bind))
70 return BeginConnect(addr, bind, maxtime);
73 static void IncreaseOSBuffers(int fd)
75 // attempt to increase socket sendq and recvq as high as its possible
78 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
79 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(recvbuf));
80 // 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.
83 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
86 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
91 if (bind.sa.sa_family != 0)
93 if (ServerInstance->SE->Bind(fd, bind) < 0)
97 ServerInstance->SE->NonBlocking(fd);
99 if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
101 if (errno != EINPROGRESS)
102 return I_ERR_CONNECT;
105 this->state = I_CONNECTING;
107 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE))
108 return I_ERR_NOMOREFDS;
110 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
111 ServerInstance->Timers->AddTimer(this->Timeout);
113 IncreaseOSBuffers(fd);
115 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
119 void StreamSocket::Close()
127 IOHook->OnStreamSocketClose(this);
129 catch (CoreException& modexcept)
131 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
132 modexcept.GetSource(), modexcept.GetReason());
135 ServerInstance->SE->Shutdown(this, 2);
136 ServerInstance->SE->DelFd(this);
137 ServerInstance->SE->Close(this);
142 CullResult StreamSocket::cull()
145 return EventHandler::cull();
148 bool StreamSocket::GetNextLine(std::string& line, char delim)
150 std::string::size_type i = recvq.find(delim);
151 if (i == std::string::npos)
153 line = recvq.substr(0, i);
154 // TODO is this the most efficient way to split?
155 recvq = recvq.substr(i + 1);
159 void StreamSocket::DoRead()
166 rv = IOHook->OnStreamSocketRead(this, recvq);
168 catch (CoreException& modexcept)
170 ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
171 modexcept.GetSource(), modexcept.GetReason());
177 SetError("Read Error"); // will not overwrite a better error message
181 char* ReadBuffer = ServerInstance->GetReadBuffer();
182 int n = recv(fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
183 if (n == ServerInstance->Config->NetBufferSize)
185 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
186 recvq.append(ReadBuffer, n);
191 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
192 recvq.append(ReadBuffer, n);
197 error = "Connection closed";
198 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
200 else if (errno == EAGAIN)
202 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
204 else if (errno == EINTR)
206 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
210 error = strerror(errno);
211 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
216 void StreamSocket::DoWrite()
220 if (!error.empty() || fd < 0 || fd == INT_MAX)
222 ServerInstance->Logs->Log("SOCKET", DEBUG, "DoWrite on errored or closed socket");
226 #ifndef DISABLE_WRITEV
233 while (!sendq.empty())
235 if (sendq.size() > 1 && sendq[0].length() < 1024)
237 // Avoid multiple repeated SSL encryption invocations
238 // This adds a single copy of the queue, but avoids
239 // much more overhead in terms of system calls invoked
242 // The length limit of 1024 is to prevent merging strings
243 // more than once when writes begin to block.
245 tmp.reserve(sendq_len);
246 for(unsigned int i=0; i < sendq.size(); i++)
247 tmp.append(sendq[i]);
249 sendq.push_back(tmp);
251 std::string& front = sendq.front();
252 int itemlen = front.length();
255 rv = IOHook->OnStreamSocketWrite(this, front);
258 // consumed the entire string, and is ready for more
259 sendq_len -= itemlen;
264 // socket has blocked. Stop trying to send data.
265 // IOHook has requested unblock notification from the socketengine
267 // Since it is possible that a partial write took place, adjust sendq_len
268 sendq_len = sendq_len - itemlen + front.length();
273 SetError("Write Error"); // will not overwrite a better error message
277 #ifdef DISABLE_WRITEV
280 rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
283 SetError("Connection closed");
288 if (errno == EAGAIN || errno == EINTR)
289 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
291 SetError(strerror(errno));
294 else if (rv < itemlen)
296 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
297 front = front.substr(itemlen - rv);
303 sendq_len -= itemlen;
306 ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
312 catch (CoreException& modexcept)
314 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
315 modexcept.GetSource(), modexcept.GetReason());
318 #ifndef DISABLE_WRITEV
321 // don't even try if we are known to be blocking
322 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
324 // start out optimistic - we won't need to write any more
325 int eventChange = FD_WANT_EDGE_WRITE;
326 while (sendq_len && eventChange == FD_WANT_EDGE_WRITE)
328 // Prepare a writev() call to write all buffers efficiently
329 int bufcount = sendq.size();
331 // cap the number of buffers at IOV_MAX
332 if (bufcount > IOV_MAX)
338 iovec* iovecs = new iovec[bufcount];
339 for(int i=0; i < bufcount; i++)
341 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
342 iovecs[i].iov_len = sendq[i].length();
343 rv_max += sendq[i].length();
345 int rv = writev(fd, iovecs, bufcount);
348 if (rv == (int)sendq_len)
350 // it's our lucky day, everything got written out. Fast cleanup.
351 // This won't ever happen if the number of buffers got capped.
357 // Partial write. Clean out strings from the sendq
360 // it's going to block now
361 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
364 while (rv > 0 && !sendq.empty())
366 std::string& front = sendq.front();
367 if (front.length() <= (size_t)rv)
369 // this string got fully written out
370 rv -= front.length();
375 // stopped in the middle of this string
376 front = front.substr(rv);
383 error = "Connection closed";
385 else if (errno == EAGAIN)
387 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
389 else if (errno == EINTR)
391 // restart interrupted syscall
396 error = strerror(errno);
401 // error - kill all events
402 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
406 ServerInstance->SE->ChangeEventMask(this, eventChange);
412 void StreamSocket::WriteData(const std::string &data)
416 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
421 /* Append the data to the back of the queue ready for writing */
422 sendq.push_back(data);
423 sendq_len += data.length();
425 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
428 void SocketTimeout::Tick(time_t)
430 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
432 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
435 if (this->sock->state == I_CONNECTING)
437 // for connecting sockets, the timeout can occur
438 // which causes termination of the connection after
439 // the given number of seconds without a successful
441 this->sock->OnTimeout();
442 this->sock->OnError(I_ERR_TIMEOUT);
444 /* NOTE: We must set this AFTER DelFd, as we added
445 * this socket whilst writeable. This means that we
446 * must DELETE the socket whilst writeable too!
448 this->sock->state = I_ERROR;
450 ServerInstance->GlobalCulls.AddItem(sock);
453 this->sock->Timeout = NULL;
456 void BufferedSocket::OnConnected() { }
457 void BufferedSocket::OnTimeout() { return; }
459 void BufferedSocket::DoWrite()
461 if (state == I_CONNECTING)
466 GetIOHook()->OnStreamSocketConnect(this);
468 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
470 this->StreamSocket::DoWrite();
473 BufferedSocket::~BufferedSocket()
478 ServerInstance->Timers->DelTimer(Timeout);
483 void StreamSocket::HandleEvent(EventType et, int errornum)
487 BufferedSocketError errcode = I_ERR_OTHER;
494 SetError("Connection closed");
496 SetError(strerror(errornum));
500 errcode = I_ERR_TIMEOUT;
504 errcode = I_ERR_CONNECT;
507 errcode = I_ERR_BIND;
511 errcode = I_ERR_WRITE;
528 catch (CoreException& ex)
530 ServerInstance->Logs->Log("SOCKET", DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
532 SetError(ex.GetReason());
536 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());