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