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