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