]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
Same again
[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, int errornum)
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, int &ports_found, FailedPortList &failed_ports)
393 {
394         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
395         insp_sockaddr client, server;
396         int clientportcount = 0;
397         int BoundPortCount = 0;
398
399         ports_found = 0;
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")))
411                 {
412                         irc::portparser portrange(configToken, false);
413                         long portno = -1;
414                         while ((portno = portrange.GetToken()))
415                         {
416                                 if (!HasPort(portno, Addr))
417                                 {
418                                         ports_found++;
419                                         Config->ports[clientportcount+InitialPortCount] = portno;
420                                         if (*Addr == '*')
421                                                 *Addr = 0;
422
423                                         strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
424                                         clientportcount++;
425                                         this->Log(DEBUG,"NEW binding %s:%d [%s] from config",Addr, portno, Type);
426                                 }
427                         }
428                 }
429
430                 if (!bail)
431                 {
432                         int PortCount = clientportcount;
433                         if (PortCount)
434                         {
435                                 BoundPortCount = stats->BoundPortCount;
436                                 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
437                                 {
438                                         int fd = OpenTCPSocket();
439                                         if (fd == ERROR)
440                                         {
441                                                 this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
442                                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
443                                         }
444                                         else
445                                         {
446                                                 Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
447                                                 if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
448                                                 {
449                                                         if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
450                                                         {
451                                                                 this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
452                                                                 shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
453                                                                 close(Config->openSockfd[BoundPortCount]->GetFd());
454                                                                 delete Config->openSockfd[BoundPortCount];
455                                                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
456                                                         }
457                                                         else
458                                                                 BoundPortCount++;
459                                                 }
460                                         }
461                                 }
462                                 return InitialPortCount + BoundPortCount;
463                         }
464                         else
465                         {
466                                 this->Log(DEBUG,"There is nothing new to bind!");
467                         }
468                         return InitialPortCount;
469                 }
470         }
471
472         int PortCount = clientportcount;
473
474         for (int count = 0; count < PortCount; count++)
475         {
476                 int fd = OpenTCPSocket();
477                 if (fd == ERROR)
478                 {
479                         this->Log(DEBUG,"Bad fd %d binding port [%s:%d]",fd,Config->addrs[count],Config->ports[count]);
480                         failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
481                 }
482                 else
483                 {
484                         Config->openSockfd[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
485                         if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
486                         {
487                                 BoundPortCount++;
488                         }
489                         else
490                                 failed_ports.push_back(std::make_pair(Config->addrs[count],Config->ports[count]));
491                 }
492         }
493         return BoundPortCount;
494 }
495
496 const char* irc::sockets::insp_ntoa(insp_inaddr n)
497 {
498         static char buf[1024];
499         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
500         return buf;
501 }
502
503 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
504 {
505         return inet_pton(AF_FAMILY, a, n);
506 }
507