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