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