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