]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
I'll give you ##TOAST, :p
[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 "socketengine.h"
22 #include "wildcard.h"
23
24 using namespace std;
25 using namespace irc::sockets;
26
27 /* Used when comparing CIDR masks for the modulus bits left over.
28  * A lot of ircd's seem to do this:
29  * ((-1) << (8 - (mask % 8)))
30  * But imho, it sucks in comparison to a nice neat lookup table.
31  */
32 const char inverted_bits[8] = { 0x00, /* 00000000 - 0 bits - never actually used */
33                                 0x80, /* 10000000 - 1 bits */
34                                 0xC0, /* 11000000 - 2 bits */
35                                 0xE0, /* 11100000 - 3 bits */
36                                 0xF0, /* 11110000 - 4 bits */
37                                 0xF8, /* 11111000 - 5 bits */
38                                 0xFC, /* 11111100 - 6 bits */
39                                 0xFE  /* 11111110 - 7 bits */
40 };
41
42
43 ListenSocket::ListenSocket(InspIRCd* Instance, int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr) : ServerInstance(Instance)
44 {
45         this->SetFd(sockfd);
46         Instance->Log(DEBUG,"Binding to port %s:%d",addr,port);
47         if (!Instance->BindSocket(this->fd,client,server,port,addr))
48         {
49                 Instance->Log(DEBUG,"Binding failed!");
50                 this->fd = -1;
51         }
52 }
53
54 void ListenSocket::HandleEvent(EventType et)
55 {
56         insp_sockaddr sock_us;  // our port number
57         socklen_t uslen;        // length of our port number
58         insp_sockaddr client;
59         socklen_t length;
60         int incomingSockfd, in_port;
61
62         ServerInstance->Log(DEBUG,"Handle ListenSocket event");
63
64         uslen = sizeof(sock_us);
65         length = sizeof(client);
66         incomingSockfd = accept (this->GetFd(),(struct sockaddr*)&client, &length);
67         
68         if ((incomingSockfd > -1) && (!getsockname(incomingSockfd, (sockaddr*)&sock_us, &uslen)))
69         {
70 #ifdef IPV6
71                 in_port = ntohs(sock_us.sin6_port);
72 #else
73                 in_port = ntohs(sock_us.sin_port);
74 #endif
75                 ServerInstance->Log(DEBUG,"Accepted socket %d",incomingSockfd);
76                 NonBlocking(incomingSockfd);
77                 if (ServerInstance->Config->GetIOHook(in_port))
78                 {
79                         try
80                         {
81 #ifdef IPV6
82                                 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
83 #else
84                                 ServerInstance->Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
85 #endif
86                         }
87                         catch (ModuleException& modexcept)
88                         {
89                                 ServerInstance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
90                         }
91                 }
92                 ServerInstance->stats->statsAccept++;
93 #ifdef IPV6
94                 ServerInstance->Log(DEBUG,"Add ipv6 client");
95                 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin6_addr);
96 #else
97                 ServerInstance->Log(DEBUG,"Add ipv4 client");
98                 userrec::AddClient(ServerInstance, incomingSockfd, in_port, false, client.sin_addr);
99 #endif
100                 ServerInstance->Log(DEBUG,"Adding client on port %d fd=%d",in_port,incomingSockfd);
101         }
102         else
103         {
104                 ServerInstance->Log(DEBUG,"Accept failed on fd %d: %s",incomingSockfd,strerror(errno));
105                 shutdown(incomingSockfd,2);
106                 close(incomingSockfd);
107                 ServerInstance->stats->statsRefused++;
108         }
109 }
110
111 /* Match raw bytes using CIDR bit matching, used by higher level MatchCIDR() */
112 bool irc::sockets::MatchCIDRBits(unsigned char* address, unsigned char* mask, unsigned int mask_bits)
113 {
114         unsigned int modulus = mask_bits % 8; /* Number of whole bytes in the mask */
115         unsigned int divisor = mask_bits / 8; /* Remaining bits in the mask after whole bytes are dealt with */
116
117         /* First compare the whole bytes, if they dont match, return false */
118         if (memcmp(address, mask, divisor))
119                 return false;
120
121         /* Now if there are any remainder bits, we compare them with logic AND */
122         if (modulus)
123                 if ((address[divisor] & inverted_bits[modulus]) != (mask[divisor] & inverted_bits[modulus]))
124                         /* If they dont match, return false */
125                         return false;
126
127         /* The address matches the mask, to mask_bits bits of mask */
128         return true;
129 }
130
131 /* Match CIDR, but dont attempt to match() against leading *!*@ sections */
132 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask)
133 {
134         return MatchCIDR(address, cidr_mask, false);
135 }
136
137 /* 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
138  * If you have a lot of hosts to match, youre probably better off building your mask once
139  * and then using the lower level MatchCIDRBits directly.
140  *
141  * This will also attempt to match any leading usernames or nicknames on the mask, using
142  * match(), when match_with_username is true.
143  */
144 bool irc::sockets::MatchCIDR(const char* address, const char* cidr_mask, bool match_with_username)
145 {
146         unsigned char addr_raw[16];
147         unsigned char mask_raw[16];
148         unsigned int bits = 0;
149         char* mask = NULL;
150
151         /* The caller is trying to match ident@<mask>/bits.
152          * Chop off the ident@ portion, use match() on it
153          * seperately.
154          */
155         if (match_with_username)
156         {
157                 /* Duplicate the strings, and try to find the position
158                  * of the @ symbol in each */
159                 char* address_dupe = strdup(address);
160                 char* cidr_dupe = strdup(cidr_mask);
161         
162                 /* Use strchr not strrchr, because its going to be nearer to the left */
163                 char* username_mask_pos = strrchr(cidr_dupe, '@');
164                 char* username_addr_pos = strrchr(address_dupe, '@');
165
166                 /* Both strings have an @ symbol in them */
167                 if (username_mask_pos && username_addr_pos)
168                 {
169                         /* Zero out the location of the @ symbol */
170                         *username_mask_pos = *username_addr_pos = 0;
171
172                         /* Try and match() the strings before the @
173                          * symbols, and recursively call MatchCIDR without
174                          * username matching enabled to match the host part.
175                          */
176                         bool result = (match(address_dupe, cidr_dupe) && MatchCIDR(username_addr_pos + 1, username_mask_pos + 1, false));
177
178                         /* Free the stuff we created */
179                         free(address_dupe);
180                         free(cidr_dupe);
181
182                         /* Return a result */
183                         return result;
184                 }
185                 else
186                 {
187                         /* One or both didnt have an @ in,
188                          * just match as CIDR
189                          */
190                         free(address_dupe);
191                         free(cidr_dupe);
192                         mask = strdup(cidr_mask);
193                 }
194         }
195         else
196         {
197                 /* Make a copy of the cidr mask string,
198                  * we're going to change it
199                  */
200                 mask = strdup(cidr_mask);
201         }
202
203         in_addr  address_in4;
204         in_addr  mask_in4;
205
206
207         /* Use strrchr for this, its nearer to the right */
208         char* bits_chars = strrchr(mask,'/');
209
210         if (bits_chars)
211         {
212                 bits = atoi(bits_chars + 1);
213                 *bits_chars = 0;
214         }
215         else
216         {
217                 /* No 'number of bits' field! */
218                 free(mask);
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                         BoundPortCount = stats->BoundPortCount;
426                         for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
427                         {
428                                 int fd = OpenTCPSocket();
429                                 if (fd == ERROR)
430                                 {
431                                         this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
432                                 }
433                                 else
434                                 {
435                                         Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
436                                         if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
437                                         {
438                                                 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
439                                                 {
440                                                         this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
441                                                         shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
442                                                         close(Config->openSockfd[BoundPortCount]->GetFd());
443                                                         delete Config->openSockfd[BoundPortCount];
444                                                 }
445                                                 else
446                                                         BoundPortCount++;
447                                         }
448                                         /*if (!BindSocket(Config->openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
449                                         {
450                                                 this->Log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
451                                         }*/
452                                 }
453                         }
454                         return InitialPortCount + BoundPortCount;
455                 }
456                 else
457                 {
458                         this->Log(DEBUG,"There is nothing new to bind!");
459                 }
460                 return InitialPortCount;
461         }
462
463         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
464         {
465                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
466                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
467                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
468
469                 if ((!*Type) || (!strcmp(Type,"clients")))
470                 {
471                         // modules handle server bind types now
472                         Config->ports[clientportcount] = atoi(configToken);
473
474                         // If the client put bind "*", this is an unrealism.
475                         // We don't actually support this as documented, but
476                         // i got fed up of people trying it, so now it converts
477                         // it to an empty string meaning the same 'bind to all'.
478                         if (*Addr == '*')
479                                 *Addr = 0;
480
481                         strlcpy(Config->addrs[clientportcount],Addr,256);
482                         clientportcount++;
483                         this->Log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
484                 }
485         }
486
487         int PortCount = clientportcount;
488
489         for (int count = 0; count < PortCount; count++)
490         {
491                 int fd = OpenTCPSocket();
492                 if (fd == ERROR)
493                 {
494                         this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
495                 }
496                 else
497                 {
498                         Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
499                         if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
500                         {
501                                 BoundPortCount++;
502                         }
503                         /*if (!BindSocket(Config->openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
504                         {
505                                 this->Log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
506                         }*/
507                 }
508         }
509         return BoundPortCount;
510 }
511
512 const char* irc::sockets::insp_ntoa(insp_inaddr n)
513 {
514         static char buf[1024];
515         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
516         return buf;
517 }
518
519 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
520 {
521         return inet_pton(AF_FAMILY, a, n);
522 }
523