2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5 * Copyright (C) 2018 Dylan Frank <b00mx0r@aureus.pw>
6 * Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
7 * Copyright (C) 2013, 2017-2020 Sadie Powell <sadie@witchery.services>
8 * Copyright (C) 2013 Adam <Adam@anope.org>
9 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
10 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
11 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
12 * Copyright (C) 2007 John Brooks <special@inspircd.org>
13 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
14 * Copyright (C) 2007 Craig Edwards <brain@inspircd.org>
16 * This file is part of InspIRCd. InspIRCd is free software: you can
17 * redistribute it and/or modify it under the terms of the GNU General Public
18 * License as published by the Free Software Foundation, version 2.
20 * This program is distributed in the hope that it will be useful, but WITHOUT
21 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
33 static IOHook* GetNextHook(IOHook* hook)
35 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
37 return iohm->GetNextHook();
41 BufferedSocket::BufferedSocket()
47 BufferedSocket::BufferedSocket(int newfd)
51 this->state = I_CONNECTED;
53 SocketEngine::AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
56 void BufferedSocket::DoConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int maxtime)
58 BufferedSocketError err = BeginConnect(dest, bind, maxtime);
59 if (err != I_ERR_NONE)
62 SetError(SocketEngine::LastError());
67 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned int timeout)
70 fd = socket(dest.family(), SOCK_STREAM, 0);
75 if (bind.family() != 0)
77 if (SocketEngine::Bind(fd, bind) < 0)
81 SocketEngine::NonBlocking(fd);
83 if (SocketEngine::Connect(this, dest) == -1)
85 if (errno != EINPROGRESS)
89 this->state = I_CONNECTING;
91 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
92 return I_ERR_NOMOREFDS;
94 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
95 ServerInstance->Timers.AddTimer(this->Timeout);
97 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
101 void StreamSocket::Close()
109 // final chance, dump as much of the sendq as we can
112 IOHook* hook = GetIOHook();
116 hook->OnStreamSocketClose(this);
117 IOHook* const nexthook = GetNextHook(hook);
121 SocketEngine::Shutdown(this, 2);
122 SocketEngine::Close(this);
126 void StreamSocket::Close(bool writeblock)
128 if (getSendQSize() != 0 && writeblock)
134 CullResult StreamSocket::cull()
137 return EventHandler::cull();
140 bool StreamSocket::GetNextLine(std::string& line, char delim)
142 std::string::size_type i = recvq.find(delim);
143 if (i == std::string::npos)
145 line.assign(recvq, 0, i);
146 recvq.erase(0, i + 1);
150 int StreamSocket::HookChainRead(IOHook* hook, std::string& rq)
153 return ReadToRecvQ(rq);
155 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
158 // Call the next hook to put data into the recvq of the current hook
159 const int ret = HookChainRead(iohm->GetNextHook(), iohm->GetRecvQ());
163 return hook->OnStreamSocketRead(this, rq);
166 void StreamSocket::DoRead()
168 const std::string::size_type prevrecvqsize = recvq.size();
170 const int result = HookChainRead(GetIOHook(), recvq);
173 SetError("Read Error"); // will not overwrite a better error message
177 if (recvq.size() > prevrecvqsize)
181 int StreamSocket::ReadToRecvQ(std::string& rq)
183 char* ReadBuffer = ServerInstance->GetReadBuffer();
184 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
185 if (n == ServerInstance->Config->NetBufferSize)
187 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
188 rq.append(ReadBuffer, n);
192 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
193 rq.append(ReadBuffer, n);
197 error = "Connection closed";
198 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
201 else if (SocketEngine::IgnoreError())
203 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
206 else if (errno == EINTR)
208 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
213 error = SocketEngine::LastError();
214 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
220 /* Don't try to prepare huge blobs of data to send to a blocked socket */
221 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
223 void StreamSocket::DoWrite()
225 if (getSendQSize() == 0)
232 if (!error.empty() || !HasFd())
234 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
238 SendQueue* psendq = &sendq;
239 IOHook* hook = GetIOHook();
242 int rv = hook->OnStreamSocketWrite(this, *psendq);
245 // rv == 0 means the socket has blocked. Stop trying to send data.
246 // IOHook has requested unblock notification from the socketengine.
252 SetError("Write Error"); // will not overwrite a better error message
256 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
260 psendq = &iohm->GetSendQ();
261 hook = iohm->GetNextHook();
268 if (getSendQSize() == 0 && closeonempty)
272 void StreamSocket::FlushSendQ(SendQueue& sq)
274 // don't even try if we are known to be blocking
275 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
277 // start out optimistic - we won't need to write any more
278 int eventChange = FD_WANT_EDGE_WRITE;
279 while (error.empty() && !sq.empty() && eventChange == FD_WANT_EDGE_WRITE)
281 // Prepare a writev() call to write all buffers efficiently
282 int bufcount = sq.size();
284 // cap the number of buffers at MYIOV_MAX
285 if (bufcount > MYIOV_MAX)
287 bufcount = MYIOV_MAX;
293 SocketEngine::IOVector iovecs[MYIOV_MAX];
295 for (SendQueue::const_iterator i = sq.begin(), end = i+bufcount; i != end; ++i, j++)
297 const SendQueue::Element& elem = *i;
298 iovecs[j].iov_base = const_cast<char*>(elem.data());
299 iovecs[j].iov_len = elem.length();
300 rv_max += iovecs[j].iov_len;
302 rv = SocketEngine::WriteV(this, iovecs, bufcount);
305 if (rv == (int)sq.bytes())
307 // it's our lucky day, everything got written out. Fast cleanup.
308 // This won't ever happen if the number of buffers got capped.
313 // Partial write. Clean out strings from the sendq
316 // it's going to block now
317 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
319 while (rv > 0 && !sq.empty())
321 const SendQueue::Element& front = sq.front();
322 if (front.length() <= (size_t)rv)
324 // this string got fully written out
325 rv -= front.length();
330 // stopped in the middle of this string
338 error = "Connection closed";
340 else if (SocketEngine::IgnoreError())
342 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
344 else if (errno == EINTR)
346 // restart interrupted syscall
351 error = SocketEngine::LastError();
356 // error - kill all events
357 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
361 SocketEngine::ChangeEventMask(this, eventChange);
365 bool StreamSocket::OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote)
370 void StreamSocket::WriteData(const std::string &data)
374 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
379 /* Append the data to the back of the queue ready for writing */
380 sendq.push_back(data);
382 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
385 bool SocketTimeout::Tick(time_t)
387 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
389 if (SocketEngine::GetRef(this->sfd) != this->sock)
395 if (this->sock->state == I_CONNECTING)
397 // for connecting sockets, the timeout can occur
398 // which causes termination of the connection after
399 // the given number of seconds without a successful
401 this->sock->OnTimeout();
402 this->sock->OnError(I_ERR_TIMEOUT);
403 this->sock->state = I_ERROR;
405 ServerInstance->GlobalCulls.AddItem(sock);
408 this->sock->Timeout = NULL;
413 void BufferedSocket::OnConnected() { }
414 void BufferedSocket::OnTimeout() { return; }
416 void BufferedSocket::OnEventHandlerWrite()
418 if (state == I_CONNECTING)
423 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
425 this->StreamSocket::OnEventHandlerWrite();
428 BufferedSocket::~BufferedSocket()
431 // The timer is removed from the TimerManager in Timer::~Timer()
435 void StreamSocket::OnEventHandlerError(int errornum)
441 SetError("Connection closed");
443 SetError(SocketEngine::GetError(errornum));
445 BufferedSocketError errcode = I_ERR_OTHER;
449 errcode = I_ERR_TIMEOUT;
453 errcode = I_ERR_CONNECT;
456 errcode = I_ERR_BIND;
460 errcode = I_ERR_WRITE;
464 // Log and call OnError()
468 void StreamSocket::OnEventHandlerRead()
477 catch (CoreException& ex)
479 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'", fd, ex.GetReason().c_str());
480 SetError(ex.GetReason());
482 CheckError(I_ERR_OTHER);
485 void StreamSocket::OnEventHandlerWrite()
491 CheckError(I_ERR_OTHER);
494 void StreamSocket::CheckError(BufferedSocketError errcode)
498 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
503 IOHook* StreamSocket::GetModHook(Module* mod) const
505 for (IOHook* curr = GetIOHook(); curr; curr = GetNextHook(curr))
507 if (curr->prov->creator == mod)
513 void StreamSocket::AddIOHook(IOHook* newhook)
515 IOHook* curr = GetIOHook();
522 IOHookMiddle* lasthook;
525 lasthook = IOHookMiddle::ToMiddleHook(curr);
528 curr = lasthook->GetNextHook();
531 lasthook->SetNextHook(newhook);
534 size_t StreamSocket::getSendQSize() const
536 size_t ret = sendq.bytes();
537 IOHook* curr = GetIOHook();
540 const IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(curr);
544 ret += iohm->GetSendQ().bytes();
545 curr = iohm->GetNextHook();
550 void StreamSocket::SwapInternals(StreamSocket& other)
552 if (type != other.type)
555 EventHandler::SwapInternals(other);
556 std::swap(closeonempty, other.closeonempty);
557 std::swap(closing, other.closing);
558 std::swap(error, other.error);
559 std::swap(iohook, other.iohook);
560 std::swap(recvq, other.recvq);
561 std::swap(sendq, other.sendq);