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