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