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