Debian Codegraph @

Framework/Pantomime/CWDNSManager.m

raw
1 /*
2 ** CWDNSManager.m
3 **
4 ** Copyright (c) 2004-2007 Ludovic Marcotte
5 ** Copyright (C) 2012-2022 Riccardo Mottola
6 **
7 ** Author: Ludovic Marcotte <[email protected]>
8 ** Riccardo Mottola <[email protected]>
9 **
10 ** This library is free software; you can redistribute it and/or
11 ** modify it under the terms of the GNU Lesser General Public
12 ** License as published by the Free Software Foundation; either
13 ** version 2.1 of the License, or (at your option) any later version.
14 **
15 ** This library is distributed in the hope that it will be useful,
16 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 ** Lesser General Public License for more details.
19 **
20 ** You should have received a copy of the GNU General Public License
21 ** along with this program. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #import <Pantomime/CWDNSManager.h>
25
26 #import <Pantomime/CWConstants.h>
27 #import <Pantomime/NSData+Extensions.h>
28
29 #import <Foundation/NSCharacterSet.h>
30 #import <Foundation/NSValue.h>
31 #import <Foundation/NSScanner.h>
32
33 #ifdef __MINGW32__
34 #include <winsock2.h>
35
36 #elif defined (__NetBSD__)
37 #include <sys/types.h>
38 #include <netinet/in.h>
39 #include <arpa/nameser.h>
40 #include <resolv.h>
41 //#include <res_update.h>
42 #include <arpa/inet.h>
43 #include <netdb.h>
44 #if __NetBSD_Version__ >= 300000000
45 #define HAS_RES_NINIT 1
46 #endif
47
48 #else
49 #include <sys/types.h> // For u_char on Mac OS X
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
53 #include <netdb.h>
54 #include <resolv.h>
55 #endif
56
57 #include <unistd.h>
58
59 #define MAX_PACKET_SIZE 512
60 #define MAX_TIMEOUT 2
61
62
63
64 static CWDNSManager *singleInstance = nil;
65
66 typedef struct _dns_packet_header
67 {
68 unsigned short packet_id;
69 unsigned short flags;
70 unsigned short qdcount;
71 unsigned short ancount;
72 unsigned short nscount;
73 unsigned short arcount;
74 } dns_packet_header;
75
76 typedef struct _dns_packet_question
77 {
78 unsigned short qtype;
79 unsigned short qclass;
80 } dns_packet_question;
81
82 typedef struct _dns_resource_record
83 {
84 unsigned short type;
85 unsigned short class;
86 unsigned int ttl;
87 unsigned short rdlength;
88 } dns_resource_record;
89
90 #ifdef MACOSX
91 void dns_socket_callback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void* data, void* info);
92
93 void dns_socket_callback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void* data, void* info)
94 {
95 if (type&kCFSocketReadCallBack)
96 {
97 [(CWDNSManager *)info receivedEvent: (void*)CFSocketGetNative(s)
98 type: ET_RDESC
99 extra: 0
100 forMode: nil];
101 }
102 }
103 #endif
104
105 //
106 //
107 //
108 @interface CWDNSRequest : NSObject
109 {
110 @protected
111 NSMutableArray *servers;
112 NSData *name;
113
114 @public
115 unsigned short packet_id, count;
116 }
117
118 - (id) initWithName: (NSString *) theName;
119 - (NSMutableArray *) servers;
120 - (void) setServers: (NSMutableArray *)serverArray;
121 - (NSData *) name;
122
123 @end
124
125 @implementation CWDNSRequest
126
127 - (id) initWithName: (NSString *) theName
128 {
129 self = [super init];
130 if (self)
131 {
132 servers = [[NSMutableArray alloc] init];
133 name = RETAIN([theName dataUsingEncoding: NSASCIIStringEncoding]);
134 count = 0;
135 }
136 return self;
137 }
138
139 - (NSMutableArray *) servers
140 {
141 return servers;
142 }
143
144 - (void) setServers: (NSMutableArray *)serverArray
145 {
146 ASSIGN(self->servers, serverArray);
147 }
148
149 - (NSData *) name
150 {
151 return name;
152 }
153
154 - (void) dealloc
155 {
156 RELEASE(servers);
157 RELEASE(name);
158 [super dealloc];
159 }
160
161 @end
162
163 //
164 //
165 //
166 @interface CWDNSManager (Private)
167
168 - (void) _parseHostsFile;
169 - (void) _parseResolvFile;
170 - (void) _processResponse;
171 - (void) _sendRequest: (CWDNSRequest *) theRequest;
172 - (void) _tick: (id) sender;
173
174 @end
175
176 //
177 //
178 //
179 @implementation CWDNSManager
180
181 - (id) init
182 {
183 self = [super init];
184 if (self)
185 {
186 _cache = [[NSMutableDictionary alloc] init];
187 _servers = [[NSMutableArray alloc] init];
188 _queue = [[NSMutableArray alloc] init];
189 _is_asynchronous = NO;
190
191 #ifdef MACOSX
192 _runLoopSource = nil;
193 _context = nil;
194 _cf_socket = nil;
195 #endif
196
197 [self _parseResolvFile];
198 [self _parseHostsFile];
199
200 if ([_servers count] && (_socket = socket(PF_INET, SOCK_DGRAM, 0)) >= 0)
201 {
202 _is_asynchronous = YES;
203 _packet_id = 1;
204
205 #ifdef MACOSX
206 _context = (CFSocketContext *)malloc(sizeof(CFSocketContext));
207 memset(_context, 0, sizeof(CFSocketContext));
208 _context->info = self;
209
210 _cf_socket = CFSocketCreateWithNative(NULL, _socket, kCFSocketReadCallBack|kCFSocketWriteCallBack, dns_socket_callback, _context);
211 CFSocketDisableCallBacks(_cf_socket, kCFSocketReadCallBack|kCFSocketWriteCallBack);
212
213 if (!_cf_socket)
214 {
215 _is_asynchronous = NO;
216 return self;
217 }
218
219 _runLoopSource = CFSocketCreateRunLoopSource(NULL, _cf_socket, 1);
220
221 if (!_runLoopSource)
222 {
223 CFSocketInvalidate(_cf_socket);
224 _is_asynchronous = NO;
225 return self;
226 }
227
228 CFRunLoopAddSource(CFRunLoopGetCurrent(), _runLoopSource, kCFRunLoopCommonModes);
229 #else
230 [[NSRunLoop currentRunLoop] addEvent: (void *)_socket
231 #ifdef __MINGW32__
232 type: ET_HANDLE
233 #else
234 type: ET_RDESC
235 #endif
236 watcher: self
237 forMode: NSDefaultRunLoopMode];
238 #endif
239
240 _timer = [NSTimer scheduledTimerWithTimeInterval: 1.0
241 target: self
242 selector: @selector(_tick:)
243 userInfo: nil
244 repeats: YES];
245 RETAIN(_timer);
246 [_timer fire];
247 }
248 }
249 return self;
250 }
251
252 //
253 //
254 //
255 - (void) dealloc
256 {
257 [_timer invalidate];
258 RELEASE(_timer);
259
260 #ifdef MACOSX
261 if (CFRunLoopSourceIsValid(_runLoopSource))
262 {
263 CFRunLoopSourceInvalidate(_runLoopSource);
264 CFRelease(_runLoopSource);
265 }
266
267 if (CFSocketIsValid(_cf_socket))
268 {
269 CFSocketInvalidate(_cf_socket);
270 }
271
272 CFRelease(_cf_socket);
273 free(_context);
274 #endif
275
276 RELEASE(_cache);
277 RELEASE(_servers);
278 RELEASE(_queue);
279 [super dealloc];
280 }
281
282 //
283 //
284 //
285 - (NSArray *) addressesForName: (NSString *) theName background: (BOOL) theBOOL
286 {
287 id o;
288
289 NSDebugLog(@"DNSManager - Looking up address: %@, background? %u", theName, theBOOL);
290 o = [_cache objectForKey: theName];
291
292 if (theBOOL)
293 {
294 if (o)
295 {
296 POST_NOTIFICATION(PantomimeDNSResolutionCompleted, self, ([NSDictionary dictionaryWithObjectsAndKeys: theName, @"Name", [o objectAtIndex: 0], @"Address", nil]));
297 }
298 else
299 {
300 CWDNSRequest *aRequest;
301 NSMutableArray *serversCopy;
302
303 serversCopy = [[NSMutableArray alloc] initWithArray: _servers];
304 aRequest = AUTORELEASE([[CWDNSRequest alloc] initWithName: theName]);
305 aRequest->packet_id = _packet_id++;
306 [aRequest setServers: serversCopy];
307 [serversCopy release];
308 aRequest->count = 0;
309
310 if ([_servers count])
311 {
312 [self _sendRequest: aRequest];
313 }
314 }
315
316 return nil;
317 }
318
319 if (!o)
320 {
321 struct hostent *host_info;
322
323 //
324 // We don't compare with _servers as it might have more
325 // magic to obtain IP addresses from DNS names.
326 //
327 host_info = gethostbyname([theName cString]);
328
329 if (host_info)
330 {
331 unsigned i;
332
333 o = [NSMutableArray array];
334 i = 0;
335 while (host_info->h_addr_list[i] != NULL)
336 {
337 uint8_t c0, c1, c2, c3;
338 char *buf;
339 uint32_t r;
340
341 buf = host_info->h_addr_list[i];
342 c0 = (uint8_t)*(buf);
343 c1 = (uint8_t)*(buf+1);
344 c2 = (uint8_t)*(buf+2);
345 c3 = (uint8_t)*(buf+3);
346
347 r = ntohl((uint32_t)((c0<<24)|(c1<<16)|(c2<<8)|c3));
348
349 [o addObject: [NSNumber numberWithUnsignedInt: r]];
350
351 i++;
352 }
353
354 // We only cache if we have at least one address for the DNS name.
355 if ([o count])
356 {
357 [_cache setObject: o forKey: theName];
358 }
359 }
360 else
361 {
362 o = nil;
363 }
364 }
365
366 return o;
367 }
368
369 //
370 //
371 //
372 - (void) receivedEvent: (void *) theData
373 type: (RunLoopEventType) theType
374 extra: (void *) theExtra
375 forMode: (NSString *) theMode
376 {
377 switch (theType)
378 {
379 #ifdef __MINGW32__
380 case ET_HANDLE:
381 case ET_TRIGGER:
382 #else
383 case ET_RDESC:
384 #endif
385 [self _processResponse];
386 break;
387
388 default:
389 break;
390 }
391 }
392
393 //
394 //
395 //
396 + (id) singleInstance
397 {
398 if (!singleInstance)
399 {
400 singleInstance = [[CWDNSManager alloc] init];
401 }
402
403 return singleInstance;
404 }
405
406 @end
407
408 @implementation CWDNSManager (Private)
409
410 //
411 // See man 5 hosts for all details
412 // on the format of the /etc/hosts file.
413 //
414 - (void) _parseHostsFile
415 {
416 NSData *aData;
417
418 aData = [NSData dataWithContentsOfFile: @"/etc/hosts"];
419
420 if (aData)
421 {
422 NSArray *allLines;
423 NSString *aString;
424 BOOL b;
425 NSUInteger i;
426
427 allLines = [aData componentsSeparatedByCString: "\n"];
428
429 for (i = 0; i < [allLines count]; i++)
430 {
431 aData = [allLines objectAtIndex: i];
432
433 if ([aData hasCPrefix: "#"]) continue;
434
435 aString = [[NSString alloc] initWithData: aData encoding: NSASCIIStringEncoding];
436 b = YES;
437
438 if (aString)
439 {
440 NSString *aWord;
441 NSString *theIP;
442 NSScanner *aScanner;
443
444 aScanner = [NSScanner scannerWithString: aString];
445 theIP = nil;
446
447 [aScanner scanCharactersFromSet: [NSCharacterSet whitespaceAndNewlineCharacterSet] intoString: NULL];
448
449 while ([aScanner scanUpToCharactersFromSet: [NSCharacterSet whitespaceAndNewlineCharacterSet] intoString: &aWord] == YES)
450 {
451 if (b)
452 {
453 theIP = aWord;
454 b = NO;
455 continue;
456 }
457
458 [_cache setObject: [NSArray arrayWithObject: [NSNumber numberWithUnsignedInt: inet_addr([theIP UTF8String])]] forKey: aWord];
459 [aScanner scanCharactersFromSet: [NSCharacterSet whitespaceAndNewlineCharacterSet] intoString: NULL];
460
461 }
462
463 RELEASE(aString);
464 }
465 }
466 }
467 }
468
469 //
470 // See man 5 resolv.conf for all details
471 // on the format of the /etc/resolv.conf file.
472 //
473 - (void) _parseResolvFile
474 {
475 int i;
476 #ifdef HAS_RES_NINIT
477 struct __res_state cw_res;
478 #else
479 #define cw_res _res
480 #endif
481
482 #ifdef HAS_RES_NINIT
483 memset(&cw_res, 0, sizeof(cw_res));
484
485 if (res_ninit(&cw_res) == -1)
486 return;
487 #else
488 if (res_init() == -1)
489 return;
490 #endif
491
492 if ((cw_res.options & RES_INIT) == 0)
493 return;
494
495 for (i = 0 ; i < cw_res.nscount; i++ )
496 {
497 [_servers addObject: [NSNumber numberWithUnsignedInt: cw_res.nsaddr_list[i].sin_addr.s_addr]];
498 }
499
500 #ifdef HAS_RES_NINIT
501 res_ndestroy(&cw_res);
502 #endif
503 }
504
505
506 //
507 //
508 //
509 - (void) _processResponse
510 {
511 CWDNSRequest *aRequest;
512 NSString *aString;
513 NSNumber *aNumber;
514
515 dns_resource_record *resource_record;
516 dns_packet_header *header;
517
518 char *buf, qr, ra, rcode, *start;
519 unsigned short flags, i, type;
520 uint8_t c0, c1, c2, c3;
521 uint32_t r;
522
523 start = buf = (char *)malloc(MAX_PACKET_SIZE);
524
525 if (recvfrom(_socket, buf, MAX_PACKET_SIZE, 0, NULL, NULL) == -1)
526 {
527 free(buf);
528 return;
529 }
530
531 // We build our packet header. We should get (~118 bytes in total):
532 //
533 // - packet identifier
534 // - flags (0x8180)
535 // - qdcount
536 // - ancount
537 // - nscount
538 // - arcount
539 header = (dns_packet_header *)buf;
540
541 // We get the right DNSRequest object from the queue
542 // based on our packet ID.
543 aRequest = nil;
544
545 for (i = 0; i < [_queue count]; i++)
546 {
547 aRequest = [_queue objectAtIndex: i];
548 if (aRequest->packet_id == ntohs(header->packet_id)) break;
549 }
550
551 if (!aRequest)
552 {
553 free(buf);
554 return;
555 }
556
557 flags = ntohs(header->flags);
558
559 qr = (char)((flags & 0x8000) >> 15);
560
561 // We check if we got a response from the server. If not,
562 // we try the next server, if any.
563 if (!qr) return;
564
565 ra = (char)((flags & 0x0080) >> 7);
566
567 // We check if recursive queries are supported by
568 // the server. If not, we try the next server, if any.
569 if (!ra) return;
570
571 rcode = (char)((flags & 0x000F) >> 0);
572
573 // We check if we got any errors...
574 // 2 - server failure
575 // 3 - domain does not exist
576 // 5 - the server refused to serve our query
577 if (rcode)
578 {
579 return;
580 }
581
582 // We check if we got a response from the server. If not,
583 // we try the next server, if any.
584 if (!htons(header->ancount)) return;
585
586 buf += sizeof(dns_packet_header);
587
588 //
589 // We skip over the Question section.
590 //
591 while (*buf)
592 {
593 buf += (int)(*buf)+1;
594 }
595
596 buf += sizeof(dns_packet_question)+1;
597
598
599 //
600 // We now read the Answer section of our packet
601 //
602 // 1 1 1 1 1 1
603 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
604 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
605 // | |
606 // / /
607 // / NAME /
608 // | |
609 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
610 // | TYPE |
611 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
612 // | CLASS |
613 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
614 // | TTL |
615 // | |
616 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
617 // | RDLENGTH |
618 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
619 // / RDATA /
620 // / /
621 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
622 type = 0;
623
624 while (type != 1)
625 {
626 if (!((*buf) & 0xC0))
627 {
628 while (*buf)
629 {
630 buf+=(int)(*buf)+1;
631 }
632
633 buf-=1;
634 }
635
636 resource_record = (dns_resource_record *)(buf+=2);
637 type = ntohs(resource_record->type);
638 buf += (sizeof(dns_resource_record)-2)+ntohs(resource_record->rdlength);
639 }
640
641 buf -= ntohs(resource_record->rdlength);
642 c0 = (uint8_t)*(buf);
643 c1 = (uint8_t)*(buf+1);
644 c2 = (uint8_t)*(buf+2);
645 c3 = (uint8_t)*(buf+3);
646
647 r = ntohl((uint32_t)((c0<<24)|(c1<<16)|(c2<<8)|c3));
648
649 aString = AUTORELEASE([[NSString alloc] initWithData: [aRequest name] encoding: NSASCIIStringEncoding]);
650 aNumber = [NSNumber numberWithUnsignedInt: r];
651
652 POST_NOTIFICATION(PantomimeDNSResolutionCompleted, self, ([NSDictionary dictionaryWithObjectsAndKeys: aString, @"Name", aNumber, @"Address", nil]));
653
654 [_cache setObject: [NSArray arrayWithObject: aNumber] forKey: aString];
655
656 // We remove our request from the queue
657 [_queue removeObject: aRequest];
658
659 free(start);
660 }
661
662 //
663 //
664 //
665 - (void) _sendRequest: (CWDNSRequest *) theRequest
666 {
667 NSArray *subdomains;
668
669 struct sockaddr_in peer_address;
670 dns_packet_question *question;
671 dns_packet_header *header;
672 unsigned i;
673 size_t len;
674 char *packet, *start;
675
676 peer_address.sin_family = PF_INET;
677 peer_address.sin_port = htons(53);
678
679 peer_address.sin_addr.s_addr = [[[theRequest servers] objectAtIndex: 0] unsignedIntValue];
680 start = packet = (char *)malloc(MAX_PACKET_SIZE);
681
682 // We build our packet header. We have to set:
683 //
684 // - packet identifier
685 // - flags, we have something like this to fill:
686 // |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
687 // 0 0000 0 0 1 0 000 0000
688 // - qdcount: 1 entry in the question section.
689 // - ancount: 0 resource record in the answer section
690 // - nscount: 0 name server resource record in the authority records section
691 // - arcount: 0 resource record in the additional records section
692 //
693 //NSLog(@"(0x0100:\t%d to %d\n1:\t\t%d to %d\n", 0x0100, htons(0x0100), 1, htons(1));
694 header = (dns_packet_header *)packet;
695 header->packet_id = htons(theRequest->packet_id);
696 header->flags = htons(0x0100);
697 header->qdcount = htons(1);
698 header->ancount = header->nscount = header->arcount = 0;
699
700 // We build our packet question.
701 packet += sizeof(dns_packet_header);
702
703 // QNAME
704 // a domain name represented as a sequence of labels, where
705 // each label consists of a length octet followed by that
706 // number of octets. The domain name terminates with the
707 // zero length octet for the null label of the root. Note
708 // that this field may be an odd number of octets; no
709 // padding is used.
710 //
711 subdomains = [[theRequest name] componentsSeparatedByCString: "."];
712
713 for (i = 0; i < [subdomains count]; i++)
714 {
715 *packet = len = [[subdomains objectAtIndex: i] length];
716 memcpy(++packet, [[subdomains objectAtIndex: i] bytes], len);
717 packet += len;
718 }
719
720 *(packet++) = '\0';
721 question = (dns_packet_question *)packet;
722 question->qtype = htons(1); // Type A: 1 a host address
723 question->qclass = htons(1); // IN: 1 the Internet
724 packet += sizeof(dns_packet_question);
725
726 len = packet-(char *)header;
727
728 // We queue our DNS request
729 if (![_queue containsObject: theRequest]) [_queue addObject: theRequest];
730
731 // We send our packet. If we failed to send it, we don't care since
732 // we'll try to send it to an other server shortly after.
733 sendto(_socket, start, len, 0, (struct sockaddr *)&peer_address, sizeof(struct sockaddr));
734
735 free(start);
736 }
737
738 //
739 //
740 //
741 - (void) _tick: (id) sender
742 {
743 NSUInteger c;
744
745 if ((c = [_queue count]))
746 {
747 CWDNSRequest *aRequest;
748
749 while (c--)
750 {
751 aRequest = [_queue objectAtIndex: c];
752
753 if (aRequest->count == MAX_TIMEOUT)
754 {
755 if ([[aRequest servers] count] > 1)
756 {
757 [[aRequest servers] removeObjectAtIndex: 0];
758 aRequest->count = 0;
759
760 [self _sendRequest: aRequest];
761 }
762 else
763 {
764 NSDictionary *aDictionary;
765
766 aDictionary = [NSDictionary dictionaryWithObject: AUTORELEASE([[NSString alloc] initWithData: [aRequest name] encoding: NSASCIIStringEncoding])
767 forKey: @"Name"];
768 POST_NOTIFICATION(PantomimeDNSResolutionFailed, self, aDictionary);
769
770 [_queue removeObject: aRequest];
771 }
772 }
773
774 aRequest->count++;
775 }
776 }
777 }
778
779 @end
780