]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
f06ddf28d84d1ef96b6fec587cc6ff193b5b8229
[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                 if (IOHook)
124                 {
125                         try
126                         {
127                                 IOHook->OnStreamSocketClose(this);
128                         }
129                         catch (CoreException& modexcept)
130                         {
131                                 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s",
132                                         modexcept.GetSource(), modexcept.GetReason());
133                         }
134                         IOHook = NULL;
135                 }
136                 ServerInstance->SE->Shutdown(this, 2);
137                 ServerInstance->SE->DelFd(this);
138                 ServerInstance->SE->Close(this);
139                 fd = -1;
140         }
141 }
142
143 CullResult StreamSocket::cull()
144 {
145         Close();
146         return EventHandler::cull();
147 }
148
149 bool StreamSocket::GetNextLine(std::string& line, char delim)
150 {
151         std::string::size_type i = recvq.find(delim);
152         if (i == std::string::npos)
153                 return false;
154         line = recvq.substr(0, i);
155         // TODO is this the most efficient way to split?
156         recvq = recvq.substr(i + 1);
157         return true;
158 }
159
160 void StreamSocket::DoRead()
161 {
162         if (IOHook)
163         {
164                 int rv = -1;
165                 try
166                 {
167                         rv = IOHook->OnStreamSocketRead(this, recvq);
168                 }
169                 catch (CoreException& modexcept)
170                 {
171                         ServerInstance->Logs->Log("SOCKET", DEFAULT, "%s threw an exception: %s",
172                                 modexcept.GetSource(), modexcept.GetReason());
173                         return;
174                 }
175                 if (rv > 0)
176                         OnDataReady();
177                 if (rv < 0)
178                         SetError("Read Error"); // will not overwrite a better error message
179         }
180         else
181         {
182                 char* ReadBuffer = ServerInstance->GetReadBuffer();
183                 int n = recv(fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
184                 if (n == ServerInstance->Config->NetBufferSize)
185                 {
186                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
187                         recvq.append(ReadBuffer, n);
188                         OnDataReady();
189                 }
190                 else if (n > 0)
191                 {
192                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ);
193                         recvq.append(ReadBuffer, n);
194                         OnDataReady();
195                 }
196                 else if (n == 0)
197                 {
198                         error = "Connection closed";
199                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
200                 }
201                 else if (errno == EAGAIN)
202                 {
203                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_READ_WILL_BLOCK);
204                 }
205                 else if (errno == EINTR)
206                 {
207                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_ADD_TRIAL_READ);
208                 }
209                 else
210                 {
211                         error = strerror(errno);
212                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
213                 }
214         }
215 }
216
217 void StreamSocket::DoWrite()
218 {
219         if (sendq.empty())
220                 return;
221         if (!error.empty() || fd < 0 || fd == INT_MAX)
222         {
223                 ServerInstance->Logs->Log("SOCKET", DEBUG, "DoWrite on errored or closed socket");
224                 return;
225         }
226
227 #ifndef DISABLE_WRITEV
228         if (IOHook)
229 #endif
230         {
231                 int rv = -1;
232                 try
233                 {
234                         while (error.empty() && !sendq.empty())
235                         {
236                                 if (sendq.size() > 1 && sendq[0].length() < 1024)
237                                 {
238                                         // Avoid multiple repeated SSL encryption invocations
239                                         // This adds a single copy of the queue, but avoids
240                                         // much more overhead in terms of system calls invoked
241                                         // by the IOHook.
242                                         //
243                                         // The length limit of 1024 is to prevent merging strings
244                                         // more than once when writes begin to block.
245                                         std::string tmp;
246                                         tmp.reserve(sendq_len);
247                                         for(unsigned int i=0; i < sendq.size(); i++)
248                                                 tmp.append(sendq[i]);
249                                         sendq.clear();
250                                         sendq.push_back(tmp);
251                                 }
252                                 std::string& front = sendq.front();
253                                 int itemlen = front.length();
254                                 if (IOHook)
255                                 {
256                                         rv = IOHook->OnStreamSocketWrite(this, front);
257                                         if (rv > 0)
258                                         {
259                                                 // consumed the entire string, and is ready for more
260                                                 sendq_len -= itemlen;
261                                                 sendq.pop_front();
262                                         }
263                                         else if (rv == 0)
264                                         {
265                                                 // socket has blocked. Stop trying to send data.
266                                                 // IOHook has requested unblock notification from the socketengine
267
268                                                 // Since it is possible that a partial write took place, adjust sendq_len
269                                                 sendq_len = sendq_len - itemlen + front.length();
270                                                 return;
271                                         }
272                                         else
273                                         {
274                                                 SetError("Write Error"); // will not overwrite a better error message
275                                                 return;
276                                         }
277                                 }
278 #ifdef DISABLE_WRITEV
279                                 else
280                                 {
281                                         rv = ServerInstance->SE->Send(this, front.data(), itemlen, 0);
282                                         if (rv == 0)
283                                         {
284                                                 SetError("Connection closed");
285                                                 return;
286                                         }
287                                         else if (rv < 0)
288                                         {
289                                                 if (errno == EAGAIN || errno == EINTR)
290                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
291                                                 else
292                                                         SetError(strerror(errno));
293                                                 return;
294                                         }
295                                         else if (rv < itemlen)
296                                         {
297                                                 ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK);
298                                                 front = front.substr(itemlen - rv);
299                                                 sendq_len -= rv;
300                                                 return;
301                                         }
302                                         else
303                                         {
304                                                 sendq_len -= itemlen;
305                                                 sendq.pop_front();
306                                                 if (sendq.empty())
307                                                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_EDGE_WRITE);
308                                         }
309                                 }
310 #endif
311                         }
312                 }
313                 catch (CoreException& modexcept)
314                 {
315                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s",
316                                 modexcept.GetSource(), modexcept.GetReason());
317                 }
318         }
319 #ifndef DISABLE_WRITEV
320         else
321         {
322                 // don't even try if we are known to be blocking
323                 if (GetEventMask() & FD_WRITE_WILL_BLOCK)
324                         return;
325                 // start out optimistic - we won't need to write any more
326                 int eventChange = FD_WANT_EDGE_WRITE;
327                 while (error.empty() && sendq_len && eventChange == FD_WANT_EDGE_WRITE)
328                 {
329                         // Prepare a writev() call to write all buffers efficiently
330                         int bufcount = sendq.size();
331                 
332                         // cap the number of buffers at IOV_MAX
333                         if (bufcount > IOV_MAX)
334                         {
335                                 bufcount = IOV_MAX;
336                         }
337
338                         int rv_max = 0;
339                         iovec* iovecs = new iovec[bufcount];
340                         for(int i=0; i < bufcount; i++)
341                         {
342                                 iovecs[i].iov_base = const_cast<char*>(sendq[i].data());
343                                 iovecs[i].iov_len = sendq[i].length();
344                                 rv_max += sendq[i].length();
345                         }
346                         int rv = writev(fd, iovecs, bufcount);
347                         delete[] iovecs;
348
349                         if (rv == (int)sendq_len)
350                         {
351                                 // it's our lucky day, everything got written out. Fast cleanup.
352                                 // This won't ever happen if the number of buffers got capped.
353                                 sendq_len = 0;
354                                 sendq.clear();
355                         }
356                         else if (rv > 0)
357                         {
358                                 // Partial write. Clean out strings from the sendq
359                                 if (rv < rv_max)
360                                 {
361                                         // it's going to block now
362                                         eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
363                                 }
364                                 sendq_len -= rv;
365                                 while (rv > 0 && !sendq.empty())
366                                 {
367                                         std::string& front = sendq.front();
368                                         if (front.length() <= (size_t)rv)
369                                         {
370                                                 // this string got fully written out
371                                                 rv -= front.length();
372                                                 sendq.pop_front();
373                                         }
374                                         else
375                                         {
376                                                 // stopped in the middle of this string
377                                                 front = front.substr(rv);
378                                                 rv = 0;
379                                         }
380                                 }
381                         }
382                         else if (rv == 0)
383                         {
384                                 error = "Connection closed";
385                         }
386                         else if (errno == EAGAIN)
387                         {
388                                 eventChange = FD_WANT_FAST_WRITE | FD_WRITE_WILL_BLOCK;
389                         }
390                         else if (errno == EINTR)
391                         {
392                                 // restart interrupted syscall
393                                 errno = 0;
394                         }
395                         else
396                         {
397                                 error = strerror(errno);
398                         }
399                 }
400                 if (!error.empty())
401                 {
402                         // error - kill all events
403                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_NO_READ | FD_WANT_NO_WRITE);
404                 }
405                 else
406                 {
407                         ServerInstance->SE->ChangeEventMask(this, eventChange);
408                 }
409         }
410 #endif
411 }
412
413 void StreamSocket::WriteData(const std::string &data)
414 {
415         if (fd < 0)
416         {
417                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Attempt to write data to dead socket: %s",
418                         data.c_str());
419                 return;
420         }
421
422         /* Append the data to the back of the queue ready for writing */
423         sendq.push_back(data);
424         sendq_len += data.length();
425
426         ServerInstance->SE->ChangeEventMask(this, FD_ADD_TRIAL_WRITE);
427 }
428
429 void SocketTimeout::Tick(time_t)
430 {
431         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
432
433         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
434                 return;
435
436         if (this->sock->state == I_CONNECTING)
437         {
438                 // for connecting sockets, the timeout can occur
439                 // which causes termination of the connection after
440                 // the given number of seconds without a successful
441                 // connection.
442                 this->sock->OnTimeout();
443                 this->sock->OnError(I_ERR_TIMEOUT);
444
445                 /* NOTE: We must set this AFTER DelFd, as we added
446                  * this socket whilst writeable. This means that we
447                  * must DELETE the socket whilst writeable too!
448                  */
449                 this->sock->state = I_ERROR;
450
451                 ServerInstance->GlobalCulls.AddItem(sock);
452         }
453
454         this->sock->Timeout = NULL;
455 }
456
457 void BufferedSocket::OnConnected() { }
458 void BufferedSocket::OnTimeout() { return; }
459
460 void BufferedSocket::DoWrite()
461 {
462         if (state == I_CONNECTING)
463         {
464                 state = I_CONNECTED;
465                 this->OnConnected();
466                 if (GetIOHook())
467                         GetIOHook()->OnStreamSocketConnect(this);
468                 else
469                         ServerInstance->SE->ChangeEventMask(this, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE);
470         }
471         this->StreamSocket::DoWrite();
472 }
473
474 BufferedSocket::~BufferedSocket()
475 {
476         this->Close();
477         if (Timeout)
478         {
479                 ServerInstance->Timers->DelTimer(Timeout);
480                 Timeout = NULL;
481         }
482 }
483
484 void StreamSocket::HandleEvent(EventType et, int errornum)
485 {
486         if (!error.empty())
487                 return;
488         BufferedSocketError errcode = I_ERR_OTHER;
489         try {
490                 switch (et)
491                 {
492                         case EVENT_ERROR:
493                         {
494                                 if (errornum == 0)
495                                         SetError("Connection closed");
496                                 else
497                                         SetError(strerror(errornum));
498                                 switch (errornum)
499                                 {
500                                         case ETIMEDOUT:
501                                                 errcode = I_ERR_TIMEOUT;
502                                                 break;
503                                         case ECONNREFUSED:
504                                         case 0:
505                                                 errcode = I_ERR_CONNECT;
506                                                 break;
507                                         case EADDRINUSE:
508                                                 errcode = I_ERR_BIND;
509                                                 break;
510                                         case EPIPE:
511                                         case EIO:
512                                                 errcode = I_ERR_WRITE;
513                                                 break;
514                                 }
515                                 break;
516                         }
517                         case EVENT_READ:
518                         {
519                                 DoRead();
520                                 break;
521                         }
522                         case EVENT_WRITE:
523                         {
524                                 DoWrite();
525                                 break;
526                         }
527                 }
528         }
529         catch (CoreException& ex)
530         {
531                 ServerInstance->Logs->Log("SOCKET", DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
532                         fd, ex.GetReason());
533                 SetError(ex.GetReason());
534         }
535         if (!error.empty())
536         {
537                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
538                 OnError(errcode);
539         }
540 }
541