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