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