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