2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2020 Matt Schatz <genius3000@g3k.solutions>
5 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6 * Copyright (C) 2018 Dylan Frank <b00mx0r@aureus.pw>
7 * Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
8 * Copyright (C) 2013, 2017-2020 Sadie Powell <sadie@witchery.services>
9 * Copyright (C) 2013 Adam <Adam@anope.org>
10 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
11 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
13 * Copyright (C) 2007 John Brooks <special@inspircd.org>
14 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
15 * Copyright (C) 2007 Craig Edwards <brain@inspircd.org>
17 * This file is part of InspIRCd. InspIRCd is free software: you can
18 * redistribute it and/or modify it under the terms of the GNU General Public
19 * License as published by the Free Software Foundation, version 2.
21 * This program is distributed in the hope that it will be useful, but WITHOUT
22 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
23 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 static IOHook* GetNextHook(IOHook* hook)
36 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
38 return iohm->GetNextHook();
42 BufferedSocket::BufferedSocket()
48 BufferedSocket::BufferedSocket(int newfd)
52 this->state = I_CONNECTED;
54 SocketEngine::AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
57 void BufferedSocket::DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime)
59 BufferedSocketError err = BeginConnect(dest, bind, maxtime);
60 if (err != I_ERR_NONE)
63 SetError(SocketEngine::LastError());
68 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout)
71 fd = socket(dest.family(), SOCK_STREAM, 0);
76 if (bind.family() != 0)
78 if (SocketEngine::Bind(fd, bind) < 0)
82 SocketEngine::NonBlocking(fd);
84 if (SocketEngine::Connect(this, dest) == -1)
86 if (errno != EINPROGRESS)
90 this->state = I_CONNECTING;
92 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
93 return I_ERR_NOMOREFDS;
95 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
96 ServerInstance->Timers.AddTimer(this->Timeout);
98 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
102 void StreamSocket::Close()
110 // final chance, dump as much of the sendq as we can
113 IOHook* hook = GetIOHook();
117 hook->OnStreamSocketClose(this);
118 IOHook* const nexthook = GetNextHook(hook);
122 SocketEngine::Shutdown(this, 2);
123 SocketEngine::Close(this);
127 void StreamSocket::Close(bool writeblock)
129 if (getSendQSize() != 0 && writeblock)
135 CullResult StreamSocket::cull()
138 return EventHandler::cull();
141 bool StreamSocket::GetNextLine(std::string& line, char delim)
143 std::string::size_type i = recvq.find(delim);
144 if (i == std::string::npos)
146 line.assign(recvq, 0, i);
147 recvq.erase(0, i + 1);
151 int StreamSocket::HookChainRead(IOHook* hook, std::string& rq)
154 return ReadToRecvQ(rq);
156 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
159 // Call the next hook to put data into the recvq of the current hook
160 const int ret = HookChainRead(iohm->GetNextHook(), iohm->GetRecvQ());
164 return hook->OnStreamSocketRead(this, rq);
167 void StreamSocket::DoRead()
169 const std::string::size_type prevrecvqsize = recvq.size();
171 const int result = HookChainRead(GetIOHook(), recvq);
174 SetError("Read Error"); // will not overwrite a better error message
178 if (recvq.size() > prevrecvqsize)
182 int StreamSocket::ReadToRecvQ(std::string& rq)
184 char* ReadBuffer = ServerInstance->GetReadBuffer();
185 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
186 if (n == ServerInstance->Config->NetBufferSize)
188 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
189 rq.append(ReadBuffer, n);
193 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
194 rq.append(ReadBuffer, n);
198 error = "Connection closed";
199 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
202 else if (SocketEngine::IgnoreError())
204 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
207 else if (errno == EINTR)
209 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
214 error = SocketEngine::LastError();
215 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
221 /* Don't try to prepare huge blobs of data to send to a blocked socket */
222 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
224 void StreamSocket::DoWrite()
226 if (getSendQSize() == 0)
233 if (!error.empty() || !HasFd())
235 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
239 SendQueue* psendq = &sendq;
240 IOHook* hook = GetIOHook();
243 int rv = hook->OnStreamSocketWrite(this, *psendq);
246 // rv == 0 means the socket has blocked. Stop trying to send data.
247 // IOHook has requested unblock notification from the socketengine.
253 SetError("Write Error"); // will not overwrite a better error message
257 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
261 psendq = &iohm->GetSendQ();
262 hook = iohm->GetNextHook();
269 if (getSendQSize() == 0 && closeonempty)
273 void StreamSocket::FlushSendQ(SendQueue& sq)
275 // don't even try if we are known to be blocking
276 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
278 // start out optimistic - we won't need to write any more
279 int eventChange = FD_WANT_EDGE_WRITE;
280 while (error.empty() && !sq.empty() && eventChange == FD_WANT_EDGE_WRITE)
282 // Prepare a writev() call to write all buffers efficiently
283 int bufcount = sq.size();
285 // cap the number of buffers at MYIOV_MAX
286 if (bufcount > MYIOV_MAX)
288 bufcount = MYIOV_MAX;
294 SocketEngine::IOVector iovecs[MYIOV_MAX];
296 for (SendQueue::const_iterator i = sq.begin(), end = i+bufcount; i != end; ++i, j++)
298 const SendQueue::Element& elem = *i;
299 iovecs[j].iov_base = const_cast<char*>(elem.data());
300 iovecs[j].iov_len = elem.length();
301 rv_max += iovecs[j].iov_len;
303 rv = SocketEngine::WriteV(this, iovecs, bufcount);
306 if (rv == (int)sq.bytes())
308 // it's our lucky day, everything got written out. Fast cleanup.
309 // This won't ever happen if the number of buffers got capped.
314 // Partial write. Clean out strings from the sendq
317 // it's going to block now
318 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
320 while (rv > 0 && !sq.empty())
322 const SendQueue::Element& front = sq.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
339 error = "Connection closed";
341 else if (SocketEngine::IgnoreError())
343 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
345 else if (errno == EINTR)
347 // restart interrupted syscall
352 error = SocketEngine::LastError();
357 // error - kill all events
358 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
362 SocketEngine::ChangeEventMask(this, eventChange);
366 bool StreamSocket::OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote)
371 void StreamSocket::WriteData(const std::string &data)
375 ServerInstance->Logs->Log("SOCKET", LOG_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);
383 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
386 bool SocketTimeout::Tick(time_t)
388 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
390 if (SocketEngine::GetRef(this->sfd) != this->sock)
396 if (this->sock->state == I_CONNECTING)
398 // for connecting sockets, the timeout can occur
399 // which causes termination of the connection after
400 // the given number of seconds without a successful
402 this->sock->OnTimeout();
403 this->sock->OnError(I_ERR_TIMEOUT);
404 this->sock->state = I_ERROR;
406 ServerInstance->GlobalCulls.AddItem(sock);
409 this->sock->Timeout = NULL;
414 void BufferedSocket::OnConnected() { }
415 void BufferedSocket::OnTimeout() { return; }
417 void BufferedSocket::OnEventHandlerWrite()
419 if (state == I_CONNECTING)
424 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
426 this->StreamSocket::OnEventHandlerWrite();
429 BufferedSocket::~BufferedSocket()
432 // The timer is removed from the TimerManager in Timer::~Timer()
436 void StreamSocket::OnEventHandlerError(int errornum)
442 SetError("Connection closed");
444 SetError(SocketEngine::GetError(errornum));
446 BufferedSocketError errcode = I_ERR_OTHER;
450 errcode = I_ERR_TIMEOUT;
454 errcode = I_ERR_CONNECT;
457 errcode = I_ERR_BIND;
461 errcode = I_ERR_WRITE;
465 // Log and call OnError()
469 void StreamSocket::OnEventHandlerRead()
478 catch (CoreException& ex)
480 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'", fd, ex.GetReason().c_str());
481 SetError(ex.GetReason());
483 CheckError(I_ERR_OTHER);
486 void StreamSocket::OnEventHandlerWrite()
492 CheckError(I_ERR_OTHER);
495 void StreamSocket::CheckError(BufferedSocketError errcode)
499 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
504 IOHook* StreamSocket::GetModHook(Module* mod) const
506 for (IOHook* curr = GetIOHook(); curr; curr = GetNextHook(curr))
508 if (curr->prov->creator == mod)
514 IOHook* StreamSocket::GetLastHook() const
516 IOHook* curr = GetIOHook();
519 for (; curr; curr = GetNextHook(curr))
526 void StreamSocket::AddIOHook(IOHook* newhook)
528 IOHook* curr = GetIOHook();
535 IOHookMiddle* lasthook;
538 lasthook = IOHookMiddle::ToMiddleHook(curr);
541 curr = lasthook->GetNextHook();
544 lasthook->SetNextHook(newhook);
547 size_t StreamSocket::getSendQSize() const
549 size_t ret = sendq.bytes();
550 IOHook* curr = GetIOHook();
553 const IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(curr);
557 ret += iohm->GetSendQ().bytes();
558 curr = iohm->GetNextHook();
563 void StreamSocket::SwapInternals(StreamSocket& other)
565 if (type != other.type)
568 EventHandler::SwapInternals(other);
569 std::swap(closeonempty, other.closeonempty);
570 std::swap(closing, other.closing);
571 std::swap(error, other.error);
572 std::swap(iohook, other.iohook);
573 std::swap(recvq, other.recvq);
574 std::swap(sendq, other.sendq);