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"
19 BufferedSocket::BufferedSocket()
25 BufferedSocket::BufferedSocket(int newfd)
29 this->state = I_CONNECTED;
31 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
34 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
36 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
37 if (err != I_ERR_NONE)
40 SetError(strerror(errno));
45 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
47 irc::sockets::sockaddrs addr, bind;
48 if (!irc::sockets::aptosa(ipaddr.c_str(), aport, &addr))
50 ServerInstance->Logs->Log("SOCKET", DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
54 bind.sa.sa_family = 0;
55 if (!connectbindip.empty())
57 if (!irc::sockets::aptosa(connectbindip.c_str(), 0, &bind))
63 return BeginConnect(addr, bind, maxtime);
66 static void IncreaseOSBuffers(int fd)
68 // attempt to increase socket sendq and recvq as high as its possible
71 setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
72 setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(recvbuf));
73 // 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.
76 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
79 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
84 if (bind.sa.sa_family != 0)
86 if (ServerInstance->SE->Bind(fd, &bind.sa, sa_size(bind)) < 0)
90 ServerInstance->SE->NonBlocking(fd);
92 if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
94 if (errno != EINPROGRESS)
98 this->state = I_CONNECTING;
100 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE))
101 return I_ERR_NOMOREFDS;
103 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
104 ServerInstance->Timers->AddTimer(this->Timeout);
106 IncreaseOSBuffers(fd);
108 ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
112 void StreamSocket::Close()
114 /* Save this, so we dont lose it,
115 * otherise on failure, error messages
116 * might be inaccurate.
125 IOHook->OnStreamSocketClose(this);
127 catch (CoreException& modexcept)
129 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
130 modexcept.GetSource(), modexcept.GetReason());
133 ServerInstance->SE->Shutdown(this, 2);
134 ServerInstance->SE->DelFd(this);
135 ServerInstance->SE->Close(this);
141 void StreamSocket::cull()
146 bool StreamSocket::GetNextLine(std::string& line, char delim)
148 std::string::size_type i = recvq.find(delim);
149 if (i == std::string::npos)
151 line = recvq.substr(0, i - 1);
152 // TODO is this the most efficient way to split?
153 recvq = recvq.substr(i + 1);
157 void StreamSocket::DoRead()
164 rv = IOHook->OnStreamSocketRead(this, recvq);
166 catch (CoreException& modexcept)
168 ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
169 modexcept.GetSource(), modexcept.GetReason());
175 SetError("Read Error"); // will not overwrite a better error message
179 char* ReadBuffer = ServerInstance->GetReadBuffer();
180 int n = recv(fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
181 if (n == ServerInstance->Config->NetBufferSize)
183 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
184 recvq.append(ReadBuffer, n);
189 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
190 recvq.append(ReadBuffer, n);
195 error = "Connection closed";
196 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
198 else if (errno == EAGAIN)
200 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
202 else if (errno == EINTR)
204 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
208 error = strerror(errno);
209 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
214 void StreamSocket::DoWrite()
218 if (!error.empty() || fd < 0 || fd == INT_MAX)
220 ServerInstance->Logs->Log("SOCKET", DEBUG, "DoWrite on errored or closed socket");
229 if (sendq.size() > 1 && sendq[0].length() < 1024)
231 // Avoid multiple repeated SSL encryption invocations
232 // This adds a single copy of the queue, but avoids
233 // much more overhead in terms of system calls invoked
236 // The length limit of 1024 is to prevent merging strings
237 // more than once when writes begin to block.
239 tmp.reserve(sendq_len);
240 for(unsigned int i=0; i < sendq.size(); i++)
241 tmp.append(sendq[i]);
243 sendq.push_back(tmp);
245 while (!sendq.empty())
247 std::string& front = sendq.front();
248 int itemlen = front.length();
249 rv = IOHook->OnStreamSocketWrite(this, front);
252 // consumed the entire string, and is ready for more
253 sendq_len -= itemlen;
258 // socket has blocked. Stop trying to send data.
259 // IOHook has requested unblock notification from the socketengine
261 // Since it is possible that a partial write took place, adjust sendq_len
262 sendq_len = sendq_len - itemlen + front.length();
267 SetError("Write Error"); // will not overwrite a better error message
272 catch (CoreException& modexcept)
274 ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
275 modexcept.GetSource(), modexcept.GetReason());
280 // don't even try if we are known to be blocking
281 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
283 // start out optimistic - we won't need to write any more
284 int eventChange = FD_WANT_EDGE_WRITE;
285 while (sendq_len && eventChange == FD_WANT_EDGE_WRITE)
287 // Prepare a writev() call to write all buffers efficiently
288 int bufcount = sendq.size();
290 // cap the number of buffers at IOV_MAX
291 if (bufcount > IOV_MAX)
297 iovec* iovecs = new iovec[bufcount];
298 for(int i=0; i < bufcount; i++)
300 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
301 iovecs[i].iov_len = sendq[i].length();
302 rv_max += sendq[i].length();
304 int rv = writev(fd, iovecs, bufcount);
307 if (rv == (int)sendq_len)
309 // it's our lucky day, everything got written out. Fast cleanup.
310 // This won't ever happen if the number of buffers got capped.
316 // Partial write. Clean out strings from the sendq
318 while (rv > 0 && !sendq.empty())
320 std::string& front = sendq.front();
321 if (front.length() <= (size_t)rv)
323 // this string got fully written out
324 rv -= front.length();
329 // stopped in the middle of this string
330 front = front.substr(rv);
336 // it's going to block now
337 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
342 error = "Connection closed";
344 else if (errno == EAGAIN)
346 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
348 else if (errno == EINTR)
350 // restart interrupted syscall
354 error = strerror(errno);
359 // error - kill all events
360 ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
364 ServerInstance->SE->ChangeEventMask(this, eventChange);
369 void StreamSocket::WriteData(const std::string &data)
373 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
378 /* Append the data to the back of the queue ready for writing */
379 sendq.push_back(data);
380 sendq_len += data.length();
382 ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
385 void SocketTimeout::Tick(time_t)
387 ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
389 if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
392 if (this->sock->state == I_CONNECTING)
394 // for connecting sockets, the timeout can occur
395 // which causes termination of the connection after
396 // the given number of seconds without a successful
398 this->sock->OnTimeout();
399 this->sock->OnError(I_ERR_TIMEOUT);
401 /* NOTE: We must set this AFTER DelFd, as we added
402 * this socket whilst writeable. This means that we
403 * must DELETE the socket whilst writeable too!
405 this->sock->state = I_ERROR;
407 ServerInstance->GlobalCulls.AddItem(sock);
410 this->sock->Timeout = NULL;
413 void BufferedSocket::OnConnected() { }
414 void BufferedSocket::OnTimeout() { return; }
416 void BufferedSocket::DoWrite()
418 if (state == I_CONNECTING)
423 GetIOHook()->OnStreamSocketConnect(this);
425 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
427 this->StreamSocket::DoWrite();
430 BufferedSocket::~BufferedSocket()
435 ServerInstance->Timers->DelTimer(Timeout);
440 void StreamSocket::HandleEvent(EventType et, int errornum)
442 BufferedSocketError errcode = I_ERR_OTHER;
448 SetError("Connection closed");
450 SetError(strerror(errornum));
454 errcode = I_ERR_TIMEOUT;
458 errcode = I_ERR_CONNECT;
461 errcode = I_ERR_BIND;
465 errcode = I_ERR_WRITE;
483 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
485 ServerInstance->GlobalCulls.AddItem(this);