systemctl.c 192 KB
Newer Older
1
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

/***
  This file is part of systemd.

  Copyright 2010 Lennart Poettering

  systemd is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/

22
#include <sys/reboot.h>
23 24 25 26 27 28 29 30
#include <stdio.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
31
#include <fcntl.h>
32
#include <sys/socket.h>
33
#include <sys/stat.h>
34
#include <stddef.h>
35
#include <sys/prctl.h>
36 37 38 39 40 41 42

#include <dbus/dbus.h>

#include "log.h"
#include "util.h"
#include "macro.h"
#include "set.h"
43
#include "utmp-wtmp.h"
44
#include "special.h"
45
#include "initreq.h"
46
#include "strv.h"
47
#include "dbus-common.h"
48
#include "cgroup-show.h"
49
#include "cgroup-util.h"
50
#include "list.h"
51 52 53
#include "path-lookup.h"
#include "conf-parser.h"
#include "sd-daemon.h"
54
#include "shutdownd.h"
55
#include "exit-status.h"
56
#include "bus-errors.h"
57
#include "build.h"
58
#include "unit-name.h"
59 60

static const char *arg_type = NULL;
61
static char **arg_property = NULL;
62
static bool arg_all = false;
63
static const char *arg_job_mode = "replace";
64
static bool arg_user = false;
65
static bool arg_global = false;
66
static bool arg_immediate = false;
67
static bool arg_no_block = false;
68
static bool arg_no_pager = false;
69 70
static bool arg_no_wtmp = false;
static bool arg_no_sync = false;
71
static bool arg_no_wall = false;
72
static bool arg_no_reload = false;
73
static bool arg_dry = false;
74
static bool arg_quiet = false;
75 76 77
static bool arg_full = false;
static bool arg_force = false;
static bool arg_defaults = false;
78
static bool arg_ask_password = false;
79
static bool arg_failed = false;
80
static char **arg_wall = NULL;
81 82 83
static const char *arg_kill_who = NULL;
static const char *arg_kill_mode = NULL;
static int arg_signal = SIGTERM;
84
static usec_t arg_when = 0;
85
static enum action {
86 87 88 89 90
        ACTION_INVALID,
        ACTION_SYSTEMCTL,
        ACTION_HALT,
        ACTION_POWEROFF,
        ACTION_REBOOT,
91 92
        ACTION_KEXEC,
        ACTION_EXIT,
93 94 95 96 97
        ACTION_RUNLEVEL2,
        ACTION_RUNLEVEL3,
        ACTION_RUNLEVEL4,
        ACTION_RUNLEVEL5,
        ACTION_RESCUE,
98 99
        ACTION_EMERGENCY,
        ACTION_DEFAULT,
100 101 102
        ACTION_RELOAD,
        ACTION_REEXEC,
        ACTION_RUNLEVEL,
103
        ACTION_CANCEL_SHUTDOWN,
104 105
        _ACTION_MAX
} arg_action = ACTION_SYSTEMCTL;
106 107 108 109 110
static enum dot {
        DOT_ALL,
        DOT_ORDER,
        DOT_REQUIRE
} arg_dot = DOT_ALL;
111 112 113 114 115 116
static enum transport {
        TRANSPORT_NORMAL,
        TRANSPORT_SSH,
        TRANSPORT_POLKIT
} arg_transport = TRANSPORT_NORMAL;
static const char *arg_host = NULL;
117

118 119
static bool private_bus = false;

120
static pid_t pager_pid = 0;
121
static pid_t agent_pid = 0;
122

123
static int daemon_reload(DBusConnection *bus, char **args, unsigned n);
124
static void pager_open(void);
125

126
static bool on_tty(void) {
127 128
        static int t = -1;

129 130 131
        /* Note that this is invoked relatively early, before we start
         * the pager. That means the value we return reflects whether
         * we originally were started on a tty, not if we currently
132
         * are. But this is intended, since we want colour and so on
133 134
         * when run in our own pager. */

135 136 137
        if (_unlikely_(t < 0))
                t = isatty(STDOUT_FILENO) > 0;

138 139 140
        return t;
}

141
static void spawn_ask_password_agent(void) {
142 143 144 145
        pid_t parent;

        if (agent_pid > 0)
                return;
146 147 148 149 150 151 152 153

        /* We check STDIN here, not STDOUT, since this is about input,
         * not output */
        if (!isatty(STDIN_FILENO))
                return;

        if (!arg_ask_password)
                return;
154 155 156

        if (arg_user)
                return;
157 158 159 160 161 162

        parent = getpid();

        /* Spawns a temporary TTY agent, making sure it goes away when
         * we go away */

163
        if ((agent_pid = fork()) < 0)
164 165
                return;

166
        if (agent_pid == 0) {
167 168
                /* In the child */

169
                int fd;
170
                bool stdout_is_tty, stderr_is_tty;
171 172

                /* Make sure the agent goes away when the parent dies */
173 174 175 176 177 178 179 180
                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
                        _exit(EXIT_FAILURE);

                /* Check whether our parent died before we were able
                 * to set the death signal */
                if (getppid() != parent)
                        _exit(EXIT_SUCCESS);

181 182 183
                /* Don't leak fds to the agent */
                close_all_fds(NULL, 0);

184 185 186 187
                stdout_is_tty = isatty(STDOUT_FILENO);
                stderr_is_tty = isatty(STDERR_FILENO);

                if (!stdout_is_tty || !stderr_is_tty) {
188 189 190 191 192 193 194 195 196 197 198 199
                        /* Detach from stdout/stderr. and reopen
                         * /dev/tty for them. This is important to
                         * ensure that when systemctl is started via
                         * popen() or a similar call that expects to
                         * read EOF we actually do generate EOF and
                         * not delay this indefinitely by because we
                         * keep an unused copy of stdin around. */
                        if ((fd = open("/dev/tty", O_WRONLY)) < 0) {
                                log_error("Failed to open /dev/tty: %m");
                                _exit(EXIT_FAILURE);
                        }

200
                        if (!stdout_is_tty)
201 202
                                dup2(fd, STDOUT_FILENO);

203
                        if (!stderr_is_tty)
204 205 206 207
                                dup2(fd, STDERR_FILENO);

                        if (fd > 2)
                                close(fd);
208 209
                }

210 211 212
                execl(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);

                log_error("Unable to execute agent: %m");
213 214 215 216
                _exit(EXIT_FAILURE);
        }
}

217 218 219
static const char *ansi_highlight(bool b) {

        if (!on_tty())
220 221 222 223 224
                return "";

        return b ? ANSI_HIGHLIGHT_ON : ANSI_HIGHLIGHT_OFF;
}

225 226 227 228 229 230 231 232
static const char *ansi_highlight_green(bool b) {

        if (!on_tty())
                return "";

        return b ? ANSI_HIGHLIGHT_GREEN_ON : ANSI_HIGHLIGHT_OFF;
}

233
static bool error_is_no_service(const DBusError *error) {
234 235
        assert(error);

236 237 238 239 240 241 242 243 244 245 246
        if (!dbus_error_is_set(error))
                return false;

        if (dbus_error_has_name(error, DBUS_ERROR_NAME_HAS_NO_OWNER))
                return true;

        if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN))
                return true;

        return startswith(error->name, "org.freedesktop.DBus.Error.Spawn.");
}
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
static int translate_bus_error_to_exit_status(int r, const DBusError *error) {
        assert(error);

        if (!dbus_error_is_set(error))
                return r;

        if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED) ||
            dbus_error_has_name(error, BUS_ERROR_ONLY_BY_DEPENDENCY) ||
            dbus_error_has_name(error, BUS_ERROR_NO_ISOLATION) ||
            dbus_error_has_name(error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE))
                return EXIT_NOPERMISSION;

        if (dbus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT))
                return EXIT_NOTINSTALLED;

        if (dbus_error_has_name(error, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE) ||
            dbus_error_has_name(error, BUS_ERROR_NOT_SUPPORTED))
                return EXIT_NOTIMPLEMENTED;

        if (dbus_error_has_name(error, BUS_ERROR_LOAD_FAILED))
                return EXIT_NOTCONFIGURED;

        if (r != 0)
                return r;

        return EXIT_FAILURE;
}

276 277
static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {

278 279 280
        assert(iter);
        assert(data);

281 282 283 284 285 286 287 288 289 290 291
        if (dbus_message_iter_get_arg_type(iter) != type)
                return -EIO;

        dbus_message_iter_get_basic(iter, data);

        if (!dbus_message_iter_next(iter) != !next)
                return -EIO;

        return 0;
}

292
static void warn_wall(enum action action) {
293
        static const char *table[_ACTION_MAX] = {
294 295 296
                [ACTION_HALT]      = "The system is going down for system halt NOW!",
                [ACTION_REBOOT]    = "The system is going down for reboot NOW!",
                [ACTION_POWEROFF]  = "The system is going down for power-off NOW!",
297
                [ACTION_KEXEC]     = "The system is going down for kexec reboot NOW!",
298 299
                [ACTION_RESCUE]    = "The system is going down to rescue mode NOW!",
                [ACTION_EMERGENCY] = "The system is going down to emergency mode NOW!"
300 301
        };

302 303 304
        if (arg_no_wall)
                return;

305 306 307 308 309 310 311 312 313
        if (arg_wall) {
                char *p;

                if (!(p = strv_join(arg_wall, " "))) {
                        log_error("Failed to join strings.");
                        return;
                }

                if (*p) {
314
                        utmp_wall(p, NULL);
315 316 317 318 319 320 321
                        free(p);
                        return;
                }

                free(p);
        }

322
        if (!table[action])
323 324
                return;

325
        utmp_wall(table[action], NULL);
326 327
}

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
struct unit_info {
        const char *id;
        const char *description;
        const char *load_state;
        const char *active_state;
        const char *sub_state;
        const char *following;
        const char *unit_path;
        uint32_t job_id;
        const char *job_type;
        const char *job_path;
};

static int compare_unit_info(const void *a, const void *b) {
        const char *d1, *d2;
        const struct unit_info *u = a, *v = b;

        d1 = strrchr(u->id, '.');
        d2 = strrchr(v->id, '.');

        if (d1 && d2) {
                int r;

351
                if ((r = strcasecmp(d1, d2)) != 0)
352 353 354
                        return r;
        }

355
        return strcasecmp(u->id, v->id);
356 357
}

358
static bool output_show_unit(const struct unit_info *u) {
359
        const char *dot;
360

361 362 363
        if (arg_failed)
                return streq(u->active_state, "failed");

364 365 366 367 368
        return (!arg_type || ((dot = strrchr(u->id, '.')) &&
                              streq(dot+1, arg_type))) &&
                (arg_all || !(streq(u->active_state, "inactive") || u->following[0]) || u->job_id > 0);
}

369
static void output_units_list(const struct unit_info *unit_infos, unsigned c) {
370
        unsigned active_len, sub_len, job_len, n_shown = 0;
371
        const struct unit_info *u;
372

373 374 375 376 377
        active_len = sizeof("ACTIVE")-1;
        sub_len = sizeof("SUB")-1;
        job_len = sizeof("JOB")-1;

        for (u = unit_infos; u < unit_infos + c; u++) {
378
                if (!output_show_unit(u))
379 380 381 382 383 384
                        continue;

                active_len = MAX(active_len, strlen(u->active_state));
                sub_len = MAX(sub_len, strlen(u->sub_state));
                if (u->job_id != 0)
                        job_len = MAX(job_len, strlen(u->job_type));
385 386
        }

387
        if (on_tty()) {
388 389
                printf("%-25s %-6s %-*s %-*s %-*s", "UNIT", "LOAD",
                       active_len, "ACTIVE", sub_len, "SUB", job_len, "JOB");
390
                if (columns() >= 80+12 || arg_full)
391
                        printf(" %s\n", "DESCRIPTION");
392
                else
393
                        printf("\n");
394 395
        }

396 397 398 399 400 401
        for (u = unit_infos; u < unit_infos + c; u++) {
                char *e;
                int a = 0, b = 0;
                const char *on_loaded, *off_loaded;
                const char *on_active, *off_active;

402
                if (!output_show_unit(u))
403 404
                        continue;

405 406
                n_shown++;

407 408
                if (!streq(u->load_state, "loaded") &&
                    !streq(u->load_state, "banned")) {
409 410 411 412 413 414 415 416 417 418
                        on_loaded = ansi_highlight(true);
                        off_loaded = ansi_highlight(false);
                } else
                        on_loaded = off_loaded = "";

                if (streq(u->active_state, "failed")) {
                        on_active = ansi_highlight(true);
                        off_active = ansi_highlight(false);
                } else
                        on_active = off_active = "";
419

420
                e = arg_full ? NULL : ellipsize(u->id, 25, 33);
421

422 423 424 425 426 427
                printf("%-25s %s%-6s%s %s%-*s %-*s%s%n",
                       e ? e : u->id,
                       on_loaded, u->load_state, off_loaded,
                       on_active, active_len, u->active_state,
                       sub_len, u->sub_state, off_active,
                       &a);
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
                free(e);

                a -= strlen(on_loaded) + strlen(off_loaded);
                a -= strlen(on_active) + strlen(off_active);

                if (u->job_id != 0)
                        printf(" %-*s", job_len, u->job_type);
                else
                        b = 1 + job_len;

                if (a + b + 1 < columns()) {
                        if (u->job_id == 0)
                                printf(" %-*s", job_len, "");

                        if (arg_full)
                                printf(" %s", u->description);
                        else
                                printf(" %.*s", columns() - a - b - 1, u->description);
447
                }
448 449

                fputs("\n", stdout);
450 451
        }

452
        if (on_tty()) {
453 454 455 456 457 458
                printf("\nLOAD   = Reflects whether the unit definition was properly loaded.\n"
                       "ACTIVE = The high-level unit activation state, i.e. generalization of SUB.\n"
                       "SUB    = The low-level unit activation state, values depend on unit type.\n"
                       "JOB    = Pending job for the unit.\n");

                if (arg_all)
459
                        printf("\n%u units listed.\n", n_shown);
460
                else
461
                        printf("\n%u units listed. Pass --all to see inactive units, too.\n", n_shown);
462 463 464
        }
}

465 466 467 468 469
static int list_units(DBusConnection *bus, char **args, unsigned n) {
        DBusMessage *m = NULL, *reply = NULL;
        DBusError error;
        int r;
        DBusMessageIter iter, sub, sub2;
470
        unsigned c = 0, n_units = 0;
471
        struct unit_info *unit_infos = NULL;
472 473 474

        dbus_error_init(&error);

475 476
        assert(bus);

477 478
        pager_open();

479 480 481 482 483 484 485 486 487 488
        if (!(m = dbus_message_new_method_call(
                              "org.freedesktop.systemd1",
                              "/org/freedesktop/systemd1",
                              "org.freedesktop.systemd1.Manager",
                              "ListUnits"))) {
                log_error("Could not allocate message.");
                return -ENOMEM;
        }

        if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
489
                log_error("Failed to issue method call: %s", bus_error_message(&error));
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
                r = -EIO;
                goto finish;
        }

        if (!dbus_message_iter_init(reply, &iter) ||
            dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
            dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
                log_error("Failed to parse reply.");
                r = -EIO;
                goto finish;
        }

        dbus_message_iter_recurse(&iter, &sub);

        while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
505
                struct unit_info *u;
506 507 508 509 510 511 512

                if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
                if (c >= n_units) {
                        struct unit_info *w;

                        n_units = MAX(2*c, 16);
                        w = realloc(unit_infos, sizeof(struct unit_info) * n_units);

                        if (!w) {
                                log_error("Failed to allocate unit array.");
                                r = -ENOMEM;
                                goto finish;
                        }

                        unit_infos = w;
                }

                u = unit_infos+c;

530 531
                dbus_message_iter_recurse(&sub, &sub2);

532 533 534 535 536 537 538 539 540 541
                if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->id, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->description, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->load_state, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->active_state, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->sub_state, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->following, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->unit_path, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &u->job_id, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &u->job_type, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &u->job_path, false) < 0) {
542 543 544 545 546
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

547 548 549 550
                dbus_message_iter_next(&sub);
                c++;
        }

551 552 553 554
        if (c > 0) {
                qsort(unit_infos, c, sizeof(struct unit_info), compare_unit_info);
                output_units_list(unit_infos, c);
        }
555 556 557 558 559 560 561 562 563 564

        r = 0;

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

565 566
        free(unit_infos);

567 568 569 570 571 572 573 574 575 576 577 578 579
        dbus_error_free(&error);

        return r;
}

static int dot_one_property(const char *name, const char *prop, DBusMessageIter *iter) {
        static const char * const colors[] = {
                "Requires",              "[color=\"black\"]",
                "RequiresOverridable",   "[color=\"black\"]",
                "Requisite",             "[color=\"darkblue\"]",
                "RequisiteOverridable",  "[color=\"darkblue\"]",
                "Wants",                 "[color=\"darkgrey\"]",
                "Conflicts",             "[color=\"red\"]",
580
                "ConflictedBy",          "[color=\"red\"]",
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
                "After",                 "[color=\"green\"]"
        };

        const char *c = NULL;
        unsigned i;

        assert(name);
        assert(prop);
        assert(iter);

        for (i = 0; i < ELEMENTSOF(colors); i += 2)
                if (streq(colors[i], prop)) {
                        c = colors[i+1];
                        break;
                }

        if (!c)
                return 0;

        if (arg_dot != DOT_ALL)
                if ((arg_dot == DOT_ORDER) != streq(prop, "After"))
                        return 0;

        switch (dbus_message_iter_get_arg_type(iter)) {

        case DBUS_TYPE_ARRAY:

                if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
                        DBusMessageIter sub;

                        dbus_message_iter_recurse(iter, &sub);

                        while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
                                const char *s;

                                assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
                                dbus_message_iter_get_basic(&sub, &s);
                                printf("\t\"%s\"->\"%s\" %s;\n", name, s, c);

                                dbus_message_iter_next(&sub);
                        }

                        return 0;
                }
        }

        return 0;
}

static int dot_one(DBusConnection *bus, const char *name, const char *path) {
        DBusMessage *m = NULL, *reply = NULL;
        const char *interface = "org.freedesktop.systemd1.Unit";
        int r;
        DBusError error;
        DBusMessageIter iter, sub, sub2, sub3;

        assert(bus);
        assert(path);

        dbus_error_init(&error);

        if (!(m = dbus_message_new_method_call(
                              "org.freedesktop.systemd1",
                              path,
                              "org.freedesktop.DBus.Properties",
                              "GetAll"))) {
                log_error("Could not allocate message.");
                r = -ENOMEM;
                goto finish;
        }

        if (!dbus_message_append_args(m,
                                      DBUS_TYPE_STRING, &interface,
                                      DBUS_TYPE_INVALID)) {
                log_error("Could not append arguments to message.");
                r = -ENOMEM;
                goto finish;
        }

        if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
661
                log_error("Failed to issue method call: %s", bus_error_message(&error));
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
                r = -EIO;
                goto finish;
        }

        if (!dbus_message_iter_init(reply, &iter) ||
            dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
            dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_DICT_ENTRY)  {
                log_error("Failed to parse reply.");
                r = -EIO;
                goto finish;
        }

        dbus_message_iter_recurse(&iter, &sub);

        while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
                const char *prop;

                if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_DICT_ENTRY) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

                dbus_message_iter_recurse(&sub, &sub2);

                if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &prop, true) < 0) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

                if (dbus_message_iter_get_arg_type(&sub2) != DBUS_TYPE_VARIANT)  {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

                dbus_message_iter_recurse(&sub2, &sub3);

                if (dot_one_property(name, prop, &sub3)) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

                dbus_message_iter_next(&sub);
        }

710 711
        r = 0;

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

        dbus_error_free(&error);

        return r;
}

static int dot(DBusConnection *bus, char **args, unsigned n) {
        DBusMessage *m = NULL, *reply = NULL;
        DBusError error;
        int r;
        DBusMessageIter iter, sub, sub2;

        dbus_error_init(&error);

        assert(bus);

        if (!(m = dbus_message_new_method_call(
                              "org.freedesktop.systemd1",
                              "/org/freedesktop/systemd1",
                              "org.freedesktop.systemd1.Manager",
                              "ListUnits"))) {
                log_error("Could not allocate message.");
                return -ENOMEM;
        }

        if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
744
                log_error("Failed to issue method call: %s", bus_error_message(&error));
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
                r = -EIO;
                goto finish;
        }

        if (!dbus_message_iter_init(reply, &iter) ||
            dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
            dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
                log_error("Failed to parse reply.");
                r = -EIO;
                goto finish;
        }

        printf("digraph systemd {\n");

        dbus_message_iter_recurse(&iter, &sub);
        while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
761
                const char *id, *description, *load_state, *active_state, *sub_state, *following, *unit_path;
762 763 764 765 766 767 768 769 770 771 772 773 774 775

                if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

                dbus_message_iter_recurse(&sub, &sub2);

                if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &id, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &description, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &load_state, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &active_state, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &sub_state, true) < 0 ||
776
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &following, true) < 0 ||
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, true) < 0) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

                if ((r = dot_one(bus, id, unit_path)) < 0)
                        goto finish;

                /* printf("\t\"%s\";\n", id); */
                dbus_message_iter_next(&sub);
        }

        printf("}\n");

        log_info("   Color legend: black     = Requires\n"
                 "                 dark blue = Requisite\n"
                 "                 dark grey = Wants\n"
                 "                 red       = Conflicts\n"
                 "                 green     = After\n");

        if (isatty(fileno(stdout)))
                log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
                           "-- Try a shell pipeline like 'systemctl dot | dot -Tsvg > systemd.svg'!\n");
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824

        r = 0;

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

        dbus_error_free(&error);

        return r;
}

static int list_jobs(DBusConnection *bus, char **args, unsigned n) {
        DBusMessage *m = NULL, *reply = NULL;
        DBusError error;
        int r;
        DBusMessageIter iter, sub, sub2;
        unsigned k = 0;

        dbus_error_init(&error);

825 826
        assert(bus);

827 828
        pager_open();

829 830 831 832 833 834 835 836 837 838
        if (!(m = dbus_message_new_method_call(
                              "org.freedesktop.systemd1",
                              "/org/freedesktop/systemd1",
                              "org.freedesktop.systemd1.Manager",
                              "ListJobs"))) {
                log_error("Could not allocate message.");
                return -ENOMEM;
        }

        if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
839
                log_error("Failed to issue method call: %s", bus_error_message(&error));
840 841 842 843 844 845 846 847 848 849 850 851 852 853
                r = -EIO;
                goto finish;
        }

        if (!dbus_message_iter_init(reply, &iter) ||
            dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
            dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRUCT)  {
                log_error("Failed to parse reply.");
                r = -EIO;
                goto finish;
        }

        dbus_message_iter_recurse(&iter, &sub);

854 855
        if (isatty(STDOUT_FILENO))
                printf("%4s %-25s %-15s %-7s\n", "JOB", "UNIT", "TYPE", "STATE");
856 857 858 859

        while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
                const char *name, *type, *state, *job_path, *unit_path;
                uint32_t id;
860
                char *e;
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

                if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRUCT) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

                dbus_message_iter_recurse(&sub, &sub2);

                if (bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_UINT32, &id, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &name, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &type, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_STRING, &state, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &job_path, true) < 0 ||
                    bus_iter_get_basic_and_next(&sub2, DBUS_TYPE_OBJECT_PATH, &unit_path, false) < 0) {
                        log_error("Failed to parse reply.");
                        r = -EIO;
                        goto finish;
                }

881 882
                e = arg_full ? NULL : ellipsize(name, 25, 33);
                printf("%4u %-25s %-15s %-7s\n", id, e ? e : name, type, state);
883 884
                free(e);

885 886 887 888 889
                k++;

                dbus_message_iter_next(&sub);
        }

890 891 892
        if (isatty(STDOUT_FILENO))
                printf("\n%u jobs listed.\n", k);

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
        r = 0;

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

        dbus_error_free(&error);

        return r;
}

static int load_unit(DBusConnection *bus, char **args, unsigned n) {
        DBusMessage *m = NULL, *reply = NULL;
        DBusError error;
        int r;
        unsigned i;

        dbus_error_init(&error);

915 916 917
        assert(bus);
        assert(args);

918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
        for (i = 1; i < n; i++) {

                if (!(m = dbus_message_new_method_call(
                                      "org.freedesktop.systemd1",
                                      "/org/freedesktop/systemd1",
                                      "org.freedesktop.systemd1.Manager",
                                      "LoadUnit"))) {
                        log_error("Could not allocate message.");
                        r = -ENOMEM;
                        goto finish;
                }

                if (!dbus_message_append_args(m,
                                              DBUS_TYPE_STRING, &args[i],
                                              DBUS_TYPE_INVALID)) {
                        log_error("Could not append arguments to message.");
                        r = -ENOMEM;
                        goto finish;
                }

                if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
939
                        log_error("Failed to issue method call: %s", bus_error_message(&error));
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
                        r = -EIO;
                        goto finish;
                }

                dbus_message_unref(m);
                dbus_message_unref(reply);

                m = reply = NULL;
        }

        r = 0;

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

        dbus_error_free(&error);

        return r;
}

static int cancel_job(DBusConnection *bus, char **args, unsigned n) {
        DBusMessage *m = NULL, *reply = NULL;
        DBusError error;
        int r;
        unsigned i;

        dbus_error_init(&error);

972 973 974
        assert(bus);
        assert(args);

975 976 977
        if (n <= 1)
                return daemon_reload(bus, args, n);

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
        for (i = 1; i < n; i++) {
                unsigned id;
                const char *path;

                if (!(m = dbus_message_new_method_call(
                                      "org.freedesktop.systemd1",
                                      "/org/freedesktop/systemd1",
                                      "org.freedesktop.systemd1.Manager",
                                      "GetJob"))) {
                        log_error("Could not allocate message.");
                        r = -ENOMEM;
                        goto finish;
                }

                if ((r = safe_atou(args[i], &id)) < 0) {
                        log_error("Failed to parse job id: %s", strerror(-r));
                        goto finish;
                }

                assert_cc(sizeof(uint32_t) == sizeof(id));
                if (!dbus_message_append_args(m,
                                              DBUS_TYPE_UINT32, &id,
                                              DBUS_TYPE_INVALID)) {
                        log_error("Could not append arguments to message.");
                        r = -ENOMEM;
                        goto finish;
                }

                if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1007
                        log_error("Failed to issue method call: %s", bus_error_message(&error));
1008 1009 1010 1011 1012 1013 1014
                        r = -EIO;
                        goto finish;
                }

                if (!dbus_message_get_args(reply, &error,
                                           DBUS_TYPE_OBJECT_PATH, &path,
                                           DBUS_TYPE_INVALID)) {
1015
                        log_error("Failed to parse reply: %s", bus_error_message(&error));
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
                        r = -EIO;
                        goto finish;
                }

                dbus_message_unref(m);
                if (!(m = dbus_message_new_method_call(
                                      "org.freedesktop.systemd1",
                                      path,
                                      "org.freedesktop.systemd1.Job",
                                      "Cancel"))) {
                        log_error("Could not allocate message.");
                        r = -ENOMEM;
                        goto finish;
                }

                dbus_message_unref(reply);
                if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
1033
                        log_error("Failed to issue method call: %s", bus_error_message(&error));
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
                        r = -EIO;
                        goto finish;
                }

                dbus_message_unref(m);
                dbus_message_unref(reply);
                m = reply = NULL;
        }

        r = 0;

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

        dbus_error_free(&error);

        return r;
}

1057
static bool need_daemon_reload(DBusConnection *bus, const char *unit) {
1058
        DBusMessage *m = NULL, *reply = NULL;
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
        dbus_bool_t b = FALSE;
        DBusMessageIter iter, sub;
        const char
                *interface = "org.freedesktop.systemd1.Unit",
                *property = "NeedDaemonReload",
                *path;

        /* We ignore all errors here, since this is used to show a warning only */

        if (!(m = dbus_message_new_method_call(
                              "org.freedesktop.systemd1",
                              "/org/freedesktop/systemd1",
                              "org.freedesktop.systemd1.Manager",
                              "GetUnit")))
                goto finish;

        if (!dbus_message_append_args(m,
                                      DBUS_TYPE_STRING, &unit,
                                      DBUS_TYPE_INVALID))
                goto finish;

        if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
                goto finish;

        if (!dbus_message_get_args(reply, NULL,
                                   DBUS_TYPE_OBJECT_PATH, &path,
                                   DBUS_TYPE_INVALID))
                goto finish;

        dbus_message_unref(m);
        if (!(m = dbus_message_new_method_call(
                              "org.freedesktop.systemd1",
                              path,
                              "org.freedesktop.DBus.Properties",
                              "Get")))
                goto finish;

        if (!dbus_message_append_args(m,
                                      DBUS_TYPE_STRING, &interface,
                                      DBUS_TYPE_STRING, &property,
                                      DBUS_TYPE_INVALID)) {
                goto finish;
        }

        dbus_message_unref(reply);
        if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, NULL)))
                goto finish;

        if (!dbus_message_iter_init(reply, &iter) ||
            dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
                goto finish;

        dbus_message_iter_recurse(&iter, &sub);

        if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
                goto finish;

        dbus_message_iter_get_basic(&sub, &b);

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

        return b;
}

1128 1129
typedef struct WaitData {
        Set *set;
1130
        char *result;
1131 1132
} WaitData;

1133 1134
static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *message, void *data) {
        DBusError error;
1135
        WaitData *d = data;
1136 1137 1138

        assert(connection);
        assert(message);
1139
        assert(d);
1140 1141 1142

        dbus_error_init(&error);

1143 1144 1145 1146
        log_debug("Got D-Bus request: %s.%s() on %s",
                  dbus_message_get_interface(message),
                  dbus_message_get_member(message),
                  dbus_message_get_path(message));
1147 1148 1149 1150 1151 1152 1153

        if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
                log_error("Warning! D-Bus connection terminated.");
                dbus_connection_close(connection);

        } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
                uint32_t id;
1154
                const char *path, *result;
1155
                dbus_bool_t success = true;
1156

1157 1158 1159 1160 1161
                if (dbus_message_get_args(message, &error,
                                          DBUS_TYPE_UINT32, &id,
                                          DBUS_TYPE_OBJECT_PATH, &path,
                                          DBUS_TYPE_STRING, &result,
                                          DBUS_TYPE_INVALID)) {
1162 1163
                        char *p;

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
                        if ((p = set_remove(d->set, (char*) path)))
                                free(p);

                        if (*result)
                                d->result = strdup(result);

                        goto finish;
                }
#ifndef LEGACY
                dbus_error_free(&error);

                if (dbus_message_get_args(message, &error,
                                          DBUS_TYPE_UINT32, &id,
                                          DBUS_TYPE_OBJECT_PATH, &path,
                                          DBUS_TYPE_BOOLEAN, &success,
                                          DBUS_TYPE_INVALID)) {
                        char *p;

                        /* Compatibility with older systemd versions <
                         * 19 during upgrades. This should be dropped
                         * one day */

1186
                        if ((p = set_remove(d->set, (char*) path)))
1187
                                free(p);
1188 1189

                        if (!success)
1190 1191 1192
                                d->result = strdup("failed");

                        goto finish;
1193
                }
1194 1195 1196
#endif

                log_error("Failed to parse message: %s", bus_error_message(&error));
1197 1198
        }

1199
finish:
1200 1201 1202 1203
        dbus_error_free(&error);
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

1204
static int enable_wait_for_jobs(DBusConnection *bus) {
1205 1206 1207 1208
        DBusError error;

        assert(bus);

1209 1210 1211
        if (private_bus)
                return 0;

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        dbus_error_init(&error);
        dbus_bus_add_match(bus,
                           "type='signal',"
                           "sender='org.freedesktop.systemd1',"
                           "interface='org.freedesktop.systemd1.Manager',"
                           "member='JobRemoved',"
                           "path='/org/freedesktop/systemd1'",
                           &error);

        if (dbus_error_is_set(&error)) {
1222
                log_error("Failed to add match: %s", bus_error_message(&error));
1223 1224
                dbus_error_free(&error);
                return -EIO;
1225 1226
        }

1227
        /* This is slightly dirty, since we don't undo the match registrations. */
1228
        return 0;
1229 1230
}

1231 1232
static int wait_for_jobs(DBusConnection *bus, Set *s) {
        int r;
1233
        WaitData d;
1234 1235 1236 1237

        assert(bus);
        assert(s);

1238 1239 1240 1241
        zero(d);
        d.set = s;

        if (!dbus_connection_add_filter(bus, wait_filter, &d, NULL)) {
1242 1243 1244 1245 1246 1247 1248 1249 1250
                log_error("Failed to add filter.");
                r = -ENOMEM;
                goto finish;
        }

        while (!set_isempty(s) &&
               dbus_connection_read_write_dispatch(bus, -1))
                ;