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