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