]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Fix mistakenly using Clang instead of GCC on older FreeBSD versions.
[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(SocketEngine::LastError());
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", 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, sa_size(dest)) == -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", 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", 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", 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 = SocketEngine::LastError();
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", 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(1280);
252                                         while (!sendq.empty() && tmp.length() < 1024)
253                                         {
254                                                 tmp.append(sendq.front());
255                                                 sendq.pop_front();
256                                         }
257                                         sendq.push_front(tmp);
258                                 }
259                                 std::string& front = sendq.front();
260                                 int itemlen = front.length();
261                                 if (IOHook)
262                                 {
263                                         rv = IOHook->OnStreamSocketWrite(this, front);
264                                         if (rv > 0)
265                                         {
266                                                 // consumed the entire string, and is ready for more
267                                                 sendq_len -= itemlen;
268                                                 sendq.pop_front();
269                                         }
270                                         else if (rv == 0)
271                                         {
272                                                 // socket has blocked. Stop trying to send data.
273                                                 // IOHook has requested unblock notification from the socketengine
274
275                                                 // Since it is possible that a partial write took place, adjust sendq_len
276                                                 sendq_len = sendq_len - itemlen + front.length();
277                                                 return;
278                                         }
279                                         else
280                                         {
281                                                 SetError("Write Error"); // will not overwrite a better error message
282                                                 return;
283                                         }
284                                 }
285 #ifdef DISABLE_WRITEV
286                                 else
287                                 {
288                                         rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
289                                         if (rv == 0)
290                                         {
291                                                 SetError("Connection closed");
292                                                 return;
293                                         }
294                                         else if (rv < 0)
295                                         {
296                                                 if (errno == EINTR || SocketEngine::IgnoreError())
297                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
298                                                 else
299                                                         SetError(SocketEngine::LastError());
300                                                 return;
301                                         }
302                                         else if (rv < itemlen)
303                                         {
304                                                 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
305                                                 front = front.substr(rv);
306                                                 sendq_len -= rv;
307                                                 return;
308                                         }
309                                         else
310                                         {
311                                                 sendq_len -= itemlen;
312                                                 sendq.pop_front();
313                                                 if (sendq.empty())
314                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
315                                         }
316                                 }
317 #endif
318                         }
319                 }
320                 catch (CoreException& modexcept)
321                 {
322                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
323                                 modexcept.GetSource(), modexcept.GetReason());
324                 }
325         }
326 #ifndef DISABLE_WRITEV
327         else
328         {
329                 // don't even try if we are known to be blocking
330                 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
331                         return;
332                 // start out optimistic - we won't need to write any more
333                 int eventChange = FD_WANT_EDGE_WRITE;
334                 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
335                 {
336                         // Prepare a writev() call to write all buffers efficiently
337                         int bufcount = sendq.size();
338
339                         // cap the number of buffers at MYIOV_MAX
340                         if (bufcount > MYIOV_MAX)
341                         {
342                                 bufcount = MYIOV_MAX;
343                         }
344
345                         int rv_max = 0;
346                         iovec* iovecs = new iovec[bufcount];
347                         for(int i=0; i < bufcount; i++)
348                         {
349                                 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
350                                 iovecs[i].iov_len = sendq[i].length();
351                                 rv_max += sendq[i].length();
352                         }
353                         int rv = writev(fd, iovecs, bufcount);
354                         delete[] iovecs;
355
356                         if (rv == (int)sendq_len)
357                         {
358                                 // it's our lucky day, everything got written out. Fast cleanup.
359                                 // This won't ever happen if the number of buffers got capped.
360                                 sendq_len = 0;
361                                 sendq.clear();
362                         }
363                         else if (rv > 0)
364                         {
365                                 // Partial write. Clean out strings from the sendq
366                                 if (rv < rv_max)
367                                 {
368                                         // it's going to block now
369                                         eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
370                                 }
371                                 sendq_len -= rv;
372                                 while (rv > 0 && !sendq.empty())
373                                 {
374                                         std::string& front = sendq.front();
375                                         if (front.length() <= (size_t)rv)
376                                         {
377                                                 // this string got fully written out
378                                                 rv -= front.length();
379                                                 sendq.pop_front();
380                                         }
381                                         else
382                                         {
383                                                 // stopped in the middle of this string
384                                                 front = front.substr(rv);
385                                                 rv = 0;
386                                         }
387                                 }
388                         }
389                         else if (rv == 0)
390                         {
391                                 error = "Connection closed";
392                         }
393                         else if (SocketEngine::IgnoreError())
394                         {
395                                 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
396                         }
397                         else if (errno == EINTR)
398                         {
399                                 // restart interrupted syscall
400                                 errno = 0;
401                         }
402                         else
403                         {
404                                 error = SocketEngine::LastError();
405                         }
406                 }
407                 if (!error.empty())
408                 {
409                         // error - kill all events
410                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
411                 }
412                 else
413                 {
414                         ServerInstance->SE->ChangeEventMask(this, eventChange);
415                 }
416         }
417 #endif
418 }
419
420 void StreamSocket::WriteData(const std::string &data)
421 {
422         if (fd < 0)
423         {
424                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
425                         data.c_str());
426                 return;
427         }
428
429         /* Append the data to the back of the queue ready for writing */
430         sendq.push_back(data);
431         sendq_len += data.length();
432
433         ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
434 }
435
436 void SocketTimeout::Tick(time_t)
437 {
438         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
439
440         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
441                 return;
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 }
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                 ServerInstance->Timers->DelTimer(Timeout);
482                 Timeout = NULL;
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", 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", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
540                 OnError(errcode);
541         }
542 }
543