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