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