]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
b286ee96fe1b977cb994c664ee4cbd692aa50863
[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 inline 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 inline 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
287 /** This will bind a socket to a port. It works for UDP/TCP.
288  * It can only bind to IP addresses, if you wish to bind to hostnames
289  * you should first resolve them using class 'Resolver'.
290  */ 
291 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
292 {
293         memset(&server,0,sizeof(server));
294         insp_inaddr addy;
295
296         if (*addr == '*')
297                 *addr = 0;
298
299         if ((*addr) && (insp_aton(addr,&addy) < 1))
300         {
301                 this->Log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
302                 return false;;
303         }
304
305 #ifdef IPV6
306         server.sin6_family = AF_FAMILY;
307 #else
308         server.sin_family = AF_FAMILY;
309 #endif
310         if (!*addr)
311         {
312 #ifdef IPV6
313                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
314 #else
315                 server.sin_addr.s_addr = htonl(INADDR_ANY);
316 #endif
317         }
318         else
319         {
320 #ifdef IPV6
321                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
322 #else
323                 server.sin_addr = addy;
324 #endif
325         }
326 #ifdef IPV6
327         server.sin6_port = htons(port);
328 #else
329         server.sin_port = htons(port);
330 #endif
331         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
332         {
333                 return false;
334         }
335         else
336         {
337                 this->Log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
338                 if (listen(sockfd, Config->MaxConn) == -1)
339                 {
340                         this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
341                         return false;
342                 }
343                 else
344                 {
345                         NonBlocking(sockfd);
346                         return true;
347                 }
348         }
349 }
350
351
352 // Open a TCP Socket
353 int irc::sockets::OpenTCPSocket()
354 {
355         int sockfd;
356         int on = 1;
357         struct linger linger = { 0 };
358   
359         if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
360         {
361                 return ERROR;
362         }
363         else
364         {
365                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
366                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
367                 linger.l_onoff = 1;
368                 linger.l_linger = 1;
369                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
370                 return (sockfd);
371         }
372 }
373
374 /* XXX: Probably belongs in class InspIRCd */
375 bool InspIRCd::HasPort(int port, char* addr)
376 {
377         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
378         {
379                 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
380                 {
381                         return true;
382                 }
383         }
384         return false;
385 }
386
387 /* XXX: Probably belongs in class InspIRCd */
388 int InspIRCd::BindPorts(bool bail, int &ports_found, FailedPortList &failed_ports)
389 {
390         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
391         insp_sockaddr client, server;
392         int clientportcount = 0;
393         int BoundPortCount = 0;
394
395         ports_found = 0;
396
397         int InitialPortCount = stats->BoundPortCount;
398         this->Log(DEBUG,"Initial port count: %d",InitialPortCount);
399
400         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
401         {
402                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
403                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
404                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
405
406                 if ((!*Type) || (!strcmp(Type,"clients")))
407                 {
408                         irc::portparser portrange(configToken, false);
409                         long portno = -1;
410                         while ((portno = portrange.GetToken()))
411                         {
412                                 if (!HasPort(portno, Addr))
413                                 {
414                                         ports_found++;
415                                         Config->ports[clientportcount+InitialPortCount] = portno;
416                                         if (*Addr == '*')
417                                                 *Addr = 0;
418
419                                         strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
420                                         clientportcount++;
421                                         this->Log(DEBUG,"NEW binding %s:%d [%s] from config",Addr, portno, Type);
422                                 }
423                         }
424                 }
425
426                 if (!bail)
427                 {
428                         int PortCount = clientportcount;
429                         if (PortCount)
430                         {
431                                 BoundPortCount = stats->BoundPortCount;
432                                 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
433                                 {
434                                         int fd = OpenTCPSocket();
435                                         if (fd == ERROR)
436                                         {
437                                                 this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
438                                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
439                                         }
440                                         else
441                                         {
442                                                 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
443                                                 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
444                                                 {
445                                                         if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
446                                                         {
447                                                                 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
448                                                                 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
449                                                                 close(Config->openSockfd[BoundPortCount]->GetFd());
450                                                                 delete Config->openSockfd[BoundPortCount];
451                                                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
452                                                         }
453                                                         else
454                                                                 BoundPortCount++;
455                                                 }
456                                         }
457                                 }
458                                 return InitialPortCount + BoundPortCount;
459                         }
460                         else
461                         {
462                                 this->Log(DEBUG,"There is nothing new to bind!");
463                         }
464                         return InitialPortCount;
465                 }
466         }
467
468         int PortCount = clientportcount;
469
470         for (int count = 0; count < PortCount; count++)
471         {
472                 int fd = OpenTCPSocket();
473                 if (fd == ERROR)
474                 {
475                         this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
476                         failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
477                 }
478                 else
479                 {
480                         Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
481                         if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
482                         {
483                                 BoundPortCount++;
484                         }
485                         else
486                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
487                 }
488         }
489         return BoundPortCount;
490 }
491
492 const char* irc::sockets::insp_ntoa(insp_inaddr n)
493 {
494         static char buf[1024];
495         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
496         return buf;
497 }
498
499 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
500 {
501         return inet_pton(AF_FAMILY, a, n);
502 }
503