clarify RTC/UTC messages/comments
[systembsd.git] / src / interfaces / timedated / timedated.c
1 /*
2 * Copyright (c) 2014 Ian Sutton <ian@kremlin.cc>
3 *
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.
7 *
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.
15 */
16
17 #include <unistd.h>
18 #include <limits.h>
19 #include <signal.h>
20
21 #include <sys/types.h>
22 #include <sys/time.h>
23 #include <sys/stat.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <string.h>
27 #include <tzfile.h>
28
29 #include <glib/gprintf.h>
30 #include <glib-unix.h>
31 #include <glib/gstdio.h>
32 #include <polkit/polkit.h>
33
34 #include "timedated-gen.h"
35 #include "timedated.h"
36
37 #include "../../util.h"
38
39 #define TZNAME_MAX PATH_MAX
40
41 GPtrArray *timedated_freeable;
42 Timedate1 *timedated_interf;
43
44 GMainLoop *timedated_loop;
45
46 guint bus_descriptor;
47 gboolean dbus_interface_exported; /* reliable because of gdbus operational guarantees */
48
49 const gchar *OS_LOCALTIME = "/etc/localtime"; /* current timezone file */
50 const gchar *OS_TIMEZONE_PATH = "/usr/share/zoneinfo"; /* path to system timezone files */
51
52 struct timezone_checksum_pair {
53
54 gchar *path;
55 gchar *sum;
56 gboolean posix;
57 gboolean right;
58 };
59
60 static struct timezone_checksum_pair tz_table[5000];
61
62 /* --- begin method/property/dbus signal code --- */
63
64 static gboolean
65 on_handle_set_time(Timedate1 *td1_passed_interf,
66 GDBusMethodInvocation *invoc,
67 const gchar *greet,
68 gpointer data) {
69
70 GVariant *params;
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;
77
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);
81
82 is_authed = polkit_try_auth(bus_name, "org.freedesktop.timedate1.set-time", policykit_auth);
83
84 switch(is_authed) {
85
86 case AUTHORIZED_NATIVELY:
87 case AUTHORIZED_BY_PROMPT:
88 break;
89
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.");
93 return FALSE;
94
95 case ERROR_BADBUS:
96 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EFAULT", "Provided bus name is invalid.");
97 return FALSE;
98
99 case ERROR_BADACTION:
100 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EFAULT", "Provided action ID is invalid.");
101 return FALSE;
102
103 case ERROR_GENERIC:
104 default:
105 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set system time for unknown reasons.");
106 return FALSE;
107 }
108
109 if(!proposed_time) {
110
111 timedate1_complete_set_time(td1_passed_interf, invoc);
112 return TRUE;
113
114 } else if(relative) {
115
116 cur_time = g_get_real_time();
117
118 if(proposed_time < 0 && cur_time + proposed_time > cur_time) {
119
120 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EINVAL", "Resultant time out of bounds.");
121 return FALSE;
122
123 } else if(proposed_time > 0 && cur_time + proposed_time < cur_time) {
124
125 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EINVAL", "Resultant time out of bounds.");
126 return FALSE;
127 }
128
129 new_time = mktimespec(proposed_time);
130
131 if(!clock_settime(CLOCK_REALTIME, new_time)) {
132
133 timedate1_complete_set_time(td1_passed_interf, invoc);
134 return TRUE;
135
136 } else {
137
138 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set system time for unknown reasons.");
139 return FALSE;
140 }
141
142 } else if(proposed_time > 0) {
143
144
145 new_time = mktimespec(proposed_time);
146
147 if(!clock_settime(CLOCK_REALTIME, new_time)) {
148
149 timedate1_complete_set_time(td1_passed_interf, invoc);
150 return TRUE;
151
152 } else {
153
154 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set system time for unknown reasons.");
155 return FALSE;
156 }
157
158 } else {
159
160 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EINVAL", "Resultant time out of bounds.");
161 return FALSE;
162 }
163 }
164
165 static gboolean
166 on_handle_set_timezone(Timedate1 *td1_passed_interf,
167 GDBusMethodInvocation *invoc,
168 const gchar *greet,
169 gpointer data) {
170
171 GVariant *params;
172 gchar *proposed_tz;
173 const gchar *bus_name;
174 gboolean policykit_auth;
175 check_auth_result is_authed;
176
177 gchar *tz_target_path;
178 struct stat *statbuf;
179 extern int errno;
180
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);
184
185 is_authed = polkit_try_auth(bus_name, "org.freedesktop.timedate1.set-timezone", policykit_auth);
186
187 switch(is_authed) {
188
189 case AUTHORIZED_NATIVELY:
190 case AUTHORIZED_BY_PROMPT:
191 break;
192
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.");
196 return FALSE;
197
198 case ERROR_BADBUS:
199 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EFAULT", "Provided bus name is invalid.");
200 return FALSE;
201
202 case ERROR_BADACTION:
203 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EFAULT", "Provided action ID is invalid.");
204 return FALSE;
205
206 case ERROR_GENERIC:
207 default:
208 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.ECANCELED", "Failed to set timezone for unknown reasons.");
209 return FALSE;
210 }
211
212 statbuf = (struct stat*) calloc(1, sizeof(struct stat));
213 tz_target_path = (gchar *) calloc(1, TZNAME_MAX);
214
215 g_ptr_array_add(timedated_freeable, statbuf);
216 g_ptr_array_add(timedated_freeable, tz_target_path);
217
218 strlcat(tz_target_path, TZDIR, TZNAME_MAX);
219 strlcat(tz_target_path, "/", TZNAME_MAX);
220 strlcat(tz_target_path, proposed_tz, TZNAME_MAX);
221
222 if(strstr(tz_target_path, "../")) {
223
224 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EBADF", "Provided timezone is invalid.");
225 return FALSE;
226 }
227
228 if(!statbuf)
229 return FALSE;
230
231 if(lstat(tz_target_path, statbuf)) {
232
233 switch(errno) {
234
235 case ENOENT:
236 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.ENOENT", "Specified timezone does not exist.");
237 break;
238
239 default:
240 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EBADF", "Specified timezone is invalid.");
241 break;
242 }
243
244 return FALSE;
245 }
246
247 if(!S_ISREG(statbuf->st_mode)) {
248
249 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.EBADF", "Specified path is of an inappropriate type.");
250 return FALSE;
251 }
252
253 memset(statbuf, 0, sizeof statbuf);
254
255 if(!lstat(TZDEFAULT, statbuf))
256 if(remove(TZDEFAULT))
257 return FALSE;
258
259 if(symlink(tz_target_path, TZDEFAULT))
260 return FALSE;
261
262
263 timedate1_complete_set_timezone(td1_passed_interf, invoc);
264
265 return TRUE;
266 }
267
268 static gboolean
269 on_handle_set_local_rtc(Timedate1 *td1_passed_interf,
270 GDBusMethodInvocation *invoc,
271 const gchar *greet,
272 gpointer data) {
273
274 g_dbus_method_invocation_return_dbus_error(invoc, "org.freedesktop.timedate1.Error.ENODEV", "Unix RTC must be in UTC.");
275 return TRUE;
276 }
277
278 static gboolean
279 on_handle_set_ntp(Timedate1 *td1_passed_interf,
280 GDBusMethodInvocation *invoc,
281 const gchar *greet,
282 gpointer data) {
283 return FALSE;
284 }
285
286 const gchar *
287 our_get_timezone() {
288
289 GStatBuf *stat_zoneinfo;
290 gchar *find_cmd, *readlink_path, *ret, *argvp, *hash_to_match;
291 gint argcp;
292 GError *err;
293 struct timezone_checksum_pair tmp;
294
295 find_cmd = (gchar *) g_malloc0(2048);
296 stat_zoneinfo = (GStatBuf *) g_malloc0(8192);
297 err = (GError *) g_malloc0(2048);
298
299 if(g_stat(OS_LOCALTIME, stat_zoneinfo)) {
300
301 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);
302 ret = NULL;
303
304 } else if(g_file_test(OS_LOCALTIME, G_FILE_TEST_IS_SYMLINK)) {
305
306 readlink_path = g_file_read_link(OS_LOCALTIME, &err);
307
308 gchar *split[2] = { readlink_path, "" };
309 tmp = parse_timezone_path(split);
310
311 ret = tmp.path;
312
313 if(readlink_path)
314 g_free(readlink_path);
315
316 } else {
317
318 g_printf("%s is not a symlink! attempting to match checksums in %s...\n", OS_LOCALTIME, OS_TIMEZONE_PATH);
319 hash_to_match = get_file_sha256(OS_LOCALTIME);
320
321 /* ret = lookup_hash(hash_to_match); */
322 return FALSE; /* TODO fix me for real */
323
324 if(hash_to_match)
325 g_free(hash_to_match);
326 }
327
328
329
330 return ret;
331 }
332
333 /* Unix time must be in UTC. */
334 gboolean
335 our_get_local_rtc() {
336
337 gboolean ret = FALSE;
338
339 return ret;
340 }
341
342 gboolean
343 our_get_can_ntp() {
344
345 const gboolean ret = FALSE;
346
347 return ret;
348 }
349
350 gboolean
351 our_get_ntp() {
352
353 const gboolean ret = FALSE;
354
355 return ret;
356 }
357
358 gboolean
359 our_get_ntpsynchronized() {
360
361 const gboolean ret = FALSE;
362
363 return ret;
364 }
365
366 guint64
367 our_get_time_usec() {
368
369 guint64 ret = 0;
370
371 return ret;
372 }
373
374 guint64
375 our_get_rtc_time_usec() {
376
377 guint64 ret = 0;
378
379 return ret;
380 }
381
382 /* --- end method/property/dbus signal code, begin bus/name handlers --- */
383
384 static void timedated_on_bus_acquired(GDBusConnection *conn,
385 const gchar *name,
386 gpointer user_data) {
387
388 g_printf("got bus/name, exporting %s's interface...\n", name);
389
390 timedated_interf = timedate1_skeleton_new();
391
392 /* attach function pointers to generated struct's method handlers */
393 g_signal_connect(timedated_interf, "handle-set-time", G_CALLBACK(on_handle_set_time), NULL);
394 g_signal_connect(timedated_interf, "handle-set-timezone", G_CALLBACK(on_handle_set_timezone), NULL);
395 g_signal_connect(timedated_interf, "handle-set-local-rtc", G_CALLBACK(on_handle_set_local_rtc), NULL);
396 g_signal_connect(timedated_interf, "handle-set-ntp", G_CALLBACK(on_handle_set_ntp), NULL);
397
398 /* set our properties before export */
399 timedate1_set_timezone(timedated_interf, our_get_timezone());
400 timedate1_set_local_rtc(timedated_interf, our_get_local_rtc());
401 timedate1_set_can_ntp(timedated_interf, our_get_can_ntp());
402 timedate1_set_ntp(timedated_interf, our_get_ntp());
403 timedate1_set_ntpsynchronized(timedated_interf, our_get_ntpsynchronized());
404 timedate1_set_time_usec(timedated_interf, our_get_time_usec());
405 timedate1_set_rtctime_usec(timedated_interf, our_get_rtc_time_usec());
406
407 if(!g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(timedated_interf),
408 conn,
409 "/org/freedesktop/timedate1",
410 NULL)) {
411
412 g_printf("failed to export %s's interface!\n", name);
413 timedated_mem_clean();
414
415 } else {
416
417 dbus_interface_exported = TRUE;
418 g_printf("exported %s's interface on the system bus...\n", name);
419 }
420 }
421
422 static void timedated_on_name_acquired(GDBusConnection *conn,
423 const gchar *name,
424 gpointer user_data) {
425
426 g_printf("success!\n");
427 }
428
429 static void timedated_on_name_lost(GDBusConnection *conn,
430 const gchar *name,
431 gpointer user_data) {
432
433 if(!conn) {
434
435 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);
436 timedated_mem_clean();
437 }
438
439 g_print("lost name %s, exiting...\n", name);
440
441 timedated_mem_clean();
442 }
443
444 /* --- end bus/name handlers, begin misc unix functions --- */
445
446 /* safe call to clean and then exit
447 * this stops our GMainLoop safely before letting main() return */
448 void timedated_mem_clean() {
449
450 g_printf("exiting...\n");
451
452 if(dbus_interface_exported)
453 g_dbus_interface_skeleton_unexport(G_DBUS_INTERFACE_SKELETON(timedated_interf));
454
455 if(g_main_loop_is_running(timedated_loop))
456 g_main_loop_quit(timedated_loop);
457
458 }
459
460 /* wrapper for glib's unix signal handling; called only once if terminating signal is raised against us */
461 gboolean unix_sig_terminate_handler(gpointer data) {
462
463 g_printf("caught SIGINT/HUP/TERM, exiting\n");
464
465 timedated_mem_clean();
466 return G_SOURCE_REMOVE;
467 }
468
469 void set_signal_handlers() {
470
471 /* we don't care about its descriptor, we never need to unregister these */
472 g_unix_signal_add(SIGINT, unix_sig_terminate_handler, NULL);
473 g_unix_signal_add(SIGHUP, unix_sig_terminate_handler, NULL);
474 g_unix_signal_add(SIGTERM, unix_sig_terminate_handler, NULL);
475 }
476
477 int main() {
478
479 set_signal_handlers();
480
481 /*if(!build_lookup_table())
482 return 1; */
483
484 timedated_loop = g_main_loop_new(NULL, TRUE);
485 timedated_freeable = g_ptr_array_new();
486
487 bus_descriptor = g_bus_own_name(G_BUS_TYPE_SYSTEM,
488 "org.freedesktop.timedate1",
489 G_BUS_NAME_OWNER_FLAGS_NONE,
490 timedated_on_bus_acquired,
491 timedated_on_name_acquired,
492 timedated_on_name_lost,
493 NULL,
494 NULL);
495
496 g_main_loop_run(timedated_loop);
497 /* runs until single g_main_loop_quit() call is raised inside <interface>_mem_clean() */
498 g_main_loop_unref(timedated_loop);
499
500 /* guaranteed unownable */
501 g_bus_unown_name(bus_descriptor);
502
503 /* at this point no operations can occur with our data, it is safe to free it + its container */
504 g_ptr_array_free(timedated_freeable, TRUE);
505
506 return 0;
507 }
508
509 static struct timezone_checksum_pair parse_timezone_path(gchar **pair) {
510
511 gchar *prefix_pattern, *right_prefix_pattern, *posix_prefix_pattern, *lean_path;
512 GRegex *prefix, *posix, *right;
513 GError *err = NULL;
514 struct timezone_checksum_pair ret = { NULL, NULL, FALSE, FALSE };
515
516 if(!pair[0])
517 return ret;
518
519 prefix_pattern = (gchar *) g_malloc0(4096);
520 right_prefix_pattern = (gchar *) g_malloc0(4096);
521 posix_prefix_pattern = (gchar *) g_malloc0(4096);
522
523 g_sprintf(prefix_pattern, "%s/", OS_TIMEZONE_PATH);
524 g_sprintf(posix_prefix_pattern, "%s/posix/", OS_TIMEZONE_PATH);
525 g_sprintf(right_prefix_pattern, "%s/right/", OS_TIMEZONE_PATH);
526
527 prefix = g_regex_new(prefix_pattern, 0, 0, &err);
528 posix = g_regex_new(posix_prefix_pattern, 0, 0, &err);
529 right = g_regex_new(right_prefix_pattern, 0, 0, &err);
530
531 if(g_regex_match_full(posix, pair[0], -1, 0, G_REGEX_MATCH_NOTEMPTY, NULL, NULL)) {
532
533 ret.posix = TRUE;
534 lean_path = g_regex_replace_literal(posix, pair[0], -1, 0, "", G_REGEX_MATCH_NOTEMPTY, NULL);
535
536 } else if(g_regex_match_full(right, pair[0], -1, 0, G_REGEX_MATCH_NOTEMPTY, NULL, NULL)) {
537
538 ret.right = TRUE;
539 lean_path = g_regex_replace_literal(right, pair[0], -1, 0, "", G_REGEX_MATCH_NOTEMPTY, NULL);
540
541 } else
542 lean_path = g_regex_replace_literal(prefix, pair[0], -1, 0, "", G_REGEX_MATCH_NOTEMPTY, NULL);
543
544 ret.path = lean_path;
545
546 ret.sum = g_malloc0(256);
547 g_strlcpy(ret.sum, pair[1], 66);
548
549 g_regex_unref(prefix);
550 g_regex_unref(right);
551 g_regex_unref(posix);
552
553 return ret;
554 }
555
556 /* TODO need to deconstruct tz_table on exit
557 static gboolean build_lookup_table() {
558
559 gchar *find_cmd, **map_pairs, *find_output, *path_buf, *sum_buf, **entry_buf;
560 GError *err;
561 gboolean ret;
562 gint i;
563
564 i = 0;
565 err = NULL;
566 ret = TRUE;
567
568 find_cmd = (gchar *) g_malloc0(4096);
569 find_output = (gchar *) g_malloc0(1000000);
570
571 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);
572
573 if(!g_spawn_command_line_sync(find_cmd, &find_output, NULL, NULL, &err)) {
574
575 g_printf("error running `%s`\n", find_cmd);
576 ret = FALSE;
577 }
578
579 map_pairs = g_strsplit(find_output, "\n", INT_MAX);
580
581 while(map_pairs[i] && (entry_buf = g_strsplit(map_pairs[i], "=", INT_MAX))) {
582
583 tz_table[i] = parse_timezone_path(entry_buf);
584
585 g_strfreev(entry_buf);
586 i++;
587 }
588
589 g_free(find_output);
590 g_free(find_cmd);
591 g_free(map_pairs);
592
593 return ret;
594 }
595
596 static gchar *lookup_hash(gchar *hash) {
597
598 gint i = 0;
599
600 while(tz_table[i].sum)
601 if(!g_strcmp0(tz_table[i].sum, hash))
602 return tz_table[i].path;
603 else
604 i++;
605
606 return NULL;
607 }*/
608
609 /* takes number of microseconds since epoch and returns a
610 * ptr to a timespec suitable to be passed to clock_settime(3)
611 */
612 static struct timespec* mktimespec(gint64 us) {
613
614 long nanoseconds;
615 time_t seconds;
616
617 gint64 div_buf_remainder, div_buf_s, div_buf_ns;
618 struct timespec *ret;
619
620 div_buf_s = (us / 1000000); /* us / 10^6 = s */
621 div_buf_remainder = (us % 1000000); /* fraction of second lost from prev. line */
622 div_buf_ns = div_buf_remainder * 1000; /* us * 10^3 = ns */
623
624 seconds = (time_t) div_buf_s; /* porting note: most systems use 32 bit time, adjust accordingly */
625 nanoseconds = (long) div_buf_ns;
626
627 ret = (struct timespec *) calloc(1, sizeof(struct timespec));
628
629 ret->tv_sec = seconds;
630 ret->tv_nsec = nanoseconds;
631
632 g_ptr_array_add(timedated_freeable, ret);
633
634 return ret;
635 }