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