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) 2006-2007 Craig Edwards <brain@inspircd.org>
16 * Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
18 * This file is part of InspIRCd. InspIRCd is free software: you can
19 * redistribute it and/or modify it under the terms of the GNU General Public
20 * License as published by the Free Software Foundation, version 2.
22 * This program is distributed in the hope that it will be useful, but WITHOUT
23 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
24 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 static IOHook* GetNextHook(IOHook* hook)
37 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
39 return iohm->GetNextHook();
43 BufferedSocket::BufferedSocket()
49 BufferedSocket::BufferedSocket(int newfd)
53 this->state = I_CONNECTED;
55 SocketEngine::AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
58 void BufferedSocket::DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime)
60 BufferedSocketError err = BeginConnect(dest, bind, maxtime);
61 if (err != I_ERR_NONE)
64 SetError(SocketEngine::LastError());
69 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout)
72 fd = socket(dest.family(), SOCK_STREAM, 0);
77 if (bind.family() != 0)
79 if (SocketEngine::Bind(fd, bind) < 0)
83 SocketEngine::NonBlocking(fd);
85 if (SocketEngine::Connect(this, dest) == -1)
87 if (errno != EINPROGRESS)
91 this->state = I_CONNECTING;
93 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
94 return I_ERR_NOMOREFDS;
96 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
97 ServerInstance->Timers.AddTimer(this->Timeout);
99 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
103 void StreamSocket::Close()
111 // final chance, dump as much of the sendq as we can
114 IOHook* hook = GetIOHook();
118 hook->OnStreamSocketClose(this);
119 IOHook* const nexthook = GetNextHook(hook);
123 SocketEngine::Shutdown(this, 2);
124 SocketEngine::Close(this);
128 void StreamSocket::Close(bool writeblock)
130 if (getSendQSize() != 0 && writeblock)
136 CullResult StreamSocket::cull()
139 return EventHandler::cull();
142 bool StreamSocket::GetNextLine(std::string& line, char delim)
144 std::string::size_type i = recvq.find(delim);
145 if (i == std::string::npos)
147 line.assign(recvq, 0, i);
148 recvq.erase(0, i + 1);
152 int StreamSocket::HookChainRead(IOHook* hook, std::string& rq)
155 return ReadToRecvQ(rq);
157 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
160 // Call the next hook to put data into the recvq of the current hook
161 const int ret = HookChainRead(iohm->GetNextHook(), iohm->GetRecvQ());
165 return hook->OnStreamSocketRead(this, rq);
168 void StreamSocket::DoRead()
170 const std::string::size_type prevrecvqsize = recvq.size();
172 const int result = HookChainRead(GetIOHook(), recvq);
175 SetError("Read Error"); // will not overwrite a better error message
179 if (recvq.size() > prevrecvqsize)
183 int StreamSocket::ReadToRecvQ(std::string& rq)
185 char* ReadBuffer = ServerInstance->GetReadBuffer();
186 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
187 if (n == ServerInstance->Config->NetBufferSize)
189 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
190 rq.append(ReadBuffer, n);
194 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
195 rq.append(ReadBuffer, n);
199 error = "Connection closed";
200 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
203 else if (SocketEngine::IgnoreError())
205 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
208 else if (errno == EINTR)
210 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
215 error = SocketEngine::LastError();
216 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
222 /* Don't try to prepare huge blobs of data to send to a blocked socket */
223 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
225 void StreamSocket::DoWrite()
227 if (getSendQSize() == 0)
234 if (!error.empty() || !HasFd())
236 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
240 SendQueue* psendq = &sendq;
241 IOHook* hook = GetIOHook();
244 int rv = hook->OnStreamSocketWrite(this, *psendq);
247 // rv == 0 means the socket has blocked. Stop trying to send data.
248 // IOHook has requested unblock notification from the socketengine.
254 SetError("Write Error"); // will not overwrite a better error message
258 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
262 psendq = &iohm->GetSendQ();
263 hook = iohm->GetNextHook();
270 if (getSendQSize() == 0 && closeonempty)
274 void StreamSocket::FlushSendQ(SendQueue& sq)
276 // don't even try if we are known to be blocking
277 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
279 // start out optimistic - we won't need to write any more
280 int eventChange = FD_WANT_EDGE_WRITE;
281 while (error.empty() && !sq.empty() && eventChange == FD_WANT_EDGE_WRITE)
283 // Prepare a writev() call to write all buffers efficiently
284 int bufcount = sq.size();
286 // cap the number of buffers at MYIOV_MAX
287 if (bufcount > MYIOV_MAX)
289 bufcount = MYIOV_MAX;
295 SocketEngine::IOVector iovecs[MYIOV_MAX];
297 for (SendQueue::const_iterator i = sq.begin(), end = i+bufcount; i != end; ++i, j++)
299 const SendQueue::Element& elem = *i;
300 iovecs[j].iov_base = const_cast<char*>(elem.data());
301 iovecs[j].iov_len = elem.length();
302 rv_max += iovecs[j].iov_len;
304 rv = SocketEngine::WriteV(this, iovecs, bufcount);
307 if (rv == (int)sq.bytes())
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.
315 // Partial write. Clean out strings from the sendq
318 // it's going to block now
319 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
321 while (rv > 0 && !sq.empty())
323 const SendQueue::Element& front = sq.front();
324 if (front.length() <= (size_t)rv)
326 // this string got fully written out
327 rv -= front.length();
332 // stopped in the middle of this string
340 error = "Connection closed";
342 else if (SocketEngine::IgnoreError())
344 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
346 else if (errno == EINTR)
348 // restart interrupted syscall
353 error = SocketEngine::LastError();
358 // error - kill all events
359 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
363 SocketEngine::ChangeEventMask(this, eventChange);
367 bool StreamSocket::OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote)
372 void StreamSocket::WriteData(const std::string &data)
376 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
381 /* Append the data to the back of the queue ready for writing */
382 sendq.push_back(data);
384 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
387 bool SocketTimeout::Tick(time_t)
389 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
391 if (SocketEngine::GetRef(this->sfd) != this->sock)
397 if (this->sock->state == I_CONNECTING)
399 // for connecting sockets, the timeout can occur
400 // which causes termination of the connection after
401 // the given number of seconds without a successful
403 this->sock->OnTimeout();
404 this->sock->OnError(I_ERR_TIMEOUT);
405 this->sock->state = I_ERROR;
407 ServerInstance->GlobalCulls.AddItem(sock);
410 this->sock->Timeout = NULL;
415 void BufferedSocket::OnConnected() { }
416 void BufferedSocket::OnTimeout() { return; }
418 void BufferedSocket::OnEventHandlerWrite()
420 if (state == I_CONNECTING)
425 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
427 this->StreamSocket::OnEventHandlerWrite();
430 BufferedSocket::~BufferedSocket()
433 // The timer is removed from the TimerManager in Timer::~Timer()
437 void StreamSocket::OnEventHandlerError(int errornum)
443 SetError("Connection closed");
445 SetError(SocketEngine::GetError(errornum));
447 BufferedSocketError errcode = I_ERR_OTHER;
451 errcode = I_ERR_TIMEOUT;
455 errcode = I_ERR_CONNECT;
458 errcode = I_ERR_BIND;
462 errcode = I_ERR_WRITE;
466 // Log and call OnError()
470 void StreamSocket::OnEventHandlerRead()
479 catch (CoreException& ex)
481 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'", fd, ex.GetReason().c_str());
482 SetError(ex.GetReason());
484 CheckError(I_ERR_OTHER);
487 void StreamSocket::OnEventHandlerWrite()
493 CheckError(I_ERR_OTHER);
496 void StreamSocket::CheckError(BufferedSocketError errcode)
500 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
505 IOHook* StreamSocket::GetModHook(Module* mod) const
507 for (IOHook* curr = GetIOHook(); curr; curr = GetNextHook(curr))
509 if (curr->prov->creator == mod)
515 IOHook* StreamSocket::GetLastHook() const
517 IOHook* curr = GetIOHook();
520 for (; curr; curr = GetNextHook(curr))
527 void StreamSocket::AddIOHook(IOHook* newhook)
529 IOHook* curr = GetIOHook();
536 IOHookMiddle* lasthook;
539 lasthook = IOHookMiddle::ToMiddleHook(curr);
542 curr = lasthook->GetNextHook();
545 lasthook->SetNextHook(newhook);
548 size_t StreamSocket::getSendQSize() const
550 size_t ret = sendq.bytes();
551 IOHook* curr = GetIOHook();
554 const IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(curr);
558 ret += iohm->GetSendQ().bytes();
559 curr = iohm->GetNextHook();
564 void StreamSocket::SwapInternals(StreamSocket& other)
566 if (type != other.type)
569 EventHandler::SwapInternals(other);
570 std::swap(closeonempty, other.closeonempty);
571 std::swap(closing, other.closing);
572 std::swap(error, other.error);
573 std::swap(iohook, other.iohook);
574 std::swap(recvq, other.recvq);
575 std::swap(sendq, other.sendq);