]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/BonjourEvents.c
mDNSResponder-333.10.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / BonjourEvents.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2010 Apple Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #include <CoreFoundation/CoreFoundation.h>
19 #include <CoreFoundation/CFXPCBridge.h>
20 #include <dns_sd.h>
21 #include <UserEventAgentInterface.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <asl.h>
25 #include <xpc/xpc.h>
26
27
28 #pragma mark -
29 #pragma mark Types
30 #pragma mark -
31 static const char* sPluginIdentifier = "com.apple.bonjour.events";
32
33 // PLIST Keys
34 static const CFStringRef sServiceNameKey = CFSTR("ServiceName");
35 static const CFStringRef sServiceTypeKey = CFSTR("ServiceType");
36 static const CFStringRef sServiceDomainKey = CFSTR("ServiceDomain");
37
38 static const CFStringRef sOnServiceAddKey = CFSTR("OnServiceAdd");
39 static const CFStringRef sOnServiceRemoveKey = CFSTR("OnServiceRemove");
40
41 static const CFStringRef sLaunchdTokenKey = CFSTR("LaunchdToken");
42 static const CFStringRef sLaunchdDictKey = CFSTR("LaunchdDict");
43
44
45 /************************************************
46 * Launch Event Dictionary (input from launchd)
47 * Passed To: ManageEventsCallback
48 *-----------------------------------------------
49 * Typing in this dictionary is not enforced
50 * above us. So this may not be true. Type check
51 * all input before using it.
52 *-----------------------------------------------
53 * sServiceNameKey - CFString (Optional)
54 * sServiceTypeKey - CFString
55 * sServiceDomainKey - CFString
56 *
57 * One or more of the following.
58 *-----------------------------------
59 * sOnServiceAddKey - CFBoolean
60 * sOnServiceRemoveKey - CFBoolean
61 * sWhileServiceExistsKey - CFBoolean
62 ************************************************/
63
64 /************************************************
65 * Browser Dictionary
66 *-----------------------------------------------
67 * sServiceDomainKey - CFString
68 * sServiceTypeKey - CFString
69 ************************************************/
70
71 /************************************************
72 * Event Dictionary
73 *-----------------------------------------------
74 * sServiceNameKey - CFString (Optional)
75 * sLaunchdTokenKey - CFNumber
76 ************************************************/
77
78 typedef struct {
79 UserEventAgentInterfaceStruct* _UserEventAgentInterface;
80 CFUUIDRef _factoryID;
81 UInt32 _refCount;
82
83 void* _pluginContext;
84
85 CFMutableDictionaryRef _tokenToBrowserMap; // Maps a token to a browser that can be used to scan the remaining dictionaries.
86 CFMutableDictionaryRef _browsers; // A Dictionary of Browser Dictionaries where the resposible browser is the key.
87 CFMutableDictionaryRef _onAddEvents; // A Dictionary of Event Dictionaries that describe events to trigger on a service appearing.
88 CFMutableDictionaryRef _onRemoveEvents; // A Dictionary of Event Dictionaries that describe events to trigger on a service disappearing.
89 } BonjourUserEventsPlugin;
90
91 typedef struct {
92 CFIndex refCount;
93 DNSServiceRef browserRef;
94 } NetBrowserInfo;
95
96 #pragma mark -
97 #pragma mark Prototypes
98 #pragma mark -
99 // COM Stuff
100 static HRESULT QueryInterface(void *myInstance, REFIID iid, LPVOID *ppv);
101 static ULONG AddRef(void* instance);
102 static ULONG Release(void* instance);
103
104 static BonjourUserEventsPlugin* Alloc(CFUUIDRef factoryID);
105 static void Dealloc(BonjourUserEventsPlugin* plugin);
106
107 void * UserEventAgentFactory(CFAllocatorRef allocator, CFUUIDRef typeID);
108
109 // Plugin Management
110 static void Install(void* instance);
111 static void ManageEventsCallback(
112 UserEventAgentLaunchdAction action,
113 CFNumberRef token,
114 CFTypeRef eventMatchDict,
115 void * vContext);
116
117
118 // Plugin Guts
119 void AddEventToPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchdToken, CFDictionaryRef eventParameters);
120 void RemoveEventFromPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchToken);
121
122 NetBrowserInfo* CreateBrowser(BonjourUserEventsPlugin* plugin, CFStringRef type, CFStringRef domain);
123 NetBrowserInfo* BrowserForSDRef(BonjourUserEventsPlugin* plugin, DNSServiceRef sdRef);
124 void AddEventDictionary(CFDictionaryRef eventDict, CFMutableDictionaryRef allEventsDictionary, NetBrowserInfo* key);
125 void RemoveEventFromArray(CFMutableArrayRef array, CFNumberRef launchdToken);
126
127 // Net Service Browser Stuff
128 void ServiceBrowserCallback (DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char* serviceName, const char* regtype, const char* replyDomain, void* context);
129 void HandleTemporaryEventsForService(BonjourUserEventsPlugin* plugin, NetBrowserInfo* browser, CFStringRef serviceName, CFMutableDictionaryRef eventsDictionary);
130
131 // Convence Stuff
132 const char* CStringFromCFString(CFStringRef string);
133
134 // NetBrowserInfo "Object"
135 NetBrowserInfo* NetBrowserInfoCreate(CFStringRef serviceType, CFStringRef domain, void* context);
136 const void* NetBrowserInfoRetain(CFAllocatorRef allocator, const void* info);
137 void NetBrowserInfoRelease(CFAllocatorRef allocator, const void* info);
138 Boolean NetBrowserInfoEqual(const void *value1, const void *value2);
139 CFHashCode NetBrowserInfoHash(const void *value);
140 CFStringRef NetBrowserInfoCopyDescription(const void *value);
141
142 static const CFDictionaryKeyCallBacks kNetBrowserInfoDictionaryKeyCallbacks = {
143 0,
144 NetBrowserInfoRetain,
145 NetBrowserInfoRelease,
146 NetBrowserInfoCopyDescription,
147 NetBrowserInfoEqual,
148 NetBrowserInfoHash
149 };
150
151 static const CFDictionaryValueCallBacks kNetBrowserInfoDictionaryValueCallbacks = {
152 0,
153 NetBrowserInfoRetain,
154 NetBrowserInfoRelease,
155 NetBrowserInfoCopyDescription,
156 NetBrowserInfoEqual
157 };
158
159 // COM type definition goop.
160 static UserEventAgentInterfaceStruct UserEventAgentInterfaceFtbl = {
161 NULL, // Required padding for COM
162 QueryInterface, // Query Interface
163 AddRef, // AddRef()
164 Release, // Release()
165 Install // Install
166 };
167
168 #pragma mark -
169 #pragma mark COM Management
170 #pragma mark -
171
172 /*****************************************************************************
173 *****************************************************************************/
174 static HRESULT QueryInterface(void *myInstance, REFIID iid, LPVOID *ppv)
175 {
176 CFUUIDRef interfaceID = CFUUIDCreateFromUUIDBytes(NULL, iid);
177
178 // Test the requested ID against the valid interfaces.
179 if(CFEqual(interfaceID, kUserEventAgentInterfaceID))
180 {
181 ((BonjourUserEventsPlugin *) myInstance)->_UserEventAgentInterface->AddRef(myInstance);
182 *ppv = myInstance;
183 CFRelease(interfaceID);
184 return S_OK;
185 }
186 else if(CFEqual(interfaceID, IUnknownUUID))
187 {
188 ((BonjourUserEventsPlugin *) myInstance)->_UserEventAgentInterface->AddRef(myInstance);
189 *ppv = myInstance;
190 CFRelease(interfaceID);
191 return S_OK;
192 }
193 else // Requested interface unknown, bail with error.
194 {
195 *ppv = NULL;
196 CFRelease(interfaceID);
197 return E_NOINTERFACE;
198 }
199 }
200
201 /*****************************************************************************
202 *****************************************************************************/
203 static ULONG AddRef(void* instance)
204 {
205 BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)instance;
206 return ++plugin->_refCount;
207 }
208
209 /*****************************************************************************
210 *****************************************************************************/
211 static ULONG Release(void* instance)
212 {
213 BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)instance;
214
215 if (plugin->_refCount != 0)
216 --plugin->_refCount;
217
218 if (plugin->_refCount == 0)
219 {
220 Dealloc(instance);
221 return 0;
222 }
223
224 return plugin->_refCount;
225 }
226
227 /*****************************************************************************
228 * Alloc
229 * -
230 * Functionas as both +[alloc] and -[init] for the plugin. Add any
231 * initalization of member variables here.
232 *****************************************************************************/
233 static BonjourUserEventsPlugin* Alloc(CFUUIDRef factoryID)
234 {
235 BonjourUserEventsPlugin* plugin = malloc(sizeof(BonjourUserEventsPlugin));
236
237 plugin->_UserEventAgentInterface = &UserEventAgentInterfaceFtbl;
238 plugin->_pluginContext = NULL;
239
240 if (factoryID)
241 {
242 plugin->_factoryID = (CFUUIDRef)CFRetain(factoryID);
243 CFPlugInAddInstanceForFactory(factoryID);
244 }
245
246 plugin->_refCount = 1;
247 plugin->_tokenToBrowserMap = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kNetBrowserInfoDictionaryValueCallbacks);
248 plugin->_browsers = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
249 plugin->_onAddEvents = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
250 plugin->_onRemoveEvents = CFDictionaryCreateMutable(NULL, 0, &kNetBrowserInfoDictionaryKeyCallbacks, &kCFTypeDictionaryValueCallBacks);
251
252 return plugin;
253 }
254
255 /*****************************************************************************
256 * Dealloc
257 * -
258 * Much like Obj-C dealloc this method is responsible for releasing any object
259 * this plugin is holding. Unlike ObjC, you call directly free() instead of
260 * [super dalloc].
261 *****************************************************************************/
262 static void Dealloc(BonjourUserEventsPlugin* plugin)
263 {
264 CFUUIDRef factoryID = plugin->_factoryID;
265
266 if (factoryID)
267 {
268 CFPlugInRemoveInstanceForFactory(factoryID);
269 CFRelease(factoryID);
270 }
271
272 if (plugin->_tokenToBrowserMap)
273 CFRelease(plugin->_tokenToBrowserMap);
274
275 if (plugin->_browsers)
276 CFRelease(plugin->_browsers);
277
278 if (plugin->_onAddEvents)
279 CFRelease(plugin->_onAddEvents);
280
281 if (plugin->_onRemoveEvents)
282 CFRelease(plugin->_onRemoveEvents);
283
284 free(plugin);
285 }
286
287 /*******************************************************************************
288 *******************************************************************************/
289 void * UserEventAgentFactory(CFAllocatorRef allocator, CFUUIDRef typeID)
290 {
291 (void)allocator;
292 BonjourUserEventsPlugin * result = NULL;
293
294 if (typeID && CFEqual(typeID, kUserEventAgentTypeID)) {
295 result = Alloc(kUserEventAgentFactoryID);
296 }
297
298 return (void *)result;
299 }
300
301 #pragma mark -
302 #pragma mark Plugin Management
303 #pragma mark -
304 /*****************************************************************************
305 * Install
306 * -
307 * This is invoked once when the plugin is loaded to do initial setup and
308 * allow us to register with launchd. If UserEventAgent crashes, the plugin
309 * will need to be reloaded, and hence this will get invoked again.
310 *****************************************************************************/
311 static void Install(void *instance)
312 {
313 BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)instance;
314
315 plugin->_pluginContext = UserEventAgentRegisterForLaunchEvents(sPluginIdentifier, &ManageEventsCallback, plugin);
316
317 if (!plugin->_pluginContext)
318 {
319 fprintf(stderr, "%s:%s failed to register for launch events.\n", sPluginIdentifier, __FUNCTION__);
320 return;
321 }
322
323 }
324
325 /*****************************************************************************
326 * ManageEventsCallback
327 * -
328 * This is invoked when launchd loads a event dictionary and needs to inform
329 * us what a daemon / agent is looking for.
330 *****************************************************************************/
331 static void ManageEventsCallback(UserEventAgentLaunchdAction action, CFNumberRef token, CFTypeRef eventMatchDict, void* vContext)
332 {
333
334 if (!eventMatchDict)
335 {
336 fprintf(stderr, "%s:%s empty dictionary\n", sPluginIdentifier, __FUNCTION__);
337 return;
338 }
339 if (CFGetTypeID(eventMatchDict) != CFDictionaryGetTypeID())
340 {
341 fprintf(stderr, "%s:%s given non-dict for event dictionary, action %d\n", sPluginIdentifier, __FUNCTION__, action);
342 return;
343 }
344
345 if (action == kUserEventAgentLaunchdAdd)
346 {
347 // Launchd wants us to add a launch event for this token and matching dictionary.
348 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling AddEventToPlugin", sPluginIdentifier, __FUNCTION__);
349 AddEventToPlugin((BonjourUserEventsPlugin*)vContext, token, (CFDictionaryRef)eventMatchDict);
350 }
351 else if (action == kUserEventAgentLaunchdRemove)
352 {
353 // Launchd wants us to remove the event hook we setup for this token / matching dictionary.
354 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling RemoveEventToPlugin", sPluginIdentifier, __FUNCTION__);
355 RemoveEventFromPlugin((BonjourUserEventsPlugin*)vContext, token);
356 }
357 else
358 {
359 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s unknown callback event\n", sPluginIdentifier, __FUNCTION__);
360 }
361 }
362
363
364 #pragma mark -
365 #pragma mark Plugin Guts
366 #pragma mark -
367
368 /*****************************************************************************
369 * AddEventToPlugin
370 * -
371 * This method is invoked when launchd wishes the plugin to setup a launch
372 * event matching the parameters in the dictionary.
373 *****************************************************************************/
374 void AddEventToPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchdToken, CFDictionaryRef eventParameters)
375 {
376 CFStringRef domain = CFDictionaryGetValue(eventParameters, sServiceDomainKey);
377 CFStringRef type = CFDictionaryGetValue(eventParameters, sServiceTypeKey);
378 CFStringRef name = CFDictionaryGetValue(eventParameters, sServiceNameKey);
379 CFBooleanRef cfOnAdd = CFDictionaryGetValue(eventParameters, sOnServiceAddKey);
380 CFBooleanRef cfOnRemove = CFDictionaryGetValue(eventParameters, sOnServiceRemoveKey);
381
382 Boolean onAdd = false;
383 Boolean onRemove = false;
384
385 if (cfOnAdd && CFGetTypeID(cfOnAdd) == CFBooleanGetTypeID() && CFBooleanGetValue(cfOnAdd))
386 onAdd = true;
387
388 if (cfOnRemove && CFGetTypeID(cfOnRemove) == CFBooleanGetTypeID() && CFBooleanGetValue(cfOnRemove))
389 onRemove = true;
390
391 // A type is required. If none is specified, BAIL
392 if (!type || CFGetTypeID(type) != CFStringGetTypeID())
393 {
394 fprintf(stderr, "%s:%s: a LaunchEvent is missing a service type.\n", sPluginIdentifier, __FUNCTION__);
395 return;
396 }
397
398 // If we aren't suppose to launch on services appearing or disappearing, this service does nothing. Ignore.
399 if (!onAdd && !onRemove)
400 {
401 fprintf(stderr, "%s:%s a LaunchEvent is missing both onAdd and onRemove events\n", sPluginIdentifier, __FUNCTION__);
402 return;
403 }
404
405 // If no domain is specified, assume local.
406 if (!domain)
407 {
408 domain = CFSTR("local");
409 }
410 else if (CFGetTypeID(domain) != CFStringGetTypeID() ) // If the domain is not a string, fail
411 {
412 fprintf(stderr, "%s:%s a LaunchEvent has a domain that is not a string.\n", sPluginIdentifier, __FUNCTION__);
413 return;
414 }
415
416 // If we have a name filter, but it's not a string. This event is broken, bail.
417 if (name && CFGetTypeID(name) != CFStringGetTypeID())
418 {
419 fprintf(stderr, "%s:%s a LaunchEvent has a domain that is not a string.\n", sPluginIdentifier, __FUNCTION__);
420 return;
421 }
422
423 // Get us a browser
424 NetBrowserInfo* browser = CreateBrowser(plugin, type, domain);
425
426 if (!browser)
427 {
428 fprintf(stderr, "%s:%s cannot create browser\n", sPluginIdentifier, __FUNCTION__);
429 return;
430 }
431
432 // Create Event Dictionary
433 CFMutableDictionaryRef eventDictionary = CFDictionaryCreateMutable(NULL, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
434
435 // We store both the Token and the Dictionary. UserEventAgentSetLaunchEventState needs
436 // the token and UserEventAgentSetFireEvent needs both the token and the dictionary
437 CFDictionarySetValue(eventDictionary, sLaunchdTokenKey, launchdToken);
438 CFDictionarySetValue(eventDictionary, sLaunchdDictKey, eventParameters);
439
440 if (name)
441 CFDictionarySetValue(eventDictionary, sServiceNameKey, name);
442
443 // Add to the correct dictionary.
444 if (onAdd)
445 {
446 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Adding browser to AddEvents", sPluginIdentifier, __FUNCTION__);
447 AddEventDictionary(eventDictionary, plugin->_onAddEvents, browser);
448 }
449
450 if (onRemove)
451 {
452 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Adding browser to RemoveEvents", sPluginIdentifier, __FUNCTION__);
453 AddEventDictionary(eventDictionary, plugin->_onRemoveEvents, browser);
454 }
455
456 // Add Token Mapping
457 CFDictionarySetValue(plugin->_tokenToBrowserMap, launchdToken, browser);
458
459 // Release Memory
460 CFRelease(eventDictionary);
461 }
462
463 /*****************************************************************************
464 * RemoveEventFromPlugin
465 * -
466 * This method is invoked when launchd wishes the plugin to setup a launch
467 * event matching the parameters in the dictionary.
468 *****************************************************************************/
469 void RemoveEventFromPlugin(BonjourUserEventsPlugin* plugin, CFNumberRef launchdToken)
470 {
471 NetBrowserInfo* browser = (NetBrowserInfo*)CFDictionaryGetValue(plugin->_tokenToBrowserMap, launchdToken);
472 Boolean othersUsingBrowser = false;
473
474 if (!browser)
475 {
476 long long value = 0;
477 CFNumberGetValue(launchdToken, kCFNumberLongLongType, &value);
478 fprintf(stderr, "%s:%s Launchd asked us to remove a token we did not register! ==Token:%lld== \n", sPluginIdentifier, __FUNCTION__, value);
479 return;
480 }
481
482 CFMutableArrayRef onAddEvents = (CFMutableArrayRef)CFDictionaryGetValue(plugin->_onAddEvents, browser);
483 CFMutableArrayRef onRemoveEvents = (CFMutableArrayRef)CFDictionaryGetValue(plugin->_onRemoveEvents, browser);
484
485 if (onAddEvents)
486 {
487 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Calling RemoveEventFromArray for OnAddEvents", sPluginIdentifier, __FUNCTION__);
488 RemoveEventFromArray(onAddEvents, launchdToken);
489
490 // Is the array now empty, clean up
491 if (CFArrayGetCount(onAddEvents) == 0)
492 {
493 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Removing the browser from AddEvents", sPluginIdentifier, __FUNCTION__);
494 CFDictionaryRemoveValue(plugin->_onAddEvents, browser);
495 }
496 }
497
498 if (onRemoveEvents)
499 {
500 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Calling RemoveEventFromArray for OnRemoveEvents", sPluginIdentifier, __FUNCTION__);
501 RemoveEventFromArray(onRemoveEvents, launchdToken);
502
503 // Is the array now empty, clean up
504 if (CFArrayGetCount(onRemoveEvents) == 0)
505 {
506 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Removing the browser from RemoveEvents", sPluginIdentifier, __FUNCTION__);
507 CFDictionaryRemoveValue(plugin->_onRemoveEvents, browser);
508 }
509 }
510
511 // Remove ourselves from the token dictionary.
512 CFDictionaryRemoveValue(plugin->_tokenToBrowserMap, launchdToken);
513
514 // Check to see if anyone else is using this browser.
515 CFIndex i;
516 CFIndex count = CFDictionaryGetCount(plugin->_tokenToBrowserMap);
517 NetBrowserInfo** browsers = malloc(count * sizeof(NetBrowserInfo*));
518
519 // Fetch the values of the token dictionary
520 CFDictionaryGetKeysAndValues(plugin->_tokenToBrowserMap, NULL, (const void**)browsers);
521
522 for (i = 0; i < count; ++i)
523 {
524 if (NetBrowserInfoEqual(browsers[i], browser))
525 {
526 othersUsingBrowser = true;
527 break;
528 }
529 }
530
531 // If no one else is useing our browser, clean up!
532 if (!othersUsingBrowser)
533 {
534 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Removing browser %p from _browsers", sPluginIdentifier, __FUNCTION__, browser);
535 CFDictionaryRemoveValue(plugin->_browsers, browser); // This triggers release and dealloc of the browser
536 }
537 else
538 {
539 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Decrementing browsers %p count", sPluginIdentifier, __FUNCTION__, browser);
540 // Decrement my reference count (it was incremented when it was added to _browsers in CreateBrowser)
541 NetBrowserInfoRelease(NULL, browser);
542 }
543
544 free(browsers);
545 }
546
547
548 /*****************************************************************************
549 * CreateBrowser
550 * -
551 * This method returns a NetBrowserInfo that is looking for a type of
552 * service in a domain. If no browser exists, it will create one and return it.
553 *****************************************************************************/
554 NetBrowserInfo* CreateBrowser(BonjourUserEventsPlugin* plugin, CFStringRef type, CFStringRef domain)
555 {
556 CFIndex i;
557 CFIndex count = CFDictionaryGetCount(plugin->_browsers);
558 NetBrowserInfo* browser = NULL;
559 CFDictionaryRef* dicts = malloc(count * sizeof(CFDictionaryRef));
560 NetBrowserInfo** browsers = malloc(count * sizeof(NetBrowserInfo*));
561
562 // Fetch the values of the browser dictionary
563 CFDictionaryGetKeysAndValues(plugin->_browsers, (const void**)browsers, (const void**)dicts);
564
565
566 // Loop thru the browsers list and see if we can find a matching one.
567 for (i = 0; i < count; ++i)
568 {
569 CFDictionaryRef browserDict = dicts[i];
570
571 CFStringRef browserType = CFDictionaryGetValue(browserDict, sServiceTypeKey);
572 CFStringRef browserDomain = CFDictionaryGetValue(browserDict, sServiceDomainKey);
573
574 // If we have a matching browser, break
575 if ((CFStringCompare(browserType, type, kCFCompareCaseInsensitive) == kCFCompareEqualTo) &&
576 (CFStringCompare(browserDomain, domain, kCFCompareCaseInsensitive) == kCFCompareEqualTo))
577 {
578 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: found a duplicate browser\n", sPluginIdentifier, __FUNCTION__);
579 browser = browsers[i];
580 NetBrowserInfoRetain(NULL, browser);
581 break;
582 }
583 }
584
585 // No match found, lets create one!
586 if (!browser)
587 {
588
589 browser = NetBrowserInfoCreate(type, domain, plugin);
590
591 if (!browser)
592 {
593 fprintf(stderr, "%s:%s failed to search for %s.%s", sPluginIdentifier, __FUNCTION__, CStringFromCFString(type) , CStringFromCFString(domain));
594 free(dicts);
595 free(browsers);
596 return NULL;
597 }
598
599 // Service browser created, lets add this to ourselves to the dictionary.
600 CFMutableDictionaryRef browserDict = CFDictionaryCreateMutable(NULL, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
601
602 CFDictionarySetValue(browserDict, sServiceTypeKey, type);
603 CFDictionarySetValue(browserDict, sServiceDomainKey, domain);
604
605 // Add the dictionary to the browsers dictionary.
606 CFDictionarySetValue(plugin->_browsers, browser, browserDict);
607
608 NetBrowserInfoRelease(NULL, browser);
609
610 // Release Memory
611 CFRelease(browserDict);
612 }
613
614 free(dicts);
615 free(browsers);
616
617 return browser;
618 }
619
620 /*****************************************************************************
621 * BrowserForSDRef
622 * -
623 * This method returns a NetBrowserInfo that matches the calling SDRef passed
624 * in via the callback.
625 *****************************************************************************/
626 NetBrowserInfo* BrowserForSDRef(BonjourUserEventsPlugin* plugin, DNSServiceRef sdRef)
627 {
628 CFIndex i;
629 CFIndex count = CFDictionaryGetCount(plugin->_browsers);
630 NetBrowserInfo* browser = NULL;
631 NetBrowserInfo** browsers = malloc(count * sizeof(NetBrowserInfo*));
632
633 // Fetch the values of the browser dictionary
634 CFDictionaryGetKeysAndValues(plugin->_browsers, (const void**)browsers, NULL);
635
636 // Loop thru the browsers list and see if we can find a matching one.
637 for (i = 0; i < count; ++i)
638 {
639 NetBrowserInfo* currentBrowser = browsers[i];
640
641 if (currentBrowser->browserRef == sdRef)
642 {
643 browser = currentBrowser;
644 break;
645 }
646 }
647
648
649 free(browsers);
650
651 return browser;
652 }
653
654 /*****************************************************************************
655 * AddEventDictionary
656 * -
657 * Adds a event to a browser's event dictionary
658 *****************************************************************************/
659
660 void AddEventDictionary(CFDictionaryRef eventDict, CFMutableDictionaryRef allEventsDictionary, NetBrowserInfo* key)
661 {
662 CFMutableArrayRef eventsForBrowser = (CFMutableArrayRef)CFDictionaryGetValue(allEventsDictionary, key);
663
664 if (!eventsForBrowser) // We have no events for this browser yet, lets add him.
665 {
666 eventsForBrowser = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
667 CFDictionarySetValue(allEventsDictionary, key, eventsForBrowser);
668 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s creating a new array", sPluginIdentifier, __FUNCTION__);
669 }
670 else
671 {
672 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s Incrementing refcount", sPluginIdentifier, __FUNCTION__);
673 CFRetain(eventsForBrowser);
674 }
675
676 CFArrayAppendValue(eventsForBrowser, eventDict);
677 CFRelease(eventsForBrowser);
678 }
679
680 /*****************************************************************************
681 * RemoveEventFromArray
682 * -
683 * Searches a Array of Event Dictionaries to find one with a matching launchd
684 * token and remove it.
685 *****************************************************************************/
686
687 void RemoveEventFromArray(CFMutableArrayRef array, CFNumberRef launchdToken)
688 {
689 CFIndex i;
690 CFIndex count = CFArrayGetCount(array);
691
692 // Loop thru looking for us.
693 for (i = 0; i < count; )
694 {
695 CFDictionaryRef eventDict = CFArrayGetValueAtIndex(array, i);
696 CFNumberRef token = CFDictionaryGetValue(eventDict, sLaunchdTokenKey);
697
698 if (CFEqual(token, launchdToken)) // This is the same event?
699 {
700 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s found token", sPluginIdentifier, __FUNCTION__);
701 CFArrayRemoveValueAtIndex(array, i); // Remove the event,
702 break; // The token should only exist once, so it makes no sense to continue.
703 }
704 else
705 {
706 ++i; // If it's not us, advance.
707 }
708 }
709 if (i == count) asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s did not find token", sPluginIdentifier, __FUNCTION__);
710 }
711
712 #pragma mark -
713 #pragma mark Net Service Browser Stuff
714 #pragma mark -
715
716 /*****************************************************************************
717 * ServiceBrowserCallback
718 * -
719 * This method is the heart of the plugin. It's the runloop callback annoucing
720 * the appearence and disappearance of network services.
721 *****************************************************************************/
722
723 void ServiceBrowserCallback (DNSServiceRef sdRef,
724 DNSServiceFlags flags,
725 uint32_t interfaceIndex,
726 DNSServiceErrorType errorCode,
727 const char* serviceName,
728 const char* regtype,
729 const char* replyDomain,
730 void* context )
731 {
732 (void)interfaceIndex;
733 (void)regtype;
734 (void)replyDomain;
735 BonjourUserEventsPlugin* plugin = (BonjourUserEventsPlugin*)context;
736 NetBrowserInfo* browser = BrowserForSDRef(plugin, sdRef);
737
738 if (!browser) // Missing browser?
739 {
740 fprintf(stderr, "%s:%s ServiceBrowserCallback: missing browser\n", sPluginIdentifier, __FUNCTION__);
741 return;
742 }
743
744 if (errorCode != kDNSServiceErr_NoError)
745 {
746 fprintf(stderr, "%s:%s ServiceBrowserCallback: errcode set %d\n", sPluginIdentifier, __FUNCTION__, errorCode);
747 return;
748 }
749
750 CFStringRef cfServiceName = CFStringCreateWithCString(NULL, serviceName, kCFStringEncodingUTF8);
751
752 if (flags & kDNSServiceFlagsAdd)
753 {
754 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling HandleTemporaryEventsForService Add\n", sPluginIdentifier, __FUNCTION__);
755 HandleTemporaryEventsForService(plugin, browser, cfServiceName, plugin->_onAddEvents);
756 }
757 else
758 {
759 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s calling HandleTemporaryEventsForService Remove\n", sPluginIdentifier, __FUNCTION__);
760 HandleTemporaryEventsForService(plugin, browser, cfServiceName, plugin->_onRemoveEvents);
761 }
762
763 CFRelease(cfServiceName);
764 }
765
766 /*****************************************************************************
767 * HandleTemporaryEventsForService
768 * -
769 * This method handles the firing of one shot events. Aka. Events that are
770 * signaled when a service appears / disappears. They have a temporarly
771 * signaled state.
772 *****************************************************************************/
773 void HandleTemporaryEventsForService(BonjourUserEventsPlugin* plugin, NetBrowserInfo* browser, CFStringRef serviceName, CFMutableDictionaryRef eventsDictionary)
774 {
775 CFArrayRef events = (CFArrayRef)CFDictionaryGetValue(eventsDictionary, browser); // Get events for the browser we passed in.
776 CFIndex i;
777 CFIndex count;
778
779 if (!events) // Somehow we have a orphan browser...
780 return;
781
782 count = CFArrayGetCount(events);
783
784 // Go thru the events and run filters, notifity if they pass.
785 for (i = 0; i < count; ++i)
786 {
787 CFDictionaryRef eventDict = (CFDictionaryRef)CFArrayGetValueAtIndex(events, i);
788 CFStringRef eventServiceName = (CFStringRef)CFDictionaryGetValue(eventDict, sServiceNameKey);
789 CFNumberRef token = (CFNumberRef) CFDictionaryGetValue(eventDict, sLaunchdTokenKey);
790 CFDictionaryRef dict = (CFDictionaryRef) CFDictionaryGetValue(eventDict, sLaunchdDictKey);
791
792 // Currently we only filter on service name, that makes this as simple as...
793 if (!eventServiceName || CFEqual(serviceName, eventServiceName))
794 {
795 uint64_t tokenUint64;
796 // Signal Event: This is edge trigger. When the action has been taken, it will not
797 // be remembered anymore.
798
799 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s HandleTemporaryEventsForService signal\n", sPluginIdentifier, __FUNCTION__);
800 CFNumberGetValue(token, kCFNumberLongLongType, &tokenUint64);
801
802 xpc_object_t jobRequest = _CFXPCCreateXPCObjectFromCFObject(dict);
803
804 UserEventAgentFireEvent(plugin->_pluginContext, tokenUint64, jobRequest);
805 xpc_release(jobRequest);
806 }
807 }
808 }
809
810 #pragma mark -
811 #pragma mark Convenience
812 #pragma mark -
813
814 /*****************************************************************************
815 * CStringFromCFString
816 * -
817 * Silly convenence function for dealing with non-critical CFSTR -> cStr
818 * conversions.
819 *****************************************************************************/
820
821 const char* CStringFromCFString(CFStringRef string)
822 {
823 const char* defaultString = "??????";
824 const char* cstring;
825
826 if (!string)
827 return defaultString;
828
829 cstring = CFStringGetCStringPtr(string, kCFStringEncodingUTF8);
830
831 return (cstring) ? cstring : defaultString;
832
833 }
834
835 #pragma mark -
836 #pragma mark NetBrowserInfo "Object"
837 #pragma mark -
838 /*****************************************************************************
839 * NetBrowserInfoCreate
840 * -
841 * The method creates a NetBrowserInfo Object and initalizes it.
842 *****************************************************************************/
843 NetBrowserInfo* NetBrowserInfoCreate(CFStringRef serviceType, CFStringRef domain, void* context)
844 {
845 NetBrowserInfo* outObj = NULL;
846 DNSServiceRef browserRef = NULL;
847 char* cServiceType = NULL;
848 char* cDomain = NULL;
849 Boolean success = true;
850
851 CFIndex serviceSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(serviceType), kCFStringEncodingUTF8);
852 cServiceType = calloc(serviceSize, 1);
853 success = CFStringGetCString(serviceType, cServiceType, serviceSize, kCFStringEncodingUTF8);
854
855
856 if (domain)
857 {
858 CFIndex domainSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(domain), kCFStringEncodingUTF8);
859 cDomain = calloc(serviceSize, 1);
860 success = success && CFStringGetCString(domain, cDomain, domainSize, kCFStringEncodingUTF8);
861 }
862
863 if (!success)
864 {
865 fprintf(stderr, "%s:%s LaunchEvent has badly encoded service type or domain.\n", sPluginIdentifier, __FUNCTION__);
866 free(cServiceType);
867
868 if (cDomain)
869 free(cDomain);
870
871 return NULL;
872 }
873
874 DNSServiceErrorType err = DNSServiceBrowse(&browserRef, 0, 0, cServiceType, cDomain, ServiceBrowserCallback, context);
875
876 if (err != kDNSServiceErr_NoError)
877 {
878 fprintf(stderr, "%s:%s Failed to create browser for %s, %s\n", sPluginIdentifier, __FUNCTION__, cServiceType, cDomain);
879 free(cServiceType);
880
881 if (cDomain)
882 free(cDomain);
883
884 return NULL;
885 }
886
887 DNSServiceSetDispatchQueue(browserRef, dispatch_get_main_queue());
888
889
890 outObj = malloc(sizeof(NetBrowserInfo));
891
892 outObj->refCount = 1;
893 outObj->browserRef = browserRef;
894
895 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: created new object %p", sPluginIdentifier, __FUNCTION__, outObj);
896
897 free(cServiceType);
898
899 if (cDomain)
900 free(cDomain);
901
902 return outObj;
903 }
904
905 /*****************************************************************************
906 * NetBrowserInfoRetain
907 * -
908 * The method retains a NetBrowserInfo object.
909 *****************************************************************************/
910 const void* NetBrowserInfoRetain(CFAllocatorRef allocator, const void* info)
911 {
912 (void)allocator;
913 NetBrowserInfo* obj = (NetBrowserInfo*)info;
914
915 if (!obj)
916 return NULL;
917
918 ++obj->refCount;
919 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Incremented ref count on %p, count %d", sPluginIdentifier, __FUNCTION__, obj->browserRef, (int)obj->refCount);
920
921 return obj;
922 }
923
924 /*****************************************************************************
925 * NetBrowserInfoRelease
926 * -
927 * The method releases a NetBrowserInfo object.
928 *****************************************************************************/
929 void NetBrowserInfoRelease(CFAllocatorRef allocator, const void* info)
930 {
931 (void)allocator;
932 NetBrowserInfo* obj = (NetBrowserInfo*)info;
933
934 if (!obj)
935 return;
936
937 if (obj->refCount == 1)
938 {
939 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: DNSServiceRefDeallocate %p", sPluginIdentifier, __FUNCTION__, obj->browserRef);
940 DNSServiceRefDeallocate(obj->browserRef);
941 free(obj);
942 }
943 else
944 {
945 --obj->refCount;
946 asl_log(NULL, NULL, ASL_LEVEL_INFO, "%s:%s: Decremented ref count on %p, count %d", sPluginIdentifier, __FUNCTION__, obj->browserRef, (int)obj->refCount);
947 }
948
949 }
950
951 /*****************************************************************************
952 * NetBrowserInfoEqual
953 * -
954 * The method is used to compare two NetBrowserInfo objects for equality.
955 *****************************************************************************/
956 Boolean NetBrowserInfoEqual(const void *value1, const void *value2)
957 {
958 NetBrowserInfo* obj1 = (NetBrowserInfo*)value1;
959 NetBrowserInfo* obj2 = (NetBrowserInfo*)value2;
960
961 if (obj1->browserRef == obj2->browserRef)
962 return true;
963
964 return false;
965 }
966
967 /*****************************************************************************
968 * NetBrowserInfoHash
969 * -
970 * The method is used to make a hash for the object. We can cheat and use the
971 * browser pointer.
972 *****************************************************************************/
973 CFHashCode NetBrowserInfoHash(const void *value)
974 {
975 return (CFHashCode)((NetBrowserInfo*)value)->browserRef;
976 }
977
978
979 /*****************************************************************************
980 * NetBrowserInfoCopyDescription
981 * -
982 * Make CF happy.
983 *****************************************************************************/
984 CFStringRef NetBrowserInfoCopyDescription(const void *value)
985 {
986 (void)value;
987 return CFStringCreateWithCString(NULL, "NetBrowserInfo: No useful description", kCFStringEncodingUTF8);
988 }
989