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