]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspsocket.cpp
d4f6c9c17ea2b1742523211b03d25839d86ded79
[user/henk/code/inspircd.git] / src / inspsocket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/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) && (this->WaitingForWriteEvent == false));
24 }
25
26 BufferedSocket::BufferedSocket(InspIRCd* SI)
27 {
28         this->Timeout = NULL;
29         this->state = I_DISCONNECTED;
30         this->fd = -1;
31         this->WaitingForWriteEvent = false;
32         this->Instance = SI;
33 }
34
35 BufferedSocket::BufferedSocket(InspIRCd* SI, int newfd, const char* ip)
36 {
37         this->Timeout = NULL;
38         this->fd = newfd;
39         this->state = I_CONNECTED;
40         strlcpy(this->IP,ip,MAXBUF);
41         this->WaitingForWriteEvent = false;
42         this->Instance = SI;
43         if (this->fd > -1)
44                 this->Instance->SE->AddFd(this);
45 }
46
47 BufferedSocket::BufferedSocket(InspIRCd* SI, const std::string &ipaddr, int aport, unsigned long maxtime, const std::string &connectbindip)
48 {
49         this->cbindip = connectbindip;
50         this->fd = -1;
51         this->Instance = SI;
52         strlcpy(host,ipaddr.c_str(),MAXBUF);
53         this->WaitingForWriteEvent = false;
54         this->Timeout = NULL;
55
56         strlcpy(this->host,ipaddr.c_str(),MAXBUF);
57         this->port = aport;
58
59         bool ipvalid = true;
60 #ifdef IPV6
61         if (strchr(host,':'))
62         {
63                 in6_addr n;
64                 if (inet_pton(AF_INET6, host, &n) < 1)
65                         ipvalid = false;
66         }
67         else
68 #endif
69         {
70                 in_addr n;
71                 if (inet_aton(host,&n) < 1)
72                         ipvalid = false;
73         }
74         if (!ipvalid)
75         {
76                 this->Instance->Logs->Log("SOCKET", DEBUG,"BUG: Hostname passed to BufferedSocket, rather than an IP address!");
77                 this->OnError(I_ERR_CONNECT);
78                 this->Close();
79                 this->fd = -1;
80                 this->state = I_ERROR;
81                 return;
82         }
83         else
84         {
85                 strlcpy(this->IP,host,MAXBUF);
86                 timeout_val = maxtime;
87                 if (!this->DoConnect())
88                 {
89                         this->OnError(I_ERR_CONNECT);
90                         this->Close();
91                         this->fd = -1;
92                         this->state = I_ERROR;
93                         return;
94                 }
95         }
96 }
97
98 void BufferedSocket::WantWrite()
99 {
100         this->Instance->SE->WantWrite(this);
101         this->WaitingForWriteEvent = true;
102 }
103
104 void BufferedSocket::SetQueues(int nfd)
105 {
106         // attempt to increase socket sendq and recvq as high as its possible
107         int sendbuf = 32768;
108         int recvbuf = 32768;
109         if(setsockopt(nfd,SOL_SOCKET,SO_SNDBUF,(const char *)&sendbuf,sizeof(sendbuf)) || setsockopt(nfd,SOL_SOCKET,SO_RCVBUF,(const char *)&recvbuf,sizeof(sendbuf)))
110         {
111                 //this->Instance->Log(DEFAULT, "Could not increase SO_SNDBUF/SO_RCVBUF for socket %u", GetFd());
112                 ; // 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.
113         }
114 }
115
116 /* Most irc servers require you to specify the ip you want to bind to.
117  * If you dont specify an IP, they rather dumbly bind to the first IP
118  * of the box (e.g. INADDR_ANY). In InspIRCd, we scan thought the IP
119  * addresses we've bound server ports to, and we try and bind our outbound
120  * connections to the first usable non-loopback and non-any IP we find.
121  * This is easier to configure when you have a lot of links and a lot
122  * of servers to configure.
123  */
124 bool BufferedSocket::BindAddr(const std::string &ip)
125 {
126         ConfigReader Conf(this->Instance);
127         socklen_t size = sizeof(sockaddr_in);
128 #ifdef IPV6
129         bool v6 = false;
130         /* Are we looking for a binding to fit an ipv6 host? */
131         if ((ip.empty()) || (ip.find(':') != std::string::npos))
132                 v6 = true;
133 #endif
134         int j = 0;
135         while (j < Conf.Enumerate("bind") || (!ip.empty()))
136         {
137                 std::string sIP = ip.empty() ? Conf.ReadValue("bind","address",j) : ip;
138                 if (!ip.empty() || Conf.ReadValue("bind","type",j) == "servers")
139                 {
140                         if (!ip.empty() || ((sIP != "*") && (sIP != "127.0.0.1") && (!sIP.empty()) && (sIP != "::1")))
141                         {
142                                 /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
143                                 sockaddr* s = new sockaddr[2];
144 #ifdef IPV6
145                                 if (v6)
146                                 {
147                                         in6_addr n;
148                                         if (inet_pton(AF_INET6, sIP.c_str(), &n) > 0)
149                                         {
150                                                 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
151                                                 ((sockaddr_in6*)s)->sin6_port = 0;
152                                                 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
153                                                 size = sizeof(sockaddr_in6);
154                                         }
155                                         else
156                                         {
157                                                 delete[] s;
158                                                 j++;
159                                                 continue;
160                                         }
161                                 }
162                                 else
163 #endif
164                                 {
165                                         in_addr n;
166                                         if (inet_aton(sIP.c_str(), &n) > 0)
167                                         {
168                                                 ((sockaddr_in*)s)->sin_addr = n;
169                                                 ((sockaddr_in*)s)->sin_port = 0;
170                                                 ((sockaddr_in*)s)->sin_family = AF_INET;
171                                         }
172                                         else
173                                         {
174                                                 delete[] s;
175                                                 j++;
176                                                 continue;
177                                         }
178                                 }
179
180                                 if (Instance->SE->Bind(this->fd, s, size) < 0)
181                                 {
182                                         this->state = I_ERROR;
183                                         this->OnError(I_ERR_BIND);
184                                         this->fd = -1;
185                                         delete[] s;
186                                         return false;
187                                 }
188
189                                 delete[] s;
190                                 return true;
191                         }
192                 }
193                 j++;
194         }
195         Instance->Logs->Log("SOCKET", DEBUG,"nothing in the config to bind()!");
196         return true;
197 }
198
199 bool BufferedSocket::DoConnect()
200 {
201         /* The [2] is required because we may write a sockaddr_in6 here, and sockaddr_in6 is larger than sockaddr, where sockaddr_in4 is not. */
202         sockaddr* addr = new sockaddr[2];
203         socklen_t size = sizeof(sockaddr_in);
204 #ifdef IPV6
205         bool v6 = false;
206         if ((!*this->host) || strchr(this->host, ':'))
207                 v6 = true;
208
209         if (v6)
210         {
211                 this->fd = socket(AF_INET6, SOCK_STREAM, 0);
212                 if ((this->fd > -1) && ((strstr(this->IP,"::ffff:") != (char*)&this->IP) && (strstr(this->IP,"::FFFF:") != (char*)&this->IP)))
213                 {
214                         if (!this->BindAddr(this->cbindip))
215                         {
216                                 delete[] addr;
217                                 return false;
218                         }
219                 }
220         }
221         else
222 #endif
223         {
224                 this->fd = socket(AF_INET, SOCK_STREAM, 0);
225                 if (this->fd > -1)
226                 {
227                         if (!this->BindAddr(this->cbindip))
228                         {
229                                 delete[] addr;
230                                 return false;
231                         }
232                 }
233         }
234
235         if (this->fd == -1)
236         {
237                 this->state = I_ERROR;
238                 this->OnError(I_ERR_SOCKET);
239                 delete[] addr;
240                 return false;
241         }
242
243 #ifdef IPV6
244         if (v6)
245         {
246                 in6_addr addy;
247                 if (inet_pton(AF_INET6, this->host, &addy) > 0)
248                 {
249                         ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
250                         memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
251                         ((sockaddr_in6*)addr)->sin6_port = htons(this->port);
252                         size = sizeof(sockaddr_in6);
253                 }
254         }
255         else
256 #endif
257         {
258                 in_addr addy;
259                 if (inet_aton(this->host, &addy) > 0)
260                 {
261                         ((sockaddr_in*)addr)->sin_family = AF_INET;
262                         ((sockaddr_in*)addr)->sin_addr = addy;
263                         ((sockaddr_in*)addr)->sin_port = htons(this->port);
264                 }
265         }
266
267         Instance->SE->NonBlocking(this->fd);
268
269 #ifdef WIN32
270         /* UGH for the LOVE OF ZOMBIE JESUS SOMEONE FIX THIS!!!!!!!!!!! */
271         Instance->SE->Blocking(this->fd);
272 #endif
273
274         if (Instance->SE->Connect(this, (sockaddr*)addr, size) == -1)
275         {
276                 if (errno != EINPROGRESS)
277                 {
278                         this->OnError(I_ERR_CONNECT);
279                         this->Close();
280                         this->state = I_ERROR;
281                         return false;
282                 }
283
284                 this->Timeout = new SocketTimeout(this->GetFd(), this->Instance, this, timeout_val, this->Instance->Time());
285                 this->Instance->Timers->AddTimer(this->Timeout);
286         }
287 #ifdef WIN32
288         /* CRAQ SMOKING STUFF TO BE FIXED */
289         Instance->SE->NonBlocking(this->fd);
290 #endif
291         this->state = I_CONNECTING;
292         if (this->fd > -1)
293         {
294                 if (!this->Instance->SE->AddFd(this))
295                 {
296                         this->OnError(I_ERR_NOMOREFDS);
297                         this->Close();
298                         this->state = I_ERROR;
299                         return false;
300                 }
301                 this->SetQueues(this->fd);
302         }
303
304         Instance->Logs->Log("SOCKET", DEBUG,"BufferedSocket::DoConnect success");
305         return true;
306 }
307
308
309 void BufferedSocket::Close()
310 {
311         /* Save this, so we dont lose it,
312          * otherise on failure, error messages
313          * might be inaccurate.
314          */
315         int save = errno;
316         if (this->fd > -1)
317         {
318                 if (this->GetIOHook())
319                 {
320                         try
321                         {
322                                 this->GetIOHook()->OnRawSocketClose(this->fd);
323                         }
324                         catch (CoreException& modexcept)
325                         {
326                                 Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
327                         }
328                 }
329                 Instance->SE->Shutdown(this, 2);
330                 if (Instance->SE->Close(this) != -1)
331                         this->OnClose();
332
333                 if (Instance->SocketCull.find(this) == Instance->SocketCull.end())
334                         Instance->SocketCull[this] = this;
335         }
336         errno = save;
337 }
338
339 std::string BufferedSocket::GetIP()
340 {
341         return this->IP;
342 }
343
344 const char* BufferedSocket::Read()
345 {
346         if (!Instance->SE->BoundsCheckFd(this))
347                 return NULL;
348
349         int n = 0;
350         char* ReadBuffer = Instance->GetReadBuffer();
351
352         if (this->GetIOHook())
353         {
354                 int result2 = 0;
355                 int MOD_RESULT = 0;
356                 try
357                 {
358                         MOD_RESULT = this->GetIOHook()->OnRawSocketRead(this->fd, ReadBuffer, Instance->Config->NetBufferSize, result2);
359                 }
360                 catch (CoreException& modexcept)
361                 {
362                         Instance->Logs->Log("SOCKET", DEFAULT,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
363                 }
364                 if (MOD_RESULT < 0)
365                 {
366                         n = -1;
367                         errno = EAGAIN;
368                 }
369                 else
370                 {
371                         n = result2;
372                 }
373         }
374         else
375         {
376                 n = recv(this->fd, ReadBuffer, Instance->Config->NetBufferSize, 0);
377         }
378
379         /*
380          * This used to do some silly bounds checking instead of just passing bufsize - 1 to recv.
381          * Not only does that make absolutely no sense, but it could potentially result in a read buffer's worth
382          * of data being thrown into the bit bucket for no good reason, which is just *stupid*.. do things correctly now.
383          * --w00t (july 2, 2008)
384          */
385         if (n > 0)
386         {
387                 ReadBuffer[n] = 0;
388                 return ReadBuffer;
389         }
390         else
391         {
392                 int err = errno;
393                 if (err == EAGAIN)
394                         return "";
395                 else
396                         return NULL;
397         }
398 }
399
400 /*
401  * This function formerly tried to flush write buffer each call.
402  * While admirable in attempting to get the data out to wherever
403  * it is going, on a full socket, it's just going to syscall write() and
404  * EAGAIN constantly, instead of waiting in the SE to know if it can write
405  * which will chew a bit of CPU.
406  *
407  * So, now this function returns void (take note) and just adds to the sendq.
408  *
409  * It'll get written at a determinate point when the socketengine tells us it can write.
410  *              -- w00t (april 1, 2008)
411  */
412 void BufferedSocket::Write(const std::string &data)
413 {
414         /* Append the data to the back of the queue ready for writing */
415         outbuffer.push_back(data);
416
417         /* Mark ourselves as wanting write */
418         this->Instance->SE->WantWrite(this);
419 }
420
421 bool BufferedSocket::FlushWriteBuffer()
422 {
423         errno = 0;
424         if ((this->fd > -1) && (this->state == I_CONNECTED))
425         {
426                 if (this->GetIOHook())
427                 {
428                         while (outbuffer.size() && (errno != EAGAIN))
429                         {
430                                 try
431                                 {
432                                         /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
433                                          * implement their own buffering mechanisms
434                                          */
435                                         this->GetIOHook()->OnRawSocketWrite(this->fd, outbuffer[0].c_str(), outbuffer[0].length());
436                                         outbuffer.pop_front();
437                                 }
438                                 catch (CoreException& modexcept)
439                                 {
440                                         Instance->Logs->Log("SOCKET", DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
441                                         return true;
442                                 }
443                         }
444                 }
445                 else
446                 {
447                         /* If we have multiple lines, try to send them all,
448                          * not just the first one -- Brain
449                          */
450                         while (outbuffer.size() && (errno != EAGAIN))
451                         {
452                                 /* Send a line */
453                                 int result = Instance->SE->Send(this, outbuffer[0].c_str(), outbuffer[0].length(), 0);
454
455                                 if (result > 0)
456                                 {
457                                         if ((unsigned int)result >= outbuffer[0].length())
458                                         {
459                                                 /* The whole block was written (usually a line)
460                                                  * Pop the block off the front of the queue,
461                                                  * dont set errno, because we are clear of errors
462                                                  * and want to try and write the next block too.
463                                                  */
464                                                 outbuffer.pop_front();
465                                         }
466                                         else
467                                         {
468                                                 std::string temp = outbuffer[0].substr(result);
469                                                 outbuffer[0] = temp;
470                                                 /* We didnt get the whole line out. arses.
471                                                  * Try again next time, i guess. Set errno,
472                                                  * because we shouldnt be writing any more now,
473                                                  * until the socketengine says its safe to do so.
474                                                  */
475                                                 errno = EAGAIN;
476                                         }
477                                 }
478                                 else if (result == 0)
479                                 {
480                                         this->Instance->SE->DelFd(this);
481                                         this->Close();
482                                         return true;
483                                 }
484                                 else if ((result == -1) && (errno != EAGAIN))
485                                 {
486                                         this->OnError(I_ERR_WRITE);
487                                         this->state = I_ERROR;
488                                         this->Instance->SE->DelFd(this);
489                                         this->Close();
490                                         return true;
491                                 }
492                         }
493                 }
494         }
495
496         if ((errno == EAGAIN) && (fd > -1))
497         {
498                 this->Instance->SE->WantWrite(this);
499         }
500
501         return (fd < 0);
502 }
503
504 void SocketTimeout::Tick(time_t)
505 {
506         ServerInstance->Logs->Log("SOCKET", DEBUG,"SocketTimeout::Tick");
507
508         if (ServerInstance->SE->GetRef(this->sfd) != this->sock)
509                 return;
510
511         if (this->sock->state == I_CONNECTING)
512         {
513                 // for connecting sockets, the timeout can occur
514                 // which causes termination of the connection after
515                 // the given number of seconds without a successful
516                 // connection.
517                 this->sock->OnTimeout();
518                 this->sock->OnError(I_ERR_TIMEOUT);
519                 this->sock->timeout = true;
520
521                 /* NOTE: We must set this AFTER DelFd, as we added
522                  * this socket whilst writeable. This means that we
523                  * must DELETE the socket whilst writeable too!
524                  */
525                 this->sock->state = I_ERROR;
526
527                 if (ServerInstance->SocketCull.find(this->sock) == ServerInstance->SocketCull.end())
528                         ServerInstance->SocketCull[this->sock] = this->sock;
529         }
530
531         this->sock->Timeout = NULL;
532 }
533
534 bool BufferedSocket::Poll()
535 {
536 #ifndef WINDOWS
537         if (!Instance->SE->BoundsCheckFd(this))
538                 return false;
539 #endif
540
541         if (Instance->SE->GetRef(this->fd) != this)
542                 return false;
543
544         switch (this->state)
545         {
546                 case I_CONNECTING:
547                         /* Our socket was in write-state, so delete it and re-add it
548                          * in read-state.
549                          */
550 #ifndef WINDOWS
551                         if (this->fd > -1)
552                         {
553                                 this->Instance->SE->DelFd(this);
554                                 if (!this->Instance->SE->AddFd(this))
555                                         return false;
556                         }
557 #endif
558                         this->SetState(I_CONNECTED);
559
560                         if (this->GetIOHook())
561                         {
562                                 Instance->Logs->Log("SOCKET",DEBUG,"Hook for raw connect");
563                                 try
564                                 {
565                                         this->GetIOHook()->OnRawSocketConnect(this->fd);
566                                 }
567                                 catch (CoreException& modexcept)
568                                 {
569                                         Instance->Logs->Log("SOCKET",DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
570                                 }
571                         }
572                         return this->OnConnected();
573                 break;
574                 case I_CONNECTED:
575                         /* Process the read event */
576                         return this->OnDataReady();
577                 break;
578                 default:
579                 break;
580         }
581         return true;
582 }
583
584 void BufferedSocket::SetState(BufferedSocketState s)
585 {
586         this->state = s;
587 }
588
589 BufferedSocketState BufferedSocket::GetState()
590 {
591         return this->state;
592 }
593
594 int BufferedSocket::GetFd()
595 {
596         return this->fd;
597 }
598
599 bool BufferedSocket::OnConnected() { return true; }
600 void BufferedSocket::OnError(BufferedSocketError) { return; }
601 int BufferedSocket::OnDisconnect() { return 0; }
602 bool BufferedSocket::OnDataReady() { return true; }
603 bool BufferedSocket::OnWriteReady() { return true; }
604 void BufferedSocket::OnTimeout() { return; }
605 void BufferedSocket::OnClose() { return; }
606
607 BufferedSocket::~BufferedSocket()
608 {
609         this->Close();
610         if (Timeout)
611         {
612                 Instance->Timers->DelTimer(Timeout);
613                 Timeout = NULL;
614         }
615 }
616
617 void BufferedSocket::HandleEvent(EventType et, int errornum)
618 {
619         switch (et)
620         {
621                 case EVENT_ERROR:
622                         switch (errornum)
623                         {
624                                 case ETIMEDOUT:
625                                         this->OnError(I_ERR_TIMEOUT);
626                                 break;
627                                 case ECONNREFUSED:
628                                 case 0:
629                                         this->OnError(this->state == I_CONNECTING ? I_ERR_CONNECT : I_ERR_WRITE);
630                                 break;
631                                 case EADDRINUSE:
632                                         this->OnError(I_ERR_BIND);
633                                 break;
634                                 case EPIPE:
635                                 case EIO:
636                                         this->OnError(I_ERR_WRITE);
637                                 break;
638                         }
639                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
640                                 this->Instance->SocketCull[this] = this;
641                         return;
642                 break;
643                 case EVENT_READ:
644                         if (!this->Poll())
645                         {
646                                 if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
647                                         this->Instance->SocketCull[this] = this;
648                                 return;
649                         }
650                 break;
651                 case EVENT_WRITE:
652                         if (this->WaitingForWriteEvent)
653                         {
654                                 this->WaitingForWriteEvent = false;
655                                 if (!this->OnWriteReady())
656                                 {
657                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
658                                                 this->Instance->SocketCull[this] = this;
659                                         return;
660                                 }
661                         }
662                         if (this->state == I_CONNECTING)
663                         {
664                                 /* This might look wrong as if we should be actually calling
665                                  * with EVENT_WRITE, but trust me it is correct. There are some
666                                  * writeability-state things in the read code, because of how
667                                  * BufferedSocket used to work regarding write buffering in previous
668                                  * versions of InspIRCd. - Brain
669                                  */
670                                 this->HandleEvent(EVENT_READ);
671                                 return;
672                         }
673                         else
674                         {
675                                 if (this->FlushWriteBuffer())
676                                 {
677                                         if (this->Instance->SocketCull.find(this) == this->Instance->SocketCull.end())
678                                                 this->Instance->SocketCull[this] = this;
679                                         return;
680                                 }
681                         }
682                 break;
683         }
684 }
685