]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Make classbase and refcountbase uncopyable; expand comments on their indended uses
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "socket.h"
16 #include "inspstring.h"
17 #include "socketengine.h"
18
19 #ifndef DISABLE_WRITEV
20 #include <sys/uio.h>
21 #ifndef IOV_MAX
22 #define IOV_MAX 1024
23 #endif
24 #endif
25
26 BufferedSocket::BufferedSocket()
27 {
28         Timeout = NULL;
29         state = I_ERROR;
30 }
31
32 BufferedSocket::BufferedSocket(int newfd)
33 {
34         Timeout = NULL;
35         this->fd = newfd;
36         this->state = I_CONNECTED;
37         if (fd > -1)
38                 ServerInstance->SE->AddFd(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
39 }
40
41 void BufferedSocket::DoConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
42 {
43         BufferedSocketError err = BeginConnect(ipaddr, aport, maxtime, connectbindip);
44         if (err != I_ERR_NONE)
45         {
46                 state = I_ERROR;
47                 SetError(strerror(errno));
48                 OnError(err);
49         }
50 }
51
52 BufferedSocketError BufferedSocket::BeginConnect(const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
53 {
54         irc::sockets::sockaddrs addr, bind;
55         if (!irc::sockets::aptosa(ipaddr, aport, &addr))
56         {
57                 ServerInstance->Logs->Log("SOCKET", DEBUG, "BUG: Hostname passed to BufferedSocket, rather than an IP address!");
58                 return I_ERR_CONNECT;
59         }
60
61         bind.sa.sa_family = 0;
62         if (!connectbindip.empty())
63         {
64                 if (!irc::sockets::aptosa(connectbindip, 0, &bind))
65                 {
66                         return I_ERR_BIND;
67                 }
68         }
69
70         return BeginConnect(addr, bind, maxtime);
71 }
72
73 static void IncreaseOSBuffers(int fd)
74 {
75         // attempt to increase socket sendq and recvq as high as its possible
76         int sendbuf = 32768;
77         int recvbuf = 32768;
78         setsockopt(fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf));
79         setsockopt(fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(recvbuf));
80         // on failure, do nothing. I'm a little sick of people trying to interpret this message as a result of why their incorrect setups don't work.
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 (ServerInstance->SE->Bind(fd, &bind.sa, sa_size(bind)) < 0)
94                         return I_ERR_BIND;
95         }
96
97         ServerInstance->SE->NonBlocking(fd);
98
99         if (ServerInstance->SE->Connect(this, &dest.sa, sa_size(dest)) == -1)
100         {
101                 if (errno != EINPROGRESS)
102                         return I_ERR_CONNECT;
103         }
104
105         this->state = I_CONNECTING;
106
107         if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE))
108                 return I_ERR_NOMOREFDS;
109
110         this->Timeout = new SocketTimeout(this->GetFd(), this, timeout, ServerInstance->Time());
111         ServerInstance->Timers->AddTimer(this->Timeout);
112
113         IncreaseOSBuffers(fd);
114
115         ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
116         return I_ERR_NONE;
117 }
118
119 void StreamSocket::Close()
120 {
121         /* Save this, so we dont lose it,
122          * otherise on failure, error messages
123          * might be inaccurate.
124          */
125         int save = errno;
126         if (this->fd > -1)
127         {
128                 if (IOHook)
129                 {
130                         try
131                         {
132                                 IOHook->OnStreamSocketClose(this);
133                         }
134                         catch (CoreException& modexcept)
135                         {
136                                 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
137                                         modexcept.GetSource(), modexcept.GetReason());
138                         }
139                 }
140                 ServerInstance->SE->Shutdown(this, 2);
141                 ServerInstance->SE->DelFd(this);
142                 ServerInstance->SE->Close(this);
143                 fd = -1;
144         }
145         errno = save;
146 }
147
148 CullResult StreamSocket::cull()
149 {
150         Close();
151         return EventHandler::cull();
152 }
153
154 bool StreamSocket::GetNextLine(std::string& line, char delim)
155 {
156         std::string::size_type i = recvq.find(delim);
157         if (i == std::string::npos)
158                 return false;
159         line = recvq.substr(0, i - 1);
160         // TODO is this the most efficient way to split?
161         recvq = recvq.substr(i + 1);
162         return true;
163 }
164
165 void StreamSocket::DoRead()
166 {
167         if (IOHook)
168         {
169                 int rv = -1;
170                 try
171                 {
172                         rv = IOHook->OnStreamSocketRead(this, recvq);
173                 }
174                 catch (CoreException& modexcept)
175                 {
176                         ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
177                                 modexcept.GetSource(), modexcept.GetReason());
178                         return;
179                 }
180                 if (rv > 0)
181                         OnDataReady();
182                 if (rv < 0)
183                         SetError("Read Error"); // will not overwrite a better error message
184         }
185         else
186         {
187                 char* ReadBuffer = ServerInstance->GetReadBuffer();
188                 int n = recv(fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
189                 if (n == ServerInstance->Config->NetBufferSize)
190                 {
191                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
192                         recvq.append(ReadBuffer, n);
193                         OnDataReady();
194                 }
195                 else if (n > 0)
196                 {
197                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
198                         recvq.append(ReadBuffer, n);
199                         OnDataReady();
200                 }
201                 else if (n == 0)
202                 {
203                         error = "Connection closed";
204                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
205                 }
206                 else if (errno == EAGAIN)
207                 {
208                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
209                 }
210                 else if (errno == EINTR)
211                 {
212                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
213                 }
214                 else
215                 {
216                         error = strerror(errno);
217                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
218                 }
219         }
220 }
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 (!sendq.empty())
240                         {
241                                 if (sendq.size() > 1 && sendq[0].length() < 1024)
242                                 {
243                                         // Avoid multiple repeated SSL encryption invocations
244                                         // This adds a single copy of the queue, but avoids
245                                         // much more overhead in terms of system calls invoked
246                                         // by the IOHook.
247                                         //
248                                         // The length limit of 1024 is to prevent merging strings
249                                         // more than once when writes begin to block.
250                                         std::string tmp;
251                                         tmp.reserve(sendq_len);
252                                         for(unsigned int i=0; i < sendq.size(); i++)
253                                                 tmp.append(sendq[i]);
254                                         sendq.clear();
255                                         sendq.push_back(tmp);
256                                 }
257                                 std::string& front = sendq.front();
258                                 int itemlen = front.length();
259                                 if (IOHook)
260                                 {
261                                         rv = IOHook->OnStreamSocketWrite(this, front);
262                                         if (rv > 0)
263                                         {
264                                                 // consumed the entire string, and is ready for more
265                                                 sendq_len -= itemlen;
266                                                 sendq.pop_front();
267                                         }
268                                         else if (rv == 0)
269                                         {
270                                                 // socket has blocked. Stop trying to send data.
271                                                 // IOHook has requested unblock notification from the socketengine
272
273                                                 // Since it is possible that a partial write took place, adjust sendq_len
274                                                 sendq_len = sendq_len - itemlen + front.length();
275                                                 return;
276                                         }
277                                         else
278                                         {
279                                                 SetError("Write Error"); // will not overwrite a better error message
280                                                 return;
281                                         }
282                                 }
283 #ifdef DISABLE_WRITEV
284                                 else
285                                 {
286                                         rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
287                                         if (rv == 0)
288                                         {
289                                                 SetError("Connection closed");
290                                                 return;
291                                         }
292                                         else if (rv < 0)
293                                         {
294                                                 if (errno == EAGAIN || errno == EINTR)
295                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
296                                                 else
297                                                         SetError(strerror(errno));
298                                                 return;
299                                         }
300                                         else if (rv < itemlen)
301                                         {
302                                                 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
303                                                 front = front.substr(itemlen - rv);
304                                                 sendq_len -= rv;
305                                                 return;
306                                         }
307                                         else
308                                         {
309                                                 sendq_len -= itemlen;
310                                                 sendq.pop_front();
311                                                 if (sendq.empty())
312                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
313                                         }
314                                 }
315 #endif
316                         }
317                 }
318                 catch (CoreException& modexcept)
319                 {
320                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
321                                 modexcept.GetSource(), modexcept.GetReason());
322                 }
323         }
324 #ifndef DISABLE_WRITEV
325         else
326         {
327                 // don't even try if we are known to be blocking
328                 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
329                         return;
330                 // start out optimistic - we won't need to write any more
331                 int eventChange = FD_WANT_EDGE_WRITE;
332                 while (sendq_len && eventChange == FD_WANT_EDGE_WRITE)
333                 {
334                         // Prepare a writev() call to write all buffers efficiently
335                         int bufcount = sendq.size();
336                 
337                         // cap the number of buffers at IOV_MAX
338                         if (bufcount > IOV_MAX)
339                         {
340                                 bufcount = IOV_MAX;
341                         }
342
343                         int rv_max = 0;
344                         iovec* iovecs = new iovec[bufcount];
345                         for(int i=0; i < bufcount; i++)
346                         {
347                                 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
348                                 iovecs[i].iov_len = sendq[i].length();
349                                 rv_max += sendq[i].length();
350                         }
351                         int rv = writev(fd, iovecs, bufcount);
352                         delete[] iovecs;
353
354                         if (rv == (int)sendq_len)
355                         {
356                                 // it's our lucky day, everything got written out. Fast cleanup.
357                                 // This won't ever happen if the number of buffers got capped.
358                                 sendq_len = 0;
359                                 sendq.clear();
360                         }
361                         else if (rv > 0)
362                         {
363                                 // Partial write. Clean out strings from the sendq
364                                 if (rv < rv_max)
365                                 {
366                                         // it's going to block now
367                                         eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
368                                 }
369                                 sendq_len -= rv;
370                                 while (rv > 0 && !sendq.empty())
371                                 {
372                                         std::string& front = sendq.front();
373                                         if (front.length() <= (size_t)rv)
374                                         {
375                                                 // this string got fully written out
376                                                 rv -= front.length();
377                                                 sendq.pop_front();
378                                         }
379                                         else
380                                         {
381                                                 // stopped in the middle of this string
382                                                 front = front.substr(rv);
383                                                 rv = 0;
384                                         }
385                                 }
386                         }
387                         else if (rv == 0)
388                         {
389                                 error = "Connection closed";
390                         }
391                         else if (errno == EAGAIN)
392                         {
393                                 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
394                         }
395                         else if (errno == EINTR)
396                         {
397                                 // restart interrupted syscall
398                         }
399                         else
400                         {
401                                 error = strerror(errno);
402                         }
403                 }
404                 if (!error.empty())
405                 {
406                         // error - kill all events
407                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
408                 }
409                 else
410                 {
411                         ServerInstance->SE->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", 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         ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
431 }
432
433 void SocketTimeout::Tick(time_t)
434 {
435         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
436
437         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
438                 return;
439
440         if (this->sock->state == I_CONNECTING)
441         {
442                 // for connecting sockets, the timeout can occur
443                 // which causes termination of the connection after
444                 // the given number of seconds without a successful
445                 // connection.
446                 this->sock->OnTimeout();
447                 this->sock->OnError(I_ERR_TIMEOUT);
448
449                 /* NOTE: We must set this AFTER DelFd, as we added
450                  * this socket whilst writeable. This means that we
451                  * must DELETE the socket whilst writeable too!
452                  */
453                 this->sock->state = I_ERROR;
454
455                 ServerInstance->GlobalCulls.AddItem(sock);
456         }
457
458         this->sock->Timeout = NULL;
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                         GetIOHook()->OnStreamSocketConnect(this);
472                 else
473                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
474         }
475         this->StreamSocket::DoWrite();
476 }
477
478 BufferedSocket::~BufferedSocket()
479 {
480         this->Close();
481         if (Timeout)
482         {
483                 ServerInstance->Timers->DelTimer(Timeout);
484                 Timeout = NULL;
485         }
486 }
487
488 void StreamSocket::HandleEvent(EventType et, int errornum)
489 {
490         if (!error.empty())
491                 return;
492         BufferedSocketError errcode = I_ERR_OTHER;
493         switch (et)
494         {
495                 case EVENT_ERROR:
496                 {
497                         if (errornum == 0)
498                                 SetError("Connection closed");
499                         else
500                                 SetError(strerror(errornum));
501                         switch (errornum)
502                         {
503                                 case ETIMEDOUT:
504                                         errcode = I_ERR_TIMEOUT;
505                                         break;
506                                 case ECONNREFUSED:
507                                 case 0:
508                                         errcode = I_ERR_CONNECT;
509                                         break;
510                                 case EADDRINUSE:
511                                         errcode = I_ERR_BIND;
512                                         break;
513                                 case EPIPE:
514                                 case EIO:
515                                         errcode = I_ERR_WRITE;
516                                         break;
517                         }
518                         break;
519                 }
520                 case EVENT_READ:
521                 {
522                         DoRead();
523                         break;
524                 }
525                 case EVENT_WRITE:
526                 {
527                         DoWrite();
528                         break;
529                 }
530         }
531         if (!error.empty())
532         {
533                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
534                 OnError(errcode);
535                 ServerInstance->GlobalCulls.AddItem(this);
536         }
537 }
538