2 * "$Id: sysman.c 5049 2006-02-02 14:50:57Z mike $"
4 * System management definitions for the Common UNIX Printing System (CUPS).
6 * Copyright 2006 by Easy Software Products.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * cupsdStartSystemMonitor() - Start monitoring for system change.
27 * cupsdStopSystemMonitor() - Stop monitoring for system change.
28 * cupsdUpdateSystemMonitor() - Update the current system state.
29 * sysEventThreadEntry() - A thread to receive power and computer
30 * name change notifications.
31 * sysEventPowerNotifier() - Handle power notification events.
32 * sysEventConfigurationNotifier() - Computer name changed notification
34 * sysEventTimerNotifier() - Handle delayed event notifications.
39 * Include necessary headers...
46 * Power management is a new addition to CUPS. Right now it is only
47 * implemented on MacOS X, but essentially we use these three functions
48 * to let the OS know when it is OK to put the system to sleep, typically
49 * when we are not in the middle of printing a job.
51 * Once put to sleep, we invalidate all remote printers since it is
52 * common to wake up in a new location.
57 * 'cupsdStartSystemMonitor()' - Start monitoring for system change.
61 cupsdStartSystemMonitor(void)
67 * 'cupsdStopSystemMonitor()' - Stop monitoring for system change.
71 cupsdStopSystemMonitor(void)
77 * 'cupsdUpdateSystemMonitor()' - Update the current system state.
81 cupsdUpdateSystemMonitor(void)
84 #endif /* !__APPLE__ */
89 * This is the Apple-specific system event code. It works by creating
90 * a worker thread that waits for events from the OS and relays them
91 * to the main thread via a traditional pipe.
95 * Include MacOS-specific headers...
98 # include <IOKit/IOKitLib.h>
99 # include <IOKit/IOMessage.h>
100 # include <IOKit/pwr_mgt/IOPMLib.h>
101 # include <SystemConfiguration/SystemConfiguration.h>
102 # include <pthread.h>
109 # define SYSEVENT_CANSLEEP 0x1 /* Decide whether to allow sleep or not */
110 # define SYSEVENT_WILLSLEEP 0x2 /* Computer will go to sleep */
111 # define SYSEVENT_WOKE 0x4 /* Computer woke from sleep */
112 # define SYSEVENT_NETCHANGED 0x8 /* Network changed */
113 # define SYSEVENT_NAMECHANGED 0x10 /* Computer name changed */
120 typedef struct cupsd_sysevent_s
/*** System event data ****/
122 unsigned char event
; /* Event bit field */
123 io_connect_t powerKernelPort
; /* Power context data */
124 long powerNotificationID
; /* Power event data */
128 typedef struct cupsd_thread_data_s
/*** Thread context data ****/
130 cupsd_sysevent_t sysevent
; /* System event */
131 CFRunLoopTimerRef timerRef
; /* Timer to delay some change *
133 } cupsd_thread_data_t
;
140 static pthread_t SysEventThread
= NULL
;
141 /* Thread to host a runloop */
142 static pthread_mutex_t SysEventThreadMutex
= { 0 };
143 /* Coordinates access to shared gloabals */
144 static pthread_cond_t SysEventThreadCond
= { 0 };
145 /* Thread initialization complete condition */
146 static CFRunLoopRef SysEventRunloop
= NULL
;
147 /* The runloop. Access must be protected! */
148 static CFStringRef ComputerNameKey
= NULL
,
149 /* Computer name key */
150 NetworkGlobalKey
= NULL
,
151 /* Network global key */
154 NetworkInterfaceKey
= NULL
;
155 /* Netowrk interface key */
162 static void *sysEventThreadEntry(void);
163 static void sysEventPowerNotifier(void *context
, io_service_t service
,
164 natural_t messageType
,
165 void *messageArgument
);
166 static void sysEventConfigurationNotifier(SCDynamicStoreRef store
,
167 CFArrayRef changedKeys
,
169 static void sysEventTimerNotifier(CFRunLoopTimerRef timer
, void *context
);
173 * 'cupsdStartSystemMonitor()' - Start monitoring for system change.
177 cupsdStartSystemMonitor(void)
179 int flags
; /* fcntl flags on pipe */
182 if (cupsdOpenPipe(SysEventPipes
))
184 cupsdLogMessage(CUPSD_LOG_ERROR
, "System event monitor pipe() failed - %s!",
189 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
190 "cupsdStartSystemMonitor: Adding fd %d to InputSet...",
192 FD_SET(SysEventPipes
[0], InputSet
);
195 * Set non-blocking mode on the descriptor we will be receiving notification
199 flags
= fcntl(SysEventPipes
[0], F_GETFL
, 0);
200 fcntl(SysEventPipes
[0], F_SETFL
, flags
| O_NONBLOCK
);
203 * Start the thread that runs the runloop...
206 pthread_mutex_init(&SysEventThreadMutex
, NULL
);
207 pthread_cond_init(&SysEventThreadCond
, NULL
);
208 pthread_create(&SysEventThread
, NULL
, (void *(*)())sysEventThreadEntry
, NULL
);
213 * 'cupsdStopSystemMonitor()' - Stop monitoring for system change.
217 cupsdStopSystemMonitor(void)
219 CFRunLoopRef rl
; /* The event handler runloop */
225 * Make sure the thread has completed it's initialization and
226 * stored it's runloop reference in the shared global.
229 pthread_mutex_lock(&SysEventThreadMutex
);
231 if (!SysEventRunloop
)
232 pthread_cond_wait(&SysEventThreadCond
, &SysEventThreadMutex
);
234 rl
= SysEventRunloop
;
235 SysEventRunloop
= NULL
;
237 pthread_mutex_unlock(&SysEventThreadMutex
);
242 pthread_join(SysEventThread
, NULL
);
243 pthread_mutex_destroy(&SysEventThreadMutex
);
244 pthread_cond_destroy(&SysEventThreadCond
);
247 if (SysEventPipes
[0] >= 0)
249 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
250 "cupsdStopSystemMonitor: Removing fd %d from InputSet...",
253 FD_CLR(SysEventPipes
[0], InputSet
);
255 cupsdClosePipe(SysEventPipes
);
261 * 'cupsdUpdateSystemMonitor()' - Update the current system state.
265 cupsdUpdateSystemMonitor(void)
267 cupsd_sysevent_t sysevent
; /* The system event */
268 cupsd_printer_t
*p
; /* Printer information */
272 * Drain the event pipe...
275 while (read((int)SysEventPipes
[0], &sysevent
, sizeof(sysevent
))
278 if (sysevent
.event
& SYSEVENT_CANSLEEP
)
281 * If there are any active printers cancel the sleep request...
284 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
286 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
292 cupsdLogMessage(CUPSD_LOG_INFO
,
293 "System sleep canceled because printer %s is active",
295 IOCancelPowerChange(sysevent
.powerKernelPort
,
296 sysevent
.powerNotificationID
);
300 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System wants to sleep");
301 IOAllowPowerChange(sysevent
.powerKernelPort
,
302 sysevent
.powerNotificationID
);
306 if (sysevent
.event
& SYSEVENT_WILLSLEEP
)
308 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System going to sleep");
314 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
316 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
318 if (p
->type
& CUPS_PRINTER_REMOTE
)
320 cupsdLogMessage(CUPSD_LOG_DEBUG
,
321 "Deleting remote destination \"%s\"", p
->name
);
322 cupsArraySave(Printers
);
323 cupsdDeletePrinter(p
, 0);
324 cupsArrayRestore(Printers
);
328 /* TODO: Possibly update when MDNS support is added? */
329 cupsdLogMessage(CUPSD_LOG_DEBUG
,
330 "Deregistering local printer \"%s\"", p
->name
);
331 cupsdSendBrowseDelete(p
);
335 IOAllowPowerChange(sysevent
.powerKernelPort
,
336 sysevent
.powerNotificationID
);
339 if (sysevent
.event
& SYSEVENT_WOKE
)
341 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System woke from sleep");
342 IOAllowPowerChange(sysevent
.powerKernelPort
,
343 sysevent
.powerNotificationID
);
348 if (sysevent
.event
& SYSEVENT_NETCHANGED
)
352 cupsdLogMessage(CUPSD_LOG_DEBUG
,
353 "System network configuration changed");
356 * Force an update of the list of network interfaces in 2 seconds.
359 NetIFTime
= time(NULL
) - 58;
362 * Resetting browse_time before calling cupsdSendBrowseList causes
363 * browse packets to be sent for local shared printers.
366 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
368 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
371 cupsdSendBrowseList();
374 cupsdLogMessage(CUPSD_LOG_DEBUG
,
375 "System network configuration changed; "
376 "ignored while sleeping");
379 if (sysevent
.event
& SYSEVENT_NAMECHANGED
)
383 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Computer name changed");
386 * De-register the individual printers...
389 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
391 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
392 cupsdSendBrowseDelete(p
);
395 * Now re-register them...
397 * TODO: This might need updating for MDNS.
400 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
402 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
406 cupsdLogMessage(CUPSD_LOG_DEBUG
,
407 "Computer name changed; ignored while sleeping");
414 * 'sysEventThreadEntry()' - A thread to receive power and computer name
415 * change notifications.
418 static void * /* O - Return status/value */
419 sysEventThreadEntry(void)
421 io_object_t powerNotifierObj
;
422 /* Power notifier object */
423 IONotificationPortRef powerNotifierPort
;
424 /* Power notifier port */
425 SCDynamicStoreRef store
= NULL
;/* System Config dynamic store */
426 CFRunLoopSourceRef powerRLS
= NULL
,/* Power runloop source */
427 storeRLS
= NULL
;/* System Config runloop source */
428 CFStringRef key
[3], /* System Config keys */
429 pattern
[1]; /* System Config patterns */
430 CFArrayRef keys
= NULL
, /* System Config key array*/
431 patterns
= NULL
;/* System Config pattern array */
432 SCDynamicStoreContext storeContext
; /* Dynamic store context */
433 CFRunLoopTimerContext timerContext
; /* Timer context */
434 cupsd_thread_data_t threadData
; /* Thread context data for the *
435 * runloop notifiers */
439 * Register for power state change notifications
442 bzero(&threadData
, sizeof(threadData
));
444 threadData
.sysevent
.powerKernelPort
=
445 IORegisterForSystemPower(&threadData
, &powerNotifierPort
,
446 sysEventPowerNotifier
, &powerNotifierObj
);
448 if (threadData
.sysevent
.powerKernelPort
)
450 powerRLS
= IONotificationPortGetRunLoopSource(powerNotifierPort
);
451 CFRunLoopAddSource(CFRunLoopGetCurrent(), powerRLS
, kCFRunLoopDefaultMode
);
454 DEBUG_puts("sysEventThreadEntry: error registering for system power "
458 * Register for system configuration change notifications
461 bzero(&storeContext
, sizeof(storeContext
));
462 storeContext
.info
= &threadData
;
464 store
= SCDynamicStoreCreate(NULL
, CFSTR("cupsd"),
465 sysEventConfigurationNotifier
, &storeContext
);
467 if (!ComputerNameKey
)
468 ComputerNameKey
= SCDynamicStoreKeyCreateComputerName(NULL
);
470 if (!NetworkGlobalKey
)
472 SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL
,
473 kSCDynamicStoreDomainState
,
477 HostNamesKey
= SCDynamicStoreKeyCreateHostNames(NULL
);
479 if (!NetworkInterfaceKey
)
480 NetworkInterfaceKey
=
481 SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL
,
482 kSCDynamicStoreDomainState
,
486 if (store
&& ComputerNameKey
&& NetworkGlobalKey
&& HostNamesKey
&&
489 key
[0] = ComputerNameKey
;
490 key
[1] = NetworkGlobalKey
;
491 key
[2] = HostNamesKey
;
492 pattern
[0] = NetworkInterfaceKey
;
494 keys
= CFArrayCreate(NULL
, (const void **)key
,
495 sizeof(key
) / sizeof(key
[0]),
496 &kCFTypeArrayCallBacks
);
497 patterns
= CFArrayCreate(NULL
, (const void **)pattern
,
498 sizeof(pattern
) / sizeof(pattern
[0]),
499 &kCFTypeArrayCallBacks
);
501 if (keys
&& patterns
&&
502 SCDynamicStoreSetNotificationKeys(store
, keys
, patterns
))
504 if ((storeRLS
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0))
507 CFRunLoopAddSource(CFRunLoopGetCurrent(), storeRLS
,
508 kCFRunLoopDefaultMode
);
511 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreateRunLoopSource "
512 "failed: %s\n", SCErrorString(SCError())));
515 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreSetNotificationKeys "
516 "failed: %s\n", SCErrorString(SCError())));
519 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreate failed: %s\n",
520 SCErrorString(SCError())));
529 * Set up a timer to delay the wake change notifications.
531 * The initial time is set a decade or so into the future, we'll adjust
535 bzero(&timerContext
, sizeof(timerContext
));
536 timerContext
.info
= &threadData
;
538 threadData
.timerRef
=
539 CFRunLoopTimerCreate(NULL
,
540 CFAbsoluteTimeGetCurrent() + (86400L * 365L * 10L),
541 86400L * 365L * 10L, 0, 0, sysEventTimerNotifier
,
543 CFRunLoopAddTimer(CFRunLoopGetCurrent(), threadData
.timerRef
,
544 kCFRunLoopDefaultMode
);
547 * Store our runloop in a global so the main thread can use it to stop us.
550 pthread_mutex_lock(&SysEventThreadMutex
);
552 SysEventRunloop
= CFRunLoopGetCurrent();
554 pthread_cond_signal(&SysEventThreadCond
);
555 pthread_mutex_unlock(&SysEventThreadMutex
);
558 * Disappear into the runloop until it's stopped by the main thread.
564 * Clean up before exiting.
567 if (threadData
.timerRef
)
569 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), threadData
.timerRef
,
570 kCFRunLoopDefaultMode
);
571 CFRelease(threadData
.timerRef
);
574 if (threadData
.sysevent
.powerKernelPort
)
576 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), powerRLS
,
577 kCFRunLoopDefaultMode
);
578 IODeregisterForSystemPower(&powerNotifierObj
);
579 IOServiceClose(threadData
.sysevent
.powerKernelPort
);
580 IONotificationPortDestroy(powerNotifierPort
);
585 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), storeRLS
,
586 kCFRunLoopDefaultMode
);
587 CFRunLoopSourceInvalidate(storeRLS
);
599 * 'sysEventPowerNotifier()' - Handle power notification events.
603 sysEventPowerNotifier(
604 void *context
, /* I - Thread context data */
605 io_service_t service
, /* I - Unused service info */
606 natural_t messageType
, /* I - Type of message */
607 void *messageArgument
) /* I - Message data */
609 int sendit
= 1; /* Send event to main thread? *
610 * (0 = no, 1 = yes, 2 = delayed */
611 cupsd_thread_data_t
*threadData
; /* Thread context data */
614 threadData
= (cupsd_thread_data_t
*)context
;
616 (void)service
; /* anti-compiler-warning-code */
620 case kIOMessageCanSystemPowerOff
:
621 case kIOMessageCanSystemSleep
:
622 threadData
->sysevent
.event
|= SYSEVENT_CANSLEEP
;
625 case kIOMessageSystemWillRestart
:
626 case kIOMessageSystemWillPowerOff
:
627 case kIOMessageSystemWillSleep
:
628 threadData
->sysevent
.event
|= SYSEVENT_WILLSLEEP
;
631 case kIOMessageSystemHasPoweredOn
:
633 * Because powered on is followed by a net-changed event, delay
638 threadData
->sysevent
.event
|= SYSEVENT_WOKE
;
641 case kIOMessageSystemWillNotPowerOff
:
642 case kIOMessageSystemWillNotSleep
:
643 #ifdef kIOMessageSystemWillPowerOn
644 case kIOMessageSystemWillPowerOn
:
645 #endif /* kIOMessageSystemWillPowerOn */
652 IOAllowPowerChange(threadData
->sysevent
.powerKernelPort
,
653 (long)messageArgument
);
656 threadData
->sysevent
.powerNotificationID
= (long)messageArgument
;
661 * Send the event to the main thread now.
664 write(SysEventPipes
[1], &threadData
->sysevent
,
665 sizeof(threadData
->sysevent
));
666 threadData
->sysevent
.event
= 0;
671 * Send the event to the main thread after 1 to 2 seconds.
674 CFRunLoopTimerSetNextFireDate(threadData
->timerRef
,
675 CFAbsoluteTimeGetCurrent() + 2);
682 * 'sysEventConfigurationNotifier()' - Computer name changed notification
687 sysEventConfigurationNotifier(
688 SCDynamicStoreRef store
, /* I - System data (unused) */
689 CFArrayRef changedKeys
, /* I - Changed data */
690 void *context
) /* I - Thread context data */
692 cupsd_thread_data_t
*threadData
; /* Thread context data */
695 threadData
= (cupsd_thread_data_t
*)context
;
697 (void)store
; /* anti-compiler-warning-code */
699 CFRange range
= CFRangeMake(0, CFArrayGetCount(changedKeys
));
701 if (CFArrayContainsValue(changedKeys
, range
, ComputerNameKey
))
702 threadData
->sysevent
.event
|= SYSEVENT_NAMECHANGED
;
704 if (CFArrayContainsValue(changedKeys
, range
, NetworkGlobalKey
) ||
705 CFArrayContainsValue(changedKeys
, range
, HostNamesKey
) ||
706 CFArrayContainsValue(changedKeys
, range
, NetworkInterfaceKey
))
707 threadData
->sysevent
.event
|= SYSEVENT_NETCHANGED
;
710 * Because we registered for several different kinds of change notifications
711 * this callback usually gets called several times in a row. We use a timer to
712 * de-bounce these so we only end up generating one event for the main thread.
715 CFRunLoopTimerSetNextFireDate(threadData
->timerRef
,
716 CFAbsoluteTimeGetCurrent() + 2);
721 * 'sysEventTimerNotifier()' - Handle delayed event notifications.
725 sysEventTimerNotifier(
726 CFRunLoopTimerRef timer
, /* I - Timer information */
727 void *context
) /* I - Thread context data */
729 cupsd_thread_data_t
*threadData
; /* Thread context data */
732 threadData
= (cupsd_thread_data_t
*)context
;
735 * If an event is still pending send it to the main thread.
738 if (threadData
->sysevent
.event
)
740 write(SysEventPipes
[1], &threadData
->sysevent
,
741 sizeof(threadData
->sysevent
));
742 threadData
->sysevent
.event
= 0;
745 #endif /* __APPLE__ */
749 * End of "$Id: sysman.c 5049 2006-02-02 14:50:57Z mike $".