[systemd-commits] 6 commits - fixme .gitignore Makefile.am src/install.c src/log.c src/log.h src/main.c src/mount.c src/notify.c src/sd-daemon.c src/sd-daemon.h src/service.c src/socket.c src/systemctl.c src/util.c src/util.h

Lennart Poettering lennart at kemper.freedesktop.org
Thu Jun 17 13:57:38 PDT 2010


 .gitignore      |    1 
 Makefile.am     |    9 
 fixme           |   14 
 src/install.c   |    3 
 src/log.c       |   47 ++
 src/log.h       |    7 
 src/main.c      |   68 +++-
 src/mount.c     |    8 
 src/notify.c    |  179 +++++++++++
 src/sd-daemon.c |    8 
 src/sd-daemon.h |   12 
 src/service.c   |  120 ++++---
 src/socket.c    |    8 
 src/systemctl.c |  898 +++++++++++++++++++++++++++++++++++++++++++++-----------
 src/util.c      |   23 +
 src/util.h      |    1 
 16 files changed, 1150 insertions(+), 256 deletions(-)

New commits:
commit e4b613402deb901741d910fc9442d6d4c1763951
Author: Lennart Poettering <lennart at poettering.net>
Date:   Thu Jun 17 22:57:28 2010 +0200

    systemctl: provide compatibility implementations for various sysv utilities

diff --git a/Makefile.am b/Makefile.am
index 197407c..d5ada98 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -369,6 +369,7 @@ systemd_cgroups_agent_LDADD = \
 
 systemctl_SOURCES = \
 	src/systemctl.c \
+	src/utmp-wtmp.c \
 	$(BASIC_SOURCES)
 
 systemctl_CFLAGS = $(AM_CFLAGS) $(DBUS_CFLAGS)
diff --git a/fixme b/fixme
index 7a443f4..db3dda8 100644
--- a/fixme
+++ b/fixme
@@ -57,6 +57,20 @@
 
 * selinux
 
+* User= and friends needs to understand %i and similar replacements
+
+* EnvironmentFile=
+
+* make systemd bus activatable
+
+* pin /cgroup/systemd
+
+* systemd-sysvinit as package
+
+* docdir für sd-daemon.[ch]
+
+* __attribute__ for sd_notifyf
+
 Regularly:
 
 * look for close() vs. close_nointr() vs. close_nointr_nofail()
diff --git a/src/systemctl.c b/src/systemctl.c
index 35ca082..850efe2 100644
--- a/src/systemctl.c
+++ b/src/systemctl.c
@@ -19,6 +19,7 @@
   along with systemd; If not, see <http://www.gnu.org/licenses/>.
 ***/
 
+#include <sys/reboot.h>
 #include <stdio.h>
 #include <getopt.h>
 #include <stdbool.h>
@@ -34,12 +35,49 @@
 #include "util.h"
 #include "macro.h"
 #include "set.h"
+#include "utmp-wtmp.h"
 
 static const char *arg_type = NULL;
 static bool arg_all = false;
 static bool arg_replace = false;
 static bool arg_session = false;
 static bool arg_block = false;
+static bool arg_immediate = false;
+static bool arg_no_wtmp = false;
+static bool arg_no_sync = false;
+static bool arg_dry = false;
+static char **arg_wall = NULL;
+enum action {
+        ACTION_INVALID,
+        ACTION_SYSTEMCTL,
+        ACTION_HALT,
+        ACTION_POWEROFF,
+        ACTION_REBOOT,
+        ACTION_RUNLEVEL1,
+        ACTION_RUNLEVEL2,
+        ACTION_RUNLEVEL3,
+        ACTION_RUNLEVEL4,
+        ACTION_RUNLEVEL5,
+        ACTION_RESCUE,
+        ACTION_RELOAD,
+        ACTION_REEXEC,
+        ACTION_RUNLEVEL,
+        _ACTION_MAX
+} arg_action = ACTION_SYSTEMCTL;
+
+static bool error_is_no_service(DBusError *error) {
+
+        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.");
+}
 
 static int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
 
@@ -76,6 +114,7 @@ static int columns(void) {
                 parsed_columns = 80;
 
         return parsed_columns;
+
 }
 
 static int list_units(DBusConnection *bus, char **args, unsigned n) {
@@ -526,147 +565,37 @@ finish:
         return r;
 }
 
-static int start_unit(DBusConnection *bus, char **args, unsigned n) {
-        DBusMessage *m = NULL, *reply = NULL;
-        DBusError error;
-        int r;
-        unsigned i;
-        const char *method, *mode;
-        char *p = NULL;
-        Set *s = NULL;
-
-        dbus_error_init(&error);
-
-        method =
-                streq(args[0], "start")  ? "StartUnit" :
-                streq(args[0], "stop")   ? "StopUnit" :
-                streq(args[0], "reload") ? "ReloadUnit" :
-                                           "RestartUnit";
-
-        mode = arg_replace ? "replace" : "fail";
-
-        if (arg_block) {
-                if ((r = enable_wait_for_jobs(bus)) < 0) {
-                        log_error("Could not watch jobs: %s", strerror(-r));
-                        goto finish;
-                }
-        }
-
-        for (i = 1; i < n; i++) {
-
-                if (!(m = dbus_message_new_method_call(
-                                      "org.freedesktop.systemd1",
-                                      "/org/freedesktop/systemd1",
-                                      "org.freedesktop.systemd1.Manager",
-                                      method))) {
-                        log_error("Could not allocate message.");
-                        r = -ENOMEM;
-                        goto finish;
-                }
-
-                if (!dbus_message_append_args(m,
-                                              DBUS_TYPE_STRING, &args[i],
-                                              DBUS_TYPE_STRING, &mode,
-                                              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))) {
-                        log_error("Failed to issue method call: %s", error.message);
-                        r = -EIO;
-                        goto finish;
-                }
-
-                if (arg_block) {
-                        const char *path;
-
-                        if (!dbus_message_get_args(reply, &error,
-                                                   DBUS_TYPE_OBJECT_PATH, &path,
-                                                   DBUS_TYPE_INVALID)) {
-                                log_error("Failed to parse reply: %s", error.message);
-                                r = -EIO;
-                                goto finish;
-                        }
-
-                        if (!s)
-                                if (!(s = set_new(string_hash_func, string_compare_func))) {
-                                        log_error("Failed to allocate set.");
-                                        r = -ENOMEM;
-                                        goto finish;
-                                }
-
-                        if (!(p = strdup(path))) {
-                                log_error("Failed to duplicate path.");
-                                r = -ENOMEM;
-                                goto finish;
-                        }
-
-                        if ((r = set_put(s, p)) < 0) {
-                                log_error("Failed to add path to set.");
-                                goto finish;
-                        }
-                        p = NULL;
-                }
-
-                dbus_message_unref(m);
-                dbus_message_unref(reply);
-
-                m = reply = NULL;
-        }
-
-        if (arg_block)
-                r = wait_for_jobs(bus, s);
-        else
-                r = 0;
-
-finish:
-        free(p);
-
-        if (s)
-                set_free_free(s);
-
-        if (m)
-                dbus_message_unref(m);
+static int start_unit_one(
+                DBusConnection *bus,
+                const char *method,
+                const char *name,
+                const char *mode,
+                Set *s) {
 
-        if (reply)
-                dbus_message_unref(reply);
-
-        dbus_error_free(&error);
-
-        return r;
-}
-
-static int isolate_unit(DBusConnection *bus, char **args, unsigned n) {
         DBusMessage *m = NULL, *reply = NULL;
         DBusError error;
         int r;
-        const char *mode = "isolate";
-        char *p = NULL;
-        Set *s = NULL;
 
-        dbus_error_init(&error);
+        assert(bus);
+        assert(method);
+        assert(name);
+        assert(mode);
+        assert(!arg_block || s);
 
-        if (arg_block) {
-                if ((r = enable_wait_for_jobs(bus)) < 0) {
-                        log_error("Could not watch jobs: %s", strerror(-r));
-                        goto finish;
-                }
-        }
+        dbus_error_init(&error);
 
         if (!(m = dbus_message_new_method_call(
                               "org.freedesktop.systemd1",
                               "/org/freedesktop/systemd1",
                               "org.freedesktop.systemd1.Manager",
-                              "StartUnit"))) {
+                              method))) {
                 log_error("Could not allocate message.");
                 r = -ENOMEM;
                 goto finish;
         }
 
         if (!dbus_message_append_args(m,
-                                      DBUS_TYPE_STRING, &args[1],
+                                      DBUS_TYPE_STRING, &name,
                                       DBUS_TYPE_STRING, &mode,
                                       DBUS_TYPE_INVALID)) {
                 log_error("Could not append arguments to message.");
@@ -675,6 +604,14 @@ static int isolate_unit(DBusConnection *bus, char **args, unsigned n) {
         }
 
         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
+
+                if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
+                        /* There's always a fallback possible for
+                         * legacy actions. */
+                        r = 0;
+                        goto finish;
+                }
+
                 log_error("Failed to issue method call: %s", error.message);
                 r = -EIO;
                 goto finish;
@@ -682,6 +619,7 @@ static int isolate_unit(DBusConnection *bus, char **args, unsigned n) {
 
         if (arg_block) {
                 const char *path;
+                char *p;
 
                 if (!dbus_message_get_args(reply, &error,
                                            DBUS_TYPE_OBJECT_PATH, &path,
@@ -691,12 +629,6 @@ static int isolate_unit(DBusConnection *bus, char **args, unsigned n) {
                         goto finish;
                 }
 
-                if (!(s = set_new(string_hash_func, string_compare_func))) {
-                        log_error("Failed to allocate set.");
-                        r = -ENOMEM;
-                        goto finish;
-                }
-
                 if (!(p = strdup(path))) {
                         log_error("Failed to duplicate path.");
                         r = -ENOMEM;
@@ -704,22 +636,15 @@ static int isolate_unit(DBusConnection *bus, char **args, unsigned n) {
                 }
 
                 if ((r = set_put(s, p)) < 0) {
+                        free(p);
                         log_error("Failed to add path to set.");
                         goto finish;
                 }
-                p = NULL;
-
-                r = wait_for_jobs(bus, s);
+        }
 
-        } else
-                r = 0;
+        r = 1;
 
 finish:
-        free(p);
-
-        if (s)
-                set_free_free(s);
-
         if (m)
                 dbus_message_unref(m);
 
@@ -731,6 +656,80 @@ finish:
         return r;
 }
 
+static int start_unit(DBusConnection *bus, char **args, unsigned n) {
+
+        static const char * const table[_ACTION_MAX] = {
+                [ACTION_HALT] = "halt.target",
+                [ACTION_POWEROFF] = "poweroff.target",
+                [ACTION_REBOOT] = "reboot.target",
+                [ACTION_RUNLEVEL1] = "runlevel1.target",
+                [ACTION_RUNLEVEL2] = "runlevel2.target",
+                [ACTION_RUNLEVEL3] = "runlevel3.target",
+                [ACTION_RUNLEVEL4] = "runlevel4.target",
+                [ACTION_RUNLEVEL5] = "runlevel5.target",
+                [ACTION_RESCUE] = "rescue.target"
+        };
+
+        int r;
+        unsigned i;
+        const char *method, *mode;
+        Set *s = NULL;
+
+        if (arg_action == ACTION_SYSTEMCTL) {
+                method =
+                        streq(args[0], "start")   ? "StartUnit" :
+                        streq(args[0], "stop")    ? "StopUnit" :
+                        streq(args[0], "reload")  ? "ReloadUnit" :
+                        streq(args[0], "restart") ? "RestartUnit" :
+                                     /* isolate */  "StartUnit";
+
+                mode =
+                        streq(args[0], "isolate") ? "isolate" :
+                                      arg_replace ? "replace" :
+                                                    "fail";
+
+                if (arg_block) {
+                        if ((r = enable_wait_for_jobs(bus)) < 0) {
+                                log_error("Could not watch jobs: %s", strerror(-r));
+                                goto finish;
+                        }
+
+                        if (!(s = set_new(string_hash_func, string_compare_func))) {
+                                log_error("Failed to allocate set.");
+                                r = -ENOMEM;
+                                goto finish;
+                        }
+                }
+        } else {
+                assert(arg_action < ELEMENTSOF(table));
+                assert(table[arg_action]);
+
+                method = "StartUnit";
+                mode = arg_action == ACTION_RESCUE ? "isolate" : "replace";
+        }
+
+        r = 0;
+
+        if (arg_action == ACTION_SYSTEMCTL) {
+                for (i = 1; i < n; i++)
+                        if ((r = start_unit_one(bus, method, args[i], mode, s)) < 0)
+                                goto finish;
+
+                if (arg_block)
+                        r = wait_for_jobs(bus, s);
+
+        } else {
+                if ((r = start_unit_one(bus, method, table[arg_action], mode, s)) <= 0)
+                        goto finish;
+        }
+
+finish:
+        if (s)
+                set_free_free(s);
+
+        return r;
+}
+
 static DBusHandlerResult monitor_filter(DBusConnection *connection, DBusMessage *message, void *data) {
         DBusError error;
         DBusMessage *m = NULL, *reply = NULL;
@@ -1110,11 +1109,19 @@ static int clear_jobs(DBusConnection *bus, char **args, unsigned n) {
 
         dbus_error_init(&error);
 
-        method =
-                streq(args[0], "clear-jobs")    ? "ClearJobs" :
-                streq(args[0], "daemon-reload") ? "Reload" :
-                streq(args[0], "daemon-reexec") ? "Reexecute" :
-                                                  "Exit";
+        if (arg_action == ACTION_RELOAD)
+                method = "Reload";
+        else if (arg_action == ACTION_REEXEC)
+                method = "Reexecute";
+        else {
+                assert(arg_action == ACTION_SYSTEMCTL);
+
+                method =
+                        streq(args[0], "clear-jobs")    ? "ClearJobs" :
+                        streq(args[0], "daemon-reload") ? "Reload" :
+                        streq(args[0], "daemon-reexec") ? "Reexecute" :
+                                                          "Exit";
+        }
 
         if (!(m = dbus_message_new_method_call(
                               "org.freedesktop.systemd1",
@@ -1126,12 +1133,20 @@ static int clear_jobs(DBusConnection *bus, char **args, unsigned n) {
         }
 
         if (!(reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) {
+
+                if (arg_action != ACTION_SYSTEMCTL && error_is_no_service(&error)) {
+                        /* There's always a fallback possible for
+                         * legacy actions. */
+                        r = 0;
+                        goto finish;
+                }
+
                 log_error("Failed to issue method call: %s", error.message);
                 r = -EIO;
                 goto finish;
         }
 
-        r = 0;
+        r = 1;
 
 finish:
         if (m)
@@ -1292,9 +1307,10 @@ finish:
         return r;
 }
 
-static int help(void) {
+static int systemctl_help(void) {
 
         printf("%s [options]\n\n"
+               "Send control commands to the init system.\n\n"
                "  -h --help      Show this help\n"
                "  -t --type=TYPE List only units of a particular type\n"
                "  -a --all       Show all units, including dead ones\n"
@@ -1327,13 +1343,75 @@ static int help(void) {
         return 0;
 }
 
-static int parse_argv(int argc, char *argv[]) {
+static int halt_help(void) {
+
+        printf("%s [options]\n\n"
+               "%s the system.\n\n"
+               "     --help      Show this help\n"
+               "     --halt      Halt the machine\n"
+               "  -p --poweroff  Switch off the machine\n"
+               "     --reboot    Reboot the machine\n"
+               "  -f --force     Force immediate reboot/halt/power-off\n"
+               "  -w --wtmp-only Don't reboot/halt/power-off, just write wtmp record\n"
+               "  -d --no-wtmp   Don't write wtmp record\n"
+               "  -n --no-sync   Don't sync before reboot/halt/power-off\n",
+               program_invocation_short_name,
+               arg_action == ACTION_REBOOT   ? "Reboot" :
+               arg_action == ACTION_POWEROFF ? "Power off" :
+                                               "Halt");
+
+        return 0;
+}
+
+static int shutdown_help(void) {
+
+        printf("%s [options] [TIME] [WALL...]\n\n"
+               "Shut down the system.\n\n"
+               "     --help      Show this help\n"
+               "  -H --halt      Halt the machine\n"
+               "  -P --poweroff  Power-off the machine\n"
+               "  -r --reboot    Reboot the machine\n"
+               "  -h             Equivalent to --poweroff, overriden by --halt\n"
+               "  -k             Don't reboot/halt/power-off, just send warnings\n",
+               program_invocation_short_name);
+
+        return 0;
+}
+
+static int telinit_help(void) {
+
+        printf("%s [options]\n\n"
+               "Send control commands to the init system.\n\n"
+               "     --help      Show this help\n\n"
+               "Commands:\n"
+               "  0              Power-off the machine\n"
+               "  6              Reboot the machine\n"
+               "  1, 2, 3, 4, 5  Start runlevelX.target unit\n"
+               "  s, S           Start the rescue.target unit\n"
+               "  q, Q           Ask systemd to reload its configuration\n"
+               "  u, U           Ask systemd to reexecute itself\n",
+               program_invocation_short_name);
+
+        return 0;
+}
+
+static int runlevel_help(void) {
+
+        printf("%s [options]\n\n"
+               "Prints the previous and current runlevel of the init system.\n\n"
+               "     --help      Show this help\n",
+               program_invocation_short_name);
+
+        return 0;
+}
+
+static int systemctl_parse_argv(int argc, char *argv[]) {
 
         enum {
                 ARG_REPLACE = 0x100,
                 ARG_SESSION,
                 ARG_SYSTEM,
-                ARG_BLOCK,
+                ARG_BLOCK
         };
 
         static const struct option options[] = {
@@ -1349,7 +1427,7 @@ static int parse_argv(int argc, char *argv[]) {
 
         int c;
 
-        assert(argc >= 1);
+        assert(argc >= 0);
         assert(argv);
 
         while ((c = getopt_long(argc, argv, "hta", options, NULL)) >= 0) {
@@ -1357,7 +1435,7 @@ static int parse_argv(int argc, char *argv[]) {
                 switch (c) {
 
                 case 'h':
-                        help();
+                        systemctl_help();
                         return 0;
 
                 case 't':
@@ -1396,7 +1474,328 @@ static int parse_argv(int argc, char *argv[]) {
         return 1;
 }
 
-int main(int argc, char*argv[]) {
+static int halt_parse_argv(int argc, char *argv[]) {
+
+        enum {
+                ARG_HELP = 0x100,
+                ARG_HALT,
+                ARG_REBOOT
+        };
+
+        static const struct option options[] = {
+                { "help",      no_argument,       NULL, ARG_HELP    },
+                { "halt",      no_argument,       NULL, ARG_HALT    },
+                { "poweroff",  no_argument,       NULL, 'p'         },
+                { "reboot",    no_argument,       NULL, ARG_REBOOT  },
+                { "force",     no_argument,       NULL, 'f'         },
+                { "wtmp-only", no_argument,       NULL, 'w'         },
+                { "no-wtmp",   no_argument,       NULL, 'd'         },
+                { "no-sync",   no_argument,       NULL, 'n'         },
+                { NULL,        0,                 NULL, 0           }
+        };
+
+        int c, runlevel;
+
+        assert(argc >= 0);
+        assert(argv);
+
+        if (utmp_get_runlevel(&runlevel, NULL) >= 0)
+                if (runlevel == '0' || runlevel == '6')
+                        arg_immediate = true;
+
+        while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) {
+                switch (c) {
+
+                case ARG_HELP:
+                        halt_help();
+                        return 0;
+
+                case ARG_HALT:
+                        arg_action = ACTION_HALT;
+                        break;
+
+                case 'p':
+                        arg_action = ACTION_POWEROFF;
+                        break;
+
+                case ARG_REBOOT:
+                        arg_action = ACTION_REBOOT;
+                        break;
+
+                case 'f':
+                        arg_immediate = true;
+                        break;
+
+                case 'w':
+                        arg_dry = true;
+                        break;
+
+                case 'd':
+                        arg_no_wtmp = true;
+                        break;
+
+                case 'n':
+                        arg_no_sync = true;
+                        break;
+
+                case 'i':
+                case 'h':
+                        /* Compatibility nops */
+                        break;
+
+                case '?':
+                        return -EINVAL;
+
+                default:
+                        log_error("Unknown option code %c", c);
+                        return -EINVAL;
+                }
+        }
+
+        if (optind < argc) {
+                log_error("Too many arguments.");
+                return -EINVAL;
+        }
+
+        return 1;
+}
+
+static int shutdown_parse_argv(int argc, char *argv[]) {
+
+        enum {
+                ARG_HELP = 0x100,
+        };
+
+        static const struct option options[] = {
+                { "help",      no_argument,       NULL, ARG_HELP    },
+                { "halt",      no_argument,       NULL, 'H'         },
+                { "poweroff",  no_argument,       NULL, 'P'         },
+                { "reboot",    no_argument,       NULL, 'r'         },
+                { NULL,        0,                 NULL, 0           }
+        };
+
+        int c;
+
+        assert(argc >= 0);
+        assert(argv);
+
+        while ((c = getopt_long(argc, argv, "HPrhkt:a", options, NULL)) >= 0) {
+                switch (c) {
+
+                case ARG_HELP:
+                        shutdown_help();
+                        return 0;
+
+                case 'H':
+                        arg_action = ACTION_HALT;
+                        break;
+
+                case 'P':
+                        arg_action = ACTION_POWEROFF;
+                        break;
+
+                case 'r':
+                        arg_action = ACTION_REBOOT;
+                        break;
+
+                case 'h':
+                        if (arg_action != ACTION_HALT)
+                                arg_action = ACTION_POWEROFF;
+                        break;
+
+                case 'k':
+                        arg_dry = true;
+                        break;
+
+                case 't':
+                case 'a':
+                        /* Compatibility nops */
+                        break;
+
+                case '?':
+                        return -EINVAL;
+
+                default:
+                        log_error("Unknown option code %c", c);
+                        return -EINVAL;
+                }
+        }
+
+        /* We ignore the time argument */
+        if (argc > optind + 1)
+                arg_wall = argv + optind + 1;
+
+        optind = argc;
+
+        return 1;
+
+}
+
+static int telinit_parse_argv(int argc, char *argv[]) {
+
+        enum {
+                ARG_HELP = 0x100,
+        };
+
+        static const struct option options[] = {
+                { "help",      no_argument,       NULL, ARG_HELP    },
+                { NULL,        0,                 NULL, 0           }
+        };
+
+        static const struct {
+                char from;
+                enum action to;
+        } table[] = {
+                { '0', ACTION_POWEROFF },
+                { '6', ACTION_REBOOT },
+                { '1', ACTION_RUNLEVEL1 },
+                { '2', ACTION_RUNLEVEL2 },
+                { '3', ACTION_RUNLEVEL3 },
+                { '4', ACTION_RUNLEVEL4 },
+                { '5', ACTION_RUNLEVEL5 },
+                { 's', ACTION_RESCUE },
+                { 'S', ACTION_RESCUE },
+                { 'q', ACTION_RELOAD },
+                { 'Q', ACTION_RELOAD },
+                { 'u', ACTION_REEXEC },
+                { 'U', ACTION_REEXEC }
+        };
+
+        unsigned i;
+        int c;
+
+        assert(argc >= 0);
+        assert(argv);
+
+        while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
+                switch (c) {
+
+                case ARG_HELP:
+                        telinit_help();
+                        return 0;
+
+                case '?':
+                        return -EINVAL;
+
+                default:
+                        log_error("Unknown option code %c", c);
+                        return -EINVAL;
+                }
+        }
+
+        if (optind >= argc) {
+                log_error("Argument missing.");
+                return -EINVAL;
+        }
+
+        if (optind + 1 < argc) {
+                log_error("Too many arguments.");
+                return -EINVAL;
+        }
+
+        if (strlen(argv[optind]) != 1) {
+                log_error("Expected single character argument.");
+                return -EINVAL;
+        }
+
+        for (i = 0; i < ELEMENTSOF(table); i++)
+                if (table[i].from == argv[optind][0])
+                        break;
+
+        if (i >= ELEMENTSOF(table)) {
+                log_error("Unknown command %s.", argv[optind]);
+                return -EINVAL;
+        }
+
+        arg_action = table[i].to;
+
+        optind ++;
+
+        return 1;
+}
+
+static int runlevel_parse_argv(int argc, char *argv[]) {
+
+        enum {
+                ARG_HELP = 0x100,
+        };
+
+        static const struct option options[] = {
+                { "help",      no_argument,       NULL, ARG_HELP    },
+                { NULL,        0,                 NULL, 0           }
+        };
+
+        int c;
+
+        assert(argc >= 0);
+        assert(argv);
+
+        while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) {
+                switch (c) {
+
+                case ARG_HELP:
+                        runlevel_help();
+                        return 0;
+
+                case '?':
+                        return -EINVAL;
+
+                default:
+                        log_error("Unknown option code %c", c);
+                        return -EINVAL;
+                }
+        }
+
+        if (optind < argc) {
+                log_error("Too many arguments.");
+                return -EINVAL;
+        }
+
+        return 1;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+        assert(argc >= 0);
+        assert(argv);
+
+        if (program_invocation_short_name) {
+
+                if (strstr(program_invocation_short_name, "halt")) {
+                        arg_action = ACTION_HALT;
+                        return halt_parse_argv(argc, argv);
+                } else if (strstr(program_invocation_short_name, "poweroff")) {
+                        arg_action = ACTION_POWEROFF;
+                        return halt_parse_argv(argc, argv);
+                } else if (strstr(program_invocation_short_name, "reboot")) {
+                        arg_action = ACTION_REBOOT;
+                        return halt_parse_argv(argc, argv);
+                } else if (strstr(program_invocation_short_name, "shutdown")) {
+                        arg_action = ACTION_POWEROFF;
+                        return shutdown_parse_argv(argc, argv);
+                } else if (strstr(program_invocation_short_name, "init")) {
+                        arg_action = ACTION_INVALID;
+                        return telinit_parse_argv(argc, argv);
+                } else if (strstr(program_invocation_short_name, "runlevel")) {
+                        arg_action = ACTION_RUNLEVEL;
+                        return runlevel_parse_argv(argc, argv);
+                }
+        }
+
+        arg_action = ACTION_SYSTEMCTL;
+        return systemctl_parse_argv(argc, argv);
+}
+
+static int talk_upstart(DBusConnection *bus) {
+        log_error("Talking upstart");
+        return 0;
+}
+
+static int talk_initctl(void) {
+        log_error("Talking initctl");
+        return 0;
+}
+
+static int systemctl_main(DBusConnection *bus, int argc, char *argv[]) {
 
         static const struct {
                 const char* verb;
@@ -1417,7 +1816,7 @@ int main(int argc, char*argv[]) {
                 { "stop",              MORE,  2, start_unit      },
                 { "reload",            MORE,  2, start_unit      },
                 { "restart",           MORE,  2, start_unit      },
-                { "isolate",           EQUAL, 2, isolate_unit    },
+                { "isolate",           EQUAL, 2, start_unit      },
                 { "monitor",           EQUAL, 1, monitor         },
                 { "dump",              EQUAL, 1, dump            },
                 { "snapshot",          LESS,  2, snapshot        },
@@ -1429,23 +1828,12 @@ int main(int argc, char*argv[]) {
                 { "unset-environment", MORE,  2, set_environment },
         };
 
-        int r, retval = 1, left;
+        int left;
         unsigned i;
-        DBusConnection *bus = NULL;
-        DBusError error;
 
-        dbus_error_init(&error);
-
-        log_set_target(LOG_TARGET_CONSOLE);
-        log_set_max_level(LOG_INFO);
-        log_parse_environment();
-
-        if ((r = parse_argv(argc, argv)) < 0)
-                goto finish;
-        else if (r == 0) {
-                retval = 0;
-                goto finish;
-        }
+        assert(bus);
+        assert(argc >= 0);
+        assert(argv);
 
         left = argc - optind;
 
@@ -1459,7 +1847,7 @@ int main(int argc, char*argv[]) {
 
                 if (i >= ELEMENTSOF(verbs)) {
                         log_error("Unknown operation %s", argv[optind]);
-                        goto finish;
+                        return -EINVAL;
                 }
         }
 
@@ -1468,7 +1856,7 @@ int main(int argc, char*argv[]) {
         case EQUAL:
                 if (left != verbs[i].argc) {
                         log_error("Invalid number of arguments.");
-                        goto finish;
+                        return -EINVAL;
                 }
 
                 break;
@@ -1476,7 +1864,7 @@ int main(int argc, char*argv[]) {
         case MORE:
                 if (left < verbs[i].argc) {
                         log_error("Too few arguments.");
-                        goto finish;
+                        return -EINVAL;
                 }
 
                 break;
@@ -1484,7 +1872,7 @@ int main(int argc, char*argv[]) {
         case LESS:
                 if (left > verbs[i].argc) {
                         log_error("Too many arguments.");
-                        goto finish;
+                        return -EINVAL;
                 }
 
                 break;
@@ -1493,20 +1881,178 @@ int main(int argc, char*argv[]) {
                 assert_not_reached("Unknown comparison operator.");
         }
 
-        if (!(bus = dbus_bus_get(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error))) {
-                log_error("Failed to get D-Bus connection: %s", error.message);
+        return verbs[i].dispatch(bus, argv + optind, left);
+}
+
+static int reload_with_fallback(DBusConnection *bus) {
+        int r;
+
+        if (bus) {
+                /* First, try systemd via D-Bus. */
+                if ((r = clear_jobs(bus, NULL, 0)) > 0)
+                        return 0;
+        }
+
+        /* Nothing else worked, so let's try signals */
+        assert(arg_action == ACTION_RELOAD || arg_action == ACTION_REEXEC);
+
+        if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) {
+                log_error("kill() failed: %m");
+                return -errno;
+        }
+
+        return 0;
+}
+
+static int start_with_fallback(DBusConnection *bus) {
+        int r;
+
+        if (bus) {
+                /* First, try systemd via D-Bus. */
+                if ((r = start_unit(bus, NULL, 0)) > 0)
+                        return 0;
+
+                /* Hmm, talking to systemd via D-Bus didn't work. Then
+                 * let's try to talk to Upstart via D-Bus. */
+                if ((r = talk_upstart(bus)) > 0)
+                        return 0;
+        }
+
+        /* Nothing else worked, so let's try
+         * /dev/initctl */
+        return talk_initctl();
+}
+
+static int halt_main(DBusConnection *bus) {
+        int r;
+
+        if (!arg_immediate)
+                return start_with_fallback(bus);
+
+        if (!arg_no_wtmp)
+                if ((r = utmp_put_shutdown(0)) < 0)
+                        log_warning("Failed to write utmp record: %s", strerror(-r));
+
+        if (!arg_no_sync)
+                sync();
+
+        if (arg_dry)
+                return 0;
+
+        /* Make sure C-A-D is handled by the kernel from this
+         * point on... */
+        reboot(RB_ENABLE_CAD);
+
+        switch (arg_action) {
+
+        case ACTION_HALT:
+                log_info("Halting");
+                reboot(RB_HALT_SYSTEM);
+                break;
+
+        case ACTION_POWEROFF:
+                log_info("Powering off");
+                reboot(RB_POWER_OFF);
+                break;
+
+        case ACTION_REBOOT:
+                log_info("Rebooting");
+                reboot(RB_AUTOBOOT);
+                break;
+
+        default:
+                assert_not_reached("Unknown halt action.");
+        }
+
+        /* We should never reach this. */
+        return -ENOSYS;
+}
+
+static int runlevel_main(void) {
+        int r, runlevel, previous;
+
+        if ((r = utmp_get_runlevel(&runlevel, &previous)) < 0) {
+                printf("unknown");
+                return r;
+        }
+
+        printf("%c %c\n",
+               previous <= 0 ? 'N' : previous,
+               runlevel <= 0 ? 'N' : runlevel);
+
+        return 0;
+}
+
+int main(int argc, char*argv[]) {
+        int r, retval = 1;
+        DBusConnection *bus = NULL;
+        DBusError error;
+
+        dbus_error_init(&error);
+
+        log_parse_environment();
+
+        if ((r = parse_argv(argc, argv)) < 0)
+                goto finish;
+        else if (r == 0) {
+                retval = 0;
                 goto finish;
         }
 
-        dbus_connection_set_exit_on_disconnect(bus, FALSE);
+        /* /sbin/runlevel doesn't need to communicate via D-Bus, so
+         * let's shortcut this */
+        if (arg_action == ACTION_RUNLEVEL) {
+                retval = runlevel_main() < 0;
+                goto finish;
+        }
+
+        if ((bus = dbus_bus_get(arg_session ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error)))
+                dbus_connection_set_exit_on_disconnect(bus, FALSE);
+
+        switch (arg_action) {
+
+        case ACTION_SYSTEMCTL: {
+
+                if (!bus) {
+                        log_error("Failed to get D-Bus connection: %s", error.message);
+                        goto finish;
+                }
+
+                retval = systemctl_main(bus, argc, argv) < 0;
+                break;
+        }
+
+        case ACTION_HALT:
+        case ACTION_POWEROFF:
+        case ACTION_REBOOT:
+                retval = halt_main(bus) < 0;
+                break;
+
+        case ACTION_RUNLEVEL1:
+        case ACTION_RUNLEVEL2:
+        case ACTION_RUNLEVEL3:
+        case ACTION_RUNLEVEL4:
+        case ACTION_RUNLEVEL5:
+        case ACTION_RESCUE:
+                retval = start_with_fallback(bus) < 0;
+                break;
 
-        retval = verbs[i].dispatch(bus, argv + optind, left) < 0;
+        case ACTION_RELOAD:
+        case ACTION_REEXEC:
+                retval = reload_with_fallback(bus) < 0;
+                break;
+
+        default:
+                assert_not_reached("Unknown action");
+        }
 
 finish:
 
         if (bus)
                 dbus_connection_unref(bus);
 
+        dbus_error_free(&error);
+
         dbus_shutdown();
 
         return retval;
commit 5925dd3c7ab771c86036b4a91640957e5d7a0e80
Author: Lennart Poettering <lennart at poettering.net>
Date:   Thu Jun 17 22:55:53 2010 +0200

    service: rework PID parsing logic everywhere

diff --git a/src/mount.c b/src/mount.c
index 4a38e95..ea81f5f 100644
--- a/src/mount.c
+++ b/src/mount.c
@@ -839,7 +839,7 @@ static int mount_serialize(Unit *u, FILE *f, FDSet *fds) {
         unit_serialize_item(u, f, "failure", yes_no(m->failure));
 
         if (m->control_pid > 0)
-                unit_serialize_item_format(u, f, "control-pid", "%u", (unsigned) m->control_pid);
+                unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) m->control_pid);
 
         if (m->control_command_id >= 0)
                 unit_serialize_item(u, f, "control-command", mount_exec_command_to_string(m->control_command_id));
@@ -872,12 +872,12 @@ static int mount_deserialize_item(Unit *u, const char *key, const char *value, F
                         m->failure = b || m->failure;
 
         } else if (streq(key, "control-pid")) {
-                unsigned pid;
+                pid_t pid;
 
-                if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
+                if ((r = parse_pid(value, &pid)) < 0)
                         log_debug("Failed to parse control-pid value %s", value);
                 else
-                        m->control_pid = (pid_t) pid;
+                        m->control_pid = pid;
         } else if (streq(key, "control-command")) {
                 MountExecCommand id;
 
diff --git a/src/service.c b/src/service.c
index a38c880..fe91b92 100644
--- a/src/service.c
+++ b/src/service.c
@@ -125,6 +125,35 @@ static void service_unwatch_main_pid(Service *s) {
         s->main_pid = 0;
 }
 
+static int service_set_main_pid(Service *s, pid_t pid) {
+        assert(s);
+
+        if (pid <= 1)
+                return -EINVAL;
+
+        if (pid == getpid())
+                return -EINVAL;
+
+        s->main_pid = pid;
+        s->main_pid_known = true;
+
+        return 0;
+}
+
+static int service_set_control_pid(Service *s, pid_t pid) {
+        assert(s);
+
+        if (pid <= 1)
+                return -EINVAL;
+
+        if (pid == getpid())
+                return -EINVAL;
+
+        s->control_pid = pid;
+
+        return 0;
+}
+
 static void service_close_socket_fd(Service *s) {
         assert(s);
 
@@ -919,8 +948,8 @@ static void service_dump(Unit *u, FILE *f, const char *prefix) {
 
 static int service_load_pid_file(Service *s) {
         char *k;
-        unsigned long p;
         int r;
+        pid_t pid;
 
         assert(s);
 
@@ -935,29 +964,24 @@ static int service_load_pid_file(Service *s) {
         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
                 return r;
 
-        if ((r = safe_atolu(k, &p)) < 0) {
-                free(k);
-                return r;
-        }
-
-        if ((unsigned long) (pid_t) p != p)
-                return -ERANGE;
+        r = parse_pid(k, &pid);
+        free(k);
 
-        if (p <= 1)
-                return -ERANGE;
+        if (r < 0)
+                return r;
 
-        if (kill((pid_t) p, 0) < 0 && errno != EPERM) {
-                log_warning("PID %llu read from file %s does not exist. Your service or init script might be broken.",
-                            (unsigned long long) p, s->pid_file);
+        if (kill(pid, 0) < 0 && errno != EPERM) {
+                log_warning("PID %lu read from file %s does not exist. Your service or init script might be broken.",
+                            (unsigned long) pid, s->pid_file);
                 return -ESRCH;
         }
 
-        if ((r = unit_watch_pid(UNIT(s), (pid_t) p)) < 0)
-                /* FIXME: we need to do something here */
+        if ((r = service_set_main_pid(s, pid)) < 0)
                 return r;
 
-        s->main_pid = (pid_t) p;
-        s->main_pid_known = true;
+        if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
+                /* FIXME: we need to do something here */
+                return r;
 
         return 0;
 }
@@ -1460,6 +1484,8 @@ fail:
 
 static void service_enter_stop(Service *s, bool success) {
         int r;
+        pid_t pid;
+
         assert(s);
 
         if (!success)
@@ -1475,9 +1501,10 @@ static void service_enter_stop(Service *s, bool success) {
                                        false,
                                        !s->permissions_start_only,
                                        !s->root_directory_start_only,
-                                       &s->control_pid)) < 0)
+                                       &pid)) < 0)
                         goto fail;
 
+                service_set_control_pid(s, pid);
                 service_set_state(s, SERVICE_STOP);
         } else
                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
@@ -1507,6 +1534,7 @@ static void service_enter_running(Service *s, bool success) {
 
 static void service_enter_start_post(Service *s) {
         int r;
+        pid_t pid;
         assert(s);
 
         service_unwatch_control_pid(s);
@@ -1519,10 +1547,10 @@ static void service_enter_start_post(Service *s) {
                                        false,
                                        !s->permissions_start_only,
                                        !s->root_directory_start_only,
-                                       &s->control_pid)) < 0)
+                                       &pid)) < 0)
                         goto fail;
 
-
+                service_set_control_pid(s, pid);
                 service_set_state(s, SERVICE_START_POST);
         } else
                 service_enter_running(s, true);
@@ -1561,9 +1589,7 @@ static void service_enter_start(Service *s) {
                 /* For simple services we immediately start
                  * the START_POST binaries. */
 
-                s->main_pid = pid;
-                s->main_pid_known = true;
-
+                service_set_main_pid(s, pid);
                 service_enter_start_post(s);
 
         } else  if (s->type == SERVICE_FORKING) {
@@ -1571,10 +1597,10 @@ static void service_enter_start(Service *s) {
                 /* For forking services we wait until the start
                  * process exited. */
 
-                s->control_pid = pid;
-
                 s->control_command_id = SERVICE_EXEC_START;
                 s->control_command = s->exec_command[SERVICE_EXEC_START];
+
+                service_set_control_pid(s, pid);
                 service_set_state(s, SERVICE_START);
 
         } else if (s->type == SERVICE_FINISH ||
@@ -1588,9 +1614,7 @@ static void service_enter_start(Service *s) {
                  * but wait for the bus name to appear on the
                  * bus. Notify services are similar. */
 
-                s->main_pid = pid;
-                s->main_pid_known = true;
-
+                service_set_main_pid(s, pid);
                 service_set_state(s, SERVICE_START);
         } else
                 assert_not_reached("Unknown service type");
@@ -1604,6 +1628,7 @@ fail:
 
 static void service_enter_start_pre(Service *s) {
         int r;
+        pid_t pid;
 
         assert(s);
 
@@ -1617,9 +1642,10 @@ static void service_enter_start_pre(Service *s) {
                                        false,
                                        !s->permissions_start_only,
                                        !s->root_directory_start_only,
-                                       &s->control_pid)) < 0)
+                                       &pid)) < 0)
                         goto fail;
 
+                service_set_control_pid(s, pid);
                 service_set_state(s, SERVICE_START_PRE);
         } else
                 service_enter_start(s);
@@ -1651,6 +1677,7 @@ fail:
 
 static void service_enter_reload(Service *s) {
         int r;
+        pid_t pid;
 
         assert(s);
 
@@ -1664,9 +1691,10 @@ static void service_enter_reload(Service *s) {
                                        false,
                                        !s->permissions_start_only,
                                        !s->root_directory_start_only,
-                                       &s->control_pid)) < 0)
+                                       &pid)) < 0)
                         goto fail;
 
+                service_set_control_pid(s, pid);
                 service_set_state(s, SERVICE_RELOAD);
         } else
                 service_enter_running(s, true);
@@ -1680,6 +1708,7 @@ fail:
 
 static void service_run_next(Service *s, bool success) {
         int r;
+        pid_t pid;
 
         assert(s);
         assert(s->control_command);
@@ -1698,9 +1727,10 @@ static void service_run_next(Service *s, bool success) {
                                false,
                                !s->permissions_start_only,
                                !s->root_directory_start_only,
-                               &s->control_pid)) < 0)
+                               &pid)) < 0)
                 goto fail;
 
+        service_set_control_pid(s, pid);
         return;
 
 fail:
@@ -1819,10 +1849,10 @@ static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
         unit_serialize_item(u, f, "failure", yes_no(s->failure));
 
         if (s->control_pid > 0)
-                unit_serialize_item_format(u, f, "control-pid", "%u", (unsigned) (s->control_pid));
+                unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
 
-        if (s->main_pid > 0)
-                unit_serialize_item_format(u, f, "main-pid", "%u", (unsigned) (s->main_pid));
+        if (s->main_pid_known && s->main_pid > 0)
+                unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
 
         unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
 
@@ -1868,19 +1898,19 @@ static int service_deserialize_item(Unit *u, const char *key, const char *value,
                 else
                         s->failure = b || s->failure;
         } else if (streq(key, "control-pid")) {
-                unsigned pid;
+                pid_t pid;
 
-                if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
+                if ((r = parse_pid(value, &pid)) < 0)
                         log_debug("Failed to parse control-pid value %s", value);
                 else
-                        s->control_pid = (pid_t) pid;
+                        service_set_control_pid(s, pid);
         } else if (streq(key, "main-pid")) {
-                unsigned pid;
+                pid_t pid;
 
-                if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
+                if ((r = parse_pid(value, &pid)) < 0)
                         log_debug("Failed to parse main-pid value %s", value);
                 else
-                        s->main_pid = (pid_t) pid;
+                        service_set_main_pid(s, (pid_t) pid);
         } else if (streq(key, "main-pid-known")) {
                 int b;
 
@@ -2219,15 +2249,13 @@ static void service_notify_message(Unit *u, char **tags) {
              s->state == SERVICE_START_POST ||
              s->state == SERVICE_RUNNING ||
              s->state == SERVICE_RELOAD)) {
-                unsigned long pid;
+                pid_t pid;
 
-                if (safe_atolu(e + 8, &pid) < 0 ||
-                    (unsigned long) (pid_t) pid != pid ||
-                    pid <= 1)
+                if (parse_pid(e + 8, &pid) < 0)
                         log_warning("Failed to parse %s", e);
                 else {
                         log_debug("%s: got %s", u->meta.id, e);
-                        s->main_pid = (pid_t) pid;
+                        service_set_main_pid(s, pid);
                 }
         }
 
@@ -2460,7 +2488,7 @@ static void service_bus_query_pid_done(
              s->state == SERVICE_START_POST ||
              s->state == SERVICE_RUNNING ||
              s->state == SERVICE_RELOAD))
-                s->main_pid = pid;
+                service_set_main_pid(s, pid);
 }
 
 int service_set_socket_fd(Service *s, int fd) {
diff --git a/src/socket.c b/src/socket.c
index 1852fe9..874cc91 100644
--- a/src/socket.c
+++ b/src/socket.c
@@ -1047,7 +1047,7 @@ static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
         unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
 
         if (s->control_pid > 0)
-                unit_serialize_item_format(u, f, "control-pid", "%u", (unsigned) s->control_pid);
+                unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
 
         if (s->control_command_id >= 0)
                 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
@@ -1110,12 +1110,12 @@ static int socket_deserialize_item(Unit *u, const char *key, const char *value,
                 else
                         s->n_accepted += k;
         } else if (streq(key, "control-pid")) {
-                unsigned pid;
+                pid_t pid;
 
-                if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
+                if ((r = parse_pid(value, &pid)) < 0)
                         log_debug("Failed to parse control-pid value %s", value);
                 else
-                        s->control_pid = (pid_t) pid;
+                        s->control_pid = pid;
         } else if (streq(key, "control-command")) {
                 SocketExecCommand id;
 
commit 08bfb8106b3a337ebf9a4bf3a8ddd2e494d18b48
Author: Lennart Poettering <lennart at poettering.net>
Date:   Thu Jun 17 22:53:55 2010 +0200

    sd-daemon: extend return value logic of sd_notify()

diff --git a/src/sd-daemon.c b/src/sd-daemon.c
index 0dad73f..e6b9a6f 100644
--- a/src/sd-daemon.c
+++ b/src/sd-daemon.c
@@ -344,10 +344,8 @@ int sd_notify(int unset_environment, const char *state) {
                 goto finish;
         }
 
-        if (!(e = getenv("NOTIFY_SOCKET"))) {
-                r = 0;
-                goto finish;
-        }
+        if (!(e = getenv("NOTIFY_SOCKET")))
+                return 0;
 
         /* Must be an abstract socket, or an absolute path */
         if ((e[0] != '@' && e[0] != '/') || e[1] == 0) {
@@ -394,7 +392,7 @@ int sd_notify(int unset_environment, const char *state) {
                 goto finish;
         }
 
-        r = 0;
+        r = 1;
 
 finish:
         if (unset_environment)
diff --git a/src/sd-daemon.h b/src/sd-daemon.h
index 0277b0f..2d79082 100644
--- a/src/sd-daemon.h
+++ b/src/sd-daemon.h
@@ -126,9 +126,9 @@ int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t
  *                 little value in signalling non-readiness the only
  *                 value daemons should send is "READY=1".
  *
- *    STATUS=...   Passes a status string back to systemd that
- *                 describes the daemon state. This is free-from and
- *                 can be used for various purposes: general state
+ *    STATUS=...   Passes a single-line status string back to systemd
+ *                 that describes the daemon state. This is free-from
+ *                 and can be used for various purposes: general state
  *                 feedback, fsck-like programs could pass completion
  *                 percentages and failing programs could pass a human
  *                 readable error message. Example: "STATUS=Completed
@@ -143,6 +143,12 @@ int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t
  *    MAINPID=...  The main pid of a daemon, in case systemd did not
  *                 fork off the process itself. Example: "MAINPID=4711"
  *
+ * Daemons can choose to send additional variables.
+ *
+ * Returns a negative errno-style error code on failure. Returns > 0
+ * if systemd could be notified, 0 if it couldn't possibly because
+ * systemd is not running.
+ *
  * See sd_notifyf() for more complete examples.
  */
 int sd_notify(int unset_environment, const char *state);
commit bbe63281ea16ed9899dd4818874098c05e36b154
Author: Lennart Poettering <lennart at poettering.net>
Date:   Thu Jun 17 22:52:55 2010 +0200

    log: make color/location logging optional

diff --git a/src/install.c b/src/install.c
index c3dbe8b..479a38c 100644
--- a/src/install.c
+++ b/src/install.c
@@ -60,6 +60,7 @@ Hashmap *will_install = NULL, *have_installed = NULL;
 static int help(void) {
 
         printf("%s [options]\n\n"
+               "Install init system units.\n\n"
                "  -h --help        Show this help\n"
                "     --force       Override existing links\n"
                "     --system      Install into system\n"
@@ -532,8 +533,6 @@ int main(int argc, char *argv[]) {
 
         zero(paths);
 
-        log_set_target(LOG_TARGET_CONSOLE);
-        log_set_max_level(LOG_INFO);
         log_parse_environment();
 
         if ((r = parse_argv(argc, argv)) < 0)
diff --git a/src/log.c b/src/log.c
index b7173eb..4f9f2da 100644
--- a/src/log.c
+++ b/src/log.c
@@ -35,12 +35,15 @@
 #define LOG_BUFFER_MAX 1024
 
 static LogTarget log_target = LOG_TARGET_CONSOLE;
-static int log_max_level = LOG_DEBUG;
+static int log_max_level = LOG_INFO;
 
 static int console_fd = STDERR_FILENO;
 static int syslog_fd = -1;
 static int kmsg_fd = -1;
 
+static bool show_color = false;
+static bool show_location = false;
+
 /* Akin to glibc's __abort_msg; which is private and we hance cannot
  * use here. */
 static char *log_abort_msg = NULL;
@@ -218,10 +221,11 @@ static int write_to_console(
         snprintf(location, sizeof(location), "(%s:%u) ", file, line);
         char_array_0(location);
 
-        highlight = LOG_PRI(level) <= LOG_ERR;
+        highlight = LOG_PRI(level) <= LOG_ERR && show_color;
 
         zero(iovec);
-        IOVEC_SET_STRING(iovec[n++], location);
+        if (show_location)
+                IOVEC_SET_STRING(iovec[n++], location);
         if (highlight)
                 IOVEC_SET_STRING(iovec[n++], "\x1B[1;31m");
         IOVEC_SET_STRING(iovec[n++], buffer);
@@ -469,6 +473,15 @@ void log_parse_environment(void) {
         if ((e = getenv("SYSTEMD_LOG_LEVEL")))
                 if (log_set_max_level_from_string(e) < 0)
                         log_warning("Failed to parse log level %s. Ignoring.", e);
+
+        if ((e = getenv("SYSTEMD_SHOW_COLOR")))
+                if (log_show_color_from_string(e) < 0)
+                        log_warning("Failed to parse bool %s. Ignoring.", e);
+
+        if ((e = getenv("SYSTEMD_SHOW_LOCATION"))) {
+                if (log_show_location_from_string(e) < 0)
+                        log_warning("Failed to parse bool %s. Ignoring.", e);
+        }
 }
 
 LogTarget log_get_target(void) {
@@ -479,6 +492,34 @@ int log_get_max_level(void) {
         return log_max_level;
 }
 
+void log_show_color(bool b) {
+        show_color = b;
+}
+
+void log_show_location(bool b) {
+        show_location = b;
+}
+
+int log_show_color_from_string(const char *e) {
+        int t;
+
+        if ((t = parse_boolean(e)) < 0)
+                return -EINVAL;
+
+        log_show_color(t);
+        return 0;
+}
+
+int log_show_location_from_string(const char *e) {
+        int t;
+
+        if ((t = parse_boolean(e)) < 0)
+                return -EINVAL;
+
+        log_show_location(t);
+        return 0;
+}
+
 static const char *const log_target_table[] = {
         [LOG_TARGET_CONSOLE] = "console",
         [LOG_TARGET_SYSLOG] = "syslog",
diff --git a/src/log.h b/src/log.h
index 1d9a100..ed9b8c8 100644
--- a/src/log.h
+++ b/src/log.h
@@ -23,6 +23,7 @@
 ***/
 
 #include <syslog.h>
+#include <stdbool.h>
 
 #include "macro.h"
 
@@ -44,6 +45,12 @@ void log_set_max_level(int level);
 int log_set_target_from_string(const char *e);
 int log_set_max_level_from_string(const char *e);
 
+void log_show_color(bool b);
+void log_show_location(bool b);
+
+int log_show_color_from_string(const char *e);
+int log_show_location_from_string(const char *e);
+
 LogTarget log_get_target(void);
 int log_get_max_level(void);
 
diff --git a/src/main.c b/src/main.c
index e5bdf84..ec2733e 100644
--- a/src/main.c
+++ b/src/main.c
@@ -246,6 +246,16 @@ static int parse_proc_cmdline_word(const char *word) {
                 if (log_set_max_level_from_string(word + 18) < 0)
                         log_warning("Failed to parse log level %s. Ignoring.", word + 18);
 
+        } else if (startswith(word, "systemd.log_color=")) {
+
+                if (log_show_color_from_string(word + 18) < 0)
+                        log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);
+
+        } else if (startswith(word, "systemd.log_location=")) {
+
+                if (log_show_location_from_string(word + 21) < 0)
+                        log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);
+
         } else if (startswith(word, "systemd.dump_core=")) {
                 int r;
 
@@ -283,14 +293,17 @@ static int parse_proc_cmdline_word(const char *word) {
 
                 log_warning("Unknown kernel switch %s. Ignoring.", word);
 
-                log_info("Supported kernel switches:");
-                log_info("systemd.unit=UNIT                        Default unit to start");
-                log_info("systemd.log_target=console|kmsg|syslog   Log target");
-                log_info("systemd.log_level=LEVEL                  Log level");
-                log_info("systemd.dump_core=0|1                    Dump core on crash");
-                log_info("systemd.crash_shell=0|1                  On crash run shell");
-                log_info("systemd.crash_chvt=N                     Change to VT #N on crash");
-                log_info("systemd.confirm_spawn=0|1                Confirm every process spawn");
+                log_info("Supported kernel switches:\n"
+                         "systemd.unit=UNIT                        Default unit to start\n"
+                         "systemd.log_target=console|kmsg|syslog|  Log target\n"
+                         "                   syslog-org-kmsg|null\n"
+                         "systemd.log_level=LEVEL                  Log level\n"
+                         "systemd.log_color=0|1                    Highlight important log messages\n"
+                         "systemd.log_location=0|1                 Include code location in log messages\n"
+                         "systemd.dump_core=0|1                    Dump core on crash\n"
+                         "systemd.crash_shell=0|1                  On crash run shell\n"
+                         "systemd.crash_chvt=N                     Change to VT #N on crash\n"
+                         "systemd.confirm_spawn=0|1                Confirm every process spawn");
 
         } else {
                 unsigned i;
@@ -343,6 +356,8 @@ static int parse_argv(int argc, char *argv[]) {
         enum {
                 ARG_LOG_LEVEL = 0x100,
                 ARG_LOG_TARGET,
+                ARG_LOG_COLOR,
+                ARG_LOG_LOCATION,
                 ARG_UNIT,
                 ARG_RUNNING_AS,
                 ARG_TEST,
@@ -355,6 +370,8 @@ static int parse_argv(int argc, char *argv[]) {
         static const struct option options[] = {
                 { "log-level",                required_argument, NULL, ARG_LOG_LEVEL                },
                 { "log-target",               required_argument, NULL, ARG_LOG_TARGET               },
+                { "log-color",                optional_argument, NULL, ARG_LOG_COLOR                },
+                { "log-location",             optional_argument, NULL, ARG_LOG_LOCATION             },
                 { "unit",                     required_argument, NULL, ARG_UNIT                     },
                 { "running-as",               required_argument, NULL, ARG_RUNNING_AS               },
                 { "test",                     no_argument,       NULL, ARG_TEST                     },
@@ -392,6 +409,24 @@ static int parse_argv(int argc, char *argv[]) {
 
                         break;
 
+                case ARG_LOG_COLOR:
+
+                        if ((r = log_show_color_from_string(optarg)) < 0) {
+                                log_error("Failed to parse log color setting %s.", optarg);
+                                return r;
+                        }
+
+                        break;
+
+                case ARG_LOG_LOCATION:
+
+                        if ((r = log_show_location_from_string(optarg)) < 0) {
+                                log_error("Failed to parse log location setting %s.", optarg);
+                                return r;
+                        }
+
+                        break;
+
                 case ARG_UNIT:
 
                         if ((r = set_default_unit(optarg)) < 0) {
@@ -495,15 +530,18 @@ static int parse_argv(int argc, char *argv[]) {
 static int help(void) {
 
         printf("%s [options]\n\n"
+               "Starts up and maintains the system or a session.\n\n"
                "  -h --help                      Show this help\n"
                "     --unit=UNIT                 Set default unit\n"
-               "     --log-level=LEVEL           Set log level\n"
-               "     --log-target=TARGET         Set log target (console, syslog, kmsg, syslog-or-kmsg)\n"
                "     --running-as=AS             Set running as (init, system, session)\n"
                "     --test                      Determine startup sequence, dump it and exit\n"
                "     --dump-configuration-items  Dump understood unit configuration items\n"
                "     --confirm-spawn             Ask for confirmation when spawning processes\n"
-               "     --introspect[=INTERFACE]    Extract D-Bus interface data\n",
+               "     --introspect[=INTERFACE]    Extract D-Bus interface data\n"
+               "     --log-level=LEVEL           Set log level\n"
+               "     --log-target=TARGET         Set log target (console, syslog, kmsg, syslog-or-kmsg, null)\n"
+               "     --log-color[=0|1]           Highlight import log messages\n"
+               "     --log-location[=0|1]        Include code location in log messages\n",
                program_invocation_short_name);
 
         return 0;
@@ -571,11 +609,17 @@ int main(int argc, char *argv[]) {
         FDSet *fds = NULL;
         bool reexecute = false;
 
+        log_show_color(true);
+        log_show_location(false);
+        log_set_max_level(LOG_DEBUG);
+
         if (getpid() == 1) {
                 running_as = MANAGER_INIT;
                 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
-        } else
+        } else {
                 running_as = MANAGER_SESSION;
+                log_set_target(LOG_TARGET_CONSOLE);
+        }
 
         if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
                 goto finish;
commit 3ba686c107b2b33e706f59432584875a4152d19a
Author: Lennart Poettering <lennart at poettering.net>
Date:   Thu Jun 17 22:50:35 2010 +0200

    util: implement parse_pid() function

diff --git a/src/util.c b/src/util.c
index ed0991a..8f70c0f 100644
--- a/src/util.c
+++ b/src/util.c
@@ -241,6 +241,29 @@ int parse_boolean(const char *v) {
         return -EINVAL;
 }
 
+int parse_pid(const char *s, pid_t* ret_pid) {
+        unsigned long ul;
+        pid_t pid;
+        int r;
+
+        assert(s);
+        assert(ret_pid);
+
+        if ((r = safe_atolu(s, &ul)) < 0)
+                return r;
+
+        pid = (pid_t) ul;
+
+        if ((unsigned long) pid != ul)
+                return -ERANGE;
+
+        if (pid <= 0)
+                return -ERANGE;
+
+        *ret_pid = pid;
+        return 0;
+}
+
 int safe_atou(const char *s, unsigned *ret_u) {
         char *x = NULL;
         unsigned long l;
diff --git a/src/util.h b/src/util.h
index 1e5ee28..1ca8f90 100644
--- a/src/util.h
+++ b/src/util.h
@@ -108,6 +108,7 @@ void close_many(const int fds[], unsigned n_fd);
 
 int parse_boolean(const char *v);
 int parse_usec(const char *t, usec_t *usec);
+int parse_pid(const char *s, pid_t* ret_pid);
 
 int safe_atou(const char *s, unsigned *ret_u);
 int safe_atoi(const char *s, int *ret_i);
commit 4a2a8b5a82325494f5daf4c66c23fdb4f906c9e6
Author: Lennart Poettering <lennart at poettering.net>
Date:   Thu Jun 17 22:50:06 2010 +0200

    notify: add systemd-notify command line tool

diff --git a/.gitignore b/.gitignore
index 0ad1446..a0a284f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
+systemd-notify
 test-daemon
 systemd-install
 org.freedesktop.systemd1.*.xml
diff --git a/Makefile.am b/Makefile.am
index 3e77a47..197407c 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -48,7 +48,8 @@ AM_CPPFLAGS = \
 
 rootbin_PROGRAMS = \
 	systemd \
-	systemctl
+	systemctl \
+	systemd-notify
 
 bin_PROGRAMS = \
 	systemd-install
@@ -373,6 +374,11 @@ systemctl_SOURCES = \
 systemctl_CFLAGS = $(AM_CFLAGS) $(DBUS_CFLAGS)
 systemctl_LDADD = $(DBUS_LIBS)
 
+systemd_notify_SOURCES = \
+	src/notify.c \
+	src/sd-daemon.c \
+	$(BASIC_SOURCES)
+
 systemd_install_SOURCES = \
 	src/install.c \
 	src/path-lookup.c \
diff --git a/src/notify.c b/src/notify.c
new file mode 100644
index 0000000..864b7c2
--- /dev/null
+++ b/src/notify.c
@@ -0,0 +1,179 @@
+/*-*- Mode: C; c-basic-offset: 8 -*-*/
+
+/***
+  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/>.
+***/
+
+#include <stdio.h>
+#include <getopt.h>
+#include <error.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "strv.h"
+#include "util.h"
+#include "log.h"
+#include "sd-daemon.h"
+
+static bool arg_ready = false;
+static pid_t arg_pid = 0;
+static const char *arg_status = NULL;
+
+static int help(void) {
+
+        printf("%s [options] [VARIABLE=VALUE...]\n\n"
+               "Notify the init system about service status updates.\n\n"
+               "  -h --help         Show this help\n"
+               "     --ready        Inform the init system about service start-up completion\n"
+               "     --pid[=PID]    Set main pid of daemon\n"
+               "     --status=TEXT  Set status text\n",
+               program_invocation_short_name);
+
+        return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+        enum {
+                ARG_READY = 0x100,
+                ARG_PID,
+                ARG_STATUS
+        };
+
+        static const struct option options[] = {
+                { "help",      no_argument,       NULL, 'h'         },
+                { "ready",     no_argument,       NULL, ARG_READY   },
+                { "pid",       optional_argument, NULL, ARG_PID     },
+                { "status",    required_argument, NULL, ARG_STATUS  },
+                { NULL,        0,                 NULL, 0           }
+        };
+
+        int c;
+
+        assert(argc >= 0);
+        assert(argv);
+
+        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
+
+                switch (c) {
+
+                case 'h':
+                        help();
+                        return 0;
+
+                case ARG_READY:
+                        arg_ready = true;
+                        break;
+
+                case ARG_PID:
+
+                        if (optarg) {
+                                if (parse_pid(optarg, &arg_pid) < 0) {
+                                        log_error("Failed to parse PID %s.", optarg);
+                                        return -EINVAL;
+                                }
+                        } else
+                                arg_pid = getppid();
+
+                        break;
+
+                case ARG_STATUS:
+                        arg_status = optarg;
+                        break;
+
+                case '?':
+                        return -EINVAL;
+
+                default:
+                        log_error("Unknown option code %c", c);
+                        return -EINVAL;
+                }
+        }
+
+        return 1;
+}
+
+int main(int argc, char* argv[]) {
+        char* our_env[4], **final_env = NULL;
+        unsigned i = 0;
+        char *status = NULL, *cpid = NULL, *n = NULL;
+        int r, retval = 1;
+
+        log_parse_environment();
+
+        if ((r = parse_argv(argc, argv)) <= 0) {
+                retval = r < 0;
+                goto finish;
+        }
+
+        if (arg_ready)
+                our_env[i++] = (char*) "READY=1";
+
+        if (arg_status) {
+                if (!(status = strappend("STATUS=", arg_status))) {
+                        log_error("Failed to allocate STATUS string.");
+                        goto finish;
+                }
+
+                our_env[i++] = status;
+        }
+
+        if (arg_pid > 0) {
+                if (asprintf(&cpid, "MAINPID=%lu", (unsigned long) arg_pid) < 0) {
+                        log_error("Failed to allocate MAINPID string.");
+                        goto finish;
+                }
+
+                our_env[i++] = cpid;
+        }
+
+        our_env[i++] = NULL;
+
+        if (!(final_env = strv_env_merge(2, our_env, argv + optind))) {
+                log_error("Failed to merge string sets.");
+                goto finish;
+        }
+
+        if (strv_length(final_env) <= 0) {
+                retval = 0;
+                goto finish;
+        }
+
+        if (!(n = strv_join(final_env, "\n"))) {
+                log_error("Failed to concatenate strings.");
+                goto finish;
+        }
+
+        if ((r = sd_notify(false, n)) < 0) {
+                log_error("Failed to notify init system: %s", strerror(-r));
+                goto finish;
+        }
+
+        retval = r <= 0;
+
+finish:
+        free(status);
+        free(cpid);
+        free(n);
+
+        strv_free(final_env);
+
+        return retval;
+}


More information about the systemd-commits mailing list