summaryrefslogtreecommitdiffstats
path: root/mDNSResponder/Clients/DNSServiceBrowser.m
blob: b4e041404112379c9aa6aa5b03dde0d9ca4c8827 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import <Cocoa/Cocoa.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <unistd.h>
#include <dns_sd.h>

@class ServiceController;  // holds state corresponding to outstanding DNSServiceRef

@interface BrowserController : NSObject
{
    IBOutlet id nameField;
    IBOutlet id typeField;

    IBOutlet id serviceDisplayTable;
    IBOutlet id typeColumn;
    IBOutlet id nameColumn;
    IBOutlet id serviceTypeField;
    IBOutlet id serviceNameField;

    IBOutlet id hostField;
    IBOutlet id ipAddressField;
    IBOutlet id ip6AddressField;
    IBOutlet id portField;
    IBOutlet id interfaceField;
    IBOutlet id textField;
    
    NSMutableArray *_srvtypeKeys;
    NSMutableArray *_srvnameKeys;
    NSMutableArray *_sortedServices;
    NSMutableDictionary *_servicesDict;

	ServiceController *_serviceBrowser;
	ServiceController *_serviceResolver;
	ServiceController *_ipv4AddressResolver;
	ServiceController *_ipv6AddressResolver;
}

- (void)notifyTypeSelectionChange:(NSNotification*)note;
- (void)notifyNameSelectionChange:(NSNotification*)note;

- (IBAction)connect:(id)sender;

- (IBAction)handleTableClick:(id)sender;
- (IBAction)removeSelected:(id)sender;
- (IBAction)addNewService:(id)sender;

- (IBAction)update:(NSString *)Type;

- (void)updateBrowseWithName:(const char *)name type:(const char *)resulttype domain:(const char *)domain interface:(uint32_t)interface flags:(DNSServiceFlags)flags;
- (void)resolveClientWitHost:(NSString *)host port:(uint16_t)port interfaceIndex:(uint32_t)interface txtRecord:(const char*)txtRecord txtLen:(uint16_t)txtLen;
- (void)updateAddress:(uint16_t)rrtype addr:(const void *)buff addrLen:(uint16_t)addrLen host:(const char*)host interfaceIndex:(uint32_t)interface more:(boolean_t)moreToCome;

- (void)_cancelPendingResolve;
- (void)_clearResolvedInfo;

@end

// The ServiceController manages cleanup of DNSServiceRef & runloop info for an outstanding request
@interface ServiceController : NSObject
{
	DNSServiceRef       fServiceRef;
	CFSocketRef         fSocketRef;
	CFRunLoopSourceRef  fRunloopSrc;
}

- (id)initWithServiceRef:(DNSServiceRef)ref;
- (void)addToCurrentRunLoop;
- (DNSServiceRef)serviceRef;
- (void)dealloc;

@end // interface ServiceController


static void
ProcessSockData(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info)
{
	DNSServiceRef serviceRef = (DNSServiceRef)info;
	DNSServiceErrorType err = DNSServiceProcessResult(serviceRef);
	if (err != kDNSServiceErr_NoError) {
		printf("DNSServiceProcessResult() returned an error! %d\n", err);
    }
}


static void
ServiceBrowseReply(DNSServiceRef sdRef, DNSServiceFlags servFlags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, 
    const char *serviceName, const char *regtype, const char *replyDomain, void *context)
{
	if (errorCode == kDNSServiceErr_NoError) {
		[(BrowserController*)context updateBrowseWithName:serviceName type:regtype domain:replyDomain interface:interfaceIndex flags:servFlags];
	} else {
		printf("ServiceBrowseReply got an error! %d\n", errorCode);
	}
}


static void
ServiceResolveReply(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode,
    const char *fullname, const char *hosttarget, uint16_t port, uint16_t txtLen, const char *txtRecord, void *context)
{
	if (errorCode == kDNSServiceErr_NoError) {
		[(BrowserController*)context resolveClientWitHost:[NSString stringWithUTF8String:hosttarget] port:port interfaceIndex:interfaceIndex txtRecord:txtRecord txtLen:txtLen];
	} else {
		printf("ServiceResolveReply got an error! %d\n", errorCode);
	}
}


static void
QueryRecordReply(DNSServiceRef DNSServiceRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode,
    const char *fullname, uint16_t rrtype, uint16_t rrclass,  uint16_t rdlen, const void *rdata, uint32_t ttl, void *context)
{
    if (errorCode == kDNSServiceErr_NoError) {
        [(BrowserController*)context updateAddress:rrtype addr:rdata addrLen:rdlen host:fullname interfaceIndex:interfaceIndex more:(flags & kDNSServiceFlagsMoreComing)];
    } else {
        printf("QueryRecordReply got an error! %d\n", errorCode);
    }
}


static void
InterfaceIndexToName(uint32_t interface, char *interfaceName)
{
    assert(interfaceName);
    
    if (interface == kDNSServiceInterfaceIndexAny) {
        // All active network interfaces.
        strlcpy(interfaceName, "all", IF_NAMESIZE);
    } else if (interface == kDNSServiceInterfaceIndexLocalOnly) {
        // Only available locally on this machine.
        strlcpy(interfaceName, "local", IF_NAMESIZE);
    } else if (interface == kDNSServiceInterfaceIndexP2P) {
        // Peer-to-peer.
        strlcpy(interfaceName, "p2p", IF_NAMESIZE);
    } else {
        // Converts interface index to interface name.
        if_indextoname(interface, interfaceName);
    }
}


@implementation BrowserController		//Begin implementation of BrowserController methods

- (void)registerDefaults
{
    NSMutableDictionary *regDict = [NSMutableDictionary dictionary];

    NSArray *typeArray = [NSArray arrayWithObjects:@"_afpovertcp._tcp",
                                                   @"_smb._tcp",
                                                   @"_rfb._tcp",
												   @"_ssh._tcp",
                                                   @"_ftp._tcp",
												   @"_http._tcp",
												   @"_printer._tcp",
                                                   @"_ipp._tcp",
                                                   @"_airport._tcp",
												   @"_presence._tcp",
												   @"_daap._tcp",
												   @"_dpap._tcp",
                                                   nil];
                                                   
    NSArray *nameArray = [NSArray arrayWithObjects:@"AppleShare Servers",
                                                   @"Windows Sharing",
                                                   @"Screen Sharing",
	                                               @"Secure Shell",
                                                   @"FTP Servers",
	                                               @"Web Servers",
	                                               @"LPR Printers",
                                                   @"IPP Printers",
                                                   @"AirPort Base Stations",
												   @"iChat Buddies",
												   @"iTunes Libraries",
												   @"iPhoto Libraries",
                                                   nil];

    [regDict setObject:typeArray forKey:@"SrvTypeKeys"];
    [regDict setObject:nameArray forKey:@"SrvNameKeys"];

    [[NSUserDefaults standardUserDefaults] registerDefaults:regDict];
}


- (id)init
{
    self = [super init];
    if (self) {
        _srvtypeKeys = nil;
        _srvnameKeys = nil;
        _serviceBrowser = nil;
        _serviceResolver = nil;
        _ipv4AddressResolver = nil;
        _ipv6AddressResolver = nil;
        _sortedServices = [[NSMutableArray alloc] init];
        _servicesDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}


- (void)awakeFromNib
{
    [typeField sizeLastColumnToFit];
    [nameField sizeLastColumnToFit];
    [nameField setDoubleAction:@selector(connect:)];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyTypeSelectionChange:) name:NSTableViewSelectionDidChangeNotification object:typeField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyNameSelectionChange:) name:NSTableViewSelectionDidChangeNotification object:nameField];
    
    _srvtypeKeys = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"SrvTypeKeys"] mutableCopy];
    _srvnameKeys = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"SrvNameKeys"] mutableCopy];

    if (!_srvtypeKeys || !_srvnameKeys) {
        [_srvtypeKeys release];
        [_srvnameKeys release];
        [self registerDefaults];
        _srvtypeKeys = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"SrvTypeKeys"] mutableCopy];
        _srvnameKeys = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"SrvNameKeys"] mutableCopy];
    }
    
    [typeField reloadData];
}


- (void)dealloc
{
    [_srvtypeKeys release];
    [_srvnameKeys release];
    [_servicesDict release];
    [_sortedServices release];
    [super dealloc];
}


-(void)tableView:(NSTableView *)theTableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
    if (row < 0) return;
}


- (int)numberOfRowsInTableView:(NSTableView *)theTableView	//Begin mandatory TableView methods
{
    if (theTableView == typeField) {
        return [_srvnameKeys count];
    }
    if (theTableView == nameField) {
        return [_servicesDict count];
    }
    if (theTableView == serviceDisplayTable) {
        return [_srvnameKeys count];
    }
    return 0;
}


- (id)tableView:(NSTableView *)theTableView objectValueForTableColumn:(NSTableColumn *)theColumn row:(int)rowIndex
{
    if (theTableView == typeField) {
        return [_srvnameKeys objectAtIndex:rowIndex];
    }
    if (theTableView == nameField) {
        return [[_servicesDict objectForKey:[_sortedServices objectAtIndex:rowIndex]] name];
    }
    if (theTableView == serviceDisplayTable) {
        if (theColumn == typeColumn) {
            return [_srvtypeKeys objectAtIndex:rowIndex];
        }
        if (theColumn == nameColumn) {
            return [_srvnameKeys objectAtIndex:rowIndex];
        }
        return nil;
    }
    
    return nil;
}


- (void)notifyTypeSelectionChange:(NSNotification*)note
{
    [self _cancelPendingResolve];

    int index = [[note object] selectedRow];
    if (index != -1) {
        [self update:[_srvtypeKeys objectAtIndex:index]];
    } else {
        [self update:nil];
    }
}


- (void)notifyNameSelectionChange:(NSNotification*)note
{
    [self _cancelPendingResolve];
    
    int index = [[note object] selectedRow];
    if (index == -1) {
		return;
	}
    
    // Get the currently selected service
    NSNetService *service = [_servicesDict objectForKey:[_sortedServices objectAtIndex:index]];
	
    DNSServiceRef serviceRef;
	DNSServiceErrorType err = DNSServiceResolve(&serviceRef,
                                         (DNSServiceFlags)0,
                               kDNSServiceInterfaceIndexAny,
                  (const char *)[[service name] UTF8String],
                 (const char *)[[service type]  UTF8String],
                (const char *)[[service domain] UTF8String],
                (DNSServiceResolveReply)ServiceResolveReply,
                                                      self);
        
	if (kDNSServiceErr_NoError == err) {
		_serviceResolver = [[ServiceController alloc] initWithServiceRef:serviceRef];
		[_serviceResolver addToCurrentRunLoop];
	}
}


- (IBAction)update:(NSString *)theType
{
    [_servicesDict removeAllObjects];
    [_sortedServices removeAllObjects];
    [nameField reloadData];

    // get rid of the previous browser if one exists
    if (_serviceBrowser != nil) {
		[_serviceBrowser release];
        _serviceBrowser = nil;
    }
    
    if (theType) {
        DNSServiceRef serviceRef;
        DNSServiceErrorType err = DNSServiceBrowse(&serviceRef, (DNSServiceFlags)0, 0, [theType UTF8String], NULL, ServiceBrowseReply, self);
        if (kDNSServiceErr_NoError == err) {
            _serviceBrowser = [[ServiceController alloc] initWithServiceRef:serviceRef];
            [_serviceBrowser addToCurrentRunLoop];
        }
    }
}


- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
    return YES;
}


- (void)updateBrowseWithName:(const char *)name type:(const char *)type domain:(const char *)domain interface:(uint32_t)interface flags:(DNSServiceFlags)flags
{
    NSString *key = [NSString stringWithFormat:@"%s.%s%s%d", name, type, domain, interface];
    NSNetService *service = [[NSNetService alloc] initWithDomain:[NSString stringWithUTF8String:domain] type:[NSString stringWithUTF8String:type] name:[NSString stringWithUTF8String:name]];
    
    if (flags & kDNSServiceFlagsAdd) {
        [_servicesDict setObject:service forKey:key];
    } else {
        [_servicesDict removeObjectForKey:key];
    }

    // If not expecting any more data, then reload (redraw) TableView with newly found data
    if (!(flags & kDNSServiceFlagsMoreComing)) {
    
        // Save the current TableView selection
        int index = [nameField selectedRow];
        NSString *selected = (index != -1) ? [[_sortedServices objectAtIndex:index] copy] : nil;
        
        [_sortedServices release];
        _sortedServices = [[_servicesDict allKeys] mutableCopy];        
        [_sortedServices sortUsingSelector:@selector(caseInsensitiveCompare:)];
        [nameField reloadData];
        
        // Restore the previous TableView selection
        index = selected ? [_sortedServices indexOfObject:selected] : NSNotFound;
        if (index != NSNotFound) {
            [nameField selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];
            [nameField scrollRowToVisible:index];
        }
        
        [selected release];
    }

    [service release];

    return;
}


- (void)resolveClientWitHost:(NSString *)host port:(uint16_t)port interfaceIndex:(uint32_t)interface txtRecord:(const char*)txtRecord txtLen:(uint16_t)txtLen
{
	DNSServiceRef serviceRef;

	if (_ipv4AddressResolver) {
		[_ipv4AddressResolver release];
		_ipv4AddressResolver = nil;
	}
    
    if (_ipv6AddressResolver) {
		[_ipv6AddressResolver release];
		_ipv6AddressResolver = nil;
	}

	// Start an async lookup for IPv4 addresses
	DNSServiceErrorType err = DNSServiceQueryRecord(&serviceRef, (DNSServiceFlags)0, interface, [host UTF8String], kDNSServiceType_A, kDNSServiceClass_IN, QueryRecordReply, self);
	if (err == kDNSServiceErr_NoError) {
		_ipv4AddressResolver = [[ServiceController alloc] initWithServiceRef:serviceRef];
		[_ipv4AddressResolver addToCurrentRunLoop];
	}

	// Start an async lookup for IPv6 addresses
    err = DNSServiceQueryRecord(&serviceRef, (DNSServiceFlags)0, interface, [host UTF8String], kDNSServiceType_AAAA, kDNSServiceClass_IN, QueryRecordReply, self);
    if (err == kDNSServiceErr_NoError) {
        _ipv6AddressResolver = [[ServiceController alloc] initWithServiceRef:serviceRef];
        [_ipv6AddressResolver addToCurrentRunLoop];
    }

    char interfaceName[IF_NAMESIZE];
    InterfaceIndexToName(interface, interfaceName);

    [hostField setStringValue:host];
    [interfaceField setStringValue:[NSString stringWithUTF8String:interfaceName]];
    [portField setIntValue:ntohs(port)];

	// kind of a hack: munge txtRecord so it's human-readable
	if (txtLen > 0) {
		char *readableText = (char*) malloc(txtLen);
		if (readableText != nil) {
			ByteCount index, subStrLen;
			memcpy(readableText, txtRecord, txtLen);
			for (index=0; index < txtLen - 1; index += subStrLen + 1) {
				subStrLen = readableText[index];
				readableText[index] = ' ';
			}
			[textField setStringValue:[NSString stringWithCString:&readableText[1] length:txtLen - 1]];
			free(readableText);
		}
	}
}


- (void)updateAddress:(uint16_t)rrtype  addr:(const void *)buff addrLen:(uint16_t)addrLen host:(const char*) host interfaceIndex:(uint32_t)interface more:(boolean_t)moreToCome
{
    char addrBuff[256];

	if (rrtype == kDNSServiceType_A) {
		inet_ntop(AF_INET, buff, addrBuff, sizeof(addrBuff));
        if ([[ipAddressField stringValue] length] > 0) {
            [ipAddressField setStringValue:[NSString stringWithFormat:@"%@, ", [ipAddressField stringValue]]];
        }
		[ipAddressField setStringValue:[NSString stringWithFormat:@"%@%s", [ipAddressField stringValue], addrBuff]];

		if (!moreToCome) {
			[_ipv4AddressResolver release];
			_ipv4AddressResolver = nil;
		}
	} else if (rrtype == kDNSServiceType_AAAA) {
		inet_ntop(AF_INET6, buff, addrBuff, sizeof(addrBuff));
        if ([[ip6AddressField stringValue] length] > 0) {
            [ip6AddressField setStringValue:[NSString stringWithFormat:@"%@, ", [ip6AddressField stringValue]]];
        }
		[ip6AddressField setStringValue:[NSString stringWithFormat:@"%@%s", [ip6AddressField stringValue], addrBuff]];

		if (!moreToCome) {
			[_ipv6AddressResolver release];
			_ipv6AddressResolver = nil;
		}
	}
}


- (void)connect:(id)sender
{
    NSString *host = [hostField stringValue];
    NSString *txtRecord = [textField stringValue];
    int port = [portField intValue];
        
    int index = [nameField selectedRow];
    NSString *selected = (index >= 0) ? [_sortedServices objectAtIndex:index] : nil;
    NSString *type = [[_servicesDict objectForKey:selected] type];
    
    if ([type isEqual:@"_http._tcp."]) {
        NSString *pathDelim = @"path=";
		NSRange where;

        // If the TXT record specifies a path, extract it.
		where = [txtRecord rangeOfString:pathDelim options:NSCaseInsensitiveSearch];
        if (where.length) {
			NSRange	targetRange = { where.location + where.length, [txtRecord length] - where.location - where.length };
			NSRange	endDelim = [txtRecord rangeOfString:@"\n" options:kNilOptions range:targetRange];
			
			if (endDelim.length)   // if a delimiter was found, truncate the target range
				targetRange.length = endDelim.location - targetRange.location;

            NSString    *path = [txtRecord substringWithRange:targetRange];
            [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%d%@", host, port, path]]];
        } else {
            [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%d", host, port]]];
        }
    }
    else if ([type isEqual:@"_ftp._tcp."])        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"ftp://%@:%d/", host, port]]];
    else if ([type isEqual:@"_ssh._tcp."])        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"ssh://%@:%d/", host, port]]];
    else if ([type isEqual:@"_afpovertcp._tcp."]) [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"afp://%@:%d/", host, port]]];
    else if ([type isEqual:@"_smb._tcp."])        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"smb://%@:%d/", host, port]]];
    else if ([type isEqual:@"_rfb._tcp."])        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"vnc://%@:%d/", host, port]]];

    return;
}


- (IBAction)handleTableClick:(id)sender
{
    //populate the text fields
}


- (IBAction)removeSelected:(id)sender
{
    // remove the selected row and force a refresh

    int selectedRow = [serviceDisplayTable selectedRow];

    if (selectedRow) {

        [_srvtypeKeys removeObjectAtIndex:selectedRow];
        [_srvnameKeys removeObjectAtIndex:selectedRow];

        [[NSUserDefaults standardUserDefaults] setObject:_srvtypeKeys forKey:@"SrvTypeKeys"];
        [[NSUserDefaults standardUserDefaults] setObject:_srvnameKeys forKey:@"SrvNameKeys"];

        [typeField reloadData];
        [serviceDisplayTable reloadData];
    }
}


- (IBAction)addNewService:(id)sender
{
    // add new entries from the edit fields to the arrays for the defaults
    NSString *newType = [serviceTypeField stringValue];
    NSString *newName = [serviceNameField stringValue];

    // 3282283: trim trailing '.' from service type field
    if ([newType length] && [newType hasSuffix:@"."])
        newType = [newType substringToIndex:[newType length] - 1];

    if ([newType length] && [newName length]) {
        [_srvtypeKeys addObject:newType];
        [_srvnameKeys addObject:newName];

        [[NSUserDefaults standardUserDefaults] setObject:_srvtypeKeys forKey:@"SrvTypeKeys"];
        [[NSUserDefaults standardUserDefaults] setObject:_srvnameKeys forKey:@"SrvNameKeys"];

        [typeField reloadData];
        [serviceDisplayTable reloadData];
    }
}


- (void)_cancelPendingResolve
{
    [_ipv4AddressResolver release];
    _ipv4AddressResolver = nil;

    [_ipv6AddressResolver release];
    _ipv6AddressResolver = nil;

    [_serviceResolver release];
    _serviceResolver = nil;

	[self _clearResolvedInfo];
}


- (void)_clearResolvedInfo
{
	[hostField setStringValue:@""];
	[ipAddressField setStringValue:@""];
	[ip6AddressField setStringValue:@""];
	[portField setStringValue:@""];
    [interfaceField setStringValue:@""];
	[textField setStringValue:@""];
}

@end // implementation BrowserController


@implementation ServiceController : NSObject
{
	DNSServiceRef        fServiceRef;
	CFSocketRef          fSocketRef;
	CFRunLoopSourceRef   fRunloopSrc;
}


- (id)initWithServiceRef:(DNSServiceRef)ref
{
	self = [super init];
    if (self) {
        fServiceRef = ref;
        fSocketRef = NULL;
        fRunloopSrc = NULL;
    }
	return self;
}


- (void)addToCurrentRunLoop
{
	CFSocketContext	context = { 0, (void*)fServiceRef, NULL, NULL, NULL };

	fSocketRef = CFSocketCreateWithNative(kCFAllocatorDefault, DNSServiceRefSockFD(fServiceRef), kCFSocketReadCallBack, ProcessSockData, &context);
	if (fSocketRef) {
        // Prevent CFSocketInvalidate from closing DNSServiceRef's socket.
        CFOptionFlags sockFlags = CFSocketGetSocketFlags(fSocketRef);
        CFSocketSetSocketFlags(fSocketRef, sockFlags & (~kCFSocketCloseOnInvalidate));
		fRunloopSrc = CFSocketCreateRunLoopSource(kCFAllocatorDefault, fSocketRef, 0);
    }
	if (fRunloopSrc) {
		CFRunLoopAddSource(CFRunLoopGetCurrent(), fRunloopSrc, kCFRunLoopDefaultMode);
    } else {
		printf("Could not listen to runloop socket\n");
    }
}


- (DNSServiceRef)serviceRef
{
	return fServiceRef;
}


- (void)dealloc
{
	if (fSocketRef) {
		CFSocketInvalidate(fSocketRef);		// Note: Also closes the underlying socket
		CFRelease(fSocketRef);
        
        // Workaround that gives time to CFSocket's select thread so it can remove the socket from its
        // FD set before we close the socket by calling DNSServiceRefDeallocate. <rdar://problem/3585273>
        usleep(1000);
	}

	if (fRunloopSrc) {
		CFRunLoopRemoveSource(CFRunLoopGetCurrent(), fRunloopSrc, kCFRunLoopDefaultMode);
		CFRelease(fRunloopSrc);
	}

	DNSServiceRefDeallocate(fServiceRef);

	[super dealloc];
}


@end // implementation ServiceController

int main(int argc, const char *argv[])
{
    return NSApplicationMain(argc, argv);
}