2 * Copyright (c) 2014 Ian Sutton <ian@kremlin.cc>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #include <sys/types.h>
29 #include <glib/gprintf.h>
30 #include <glib-unix.h>
31 #include <glib/gstdio.h>
32 #include <polkit/polkit.h>
34 #include "timedated-gen.h"
35 #include "timedated.h"
37 #include "../../util.h"
39 #define TZNAME_MAX PATH_MAX
41 GPtrArray
*timedated_freeable
;
42 Timedate1
*timedated_interf
;
44 GMainLoop
*timedated_loop
;
47 gboolean dbus_interface_exported
; /* reliable because of gdbus operational guarantees */
49 const gchar
*OS_LOCALTIME
= "/etc/localtime"; /* current timezone file */
50 const gchar
*OS_TIMEZONE_PATH
= "/usr/share/zoneinfo"; /* path to system timezone files */
52 struct timezone_checksum_pair
{
60 static struct timezone_checksum_pair tz_table
[5000];
62 /* --- begin method/property/dbus signal code --- */
65 on_handle_set_time(Timedate1
*td1_passed_interf
,
66 GDBusMethodInvocation
*invoc
,
71 gint64 proposed_time
, cur_time
;
72 const gchar
*bus_name
;
73 gboolean policykit_auth
;
74 check_auth_result is_authed
;
75 gboolean relative
; /* relative if passed time_t is meant to be added to current time */
76 struct timespec
*new_time
;
78 params
= g_dbus_method_invocation_get_parameters(invoc
);
79 g_variant_get(params
, "(xbb)", &proposed_time
, &relative
, &policykit_auth
);
80 bus_name
= g_dbus_method_invocation_get_sender(invoc
);
82 is_authed
= polkit_try_auth(bus_name
, "org.freedesktop.timedate1.set-time", policykit_auth
);
86 case AUTHORIZED_NATIVELY
:
87 case AUTHORIZED_BY_PROMPT
:
90 case UNAUTHORIZED_NATIVELY
:
91 case UNAUTHORIZED_FAILED_PROMPT
:
92 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EACCES", "Insufficient permissions to set system time.");
96 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EFAULT", "Provided bus name is invalid.");
100 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EFAULT", "Provided action ID is invalid.");
105 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set system time for unknown reasons.");
111 timedate1_complete_set_time(td1_passed_interf
, invoc
);
114 } else if(relative
) {
116 cur_time
= g_get_real_time();
118 if(proposed_time
< 0 && cur_time
+ proposed_time
> cur_time
) {
120 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EINVAL", "Resultant time out of bounds.");
123 } else if(proposed_time
> 0 && cur_time
+ proposed_time
< cur_time
) {
125 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EINVAL", "Resultant time out of bounds.");
129 new_time
= mktimespec(proposed_time
);
131 if(!clock_settime(CLOCK_REALTIME
, new_time
)) {
133 timedate1_complete_set_time(td1_passed_interf
, invoc
);
138 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set system time for unknown reasons.");
142 } else if(proposed_time
> 0) {
145 new_time
= mktimespec(proposed_time
);
147 if(!clock_settime(CLOCK_REALTIME
, new_time
)) {
149 timedate1_complete_set_time(td1_passed_interf
, invoc
);
154 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set system time for unknown reasons.");
160 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EINVAL", "Resultant time out of bounds.");
166 on_handle_set_timezone(Timedate1
*td1_passed_interf
,
167 GDBusMethodInvocation
*invoc
,
173 const gchar
*bus_name
;
174 gboolean policykit_auth
;
175 check_auth_result is_authed
;
177 gchar
*tz_target_path
;
178 struct stat
*statbuf
;
181 params
= g_dbus_method_invocation_get_parameters(invoc
);
182 g_variant_get(params
, "(sb)", &proposed_tz
, &policykit_auth
);
183 bus_name
= g_dbus_method_invocation_get_sender(invoc
);
185 is_authed
= polkit_try_auth(bus_name
, "org.freedesktop.timedate1.set-timezone", policykit_auth
);
189 case AUTHORIZED_NATIVELY
:
190 case AUTHORIZED_BY_PROMPT
:
193 case UNAUTHORIZED_NATIVELY
:
194 case UNAUTHORIZED_FAILED_PROMPT
:
195 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EACCES", "Insufficient permissions to set timezone.");
199 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EFAULT", "Provided bus name is invalid.");
202 case ERROR_BADACTION
:
203 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EFAULT", "Provided action ID is invalid.");
208 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set timezone for unknown reasons.");
212 statbuf
= (struct stat
*) calloc(1, sizeof(struct stat
));
213 tz_target_path
= (gchar
*) calloc(1, TZNAME_MAX
);
215 g_ptr_array_add(timedated_freeable
, statbuf
);
216 g_ptr_array_add(timedated_freeable
, tz_target_path
);
218 strlcat(tz_target_path
, TZDIR
, TZNAME_MAX
);
219 strlcat(tz_target_path
, "/", TZNAME_MAX
);
220 strlcat(tz_target_path
, proposed_tz
, TZNAME_MAX
);
222 if(strstr(tz_target_path
, "../")) {
224 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EBADF", "Provided timezone is invalid.");
231 if(lstat(tz_target_path
, statbuf
)) {
236 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.ENOENT", "Specified timezone does not exist.");
240 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EBADF", "Specified timezone is invalid.");
247 if(!S_ISREG(statbuf
->st_mode
)) {
249 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EBADF", "Specified path is of an inappropriate type.");
253 memset(statbuf
, 0, sizeof statbuf
);
255 if(!lstat(TZDEFAULT
, statbuf
))
256 if(remove(TZDEFAULT
))
259 if(symlink(tz_target_path
, TZDEFAULT
))
263 timedate1_complete_set_timezone(td1_passed_interf
, invoc
);
269 on_handle_set_local_rtc(Timedate1
*td1_passed_interf
,
270 GDBusMethodInvocation
*invoc
,
274 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.ENODEV", "Unix RTC must be in UTC.");
279 on_handle_set_ntp(Timedate1
*td1_passed_interf
,
280 GDBusMethodInvocation
*invoc
,
285 const gchar
*bus_name
;
286 gboolean policykit_auth
;
287 check_auth_result is_authed
;
289 /* revert to rcctl when 5.7 rolls around */
290 gint ntpd_notrunning
, ntpd_notenabled
; /* this logic flip is due to rcctl returning 0 on success,
291 * in this case an error means ntpd is not running or not enabled */
292 gboolean proposed_ntpstate
;
297 params
= g_dbus_method_invocation_get_parameters(invoc
);
298 g_variant_get(params
, "(bb)", &proposed_ntpstate
, &policykit_auth
);
299 bus_name
= g_dbus_method_invocation_get_sender(invoc
);
301 is_authed
= polkit_try_auth(bus_name
, "org.freedesktop.timedate1.set-ntp", policykit_auth
);
305 case AUTHORIZED_NATIVELY
:
306 case AUTHORIZED_BY_PROMPT
:
309 case UNAUTHORIZED_NATIVELY
:
310 case UNAUTHORIZED_FAILED_PROMPT
:
311 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EACCES", "Insufficient permissions to toggle the NTP daemon.");
315 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EFAULT", "Provided bus name is invalid.");
318 case ERROR_BADACTION
:
319 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.EFAULT", "Provided action ID is invalid.");
324 g_dbus_method_invocation_return_dbus_error(invoc
, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to toggle the NTP daemon for unknown reasons.");
328 ntpd_notrunning
= 0; /* GLib does not bother asserting the passed return value int to zero */
329 ntpd_notenabled
= 0; /* if the program's exit status is also zero, hence this decl. */
331 if((ntpd_notrunning
= system("/etc/rc.d/ntpd check > /dev/null 2>&1")) == -1)
334 if((ntpd_notenabled
= system("/etc/rc.d/ntpd status > /dev/null 2>&1")) == -1)
337 if(proposed_ntpstate
) {
340 system("/etc/rc.d/ntpd -f start > /dev/null 2>&1");
343 system("/etc/rc.d/ntpd enable > /dev/null 2>&1");
348 system("/etc/rc.d/ntpd stop > /dev/null 2>&1");
351 system("/etc/rc.d/ntpd disable > /dev/null 2>&1");
354 timedate1_complete_set_ntp(td1_passed_interf
, invoc
);
358 /* NOTE: you should be using gobject->set_property() for these ! */
362 GStatBuf
*stat_zoneinfo
;
363 gchar
*find_cmd
, *readlink_path
, *ret
, *argvp
, *hash_to_match
;
366 struct timezone_checksum_pair tmp
;
368 find_cmd
= (gchar
*) g_malloc0(2048);
369 stat_zoneinfo
= (GStatBuf
*) g_malloc0(8192);
370 err
= (GError
*) g_malloc0(2048);
372 if(g_stat(OS_LOCALTIME
, stat_zoneinfo
)) {
374 g_printf("could not read from %s! please symlink or copy a timezone file from %s to %s!\n", OS_LOCALTIME
, OS_TIMEZONE_PATH
, OS_LOCALTIME
);
377 } else if(g_file_test(OS_LOCALTIME
, G_FILE_TEST_IS_SYMLINK
)) {
379 readlink_path
= g_file_read_link(OS_LOCALTIME
, &err
);
381 gchar
*split
[2] = { readlink_path
, "" };
382 tmp
= parse_timezone_path(split
);
387 g_free(readlink_path
);
391 g_printf("%s is not a symlink! attempting to match checksums in %s...\n", OS_LOCALTIME
, OS_TIMEZONE_PATH
);
392 hash_to_match
= get_file_sha256(OS_LOCALTIME
);
394 /* ret = lookup_hash(hash_to_match); */
395 return FALSE
; /* TODO fix me for real */
398 g_free(hash_to_match
);
404 /* Unix time is in UTC. */
406 our_get_local_rtc() {
414 /* ntpd is part of the default install */
424 system_ret
= system("/etc/rc.d/ntpd check > /dev/null 2>&1");
432 /* undocumented feature present in systemd */
434 our_get_ntpsynchronized() {
442 /* undocumented feature present in systemd */
444 our_get_time_usec() {
451 /* undocumented feature present in systemd */
453 our_get_rtc_time_usec() {
460 /* --- end method/property/dbus signal code, begin bus/name handlers --- */
462 static void timedated_on_bus_acquired(GDBusConnection
*conn
,
464 gpointer user_data
) {
466 g_printf("got bus/name, exporting %s's interface...\n", name
);
468 timedated_interf
= timedate1_skeleton_new();
470 /* attach function pointers to generated struct's method handlers */
471 g_signal_connect(timedated_interf
, "handle-set-time", G_CALLBACK(on_handle_set_time
), NULL
);
472 g_signal_connect(timedated_interf
, "handle-set-timezone", G_CALLBACK(on_handle_set_timezone
), NULL
);
473 g_signal_connect(timedated_interf
, "handle-set-local-rtc", G_CALLBACK(on_handle_set_local_rtc
), NULL
);
474 g_signal_connect(timedated_interf
, "handle-set-ntp", G_CALLBACK(on_handle_set_ntp
), NULL
);
476 /* set our properties before export */
478 timedate1_set_timezone(timedated_interf
, our_get_timezone());
479 timedate1_set_local_rtc(timedated_interf
, our_get_local_rtc());
480 timedate1_set_can_ntp(timedated_interf
, our_get_can_ntp());
481 timedate1_set_ntp(timedated_interf
, our_get_ntp());
482 timedate1_set_ntpsynchronized(timedated_interf
, our_get_ntpsynchronized());
483 timedate1_set_time_usec(timedated_interf
, our_get_time_usec());
484 timedate1_set_rtctime_usec(timedated_interf
, our_get_rtc_time_usec());
488 timedated_interf->get_timezone = our_get_timezone();
489 timedated_interf->get_local_rtc = our_get_local_rtc();
490 timedated_interf->get_can_ntp = our_get_can_ntp();
491 timedated_interf->get_ntp = our_get_ntp();
492 timedated_interf->get_ntpsynchronized = our_get_ntpsynchronized();
493 timedated_interf->get_time_usec = our_get_time_usec();
494 timedated_interf->get_rtctime_usec = our_get_rtc_time_usec(); */
496 if(!g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(timedated_interf
),
498 "/org/freedesktop/timedate1",
501 g_printf("failed to export %s's interface!\n", name
);
502 timedated_mem_clean();
506 dbus_interface_exported
= TRUE
;
507 g_printf("exported %s's interface on the system bus...\n", name
);
511 static void timedated_on_name_acquired(GDBusConnection
*conn
,
513 gpointer user_data
) {
515 g_printf("success!\n");
518 static void timedated_on_name_lost(GDBusConnection
*conn
,
520 gpointer user_data
) {
524 g_printf("failed to connect to the system bus while trying to acquire name '%s': either dbus-daemon isn't running or we don't have permission to push names and/or their interfaces to it.\n", name
);
525 timedated_mem_clean();
528 g_print("lost name %s, exiting...\n", name
);
530 timedated_mem_clean();
533 /* --- end bus/name handlers, begin misc unix functions --- */
535 /* safe call to clean and then exit
536 * this stops our GMainLoop safely before letting main() return */
537 void timedated_mem_clean() {
539 g_printf("exiting...\n");
541 if(dbus_interface_exported
)
542 g_dbus_interface_skeleton_unexport(G_DBUS_INTERFACE_SKELETON(timedated_interf
));
544 if(g_main_loop_is_running(timedated_loop
))
545 g_main_loop_quit(timedated_loop
);
549 /* wrapper for glib's unix signal handling; called only once if terminating signal is raised against us */
550 gboolean
unix_sig_terminate_handler(gpointer data
) {
552 g_printf("caught SIGINT/HUP/TERM, exiting\n");
554 timedated_mem_clean();
555 return G_SOURCE_REMOVE
;
558 void set_signal_handlers() {
560 /* we don't care about its descriptor, we never need to unregister these */
561 g_unix_signal_add(SIGINT
, unix_sig_terminate_handler
, NULL
);
562 g_unix_signal_add(SIGHUP
, unix_sig_terminate_handler
, NULL
);
563 g_unix_signal_add(SIGTERM
, unix_sig_terminate_handler
, NULL
);
568 set_signal_handlers();
570 /*if(!build_lookup_table())
573 timedated_loop
= g_main_loop_new(NULL
, TRUE
);
574 timedated_freeable
= g_ptr_array_new();
576 bus_descriptor
= g_bus_own_name(G_BUS_TYPE_SYSTEM
,
577 "org.freedesktop.timedate1",
578 G_BUS_NAME_OWNER_FLAGS_NONE
,
579 timedated_on_bus_acquired
,
580 timedated_on_name_acquired
,
581 timedated_on_name_lost
,
585 g_main_loop_run(timedated_loop
);
586 /* runs until single g_main_loop_quit() call is raised inside <interface>_mem_clean() */
587 g_main_loop_unref(timedated_loop
);
589 /* guaranteed unownable */
590 g_bus_unown_name(bus_descriptor
);
592 /* at this point no operations can occur with our data, it is safe to free it + its container */
593 g_ptr_array_free(timedated_freeable
, TRUE
);
598 static struct timezone_checksum_pair
parse_timezone_path(gchar
**pair
) {
600 gchar
*prefix_pattern
, *right_prefix_pattern
, *posix_prefix_pattern
, *lean_path
;
601 GRegex
*prefix
, *posix
, *right
;
603 struct timezone_checksum_pair ret
= { NULL
, NULL
, FALSE
, FALSE
};
608 prefix_pattern
= (gchar
*) g_malloc0(4096);
609 right_prefix_pattern
= (gchar
*) g_malloc0(4096);
610 posix_prefix_pattern
= (gchar
*) g_malloc0(4096);
612 g_sprintf(prefix_pattern
, "%s/", OS_TIMEZONE_PATH
);
613 g_sprintf(posix_prefix_pattern
, "%s/posix/", OS_TIMEZONE_PATH
);
614 g_sprintf(right_prefix_pattern
, "%s/right/", OS_TIMEZONE_PATH
);
616 prefix
= g_regex_new(prefix_pattern
, 0, 0, &err
);
617 posix
= g_regex_new(posix_prefix_pattern
, 0, 0, &err
);
618 right
= g_regex_new(right_prefix_pattern
, 0, 0, &err
);
620 if(g_regex_match_full(posix
, pair
[0], -1, 0, G_REGEX_MATCH_NOTEMPTY
, NULL
, NULL
)) {
623 lean_path
= g_regex_replace_literal(posix
, pair
[0], -1, 0, "", G_REGEX_MATCH_NOTEMPTY
, NULL
);
625 } else if(g_regex_match_full(right
, pair
[0], -1, 0, G_REGEX_MATCH_NOTEMPTY
, NULL
, NULL
)) {
628 lean_path
= g_regex_replace_literal(right
, pair
[0], -1, 0, "", G_REGEX_MATCH_NOTEMPTY
, NULL
);
631 lean_path
= g_regex_replace_literal(prefix
, pair
[0], -1, 0, "", G_REGEX_MATCH_NOTEMPTY
, NULL
);
633 ret
.path
= lean_path
;
635 ret
.sum
= g_malloc0(256);
636 g_strlcpy(ret
.sum
, pair
[1], 66);
638 g_regex_unref(prefix
);
639 g_regex_unref(right
);
640 g_regex_unref(posix
);
645 /* TODO need to deconstruct tz_table on exit
646 static gboolean build_lookup_table() {
648 gchar *find_cmd, **map_pairs, *find_output, *path_buf, *sum_buf, **entry_buf;
657 find_cmd = (gchar *) g_malloc0(4096);
658 find_output = (gchar *) g_malloc0(1000000);
660 g_sprintf(find_cmd, "/bin/sh -c \"find %s -type f -exec cksum -a sha256 {} \\; | sed -E 's/SHA256 \\(//g' | sed -E 's/\\) = /=/g'\"", OS_TIMEZONE_PATH);
662 if(!g_spawn_command_line_sync(find_cmd, &find_output, NULL, NULL, &err)) {
664 g_printf("error running `%s`\n", find_cmd);
668 map_pairs = g_strsplit(find_output, "\n", INT_MAX);
670 while(map_pairs[i] && (entry_buf = g_strsplit(map_pairs[i], "=", INT_MAX))) {
672 tz_table[i] = parse_timezone_path(entry_buf);
674 g_strfreev(entry_buf);
685 static gchar *lookup_hash(gchar *hash) {
689 while(tz_table[i].sum)
690 if(!g_strcmp0(tz_table[i].sum, hash))
691 return tz_table[i].path;
698 /* takes number of microseconds since epoch and returns a
699 * ptr to a timespec suitable to be passed to clock_settime(3)
701 static struct timespec
* mktimespec(gint64 us
) {
706 gint64 div_buf_remainder
, div_buf_s
, div_buf_ns
;
707 struct timespec
*ret
;
709 div_buf_s
= (us
/ 1000000); /* us / 10^6 = s */
710 div_buf_remainder
= (us
% 1000000); /* fraction of second lost from prev. line */
711 div_buf_ns
= div_buf_remainder
* 1000; /* us * 10^3 = ns */
713 seconds
= (time_t) div_buf_s
; /* porting note: most systems use 32 bit time, adjust accordingly */
714 nanoseconds
= (long) div_buf_ns
;
716 ret
= (struct timespec
*) calloc(1, sizeof(struct timespec
));
718 ret
->tv_sec
= seconds
;
719 ret
->tv_nsec
= nanoseconds
;
721 g_ptr_array_add(timedated_freeable
, ret
);