summaryrefslogtreecommitdiffstats
path: root/mDNSResponder/mDNSMacOSX/BonjourEvents.c
blob: b930818939fcc35fd27d77cbf95ed55b0224fd2c (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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2010 Apple 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.
 */

#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFXPCBridge.h>
#include "dns_sd.h"
#include <UserEventAgentInterface.h>
#include <stdio.h>
#include <stdlib.h>
#include <asl.h>
#include <xpc/xpc.h>


#pragma mark -
#pragma mark Types
#pragma mark -
static const char*          sPluginIdentifier       = "com.apple.bonjour.events";

// PLIST Keys
static const CFStringRef sServiceNameKey         = CFSTR("ServiceName");
static const CFStringRef sServiceTypeKey         = CFSTR("ServiceType");
static const CFStringRef sServiceDomainKey       = CFSTR("ServiceDomain");

static const CFStringRef sOnServiceAddKey        = CFSTR("OnServiceAdd");
static const CFStringRef sOnServiceRemoveKey     = CFSTR("OnServiceRemove");

static const CFStringRef sLaunchdTokenKey        = CFSTR("LaunchdToken");
static const CFStringRef sLaunchdDictKey         = CFSTR("LaunchdDict");


/************************************************
* Launch Event Dictionary (input from launchd)
* Passed To: ManageEventsCallback
*-----------------------------------------------
* Typing in this dictionary is not enforced
* above us. So this may not be true. Type check
* all input before using it.
*-----------------------------------------------
* sServiceNameKey		- CFString (Optional)
* sServiceTypeKey		- CFString
* sServiceDomainKey	- CFString
*
* One or more of the following.
*-----------------------------------
* sOnServiceAddKey			- CFBoolean
* sOnServiceRemoveKey		- CFBoolean
* sWhileServiceExistsKey	- CFBoolean
************************************************/

/************************************************
* Browser Dictionary
*-----------------------------------------------
* sServiceDomainKey - CFString
* sServiceTypeKey   - CFString
************************************************/

/************************************************
* Event Dictionary
*-----------------------------------------------
* sServiceNameKey	 - CFString (Optional)
* sLaunchdTokenKey	 - CFNumber
************************************************/

typedef struct {
    UserEventAgentInterfaceStruct*      _UserEventAgentInterface;
    CFUUIDRef _factoryID;
    UInt32 _refCount;

    void*                               _pluginContext;

    CFMutableDictionaryRef _tokenToBrowserMap;                  // Maps a token to a browser that can be used to scan the remaining dictionaries.
    CFMutableDictionaryRef _browsers;                           // A Dictionary of Browser Dictionaries where the resposible browser is the key.
    CFMutableDictionaryRef _onAddEvents;                        // A Dictionary of Event Dictionaries that describe events to trigger on a service appearing.
    CFMutableDictionaryRef _onRemoveEvents;                     // A Dictionary of Event Dictionaries that describe events to trigger on a service disappearing.
} BonjourUserEventsPlugin;

typedef struct {
    CFIndex refCount;
    DNSServiceRef browserRef;
} NetBrowserInfo;

#pragma mark -
#pragma mark Prototypes
#pragma mark -
// COM Stuff
static HRESULT  QueryInterface(void *myInstance, REFIID iid, LPVOID *ppv);
static ULONG    AddRef(void* instance);
static ULONG    Release(void* instance);

static BonjourUserEventsPlugin* Alloc(CFUUIDRef factoryID);
static void Dealloc(BonjourUserEventsPlugin* plugin);

void * UserEventAgentFactory(CFAllocatorRef allocator, CFUUIDRef typeID);

// Plugin Management
static void Install(void* instance);
static void ManageEventsCallback(
    UserEventAgentLaunchdAction action,
    CFNumberRef token,
    CFTypeRef eventMatchDict,
    void                      * vContext);


// Plugin Guts
void AddEventToPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchdToken, CFDictionaryRef eventParameters);
void RemoveEventFromPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchToken);

NetBrowserInfo* CreateBrowser(BonjourUserEventsPlugin* plugin, CFStringRef type, CFStringRef domain);
NetBrowserInfo* BrowserForSDRef(BonjourUserEventsPlugin* plugin, DNSServiceRef sdRef);
void AddEventDictionary(CFDictionaryRef eventDict, CFMutableDictionaryRef allEventsDictionary, NetBrowserInfo* key);
void RemoveEventFromArray(CFMutableArrayRef array, CFNumberRef launchdToken);

// Net Service Browser Stuff
void ServiceBrowserCallback (DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char* serviceName, const char* regtype, const char* replyDomain, void* context);
void HandleTemporaryEventsForService(BonjourUserEventsPlugin* plugin, NetBrowserInfo* browser, CFStringRef serviceName, CFMutableDictionaryRef eventsDictionary);

// Convence Stuff
const char* CStringFromCFString(CFStringRef string);

// NetBrowserInfo "Object"
NetBrowserInfo* NetBrowserInfoCreate(CFStringRef serviceType, CFStringRef domain, void* context);
const void* NetBrowserInfoRetain(CFAllocatorRef allocator, const void* info);
void NetBrowserInfoRelease(CFAllocatorRef allocator, const void* info);
Boolean NetBrowserInfoEqual(const void *value1, const void *value2);
CFHashCode  NetBrowserInfoHash(const void *value);
CFStringRef NetBrowserInfoCopyDescription(const void *value);

static const CFDictionaryKeyCallBacks kNetBrowserInfoDictionaryKeyCallbacks = {
    0,
    NetBrowserInfoRetain,
    NetBrowserInfoRelease,
    NetBrowserInfoCopyDescription,
    NetBrowserInfoEqual,
    NetBrowserInfoHash
};

static const CFDictionaryValueCallBacks kNetBrowserInfoDictionaryValueCallbacks = {
    0,
    NetBrowserInfoRetain,
    NetBrowserInfoRelease,
    NetBrowserInfoCopyDescription,
    NetBrowserInfoEqual
};

// COM type definition goop.
static UserEventAgentInterfaceStruct UserEventAgentInterfaceFtbl = {
    NULL,                   // Required padding for COM
    QueryInterface,         // Query Interface
    AddRef,                 // AddRef()
    Release,                // Release()
    Install                 // Install
};

#pragma mark -
#pragma mark COM Management
#pragma mark -

/*****************************************************************************
*****************************************************************************/
static HRESULT QueryInterface(void *myInstance, REFIID iid, LPVOID *ppv)
{
    CFUUIDRef interfaceID = CFUUIDCreateFromUUIDBytes(NULL, iid);

    // Test the requested ID against the valid interfaces.
    if(CFEqual(interfaceID, kUserEventAgentInterfaceID))
    {
        ((BonjourUserEventsPlugin *) myInstance)->_UserEventAgentInterface->AddRef(myInstance);
        *ppv = myInstance;
        CFRelease(interfaceID);
        return S_OK;
    }
    else if(CFEqual(interfaceID, IUnknownUUID))
    {
        ((BonjourUserEventsPlugin *) myInstance)->_UserEventAgentInterface->AddRef(myInstance);
        *ppv = myInstance;
        CFRelease(interfaceID);
        return S_OK;
    }
    else //  Requested interface unknown, bail with error.
    {
        *ppv = NULL;
        CFRelease(interfaceID);
        return E_NOINTERFACE;
    }
}

/*****************************************************************************
*****************************************************************************/
static ULONG AddRef(void* instance)
{
    BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)instance;
    return ++plugin->_refCount;
}

/*****************************************************************************
*****************************************************************************/
static ULONG Release(void* instance)
{
    BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)instance;

    if (plugin->_refCount != 0)
        --plugin->_refCount;

    if (plugin->_refCount == 0)
    {
        Dealloc(instance);
        return 0;
    }

    return plugin->_refCount;
}

/*****************************************************************************
* Alloc
* -
* Functionas as both +[alloc] and -[init] for the plugin. Add any
* initalization of member variables here.
*****************************************************************************/
static BonjourUserEventsPlugin* Alloc(CFUUIDRef factoryID)
{
    BonjourUserEventsPlugin* plugin = malloc(sizeof(BonjourUserEventsPlugin));

    plugin->_UserEventAgentInterface = &UserEventAgentInterfaceFtbl;
    plugin->_pluginContext = NULL;

    if (factoryID)
    {
        plugin->_factoryID = (CFUUIDRef)CFRetain(factoryID);
        CFPlugInAddInstanceForFactory(factoryID);
    }

    plugin->_refCount = 1;
    plugin->_tokenToBrowserMap = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kNetBrowserInfoDictionaryValueCallbacks);
    plugin->_browsers = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
    plugin->_onAddEvents = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
    plugin->_onRemoveEvents = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);

    return plugin;
}

/*****************************************************************************
* Dealloc
* -
* Much like Obj-C dealloc this method is responsible for releasing any object
* this plugin is holding. Unlike ObjC, you call directly free() instead of
* [super dalloc].
*****************************************************************************/
static void Dealloc(BonjourUserEventsPlugin* plugin)
{
    CFUUIDRef factoryID = plugin->_factoryID;

    if (factoryID)
    {
        CFPlugInRemoveInstanceForFactory(factoryID);
        CFRelease(factoryID);
    }

    if (plugin->_tokenToBrowserMap)
        CFRelease(plugin->_tokenToBrowserMap);

    if (plugin->_browsers)
        CFRelease(plugin->_browsers);

    if (plugin->_onAddEvents)
        CFRelease(plugin->_onAddEvents);

    if (plugin->_onRemoveEvents)
        CFRelease(plugin->_onRemoveEvents);

    free(plugin);
}

/*******************************************************************************
*******************************************************************************/
void * UserEventAgentFactory(CFAllocatorRef allocator, CFUUIDRef typeID)
{
    (void)allocator;
    BonjourUserEventsPlugin * result = NULL;

    if (typeID && CFEqual(typeID, kUserEventAgentTypeID)) {
        result = Alloc(kUserEventAgentFactoryID);
    }

    return (void *)result;
}

#pragma mark -
#pragma mark Plugin Management
#pragma mark -
/*****************************************************************************
* Install
* -
* This is invoked once when the plugin is loaded to do initial setup and
* allow us to register with launchd. If UserEventAgent crashes, the plugin
* will need to be reloaded, and hence this will get invoked again.
*****************************************************************************/
static void Install(void *instance)
{
    BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)instance;

    plugin->_pluginContext = UserEventAgentRegisterForLaunchEvents(sPluginIdentifier, &ManageEventsCallback, plugin);

    if (!plugin->_pluginContext)
    {
        fprintf(stderr, "%s:%s failed to register for launch events.\n", sPluginIdentifier, __FUNCTION__);
        return;
    }

}

/*****************************************************************************
* ManageEventsCallback
* -
* This is invoked when launchd loads a event dictionary and needs to inform
* us what a daemon / agent is looking for.
*****************************************************************************/
static void ManageEventsCallback(UserEventAgentLaunchdAction action, CFNumberRef token, CFTypeRef eventMatchDict, void* vContext)
{
    if (action == kUserEventAgentLaunchdAdd)
    {
        if (!eventMatchDict)
        {
            fprintf(stderr, "%s:%s empty dictionary\n", sPluginIdentifier, __FUNCTION__);
            return;
        }
        if (CFGetTypeID(eventMatchDict) != CFDictionaryGetTypeID())
        {
            fprintf(stderr, "%s:%s given non-dict for event dictionary, action %d\n", sPluginIdentifier, __FUNCTION__, action);
            return;
        }
        // Launchd wants us to add a launch event for this token and matching dictionary.
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling AddEventToPlugin", sPluginIdentifier, __FUNCTION__);
        AddEventToPlugin((BonjourUserEventsPlugin*)vContext, token, (CFDictionaryRef)eventMatchDict);
    }
    else if (action == kUserEventAgentLaunchdRemove)
    {
        // Launchd wants us to remove the event hook we setup for this token / matching dictionary.
        // Note: eventMatchDict can be NULL for Remove.
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling RemoveEventToPlugin", sPluginIdentifier, __FUNCTION__);
        RemoveEventFromPlugin((BonjourUserEventsPlugin*)vContext, token);
    }
    else
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s unknown callback event\n", sPluginIdentifier, __FUNCTION__);
    }
}


#pragma mark -
#pragma mark Plugin Guts
#pragma mark -

/*****************************************************************************
* AddEventToPlugin
* -
* This method is invoked when launchd wishes the plugin to setup a launch
* event matching the parameters in the dictionary.
*****************************************************************************/
void AddEventToPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchdToken, CFDictionaryRef eventParameters)
{
    CFStringRef domain = CFDictionaryGetValue(eventParameters, sServiceDomainKey);
    CFStringRef type = CFDictionaryGetValue(eventParameters, sServiceTypeKey);
    CFStringRef name = CFDictionaryGetValue(eventParameters, sServiceNameKey);
    CFBooleanRef cfOnAdd = CFDictionaryGetValue(eventParameters, sOnServiceAddKey);
    CFBooleanRef cfOnRemove = CFDictionaryGetValue(eventParameters, sOnServiceRemoveKey);

    Boolean onAdd = false;
    Boolean onRemove = false;

    if (cfOnAdd && CFGetTypeID(cfOnAdd) == CFBooleanGetTypeID() && CFBooleanGetValue(cfOnAdd))
        onAdd = true;

    if (cfOnRemove && CFGetTypeID(cfOnRemove) == CFBooleanGetTypeID() && CFBooleanGetValue(cfOnRemove))
        onRemove = true;

    // A type is required. If none is specified, BAIL
    if (!type || CFGetTypeID(type) != CFStringGetTypeID())
    {
        fprintf(stderr, "%s:%s: a LaunchEvent is missing a service type.\n", sPluginIdentifier, __FUNCTION__);
        return;
    }

    // If we aren't suppose to launch on services appearing or disappearing, this service does nothing. Ignore.
    if (!onAdd && !onRemove)
    {
        fprintf(stderr, "%s:%s a LaunchEvent is missing both onAdd and onRemove events\n", sPluginIdentifier, __FUNCTION__);
        return;
    }

    // If no domain is specified, assume local.
    if (!domain)
    {
        domain = CFSTR("local");
    }
    else if (CFGetTypeID(domain) != CFStringGetTypeID() ) // If the domain is not a string, fail
    {
        fprintf(stderr, "%s:%s a LaunchEvent has a domain that is not a string.\n", sPluginIdentifier, __FUNCTION__);
        return;
    }

    // If we have a name filter, but it's not a string. This event is broken, bail.
    if (name && CFGetTypeID(name) != CFStringGetTypeID())
    {
        fprintf(stderr, "%s:%s a LaunchEvent has a domain that is not a string.\n", sPluginIdentifier, __FUNCTION__);
        return;
    }

    // Get us a browser
    NetBrowserInfo* browser = CreateBrowser(plugin, type, domain);

    if (!browser)
    {
        fprintf(stderr, "%s:%s cannot create browser\n", sPluginIdentifier, __FUNCTION__);
        return;
    }

    // Create Event Dictionary
    CFMutableDictionaryRef eventDictionary = CFDictionaryCreateMutable(NULL, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    // We store both the Token and the Dictionary. UserEventAgentSetLaunchEventState needs
    // the token and UserEventAgentSetFireEvent needs both the token and the dictionary
    CFDictionarySetValue(eventDictionary, sLaunchdTokenKey, launchdToken);
    CFDictionarySetValue(eventDictionary, sLaunchdDictKey, eventParameters);

    if (name)
        CFDictionarySetValue(eventDictionary, sServiceNameKey, name);

    // Add to the correct dictionary.
    if (onAdd)
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Adding browser to AddEvents", sPluginIdentifier, __FUNCTION__);
        AddEventDictionary(eventDictionary, plugin->_onAddEvents, browser);
    }

    if (onRemove)
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Adding browser to RemoveEvents", sPluginIdentifier, __FUNCTION__);
        AddEventDictionary(eventDictionary, plugin->_onRemoveEvents, browser);
    }

    // Add Token Mapping
    CFDictionarySetValue(plugin->_tokenToBrowserMap, launchdToken, browser);

    // Release Memory
    CFRelease(eventDictionary);
}

/*****************************************************************************
* RemoveEventFromPlugin
* -
* This method is invoked when launchd wishes the plugin to setup a launch
* event matching the parameters in the dictionary.
*****************************************************************************/
void RemoveEventFromPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchdToken)
{
    NetBrowserInfo* browser = (NetBrowserInfo*)CFDictionaryGetValue(plugin->_tokenToBrowserMap, launchdToken);
    Boolean othersUsingBrowser = false;

    if (!browser)
    {
        long long value = 0;
        CFNumberGetValue(launchdToken, kCFNumberLongLongType, &value);
        fprintf(stderr, "%s:%s Launchd asked us to remove a token we did not register! ==Token:%lld== \n", sPluginIdentifier, __FUNCTION__, value);
        return;
    }

    CFMutableArrayRef onAddEvents = (CFMutableArrayRef)CFDictionaryGetValue(plugin->_onAddEvents, browser);
    CFMutableArrayRef onRemoveEvents = (CFMutableArrayRef)CFDictionaryGetValue(plugin->_onRemoveEvents, browser);

    if (onAddEvents)
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Calling RemoveEventFromArray for OnAddEvents", sPluginIdentifier, __FUNCTION__);
        RemoveEventFromArray(onAddEvents, launchdToken);

        // Is the array now empty, clean up
        if (CFArrayGetCount(onAddEvents) == 0)
        {
            asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Removing the browser from AddEvents", sPluginIdentifier, __FUNCTION__);
            CFDictionaryRemoveValue(plugin->_onAddEvents, browser);
        }
    }

    if (onRemoveEvents)
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Calling RemoveEventFromArray for OnRemoveEvents", sPluginIdentifier, __FUNCTION__);
        RemoveEventFromArray(onRemoveEvents, launchdToken);

        // Is the array now empty, clean up
        if (CFArrayGetCount(onRemoveEvents) == 0)
        {
            asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Removing the browser from RemoveEvents", sPluginIdentifier, __FUNCTION__);
            CFDictionaryRemoveValue(plugin->_onRemoveEvents, browser);
        }
    }

    // Remove ourselves from the token dictionary.
    CFDictionaryRemoveValue(plugin->_tokenToBrowserMap, launchdToken);

    // Check to see if anyone else is using this browser.
    CFIndex i;
    CFIndex count = CFDictionaryGetCount(plugin->_tokenToBrowserMap);
    NetBrowserInfo** browsers = malloc(count * sizeof(NetBrowserInfo*));

    // Fetch the values of the token dictionary
    CFDictionaryGetKeysAndValues(plugin->_tokenToBrowserMap, NULL, (const void**)browsers);

    for (i = 0; i < count; ++i)
    {
        if (NetBrowserInfoEqual(browsers[i], browser))
        {
            othersUsingBrowser = true;
            break;
        }
    }

    // If no one else is useing our browser, clean up!
    if (!othersUsingBrowser)
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Removing browser %p from _browsers", sPluginIdentifier, __FUNCTION__, browser);
        CFDictionaryRemoveValue(plugin->_browsers, browser); // This triggers release and dealloc of the browser
    }
    else
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Decrementing browsers %p count", sPluginIdentifier, __FUNCTION__, browser);
        // Decrement my reference count (it was incremented when it was added to _browsers in CreateBrowser)
        NetBrowserInfoRelease(NULL, browser);
    }

    free(browsers);
}


/*****************************************************************************
* CreateBrowser
* -
* This method returns a NetBrowserInfo that is looking for a type of
* service in a domain. If no browser exists, it will create one and return it.
*****************************************************************************/
NetBrowserInfo* CreateBrowser(BonjourUserEventsPlugin* plugin, CFStringRef type, CFStringRef domain)
{
    CFIndex i;
    CFIndex count = CFDictionaryGetCount(plugin->_browsers);
    NetBrowserInfo* browser = NULL;
    CFDictionaryRef* dicts = malloc(count * sizeof(CFDictionaryRef));
    NetBrowserInfo** browsers = malloc(count * sizeof(NetBrowserInfo*));

    // Fetch the values of the browser dictionary
    CFDictionaryGetKeysAndValues(plugin->_browsers, (const void**)browsers, (const void**)dicts);


    // Loop thru the browsers list and see if we can find a matching one.
    for (i = 0; i < count; ++i)
    {
        CFDictionaryRef browserDict = dicts[i];

        CFStringRef browserType = CFDictionaryGetValue(browserDict, sServiceTypeKey);
        CFStringRef browserDomain = CFDictionaryGetValue(browserDict, sServiceDomainKey);

        // If we have a matching browser, break
        if ((CFStringCompare(browserType, type, kCFCompareCaseInsensitive) == kCFCompareEqualTo) &&
            (CFStringCompare(browserDomain, domain, kCFCompareCaseInsensitive) == kCFCompareEqualTo))
        {
            asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: found a duplicate browser\n", sPluginIdentifier, __FUNCTION__);
            browser = browsers[i];
            NetBrowserInfoRetain(NULL, browser);
            break;
        }
    }

    // No match found, lets create one!
    if (!browser)
    {

        browser = NetBrowserInfoCreate(type, domain, plugin);

        if (!browser)
        {
            fprintf(stderr, "%s:%s failed to search for %s.%s", sPluginIdentifier, __FUNCTION__, CStringFromCFString(type), CStringFromCFString(domain));
            free(dicts);
            free(browsers);
            return NULL;
        }

        // Service browser created, lets add this to ourselves to the dictionary.
        CFMutableDictionaryRef browserDict = CFDictionaryCreateMutable(NULL, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

        CFDictionarySetValue(browserDict, sServiceTypeKey, type);
        CFDictionarySetValue(browserDict, sServiceDomainKey, domain);

        // Add the dictionary to the browsers dictionary.
        CFDictionarySetValue(plugin->_browsers, browser, browserDict);

        NetBrowserInfoRelease(NULL, browser);

        // Release Memory
        CFRelease(browserDict);
    }

    free(dicts);
    free(browsers);

    return browser;
}

/*****************************************************************************
* BrowserForSDRef
* -
* This method returns a NetBrowserInfo that matches the calling SDRef passed
* in via the callback.
*****************************************************************************/
NetBrowserInfo* BrowserForSDRef(BonjourUserEventsPlugin* plugin, DNSServiceRef sdRef)
{
    CFIndex i;
    CFIndex count = CFDictionaryGetCount(plugin->_browsers);
    NetBrowserInfo* browser = NULL;
    NetBrowserInfo** browsers = malloc(count * sizeof(NetBrowserInfo*));

    // Fetch the values of the browser dictionary
    CFDictionaryGetKeysAndValues(plugin->_browsers, (const void**)browsers, NULL);

    // Loop thru the browsers list and see if we can find a matching one.
    for (i = 0; i < count; ++i)
    {
        NetBrowserInfo* currentBrowser = browsers[i];

        if (currentBrowser->browserRef == sdRef)
        {
            browser = currentBrowser;
            break;
        }
    }


    free(browsers);

    return browser;
}

/*****************************************************************************
* AddEventDictionary
* -
* Adds a event to a browser's event dictionary
*****************************************************************************/

void AddEventDictionary(CFDictionaryRef eventDict, CFMutableDictionaryRef allEventsDictionary, NetBrowserInfo* key)
{
    CFMutableArrayRef eventsForBrowser = (CFMutableArrayRef)CFDictionaryGetValue(allEventsDictionary, key);

    if (!eventsForBrowser) // We have no events for this browser yet, lets add him.
    {
        eventsForBrowser = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
        CFDictionarySetValue(allEventsDictionary, key, eventsForBrowser);
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s creating a new array", sPluginIdentifier, __FUNCTION__);
    }
    else
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s Incrementing refcount", sPluginIdentifier, __FUNCTION__);
        CFRetain(eventsForBrowser);
    }

    CFArrayAppendValue(eventsForBrowser, eventDict);
    CFRelease(eventsForBrowser);
}

/*****************************************************************************
* RemoveEventFromArray
* -
* Searches a Array of Event Dictionaries to find one with a matching launchd
* token and remove it.
*****************************************************************************/

void RemoveEventFromArray(CFMutableArrayRef array, CFNumberRef launchdToken)
{
    CFIndex i;
    CFIndex count = CFArrayGetCount(array);

    // Loop thru looking for us.
    for (i = 0; i < count; )
    {
        CFDictionaryRef eventDict = CFArrayGetValueAtIndex(array, i);
        CFNumberRef token = CFDictionaryGetValue(eventDict, sLaunchdTokenKey);

        if (CFEqual(token, launchdToken)) // This is the same event?
        {
            asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s found token", sPluginIdentifier, __FUNCTION__);
            CFArrayRemoveValueAtIndex(array, i);    // Remove the event,
            break; // The token should only exist once, so it makes no sense to continue.
        }
        else
        {
            ++i; // If it's not us, advance.
        }
    }
    if (i == count) asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s did not find token", sPluginIdentifier, __FUNCTION__);
}

#pragma mark -
#pragma mark Net Service Browser Stuff
#pragma mark -

/*****************************************************************************
* ServiceBrowserCallback
* -
* This method is the heart of the plugin. It's the runloop callback annoucing
* the appearence and disappearance of network services.
*****************************************************************************/

void ServiceBrowserCallback (DNSServiceRef sdRef,
                             DNSServiceFlags flags,
                             uint32_t interfaceIndex,
                             DNSServiceErrorType errorCode,
                             const char*                serviceName,
                             const char*                regtype,
                             const char*                replyDomain,
                             void*                      context )
{
    (void)interfaceIndex;
    (void)regtype;
    (void)replyDomain;
    BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)context;
    NetBrowserInfo* browser = BrowserForSDRef(plugin, sdRef);

    if (!browser) // Missing browser?
    {
        fprintf(stderr, "%s:%s ServiceBrowserCallback: missing browser\n", sPluginIdentifier, __FUNCTION__);
        return;
    }

    if (errorCode != kDNSServiceErr_NoError)
    {
        fprintf(stderr, "%s:%s ServiceBrowserCallback: errcode set %d\n", sPluginIdentifier, __FUNCTION__, errorCode);
        return;
    }

    CFStringRef cfServiceName = CFStringCreateWithCString(NULL, serviceName, kCFStringEncodingUTF8);

    if (flags & kDNSServiceFlagsAdd)
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling HandleTemporaryEventsForService Add\n", sPluginIdentifier, __FUNCTION__);
        HandleTemporaryEventsForService(plugin, browser, cfServiceName, plugin->_onAddEvents);
    }
    else
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling HandleTemporaryEventsForService Remove\n", sPluginIdentifier, __FUNCTION__);
        HandleTemporaryEventsForService(plugin, browser, cfServiceName, plugin->_onRemoveEvents);
    }

    CFRelease(cfServiceName);
}

/*****************************************************************************
* HandleTemporaryEventsForService
* -
* This method handles the firing of one shot events. Aka. Events that are
* signaled when a service appears / disappears. They have a temporarly
* signaled state.
*****************************************************************************/
void HandleTemporaryEventsForService(BonjourUserEventsPlugin* plugin, NetBrowserInfo* browser, CFStringRef serviceName, CFMutableDictionaryRef eventsDictionary)
{
    CFArrayRef events = (CFArrayRef)CFDictionaryGetValue(eventsDictionary, browser); // Get events for the browser we passed in.
    CFIndex i;
    CFIndex count;

    if (!events)  // Somehow we have a orphan browser...
        return;

    count = CFArrayGetCount(events);

    // Go thru the events and run filters, notifity if they pass.
    for (i = 0; i < count; ++i)
    {
        CFDictionaryRef eventDict = (CFDictionaryRef)CFArrayGetValueAtIndex(events, i);
        CFStringRef eventServiceName = (CFStringRef)CFDictionaryGetValue(eventDict, sServiceNameKey);
        CFNumberRef token = (CFNumberRef) CFDictionaryGetValue(eventDict, sLaunchdTokenKey);
        CFDictionaryRef dict = (CFDictionaryRef) CFDictionaryGetValue(eventDict, sLaunchdDictKey);

        // Currently we only filter on service name, that makes this as simple as...
        if (!eventServiceName || CFEqual(serviceName, eventServiceName))
        {
            uint64_t tokenUint64;
            // Signal Event: This is edge trigger. When the action has been taken, it will not
            // be remembered anymore.

            asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s HandleTemporaryEventsForService signal\n", sPluginIdentifier, __FUNCTION__);
            CFNumberGetValue(token, kCFNumberLongLongType, &tokenUint64);

            xpc_object_t jobRequest = _CFXPCCreateXPCObjectFromCFObject(dict);

            UserEventAgentFireEvent(plugin->_pluginContext, tokenUint64, jobRequest);
            xpc_release(jobRequest);
        }
    }
}

#pragma mark -
#pragma mark Convenience
#pragma mark -

/*****************************************************************************
* CStringFromCFString
* -
* Silly convenence function for dealing with non-critical CFSTR -> cStr
* conversions.
*****************************************************************************/

const char* CStringFromCFString(CFStringRef string)
{
    const char* defaultString = "??????";
    const char* cstring;

    if (!string)
        return defaultString;

    cstring = CFStringGetCStringPtr(string, kCFStringEncodingUTF8);

    return (cstring) ? cstring : defaultString;

}

#pragma mark -
#pragma mark NetBrowserInfo "Object"
#pragma mark -
/*****************************************************************************
* NetBrowserInfoCreate
* -
* The method creates a NetBrowserInfo Object and initalizes it.
*****************************************************************************/
NetBrowserInfo* NetBrowserInfoCreate(CFStringRef serviceType, CFStringRef domain, void* context)
{
    NetBrowserInfo* outObj = NULL;
    DNSServiceRef browserRef = NULL;
    char* cServiceType = NULL;
    char* cDomain = NULL;
    Boolean success = true;

    CFIndex serviceSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(serviceType), kCFStringEncodingUTF8);
    cServiceType = calloc(serviceSize, 1);
    success = CFStringGetCString(serviceType, cServiceType, serviceSize, kCFStringEncodingUTF8);


    if (domain)
    {
        CFIndex domainSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(domain), kCFStringEncodingUTF8);
        if (domainSize)
        {
            cDomain = calloc(domainSize, 1);
            success = success && CFStringGetCString(domain, cDomain, domainSize, kCFStringEncodingUTF8);
        }
    }

    if (!success)
    {
        fprintf(stderr, "%s:%s LaunchEvent has badly encoded service type or domain.\n", sPluginIdentifier, __FUNCTION__);
        free(cServiceType);

        if (cDomain)
            free(cDomain);

        return NULL;
    }

    DNSServiceErrorType err = DNSServiceBrowse(&browserRef, 0, 0, cServiceType, cDomain, ServiceBrowserCallback, context);

    if (err != kDNSServiceErr_NoError)
    {
        fprintf(stderr, "%s:%s Failed to create browser for %s, %s\n", sPluginIdentifier, __FUNCTION__, cServiceType, cDomain);
        free(cServiceType);

        if (cDomain)
            free(cDomain);

        return NULL;
    }

    DNSServiceSetDispatchQueue(browserRef, dispatch_get_main_queue());


    outObj = malloc(sizeof(NetBrowserInfo));

    outObj->refCount = 1;
    outObj->browserRef = browserRef;

    asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: created new object %p", sPluginIdentifier, __FUNCTION__, outObj);

    free(cServiceType);

    if (cDomain)
        free(cDomain);

    return outObj;
}

/*****************************************************************************
* NetBrowserInfoRetain
* -
* The method retains a NetBrowserInfo object.
*****************************************************************************/
const void* NetBrowserInfoRetain(CFAllocatorRef allocator, const void* info)
{
    (void)allocator;
    NetBrowserInfo* obj = (NetBrowserInfo*)info;

    if (!obj)
        return NULL;

    ++obj->refCount;
    asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Incremented ref count on %p, count %d", sPluginIdentifier, __FUNCTION__, obj->browserRef, (int)obj->refCount);

    return obj;
}

/*****************************************************************************
* NetBrowserInfoRelease
* -
* The method releases a NetBrowserInfo object.
*****************************************************************************/
void NetBrowserInfoRelease(CFAllocatorRef allocator, const void* info)
{
    (void)allocator;
    NetBrowserInfo* obj = (NetBrowserInfo*)info;

    if (!obj)
        return;

    if (obj->refCount == 1)
    {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: DNSServiceRefDeallocate %p", sPluginIdentifier, __FUNCTION__, obj->browserRef);
        DNSServiceRefDeallocate(obj->browserRef);
        free(obj);
    }
    else
    {
        --obj->refCount;
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Decremented ref count on %p, count %d", sPluginIdentifier, __FUNCTION__, obj->browserRef, (int)obj->refCount);
    }

}

/*****************************************************************************
* NetBrowserInfoEqual
* -
* The method is used to compare two NetBrowserInfo objects for equality.
*****************************************************************************/
Boolean NetBrowserInfoEqual(const void *value1, const void *value2)
{
    NetBrowserInfo* obj1 = (NetBrowserInfo*)value1;
    NetBrowserInfo* obj2 = (NetBrowserInfo*)value2;

    if (obj1->browserRef == obj2->browserRef)
        return true;

    return false;
}

/*****************************************************************************
* NetBrowserInfoHash
* -
* The method is used to make a hash for the object. We can cheat and use the
* browser pointer.
*****************************************************************************/
CFHashCode  NetBrowserInfoHash(const void *value)
{
    return (CFHashCode)((NetBrowserInfo*)value)->browserRef;
}


/*****************************************************************************
* NetBrowserInfoCopyDescription
* -
* Make CF happy.
*****************************************************************************/
CFStringRef NetBrowserInfoCopyDescription(const void *value)
{
    (void)value;
    return CFStringCreateWithCString(NULL, "NetBrowserInfo: No useful description", kCFStringEncodingUTF8);
}