]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Remove pointless fd == INT_MAX check from StreamSocket::DoWrite()
[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                         iovec* iovecs = new iovec[bufcount];
343                         for(int i=0; i < bufcount; i++)
344                         {
345                                 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
346                                 iovecs[i].iov_len = sendq[i].length();
347                                 rv_max += sendq[i].length();
348                         }
349                         int rv = writev(fd, iovecs, bufcount);
350                         delete[] iovecs;
351
352                         if (rv == (int)sendq_len)
353                         {
354                                 // it's our lucky day, everything got written out. Fast cleanup.
355                                 // This won't ever happen if the number of buffers got capped.
356                                 sendq_len = 0;
357                                 sendq.clear();
358                         }
359                         else if (rv > 0)
360                         {
361                                 // Partial write. Clean out strings from the sendq
362                                 if (rv < rv_max)
363                                 {
364                                         // it's going to block now
365                                         eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
366                                 }
367                                 sendq_len -= rv;
368                                 while (rv > 0 && !sendq.empty())
369                                 {
370                                         std::string& front = sendq.front();
371                                         if (front.length() <= (size_t)rv)
372                                         {
373                                                 // this string got fully written out
374                                                 rv -= front.length();
375                                                 sendq.pop_front();
376                                         }
377                                         else
378                                         {
379                                                 // stopped in the middle of this string
380                                                 front.erase(0, rv);
381                                                 rv = 0;
382                                         }
383                                 }
384                         }
385                         else if (rv == 0)
386                         {
387                                 error = "Connection closed";
388                         }
389                         else if (SocketEngine::IgnoreError())
390                         {
391                                 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
392                         }
393                         else if (errno == EINTR)
394                         {
395                                 // restart interrupted syscall
396                                 errno = 0;
397                         }
398                         else
399                         {
400                                 error = SocketEngine::LastError();
401                         }
402                 }
403                 if (!error.empty())
404                 {
405                         // error - kill all events
406                         SocketEngine::ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
407                 }
408                 else
409                 {
410                         SocketEngine::ChangeEventMask(this, eventChange);
411                 }
412         }
413 #endif
414 }
415
416 void StreamSocket::WriteData(const std::string &data)
417 {
418         if (fd < 0)
419         {
420                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to write data to dead socket: %s",
421                         data.c_str());
422                 return;
423         }
424
425         /* Append the data to the back of the queue ready for writing */
426         sendq.push_back(data);
427         sendq_len += data.length();
428
429         SocketEngine::ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
430 }
431
432 bool SocketTimeout::Tick(time_t)
433 {
434         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SocketTimeout::Tick");
435
436         if (SocketEngine::GetRef(this->sfd) != this->sock)
437         {
438                 delete this;
439                 return false;
440         }
441
442         if (this->sock->state == I_CONNECTING)
443         {
444                 // for connecting sockets, the timeout can occur
445                 // which causes termination of the connection after
446                 // the given number of seconds without a successful
447                 // connection.
448                 this->sock->OnTimeout();
449                 this->sock->OnError(I_ERR_TIMEOUT);
450                 this->sock->state = I_ERROR;
451
452                 ServerInstance->GlobalCulls.AddItem(sock);
453         }
454
455         this->sock->Timeout = NULL;
456         delete this;
457         return false;
458 }
459
460 void BufferedSocket::OnConnected() { }
461 void BufferedSocket::OnTimeout() { return; }
462
463 void BufferedSocket::DoWrite()
464 {
465         if (state == I_CONNECTING)
466         {
467                 state = I_CONNECTED;
468                 this->OnConnected();
469                 if (!GetIOHook())
470                         SocketEngine::ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
471         }
472         this->StreamSocket::DoWrite();
473 }
474
475 BufferedSocket::~BufferedSocket()
476 {
477         this->Close();
478         // The timer is removed from the TimerManager in Timer::~Timer()
479         delete Timeout;
480 }
481
482 void StreamSocket::HandleEvent(EventType et, int errornum)
483 {
484         if (!error.empty())
485                 return;
486         BufferedSocketError errcode = I_ERR_OTHER;
487         try {
488                 switch (et)
489                 {
490                         case EVENT_ERROR:
491                         {
492                                 if (errornum == 0)
493                                         SetError("Connection closed");
494                                 else
495                                         SetError(SocketEngine::GetError(errornum));
496                                 switch (errornum)
497                                 {
498                                         case ETIMEDOUT:
499                                                 errcode = I_ERR_TIMEOUT;
500                                                 break;
501                                         case ECONNREFUSED:
502                                         case 0:
503                                                 errcode = I_ERR_CONNECT;
504                                                 break;
505                                         case EADDRINUSE:
506                                                 errcode = I_ERR_BIND;
507                                                 break;
508                                         case EPIPE:
509                                         case EIO:
510                                                 errcode = I_ERR_WRITE;
511                                                 break;
512                                 }
513                                 break;
514                         }
515                         case EVENT_READ:
516                         {
517                                 DoRead();
518                                 break;
519                         }
520                         case EVENT_WRITE:
521                         {
522                                 DoWrite();
523                                 break;
524                         }
525                 }
526         }
527         catch (CoreException& ex)
528         {
529                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
530                         fd, ex.GetReason().c_str());
531                 SetError(ex.GetReason());
532         }
533         if (!error.empty())
534         {
535                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
536                 OnError(errcode);
537         }
538 }