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