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