]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Merge pull request #545 from SaberUK/master+logging-cleanup
[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
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", LOG_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 BufferedSocketError BufferedSocket::BeginConnect(const irc::sockets::sockaddrs& dest, const irc::sockets::sockaddrs& bind, unsigned long timeout)
86 {
87         if (fd < 0)
88                 fd = socket(dest.sa.sa_family, SOCK_STREAM, 0);
89
90         if (fd < 0)
91                 return I_ERR_SOCKET;
92
93         if (bind.sa.sa_family != 0)
94         {
95                 if (ServerInstance->SE->Bind(fd, bind) < 0)
96                         return I_ERR_BIND;
97         }
98
99         ServerInstance->SE->NonBlocking(fd);
100
101         if (ServerInstance->SE->Connect(this, &dest.sa, dest.sa_size()) == -1)
102         {
103                 if (errno != EINPROGRESS)
104                         return I_ERR_CONNECT;
105         }
106
107         this->state = I_CONNECTING;
108
109         if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE | FD_WRITE_WILL_BLOCK))
110                 return I_ERR_NOMOREFDS;
111
112         this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
113         ServerInstance->Timers->AddTimer(this->Timeout);
114
115         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "BufferedSocket::DoConnect success");
116         return I_ERR_NONE;
117 }
118
119 void StreamSocket::Close()
120 {
121         if (this->fd > -1)
122         {
123                 // final chance, dump as much of the sendq as we can
124                 DoWrite();
125                 if (IOHook)
126                 {
127                         try
128                         {
129                                 IOHook->OnStreamSocketClose(this);
130                         }
131                         catch (CoreException& modexcept)
132                         {
133                                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
134                                         modexcept.GetSource(), modexcept.GetReason());
135                         }
136                         IOHook = NULL;
137                 }
138                 ServerInstance->SE->Shutdown(this, 2);
139                 ServerInstance->SE->DelFd(this);
140                 ServerInstance->SE->Close(this);
141                 fd = -1;
142         }
143 }
144
145 CullResult StreamSocket::cull()
146 {
147         Close();
148         return EventHandler::cull();
149 }
150
151 bool StreamSocket::GetNextLine(std::string& line, char delim)
152 {
153         std::string::size_type i = recvq.find(delim);
154         if (i == std::string::npos)
155                 return false;
156         line = recvq.substr(0, i);
157         // TODO is this the most efficient way to split?
158         recvq = recvq.substr(i + 1);
159         return true;
160 }
161
162 void StreamSocket::DoRead()
163 {
164         if (IOHook)
165         {
166                 int rv = -1;
167                 try
168                 {
169                         rv = IOHook->OnStreamSocketRead(this, recvq);
170                 }
171                 catch (CoreException& modexcept)
172                 {
173                         ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
174                                 modexcept.GetSource(), modexcept.GetReason());
175                         return;
176                 }
177                 if (rv > 0)
178                         OnDataReady();
179                 if (rv < 0)
180                         SetError("Read Error"); // will not overwrite a better error message
181         }
182         else
183         {
184                 char* ReadBuffer = ServerInstance->GetReadBuffer();
185                 int n = ServerInstance->SE->Recv(this, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
186                 if (n == ServerInstance->Config->NetBufferSize)
187                 {
188                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
189                         recvq.append(ReadBuffer, n);
190                         OnDataReady();
191                 }
192                 else if (n > 0)
193                 {
194                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
195                         recvq.append(ReadBuffer, n);
196                         OnDataReady();
197                 }
198                 else if (n == 0)
199                 {
200                         error = "Connection closed";
201                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
202                 }
203                 else if (SocketEngine::IgnoreError())
204                 {
205                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
206                 }
207                 else if (errno == EINTR)
208                 {
209                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
210                 }
211                 else
212                 {
213                         error = strerror(errno);
214                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
215                 }
216         }
217 }
218
219 /* Don't try to prepare huge blobs of data to send to a blocked socket */
220 static const int MYIOV_MAX = IOV_MAX < 128 ? IOV_MAX : 128;
221
222 void StreamSocket::DoWrite()
223 {
224         if (sendq.empty())
225                 return;
226         if (!error.empty() || fd < 0 || fd == INT_MAX)
227         {
228                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DoWrite on errored or closed socket");
229                 return;
230         }
231
232 #ifndef DISABLE_WRITEV
233         if (IOHook)
234 #endif
235         {
236                 int rv = -1;
237                 try
238                 {
239                         while (error.empty() && !sendq.empty())
240                         {
241                                 if (sendq.size() > 1 && sendq[0].length() < 1024)
242                                 {
243                                         // Avoid multiple repeated SSL encryption invocations
244                                         // This adds a single copy of the queue, but avoids
245                                         // much more overhead in terms of system calls invoked
246                                         // by the IOHook.
247                                         //
248                                         // The length limit of 1024 is to prevent merging strings
249                                         // more than once when writes begin to block.
250                                         std::string tmp;
251                                         tmp.reserve(sendq_len);
252                                         for(unsigned int i=0; i < sendq.size(); i++)
253                                                 tmp.append(sendq[i]);
254                                         sendq.clear();
255                                         sendq.push_back(tmp);
256                                 }
257                                 std::string& front = sendq.front();
258                                 int itemlen = front.length();
259                                 if (IOHook)
260                                 {
261                                         rv = IOHook->OnStreamSocketWrite(this, front);
262                                         if (rv > 0)
263                                         {
264                                                 // consumed the entire string, and is ready for more
265                                                 sendq_len -= itemlen;
266                                                 sendq.pop_front();
267                                         }
268                                         else if (rv == 0)
269                                         {
270                                                 // socket has blocked. Stop trying to send data.
271                                                 // IOHook has requested unblock notification from the socketengine
272
273                                                 // Since it is possible that a partial write took place, adjust sendq_len
274                                                 sendq_len = sendq_len - itemlen + front.length();
275                                                 return;
276                                         }
277                                         else
278                                         {
279                                                 SetError("Write Error"); // will not overwrite a better error message
280                                                 return;
281                                         }
282                                 }
283 #ifdef DISABLE_WRITEV
284                                 else
285                                 {
286                                         rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
287                                         if (rv == 0)
288                                         {
289                                                 SetError("Connection closed");
290                                                 return;
291                                         }
292                                         else if (rv < 0)
293                                         {
294                                                 if (errno == EINTR || SocketEngine::IgnoreError())
295                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
296                                                 else
297                                                         SetError(strerror(errno));
298                                                 return;
299                                         }
300                                         else if (rv < itemlen)
301                                         {
302                                                 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
303                                                 front = front.substr(rv);
304                                                 sendq_len -= rv;
305                                                 return;
306                                         }
307                                         else
308                                         {
309                                                 sendq_len -= itemlen;
310                                                 sendq.pop_front();
311                                                 if (sendq.empty())
312                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
313                                         }
314                                 }
315 #endif
316                         }
317                 }
318                 catch (CoreException& modexcept)
319                 {
320                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "%s threw an exception: %s",
321                                 modexcept.GetSource(), modexcept.GetReason());
322                 }
323         }
324 #ifndef DISABLE_WRITEV
325         else
326         {
327                 // don't even try if we are known to be blocking
328                 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
329                         return;
330                 // start out optimistic - we won't need to write any more
331                 int eventChange = FD_WANT_EDGE_WRITE;
332                 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
333                 {
334                         // Prepare a writev() call to write all buffers efficiently
335                         int bufcount = sendq.size();
336
337                         // cap the number of buffers at MYIOV_MAX
338                         if (bufcount > MYIOV_MAX)
339                         {
340                                 bufcount = MYIOV_MAX;
341                         }
342
343                         int rv_max = 0;
344                         iovec* iovecs = new iovec[bufcount];
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                         int rv = writev(fd, iovecs, bufcount);
352                         delete[] iovecs;
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 = front.substr(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 = strerror(errno);
403                         }
404                 }
405                 if (!error.empty())
406                 {
407                         // error - kill all events
408                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
409                 }
410                 else
411                 {
412                         ServerInstance->SE->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         ServerInstance->SE->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 (ServerInstance->SE->GetRef(this->sfd) != this->sock)
439                 return false;
440
441         if (this->sock->state == I_CONNECTING)
442         {
443                 // for connecting sockets, the timeout can occur
444                 // which causes termination of the connection after
445                 // the given number of seconds without a successful
446                 // connection.
447                 this->sock->OnTimeout();
448                 this->sock->OnError(I_ERR_TIMEOUT);
449                 this->sock->state = I_ERROR;
450
451                 ServerInstance->GlobalCulls.AddItem(sock);
452         }
453
454         this->sock->Timeout = NULL;
455         return false;
456 }
457
458 void BufferedSocket::OnConnected() { }
459 void BufferedSocket::OnTimeout() { return; }
460
461 void BufferedSocket::DoWrite()
462 {
463         if (state == I_CONNECTING)
464         {
465                 state = I_CONNECTED;
466                 this->OnConnected();
467                 if (GetIOHook())
468                         GetIOHook()->OnStreamSocketConnect(this);
469                 else
470                         ServerInstance->SE->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         if (Timeout)
479         {
480                 // The timer is removed from the TimerManager in Timer::~Timer()
481                 delete Timeout;
482         }
483 }
484
485 void StreamSocket::HandleEvent(EventType et, int errornum)
486 {
487         if (!error.empty())
488                 return;
489         BufferedSocketError errcode = I_ERR_OTHER;
490         try {
491                 switch (et)
492                 {
493                         case EVENT_ERROR:
494                         {
495                                 if (errornum == 0)
496                                         SetError("Connection closed");
497                                 else
498                                         SetError(strerror(errornum));
499                                 switch (errornum)
500                                 {
501                                         case ETIMEDOUT:
502                                                 errcode = I_ERR_TIMEOUT;
503                                                 break;
504                                         case ECONNREFUSED:
505                                         case 0:
506                                                 errcode = I_ERR_CONNECT;
507                                                 break;
508                                         case EADDRINUSE:
509                                                 errcode = I_ERR_BIND;
510                                                 break;
511                                         case EPIPE:
512                                         case EIO:
513                                                 errcode = I_ERR_WRITE;
514                                                 break;
515                                 }
516                                 break;
517                         }
518                         case EVENT_READ:
519                         {
520                                 DoRead();
521                                 break;
522                         }
523                         case EVENT_WRITE:
524                         {
525                                 DoWrite();
526                                 break;
527                         }
528                 }
529         }
530         catch (CoreException& ex)
531         {
532                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
533                         fd, ex.GetReason());
534                 SetError(ex.GetReason());
535         }
536         if (!error.empty())
537         {
538                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
539                 OnError(errcode);
540         }
541 }
542