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