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