]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
7ddd774954f913e13cb196e861ba2f44814fe559
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
10  *
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.
14  *
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
18  * details.
19  *
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/>.
22  */
23
24
25 #include "inspircd.h"
26 #include "iohook.h"
27
28 BufferedSocket::BufferedSocket()
29 {
30         Timeout = NULL;
31         state = I_ERROR;
32 }
33
34 BufferedSocket::BufferedSocket(int newfd)
35 {
36         Timeout = NULL;
37         this->fd = newfd;
38         this->state = I_CONNECTED;
39         if (fd > -1)
40                 SocketEngine::AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
41 }
42
43 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
44 {
45         BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
46         if (err != I_ERR_NONE)
47         {
48                 state = I_ERROR;
49                 SetError(SocketEngine::LastError());
50                 OnError(err);
51         }
52 }
53
54 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
55 {
56         irc::sockets::sockaddrs addr, bind;
57         if (!irc::sockets::aptosa(ipaddr, aport, addr))
58         {
59                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
60                 return I_ERR_CONNECT;
61         }
62
63         bind.sa.sa_family = 0;
64         if (!connectbindip.empty())
65         {
66                 if (!irc::sockets::aptosa(connectbindip, 0, bind))
67                 {
68                         return I_ERR_BIND;
69                 }
70         }
71
72         return BeginConnect(addr, bind, maxtime);
73 }
74
75 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
76 {
77         if (fd < 0)
78                 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
79
80         if (fd < 0)
81                 return I_ERR_SOCKET;
82
83         if (bind.sa.sa_family != 0)
84         {
85                 if (SocketEngine::Bind(fd, bind) < 0)
86                         return I_ERR_BIND;
87         }
88
89         SocketEngine::NonBlocking(fd);
90
91         if (SocketEngine::Connect(this, &dest.sa, dest.sa_size()) == -1)
92         {
93                 if (errno != EINPROGRESS)
94                         return I_ERR_CONNECT;
95         }
96
97         this->state = I_CONNECTING;
98
99         if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
100                 return I_ERR_NOMOREFDS;
101
102         this->Timeout = new SocketTimeout(this->GetFd(), this, timeout);
103         ServerInstance->Timers.AddTimer(this->Timeout);
104
105         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
106         return I_ERR_NONE;
107 }
108
109 void StreamSocket::Close()
110 {
111         if (this->fd > -1)
112         {
113                 // final chance, dump as much of the sendq as we can
114                 DoWrite();
115                 if (GetIOHook())
116                 {
117                         GetIOHook()->OnStreamSocketClose(this);
118                         delete iohook;
119                         DelIOHook();
120                 }
121                 SocketEngine::Shutdown(this, 2);
122                 SocketEngine::Close(this);
123         }
124 }
125
126 CullResult StreamSocket::cull()
127 {
128         Close();
129         return EventHandler::cull();
130 }
131
132 bool StreamSocket::GetNextLine(std::string& line, char delim)
133 {
134         std::string::size_type i = recvq.find(delim);
135         if (i == std::string::npos)
136                 return false;
137         line.assign(recvq, 0, i);
138         recvq.erase(0, i + 1);
139         return true;
140 }
141
142 void StreamSocket::DoRead()
143 {
144         if (GetIOHook())
145         {
146                 int rv = GetIOHook()->OnStreamSocketRead(this, recvq);
147                 if (rv > 0)
148                         OnDataReady();
149                 if (rv < 0)
150                         SetError("Read Error"); // will not overwrite a better error message
151         }
152         else
153         {
154                 char* ReadBuffer = ServerInstance->GetReadBuffer();
155                 int n = SocketEngine::Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
156                 if (n == ServerInstance->Config->NetBufferSize)
157                 {
158                         SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
159                         recvq.append(ReadBuffer, n);
160                         OnDataReady();
161                 }
162                 else if (n > 0)
163                 {
164                         SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ);
165                         recvq.append(ReadBuffer, n);
166                         OnDataReady();
167                 }
168                 else if (n == 0)
169                 {
170                         error = "Connection closed";
171                         SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
172                 }
173                 else if (SocketEngine::IgnoreError())
174                 {
175                         SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
176                 }
177                 else if (errno == EINTR)
178                 {
179                         SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
180                 }
181                 else
182                 {
183                         error = SocketEngine::LastError();
184                         SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
185                 }
186         }
187 }
188
189 /* Don't try to prepare huge blobs of data to send to a blocked socket */
190 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
191
192 void StreamSocket::DoWrite()
193 {
194         if (sendq.empty())
195                 return;
196         if (!error.empty() || fd < 0)
197         {
198                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
199                 return;
200         }
201
202         if (GetIOHook())
203         {
204                 {
205                         while (error.empty() && !sendq.empty())
206                         {
207                                 if (sendq.size() > 1 && sendq[0].length() < 1024)
208                                 {
209                                         // Avoid multiple repeated SSL encryption invocations
210                                         // This adds a single copy of the queue, but avoids
211                                         // much more overhead in terms of system calls invoked
212                                         // by the IOHook.
213                                         //
214                                         // The length limit of 1024 is to prevent merging strings
215                                         // more than once when writes begin to block.
216                                         std::string tmp;
217                                         tmp.reserve(1280);
218                                         while (!sendq.empty() && tmp.length() < 1024)
219                                         {
220                                                 tmp.append(sendq.front());
221                                                 sendq.pop_front();
222                                         }
223                                         sendq.push_front(tmp);
224                                 }
225                                 std::string& front = sendq.front();
226                                 int itemlen = front.length();
227
228                                 {
229                                         int rv = GetIOHook()->OnStreamSocketWrite(this, front);
230                                         if (rv > 0)
231                                         {
232                                                 // consumed the entire string, and is ready for more
233                                                 sendq_len -= itemlen;
234                                                 sendq.pop_front();
235                                         }
236                                         else if (rv == 0)
237                                         {
238                                                 // socket has blocked. Stop trying to send data.
239                                                 // IOHook has requested unblock notification from the socketengine
240
241                                                 // Since it is possible that a partial write took place, adjust sendq_len
242                                                 sendq_len = sendq_len - itemlen + front.length();
243                                                 return;
244                                         }
245                                         else
246                                         {
247                                                 SetError("Write Error"); // will not overwrite a better error message
248                                                 return;
249                                         }
250                                 }
251                         }
252                 }
253         }
254         else
255         {
256                 // don't even try if we are known to be blocking
257                 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
258                         return;
259                 // start out optimistic - we won't need to write any more
260                 int eventChange = FD_WANT_EDGE_WRITE;
261                 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
262                 {
263                         // Prepare a writev() call to write all buffers efficiently
264                         int bufcount = sendq.size();
265
266                         // cap the number of buffers at MYIOV_MAX
267                         if (bufcount > MYIOV_MAX)
268                         {
269                                 bufcount = MYIOV_MAX;
270                         }
271
272                         int rv_max = 0;
273                         int rv;
274                         {
275                                 SocketEngine::IOVector iovecs[MYIOV_MAX];
276                                 for (int i = 0; i < bufcount; i++)
277                                 {
278                                         iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
279                                         iovecs[i].iov_len = sendq[i].length();
280                                         rv_max += sendq[i].length();
281                                 }
282                                 rv = SocketEngine::WriteV(this, iovecs, bufcount);
283                         }
284
285                         if (rv == (int)sendq_len)
286                         {
287                                 // it's our lucky day, everything got written out. Fast cleanup.
288                                 // This won't ever happen if the number of buffers got capped.
289                                 sendq_len = 0;
290                                 sendq.clear();
291                         }
292                         else if (rv > 0)
293                         {
294                                 // Partial write. Clean out strings from the sendq
295                                 if (rv < rv_max)
296                                 {
297                                         // it's going to block now
298                                         eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
299                                 }
300                                 sendq_len -= rv;
301                                 while (rv > 0 && !sendq.empty())
302                                 {
303                                         std::string& front = sendq.front();
304                                         if (front.length() <= (size_t)rv)
305                                         {
306                                                 // this string got fully written out
307                                                 rv -= front.length();
308                                                 sendq.pop_front();
309                                         }
310                                         else
311                                         {
312                                                 // stopped in the middle of this string
313                                                 front.erase(0, rv);
314                                                 rv = 0;
315                                         }
316                                 }
317                         }
318                         else if (rv == 0)
319                         {
320                                 error = "Connection closed";
321                         }
322                         else if (SocketEngine::IgnoreError())
323                         {
324                                 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
325                         }
326                         else if (errno == EINTR)
327                         {
328                                 // restart interrupted syscall
329                                 errno = 0;
330                         }
331                         else
332                         {
333                                 error = SocketEngine::LastError();
334                         }
335                 }
336                 if (!error.empty())
337                 {
338                         // error - kill all events
339                         SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
340                 }
341                 else
342                 {
343                         SocketEngine::ChangeEventMask(this, eventChange);
344                 }
345         }
346 }
347
348 void StreamSocket::WriteData(const std::string &data)
349 {
350         if (fd < 0)
351         {
352                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
353                         data.c_str());
354                 return;
355         }
356
357         /* Append the data to the back of the queue ready for writing */
358         sendq.push_back(data);
359         sendq_len += data.length();
360
361         SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
362 }
363
364 bool SocketTimeout::Tick(time_t)
365 {
366         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
367
368         if (SocketEngine::GetRef(this->sfd) != this->sock)
369         {
370                 delete this;
371                 return false;
372         }
373
374         if (this->sock->state == I_CONNECTING)
375         {
376                 // for connecting sockets, the timeout can occur
377                 // which causes termination of the connection after
378                 // the given number of seconds without a successful
379                 // connection.
380                 this->sock->OnTimeout();
381                 this->sock->OnError(I_ERR_TIMEOUT);
382                 this->sock->state = I_ERROR;
383
384                 ServerInstance->GlobalCulls.AddItem(sock);
385         }
386
387         this->sock->Timeout = NULL;
388         delete this;
389         return false;
390 }
391
392 void BufferedSocket::OnConnected() { }
393 void BufferedSocket::OnTimeout() { return; }
394
395 void BufferedSocket::OnEventHandlerWrite()
396 {
397         if (state == I_CONNECTING)
398         {
399                 state = I_CONNECTED;
400                 this->OnConnected();
401                 if (!GetIOHook())
402                         SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
403         }
404         this->StreamSocket::OnEventHandlerWrite();
405 }
406
407 BufferedSocket::~BufferedSocket()
408 {
409         this->Close();
410         // The timer is removed from the TimerManager in Timer::~Timer()
411         delete Timeout;
412 }
413
414 void StreamSocket::OnEventHandlerError(int errornum)
415 {
416         if (!error.empty())
417                 return;
418
419         if (errornum == 0)
420                 SetError("Connection closed");
421         else
422                 SetError(SocketEngine::GetError(errornum));
423
424         BufferedSocketError errcode = I_ERR_OTHER;
425         switch (errornum)
426         {
427                 case ETIMEDOUT:
428                         errcode = I_ERR_TIMEOUT;
429                         break;
430                 case ECONNREFUSED:
431                 case 0:
432                         errcode = I_ERR_CONNECT;
433                         break;
434                 case EADDRINUSE:
435                         errcode = I_ERR_BIND;
436                         break;
437                 case EPIPE:
438                 case EIO:
439                         errcode = I_ERR_WRITE;
440                         break;
441         }
442
443         // Log and call OnError()
444         CheckError(errcode);
445 }
446
447 void StreamSocket::OnEventHandlerRead()
448 {
449         if (!error.empty())
450                 return;
451
452         try
453         {
454                 DoRead();
455         }
456         catch (CoreException& ex)
457         {
458                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'", fd, ex.GetReason().c_str());
459                 SetError(ex.GetReason());
460         }
461         CheckError(I_ERR_OTHER);
462 }
463
464 void StreamSocket::OnEventHandlerWrite()
465 {
466         if (!error.empty())
467                 return;
468
469         DoWrite();
470         CheckError(I_ERR_OTHER);
471 }
472
473 void StreamSocket::CheckError(BufferedSocketError errcode)
474 {
475         if (!error.empty())
476         {
477                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
478                 OnError(errcode);
479         }
480 }