]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
Move IP<->sockaddr conversions into irc::sockets:: namespace
[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 /* $Core */
15
16 #include "socket.h"
17 #include "inspstring.h"
18 #include "socketengine.h"
19 #include "inspircd.h"
20
21 bool BufferedSocket::Readable()
22 {
23         return (this->state != I_CONNECTING);
24 }
25
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
27 {
28         this->Timeout = NULL;
29         this->state = I_DISCONNECTED;
30         this->fd = -1;
31         this->ServerInstance = SI;
32 }
33
34 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
35 {
36         this->Timeout = NULL;
37         this->fd = newfd;
38         this->state = I_CONNECTED;
39         strlcpy(this->IP,ip,MAXBUF);
40         this->ServerInstance = SI;
41         if (this->fd > -1)
42                 this->ServerInstance->SE->AddFd(this);
43 }
44
45 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
46 {
47         this->cbindip = connectbindip;
48         this->fd = -1;
49         this->ServerInstance = SI;
50         strlcpy(host,ipaddr.c_str(),MAXBUF);
51         this->Timeout = NULL;
52
53         strlcpy(this->host,ipaddr.c_str(),MAXBUF);
54         this->port = aport;
55
56         irc::sockets::sockaddrs testaddr;
57         if (!irc::sockets::aptosa(host, aport, &testaddr))
58         {
59                 this->ServerInstance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
60                 this->OnError(I_ERR_CONNECT);
61                 this->Close();
62                 this->fd = -1;
63                 this->state = I_ERROR;
64                 return;
65         }
66         else
67         {
68                 strlcpy(this->IP,host,MAXBUF);
69                 if (!this->DoConnect(maxtime))
70                 {
71                         this->OnError(I_ERR_CONNECT);
72                         this->Close();
73                         this->fd = -1;
74                         this->state = I_ERROR;
75                         return;
76                 }
77         }
78 }
79
80 void BufferedSocket::SetQueues()
81 {
82         // attempt to increase socket sendq and recvq as high as its possible
83         int sendbuf = 32768;
84         int recvbuf = 32768;
85         if(setsockopt(this->fd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(this->fd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
86         {
87                 //this->ServerInstance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
88                 ; // 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.
89         }
90 }
91
92 bool BufferedSocket::DoBindMagic(const std::string &current_ip, bool v6)
93 {
94         irc::sockets::sockaddrs s;
95         if (!irc::sockets::aptosa(current_ip.c_str(), 0, &s))
96         {
97                 errno = EADDRNOTAVAIL;
98                 return false;
99         }
100
101         if (ServerInstance->SE->Bind(this->fd, &s.sa, sizeof(s)) < 0)
102         {
103                 this->state = I_ERROR;
104                 this->OnError(I_ERR_BIND);
105                 return false;
106         }
107
108         return true;
109 }
110
111 /* Most irc servers require you to specify the ip you want to bind to.
112  * If you dont specify an IP, they rather dumbly bind to the first IP
113  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
114  * addresses we've bound server ports to, and we try and bind our outbound
115  * connections to the first usable non-loopback and non-any IP we find.
116  * This is easier to configure when you have a lot of links and a lot
117  * of servers to configure.
118  */
119 bool BufferedSocket::BindAddr(const std::string &ip_to_bind)
120 {
121         ConfigReader Conf(this->ServerInstance);
122         bool v6 = false;
123
124         // Case one: If they provided an IP, try bind it
125         if (!ip_to_bind.empty())
126         {
127 #ifdef IPV6
128                 // Check whether or not they are binding to an IPv6 IP..
129                 if (ip_to_bind.find(':') != std::string::npos)
130                         v6 = true;
131 #endif
132                 // And if it fails, don't do anything.
133                 return this->DoBindMagic(ip_to_bind, v6);
134         }
135
136         for (int j = 0; j < Conf.Enumerate("bind"); j++)
137         {
138                 // We only want to try bind to a server ip.
139                 if (Conf.ReadValue("bind","type",j) != "servers")
140                         continue;
141
142                 // set current IP to the <bind> tag
143                 std::string current_ip = Conf.ReadValue("bind","address",j);
144
145 #ifdef IPV6
146                 // Check whether this <bind> is for an ipv6 address
147                 if (current_ip.find(':') != std::string::npos)
148                         v6 = true;
149                 else
150                         v6 = false;
151 #endif
152
153                 // Make sure IP is nothing local
154                 if (current_ip == "*" || current_ip == "127.0.0.1" || current_ip.empty() || current_ip == "::1")
155                         continue;
156
157                 // Try bind, don't fail if it doesn't bind though.
158                 if (this->DoBindMagic(current_ip, v6))
159                         return true;
160         }
161
162         // NOTE: You may wonder WTF we are returning *true* here, but that is because there were no custom binds setup, and so we have nothing to do
163         // (remember, outgoing connections without binding are perfectly ok).
164         ServerInstance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
165         return true;
166 }
167
168 bool BufferedSocket::DoConnect(unsigned long maxtime)
169 {
170         irc::sockets::sockaddrs addr;
171         irc::sockets::aptosa(this->host, this->port, &addr);
172
173         this->fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
174
175         if (this->fd == -1)
176         {
177                 this->state = I_ERROR;
178                 this->OnError(I_ERR_SOCKET);
179                 return false;
180         }
181
182         if (!this->BindAddr(this->cbindip))
183         {
184                 this->Close();
185                 this->fd = -1;
186                 return false;
187         }
188
189         ServerInstance->SE->NonBlocking(this->fd);
190
191         if (ServerInstance->SE->Connect(this, &addr.sa, sa_size(addr)) == -1)
192         {
193                 if (errno != EINPROGRESS)
194                 {
195                         this->OnError(I_ERR_CONNECT);
196                         this->Close();
197                         this->state = I_ERROR;
198                         return false;
199                 }
200
201                 this->Timeout = new SocketTimeout(this->GetFd(), this->ServerInstance, this, maxtime, this->ServerInstance->Time());
202                 this->ServerInstance->Timers->AddTimer(this->Timeout);
203         }
204
205         this->state = I_CONNECTING;
206         if (this->fd > -1)
207         {
208                 if (!this->ServerInstance->SE->AddFd(this))
209                 {
210                         this->OnError(I_ERR_NOMOREFDS);
211                         this->Close();
212                         this->state = I_ERROR;
213                         return false;
214                 }
215                 this->SetQueues();
216         }
217
218         ServerInstance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
219         return true;
220 }
221
222
223 void BufferedSocket::Close()
224 {
225         /* Save this, so we dont lose it,
226          * otherise on failure, error messages
227          * might be inaccurate.
228          */
229         int save = errno;
230         if (this->fd > -1)
231         {
232                 if (this->GetIOHook())
233                 {
234                         try
235                         {
236                                 this->GetIOHook()->OnRawSocketClose(this->fd);
237                         }
238                         catch (CoreException& modexcept)
239                         {
240                                 ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
241                         }
242                 }
243                 ServerInstance->SE->Shutdown(this, 2);
244                 if (ServerInstance->SE->Close(this) != -1)
245                         this->OnClose();
246
247                 if (ServerInstance->SocketCull.find(this) == ServerInstance->SocketCull.end())
248                         ServerInstance->SocketCull[this] = this;
249         }
250         errno = save;
251 }
252
253 std::string BufferedSocket::GetIP()
254 {
255         return this->IP;
256 }
257
258 const char* BufferedSocket::Read()
259 {
260         if (!ServerInstance->SE->BoundsCheckFd(this))
261                 return NULL;
262
263         int n = 0;
264         char* ReadBuffer = ServerInstance->GetReadBuffer();
265
266         if (this->GetIOHook())
267         {
268                 int result2 = 0;
269                 int MOD_RESULT = 0;
270                 try
271                 {
272                         MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, result2);
273                 }
274                 catch (CoreException& modexcept)
275                 {
276                         ServerInstance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
277                 }
278                 if (MOD_RESULT < 0)
279                 {
280                         n = -1;
281                         errno = EAGAIN;
282                 }
283                 else
284                 {
285                         n = result2;
286                 }
287         }
288         else
289         {
290                 n = recv(this->fd, ReadBuffer, ServerInstance->Config->NetBufferSize, 0);
291         }
292
293         /*
294          * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
295          * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
296          * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
297          * --w00t (july 2, 2008)
298          */
299         if (n > 0)
300         {
301                 ReadBuffer[n] = 0;
302                 return ReadBuffer;
303         }
304         else
305         {
306                 int err = errno;
307                 if (err == EAGAIN)
308                         return "";
309                 else
310                         return NULL;
311         }
312 }
313
314 /*
315  * This function formerly tried to flush write buffer each call.
316  * While admirable in attempting to get the data out to wherever
317  * it is going, on a full socket, it's just going to syscall write() and
318  * EAGAIN constantly, instead of waiting in the SE to know if it can write
319  * which will chew a bit of CPU.
320  *
321  * So, now this function returns void (take note) and just adds to the sendq.
322  *
323  * It'll get written at a determinate point when the socketengine tells us it can write.
324  *              -- w00t (april 1, 2008)
325  */
326 void BufferedSocket::Write(const std::string &data)
327 {
328         /* Append the data to the back of the queue ready for writing */
329         outbuffer.push_back(data);
330
331         /* Mark ourselves as wanting write */
332         this->ServerInstance->SE->WantWrite(this);
333 }
334
335 bool BufferedSocket::FlushWriteBuffer()
336 {
337         errno = 0;
338         if ((this->fd > -1) && (this->state == I_CONNECTED))
339         {
340                 if (this->GetIOHook())
341                 {
342                         while (outbuffer.size() && (errno != EAGAIN))
343                         {
344                                 try
345                                 {
346                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
347                                          * implement their own buffering mechanisms
348                                          */
349                                         this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
350                                         outbuffer.pop_front();
351                                 }
352                                 catch (CoreException& modexcept)
353                                 {
354                                         ServerInstance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
355                                         return true;
356                                 }
357                         }
358                 }
359                 else
360                 {
361                         /* If we have multiple lines, try to send them all,
362                          * not just the first one -- Brain
363                          */
364                         while (outbuffer.size() && (errno != EAGAIN))
365                         {
366                                 /* Send a line */
367                                 int result = ServerInstance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
368
369                                 if (result > 0)
370                                 {
371                                         if ((unsigned int)result >= outbuffer[0].length())
372                                         {
373                                                 /* The whole block was written (usually a line)
374                                                  * Pop the block off the front of the queue,
375                                                  * dont set errno, because we are clear of errors
376                                                  * and want to try and write the next block too.
377                                                  */
378                                                 outbuffer.pop_front();
379                                         }
380                                         else
381                                         {
382                                                 std::string temp = outbuffer[0].substr(result);
383                                                 outbuffer[0] = temp;
384                                                 /* We didnt get the whole line out. arses.
385                                                  * Try again next time, i guess. Set errno,
386                                                  * because we shouldnt be writing any more now,
387                                                  * until the socketengine says its safe to do so.
388                                                  */
389                                                 errno = EAGAIN;
390                                         }
391                                 }
392                                 else if (result == 0)
393                                 {
394                                         this->ServerInstance->SE->DelFd(this);
395                                         this->Close();
396                                         return true;
397                                 }
398                                 else if ((result == -1) && (errno != EAGAIN))
399                                 {
400                                         this->OnError(I_ERR_WRITE);
401                                         this->state = I_ERROR;
402                                         this->ServerInstance->SE->DelFd(this);
403                                         this->Close();
404                                         return true;
405                                 }
406                         }
407                 }
408         }
409
410         if ((errno == EAGAIN) && (fd > -1))
411         {
412                 this->ServerInstance->SE->WantWrite(this);
413         }
414
415         return (fd < 0);
416 }
417
418 void SocketTimeout::Tick(time_t)
419 {
420         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
421
422         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
423                 return;
424
425         if (this->sock->state == I_CONNECTING)
426         {
427                 // for connecting sockets, the timeout can occur
428                 // which causes termination of the connection after
429                 // the given number of seconds without a successful
430                 // connection.
431                 this->sock->OnTimeout();
432                 this->sock->OnError(I_ERR_TIMEOUT);
433
434                 /* NOTE: We must set this AFTER DelFd, as we added
435                  * this socket whilst writeable. This means that we
436                  * must DELETE the socket whilst writeable too!
437                  */
438                 this->sock->state = I_ERROR;
439
440                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
441                         ServerInstance->SocketCull[this->sock] = this->sock;
442         }
443
444         this->sock->Timeout = NULL;
445 }
446
447 bool BufferedSocket::InternalMarkConnected()
448 {
449         /* Our socket was in write-state, so delete it and re-add it
450          * in read-state.
451          */
452         this->SetState(I_CONNECTED);
453
454         if (this->GetIOHook())
455         {
456                 ServerInstance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
457                 try
458                 {
459                         this->GetIOHook()->OnRawSocketConnect(this->fd);
460                 }
461                 catch (CoreException& modexcept)
462                 {
463                         ServerInstance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
464                         return false;
465                 }
466         }
467         return this->OnConnected();
468 }
469
470 void BufferedSocket::SetState(BufferedSocketState s)
471 {
472         this->state = s;
473 }
474
475 BufferedSocketState BufferedSocket::GetState()
476 {
477         return this->state;
478 }
479
480 bool BufferedSocket::OnConnected() { return true; }
481 void BufferedSocket::OnError(BufferedSocketError) { return; }
482 int BufferedSocket::OnDisconnect() { return 0; }
483 bool BufferedSocket::OnDataReady() { return true; }
484 bool BufferedSocket::OnWriteReady()
485 {
486         // Default behaviour: just try write some.
487         return !this->FlushWriteBuffer();
488 }
489 void BufferedSocket::OnTimeout() { return; }
490 void BufferedSocket::OnClose() { return; }
491
492 BufferedSocket::~BufferedSocket()
493 {
494         this->Close();
495         if (Timeout)
496         {
497                 ServerInstance->Timers->DelTimer(Timeout);
498                 Timeout = NULL;
499         }
500 }
501
502 void BufferedSocket::HandleEvent(EventType et, int errornum)
503 {
504         switch (et)
505         {
506                 case EVENT_ERROR:
507                 {
508                         switch (errornum)
509                         {
510                                 case ETIMEDOUT:
511                                         this->OnError(I_ERR_TIMEOUT);
512                                         break;
513                                 case ECONNREFUSED:
514                                 case 0:
515                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
516                                         break;
517                                 case EADDRINUSE:
518                                         this->OnError(I_ERR_BIND);
519                                         break;
520                                 case EPIPE:
521                                 case EIO:
522                                         this->OnError(I_ERR_WRITE);
523                                         break;
524                         }
525
526                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
527                                 this->ServerInstance->SocketCull[this] = this;
528                         return;
529                         break;
530                 }
531                 case EVENT_READ:
532                 {
533                         if (!this->OnDataReady())
534                         {
535                                 if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
536                                         this->ServerInstance->SocketCull[this] = this;
537                                 return;
538                         }
539                         break;
540                 }
541                 case EVENT_WRITE:
542                 {
543                         if (this->state == I_CONNECTING)
544                         {
545                                 if (!this->InternalMarkConnected())
546                                 {
547                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
548                                                 this->ServerInstance->SocketCull[this] = this;
549                                         return;
550                                 }
551                                 return;
552                         }
553                         else
554                         {
555                                 if (!this->OnWriteReady())
556                                 {
557                                         if (this->ServerInstance->SocketCull.find(this) == this->ServerInstance->SocketCull.end())
558                                                 this->ServerInstance->SocketCull[this] = this;
559                                         return;
560                                 }
561                         }
562                         break;
563                 }
564         }
565 }
566