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 * This is the Apple-specific system event code. It works by creating
58 * a worker thread that waits for events from the OS and relays them
59 * to the main thread via a traditional pipe.
63 * Include MacOS-specific headers...
66 # include <IOKit/IOKitLib.h>
67 # include <IOKit/IOMessage.h>
68 # include <IOKit/pwr_mgt/IOPMLib.h>
69 # include <SystemConfiguration/SystemConfiguration.h>
77 # define SYSEVENT_CANSLEEP 0x1 /* Decide whether to allow sleep or not */
78 # define SYSEVENT_WILLSLEEP 0x2 /* Computer will go to sleep */
79 # define SYSEVENT_WOKE 0x4 /* Computer woke from sleep */
80 # define SYSEVENT_NETCHANGED 0x8 /* Network changed */
81 # define SYSEVENT_NAMECHANGED 0x10 /* Computer name changed */
88 typedef struct cupsd_sysevent_s
/*** System event data ****/
90 unsigned char event
; /* Event bit field */
91 io_connect_t powerKernelPort
; /* Power context data */
92 long powerNotificationID
; /* Power event data */
96 typedef struct cupsd_thread_data_s
/*** Thread context data ****/
98 cupsd_sysevent_t sysevent
; /* System event */
99 CFRunLoopTimerRef timerRef
; /* Timer to delay some change *
101 } cupsd_thread_data_t
;
108 static pthread_t SysEventThread
= NULL
;
109 /* Thread to host a runloop */
110 static pthread_mutex_t SysEventThreadMutex
= { 0 };
111 /* Coordinates access to shared gloabals */
112 static pthread_cond_t SysEventThreadCond
= { 0 };
113 /* Thread initialization complete condition */
114 static CFRunLoopRef SysEventRunloop
= NULL
;
115 /* The runloop. Access must be protected! */
116 static CFStringRef ComputerNameKey
= NULL
,
117 /* Computer name key */
118 NetworkGlobalKey
= NULL
,
119 /* Network global key */
122 NetworkInterfaceKey
= NULL
;
123 /* Netowrk interface key */
130 static void *sysEventThreadEntry(void);
131 static void sysEventPowerNotifier(void *context
, io_service_t service
,
132 natural_t messageType
,
133 void *messageArgument
);
134 static void sysEventConfigurationNotifier(SCDynamicStoreRef store
,
135 CFArrayRef changedKeys
,
137 static void sysEventTimerNotifier(CFRunLoopTimerRef timer
, void *context
);
141 * 'cupsdStartSystemMonitor()' - Start monitoring for system change.
145 cupsdStartSystemMonitor(void)
147 int flags
; /* fcntl flags on pipe */
150 if (cupsdOpenPipe(SysEventPipes
))
152 cupsdLogMessage(CUPSD_LOG_ERROR
, "System event monitor pipe() failed - %s!",
157 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
158 "cupsdStartSystemMonitor: Adding fd %d to InputSet...",
160 FD_SET(SysEventPipes
[0], InputSet
);
163 * Set non-blocking mode on the descriptor we will be receiving notification
167 flags
= fcntl(SysEventPipes
[0], F_GETFL
, 0);
168 fcntl(SysEventPipes
[0], F_SETFL
, flags
| O_NONBLOCK
);
171 * Start the thread that runs the runloop...
174 pthread_mutex_init(&SysEventThreadMutex
, NULL
);
175 pthread_cond_init(&SysEventThreadCond
, NULL
);
176 pthread_create(&SysEventThread
, NULL
, (void *(*)())sysEventThreadEntry
, NULL
);
181 * 'cupsdStopSystemMonitor()' - Stop monitoring for system change.
185 cupsdStopSystemMonitor(void)
187 CFRunLoopRef rl
; /* The event handler runloop */
193 * Make sure the thread has completed it's initialization and
194 * stored it's runloop reference in the shared global.
197 pthread_mutex_lock(&SysEventThreadMutex
);
199 if (!SysEventRunloop
)
200 pthread_cond_wait(&SysEventThreadCond
, &SysEventThreadMutex
);
202 rl
= SysEventRunloop
;
203 SysEventRunloop
= NULL
;
205 pthread_mutex_unlock(&SysEventThreadMutex
);
210 pthread_join(SysEventThread
, NULL
);
211 pthread_mutex_destroy(&SysEventThreadMutex
);
212 pthread_cond_destroy(&SysEventThreadCond
);
215 if (SysEventPipes
[0] >= 0)
217 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
218 "cupsdStopSystemMonitor: Removing fd %d from InputSet...",
221 FD_CLR(SysEventPipes
[0], InputSet
);
223 cupsdClosePipe(SysEventPipes
);
229 * 'cupsdUpdateSystemMonitor()' - Update the current system state.
233 cupsdUpdateSystemMonitor(void)
235 int i
; /* Looping var */
236 cupsd_sysevent_t sysevent
; /* The system event */
237 cupsd_printer_t
*p
; /* Printer information */
241 * Drain the event pipe...
244 while (read((int)SysEventPipes
[0], &sysevent
, sizeof(sysevent
))
247 if (sysevent
.event
& SYSEVENT_CANSLEEP
)
250 * If there are active printers that don't have the connecting-to-device
251 * printer-state-reason then cancel the sleep request (i.e. this reason
252 * indicates a job that is not yet connected to the printer)...
255 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
257 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
261 for (i
= 0; i
< p
->num_reasons
; i
++)
262 if (!strcmp(p
->reasons
[i
], "connecting-to-device"))
265 if (!p
->num_reasons
|| i
>= p
->num_reasons
)
272 cupsdLogMessage(CUPSD_LOG_INFO
,
273 "System sleep canceled because printer %s is active",
275 IOCancelPowerChange(sysevent
.powerKernelPort
,
276 sysevent
.powerNotificationID
);
280 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System wants to sleep");
281 IOAllowPowerChange(sysevent
.powerKernelPort
,
282 sysevent
.powerNotificationID
);
286 if (sysevent
.event
& SYSEVENT_WILLSLEEP
)
288 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System going to sleep");
295 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
297 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
299 if (p
->type
& CUPS_PRINTER_REMOTE
)
301 cupsdLogMessage(CUPSD_LOG_DEBUG
,
302 "Deleting remote destination \"%s\"", p
->name
);
303 cupsArraySave(Printers
);
304 cupsdDeletePrinter(p
, 0);
305 cupsArrayRestore(Printers
);
309 /* TODO: Possibly update when MDNS support is added? */
310 cupsdLogMessage(CUPSD_LOG_DEBUG
,
311 "Deregistering local printer \"%s\"", p
->name
);
312 cupsdSendBrowseDelete(p
);
316 IOAllowPowerChange(sysevent
.powerKernelPort
,
317 sysevent
.powerNotificationID
);
320 if (sysevent
.event
& SYSEVENT_WOKE
)
322 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System woke from sleep");
323 IOAllowPowerChange(sysevent
.powerKernelPort
,
324 sysevent
.powerNotificationID
);
329 if (sysevent
.event
& SYSEVENT_NETCHANGED
)
333 cupsdLogMessage(CUPSD_LOG_DEBUG
,
334 "System network configuration changed");
337 * Force an update of the list of network interfaces in 2 seconds.
340 NetIFTime
= time(NULL
) - 58;
343 * Resetting browse_time before calling cupsdSendBrowseList causes
344 * browse packets to be sent for local shared printers.
347 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
349 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
352 cupsdSendBrowseList();
355 cupsdLogMessage(CUPSD_LOG_DEBUG
,
356 "System network configuration changed; "
357 "ignored while sleeping");
360 if (sysevent
.event
& SYSEVENT_NAMECHANGED
)
364 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Computer name changed");
367 * De-register the individual printers...
370 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
372 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
373 cupsdSendBrowseDelete(p
);
376 * Now re-register them...
378 * TODO: This might need updating for MDNS.
381 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
383 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
387 cupsdLogMessage(CUPSD_LOG_DEBUG
,
388 "Computer name changed; ignored while sleeping");
395 * 'sysEventThreadEntry()' - A thread to receive power and computer name
396 * change notifications.
399 static void * /* O - Return status/value */
400 sysEventThreadEntry(void)
402 io_object_t powerNotifierObj
;
403 /* Power notifier object */
404 IONotificationPortRef powerNotifierPort
;
405 /* Power notifier port */
406 SCDynamicStoreRef store
= NULL
;/* System Config dynamic store */
407 CFRunLoopSourceRef powerRLS
= NULL
,/* Power runloop source */
408 storeRLS
= NULL
;/* System Config runloop source */
409 CFStringRef key
[3], /* System Config keys */
410 pattern
[1]; /* System Config patterns */
411 CFArrayRef keys
= NULL
, /* System Config key array*/
412 patterns
= NULL
;/* System Config pattern array */
413 SCDynamicStoreContext storeContext
; /* Dynamic store context */
414 CFRunLoopTimerContext timerContext
; /* Timer context */
415 cupsd_thread_data_t threadData
; /* Thread context data for the *
416 * runloop notifiers */
420 * Register for power state change notifications
423 bzero(&threadData
, sizeof(threadData
));
425 threadData
.sysevent
.powerKernelPort
=
426 IORegisterForSystemPower(&threadData
, &powerNotifierPort
,
427 sysEventPowerNotifier
, &powerNotifierObj
);
429 if (threadData
.sysevent
.powerKernelPort
)
431 powerRLS
= IONotificationPortGetRunLoopSource(powerNotifierPort
);
432 CFRunLoopAddSource(CFRunLoopGetCurrent(), powerRLS
, kCFRunLoopDefaultMode
);
435 DEBUG_puts("sysEventThreadEntry: error registering for system power "
439 * Register for system configuration change notifications
442 bzero(&storeContext
, sizeof(storeContext
));
443 storeContext
.info
= &threadData
;
445 store
= SCDynamicStoreCreate(NULL
, CFSTR("cupsd"),
446 sysEventConfigurationNotifier
, &storeContext
);
448 if (!ComputerNameKey
)
449 ComputerNameKey
= SCDynamicStoreKeyCreateComputerName(NULL
);
451 if (!NetworkGlobalKey
)
453 SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL
,
454 kSCDynamicStoreDomainState
,
458 HostNamesKey
= SCDynamicStoreKeyCreateHostNames(NULL
);
460 if (!NetworkInterfaceKey
)
461 NetworkInterfaceKey
=
462 SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL
,
463 kSCDynamicStoreDomainState
,
467 if (store
&& ComputerNameKey
&& NetworkGlobalKey
&& HostNamesKey
&&
470 key
[0] = ComputerNameKey
;
471 key
[1] = NetworkGlobalKey
;
472 key
[2] = HostNamesKey
;
473 pattern
[0] = NetworkInterfaceKey
;
475 keys
= CFArrayCreate(NULL
, (const void **)key
,
476 sizeof(key
) / sizeof(key
[0]),
477 &kCFTypeArrayCallBacks
);
478 patterns
= CFArrayCreate(NULL
, (const void **)pattern
,
479 sizeof(pattern
) / sizeof(pattern
[0]),
480 &kCFTypeArrayCallBacks
);
482 if (keys
&& patterns
&&
483 SCDynamicStoreSetNotificationKeys(store
, keys
, patterns
))
485 if ((storeRLS
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0))
488 CFRunLoopAddSource(CFRunLoopGetCurrent(), storeRLS
,
489 kCFRunLoopDefaultMode
);
492 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreateRunLoopSource "
493 "failed: %s\n", SCErrorString(SCError())));
496 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreSetNotificationKeys "
497 "failed: %s\n", SCErrorString(SCError())));
500 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreate failed: %s\n",
501 SCErrorString(SCError())));
510 * Set up a timer to delay the wake change notifications.
512 * The initial time is set a decade or so into the future, we'll adjust
516 bzero(&timerContext
, sizeof(timerContext
));
517 timerContext
.info
= &threadData
;
519 threadData
.timerRef
=
520 CFRunLoopTimerCreate(NULL
,
521 CFAbsoluteTimeGetCurrent() + (86400L * 365L * 10L),
522 86400L * 365L * 10L, 0, 0, sysEventTimerNotifier
,
524 CFRunLoopAddTimer(CFRunLoopGetCurrent(), threadData
.timerRef
,
525 kCFRunLoopDefaultMode
);
528 * Store our runloop in a global so the main thread can use it to stop us.
531 pthread_mutex_lock(&SysEventThreadMutex
);
533 SysEventRunloop
= CFRunLoopGetCurrent();
535 pthread_cond_signal(&SysEventThreadCond
);
536 pthread_mutex_unlock(&SysEventThreadMutex
);
539 * Disappear into the runloop until it's stopped by the main thread.
545 * Clean up before exiting.
548 if (threadData
.timerRef
)
550 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), threadData
.timerRef
,
551 kCFRunLoopDefaultMode
);
552 CFRelease(threadData
.timerRef
);
555 if (threadData
.sysevent
.powerKernelPort
)
557 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), powerRLS
,
558 kCFRunLoopDefaultMode
);
559 IODeregisterForSystemPower(&powerNotifierObj
);
560 IOServiceClose(threadData
.sysevent
.powerKernelPort
);
561 IONotificationPortDestroy(powerNotifierPort
);
566 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), storeRLS
,
567 kCFRunLoopDefaultMode
);
568 CFRunLoopSourceInvalidate(storeRLS
);
580 * 'sysEventPowerNotifier()' - Handle power notification events.
584 sysEventPowerNotifier(
585 void *context
, /* I - Thread context data */
586 io_service_t service
, /* I - Unused service info */
587 natural_t messageType
, /* I - Type of message */
588 void *messageArgument
) /* I - Message data */
590 int sendit
= 1; /* Send event to main thread? *
591 * (0 = no, 1 = yes, 2 = delayed */
592 cupsd_thread_data_t
*threadData
; /* Thread context data */
595 threadData
= (cupsd_thread_data_t
*)context
;
597 (void)service
; /* anti-compiler-warning-code */
601 case kIOMessageCanSystemPowerOff
:
602 case kIOMessageCanSystemSleep
:
603 threadData
->sysevent
.event
|= SYSEVENT_CANSLEEP
;
606 case kIOMessageSystemWillRestart
:
607 case kIOMessageSystemWillPowerOff
:
608 case kIOMessageSystemWillSleep
:
609 threadData
->sysevent
.event
|= SYSEVENT_WILLSLEEP
;
612 case kIOMessageSystemHasPoweredOn
:
614 * Because powered on is followed by a net-changed event, delay
619 threadData
->sysevent
.event
|= SYSEVENT_WOKE
;
622 case kIOMessageSystemWillNotPowerOff
:
623 case kIOMessageSystemWillNotSleep
:
624 #ifdef kIOMessageSystemWillPowerOn
625 case kIOMessageSystemWillPowerOn
:
626 #endif /* kIOMessageSystemWillPowerOn */
633 IOAllowPowerChange(threadData
->sysevent
.powerKernelPort
,
634 (long)messageArgument
);
637 threadData
->sysevent
.powerNotificationID
= (long)messageArgument
;
642 * Send the event to the main thread now.
645 write(SysEventPipes
[1], &threadData
->sysevent
,
646 sizeof(threadData
->sysevent
));
647 threadData
->sysevent
.event
= 0;
652 * Send the event to the main thread after 1 to 2 seconds.
655 CFRunLoopTimerSetNextFireDate(threadData
->timerRef
,
656 CFAbsoluteTimeGetCurrent() + 2);
663 * 'sysEventConfigurationNotifier()' - Computer name changed notification
668 sysEventConfigurationNotifier(
669 SCDynamicStoreRef store
, /* I - System data (unused) */
670 CFArrayRef changedKeys
, /* I - Changed data */
671 void *context
) /* I - Thread context data */
673 cupsd_thread_data_t
*threadData
; /* Thread context data */
676 threadData
= (cupsd_thread_data_t
*)context
;
678 (void)store
; /* anti-compiler-warning-code */
680 CFRange range
= CFRangeMake(0, CFArrayGetCount(changedKeys
));
682 if (CFArrayContainsValue(changedKeys
, range
, ComputerNameKey
))
683 threadData
->sysevent
.event
|= SYSEVENT_NAMECHANGED
;
685 if (CFArrayContainsValue(changedKeys
, range
, NetworkGlobalKey
) ||
686 CFArrayContainsValue(changedKeys
, range
, HostNamesKey
) ||
687 CFArrayContainsValue(changedKeys
, range
, NetworkInterfaceKey
))
688 threadData
->sysevent
.event
|= SYSEVENT_NETCHANGED
;
691 * Because we registered for several different kinds of change notifications
692 * this callback usually gets called several times in a row. We use a timer to
693 * de-bounce these so we only end up generating one event for the main thread.
696 CFRunLoopTimerSetNextFireDate(threadData
->timerRef
,
697 CFAbsoluteTimeGetCurrent() + 2);
702 * 'sysEventTimerNotifier()' - Handle delayed event notifications.
706 sysEventTimerNotifier(
707 CFRunLoopTimerRef timer
, /* I - Timer information */
708 void *context
) /* I - Thread context data */
710 cupsd_thread_data_t
*threadData
; /* Thread context data */
713 threadData
= (cupsd_thread_data_t
*)context
;
716 * If an event is still pending send it to the main thread.
719 if (threadData
->sysevent
.event
)
721 write(SysEventPipes
[1], &threadData
->sysevent
,
722 sizeof(threadData
->sysevent
));
723 threadData
->sysevent
.event
= 0;
726 #endif /* __APPLE__ */