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 std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
53 BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
54 if (err != I_ERR_NONE)
57 SetError(SocketEngine::LastError());
62 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
64 irc::sockets::sockaddrs addr, bind;
65 if (!irc::sockets::aptosa(ipaddr, aport, addr))
67 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
71 bind.sa.sa_family = 0;
72 if (!connectbindip.empty())
74 if (!irc::sockets::aptosa(connectbindip, 0, bind))
80 return BeginConnect(addr, bind, maxtime);
83 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
86 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
91 if (bind.sa.sa_family != 0)
93 if (SocketEngine::Bind(fd, bind) < 0)
97 SocketEngine::NonBlocking(fd);
99 if (SocketEngine::Connect(this, &dest.sa, dest.sa_size()) == -1)
101 if (errno != EINPROGRESS)
102 return I_ERR_CONNECT;
105 this->state = I_CONNECTING;
107 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
108 return I_ERR_NOMOREFDS;
110 this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
111 ServerInstance->Timers.AddTimer(this->Timeout);
113 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
117 void StreamSocket::Close()
121 // final chance, dump as much of the sendq as we can
124 IOHook* hook = GetIOHook();
128 hook->OnStreamSocketClose(this);
129 IOHook* const nexthook = GetNextHook(hook);
133 SocketEngine::Shutdown(this, 2);
134 SocketEngine::Close(this);
138 CullResult StreamSocket::cull()
141 return EventHandler::cull();
144 bool StreamSocket::GetNextLine(std::string& line, char delim)
146 std::string::size_type i = recvq.find(delim);
147 if (i == std::string::npos)
149 line.assign(recvq, 0, i);
150 recvq.erase(0, i + 1);
154 int StreamSocket::HookChainRead(IOHook* hook, std::string& rq)
157 return ReadToRecvQ(rq);
159 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
162 // Call the next hook to put data into the recvq of the current hook
163 const int ret = HookChainRead(iohm->GetNextHook(), iohm->GetRecvQ());
167 return hook->OnStreamSocketRead(this, rq);
170 void StreamSocket::DoRead()
172 const std::string::size_type prevrecvqsize = recvq.size();
174 const int result = HookChainRead(GetIOHook(), recvq);
177 SetError("Read Error"); // will not overwrite a better error message
181 if (recvq.size() > prevrecvqsize)
185 int StreamSocket::ReadToRecvQ(std::string& rq)
187 char* ReadBuffer = ServerInstance->GetReadBuffer();
188 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
189 if (n == ServerInstance->Config->NetBufferSize)
191 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
192 rq.append(ReadBuffer, n);
196 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
197 rq.append(ReadBuffer, n);
201 error = "Connection closed";
202 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
205 else if (SocketEngine::IgnoreError())
207 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
210 else if (errno == EINTR)
212 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
217 error = SocketEngine::LastError();
218 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
224 /* Don't try to prepare huge blobs of data to send to a blocked socket */
225 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
227 void StreamSocket::DoWrite()
229 if (getSendQSize() == 0)
231 if (!error.empty() || fd < 0)
233 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
237 SendQueue* psendq = &sendq;
238 IOHook* hook = GetIOHook();
241 int rv = hook->OnStreamSocketWrite(this, *psendq);
244 // rv == 0 means the socket has blocked. Stop trying to send data.
245 // IOHook has requested unblock notification from the socketengine.
251 SetError("Write Error"); // will not overwrite a better error message
255 IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(hook);
259 psendq = &iohm->GetSendQ();
260 hook = iohm->GetNextHook();
268 void StreamSocket::FlushSendQ(SendQueue& sq)
270 // don't even try if we are known to be blocking
271 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
273 // start out optimistic - we won't need to write any more
274 int eventChange = FD_WANT_EDGE_WRITE;
275 while (error.empty() && !sq.empty() && eventChange == FD_WANT_EDGE_WRITE)
277 // Prepare a writev() call to write all buffers efficiently
278 int bufcount = sq.size();
280 // cap the number of buffers at MYIOV_MAX
281 if (bufcount > MYIOV_MAX)
283 bufcount = MYIOV_MAX;
289 SocketEngine::IOVector iovecs[MYIOV_MAX];
291 for (SendQueue::const_iterator i = sq.begin(), end = i+bufcount; i != end; ++i, j++)
293 const SendQueue::Element& elem = *i;
294 iovecs[j].iov_base = const_cast<char*>(elem.data());
295 iovecs[j].iov_len = elem.length();
296 rv_max += elem.length();
298 rv = SocketEngine::WriteV(this, iovecs, bufcount);
301 if (rv == (int)sq.bytes())
303 // it's our lucky day, everything got written out. Fast cleanup.
304 // This won't ever happen if the number of buffers got capped.
309 // Partial write. Clean out strings from the sendq
312 // it's going to block now
313 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
315 while (rv > 0 && !sq.empty())
317 const SendQueue::Element& front = sq.front();
318 if (front.length() <= (size_t)rv)
320 // this string got fully written out
321 rv -= front.length();
326 // stopped in the middle of this string
334 error = "Connection closed";
336 else if (SocketEngine::IgnoreError())
338 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
340 else if (errno == EINTR)
342 // restart interrupted syscall
347 error = SocketEngine::LastError();
352 // error - kill all events
353 SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
357 SocketEngine::ChangeEventMask(this, eventChange);
361 void StreamSocket::WriteData(const std::string &data)
365 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
370 /* Append the data to the back of the queue ready for writing */
371 sendq.push_back(data);
373 SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
376 bool SocketTimeout::Tick(time_t)
378 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
380 if (SocketEngine::GetRef(this->sfd) != this->sock)
386 if (this->sock->state == I_CONNECTING)
388 // for connecting sockets, the timeout can occur
389 // which causes termination of the connection after
390 // the given number of seconds without a successful
392 this->sock->OnTimeout();
393 this->sock->OnError(I_ERR_TIMEOUT);
394 this->sock->state = I_ERROR;
396 ServerInstance->GlobalCulls.AddItem(sock);
399 this->sock->Timeout = NULL;
404 void BufferedSocket::OnConnected() { }
405 void BufferedSocket::OnTimeout() { return; }
407 void BufferedSocket::OnEventHandlerWrite()
409 if (state == I_CONNECTING)
414 SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
416 this->StreamSocket::OnEventHandlerWrite();
419 BufferedSocket::~BufferedSocket()
422 // The timer is removed from the TimerManager in Timer::~Timer()
426 void StreamSocket::OnEventHandlerError(int errornum)
432 SetError("Connection closed");
434 SetError(SocketEngine::GetError(errornum));
436 BufferedSocketError errcode = I_ERR_OTHER;
440 errcode = I_ERR_TIMEOUT;
444 errcode = I_ERR_CONNECT;
447 errcode = I_ERR_BIND;
451 errcode = I_ERR_WRITE;
455 // Log and call OnError()
459 void StreamSocket::OnEventHandlerRead()
468 catch (CoreException& ex)
470 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'", fd, ex.GetReason().c_str());
471 SetError(ex.GetReason());
473 CheckError(I_ERR_OTHER);
476 void StreamSocket::OnEventHandlerWrite()
482 CheckError(I_ERR_OTHER);
485 void StreamSocket::CheckError(BufferedSocketError errcode)
489 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
494 IOHook* StreamSocket::GetModHook(Module* mod) const
496 for (IOHook* curr = GetIOHook(); curr; curr = GetNextHook(curr))
498 if (curr->prov->creator == mod)
504 void StreamSocket::AddIOHook(IOHook* newhook)
506 IOHook* curr = GetIOHook();
513 IOHookMiddle* lasthook;
516 lasthook = IOHookMiddle::ToMiddleHook(curr);
519 curr = lasthook->GetNextHook();
522 lasthook->SetNextHook(newhook);
525 size_t StreamSocket::getSendQSize() const
527 size_t ret = sendq.bytes();
528 IOHook* curr = GetIOHook();
531 const IOHookMiddle* const iohm = IOHookMiddle::ToMiddleHook(curr);
535 ret += iohm->GetSendQ().bytes();
536 curr = iohm->GetNextHook();