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/>.
28 static IOHook* GetNextHook(IOHook* hook)
30 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
32 return iohm->GetNextHook();
36 BufferedSocket::BufferedSocket()
42 BufferedSocket::BufferedSocket(int newfd)
46 this->state = I_CONNECTED;
48 SocketEngine::AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
51 void BufferedSocket::DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime)
53 BufferedSocketError err = BeginConnect(dest, bind, maxtime);
54 if (err != I_ERR_NONE)
57 SetError(SocketEngine::LastError());
62 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout)
65 fd = socket(dest.family(), SOCK_STREAM, 0);
70 if (bind.family() != 0)
72 if (SocketEngine::Bind(fd, bind) < 0)
76 SocketEngine::NonBlocking(fd);
78 if (SocketEngine::Connect(this, dest) == -1)
80 if (errno != EINPROGRESS)
84 this->state = I_CONNECTING;
86 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
87 return I_ERR_NOMOREFDS;
89 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
90 ServerInstance->Timers.AddTimer(this->Timeout);
92 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
96 void StreamSocket::Close()
104 // final chance, dump as much of the sendq as we can
107 IOHook* hook = GetIOHook();
111 hook->OnStreamSocketClose(this);
112 IOHook* const nexthook = GetNextHook(hook);
116 SocketEngine::Shutdown(this, 2);
117 SocketEngine::Close(this);
121 void StreamSocket::Close(bool writeblock)
123 if (getSendQSize() != 0 && writeblock)
129 CullResult StreamSocket::cull()
132 return EventHandler::cull();
135 bool StreamSocket::GetNextLine(std::string& line, char delim)
137 std::string::size_type i = recvq.find(delim);
138 if (i == std::string::npos)
140 line.assign(recvq, 0, i);
141 recvq.erase(0, i + 1);
145 int StreamSocket::HookChainRead(IOHook* hook, std::string& rq)
148 return ReadToRecvQ(rq);
150 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
153 // Call the next hook to put data into the recvq of the current hook
154 const int ret = HookChainRead(iohm->GetNextHook(), iohm->GetRecvQ());
158 return hook->OnStreamSocketRead(this, rq);
161 void StreamSocket::DoRead()
163 const std::string::size_type prevrecvqsize = recvq.size();
165 const int result = HookChainRead(GetIOHook(), recvq);
168 SetError("Read Error"); // will not overwrite a better error message
172 if (recvq.size() > prevrecvqsize)
176 int StreamSocket::ReadToRecvQ(std::string& rq)
178 char* ReadBuffer = ServerInstance->GetReadBuffer();
179 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
180 if (n == ServerInstance->Config->NetBufferSize)
182 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
183 rq.append(ReadBuffer, n);
187 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
188 rq.append(ReadBuffer, n);
192 error = "Connection closed";
193 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
196 else if (SocketEngine::IgnoreError())
198 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
201 else if (errno == EINTR)
203 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
208 error = SocketEngine::LastError();
209 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
215 /* Don't try to prepare huge blobs of data to send to a blocked socket */
216 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
218 void StreamSocket::DoWrite()
220 if (getSendQSize() == 0)
227 if (!error.empty() || fd < 0)
229 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
233 SendQueue* psendq = &sendq;
234 IOHook* hook = GetIOHook();
237 int rv = hook->OnStreamSocketWrite(this, *psendq);
240 // rv == 0 means the socket has blocked. Stop trying to send data.
241 // IOHook has requested unblock notification from the socketengine.
247 SetError("Write Error"); // will not overwrite a better error message
251 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
255 psendq = &iohm->GetSendQ();
256 hook = iohm->GetNextHook();
263 if (getSendQSize() == 0 && closeonempty)
267 void StreamSocket::FlushSendQ(SendQueue& sq)
269 // don't even try if we are known to be blocking
270 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
272 // start out optimistic - we won't need to write any more
273 int eventChange = FD_WANT_EDGE_WRITE;
274 while (error.empty() && !sq.empty() && eventChange == FD_WANT_EDGE_WRITE)
276 // Prepare a writev() call to write all buffers efficiently
277 int bufcount = sq.size();
279 // cap the number of buffers at MYIOV_MAX
280 if (bufcount > MYIOV_MAX)
282 bufcount = MYIOV_MAX;
288 SocketEngine::IOVector iovecs[MYIOV_MAX];
290 for (SendQueue::const_iterator i = sq.begin(), end = i+bufcount; i != end; ++i, j++)
292 const SendQueue::Element& elem = *i;
293 iovecs[j].iov_base = const_cast<char*>(elem.data());
294 iovecs[j].iov_len = elem.length();
295 rv_max += iovecs[j].iov_len;
297 rv = SocketEngine::WriteV(this, iovecs, bufcount);
300 if (rv == (int)sq.bytes())
302 // it's our lucky day, everything got written out. Fast cleanup.
303 // This won't ever happen if the number of buffers got capped.
308 // Partial write. Clean out strings from the sendq
311 // it's going to block now
312 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
314 while (rv > 0 && !sq.empty())
316 const SendQueue::Element& front = sq.front();
317 if (front.length() <= (size_t)rv)
319 // this string got fully written out
320 rv -= front.length();
325 // stopped in the middle of this string
333 error = "Connection closed";
335 else if (SocketEngine::IgnoreError())
337 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
339 else if (errno == EINTR)
341 // restart interrupted syscall
346 error = SocketEngine::LastError();
351 // error - kill all events
352 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
356 SocketEngine::ChangeEventMask(this, eventChange);
360 bool StreamSocket::OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote)
365 void StreamSocket::WriteData(const std::string &data)
369 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
374 /* Append the data to the back of the queue ready for writing */
375 sendq.push_back(data);
377 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
380 bool SocketTimeout::Tick(time_t)
382 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
384 if (SocketEngine::GetRef(this->sfd) != this->sock)
390 if (this->sock->state == I_CONNECTING)
392 // for connecting sockets, the timeout can occur
393 // which causes termination of the connection after
394 // the given number of seconds without a successful
396 this->sock->OnTimeout();
397 this->sock->OnError(I_ERR_TIMEOUT);
398 this->sock->state = I_ERROR;
400 ServerInstance->GlobalCulls.AddItem(sock);
403 this->sock->Timeout = NULL;
408 void BufferedSocket::OnConnected() { }
409 void BufferedSocket::OnTimeout() { return; }
411 void BufferedSocket::OnEventHandlerWrite()
413 if (state == I_CONNECTING)
418 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
420 this->StreamSocket::OnEventHandlerWrite();
423 BufferedSocket::~BufferedSocket()
426 // The timer is removed from the TimerManager in Timer::~Timer()
430 void StreamSocket::OnEventHandlerError(int errornum)
436 SetError("Connection closed");
438 SetError(SocketEngine::GetError(errornum));
440 BufferedSocketError errcode = I_ERR_OTHER;
444 errcode = I_ERR_TIMEOUT;
448 errcode = I_ERR_CONNECT;
451 errcode = I_ERR_BIND;
455 errcode = I_ERR_WRITE;
459 // Log and call OnError()
463 void StreamSocket::OnEventHandlerRead()
472 catch (CoreException& ex)
474 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'", fd, ex.GetReason().c_str());
475 SetError(ex.GetReason());
477 CheckError(I_ERR_OTHER);
480 void StreamSocket::OnEventHandlerWrite()
486 CheckError(I_ERR_OTHER);
489 void StreamSocket::CheckError(BufferedSocketError errcode)
493 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
498 IOHook* StreamSocket::GetModHook(Module* mod) const
500 for (IOHook* curr = GetIOHook(); curr; curr = GetNextHook(curr))
502 if (curr->prov->creator == mod)
508 void StreamSocket::AddIOHook(IOHook* newhook)
510 IOHook* curr = GetIOHook();
517 IOHookMiddle* lasthook;
520 lasthook = IOHookMiddle::ToMiddleHook(curr);
523 curr = lasthook->GetNextHook();
526 lasthook->SetNextHook(newhook);
529 size_t StreamSocket::getSendQSize() const
531 size_t ret = sendq.bytes();
532 IOHook* curr = GetIOHook();
535 const IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(curr);
539 ret += iohm->GetSendQ().bytes();
540 curr = iohm->GetNextHook();
545 void StreamSocket::SwapInternals(StreamSocket& other)
547 if (type != other.type)
550 EventHandler::SwapInternals(other);
551 std::swap(closeonempty, other.closeonempty);
552 std::swap(closing, other.closing);
553 std::swap(error, other.error);
554 std::swap(iohook, other.iohook);
555 std::swap(recvq, other.recvq);
556 std::swap(sendq, other.sendq);