]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
65b554006a3207f86248b00b629f92c68b3ce5c7
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 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) < 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         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 = recv(fd, 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 (errno == EAGAIN)
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 = strerror(errno);
214                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
215                 }
216         }
217 }
218
219 void StreamSocket::DoWrite()
220 {
221         if (sendq.empty())
222                 return;
223         if (!error.empty() || fd < 0 || fd == INT_MAX)
224         {
225                 ServerInstance->Logs->Log("SOCKET", DEBUG, "DoWrite on errored or closed socket");
226                 return;
227         }
228
229 #ifndef DISABLE_WRITEV
230         if (IOHook)
231 #endif
232         {
233                 int rv = -1;
234                 try
235                 {
236                         while (error.empty() && !sendq.empty())
237                         {
238                                 if (sendq.size() > 1 && sendq[0].length() < 1024)
239                                 {
240                                         // Avoid multiple repeated SSL encryption invocations
241                                         // This adds a single copy of the queue, but avoids
242                                         // much more overhead in terms of system calls invoked
243                                         // by the IOHook.
244                                         //
245                                         // The length limit of 1024 is to prevent merging strings
246                                         // more than once when writes begin to block.
247                                         std::string tmp;
248                                         tmp.reserve(sendq_len);
249                                         for(unsigned int i=0; i < sendq.size(); i++)
250                                                 tmp.append(sendq[i]);
251                                         sendq.clear();
252                                         sendq.push_back(tmp);
253                                 }
254                                 std::string& front = sendq.front();
255                                 int itemlen = front.length();
256                                 if (IOHook)
257                                 {
258                                         rv = IOHook->OnStreamSocketWrite(this, front);
259                                         if (rv > 0)
260                                         {
261                                                 // consumed the entire string, and is ready for more
262                                                 sendq_len -= itemlen;
263                                                 sendq.pop_front();
264                                         }
265                                         else if (rv == 0)
266                                         {
267                                                 // socket has blocked. Stop trying to send data.
268                                                 // IOHook has requested unblock notification from the socketengine
269
270                                                 // Since it is possible that a partial write took place, adjust sendq_len
271                                                 sendq_len = sendq_len - itemlen + front.length();
272                                                 return;
273                                         }
274                                         else
275                                         {
276                                                 SetError("Write Error"); // will not overwrite a better error message
277                                                 return;
278                                         }
279                                 }
280 #ifdef DISABLE_WRITEV
281                                 else
282                                 {
283                                         rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
284                                         if (rv == 0)
285                                         {
286                                                 SetError("Connection closed");
287                                                 return;
288                                         }
289                                         else if (rv < 0)
290                                         {
291                                                 if (errno == EAGAIN || errno == EINTR)
292                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
293                                                 else
294                                                         SetError(strerror(errno));
295                                                 return;
296                                         }
297                                         else if (rv < itemlen)
298                                         {
299                                                 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
300                                                 front = front.substr(itemlen - rv);
301                                                 sendq_len -= rv;
302                                                 return;
303                                         }
304                                         else
305                                         {
306                                                 sendq_len -= itemlen;
307                                                 sendq.pop_front();
308                                                 if (sendq.empty())
309                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
310                                         }
311                                 }
312 #endif
313                         }
314                 }
315                 catch (CoreException& modexcept)
316                 {
317                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
318                                 modexcept.GetSource(), modexcept.GetReason());
319                 }
320         }
321 #ifndef DISABLE_WRITEV
322         else
323         {
324                 // don't even try if we are known to be blocking
325                 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
326                         return;
327                 // start out optimistic - we won't need to write any more
328                 int eventChange = FD_WANT_EDGE_WRITE;
329                 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
330                 {
331                         // Prepare a writev() call to write all buffers efficiently
332                         int bufcount = sendq.size();
333                 
334                         // cap the number of buffers at IOV_MAX
335                         if (bufcount > IOV_MAX)
336                         {
337                                 bufcount = IOV_MAX;
338                         }
339
340                         int rv_max = 0;
341                         iovec* iovecs = new iovec[bufcount];
342                         for(int i=0; i < bufcount; i++)
343                         {
344                                 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
345                                 iovecs[i].iov_len = sendq[i].length();
346                                 rv_max += sendq[i].length();
347                         }
348                         int rv = writev(fd, iovecs, bufcount);
349                         delete[] iovecs;
350
351                         if (rv == (int)sendq_len)
352                         {
353                                 // it's our lucky day, everything got written out. Fast cleanup.
354                                 // This won't ever happen if the number of buffers got capped.
355                                 sendq_len = 0;
356                                 sendq.clear();
357                         }
358                         else if (rv > 0)
359                         {
360                                 // Partial write. Clean out strings from the sendq
361                                 if (rv < rv_max)
362                                 {
363                                         // it's going to block now
364                                         eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
365                                 }
366                                 sendq_len -= rv;
367                                 while (rv > 0 && !sendq.empty())
368                                 {
369                                         std::string& front = sendq.front();
370                                         if (front.length() <= (size_t)rv)
371                                         {
372                                                 // this string got fully written out
373                                                 rv -= front.length();
374                                                 sendq.pop_front();
375                                         }
376                                         else
377                                         {
378                                                 // stopped in the middle of this string
379                                                 front = front.substr(rv);
380                                                 rv = 0;
381                                         }
382                                 }
383                         }
384                         else if (rv == 0)
385                         {
386                                 error = "Connection closed";
387                         }
388                         else if (errno == EAGAIN)
389                         {
390                                 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
391                         }
392                         else if (errno == EINTR)
393                         {
394                                 // restart interrupted syscall
395                                 errno = 0;
396                         }
397                         else
398                         {
399                                 error = strerror(errno);
400                         }
401                 }
402                 if (!error.empty())
403                 {
404                         // error - kill all events
405                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
406                 }
407                 else
408                 {
409                         ServerInstance->SE->ChangeEventMask(this, eventChange);
410                 }
411         }
412 #endif
413 }
414
415 void StreamSocket::WriteData(const std::string &data)
416 {
417         if (fd < 0)
418         {
419                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
420                         data.c_str());
421                 return;
422         }
423
424         /* Append the data to the back of the queue ready for writing */
425         sendq.push_back(data);
426         sendq_len += data.length();
427
428         ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
429 }
430
431 void SocketTimeout::Tick(time_t)
432 {
433         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
434
435         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
436                 return;
437
438         if (this->sock->state == I_CONNECTING)
439         {
440                 // for connecting sockets, the timeout can occur
441                 // which causes termination of the connection after
442                 // the given number of seconds without a successful
443                 // connection.
444                 this->sock->OnTimeout();
445                 this->sock->OnError(I_ERR_TIMEOUT);
446
447                 /* NOTE: We must set this AFTER DelFd, as we added
448                  * this socket whilst writeable. This means that we
449                  * must DELETE the socket whilst writeable too!
450                  */
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(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", 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