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