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