]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
And fix a bug
[user/henk/code/inspircd.git] / src / socket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include <string>
18 #include "configreader.h"
19 #include "socket.h"
20 #include "inspircd.h"
21 #include "inspstring.h"
22 #include "helperfuncs.h"
23 #include "socketengine.h"
24 #include "wildcard.h"
25
26 extern InspIRCd* ServerInstance;
27 extern time_t TIME;
28
29 using namespace std;
30 using namespace irc::sockets;
31
32 /* Used when comparing CIDR masks for the modulus bits left over.
33  * A lot of ircd's seem to do this:
34  * ((-1) << (8 - (mask % 8)))
35  * But imho, it sucks in comparison to a nice neat lookup table.
36  */
37 const char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits - never actually used */
38                                 0x80, /* 10000000 - 1 bits */
39                                 0xC0, /* 11000000 - 2 bits */
40                                 0xE0, /* 11100000 - 3 bits */
41                                 0xF0, /* 11110000 - 4 bits */
42                                 0xF8, /* 11111000 - 5 bits */
43                                 0xFC, /* 11111100 - 6 bits */
44                                 0xFE  /* 11111110 - 7 bits */
45 };
46
47 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
48 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
49 {
50         unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
51         unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
52
53         /* First compare the whole bytes, if they dont match, return false */
54         if (memcmp(address, mask, divisor))
55                 return false;
56
57         /* Now if there are any remainder bits, we compare them with logic AND */
58         if (modulus)
59                 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
60                         /* If they dont match, return false */
61                         return false;
62
63         /* The address matches the mask, to mask_bits bits of mask */
64         return true;
65 }
66
67 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
68 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
69 {
70         return MatchCIDR(address, cidr_mask, false);
71 }
72
73 /* 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
74  * If you have a lot of hosts to match, youre probably better off building your mask once
75  * and then using the lower level MatchCIDRBits directly.
76  *
77  * This will also attempt to match any leading usernames or nicknames on the mask, using
78  * match(), when match_with_username is true.
79  */
80 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
81 {
82         unsigned char addr_raw[16];
83         unsigned char mask_raw[16];
84         unsigned int bits = 0;
85         char* mask = NULL;
86
87         /* The caller is trying to match ident@<mask>/bits.
88          * Chop off the ident@ portion, use match() on it
89          * seperately.
90          */
91         if (match_with_username)
92         {
93                 /* Duplicate the strings, and try to find the position
94                  * of the @ symbol in each */
95                 char* address_dupe = strdup(address);
96                 char* cidr_dupe = strdup(cidr_mask);
97         
98                 /* Use strchr not strrchr, because its going to be nearer to the left */
99                 char* username_mask_pos = strrchr(cidr_dupe, '@');
100                 char* username_addr_pos = strrchr(address_dupe, '@');
101
102                 /* Both strings have an @ symbol in them */
103                 if (username_mask_pos && username_addr_pos)
104                 {
105                         /* Zero out the location of the @ symbol */
106                         *username_mask_pos = *username_addr_pos = 0;
107
108                         /* Try and match() the strings before the @
109                          * symbols, and recursively call MatchCIDR without
110                          * username matching enabled to match the host part.
111                          */
112                         bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
113
114                         /* Free the stuff we created */
115                         free(address_dupe);
116                         free(cidr_dupe);
117
118                         /* Return a result */
119                         return result;
120                 }
121                 else
122                 {
123                         /* One or both didnt have an @ in,
124                          * just match as CIDR
125                          */
126                         free(address_dupe);
127                         free(cidr_dupe);
128                         mask = strdup(cidr_mask);
129                 }
130         }
131         else
132         {
133                 /* Make a copy of the cidr mask string,
134                  * we're going to change it
135                  */
136                 mask = strdup(cidr_mask);
137         }
138
139         in_addr  address_in4;
140         in_addr  mask_in4;
141
142
143         /* Use strrchr for this, its nearer to the right */
144         char* bits_chars = strrchr(mask,'/');
145
146         if (bits_chars)
147         {
148                 bits = atoi(bits_chars + 1);
149                 *bits_chars = 0;
150         }
151         else
152         {
153                 /* No 'number of bits' field! */
154                 return false;
155         }
156
157 #ifdef SUPPORT_IP6LINKS
158         in6_addr address_in6;
159         in6_addr mask_in6;
160
161         if (inet_pton(AF_INET6, address, &address_in6) > 0)
162         {
163                 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
164                 {
165                         memcpy(&addr_raw, &address_in6.s6_addr, 16);
166                         memcpy(&mask_raw, &mask_in6.s6_addr, 16);
167
168                         if (bits > 128)
169                                 bits = 128;
170                 }
171                 else
172                 {
173                         /* The address was valid ipv6, but the mask
174                          * that goes with it wasnt.
175                          */
176                         free(mask);
177                         return false;
178                 }
179         }
180         else
181 #endif
182         if (inet_pton(AF_INET, address, &address_in4) > 0)
183         {
184                 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
185                 {
186                         memcpy(&addr_raw, &address_in4.s_addr, 4);
187                         memcpy(&mask_raw, &mask_in4.s_addr, 4);
188
189                         if (bits > 32)
190                                 bits = 32;
191                 }
192                 else
193                 {
194                         /* The address was valid ipv4,
195                          * but the mask that went with it wasnt.
196                          */
197                         free(mask);
198                         return false;
199                 }
200         }
201         else
202         {
203                 /* The address was neither ipv4 or ipv6 */
204                 free(mask);
205                 return false;
206         }
207
208         /* Low-level-match the bits in the raw data */
209         free(mask);
210         return MatchCIDRBits(addr_raw, mask_raw, bits);
211 }
212
213 inline void irc::sockets::Blocking(int s)
214 {
215         int flags = fcntl(s, F_GETFL, 0);
216         fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
217 }
218
219 inline void irc::sockets::NonBlocking(int s)
220 {
221         int flags = fcntl(s, F_GETFL, 0);
222         fcntl(s, F_SETFL, flags | O_NONBLOCK);
223 }
224
225
226 /** This will bind a socket to a port. It works for UDP/TCP.
227  * It can only bind to IP addresses, if you wish to bind to hostnames
228  * you should first resolve them using class 'Resolver'.
229  */ 
230 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
231 {
232         memset(&server,0,sizeof(server));
233         insp_inaddr addy;
234
235         if (*addr == '*')
236                 *addr = 0;
237
238         if ((*addr) && (insp_aton(addr,&addy) < 1))
239         {
240                 log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
241                 return false;;
242         }
243
244 #ifdef IPV6
245         server.sin6_family = AF_FAMILY;
246 #else
247         server.sin_family = AF_FAMILY;
248 #endif
249         if (!*addr)
250         {
251 #ifdef IPV6
252                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
253 #else
254                 server.sin_addr.s_addr = htonl(INADDR_ANY);
255 #endif
256         }
257         else
258         {
259 #ifdef IPV6
260                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
261 #else
262                 server.sin_addr = addy;
263 #endif
264         }
265 #ifdef IPV6
266         server.sin6_port = htons(port);
267 #else
268         server.sin_port = htons(port);
269 #endif
270         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
271         {
272                 return false;
273         }
274         else
275         {
276                 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
277                 if (listen(sockfd, Config->MaxConn) == -1)
278                 {
279                         log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
280                         return false;
281                 }
282                 else
283                 {
284                         NonBlocking(sockfd);
285                         return true;
286                 }
287         }
288 }
289
290
291 // Open a TCP Socket
292 int irc::sockets::OpenTCPSocket()
293 {
294         int sockfd;
295         int on = 1;
296         struct linger linger = { 0 };
297   
298         if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
299         {
300                 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
301                 return (ERROR);
302         }
303         else
304         {
305                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
306                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
307                 linger.l_onoff = 1;
308                 linger.l_linger = 1;
309                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
310                 return (sockfd);
311         }
312 }
313
314 /* XXX: Probably belongs in class InspIRCd */
315 bool InspIRCd::HasPort(int port, char* addr)
316 {
317         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
318         {
319                 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
320                 {
321                         return true;
322                 }
323         }
324         return false;
325 }
326
327 /* XXX: Probably belongs in class InspIRCd */
328 int InspIRCd::BindPorts(bool bail)
329 {
330         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
331         insp_sockaddr client, server;
332         int clientportcount = 0;
333         int BoundPortCount = 0;
334
335         if (!bail)
336         {
337                 int InitialPortCount = stats->BoundPortCount;
338                 log(DEBUG,"Initial port count: %d",InitialPortCount);
339
340                 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
341                 {
342                         Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
343                         Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
344                         Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
345
346                         if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
347                         {
348                                 // modules handle server bind types now
349                                 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
350                                 if (*Addr == '*')
351                                         *Addr = 0;
352
353                                 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
354                                 clientportcount++;
355                                 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
356                         }
357                 }
358                 int PortCount = clientportcount;
359                 if (PortCount)
360                 {
361                         for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
362                         {
363                                 if ((Config->openSockfd[count] = OpenTCPSocket()) == ERROR)
364                                 {
365                                         log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[count],Config->addrs[count],Config->ports[count]);
366                                 }
367                                 else
368                                 {
369                                         if (!BindSocket(Config->openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
370                                         {
371                                                 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
372                                         }
373                                         else
374                                         {
375                                                 /* Associate the new open port with a slot in the socket engine */
376                                                 if (Config->openSockfd[count] > -1)
377                                                 {
378                                                         if (!SE->AddFd(Config->openSockfd[count],true,X_LISTEN))
379                                                         {
380                                                                 log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
381                                                                 shutdown(Config->openSockfd[count],2);
382                                                                 close(Config->openSockfd[count]);
383                                                         }
384                                                         else
385                                                                 BoundPortCount++;
386                                                 }
387                                         }
388                                 }
389                         }
390                         return InitialPortCount + BoundPortCount;
391                 }
392                 else
393                 {
394                         log(DEBUG,"There is nothing new to bind!");
395                 }
396                 return InitialPortCount;
397         }
398
399         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
400         {
401                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
402                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
403                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
404
405                 if ((!*Type) || (!strcmp(Type,"clients")))
406                 {
407                         // modules handle server bind types now
408                         Config->ports[clientportcount] = atoi(configToken);
409
410                         // If the client put bind "*", this is an unrealism.
411                         // We don't actually support this as documented, but
412                         // i got fed up of people trying it, so now it converts
413                         // it to an empty string meaning the same 'bind to all'.
414                         if (*Addr == '*')
415                                 *Addr = 0;
416
417                         strlcpy(Config->addrs[clientportcount],Addr,256);
418                         clientportcount++;
419                         log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
420                 }
421         }
422
423         int PortCount = clientportcount;
424
425         for (int count = 0; count < PortCount; count++)
426         {
427                 if ((Config->openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
428                 {
429                         log(DEBUG,"Bad fd %d binding port [%s:%d]",Config->openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
430                 }
431                 else
432                 {
433                         if (!BindSocket(Config->openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
434                         {
435                                 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
436                         }
437                         else
438                         {
439                                 /* well we at least bound to one socket so we'll continue */
440                                 BoundPortCount++;
441                         }
442                 }
443         }
444         return BoundPortCount;
445 }
446
447 const char* irc::sockets::insp_ntoa(insp_inaddr n)
448 {
449         static char buf[1024];
450         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
451         return buf;
452 }
453
454 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
455 {
456         return inet_pton(AF_FAMILY, a, n);
457 }
458