1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 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"
20 BufferedSocket::BufferedSocket()
26 BufferedSocket::BufferedSocket(int newfd)
30 this->state = I_CONNECTED;
32 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
35 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
37 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
38 if (err != I_ERR_NONE)
41 SetError(strerror(errno));
46 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
48 irc::sockets::sockaddrs addr, bind;
49 if (!irc::sockets::aptosa(ipaddr, aport, &addr))
51 ServerInstance->Logs->Log("SOCKET", DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
55 bind.sa.sa_family = 0;
56 if (!connectbindip.empty())
58 if (!irc::sockets::aptosa(connectbindip, 0, &bind))
64 return BeginConnect(addr, bind, maxtime);
67 static void IncreaseOSBuffers(int fd)
69 // attempt to increase socket sendq and recvq as high as its possible
72 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
73 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(recvbuf));
74 // 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.
77 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
80 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
85 if (bind.sa.sa_family != 0)
87 if (ServerInstance->SE->Bind(fd, &bind.sa, sa_size(bind)) < 0)
91 ServerInstance->SE->NonBlocking(fd);
93 if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
95 if (errno != EINPROGRESS)
99 this->state = I_CONNECTING;
101 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE))
102 return I_ERR_NOMOREFDS;
104 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
105 ServerInstance->Timers->AddTimer(this->Timeout);
107 IncreaseOSBuffers(fd);
109 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
113 void StreamSocket::Close()
115 /* Save this, so we dont lose it,
116 * otherise on failure, error messages
117 * might be inaccurate.
126 IOHook->OnStreamSocketClose(this);
128 catch (CoreException& modexcept)
130 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
131 modexcept.GetSource(), modexcept.GetReason());
134 ServerInstance->SE->Shutdown(this, 2);
135 ServerInstance->SE->DelFd(this);
136 ServerInstance->SE->Close(this);
142 bool StreamSocket::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 - 1);
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");
231 if (sendq.size() > 1 && sendq[0].length() < 1024)
233 // Avoid multiple repeated SSL encryption invocations
234 // This adds a single copy of the queue, but avoids
235 // much more overhead in terms of system calls invoked
238 // The length limit of 1024 is to prevent merging strings
239 // more than once when writes begin to block.
241 tmp.reserve(sendq_len);
242 for(unsigned int i=0; i < sendq.size(); i++)
243 tmp.append(sendq[i]);
245 sendq.push_back(tmp);
247 while (!sendq.empty())
249 std::string& front = sendq.front();
250 int itemlen = front.length();
251 rv = IOHook->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
274 catch (CoreException& modexcept)
276 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
277 modexcept.GetSource(), modexcept.GetReason());
282 // don't even try if we are known to be blocking
283 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
285 // start out optimistic - we won't need to write any more
286 int eventChange = FD_WANT_EDGE_WRITE;
287 while (sendq_len && eventChange == FD_WANT_EDGE_WRITE)
289 // Prepare a writev() call to write all buffers efficiently
290 int bufcount = sendq.size();
292 // cap the number of buffers at IOV_MAX
293 if (bufcount > IOV_MAX)
299 iovec* iovecs = new iovec[bufcount];
300 for(int i=0; i < bufcount; i++)
302 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
303 iovecs[i].iov_len = sendq[i].length();
304 rv_max += sendq[i].length();
306 int rv = writev(fd, iovecs, bufcount);
309 if (rv == (int)sendq_len)
311 // it's our lucky day, everything got written out. Fast cleanup.
312 // This won't ever happen if the number of buffers got capped.
318 // Partial write. Clean out strings from the sendq
320 while (rv > 0 && !sendq.empty())
322 std::string& front = sendq.front();
323 if (front.length() <= (size_t)rv)
325 // this string got fully written out
326 rv -= front.length();
331 // stopped in the middle of this string
332 front = front.substr(rv);
338 // it's going to block now
339 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
344 error = "Connection closed";
346 else if (errno == EAGAIN)
348 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
350 else if (errno == EINTR)
352 // restart interrupted syscall
356 error = strerror(errno);
361 // error - kill all events
362 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
366 ServerInstance->SE->ChangeEventMask(this, eventChange);
371 void StreamSocket::WriteData(const std::string &data)
375 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
380 /* Append the data to the back of the queue ready for writing */
381 sendq.push_back(data);
382 sendq_len += data.length();
384 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
387 void SocketTimeout::Tick(time_t)
389 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
391 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
394 if (this->sock->state == I_CONNECTING)
396 // for connecting sockets, the timeout can occur
397 // which causes termination of the connection after
398 // the given number of seconds without a successful
400 this->sock->OnTimeout();
401 this->sock->OnError(I_ERR_TIMEOUT);
403 /* NOTE: We must set this AFTER DelFd, as we added
404 * this socket whilst writeable. This means that we
405 * must DELETE the socket whilst writeable too!
407 this->sock->state = I_ERROR;
409 ServerInstance->GlobalCulls.AddItem(sock);
412 this->sock->Timeout = NULL;
415 void BufferedSocket::OnConnected() { }
416 void BufferedSocket::OnTimeout() { return; }
418 void BufferedSocket::DoWrite()
420 if (state == I_CONNECTING)
425 GetIOHook()->OnStreamSocketConnect(this);
427 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
429 this->StreamSocket::DoWrite();
432 BufferedSocket::~BufferedSocket()
437 ServerInstance->Timers->DelTimer(Timeout);
442 void StreamSocket::HandleEvent(EventType et, int errornum)
446 BufferedSocketError errcode = I_ERR_OTHER;
452 SetError("Connection closed");
454 SetError(strerror(errornum));
458 errcode = I_ERR_TIMEOUT;
462 errcode = I_ERR_CONNECT;
465 errcode = I_ERR_BIND;
469 errcode = I_ERR_WRITE;
487 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
489 ServerInstance->GlobalCulls.AddItem(this);