2 * "$Id: sysman.c 6649 2007-07-11 21:46:42Z mike $"
4 * System management definitions for the Common UNIX Printing System (CUPS).
6 * Copyright 2007-2008 by Apple Inc.
7 * Copyright 2006 by Easy Software Products.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
17 * cupsdCleanDirty() - Write dirty config and state files.
18 * cupsdMarkDirty() - Mark config or state files as needing a
20 * cupsdSetBusyState() - Let the system know when we are busy
22 * cupsdStartSystemMonitor() - Start monitoring for system change.
23 * cupsdStopSystemMonitor() - Stop monitoring for system change.
24 * cupsdUpdateSystemMonitor() - Update the current system state.
25 * sysEventThreadEntry() - A thread to receive power and computer
26 * name change notifications.
27 * sysEventPowerNotifier() - Handle power notification events.
28 * sysEventConfigurationNotifier() - Computer name changed notification
30 * sysEventTimerNotifier() - Handle delayed event notifications.
35 * Include necessary headers...
42 * The system management functions cover disk and power management which
43 * are primarily used on portable computers.
45 * Disk management involves delaying the write of certain configuration
46 * and state files to minimize the number of times the disk has to spin
49 * Power management support is currently only implemented on MacOS X, but
50 * essentially we use four functions to let the OS know when it is OK to
51 * put the system to idle sleep, typically when we are not in the middle of
54 * Once put to sleep, we invalidate all remote printers since it is common
55 * to wake up in a new location/on a new wireless network.
60 * 'cupsdCleanDirty()' - Write dirty config and state files.
66 if (DirtyFiles
& CUPSD_DIRTY_PRINTERS
)
67 cupsdSaveAllPrinters();
69 if (DirtyFiles
& CUPSD_DIRTY_CLASSES
)
70 cupsdSaveAllClasses();
72 if (DirtyFiles
& CUPSD_DIRTY_REMOTE
)
73 cupsdSaveRemoteCache();
75 if (DirtyFiles
& CUPSD_DIRTY_PRINTCAP
)
78 if (DirtyFiles
& CUPSD_DIRTY_JOBS
)
80 cupsd_job_t
*job
; /* Current job */
84 for (job
= (cupsd_job_t
*)cupsArrayFirst(Jobs
);
86 job
= (cupsd_job_t
*)cupsArrayNext(Jobs
))
91 if (DirtyFiles
& CUPSD_DIRTY_SUBSCRIPTIONS
)
92 cupsdSaveAllSubscriptions();
94 DirtyFiles
= CUPSD_DIRTY_NONE
;
100 * 'cupsdMarkDirty()' - Mark config or state files as needing a write.
104 cupsdMarkDirty(int what
) /* I - What file(s) are dirty? */
109 DirtyCleanTime
= time(NULL
) + DirtyCleanInterval
;
116 * 'cupsdSetBusyState()' - Let the system know when we are busy doing something.
120 cupsdSetBusyState(void)
122 int newbusy
; /* New busy state */
123 static int busy
= 0; /* Current busy state */
126 newbusy
= DirtyCleanTime
||
127 cupsArrayCount(PrintingJobs
) ||
128 cupsArrayCount(ActiveClients
);
135 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
136 "cupsdSetBusyState: Server no longer busy...");
138 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
139 "cupsdSetBusyState: Server is now busy...");
146 * This is the Apple-specific system event code. It works by creating
147 * a worker thread that waits for events from the OS and relays them
148 * to the main thread via a traditional pipe.
152 * Include MacOS-specific headers...
155 # include <IOKit/IOKitLib.h>
156 # include <IOKit/IOMessage.h>
157 # include <IOKit/pwr_mgt/IOPMLib.h>
158 # include <SystemConfiguration/SystemConfiguration.h>
159 # include <pthread.h>
166 # define SYSEVENT_CANSLEEP 0x1 /* Decide whether to allow sleep or not */
167 # define SYSEVENT_WILLSLEEP 0x2 /* Computer will go to sleep */
168 # define SYSEVENT_WOKE 0x4 /* Computer woke from sleep */
169 # define SYSEVENT_NETCHANGED 0x8 /* Network changed */
170 # define SYSEVENT_NAMECHANGED 0x10 /* Computer name changed */
177 typedef struct cupsd_sysevent_s
/*** System event data ****/
179 unsigned char event
; /* Event bit field */
180 io_connect_t powerKernelPort
; /* Power context data */
181 long powerNotificationID
; /* Power event data */
185 typedef struct cupsd_thread_data_s
/*** Thread context data ****/
187 cupsd_sysevent_t sysevent
; /* System event */
188 CFRunLoopTimerRef timerRef
; /* Timer to delay some change *
190 } cupsd_thread_data_t
;
197 static pthread_t SysEventThread
= NULL
;
198 /* Thread to host a runloop */
199 static pthread_mutex_t SysEventThreadMutex
= { 0 };
200 /* Coordinates access to shared gloabals */
201 static pthread_cond_t SysEventThreadCond
= { 0 };
202 /* Thread initialization complete condition */
203 static CFRunLoopRef SysEventRunloop
= NULL
;
204 /* The runloop. Access must be protected! */
205 static CFStringRef ComputerNameKey
= NULL
,
206 /* Computer name key */
207 NetworkGlobalKeyIPv4
= NULL
,
208 /* Network global IPv4 key */
209 NetworkGlobalKeyIPv6
= NULL
,
210 /* Network global IPv6 key */
211 NetworkGlobalKeyDNS
= NULL
,
212 /* Network global DNS key */
215 NetworkInterfaceKeyIPv4
= NULL
,
216 /* Netowrk interface key */
217 NetworkInterfaceKeyIPv6
= NULL
;
218 /* Netowrk interface key */
225 static void *sysEventThreadEntry(void);
226 static void sysEventPowerNotifier(void *context
, io_service_t service
,
227 natural_t messageType
,
228 void *messageArgument
);
229 static void sysEventConfigurationNotifier(SCDynamicStoreRef store
,
230 CFArrayRef changedKeys
,
232 static void sysEventTimerNotifier(CFRunLoopTimerRef timer
, void *context
);
236 * 'cupsdStartSystemMonitor()' - Start monitoring for system change.
240 cupsdStartSystemMonitor(void)
242 int flags
; /* fcntl flags on pipe */
245 if (cupsdOpenPipe(SysEventPipes
))
247 cupsdLogMessage(CUPSD_LOG_ERROR
, "System event monitor pipe() failed - %s!",
252 cupsdAddSelect(SysEventPipes
[0], (cupsd_selfunc_t
)cupsdUpdateSystemMonitor
,
256 * Set non-blocking mode on the descriptor we will be receiving notification
260 flags
= fcntl(SysEventPipes
[0], F_GETFL
, 0);
261 fcntl(SysEventPipes
[0], F_SETFL
, flags
| O_NONBLOCK
);
264 * Start the thread that runs the runloop...
267 pthread_mutex_init(&SysEventThreadMutex
, NULL
);
268 pthread_cond_init(&SysEventThreadCond
, NULL
);
269 pthread_create(&SysEventThread
, NULL
, (void *(*)())sysEventThreadEntry
, NULL
);
274 * 'cupsdStopSystemMonitor()' - Stop monitoring for system change.
278 cupsdStopSystemMonitor(void)
280 CFRunLoopRef rl
; /* The event handler runloop */
286 * Make sure the thread has completed it's initialization and
287 * stored it's runloop reference in the shared global.
290 pthread_mutex_lock(&SysEventThreadMutex
);
292 if (!SysEventRunloop
)
293 pthread_cond_wait(&SysEventThreadCond
, &SysEventThreadMutex
);
295 rl
= SysEventRunloop
;
296 SysEventRunloop
= NULL
;
298 pthread_mutex_unlock(&SysEventThreadMutex
);
303 pthread_join(SysEventThread
, NULL
);
304 pthread_mutex_destroy(&SysEventThreadMutex
);
305 pthread_cond_destroy(&SysEventThreadCond
);
308 if (SysEventPipes
[0] >= 0)
310 cupsdRemoveSelect(SysEventPipes
[0]);
311 cupsdClosePipe(SysEventPipes
);
317 * 'cupsdUpdateSystemMonitor()' - Update the current system state.
321 cupsdUpdateSystemMonitor(void)
323 int i
; /* Looping var */
324 cupsd_sysevent_t sysevent
; /* The system event */
325 cupsd_printer_t
*p
; /* Printer information */
329 * Drain the event pipe...
332 while (read((int)SysEventPipes
[0], &sysevent
, sizeof(sysevent
))
335 if (sysevent
.event
& SYSEVENT_CANSLEEP
)
338 * If there are active printers that don't have the connecting-to-device
339 * printer-state-reason then cancel the sleep request (i.e. this reason
340 * indicates a job that is not yet connected to the printer)...
343 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
345 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
349 for (i
= 0; i
< p
->num_reasons
; i
++)
350 if (!strcmp(p
->reasons
[i
], "connecting-to-device"))
353 if (!p
->num_reasons
|| i
>= p
->num_reasons
)
360 cupsdLogMessage(CUPSD_LOG_INFO
,
361 "System sleep canceled because printer %s is active",
363 IOCancelPowerChange(sysevent
.powerKernelPort
,
364 sysevent
.powerNotificationID
);
368 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System wants to sleep");
369 IOAllowPowerChange(sysevent
.powerKernelPort
,
370 sysevent
.powerNotificationID
);
374 if (sysevent
.event
& SYSEVENT_WILLSLEEP
)
376 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System going to sleep");
382 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
384 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
386 if (p
->type
& CUPS_PRINTER_DISCOVERED
)
388 cupsdLogMessage(CUPSD_LOG_DEBUG
,
389 "Deleting remote destination \"%s\"", p
->name
);
390 cupsArraySave(Printers
);
391 cupsdDeletePrinter(p
, 0);
392 cupsArrayRestore(Printers
);
396 cupsdLogMessage(CUPSD_LOG_DEBUG
,
397 "Deregistering local printer \"%s\"", p
->name
);
398 cupsdDeregisterPrinter(p
, 0);
404 IOAllowPowerChange(sysevent
.powerKernelPort
,
405 sysevent
.powerNotificationID
);
408 if (sysevent
.event
& SYSEVENT_WOKE
)
410 cupsdLogMessage(CUPSD_LOG_DEBUG
, "System woke from sleep");
411 IOAllowPowerChange(sysevent
.powerKernelPort
,
412 sysevent
.powerNotificationID
);
417 if (sysevent
.event
& SYSEVENT_NETCHANGED
)
421 cupsdLogMessage(CUPSD_LOG_DEBUG
,
422 "System network configuration changed");
425 * Resetting browse_time before calling cupsdSendBrowseList causes
426 * browse packets to be sent for local shared printers.
429 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
431 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
434 cupsdSendBrowseList();
435 cupsdRestartPolling();
438 cupsdLogMessage(CUPSD_LOG_DEBUG
,
439 "System network configuration changed; "
440 "ignored while sleeping");
443 if (sysevent
.event
& SYSEVENT_NAMECHANGED
)
447 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Computer name changed");
450 * De-register the individual printers...
453 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
455 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
456 cupsdDeregisterPrinter(p
, 1);
459 * Update the computer name...
462 cupsdUpdateDNSSDName();
465 * Now re-register them...
468 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
470 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
473 cupsdRegisterPrinter(p
);
477 cupsdLogMessage(CUPSD_LOG_DEBUG
,
478 "Computer name changed; ignored while sleeping");
485 * 'sysEventThreadEntry()' - A thread to receive power and computer name
486 * change notifications.
489 static void * /* O - Return status/value */
490 sysEventThreadEntry(void)
492 io_object_t powerNotifierObj
;
493 /* Power notifier object */
494 IONotificationPortRef powerNotifierPort
;
495 /* Power notifier port */
496 SCDynamicStoreRef store
= NULL
;/* System Config dynamic store */
497 CFRunLoopSourceRef powerRLS
= NULL
,/* Power runloop source */
498 storeRLS
= NULL
;/* System Config runloop source */
499 CFStringRef key
[5], /* System Config keys */
500 pattern
[2]; /* System Config patterns */
501 CFArrayRef keys
= NULL
, /* System Config key array*/
502 patterns
= NULL
;/* System Config pattern array */
503 SCDynamicStoreContext storeContext
; /* Dynamic store context */
504 CFRunLoopTimerContext timerContext
; /* Timer context */
505 cupsd_thread_data_t threadData
; /* Thread context data for the *
506 * runloop notifiers */
510 * Register for power state change notifications
513 bzero(&threadData
, sizeof(threadData
));
515 threadData
.sysevent
.powerKernelPort
=
516 IORegisterForSystemPower(&threadData
, &powerNotifierPort
,
517 sysEventPowerNotifier
, &powerNotifierObj
);
519 if (threadData
.sysevent
.powerKernelPort
)
521 powerRLS
= IONotificationPortGetRunLoopSource(powerNotifierPort
);
522 CFRunLoopAddSource(CFRunLoopGetCurrent(), powerRLS
, kCFRunLoopDefaultMode
);
525 DEBUG_puts("sysEventThreadEntry: error registering for system power "
529 * Register for system configuration change notifications
532 bzero(&storeContext
, sizeof(storeContext
));
533 storeContext
.info
= &threadData
;
535 store
= SCDynamicStoreCreate(NULL
, CFSTR("cupsd"),
536 sysEventConfigurationNotifier
, &storeContext
);
538 if (!ComputerNameKey
)
539 ComputerNameKey
= SCDynamicStoreKeyCreateComputerName(NULL
);
541 if (!NetworkGlobalKeyIPv4
)
542 NetworkGlobalKeyIPv4
=
543 SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL
,
544 kSCDynamicStoreDomainState
,
547 if (!NetworkGlobalKeyIPv6
)
548 NetworkGlobalKeyIPv6
=
549 SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL
,
550 kSCDynamicStoreDomainState
,
553 if (!NetworkGlobalKeyDNS
)
554 NetworkGlobalKeyDNS
=
555 SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL
,
556 kSCDynamicStoreDomainState
,
560 HostNamesKey
= SCDynamicStoreKeyCreateHostNames(NULL
);
562 if (!NetworkInterfaceKeyIPv4
)
563 NetworkInterfaceKeyIPv4
=
564 SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL
,
565 kSCDynamicStoreDomainState
,
569 if (!NetworkInterfaceKeyIPv6
)
570 NetworkInterfaceKeyIPv6
=
571 SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL
,
572 kSCDynamicStoreDomainState
,
576 if (store
&& ComputerNameKey
&& HostNamesKey
&&
577 NetworkGlobalKeyIPv4
&& NetworkGlobalKeyIPv6
&& NetworkGlobalKeyDNS
&&
578 NetworkInterfaceKeyIPv4
&& NetworkInterfaceKeyIPv6
)
580 key
[0] = ComputerNameKey
;
581 key
[1] = NetworkGlobalKeyIPv4
;
582 key
[2] = NetworkGlobalKeyIPv6
;
583 key
[3] = NetworkGlobalKeyDNS
;
584 key
[4] = HostNamesKey
;
586 pattern
[0] = NetworkInterfaceKeyIPv4
;
587 pattern
[1] = NetworkInterfaceKeyIPv6
;
589 keys
= CFArrayCreate(NULL
, (const void **)key
,
590 sizeof(key
) / sizeof(key
[0]),
591 &kCFTypeArrayCallBacks
);
593 patterns
= CFArrayCreate(NULL
, (const void **)pattern
,
594 sizeof(pattern
) / sizeof(pattern
[0]),
595 &kCFTypeArrayCallBacks
);
597 if (keys
&& patterns
&&
598 SCDynamicStoreSetNotificationKeys(store
, keys
, patterns
))
600 if ((storeRLS
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0))
603 CFRunLoopAddSource(CFRunLoopGetCurrent(), storeRLS
,
604 kCFRunLoopDefaultMode
);
607 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreateRunLoopSource "
608 "failed: %s\n", SCErrorString(SCError())));
611 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreSetNotificationKeys "
612 "failed: %s\n", SCErrorString(SCError())));
615 DEBUG_printf(("sysEventThreadEntry: SCDynamicStoreCreate failed: %s\n",
616 SCErrorString(SCError())));
625 * Set up a timer to delay the wake change notifications.
627 * The initial time is set a decade or so into the future, we'll adjust
631 bzero(&timerContext
, sizeof(timerContext
));
632 timerContext
.info
= &threadData
;
634 threadData
.timerRef
=
635 CFRunLoopTimerCreate(NULL
,
636 CFAbsoluteTimeGetCurrent() + (86400L * 365L * 10L),
637 86400L * 365L * 10L, 0, 0, sysEventTimerNotifier
,
639 CFRunLoopAddTimer(CFRunLoopGetCurrent(), threadData
.timerRef
,
640 kCFRunLoopDefaultMode
);
643 * Store our runloop in a global so the main thread can use it to stop us.
646 pthread_mutex_lock(&SysEventThreadMutex
);
648 SysEventRunloop
= CFRunLoopGetCurrent();
650 pthread_cond_signal(&SysEventThreadCond
);
651 pthread_mutex_unlock(&SysEventThreadMutex
);
654 * Disappear into the runloop until it's stopped by the main thread.
660 * Clean up before exiting.
663 if (threadData
.timerRef
)
665 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), threadData
.timerRef
,
666 kCFRunLoopDefaultMode
);
667 CFRelease(threadData
.timerRef
);
670 if (threadData
.sysevent
.powerKernelPort
)
672 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), powerRLS
,
673 kCFRunLoopDefaultMode
);
674 IODeregisterForSystemPower(&powerNotifierObj
);
675 IOServiceClose(threadData
.sysevent
.powerKernelPort
);
676 IONotificationPortDestroy(powerNotifierPort
);
681 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), storeRLS
,
682 kCFRunLoopDefaultMode
);
683 CFRunLoopSourceInvalidate(storeRLS
);
695 * 'sysEventPowerNotifier()' - Handle power notification events.
699 sysEventPowerNotifier(
700 void *context
, /* I - Thread context data */
701 io_service_t service
, /* I - Unused service info */
702 natural_t messageType
, /* I - Type of message */
703 void *messageArgument
) /* I - Message data */
705 int sendit
= 1; /* Send event to main thread? *
706 * (0 = no, 1 = yes, 2 = delayed */
707 cupsd_thread_data_t
*threadData
; /* Thread context data */
710 threadData
= (cupsd_thread_data_t
*)context
;
712 (void)service
; /* anti-compiler-warning-code */
716 case kIOMessageCanSystemPowerOff
:
717 case kIOMessageCanSystemSleep
:
718 threadData
->sysevent
.event
|= SYSEVENT_CANSLEEP
;
721 case kIOMessageSystemWillRestart
:
722 case kIOMessageSystemWillPowerOff
:
723 case kIOMessageSystemWillSleep
:
724 threadData
->sysevent
.event
|= SYSEVENT_WILLSLEEP
;
727 case kIOMessageSystemHasPoweredOn
:
729 * Because powered on is followed by a net-changed event, delay
734 threadData
->sysevent
.event
|= SYSEVENT_WOKE
;
737 case kIOMessageSystemWillNotPowerOff
:
738 case kIOMessageSystemWillNotSleep
:
739 #ifdef kIOMessageSystemWillPowerOn
740 case kIOMessageSystemWillPowerOn
:
741 #endif /* kIOMessageSystemWillPowerOn */
748 IOAllowPowerChange(threadData
->sysevent
.powerKernelPort
,
749 (long)messageArgument
);
752 threadData
->sysevent
.powerNotificationID
= (long)messageArgument
;
757 * Send the event to the main thread now.
760 write(SysEventPipes
[1], &threadData
->sysevent
,
761 sizeof(threadData
->sysevent
));
762 threadData
->sysevent
.event
= 0;
767 * Send the event to the main thread after 1 to 2 seconds.
770 CFRunLoopTimerSetNextFireDate(threadData
->timerRef
,
771 CFAbsoluteTimeGetCurrent() + 2);
778 * 'sysEventConfigurationNotifier()' - Computer name changed notification
783 sysEventConfigurationNotifier(
784 SCDynamicStoreRef store
, /* I - System data (unused) */
785 CFArrayRef changedKeys
, /* I - Changed data */
786 void *context
) /* I - Thread context data */
788 cupsd_thread_data_t
*threadData
; /* Thread context data */
791 threadData
= (cupsd_thread_data_t
*)context
;
793 (void)store
; /* anti-compiler-warning-code */
795 CFRange range
= CFRangeMake(0, CFArrayGetCount(changedKeys
));
797 if (CFArrayContainsValue(changedKeys
, range
, ComputerNameKey
))
798 threadData
->sysevent
.event
|= SYSEVENT_NAMECHANGED
;
801 threadData
->sysevent
.event
|= SYSEVENT_NETCHANGED
;
804 * Indicate the network interface list needs updating...
811 * Because we registered for several different kinds of change notifications
812 * this callback usually gets called several times in a row. We use a timer to
813 * de-bounce these so we only end up generating one event for the main thread.
816 CFRunLoopTimerSetNextFireDate(threadData
->timerRef
,
817 CFAbsoluteTimeGetCurrent() + 5);
822 * 'sysEventTimerNotifier()' - Handle delayed event notifications.
826 sysEventTimerNotifier(
827 CFRunLoopTimerRef timer
, /* I - Timer information */
828 void *context
) /* I - Thread context data */
830 cupsd_thread_data_t
*threadData
; /* Thread context data */
833 threadData
= (cupsd_thread_data_t
*)context
;
836 * If an event is still pending send it to the main thread.
839 if (threadData
->sysevent
.event
)
841 write(SysEventPipes
[1], &threadData
->sysevent
,
842 sizeof(threadData
->sysevent
));
843 threadData
->sysevent
.event
= 0;
846 #endif /* __APPLE__ */
850 * End of "$Id: sysman.c 6649 2007-07-11 21:46:42Z mike $".