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