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