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