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()
100 // final chance, dump as much of the sendq as we can
103 IOHook* hook = GetIOHook();
107 hook->OnStreamSocketClose(this);
108 IOHook* const nexthook = GetNextHook(hook);
112 SocketEngine::Shutdown(this, 2);
113 SocketEngine::Close(this);
117 CullResult StreamSocket::cull()
120 return EventHandler::cull();
123 bool StreamSocket::GetNextLine(std::string& line, char delim)
125 std::string::size_type i = recvq.find(delim);
126 if (i == std::string::npos)
128 line.assign(recvq, 0, i);
129 recvq.erase(0, i + 1);
133 int StreamSocket::HookChainRead(IOHook* hook, std::string& rq)
136 return ReadToRecvQ(rq);
138 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
141 // Call the next hook to put data into the recvq of the current hook
142 const int ret = HookChainRead(iohm->GetNextHook(), iohm->GetRecvQ());
146 return hook->OnStreamSocketRead(this, rq);
149 void StreamSocket::DoRead()
151 const std::string::size_type prevrecvqsize = recvq.size();
153 const int result = HookChainRead(GetIOHook(), recvq);
156 SetError("Read Error"); // will not overwrite a better error message
160 if (recvq.size() > prevrecvqsize)
164 int StreamSocket::ReadToRecvQ(std::string& rq)
166 char* ReadBuffer = ServerInstance->GetReadBuffer();
167 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
168 if (n == ServerInstance->Config->NetBufferSize)
170 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
171 rq.append(ReadBuffer, n);
175 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
176 rq.append(ReadBuffer, n);
180 error = "Connection closed";
181 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
184 else if (SocketEngine::IgnoreError())
186 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
189 else if (errno == EINTR)
191 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
196 error = SocketEngine::LastError();
197 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
203 /* Don't try to prepare huge blobs of data to send to a blocked socket */
204 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
206 void StreamSocket::DoWrite()
208 if (getSendQSize() == 0)
210 if (!error.empty() || fd < 0)
212 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
216 SendQueue* psendq = &sendq;
217 IOHook* hook = GetIOHook();
220 int rv = hook->OnStreamSocketWrite(this, *psendq);
223 // rv == 0 means the socket has blocked. Stop trying to send data.
224 // IOHook has requested unblock notification from the socketengine.
230 SetError("Write Error"); // will not overwrite a better error message
234 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
238 psendq = &iohm->GetSendQ();
239 hook = iohm->GetNextHook();
247 void StreamSocket::FlushSendQ(SendQueue& sq)
249 // don't even try if we are known to be blocking
250 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
252 // start out optimistic - we won't need to write any more
253 int eventChange = FD_WANT_EDGE_WRITE;
254 while (error.empty() && !sq.empty() && eventChange == FD_WANT_EDGE_WRITE)
256 // Prepare a writev() call to write all buffers efficiently
257 int bufcount = sq.size();
259 // cap the number of buffers at MYIOV_MAX
260 if (bufcount > MYIOV_MAX)
262 bufcount = MYIOV_MAX;
268 SocketEngine::IOVector iovecs[MYIOV_MAX];
270 for (SendQueue::const_iterator i = sq.begin(), end = i+bufcount; i != end; ++i, j++)
272 const SendQueue::Element& elem = *i;
273 iovecs[j].iov_base = const_cast<char*>(elem.data());
274 iovecs[j].iov_len = elem.length();
275 rv_max += iovecs[j].iov_len;
277 rv = SocketEngine::WriteV(this, iovecs, bufcount);
280 if (rv == (int)sq.bytes())
282 // it's our lucky day, everything got written out. Fast cleanup.
283 // This won't ever happen if the number of buffers got capped.
288 // Partial write. Clean out strings from the sendq
291 // it's going to block now
292 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
294 while (rv > 0 && !sq.empty())
296 const SendQueue::Element& front = sq.front();
297 if (front.length() <= (size_t)rv)
299 // this string got fully written out
300 rv -= front.length();
305 // stopped in the middle of this string
313 error = "Connection closed";
315 else if (SocketEngine::IgnoreError())
317 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
319 else if (errno == EINTR)
321 // restart interrupted syscall
326 error = SocketEngine::LastError();
331 // error - kill all events
332 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
336 SocketEngine::ChangeEventMask(this, eventChange);
340 bool StreamSocket::OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote)
345 void StreamSocket::WriteData(const std::string &data)
349 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
354 /* Append the data to the back of the queue ready for writing */
355 sendq.push_back(data);
357 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
360 bool SocketTimeout::Tick(time_t)
362 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
364 if (SocketEngine::GetRef(this->sfd) != this->sock)
370 if (this->sock->state == I_CONNECTING)
372 // for connecting sockets, the timeout can occur
373 // which causes termination of the connection after
374 // the given number of seconds without a successful
376 this->sock->OnTimeout();
377 this->sock->OnError(I_ERR_TIMEOUT);
378 this->sock->state = I_ERROR;
380 ServerInstance->GlobalCulls.AddItem(sock);
383 this->sock->Timeout = NULL;
388 void BufferedSocket::OnConnected() { }
389 void BufferedSocket::OnTimeout() { return; }
391 void BufferedSocket::OnEventHandlerWrite()
393 if (state == I_CONNECTING)
398 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
400 this->StreamSocket::OnEventHandlerWrite();
403 BufferedSocket::~BufferedSocket()
406 // The timer is removed from the TimerManager in Timer::~Timer()
410 void StreamSocket::OnEventHandlerError(int errornum)
416 SetError("Connection closed");
418 SetError(SocketEngine::GetError(errornum));
420 BufferedSocketError errcode = I_ERR_OTHER;
424 errcode = I_ERR_TIMEOUT;
428 errcode = I_ERR_CONNECT;
431 errcode = I_ERR_BIND;
435 errcode = I_ERR_WRITE;
439 // Log and call OnError()
443 void StreamSocket::OnEventHandlerRead()
452 catch (CoreException& ex)
454 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'", fd, ex.GetReason().c_str());
455 SetError(ex.GetReason());
457 CheckError(I_ERR_OTHER);
460 void StreamSocket::OnEventHandlerWrite()
466 CheckError(I_ERR_OTHER);
469 void StreamSocket::CheckError(BufferedSocketError errcode)
473 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
478 IOHook* StreamSocket::GetModHook(Module* mod) const
480 for (IOHook* curr = GetIOHook(); curr; curr = GetNextHook(curr))
482 if (curr->prov->creator == mod)
488 void StreamSocket::AddIOHook(IOHook* newhook)
490 IOHook* curr = GetIOHook();
497 IOHookMiddle* lasthook;
500 lasthook = IOHookMiddle::ToMiddleHook(curr);
503 curr = lasthook->GetNextHook();
506 lasthook->SetNextHook(newhook);
509 size_t StreamSocket::getSendQSize() const
511 size_t ret = sendq.bytes();
512 IOHook* curr = GetIOHook();
515 const IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(curr);
519 ret += iohm->GetSendQ().bytes();
520 curr = iohm->GetNextHook();