]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
Port bindings for gnutls now bind via ip:port, rather than on all ports for that...
[user/henk/code/inspircd.git] / src / socket.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: libIRCDsocket */
15
16 #include "inspircd.h"
17 #include "socket.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 unsigned 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 port, char* addr) : ServerInstance(Instance), desc("plaintext"), bind_addr(addr), bind_port(port)
40 {
41         this->SetFd(OpenTCPSocket(addr));
42         if (this->GetFd() > -1)
43         {
44                 if (!Instance->BindSocket(this->fd,port,addr))
45                         this->fd = -1;
46 #ifdef IPV6
47                 if ((!*addr) || (strchr(addr,':')))
48                         this->family = AF_INET6;
49                 else
50 #endif
51                 this->family = AF_INET;
52                 Instance->SE->AddFd(this);
53         }
54 }
55
56 ListenSocket::~ListenSocket()
57 {
58         if (this->GetFd() > -1)
59         {
60                 ServerInstance->SE->DelFd(this);
61                 ServerInstance->Logs->Log("SOCKET", DEBUG,"Shut down listener on fd %d", this->fd);
62                 if (ServerInstance->SE->Shutdown(this, 2) || ServerInstance->SE->Close(this))
63                         ServerInstance->Logs->Log("SOCKET", DEBUG,"Failed to cancel listener: %s", strerror(errno));
64                 this->fd = -1;
65         }
66 }
67
68
69 // XXX this is a bit of an untidy way to avoid reallocating this constantly. also, we leak it on shutdown.. but that's kinda minor - w
70 static sockaddr *sock_us;
71 static sockaddr *client;
72 static bool setup_sock = false;
73
74 void ListenSocket::HandleEvent(EventType, int)
75 {
76         socklen_t uslen, length;                // length of our port number
77         int incomingSockfd, in_port;
78
79         if (!setup_sock)
80         {
81                 sock_us = new sockaddr[2];
82                 client = new sockaddr[2];
83                 setup_sock = true;
84         }
85
86 #ifdef IPV6
87         if (this->family == AF_INET6)
88         {
89                 uslen = sizeof(sockaddr_in6);
90                 length = sizeof(sockaddr_in6);
91         }
92         else
93 #endif
94         {
95                 uslen = sizeof(sockaddr_in);
96                 length = sizeof(sockaddr_in);
97         }
98
99         incomingSockfd = ServerInstance->SE->Accept(this, (sockaddr*)client, &length);
100
101         if ((incomingSockfd > -1) && (!ServerInstance->SE->GetSockName(this, sock_us, &uslen)))
102         {
103                 char buf[MAXBUF];
104                 char target[MAXBUF];
105
106                 *target = *buf = '\0';
107
108                 sockaddr* raddr = new sockaddr[2];
109
110 #ifdef IPV6
111                 if (this->family == AF_INET6)
112                 {
113                         in_port = ntohs(((sockaddr_in6*)sock_us)->sin6_port);
114                         inet_ntop(AF_INET6, &((const sockaddr_in6*)ip)->sin6_addr, buf, sizeof(buf));
115                         socklen_t raddrsz = sizeof(sockaddr_in6);
116                         if (getpeername(incomingSockfd, (sockaddr*) raddr, &raddrsz) == 0)
117                                 inet_ntop(AF_INET6, &((const sockaddr_in6*)raddr)->sin6_addr, target, sizeof(target));
118                         else
119                                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Can't get peername: %s", strerror(errno));
120                 }
121                 else
122 #endif
123                 {
124                         inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
125                         in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
126                         socklen_t raddrsz = sizeof(sockaddr_in);
127                         if (getpeername(incomingSockfd, (sockaddr*) raddr, &raddrsz) == 0)
128                                 inet_ntop(AF_INET, &((const sockaddr_in*)raddr)->sin_addr, target, sizeof(target));
129                         else
130                                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Can't get peername: %s", strerror(errno));
131
132                 }
133
134                 delete[] raddr;
135
136                 ServerInstance->SE->NonBlocking(incomingSockfd);
137
138                 ServerInstance->stats->statsAccept++;
139                 ServerInstance->Users->AddClient(ServerInstance, incomingSockfd, in_port, false, this->family, client, target);
140         }
141         else
142         {
143                 ServerInstance->SE->Shutdown(incomingSockfd, 2);
144                 ServerInstance->SE->Close(incomingSockfd);
145                 ServerInstance->stats->statsRefused++;
146         }
147 }
148
149 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
150 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
151 {
152         unsigned int divisor = mask_bits / 8; /* Number of whole bytes in the mask */
153         unsigned int modulus = mask_bits % 8; /* Remaining bits in the mask after whole bytes are dealt with */
154
155         /* First (this is faster) compare the odd bits with logic ops */
156         if (modulus)
157                 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
158                         /* If they dont match, return false */
159                         return false;
160
161         /* Secondly (this is slower) compare the whole bytes */
162         if (memcmp(address, mask, divisor))
163                 return false;
164
165         /* The address matches the mask, to mask_bits bits of mask */
166         return true;
167 }
168
169 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
170 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
171 {
172         return MatchCIDR(address, cidr_mask, false);
173 }
174
175 /* 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
176  * If you have a lot of hosts to match, youre probably better off building your mask once
177  * and then using the lower level MatchCIDRBits directly.
178  *
179  * This will also attempt to match any leading usernames or nicknames on the mask, using
180  * match(), when match_with_username is true.
181  */
182 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
183 {
184         unsigned char addr_raw[16];
185         unsigned char mask_raw[16];
186         unsigned int bits = 0;
187         char* mask = NULL;
188
189         /* The caller is trying to match ident@<mask>/bits.
190          * Chop off the ident@ portion, use match() on it
191          * seperately.
192          */
193         if (match_with_username)
194         {
195                 /* Duplicate the strings, and try to find the position
196                  * of the @ symbol in each */
197                 char* address_dupe = strdup(address);
198                 char* cidr_dupe = strdup(cidr_mask);
199         
200                 /* Use strchr not strrchr, because its going to be nearer to the left */
201                 char* username_mask_pos = strrchr(cidr_dupe, '@');
202                 char* username_addr_pos = strrchr(address_dupe, '@');
203
204                 /* Both strings have an @ symbol in them */
205                 if (username_mask_pos && username_addr_pos)
206                 {
207                         /* Zero out the location of the @ symbol */
208                         *username_mask_pos = *username_addr_pos = 0;
209
210                         /* Try and match() the strings before the @
211                          * symbols, and recursively call MatchCIDR without
212                          * username matching enabled to match the host part.
213                          */
214                         bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
215
216                         /* Free the stuff we created */
217                         free(address_dupe);
218                         free(cidr_dupe);
219
220                         /* Return a result */
221                         return result;
222                 }
223                 else
224                 {
225                         /* One or both didnt have an @ in,
226                          * just match as CIDR
227                          */
228                         free(address_dupe);
229                         free(cidr_dupe);
230                         mask = strdup(cidr_mask);
231                 }
232         }
233         else
234         {
235                 /* Make a copy of the cidr mask string,
236                  * we're going to change it
237                  */
238                 mask = strdup(cidr_mask);
239         }
240
241         in_addr  address_in4;
242         in_addr  mask_in4;
243
244
245         /* Use strrchr for this, its nearer to the right */
246         char* bits_chars = strrchr(mask,'/');
247
248         if (bits_chars)
249         {
250                 bits = atoi(bits_chars + 1);
251                 *bits_chars = 0;
252         }
253         else
254         {
255                 /* No 'number of bits' field! */
256                 free(mask);
257                 return false;
258         }
259
260 #ifdef SUPPORT_IP6LINKS
261         in6_addr address_in6;
262         in6_addr mask_in6;
263
264         if (inet_pton(AF_INET6, address, &address_in6) > 0)
265         {
266                 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
267                 {
268                         memcpy(&addr_raw, &address_in6.s6_addr, 16);
269                         memcpy(&mask_raw, &mask_in6.s6_addr, 16);
270
271                         if (bits > 128)
272                                 bits = 128;
273                 }
274                 else
275                 {
276                         /* The address was valid ipv6, but the mask
277                          * that goes with it wasnt.
278                          */
279                         free(mask);
280                         return false;
281                 }
282         }
283         else
284 #endif
285         if (inet_pton(AF_INET, address, &address_in4) > 0)
286         {
287                 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
288                 {
289                         memcpy(&addr_raw, &address_in4.s_addr, 4);
290                         memcpy(&mask_raw, &mask_in4.s_addr, 4);
291
292                         if (bits > 32)
293                                 bits = 32;
294                 }
295                 else
296                 {
297                         /* The address was valid ipv4,
298                          * but the mask that went with it wasnt.
299                          */
300                         free(mask);
301                         return false;
302                 }
303         }
304         else
305         {
306                 /* The address was neither ipv4 or ipv6 */
307                 free(mask);
308                 return false;
309         }
310
311         /* Low-level-match the bits in the raw data */
312         free(mask);
313         return MatchCIDRBits(addr_raw, mask_raw, bits);
314 }
315
316 /** This will bind a socket to a port. It works for UDP/TCP.
317  * It can only bind to IP addresses, if you wish to bind to hostnames
318  * you should first resolve them using class 'Resolver'.
319  */ 
320 bool InspIRCd::BindSocket(int sockfd, int port, const char* addr, bool dolisten)
321 {
322         /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
323         sockaddr* servaddr = new sockaddr[2];
324         memset(servaddr,0,sizeof(sockaddr)*2);
325
326         int ret, size;
327
328         if (*addr == '*')
329                 addr = "";
330
331 #ifdef IPV6
332         if (*addr)
333         {
334                 /* There is an address here. Is it ipv6? */
335                 if (strchr(addr,':'))
336                 {
337                         /* Yes it is */
338                         in6_addr addy;
339                         if (inet_pton(AF_INET6, addr, &addy) < 1)
340                         {
341                                 delete[] servaddr;
342                                 return false;
343                         }
344
345                         ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
346                         memcpy(&(((sockaddr_in6*)servaddr)->sin6_addr), &addy, sizeof(in6_addr));
347                         ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
348                         size = sizeof(sockaddr_in6);
349                 }
350                 else
351                 {
352                         /* No, its not */
353                         in_addr addy;
354                         if (inet_pton(AF_INET, addr, &addy) < 1)
355                         {
356                                 delete[] servaddr;
357                                 return false;
358                         }
359
360                         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
361                         ((sockaddr_in*)servaddr)->sin_addr = addy;
362                         ((sockaddr_in*)servaddr)->sin_port = htons(port);
363                         size = sizeof(sockaddr_in);
364                 }
365         }
366         else
367         {
368                 if (port == -1)
369                 {
370                         /* Port -1: Means UDP IPV4 port binding - Special case
371                          * used by DNS engine.
372                          */
373                         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
374                         ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
375                         ((sockaddr_in*)servaddr)->sin_port = 0;
376                         size = sizeof(sockaddr_in);
377                 }
378                 else
379                 {
380                         /* Theres no address here, default to ipv6 bind to all */
381                         ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
382                         memset(&(((sockaddr_in6*)servaddr)->sin6_addr), 0, sizeof(in6_addr));
383                         ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
384                         size = sizeof(sockaddr_in6);
385                 }
386         }
387 #else
388         /* If we aren't built with ipv6, the choice becomes simple */
389         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
390         if (*addr)
391         {
392                 /* There is an address here. */
393                 in_addr addy;
394                 if (inet_pton(AF_INET, addr, &addy) < 1)
395                 {
396                         delete[] servaddr;
397                         return false;
398                 }
399                 ((sockaddr_in*)servaddr)->sin_addr = addy;
400         }
401         else
402         {
403                 /* Bind ipv4 to all */
404                 ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
405         }
406         /* Bind ipv4 port number */
407         ((sockaddr_in*)servaddr)->sin_port = htons(port);
408         size = sizeof(sockaddr_in);
409 #endif
410         ret = SE->Bind(sockfd, servaddr, size);
411         delete[] servaddr;
412
413         if (ret < 0)
414         {
415                 return false;
416         }
417         else
418         {
419                 if (dolisten)
420                 {
421                         if (SE->Listen(sockfd, Config->MaxConn) == -1)
422                         {
423                                 this->Logs->Log("SOCKET",DEFAULT,"ERROR in listen(): %s",strerror(errno));
424                                 return false;
425                         }
426                         else
427                         {
428                                 this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d with listen: %s:%d", sockfd, addr, port);
429                                 SE->NonBlocking(sockfd);
430                                 return true;
431                         }
432                 }
433                 else
434                 {
435                         this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d without listen: %s:%d", sockfd, addr, port);
436                         return true;
437                 }
438         }
439 }
440
441 // Open a TCP Socket
442 int irc::sockets::OpenTCPSocket(char* addr, int socktype)
443 {
444         int sockfd;
445         int on = 1;
446         addr = addr;
447         struct linger linger = { 0, 0 };
448 #ifdef IPV6
449         if (strchr(addr,':') || (!*addr))
450                 sockfd = socket (PF_INET6, socktype, 0);
451         else
452                 sockfd = socket (PF_INET, socktype, 0);
453         if (sockfd < 0)
454 #else
455         if ((sockfd = socket (PF_INET, socktype, 0)) < 0)
456 #endif
457         {
458                 return ERROR;
459         }
460         else
461         {
462                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
463                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
464                 linger.l_onoff = 1;
465                 linger.l_linger = 1;
466                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (char*)&linger,sizeof(linger));
467                 return (sockfd);
468         }
469 }
470
471 int InspIRCd::BindPorts(bool, int &ports_found, FailedPortList &failed_ports)
472 {
473         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
474         int bound = 0;
475         bool started_with_nothing = (Config->ports.size() == 0);
476         std::vector<std::pair<std::string, int> > old_ports;
477
478         /* XXX: Make a copy of the old ip/port pairs here */
479         for (std::vector<ListenSocket*>::iterator o = Config->ports.begin(); o != Config->ports.end(); ++o)
480                 old_ports.push_back(make_pair((*o)->GetIP(), (*o)->GetPort()));
481
482         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
483         {
484                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
485                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
486                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
487                 
488                 if (strncmp(Addr, "::ffff:", 7) == 0)
489                         this->Logs->Log("SOCKET",DEFAULT, "Using 4in6 (::ffff:) isn't recommended. You should bind IPv4 addresses directly instead.");
490                 
491                 if ((!*Type) || (!strcmp(Type,"clients")))
492                 {
493                         irc::portparser portrange(configToken, false);
494                         int portno = -1;
495                         while ((portno = portrange.GetToken()))
496                         {
497                                 if (*Addr == '*')
498                                         *Addr = 0;
499
500                                 bool skip = false;
501                                 for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
502                                 {
503                                         if (((*n)->GetIP() == Addr) && ((*n)->GetPort() == portno))
504                                         {
505                                                 skip = true;
506                                                 /* XXX: Here, erase from our copy of the list */
507                                                 for (std::vector<std::pair<std::string, int> >::iterator k = old_ports.begin(); k != old_ports.end(); ++k)
508                                                 {
509                                                         if ((k->first == Addr) && (k->second == portno))
510                                                         {
511                                                                 old_ports.erase(k);
512                                                                 break;
513                                                         }
514                                                 }
515                                         }
516                                 }
517                                 if (!skip)
518                                 {
519                                         ListenSocket* ll = new ListenSocket(this, portno, Addr);
520                                         if (ll->GetFd() > -1)
521                                         {
522                                                 bound++;
523                                                 Config->ports.push_back(ll);
524                                         }
525                                         else
526                                         {
527                                                 failed_ports.push_back(std::make_pair(Addr, portno));
528                                         }
529                                         ports_found++;
530                                 }
531                         }
532                 }
533         }
534
535         /* XXX: Here, anything left in our copy list, close as removed */
536         if (!started_with_nothing)
537         {
538                 for (size_t k = 0; k < old_ports.size(); ++k)
539                 {
540                         for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
541                         {
542                                 if (((*n)->GetIP() == old_ports[k].first) && ((*n)->GetPort() == old_ports[k].second))
543                                 {
544                                         this->Logs->Log("SOCKET",DEFAULT,"Port binding %s:%d was removed from the config file, closing.", old_ports[k].first.c_str(), old_ports[k].second);
545                                         delete *n;
546                                         Config->ports.erase(n);
547                                         break;
548                                 }
549                         }
550                 }
551         }
552
553         return bound;
554 }
555
556 const char* irc::sockets::insp_ntoa(insp_inaddr n)
557 {
558         static char buf[1024];
559         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
560         return buf;
561 }
562
563 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
564 {
565         return inet_pton(AF_FAMILY, a, n);
566 }
567