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