]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
Not safe for use yet
[user/henk/code/inspircd.git] / src / socket.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 <string>
15 #include "configreader.h"
16 #include "socket.h"
17 #include "inspircd.h"
18 #include "socketengine.h"
19 #include "wildcard.h"
20
21 using namespace irc::sockets;
22
23 /* Used when comparing CIDR masks for the modulus bits left over.
24  * A lot of ircd's seem to do this:
25  * ((-1) << (8 - (mask % 8)))
26  * But imho, it sucks in comparison to a nice neat lookup table.
27  */
28 const char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits - never actually used */
29                                 0x80, /* 10000000 - 1 bits */
30                                 0xC0, /* 11000000 - 2 bits */
31                                 0xE0, /* 11100000 - 3 bits */
32                                 0xF0, /* 11110000 - 4 bits */
33                                 0xF8, /* 11111000 - 5 bits */
34                                 0xFC, /* 11111100 - 6 bits */
35                                 0xFE  /* 11111110 - 7 bits */
36 };
37
38
39 ListenSocket::ListenSocket(InspIRCd* Instance, int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr) : ServerInstance(Instance), desc("plaintext")
40 {
41         this->SetFd(sockfd);
42         Instance->Log(DEBUG,"CRAP");
43         if (!Instance->BindSocket(this->fd,client,server,port,addr))
44                 this->fd = -1;
45 #ifdef IPV6
46         if ((!*addr) || (strchr(addr,':')))
47                 this->family = AF_INET6;
48         else
49                 this->family = AF_INET;
50 #else
51         this->family = AF_INET;
52 #endif
53 }
54
55 ListenSocket::~ListenSocket()
56 {
57         if (this->GetFd() > -1)
58         {
59                 shutdown(this->fd, 2);
60                 close(this->fd);
61                 this->fd = -1;
62         }
63 }
64
65 void ListenSocket::HandleEvent(EventType et, int errornum)
66 {
67         sockaddr* sock_us = new sockaddr[2];    // our port number
68         sockaddr* client = new sockaddr[2];
69         socklen_t uslen, length;                // length of our port number
70         int incomingSockfd, in_port;
71
72 #ifdef IPV6
73         if (this->family == AF_INET6)
74         {
75                 uslen = sizeof(sockaddr_in6);
76                 length = sizeof(sockaddr_in6);
77         }
78         else
79         {
80                 uslen = sizeof(sockaddr_in);
81                 length = sizeof(sockaddr_in);
82         }
83 #else
84         uslen = sizeof(sockaddr_in);
85         length = sizeof(sockaddr_in);
86 #endif
87         incomingSockfd = accept (this->GetFd(), (sockaddr*)client, &length);
88
89         if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, sock_us, &uslen)))
90         {
91                 char buf[MAXBUF];
92 #ifdef IPV6
93                 if (this->family == AF_INET6)
94                 {
95                         inet_ntop(AF_INET6, &((const sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
96                         in_port = ntohs(((sockaddr_in6*)sock_us)->sin6_port);
97                 }
98                 else
99                 {
100                         inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
101                         in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
102                 }
103 #else
104                 inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
105                 in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
106 #endif
107                 NonBlocking(incomingSockfd);
108                 if (ServerInstance->Config->GetIOHook(in_port))
109                 {
110                         try
111                         {
112                                 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, buf, in_port);
113                         }
114                         catch (CoreException& modexcept)
115                         {
116                                 ServerInstance->Log(DEBUG,"%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
117                         }
118                 }
119                 ServerInstance->stats->statsAccept++;
120                 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, this->family, client);
121         }
122         else
123         {
124                 shutdown(incomingSockfd,2);
125                 close(incomingSockfd);
126                 ServerInstance->stats->statsRefused++;
127         }
128         delete[] client;
129         delete[] sock_us;
130 }
131
132 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
133 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
134 {
135         unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
136         unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
137
138         /* First compare the whole bytes, if they dont match, return false */
139         if (memcmp(address, mask, divisor))
140                 return false;
141
142         /* Now if there are any remainder bits, we compare them with logic AND */
143         if (modulus)
144                 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
145                         /* If they dont match, return false */
146                         return false;
147
148         /* The address matches the mask, to mask_bits bits of mask */
149         return true;
150 }
151
152 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
153 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
154 {
155         return MatchCIDR(address, cidr_mask, false);
156 }
157
158 /* Match CIDR strings, e.g. 127.0.0.1 to 127.0.0.0/8 or 3ffe:1:5:6::8 to 3ffe:1::0/32
159  * If you have a lot of hosts to match, youre probably better off building your mask once
160  * and then using the lower level MatchCIDRBits directly.
161  *
162  * This will also attempt to match any leading usernames or nicknames on the mask, using
163  * match(), when match_with_username is true.
164  */
165 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
166 {
167         unsigned char addr_raw[16];
168         unsigned char mask_raw[16];
169         unsigned int bits = 0;
170         char* mask = NULL;
171
172         /* The caller is trying to match ident@<mask>/bits.
173          * Chop off the ident@ portion, use match() on it
174          * seperately.
175          */
176         if (match_with_username)
177         {
178                 /* Duplicate the strings, and try to find the position
179                  * of the @ symbol in each */
180                 char* address_dupe = strdup(address);
181                 char* cidr_dupe = strdup(cidr_mask);
182         
183                 /* Use strchr not strrchr, because its going to be nearer to the left */
184                 char* username_mask_pos = strrchr(cidr_dupe, '@');
185                 char* username_addr_pos = strrchr(address_dupe, '@');
186
187                 /* Both strings have an @ symbol in them */
188                 if (username_mask_pos && username_addr_pos)
189                 {
190                         /* Zero out the location of the @ symbol */
191                         *username_mask_pos = *username_addr_pos = 0;
192
193                         /* Try and match() the strings before the @
194                          * symbols, and recursively call MatchCIDR without
195                          * username matching enabled to match the host part.
196                          */
197                         bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
198
199                         /* Free the stuff we created */
200                         free(address_dupe);
201                         free(cidr_dupe);
202
203                         /* Return a result */
204                         return result;
205                 }
206                 else
207                 {
208                         /* One or both didnt have an @ in,
209                          * just match as CIDR
210                          */
211                         free(address_dupe);
212                         free(cidr_dupe);
213                         mask = strdup(cidr_mask);
214                 }
215         }
216         else
217         {
218                 /* Make a copy of the cidr mask string,
219                  * we're going to change it
220                  */
221                 mask = strdup(cidr_mask);
222         }
223
224         in_addr  address_in4;
225         in_addr  mask_in4;
226
227
228         /* Use strrchr for this, its nearer to the right */
229         char* bits_chars = strrchr(mask,'/');
230
231         if (bits_chars)
232         {
233                 bits = atoi(bits_chars + 1);
234                 *bits_chars = 0;
235         }
236         else
237         {
238                 /* No 'number of bits' field! */
239                 free(mask);
240                 return false;
241         }
242
243 #ifdef SUPPORT_IP6LINKS
244         in6_addr address_in6;
245         in6_addr mask_in6;
246
247         if (inet_pton(AF_INET6, address, &address_in6) > 0)
248         {
249                 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
250                 {
251                         memcpy(&addr_raw, &address_in6.s6_addr, 16);
252                         memcpy(&mask_raw, &mask_in6.s6_addr, 16);
253
254                         if (bits > 128)
255                                 bits = 128;
256                 }
257                 else
258                 {
259                         /* The address was valid ipv6, but the mask
260                          * that goes with it wasnt.
261                          */
262                         free(mask);
263                         return false;
264                 }
265         }
266         else
267 #endif
268         if (inet_pton(AF_INET, address, &address_in4) > 0)
269         {
270                 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
271                 {
272                         memcpy(&addr_raw, &address_in4.s_addr, 4);
273                         memcpy(&mask_raw, &mask_in4.s_addr, 4);
274
275                         if (bits > 32)
276                                 bits = 32;
277                 }
278                 else
279                 {
280                         /* The address was valid ipv4,
281                          * but the mask that went with it wasnt.
282                          */
283                         free(mask);
284                         return false;
285                 }
286         }
287         else
288         {
289                 /* The address was neither ipv4 or ipv6 */
290                 free(mask);
291                 return false;
292         }
293
294         /* Low-level-match the bits in the raw data */
295         free(mask);
296         return MatchCIDRBits(addr_raw, mask_raw, bits);
297 }
298
299 void irc::sockets::Blocking(int s)
300 {
301         int flags = fcntl(s, F_GETFL, 0);
302         fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
303 }
304
305 void irc::sockets::NonBlocking(int s)
306 {
307         int flags = fcntl(s, F_GETFL, 0);
308         fcntl(s, F_SETFL, flags | O_NONBLOCK);
309 }
310
311 /** This will bind a socket to a port. It works for UDP/TCP.
312  * It can only bind to IP addresses, if you wish to bind to hostnames
313  * you should first resolve them using class 'Resolver'.
314  */ 
315 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr clientn, insp_sockaddr servern, int port, char* addr)
316 {
317         /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
318         sockaddr* server = new sockaddr[2];
319         memset(server,0,sizeof(sockaddr)*2);
320
321         int ret, size;
322
323         if (*addr == '*')
324                 *addr = 0;
325
326 #ifdef IPV6
327         if (*addr)
328         {
329                 printf("Address %s not empty\n", addr);
330                 /* There is an address here. Is it ipv6? */
331                 if (strchr(addr,':'))
332                 {
333                         printf("Address %s is ipv6\n", addr);
334                         /* Yes it is */
335                         in6_addr addy;
336                         if (inet_pton(AF_INET6, addr, &addy) < 1)
337                         {
338                                 printf("Failed to interpret address %s", addr);
339                                 delete[] server;
340                                 return false;
341                         }
342
343                         ((sockaddr_in6*)server)->sin6_family = AF_INET6;
344                         memcpy(&(((sockaddr_in6*)server)->sin6_addr), &addy, sizeof(in6_addr));
345                         ((sockaddr_in6*)server)->sin6_port = htons(port);
346                         size = sizeof(sockaddr_in6);
347                 }
348                 else
349                 {
350                         /* No, its not */
351                         printf("Address %s is ipv4\n", addr);
352                         in_addr addy;
353                         if (inet_pton(AF_INET, addr, &addy) < 1)
354                         {
355                                 delete[] server;
356                                 return false;
357                         }
358
359                         ((sockaddr_in*)server)->sin_family = AF_INET;
360                         ((sockaddr_in*)server)->sin_addr = addy;
361                         ((sockaddr_in*)server)->sin_port = htons(port);
362                         size = sizeof(sockaddr_in);
363                 }
364         }
365         else
366         {
367                 printf("Address empty\n");
368                 /* Theres no address here, default to ipv6 bind to all */
369                 ((sockaddr_in6*)server)->sin6_family = AF_INET6;
370                 memset(&(((sockaddr_in6*)server)->sin6_addr), 0, sizeof(in6_addr));
371                 ((sockaddr_in6*)server)->sin6_port = htons(port);
372                 size = sizeof(sockaddr_in6);
373         }
374 #else
375         /* If we aren't built with ipv6, the choice becomes simple */
376         ((sockaddr_in*)server)->sin_family = AF_INET;
377         if (*addr)
378         {
379                 /* There is an address here. */
380                 in_addr addy;
381                 if (inet_pton(AF_INET, addr, &addy) < 1)
382                 {
383                         delete[] server;
384                         return false;
385                 }
386                 ((sockaddr_in*)server)->sin_addr = addy;
387         }
388         else
389         {
390                 /* Bind ipv4 to all */
391                 ((sockaddr_in*)server)->sin_addr.s_addr = htonl(INADDR_ANY);
392         }
393         /* Bind ipv4 port number */
394         ((sockaddr_in*)server)->sin_port = htons(port);
395         size = sizeof(sockaddr_in);
396 #endif
397         ret = bind(sockfd, server, size);
398         delete[] server;
399
400         if (ret < 0)
401         {
402                 Log(DEBUG,"Bind fails it! %s", strerror(errno));
403                 return false;
404         }
405         else
406         {
407                 if (listen(sockfd, Config->MaxConn) == -1)
408                 {
409                         this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
410                         return false;
411                 }
412                 else
413                 {
414                         NonBlocking(sockfd);
415                         return true;
416                 }
417         }
418 }
419
420
421 // Open a TCP Socket
422 int irc::sockets::OpenTCPSocket(char* addr)
423 {
424         int sockfd;
425         int on = 1;
426         struct linger linger = { 0 };
427 #ifdef IPV6
428         printf("IPV6 ENABLED OPENTCPSOCKET\n");
429         if (strchr(addr,':') || (!*addr))
430         {
431                 printf("IPV6 OPENTCPSOCKET DO\n");
432                 sockfd = socket (PF_INET6, SOCK_STREAM, 0);
433         }
434         else
435         {
436                 printf("IPV6->IPV4 OPENTCPSOCKET DO\n");
437                 sockfd = socket (PF_INET, SOCK_STREAM, 0);
438         }
439         if (sockfd < 0)
440 #else
441         if ((sockfd = socket (PF_INET, SOCK_STREAM, 0)) < 0)
442 #endif
443         {
444                 printf("SOCKET FAIL: %s\n", strerror(errno));
445                 return ERROR;
446         }
447         else
448         {
449                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
450                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
451                 linger.l_onoff = 1;
452                 linger.l_linger = 1;
453                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
454                 return (sockfd);
455         }
456 }
457
458 /* XXX: Probably belongs in class InspIRCd */
459 bool InspIRCd::HasPort(int port, char* addr)
460 {
461         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
462         {
463                 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
464                 {
465                         return true;
466                 }
467         }
468         return false;
469 }
470
471 /* XXX: Probably belongs in class InspIRCd */
472 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
473 {
474         Log(DEBUG,"BINDING PORTS");
475         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
476         insp_sockaddr client, server;
477         int clientportcount = 0;
478         int BoundPortCount = 0;
479
480         ports_found = 0;
481
482         int InitialPortCount = stats->BoundPortCount;
483
484         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
485         {
486                 Log(DEBUG,"FOUND PORT");
487                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
488                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
489                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
490
491                 if ((!*Type) || (!strcmp(Type,"clients")))
492                 {
493                         irc::portparser portrange(configToken, false);
494                         long portno = -1;
495                         while ((portno = portrange.GetToken()))
496                         {
497                                 if (!HasPort(portno, Addr))
498                                 {
499                                         ports_found++;
500                                         Config->ports[clientportcount+InitialPortCount] = portno;
501                                         if (*Addr == '*')
502                                                 *Addr = 0;
503
504                                         strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
505                                         clientportcount++;
506                                 }
507                         }
508                 }
509
510                 if (!bail)
511                 {
512                         int PortCount = clientportcount;
513                         if (PortCount)
514                         {
515                                 BoundPortCount = stats->BoundPortCount;
516                                 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
517                                 {
518                                         int fd = OpenTCPSocket(Config->addrs[count]);
519                                         if (fd == ERROR)
520                                         {
521                                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
522                                                 Log(DEBUG,"SOCKET FAIL");
523                                         }
524                                         else
525                                         {
526                                                 Log(DEBUG,"BIND");
527                                                 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
528                                                 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
529                                                 {
530                                                         if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
531                                                         {
532                                                                 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
533                                                                 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
534                                                                 close(Config->openSockfd[BoundPortCount]->GetFd());
535                                                                 delete Config->openSockfd[BoundPortCount];
536                                                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
537                                                         }
538                                                         else
539                                                                 BoundPortCount++;
540                                                 }
541                                         }
542                                 }
543                                 return InitialPortCount + BoundPortCount;
544                         }
545                         return InitialPortCount;
546                 }
547         }
548
549         int PortCount = clientportcount;
550
551         for (int count = 0; count < PortCount; count++)
552         {
553                 int fd = OpenTCPSocket(Config->addrs[count]);
554                 if (fd == ERROR)
555                 {
556                         Log(DEBUG,"SOCKET FAIL");
557                         failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
558                 }
559                 else
560                 {
561                         Log(DEBUG,"BIND");
562                         Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
563                         if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
564                         {
565                                 BoundPortCount++;
566                         }
567                         else
568                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
569                 }
570         }
571         return BoundPortCount;
572 }
573
574 const char* irc::sockets::insp_ntoa(insp_inaddr n)
575 {
576         static char buf[1024];
577         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
578         return buf;
579 }
580
581 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
582 {
583         return inet_pton(AF_FAMILY, a, n);
584 }
585