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