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