1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <sys/stat.h>
4 #include <sys/types.h>
5 #include <unistd.h>
6 
7 #include <errno.h>
8 
9 #include "alloc-util.h"
10 #include "bus-error.h"
11 #include "bus-util.h"
12 #include "dbus-timer.h"
13 #include "dbus-unit.h"
14 #include "fs-util.h"
15 #include "parse-util.h"
16 #include "random-util.h"
17 #include "serialize.h"
18 #include "special.h"
19 #include "string-table.h"
20 #include "string-util.h"
21 #include "timer.h"
22 #include "unit-name.h"
23 #include "unit.h"
24 #include "user-util.h"
25 #include "virt.h"
26 
27 static const UnitActiveState state_translation_table[_TIMER_STATE_MAX] = {
28         [TIMER_DEAD] = UNIT_INACTIVE,
29         [TIMER_WAITING] = UNIT_ACTIVE,
30         [TIMER_RUNNING] = UNIT_ACTIVE,
31         [TIMER_ELAPSED] = UNIT_ACTIVE,
32         [TIMER_FAILED] = UNIT_FAILED
33 };
34 
35 static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata);
36 
timer_init(Unit * u)37 static void timer_init(Unit *u) {
38         Timer *t = TIMER(u);
39 
40         assert(u);
41         assert(u->load_state == UNIT_STUB);
42 
43         t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
44         t->next_elapse_realtime = USEC_INFINITY;
45         t->accuracy_usec = u->manager->default_timer_accuracy_usec;
46         t->remain_after_elapse = true;
47 }
48 
timer_free_values(Timer * t)49 void timer_free_values(Timer *t) {
50         TimerValue *v;
51 
52         assert(t);
53 
54         while ((v = t->values)) {
55                 LIST_REMOVE(value, t->values, v);
56                 calendar_spec_free(v->calendar_spec);
57                 free(v);
58         }
59 }
60 
timer_done(Unit * u)61 static void timer_done(Unit *u) {
62         Timer *t = TIMER(u);
63 
64         assert(t);
65 
66         timer_free_values(t);
67 
68         t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
69         t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
70 
71         t->stamp_path = mfree(t->stamp_path);
72 }
73 
timer_verify(Timer * t)74 static int timer_verify(Timer *t) {
75         assert(t);
76         assert(UNIT(t)->load_state == UNIT_LOADED);
77 
78         if (!t->values && !t->on_clock_change && !t->on_timezone_change)
79                 return log_unit_error_errno(UNIT(t), SYNTHETIC_ERRNO(ENOEXEC), "Timer unit lacks value setting. Refusing.");
80 
81         return 0;
82 }
83 
timer_add_default_dependencies(Timer * t)84 static int timer_add_default_dependencies(Timer *t) {
85         int r;
86 
87         assert(t);
88 
89         if (!UNIT(t)->default_dependencies)
90                 return 0;
91 
92         r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
93         if (r < 0)
94                 return r;
95 
96         if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
97                 r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
98                 if (r < 0)
99                         return r;
100 
101                 LIST_FOREACH(value, v, t->values) {
102                         if (v->base != TIMER_CALENDAR)
103                                 continue;
104 
105                         FOREACH_STRING(target, SPECIAL_TIME_SYNC_TARGET, SPECIAL_TIME_SET_TARGET) {
106                                 r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, target, true, UNIT_DEPENDENCY_DEFAULT);
107                                 if (r < 0)
108                                         return r;
109                         }
110 
111                         break;
112                 }
113         }
114 
115         return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
116 }
117 
timer_add_trigger_dependencies(Timer * t)118 static int timer_add_trigger_dependencies(Timer *t) {
119         Unit *x;
120         int r;
121 
122         assert(t);
123 
124         if (UNIT_TRIGGER(UNIT(t)))
125                 return 0;
126 
127         r = unit_load_related_unit(UNIT(t), ".service", &x);
128         if (r < 0)
129                 return r;
130 
131         return unit_add_two_dependencies(UNIT(t), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
132 }
133 
timer_setup_persistent(Timer * t)134 static int timer_setup_persistent(Timer *t) {
135         _cleanup_free_ char *stamp_path = NULL;
136         int r;
137 
138         assert(t);
139 
140         if (!t->persistent)
141                 return 0;
142 
143         if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
144 
145                 r = unit_require_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE);
146                 if (r < 0)
147                         return r;
148 
149                 stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
150         } else {
151                 const char *e;
152 
153                 e = getenv("XDG_DATA_HOME");
154                 if (e)
155                         stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
156                 else {
157 
158                         _cleanup_free_ char *h = NULL;
159 
160                         r = get_home_dir(&h);
161                         if (r < 0)
162                                 return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
163 
164                         stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
165                 }
166         }
167 
168         if (!stamp_path)
169                 return log_oom();
170 
171         return free_and_replace(t->stamp_path, stamp_path);
172 }
173 
timer_get_fixed_delay_hash(Timer * t)174 static uint64_t timer_get_fixed_delay_hash(Timer *t) {
175         static const uint8_t hash_key[] = {
176                 0x51, 0x0a, 0xdb, 0x76, 0x29, 0x51, 0x42, 0xc2,
177                 0x80, 0x35, 0xea, 0xe6, 0x8e, 0x3a, 0x37, 0xbd
178         };
179 
180         struct siphash state;
181         sd_id128_t machine_id;
182         uid_t uid;
183         int r;
184 
185         assert(t);
186 
187         uid = getuid();
188         r = sd_id128_get_machine(&machine_id);
189         if (r < 0) {
190                 log_unit_debug_errno(UNIT(t), r,
191                                      "Failed to get machine ID for the fixed delay calculation, proceeding with 0: %m");
192                 machine_id = SD_ID128_NULL;
193         }
194 
195         siphash24_init(&state, hash_key);
196         siphash24_compress(&machine_id, sizeof(sd_id128_t), &state);
197         siphash24_compress_boolean(MANAGER_IS_SYSTEM(UNIT(t)->manager), &state);
198         siphash24_compress(&uid, sizeof(uid_t), &state);
199         siphash24_compress_string(UNIT(t)->id, &state);
200 
201         return siphash24_finalize(&state);
202 }
203 
timer_load(Unit * u)204 static int timer_load(Unit *u) {
205         Timer *t = TIMER(u);
206         int r;
207 
208         assert(u);
209         assert(u->load_state == UNIT_STUB);
210 
211         r = unit_load_fragment_and_dropin(u, true);
212         if (r < 0)
213                 return r;
214 
215         if (u->load_state != UNIT_LOADED)
216                 return 0;
217 
218         /* This is a new unit? Then let's add in some extras */
219         r = timer_add_trigger_dependencies(t);
220         if (r < 0)
221                 return r;
222 
223         r = timer_setup_persistent(t);
224         if (r < 0)
225                 return r;
226 
227         r = timer_add_default_dependencies(t);
228         if (r < 0)
229                 return r;
230 
231         return timer_verify(t);
232 }
233 
timer_dump(Unit * u,FILE * f,const char * prefix)234 static void timer_dump(Unit *u, FILE *f, const char *prefix) {
235         Timer *t = TIMER(u);
236         Unit *trigger;
237 
238         trigger = UNIT_TRIGGER(u);
239 
240         fprintf(f,
241                 "%sTimer State: %s\n"
242                 "%sResult: %s\n"
243                 "%sUnit: %s\n"
244                 "%sPersistent: %s\n"
245                 "%sWakeSystem: %s\n"
246                 "%sAccuracy: %s\n"
247                 "%sRemainAfterElapse: %s\n"
248                 "%sFixedRandomDelay: %s\n"
249                 "%sOnClockChange: %s\n"
250                 "%sOnTimeZoneChange: %s\n",
251                 prefix, timer_state_to_string(t->state),
252                 prefix, timer_result_to_string(t->result),
253                 prefix, trigger ? trigger->id : "n/a",
254                 prefix, yes_no(t->persistent),
255                 prefix, yes_no(t->wake_system),
256                 prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1),
257                 prefix, yes_no(t->remain_after_elapse),
258                 prefix, yes_no(t->fixed_random_delay),
259                 prefix, yes_no(t->on_clock_change),
260                 prefix, yes_no(t->on_timezone_change));
261 
262         LIST_FOREACH(value, v, t->values)
263                 if (v->base == TIMER_CALENDAR) {
264                         _cleanup_free_ char *p = NULL;
265 
266                         (void) calendar_spec_to_string(v->calendar_spec, &p);
267 
268                         fprintf(f,
269                                 "%s%s: %s\n",
270                                 prefix,
271                                 timer_base_to_string(v->base),
272                                 strna(p));
273                 } else
274                         fprintf(f,
275                                 "%s%s: %s\n",
276                                 prefix,
277                                 timer_base_to_string(v->base),
278                                 FORMAT_TIMESPAN(v->value, 0));
279 }
280 
timer_set_state(Timer * t,TimerState state)281 static void timer_set_state(Timer *t, TimerState state) {
282         TimerState old_state;
283         assert(t);
284 
285         if (t->state != state)
286                 bus_unit_send_pending_change_signal(UNIT(t), false);
287 
288         old_state = t->state;
289         t->state = state;
290 
291         if (state != TIMER_WAITING) {
292                 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
293                 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
294                 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
295                 t->next_elapse_realtime = USEC_INFINITY;
296         }
297 
298         if (state != old_state)
299                 log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state));
300 
301         unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], 0);
302 }
303 
304 static void timer_enter_waiting(Timer *t, bool time_change);
305 
timer_coldplug(Unit * u)306 static int timer_coldplug(Unit *u) {
307         Timer *t = TIMER(u);
308 
309         assert(t);
310         assert(t->state == TIMER_DEAD);
311 
312         if (t->deserialized_state == t->state)
313                 return 0;
314 
315         if (t->deserialized_state == TIMER_WAITING)
316                 timer_enter_waiting(t, false);
317         else
318                 timer_set_state(t, t->deserialized_state);
319 
320         return 0;
321 }
322 
timer_enter_dead(Timer * t,TimerResult f)323 static void timer_enter_dead(Timer *t, TimerResult f) {
324         assert(t);
325 
326         if (t->result == TIMER_SUCCESS)
327                 t->result = f;
328 
329         unit_log_result(UNIT(t), t->result == TIMER_SUCCESS, timer_result_to_string(t->result));
330         timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
331 }
332 
timer_enter_elapsed(Timer * t,bool leave_around)333 static void timer_enter_elapsed(Timer *t, bool leave_around) {
334         assert(t);
335 
336         /* If a unit is marked with RemainAfterElapse=yes we leave it
337          * around even after it elapsed once, so that starting it
338          * later again does not necessarily mean immediate
339          * retriggering. We unconditionally leave units with
340          * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
341          * since they might be restarted automatically at any time
342          * later on. */
343 
344         if (t->remain_after_elapse || leave_around)
345                 timer_set_state(t, TIMER_ELAPSED);
346         else
347                 timer_enter_dead(t, TIMER_SUCCESS);
348 }
349 
add_random(Timer * t,usec_t * v)350 static void add_random(Timer *t, usec_t *v) {
351         usec_t add;
352 
353         assert(t);
354         assert(v);
355 
356         if (t->random_usec == 0)
357                 return;
358         if (*v == USEC_INFINITY)
359                 return;
360 
361         add = (t->fixed_random_delay ? timer_get_fixed_delay_hash(t) : random_u64()) % t->random_usec;
362 
363         if (*v + add < *v) /* overflow */
364                 *v = (usec_t) -2; /* Highest possible value, that is not USEC_INFINITY */
365         else
366                 *v += add;
367 
368         log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0));
369 }
370 
timer_enter_waiting(Timer * t,bool time_change)371 static void timer_enter_waiting(Timer *t, bool time_change) {
372         bool found_monotonic = false, found_realtime = false;
373         bool leave_around = false;
374         triple_timestamp ts;
375         Unit *trigger;
376         int r;
377 
378         assert(t);
379 
380         trigger = UNIT_TRIGGER(UNIT(t));
381         if (!trigger) {
382                 log_unit_error(UNIT(t), "Unit to trigger vanished.");
383                 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
384                 return;
385         }
386 
387         triple_timestamp_get(&ts);
388         t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0;
389 
390         LIST_FOREACH(value, v, t->values) {
391                 if (v->disabled)
392                         continue;
393 
394                 if (v->base == TIMER_CALENDAR) {
395                         usec_t b, rebased;
396 
397                         /* If we know the last time this was
398                          * triggered, schedule the job based relative
399                          * to that. If we don't, just start from
400                          * the activation time. */
401 
402                         if (t->last_trigger.realtime > 0)
403                                 b = t->last_trigger.realtime;
404                         else {
405                                 if (state_translation_table[t->state] == UNIT_ACTIVE)
406                                         b = UNIT(t)->inactive_exit_timestamp.realtime;
407                                 else
408                                         b = ts.realtime;
409                         }
410 
411                         r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
412                         if (r < 0)
413                                 continue;
414 
415                         /* To make the delay due to RandomizedDelaySec= work even at boot, if the scheduled
416                          * time has already passed, set the time when systemd first started as the scheduled
417                          * time. Note that we base this on the monotonic timestamp of the boot, not the
418                          * realtime one, since the wallclock might have been off during boot. */
419                         rebased = map_clock_usec(UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic,
420                                                  CLOCK_MONOTONIC, CLOCK_REALTIME);
421                         if (v->next_elapse < rebased)
422                                 v->next_elapse = rebased;
423 
424                         if (!found_realtime)
425                                 t->next_elapse_realtime = v->next_elapse;
426                         else
427                                 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
428 
429                         found_realtime = true;
430 
431                 } else {
432                         usec_t base;
433 
434                         switch (v->base) {
435 
436                         case TIMER_ACTIVE:
437                                 if (state_translation_table[t->state] == UNIT_ACTIVE)
438                                         base = UNIT(t)->inactive_exit_timestamp.monotonic;
439                                 else
440                                         base = ts.monotonic;
441                                 break;
442 
443                         case TIMER_BOOT:
444                                 if (detect_container() <= 0) {
445                                         /* CLOCK_MONOTONIC equals the uptime on Linux */
446                                         base = 0;
447                                         break;
448                                 }
449                                 /* In a container we don't want to include the time the host
450                                  * was already up when the container started, so count from
451                                  * our own startup. */
452                                 _fallthrough_;
453                         case TIMER_STARTUP:
454                                 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
455                                 break;
456 
457                         case TIMER_UNIT_ACTIVE:
458                                 leave_around = true;
459                                 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
460                                 if (base <= 0)
461                                         continue;
462                                 break;
463 
464                         case TIMER_UNIT_INACTIVE:
465                                 leave_around = true;
466                                 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
467                                 if (base <= 0)
468                                         continue;
469                                 break;
470 
471                         default:
472                                 assert_not_reached();
473                         }
474 
475                         v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
476 
477                         if (dual_timestamp_is_set(&t->last_trigger) &&
478                             !time_change &&
479                             v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
480                             IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
481                                 /* This is a one time trigger, disable it now */
482                                 v->disabled = true;
483                                 continue;
484                         }
485 
486                         if (!found_monotonic)
487                                 t->next_elapse_monotonic_or_boottime = v->next_elapse;
488                         else
489                                 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
490 
491                         found_monotonic = true;
492                 }
493         }
494 
495         if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
496                 log_unit_debug(UNIT(t), "Timer is elapsed.");
497                 timer_enter_elapsed(t, leave_around);
498                 return;
499         }
500 
501         if (found_monotonic) {
502                 usec_t left;
503 
504                 add_random(t, &t->next_elapse_monotonic_or_boottime);
505 
506                 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
507                 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
508 
509                 if (t->monotonic_event_source) {
510                         r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
511                         if (r < 0)
512                                 goto fail;
513 
514                         r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
515                         if (r < 0)
516                                 goto fail;
517                 } else {
518 
519                         r = sd_event_add_time(
520                                         UNIT(t)->manager->event,
521                                         &t->monotonic_event_source,
522                                         t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
523                                         t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
524                                         timer_dispatch, t);
525                         if (r < 0)
526                                 goto fail;
527 
528                         (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
529                 }
530 
531         } else if (t->monotonic_event_source) {
532 
533                 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
534                 if (r < 0)
535                         goto fail;
536         }
537 
538         if (found_realtime) {
539                 add_random(t, &t->next_elapse_realtime);
540 
541                 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
542 
543                 if (t->realtime_event_source) {
544                         r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
545                         if (r < 0)
546                                 goto fail;
547 
548                         r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
549                         if (r < 0)
550                                 goto fail;
551                 } else {
552                         r = sd_event_add_time(
553                                         UNIT(t)->manager->event,
554                                         &t->realtime_event_source,
555                                         t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
556                                         t->next_elapse_realtime, t->accuracy_usec,
557                                         timer_dispatch, t);
558                         if (r < 0)
559                                 goto fail;
560 
561                         (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
562                 }
563 
564         } else if (t->realtime_event_source) {
565 
566                 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
567                 if (r < 0)
568                         goto fail;
569         }
570 
571         timer_set_state(t, TIMER_WAITING);
572         return;
573 
574 fail:
575         log_unit_warning_errno(UNIT(t), r, "Failed to enter waiting state: %m");
576         timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
577 }
578 
timer_enter_running(Timer * t)579 static void timer_enter_running(Timer *t) {
580         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
581         Unit *trigger;
582         int r;
583 
584         assert(t);
585 
586         /* Don't start job if we are supposed to go down */
587         if (unit_stop_pending(UNIT(t)))
588                 return;
589 
590         trigger = UNIT_TRIGGER(UNIT(t));
591         if (!trigger) {
592                 log_unit_error(UNIT(t), "Unit to trigger vanished.");
593                 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
594                 return;
595         }
596 
597         r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, NULL, &error, NULL);
598         if (r < 0)
599                 goto fail;
600 
601         dual_timestamp_get(&t->last_trigger);
602 
603         if (t->stamp_path)
604                 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
605 
606         timer_set_state(t, TIMER_RUNNING);
607         return;
608 
609 fail:
610         log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
611         timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
612 }
613 
timer_start(Unit * u)614 static int timer_start(Unit *u) {
615         Timer *t = TIMER(u);
616         int r;
617 
618         assert(t);
619         assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
620 
621         r = unit_test_trigger_loaded(u);
622         if (r < 0)
623                 return r;
624 
625         r = unit_acquire_invocation_id(u);
626         if (r < 0)
627                 return r;
628 
629         t->last_trigger = DUAL_TIMESTAMP_NULL;
630 
631         /* Reenable all timers that depend on unit activation time */
632         LIST_FOREACH(value, v, t->values)
633                 if (v->base == TIMER_ACTIVE)
634                         v->disabled = false;
635 
636         if (t->stamp_path) {
637                 struct stat st;
638 
639                 if (stat(t->stamp_path, &st) >= 0) {
640                         usec_t ft;
641 
642                         /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
643                          * something is wrong with the system clock. */
644 
645                         ft = timespec_load(&st.st_mtim);
646                         if (ft < now(CLOCK_REALTIME))
647                                 t->last_trigger.realtime = ft;
648                         else
649                                 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
650                                                  FORMAT_TIMESTAMP(ft));
651 
652                 } else if (errno == ENOENT)
653                         /* The timer has never run before, make sure a stamp file exists. */
654                         (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
655         }
656 
657         t->result = TIMER_SUCCESS;
658         timer_enter_waiting(t, false);
659         return 1;
660 }
661 
timer_stop(Unit * u)662 static int timer_stop(Unit *u) {
663         Timer *t = TIMER(u);
664 
665         assert(t);
666         assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
667 
668         timer_enter_dead(t, TIMER_SUCCESS);
669         return 1;
670 }
671 
timer_serialize(Unit * u,FILE * f,FDSet * fds)672 static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
673         Timer *t = TIMER(u);
674 
675         assert(u);
676         assert(f);
677         assert(fds);
678 
679         (void) serialize_item(f, "state", timer_state_to_string(t->state));
680         (void) serialize_item(f, "result", timer_result_to_string(t->result));
681 
682         if (t->last_trigger.realtime > 0)
683                 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
684 
685         if (t->last_trigger.monotonic > 0)
686                 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
687 
688         return 0;
689 }
690 
timer_deserialize_item(Unit * u,const char * key,const char * value,FDSet * fds)691 static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
692         Timer *t = TIMER(u);
693 
694         assert(u);
695         assert(key);
696         assert(value);
697         assert(fds);
698 
699         if (streq(key, "state")) {
700                 TimerState state;
701 
702                 state = timer_state_from_string(value);
703                 if (state < 0)
704                         log_unit_debug(u, "Failed to parse state value: %s", value);
705                 else
706                         t->deserialized_state = state;
707 
708         } else if (streq(key, "result")) {
709                 TimerResult f;
710 
711                 f = timer_result_from_string(value);
712                 if (f < 0)
713                         log_unit_debug(u, "Failed to parse result value: %s", value);
714                 else if (f != TIMER_SUCCESS)
715                         t->result = f;
716 
717         } else if (streq(key, "last-trigger-realtime"))
718                 (void) deserialize_usec(value, &t->last_trigger.realtime);
719         else if (streq(key, "last-trigger-monotonic"))
720                 (void) deserialize_usec(value, &t->last_trigger.monotonic);
721         else
722                 log_unit_debug(u, "Unknown serialization key: %s", key);
723 
724         return 0;
725 }
726 
timer_active_state(Unit * u)727 _pure_ static UnitActiveState timer_active_state(Unit *u) {
728         assert(u);
729 
730         return state_translation_table[TIMER(u)->state];
731 }
732 
timer_sub_state_to_string(Unit * u)733 _pure_ static const char *timer_sub_state_to_string(Unit *u) {
734         assert(u);
735 
736         return timer_state_to_string(TIMER(u)->state);
737 }
738 
timer_dispatch(sd_event_source * s,uint64_t usec,void * userdata)739 static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
740         Timer *t = TIMER(userdata);
741 
742         assert(t);
743 
744         if (t->state != TIMER_WAITING)
745                 return 0;
746 
747         log_unit_debug(UNIT(t), "Timer elapsed.");
748         timer_enter_running(t);
749         return 0;
750 }
751 
timer_trigger_notify(Unit * u,Unit * other)752 static void timer_trigger_notify(Unit *u, Unit *other) {
753         Timer *t = TIMER(u);
754 
755         assert(u);
756         assert(other);
757 
758         /* Filter out invocations with bogus state */
759         assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
760 
761         /* Reenable all timers that depend on unit state */
762         LIST_FOREACH(value, v, t->values)
763                 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
764                         v->disabled = false;
765 
766         switch (t->state) {
767 
768         case TIMER_WAITING:
769         case TIMER_ELAPSED:
770 
771                 /* Recalculate sleep time */
772                 timer_enter_waiting(t, false);
773                 break;
774 
775         case TIMER_RUNNING:
776 
777                 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
778                         log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
779                         timer_enter_waiting(t, false);
780                 }
781                 break;
782 
783         case TIMER_DEAD:
784         case TIMER_FAILED:
785                 break;
786 
787         default:
788                 assert_not_reached();
789         }
790 }
791 
timer_reset_failed(Unit * u)792 static void timer_reset_failed(Unit *u) {
793         Timer *t = TIMER(u);
794 
795         assert(t);
796 
797         if (t->state == TIMER_FAILED)
798                 timer_set_state(t, TIMER_DEAD);
799 
800         t->result = TIMER_SUCCESS;
801 }
802 
timer_time_change(Unit * u)803 static void timer_time_change(Unit *u) {
804         Timer *t = TIMER(u);
805         usec_t ts;
806 
807         assert(u);
808 
809         if (t->state != TIMER_WAITING)
810                 return;
811 
812         /* If we appear to have triggered in the future, the system clock must
813          * have been set backwards.  So let's rewind our own clock and allow
814          * the future trigger(s) to happen again :).  Exactly the same as when
815          * you start a timer unit with Persistent=yes. */
816         ts = now(CLOCK_REALTIME);
817         if (t->last_trigger.realtime > ts)
818                 t->last_trigger.realtime = ts;
819 
820         if (t->on_clock_change) {
821                 log_unit_debug(u, "Time change, triggering activation.");
822                 timer_enter_running(t);
823         } else {
824                 log_unit_debug(u, "Time change, recalculating next elapse.");
825                 timer_enter_waiting(t, true);
826         }
827 }
828 
timer_timezone_change(Unit * u)829 static void timer_timezone_change(Unit *u) {
830         Timer *t = TIMER(u);
831 
832         assert(u);
833 
834         if (t->state != TIMER_WAITING)
835                 return;
836 
837         if (t->on_timezone_change) {
838                 log_unit_debug(u, "Timezone change, triggering activation.");
839                 timer_enter_running(t);
840         } else {
841                 log_unit_debug(u, "Timezone change, recalculating next elapse.");
842                 timer_enter_waiting(t, false);
843         }
844 }
845 
timer_clean(Unit * u,ExecCleanMask mask)846 static int timer_clean(Unit *u, ExecCleanMask mask) {
847         Timer *t = TIMER(u);
848         int r;
849 
850         assert(t);
851         assert(mask != 0);
852 
853         if (t->state != TIMER_DEAD)
854                 return -EBUSY;
855 
856         if (!IN_SET(mask, EXEC_CLEAN_STATE))
857                 return -EUNATCH;
858 
859         r = timer_setup_persistent(t);
860         if (r < 0)
861                 return r;
862 
863         if (!t->stamp_path)
864                 return -EUNATCH;
865 
866         if (unlink(t->stamp_path) && errno != ENOENT)
867                 return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
868 
869         return 0;
870 }
871 
timer_can_clean(Unit * u,ExecCleanMask * ret)872 static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
873         Timer *t = TIMER(u);
874 
875         assert(t);
876 
877         *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
878         return 0;
879 }
880 
timer_can_start(Unit * u)881 static int timer_can_start(Unit *u) {
882         Timer *t = TIMER(u);
883         int r;
884 
885         assert(t);
886 
887         r = unit_test_start_limit(u);
888         if (r < 0) {
889                 timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
890                 return r;
891         }
892 
893         return 1;
894 }
895 
896 static const char* const timer_base_table[_TIMER_BASE_MAX] = {
897         [TIMER_ACTIVE]        = "OnActiveSec",
898         [TIMER_BOOT]          = "OnBootSec",
899         [TIMER_STARTUP]       = "OnStartupSec",
900         [TIMER_UNIT_ACTIVE]   = "OnUnitActiveSec",
901         [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
902         [TIMER_CALENDAR]      = "OnCalendar"
903 };
904 
905 DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
906 
907 static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
908         [TIMER_SUCCESS]                 = "success",
909         [TIMER_FAILURE_RESOURCES]       = "resources",
910         [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
911 };
912 
913 DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
914 
915 const UnitVTable timer_vtable = {
916         .object_size = sizeof(Timer),
917 
918         .sections =
919                 "Unit\0"
920                 "Timer\0"
921                 "Install\0",
922         .private_section = "Timer",
923 
924         .can_transient = true,
925         .can_fail = true,
926         .can_trigger = true,
927 
928         .init = timer_init,
929         .done = timer_done,
930         .load = timer_load,
931 
932         .coldplug = timer_coldplug,
933 
934         .dump = timer_dump,
935 
936         .start = timer_start,
937         .stop = timer_stop,
938 
939         .clean = timer_clean,
940         .can_clean = timer_can_clean,
941 
942         .serialize = timer_serialize,
943         .deserialize_item = timer_deserialize_item,
944 
945         .active_state = timer_active_state,
946         .sub_state_to_string = timer_sub_state_to_string,
947 
948         .trigger_notify = timer_trigger_notify,
949 
950         .reset_failed = timer_reset_failed,
951         .time_change = timer_time_change,
952         .timezone_change = timer_timezone_change,
953 
954         .bus_set_property = bus_timer_set_property,
955 
956         .can_start = timer_can_start,
957 };
958