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