]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
Fix for parameters which contain a colon (which is not the first char in the string)
[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                 return false;
219         }
220
221 #ifdef SUPPORT_IP6LINKS
222         in6_addr address_in6;
223         in6_addr mask_in6;
224
225         if (inet_pton(AF_INET6, address, &address_in6) > 0)
226         {
227                 if (inet_pton(AF_INET6, mask, &mask_in6) > 0)
228                 {
229                         memcpy(&addr_raw, &address_in6.s6_addr, 16);
230                         memcpy(&mask_raw, &mask_in6.s6_addr, 16);
231
232                         if (bits > 128)
233                                 bits = 128;
234                 }
235                 else
236                 {
237                         /* The address was valid ipv6, but the mask
238                          * that goes with it wasnt.
239                          */
240                         free(mask);
241                         return false;
242                 }
243         }
244         else
245 #endif
246         if (inet_pton(AF_INET, address, &address_in4) > 0)
247         {
248                 if (inet_pton(AF_INET, mask, &mask_in4) > 0)
249                 {
250                         memcpy(&addr_raw, &address_in4.s_addr, 4);
251                         memcpy(&mask_raw, &mask_in4.s_addr, 4);
252
253                         if (bits > 32)
254                                 bits = 32;
255                 }
256                 else
257                 {
258                         /* The address was valid ipv4,
259                          * but the mask that went with it wasnt.
260                          */
261                         free(mask);
262                         return false;
263                 }
264         }
265         else
266         {
267                 /* The address was neither ipv4 or ipv6 */
268                 free(mask);
269                 return false;
270         }
271
272         /* Low-level-match the bits in the raw data */
273         free(mask);
274         return MatchCIDRBits(addr_raw, mask_raw, bits);
275 }
276
277 inline void irc::sockets::Blocking(int s)
278 {
279         int flags = fcntl(s, F_GETFL, 0);
280         fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
281 }
282
283 inline void irc::sockets::NonBlocking(int s)
284 {
285         int flags = fcntl(s, F_GETFL, 0);
286         fcntl(s, F_SETFL, flags | O_NONBLOCK);
287 }
288
289
290 /** This will bind a socket to a port. It works for UDP/TCP.
291  * It can only bind to IP addresses, if you wish to bind to hostnames
292  * you should first resolve them using class 'Resolver'.
293  */ 
294 bool InspIRCd::BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr)
295 {
296         memset(&server,0,sizeof(server));
297         insp_inaddr addy;
298
299         if (*addr == '*')
300                 *addr = 0;
301
302         if ((*addr) && (insp_aton(addr,&addy) < 1))
303         {
304                 this->Log(DEBUG,"Invalid IP '%s' given to BindSocket()", addr);
305                 return false;;
306         }
307
308 #ifdef IPV6
309         server.sin6_family = AF_FAMILY;
310 #else
311         server.sin_family = AF_FAMILY;
312 #endif
313         if (!*addr)
314         {
315 #ifdef IPV6
316                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
317 #else
318                 server.sin_addr.s_addr = htonl(INADDR_ANY);
319 #endif
320         }
321         else
322         {
323 #ifdef IPV6
324                 memcpy(&addy, &server.sin6_addr, sizeof(in6_addr));
325 #else
326                 server.sin_addr = addy;
327 #endif
328         }
329 #ifdef IPV6
330         server.sin6_port = htons(port);
331 #else
332         server.sin_port = htons(port);
333 #endif
334         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
335         {
336                 return false;
337         }
338         else
339         {
340                 this->Log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
341                 if (listen(sockfd, Config->MaxConn) == -1)
342                 {
343                         this->Log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
344                         return false;
345                 }
346                 else
347                 {
348                         NonBlocking(sockfd);
349                         return true;
350                 }
351         }
352 }
353
354
355 // Open a TCP Socket
356 int irc::sockets::OpenTCPSocket()
357 {
358         int sockfd;
359         int on = 1;
360         struct linger linger = { 0 };
361   
362         if ((sockfd = socket (AF_FAMILY, SOCK_STREAM, 0)) < 0)
363         {
364                 return ERROR;
365         }
366         else
367         {
368                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
369                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
370                 linger.l_onoff = 1;
371                 linger.l_linger = 1;
372                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
373                 return (sockfd);
374         }
375 }
376
377 /* XXX: Probably belongs in class InspIRCd */
378 bool InspIRCd::HasPort(int port, char* addr)
379 {
380         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
381         {
382                 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
383                 {
384                         return true;
385                 }
386         }
387         return false;
388 }
389
390 /* XXX: Probably belongs in class InspIRCd */
391 int InspIRCd::BindPorts(bool bail)
392 {
393         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
394         insp_sockaddr client, server;
395         int clientportcount = 0;
396         int BoundPortCount = 0;
397
398         if (!bail)
399         {
400                 int InitialPortCount = stats->BoundPortCount;
401                 this->Log(DEBUG,"Initial port count: %d",InitialPortCount);
402
403                 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
404                 {
405                         Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
406                         Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
407                         Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
408
409                         if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
410                         {
411                                 // modules handle server bind types now
412                                 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
413                                 if (*Addr == '*')
414                                         *Addr = 0;
415
416                                 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
417                                 clientportcount++;
418                                 this->Log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
419                         }
420                 }
421                 int PortCount = clientportcount;
422                 if (PortCount)
423                 {
424                         BoundPortCount = stats->BoundPortCount;
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[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
435                                         if (Config->openSockfd[BoundPortCount]->GetFd() > -1)
436                                         {
437                                                 if (!SE->AddFd(Config->openSockfd[BoundPortCount]))
438                                                 {
439                                                         this->Log(DEFAULT,"ERK! Failed to add listening port to socket engine!");
440                                                         shutdown(Config->openSockfd[BoundPortCount]->GetFd(),2);
441                                                         close(Config->openSockfd[BoundPortCount]->GetFd());
442                                                         delete Config->openSockfd[BoundPortCount];
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[BoundPortCount] = new ListenSocket(this,fd,client,server,Config->ports[count],Config->addrs[count]);
498                         if (Config->openSockfd[BoundPortCount]->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