1 | /* |
---|
2 | * Helper application which monitors network state and checks |
---|
3 | * the reachability of either pool.ntp.org or the host given |
---|
4 | * as the first argument. |
---|
5 | */ |
---|
6 | |
---|
7 | #include <CoreFoundation/CoreFoundation.h> |
---|
8 | #include <SystemConfiguration/SystemConfiguration.h> |
---|
9 | #include <syslog.h> |
---|
10 | |
---|
11 | static void ntpReachabilityCallback (SCNetworkReachabilityRef target, |
---|
12 | SCNetworkConnectionFlags flags, |
---|
13 | void *info); |
---|
14 | |
---|
15 | int main (int argc, const char * argv[]) |
---|
16 | { |
---|
17 | const char ntp_pool[] = "pool.ntp.org"; |
---|
18 | const char *observed_host; |
---|
19 | if (argc > 1) |
---|
20 | observed_host = argv[1]; |
---|
21 | else |
---|
22 | observed_host = ntp_pool; |
---|
23 | |
---|
24 | openlog ("chrony-netchanged", LOG_CONS | LOG_PID, LOG_DAEMON); |
---|
25 | |
---|
26 | SCNetworkReachabilityRef observedHost = SCNetworkReachabilityCreateWithName (NULL, observed_host); |
---|
27 | |
---|
28 | if (observedHost == NULL) |
---|
29 | { |
---|
30 | syslog (LOG_ERR, "Error creating reachability reference."); |
---|
31 | goto bail; |
---|
32 | } |
---|
33 | |
---|
34 | if (!SCNetworkReachabilitySetCallback(observedHost, ntpReachabilityCallback, NULL)) |
---|
35 | { |
---|
36 | syslog (LOG_ERR, "Unable to set reachability callback."); |
---|
37 | goto bail; |
---|
38 | } |
---|
39 | |
---|
40 | if (!SCNetworkReachabilityScheduleWithRunLoop(observedHost, CFRunLoopGetCurrent(), kCFRunLoopCommonModes)) |
---|
41 | { |
---|
42 | syslog (LOG_ERR, "Unable to schedule run loop monitoring on run loop."); |
---|
43 | goto bail; |
---|
44 | } |
---|
45 | |
---|
46 | syslog (LOG_NOTICE, "Observing %s.", observed_host); |
---|
47 | |
---|
48 | CFRunLoopRun (); |
---|
49 | |
---|
50 | bail: |
---|
51 | if (observedHost) |
---|
52 | CFRelease (observedHost); |
---|
53 | |
---|
54 | closelog(); |
---|
55 | |
---|
56 | return EXIT_FAILURE; |
---|
57 | } |
---|
58 | |
---|
59 | static void ntpReachabilityCallback(SCNetworkReachabilityRef target, |
---|
60 | SCNetworkConnectionFlags flags, |
---|
61 | void *info) |
---|
62 | { |
---|
63 | if ((flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired)) |
---|
64 | { |
---|
65 | syslog (LOG_NOTICE, "Link is online. Signalling chronyd to start sampling servers."); |
---|
66 | system (PREFIX "/etc/chrony/chrony-netchange online"); |
---|
67 | } |
---|
68 | else |
---|
69 | { |
---|
70 | syslog (LOG_NOTICE, "Link is offline. Signalling chronyd to stop sampling servers."); |
---|
71 | system (PREFIX "/etc/chrony/chrony-netchange offline"); |
---|
72 | } |
---|
73 | } |
---|