chiark / gitweb /
daa3d9c821a5dc400339310d2aa29fb96b73da05
[elogind.git] / src / timedated.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2011 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <dbus/dbus.h>
23
24 #include <errno.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include "util.h"
29 #include "strv.h"
30 #include "dbus-common.h"
31 #include "polkit.h"
32
33 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
34 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
35
36 #define INTROSPECTION                                                   \
37         DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                       \
38         "<node>\n"                                                      \
39         " <interface name=\"org.freedesktop.timedate1\">\n"             \
40         "  <property name=\"Timezone\" type=\"s\" access=\"read\"/>\n"  \
41         "  <property name=\"LocalRTC\" type=\"b\" access=\"read\"/>\n"  \
42         "  <method name=\"SetTime\">\n"                                 \
43         "   <arg name=\"usec_utc\" type=\"x\" direction=\"in\"/>\n"     \
44         "   <arg name=\"relative\" type=\"b\" direction=\"in\"/>\n"     \
45         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
46         "  </method>\n"                                                 \
47         "  <method name=\"SetTimezone\">\n"                             \
48         "   <arg name=\"timezone\" type=\"s\" direction=\"in\"/>\n"     \
49         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
50         "  </method>\n"                                                 \
51         "  <method name=\"SetLocalRTC\">\n"                             \
52         "   <arg name=\"local_rtc\" type=\"b\" direction=\"in\"/>\n"    \
53         "   <arg name=\"fix_system\" type=\"b\" direction=\"in\"/>\n" \
54         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
55         "  </method>\n"                                                 \
56         " </interface>\n"                                               \
57         BUS_PROPERTIES_INTERFACE                                        \
58         BUS_INTROSPECTABLE_INTERFACE                                    \
59         BUS_PEER_INTERFACE                                              \
60         "</node>\n"
61
62 #define INTERFACES_LIST                         \
63         BUS_GENERIC_INTERFACES_LIST             \
64         "org.freedesktop.locale1\0"
65
66 static char *zone = NULL;
67 static bool local_rtc = false;
68
69 static void free_data(void) {
70         free(zone);
71         zone = NULL;
72
73         local_rtc = false;
74 }
75
76 static bool valid_timezone(const char *name) {
77         const char *p;
78         char *t;
79         bool slash = false;
80         int r;
81         struct stat st;
82
83         assert(name);
84
85         if (*name == '/' || *name == 0)
86                 return false;
87
88         for (p = name; *p; p++) {
89                 if (!(*p >= '0' && *p <= '9') &&
90                     !(*p >= 'a' && *p <= 'z') &&
91                     !(*p >= 'A' && *p <= 'Z') &&
92                     !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
93                         return false;
94
95                 if (*p == '/') {
96
97                         if (slash)
98                                 return false;
99
100                         slash = true;
101                 } else
102                         slash = false;
103         }
104
105         if (slash)
106                 return false;
107
108         t = strappend("/usr/share/zoneinfo/", name);
109         if (!t)
110                 return false;
111
112         r = stat(t, &st);
113         free(t);
114
115         if (r < 0)
116                 return false;
117
118         if (!S_ISREG(st.st_mode))
119                 return false;
120
121         return true;
122 }
123
124 static void verify_timezone(void) {
125         char *p, *a = NULL, *b = NULL;
126         size_t l, q;
127         int j, k;
128
129         if (!zone)
130                 return;
131
132         p = strappend("/usr/share/zoneinfo/", zone);
133         if (!p) {
134                 log_error("Out of memory");
135                 return;
136         }
137
138         j = read_full_file("/etc/localtime", &a, &l);
139         k = read_full_file(p, &b, &q);
140
141         free(p);
142
143         if (j < 0 || k < 0 || l != q || memcmp(a, b, l)) {
144                 log_warning("/etc/localtime and /etc/timezone out of sync.");
145                 free(zone);
146                 zone = NULL;
147         }
148
149         free(a);
150         free(b);
151 }
152
153 static int read_data(void) {
154         int r;
155
156         free_data();
157
158         r = read_one_line_file("/etc/timezone", &zone);
159         if (r < 0 && r != -ENOENT)
160                 return r;
161
162         verify_timezone();
163
164         local_rtc = hwclock_is_localtime() > 0;
165
166         return 0;
167 }
168
169 static int write_data_timezone(void) {
170         int r = 0;
171         char *p;
172
173         if (!zone) {
174                 if (unlink("/etc/timezone") < 0 && errno != ENOENT)
175                         r = -errno;
176
177                 if (unlink("/etc/localtime") < 0 && errno != ENOENT)
178                         r = -errno;
179
180                 return r;
181         }
182
183         p = strappend("/usr/share/zoneinfo/", zone);
184         if (!p) {
185                 log_error("Out of memory");
186                 return -ENOMEM;
187         }
188
189         r = symlink_or_copy_atomic(p, "/etc/localtime");
190         free(p);
191
192         if (r < 0)
193                 return r;
194
195         r = write_one_line_file_atomic("/etc/timezone", zone);
196         if (r < 0)
197                 return r;
198
199         return 0;
200 }
201
202 static int write_data_local_rtc(void) {
203         int r;
204         char *s, *w;
205
206         r = read_full_file("/etc/adjtime", &s, NULL);
207         if (r < 0) {
208                 if (r != -ENOENT)
209                         return r;
210
211                 if (!local_rtc)
212                         return 0;
213
214                 w = strdup(NULL_ADJTIME_LOCAL);
215                 if (!w)
216                         return -ENOMEM;
217         } else {
218                 char *p, *e;
219                 size_t a, b;
220
221                 p = strchr(s, '\n');
222                 if (!p) {
223                         free(s);
224                         return -EIO;
225                 }
226
227                 p = strchr(p+1, '\n');
228                 if (!p) {
229                         free(s);
230                         return -EIO;
231                 }
232
233                 p++;
234                 e = strchr(p, '\n');
235                 if (!p) {
236                         free(s);
237                         return -EIO;
238                 }
239
240                 a = p - s;
241                 b = strlen(e);
242
243                 w = new(char, a + (local_rtc ? 5 : 3) + b + 1);
244                 if (!w) {
245                         free(s);
246                         return -ENOMEM;
247                 }
248
249                 *(char*) mempcpy(stpcpy(mempcpy(w, s, a), local_rtc ? "LOCAL" : "UTC"), e, b) = 0;
250
251                 if (streq(w, NULL_ADJTIME_UTC)) {
252                         free(w);
253
254                         if (unlink("/etc/adjtime") < 0) {
255                                 if (errno != ENOENT)
256                                         return -errno;
257                         }
258
259                         return 0;
260                 }
261         }
262
263         r = write_one_line_file_atomic("/etc/adjtime", w);
264         free(w);
265
266         return r;
267 }
268
269 static DBusHandlerResult timedate_message_handler(
270                 DBusConnection *connection,
271                 DBusMessage *message,
272                 void *userdata) {
273
274         const BusProperty properties[] = {
275                 { "org.freedesktop.timedate1", "Timezone", bus_property_append_string, "s", zone       },
276                 { "org.freedesktop.timedate1", "LocalRTC", bus_property_append_bool,   "b", &local_rtc },
277                 { NULL, NULL, NULL, NULL, NULL }
278         };
279
280         DBusMessage *reply = NULL, *changed = NULL;
281         DBusError error;
282         int r;
283
284         assert(connection);
285         assert(message);
286
287         dbus_error_init(&error);
288
289         if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetTimezone")) {
290                 const char *z;
291                 dbus_bool_t interactive;
292
293                 if (!dbus_message_get_args(
294                                     message,
295                                     &error,
296                                     DBUS_TYPE_STRING, &z,
297                                     DBUS_TYPE_BOOLEAN, &interactive,
298                                     DBUS_TYPE_INVALID))
299                         return bus_send_error_reply(connection, message, &error, -EINVAL);
300
301                 if (!valid_timezone(z))
302                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
303
304                 if (!streq_ptr(z, zone)) {
305                         char *t;
306
307                         r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-timezone", interactive, &error);
308                         if (r < 0)
309                                 return bus_send_error_reply(connection, message, &error, r);
310
311                         t = strdup(z);
312                         if (!t)
313                                 goto oom;
314
315                         free(zone);
316                         zone = t;
317
318                         /* 1. Write new configuration file */
319                         r = write_data_timezone();
320                         if (r < 0) {
321                                 log_error("Failed to set timezone: %s", strerror(-r));
322                                 return bus_send_error_reply(connection, message, NULL, r);
323                         }
324
325                         if (local_rtc) {
326                                 struct timespec ts;
327                                 struct tm *tm;
328
329                                 /* 2. Teach kernel new timezone */
330                                 hwclock_apply_localtime_delta();
331
332                                 /* 3. Sync RTC from system clock, with the new delta */
333                                 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
334                                 assert_se(tm = localtime(&ts.tv_sec));
335                                 hwclock_set_time(tm);
336                         }
337
338                         log_info("Changed timezone to '%s'.", zone);
339
340                         changed = bus_properties_changed_new(
341                                         "/org/freedesktop/timedate1",
342                                         "org.freedesktop.timedate1",
343                                         "Timezone\0");
344                         if (!changed)
345                                 goto oom;
346                 }
347
348         } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetLocalRTC")) {
349                 dbus_bool_t lrtc;
350                 dbus_bool_t fix_system;
351                 dbus_bool_t interactive;
352
353                 if (!dbus_message_get_args(
354                                     message,
355                                     &error,
356                                     DBUS_TYPE_BOOLEAN, &lrtc,
357                                     DBUS_TYPE_BOOLEAN, &fix_system,
358                                     DBUS_TYPE_BOOLEAN, &interactive,
359                                     DBUS_TYPE_INVALID))
360                         return bus_send_error_reply(connection, message, &error, -EINVAL);
361
362                 if (lrtc != local_rtc) {
363                         struct timespec ts;
364
365                         r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-local-rtc", interactive, &error);
366                         if (r < 0)
367                                 return bus_send_error_reply(connection, message, &error, r);
368
369                         local_rtc = lrtc;
370
371                         /* 1. Write new configuration file */
372                         r = write_data_local_rtc();
373                         if (r < 0) {
374                                 log_error("Failed to set RTC to local/UTC: %s", strerror(-r));
375                                 return bus_send_error_reply(connection, message, NULL, r);
376                         }
377
378                         /* 2. Teach kernel new timezone */
379                         if (local_rtc)
380                                 hwclock_apply_localtime_delta();
381                         else
382                                 hwclock_reset_localtime_delta();
383
384                         /* 3. Synchronize clocks */
385                         assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
386
387                         if (fix_system) {
388                                 struct tm tm;
389
390                                 /* Sync system clock from RTC; first,
391                                  * initialize the timezone fields of
392                                  * struct tm. */
393                                 if (local_rtc)
394                                         tm = *localtime(&ts.tv_sec);
395                                 else
396                                         tm = *gmtime(&ts.tv_sec);
397
398                                 /* Override the main fields of
399                                  * struct tm, but not the timezone
400                                  * fields */
401                                 if (hwclock_get_time(&tm) >= 0) {
402
403                                         /* And set the system clock
404                                          * with this */
405                                         if (local_rtc)
406                                                 ts.tv_sec = mktime(&tm);
407                                         else
408                                                 ts.tv_sec = timegm(&tm);
409
410                                         clock_settime(CLOCK_REALTIME, &ts);
411                                 }
412
413                         } else {
414                                 struct tm *tm;
415
416                                 /* Sync RTC from system clock */
417                                 if (local_rtc)
418                                         tm = localtime(&ts.tv_sec);
419                                 else
420                                         tm = gmtime(&ts.tv_sec);
421
422                                 hwclock_set_time(tm);
423                         }
424
425                         log_error("RTC configured to %s time.", local_rtc ? "local" : "UTC");
426
427                         changed = bus_properties_changed_new(
428                                         "/org/freedesktop/timedate1",
429                                         "org.freedesktop.timedate1",
430                                         "LocalRTC\0");
431                         if (!changed)
432                                 goto oom;
433                 }
434
435         } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetTime")) {
436                 int64_t utc;
437                 dbus_bool_t relative;
438                 dbus_bool_t interactive;
439
440                 if (!dbus_message_get_args(
441                                     message,
442                                     &error,
443                                     DBUS_TYPE_INT64, &utc,
444                                     DBUS_TYPE_BOOLEAN, &relative,
445                                     DBUS_TYPE_BOOLEAN, &interactive,
446                                     DBUS_TYPE_INVALID))
447                         return bus_send_error_reply(connection, message, &error, -EINVAL);
448
449                 if (!relative && utc <= 0)
450                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
451
452                 if (!relative || utc != 0) {
453                         struct timespec ts;
454                         struct tm* tm;
455
456                         r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-time", interactive, &error);
457                         if (r < 0)
458                                 return bus_send_error_reply(connection, message, &error, r);
459
460                         if (relative)
461                                 timespec_store(&ts, now(CLOCK_REALTIME) + utc);
462                         else
463                                 timespec_store(&ts, utc);
464
465                         /* Set system clock */
466                         if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
467                                 log_error("Failed to set local time: %m");
468                                 return bus_send_error_reply(connection, message, NULL, -errno);
469                         }
470
471                         /* Sync down to RTC */
472                         if (local_rtc)
473                                 tm = localtime(&ts.tv_sec);
474                         else
475                                 tm = gmtime(&ts.tv_sec);
476
477                         hwclock_set_time(tm);
478
479                         log_info("Changed local time to %s", ctime(&ts.tv_sec));
480                 }
481
482         } else
483                 return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, properties);
484
485         if (!(reply = dbus_message_new_method_return(message)))
486                 goto oom;
487
488         if (!dbus_connection_send(connection, reply, NULL))
489                 goto oom;
490
491         dbus_message_unref(reply);
492         reply = NULL;
493
494         if (changed) {
495
496                 if (!dbus_connection_send(connection, changed, NULL))
497                         goto oom;
498
499                 dbus_message_unref(changed);
500         }
501
502         return DBUS_HANDLER_RESULT_HANDLED;
503
504 oom:
505         if (reply)
506                 dbus_message_unref(reply);
507
508         if (changed)
509                 dbus_message_unref(changed);
510
511         dbus_error_free(&error);
512
513         return DBUS_HANDLER_RESULT_NEED_MEMORY;
514 }
515
516 static int connect_bus(DBusConnection **_bus) {
517         static const DBusObjectPathVTable timedate_vtable = {
518                 .message_function = timedate_message_handler
519         };
520         DBusError error;
521         DBusConnection *bus = NULL;
522         int r;
523
524         assert(_bus);
525
526         dbus_error_init(&error);
527
528         bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
529         if (!bus) {
530                 log_error("Failed to get system D-Bus connection: %s", error.message);
531                 r = -ECONNREFUSED;
532                 goto fail;
533         }
534
535         if (!dbus_connection_register_object_path(bus, "/org/freedesktop/timedate1", &timedate_vtable, NULL)) {
536                 log_error("Not enough memory");
537                 r = -ENOMEM;
538                 goto fail;
539         }
540
541         if (dbus_bus_request_name(bus, "org.freedesktop.timedate1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error) < 0) {
542                 log_error("Failed to register name on bus: %s", error.message);
543                 r = -EEXIST;
544                 goto fail;
545         }
546
547         if (_bus)
548                 *_bus = bus;
549
550         return 0;
551
552 fail:
553         dbus_connection_close(bus);
554         dbus_connection_unref(bus);
555
556         dbus_error_free(&error);
557
558         return r;
559 }
560
561 int main(int argc, char *argv[]) {
562         int r;
563         DBusConnection *bus = NULL;
564
565         log_set_target(LOG_TARGET_AUTO);
566         log_parse_environment();
567         log_open();
568
569         if (argc != 1) {
570                 log_error("This program takes no arguments.");
571                 r = -EINVAL;
572                 goto finish;
573         }
574
575         umask(0022);
576
577         r = read_data();
578         if (r < 0) {
579                 log_error("Failed to read timezone data: %s", strerror(-r));
580                 goto finish;
581         }
582
583         r = connect_bus(&bus);
584         if (r < 0)
585                 goto finish;
586
587         while (dbus_connection_read_write_dispatch(bus, -1))
588                 ;
589
590         r = 0;
591
592 finish:
593         free_data();
594
595         if (bus) {
596                 dbus_connection_flush(bus);
597                 dbus_connection_close(bus);
598                 dbus_connection_unref(bus);
599         }
600
601         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
602 }