summaryrefslogtreecommitdiffstats
path: root/src/utils-systemd.c
blob: 54385001b7d6dd24aaef10da99048be81d0f7060 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
17
/*
 alsa-gateway -- provide a REST/HTTP interface to ALSA-Mixer

 Copyright (C) 2015, Fulup Ar Foll

 This program 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.

 This program 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 scope program; if not, write to the Free Software
 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

 References:

 */

(function () {
    'use strict';

    var template =
          '<div class="afb-monitor" ng-click="getping()">' +
         '<span class="afb-refresh-token"  >afb://{{hostname}}:{{httpdport}}</span>' +
         '<i class="{{icon}}"></i>' +
         '</div>';


// scope module is load statically before any route is cativated
angular.module('TokenRefresh', ['AppConfig', 'ModalNotification'])

    .directive ('tokenRefresh', function($log, $window, $timeout, $location, Notification, AppConfig, AppCall) {

    function mymethods(scope, elem, attrs) {
        scope.logged=undefined; // neither thu neither false
        
        $window.onbeforeunload = function () {
            AppCall.get (scope.plugin, "logout", {/*query*/}, function () {    
            $log.log("OPA exit");            
            });
        };
                 
        scope.online = function () {
            elem.addClass    ("online");
            elem.removeClass ("offline");
            scope.logged=true;
        };

        scope.offline = function(){
            elem.addClass    ("offline");
            elem.removeClass ("online");
            scope.logged=false;
        };
        
        scope.onerror = function() {
            if (scope.logged !== false)  {
                Notification.warning ({message: "AppFramework Binder Lost", delay: 5000});
                scope.offline();
            }
            scope.status = 0;
        };
        
        scope.onsuccess = function(jresp, errcode) {
            
            if (errcode !== 200 || jresp.request.status !== "success") {
                Notification.warning ({message: "auto-connect :" + jresp.request.info, 
@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
/*
 Copyright (C) 2015-2020 IoT.bzh

 author: José Bollo <jose.bollo@iot.bzh>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
#define _GNU_SOURCE

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>

#ifndef NO_LIBSYSTEMD
# include <systemd/sd-bus.h>
# include <systemd/sd-bus-protocol.h>
#else
  struct sd_bus;
  struct sd_bus_message;
  typedef struct { const char *name; const char *message; } sd_bus_error;
# define sd_bus_unref(...)                ((void)0)
# define sd_bus_default_user(p)           ((*(p)=NULL),(-ENOTSUP))
# define sd_bus_default_system(p)         ((*(p)=NULL),(-ENOTSUP))
# define sd_bus_call_method(...)          (-ENOTSUP)
# define SD_BUS_ERROR_NULL                {NULL,NULL}
# define sd_bus_message_read_basic(...)   (-ENOTSUP)
# define sd_bus_message_unref(...)        (NULL)
# define sd_bus_get_property_string(...)  (-ENOTSUP)
# define sd_bus_get_property_trivial(...) (-ENOTSUP)
#endif

#include "utils-systemd.h"

#if !defined(SYSTEMD_UNITS_ROOT)
# define SYSTEMD_UNITS_ROOT "/usr/local/lib/systemd"
#endif

static const char sdb_path[] = "/org/freedesktop/systemd1";
static const char sdb_destination[] = "org.freedesktop.systemd1";
static const char sdbi_manager[] = "org.freedesktop.systemd1.Manager";
static const char sdbi_unit[] = "org.freedesktop.systemd1.Unit";
static const char sdbi_service[] = "org.freedesktop.systemd1.Service";
static const char sdbi_job[] = "org.freedesktop.systemd1.Job";
static const char sdbj_state[] = "State";
static const char sdbm_reload[] = "Reload";
static const char sdbm_start_unit[] = "StartUnit";
static const char sdbm_restart_unit[] = "RestartUnit";
static const char sdbm_stop_unit[] = "StopUnit";
static const char sdbm_start[] = "Start";
static const char sdbm_restart[] = "Restart";
static const char sdbm_stop[] = "Stop";
static const char sdbm_get_unit[] = "GetUnit";
static const char sdbm_get_unit_by_pid[] = "GetUnitByPID";
static const char sdbm_load_unit[] = "LoadUnit";
static const char sdbp_active_state[] = "ActiveState";
static const char sdbp_exec_main_pid[] = "ExecMainPID";

static const char *sds_state_names[] = {
	NULL,
	"inactive",
	"activating",
	"active",
	"deactivating",
	"reloading",
	"failed"
};

static const char *sds_job_state_names[] = {
	NULL,
	"waiting",
	"running"
};

static struct sd_bus *sysbus;
static struct sd_bus *usrbus;

/*
 * Translate systemd errors to errno errors
 */
static int seterrno(int value)
{
	errno = value;
	return -1;
}

static int sderr2errno(int rc)
{
	return rc < 0 ? seterrno(-rc) : rc;
}

static int errno2sderr(int rc)
{
	return rc < 0 ? -errno : rc;
}

/*
 * Returns in 'ret' either the system bus (if isuser==0)
 * or the user bus (if isuser!=0).
 * Returns 0 in case of success or -1 in case of error
 */
int systemd_get_bus(int isuser, struct sd_bus **ret)
{
	int rc;
	struct sd_bus *bus;

	bus = isuser ? usrbus : sysbus;
	if (bus)
		*ret = bus;
	else if (isuser) {
		rc = sd_bus_default_user(ret);
		if (rc < 0)
			goto error;
		usrbus = *ret;
	} else {
		rc = sd_bus_default_system(ret);
		if (rc < 0)
			goto error;
		sysbus = *ret;
	}
	return 0;
error:
	return sderr2errno(rc);
}

void systemd_set_bus(int isuser, struct sd_bus *bus)
{
	struct sd_bus **target = isuser ? &usrbus : &sysbus;
	if (*target)
		sd_bus_unref(*target);
	*target = bus;
}

#if 0
/********************************************************************
 * routines for escaping unit names to compute dbus path of units
 *******************************************************************/
/*
 * Should the char 'c' be escaped?
 */
static inline int should_escape_for_path(char c)
{
	if (c >= 'A') {
		return c <= (c >= 'a' ? 'z' : 'Z');
	} else {
		return c >= '0' && c <= '9';
	}
}

/*
 * ascii char for the hexadecimal digit 'x'
 */
static inline char d2h(int x)
{
	return (char)(x + (x > 9 ? ('a' - 10) : '0'));
}

/*
 * escapes in 'path' of 'pathlen' the 'unit'
 * returns 0 in case of success or -1 in case of error
 */
static int unit_escape_for_path(char *path, size_t pathlen, const char *unit)
{
	size_t r, w;
	char c;

	c = unit[r = w = 0];
	while (c) {
		if (should_escape_for_path(c)) {
			if (w + 2 >= pathlen)
				goto toolong;
			path[w++] = '_';
			path[w++] = d2h((c >> 4) & 15);;
			path[w++] = d2h(c & 15);
		} else {
			if (w >= pathlen)
				goto toolong;
			path[w++] = c;
		}
		c = unit[++r];
	}
	if (w >= pathlen)
		goto toolong;
	path[w] = 0;
	return 0;
toolong:
	return seterrno(ENAMETOOLONG);
}
#endif

/********************************************************************
 * Routines for getting paths
 *******************************************************************/

static char *get_dpath(struct sd_bus_message *msg)
{
	int rc;
	const char *reply;
	char *result;

	rc = sd_bus_message_read_basic(msg, 'o', &reply);
	rc = sderr2errno(rc);
	if (rc < 0)
		result = NULL;
	else {
		result = strdup(reply);
		if (!result)
			errno = ENOMEM;
	}
	sd_bus_message_unref(msg);
	return result;
}

static char *get_unit_dpath(struct sd_bus *bus, const char *unit, int load)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, sdb_path, sdbi_manager, load ? sdbm_load_unit : sdbm_get_unit, &err, &ret, "s", unit);
	if (rc < 0)
		goto error;

	return get_dpath(ret);
error:
	sd_bus_message_unref(ret);
	return NULL;
}

static char *get_unit_dpath_by_pid(struct sd_bus *bus, unsigned pid)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, sdb_path, sdbi_manager, sdbm_get_unit_by_pid, &err, &ret, "u", pid);
	if (rc < 0)
		goto error;

	return get_dpath(ret);
error:
	sd_bus_message_unref(ret);
	return NULL;
}

static int unit_pid(struct sd_bus *bus, const char *dpath)
{
	int rc;
	unsigned u = 0;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_get_property_trivial(bus, sdb_destination, dpath, sdbi_service, sdbp_exec_main_pid, &err, 'u', &u);
	return rc < 0 ? rc : (int)u;
}

static enum SysD_State unit_state(struct sd_bus *bus, const char *dpath)
{
	int rc;
	char *st;
	enum SysD_State resu;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	resu = SysD_State_INVALID;
	rc = sd_bus_get_property_string(bus, sdb_destination, dpath, sdbi_unit, sdbp_active_state, &err, &st);
	if (rc < 0) {
		errno = -rc;
	} else {
		switch (st[0]) {
		case 'a':
			if (!strcmp(st, sds_state_names[SysD_State_Active]))
				resu = SysD_State_Active;
			else if (!strcmp(st, sds_state_names[SysD_State_Activating]))
				resu = SysD_State_Activating;
			break;
		case 'd':
			if (!strcmp(st, sds_state_names[SysD_State_Deactivating]))
				resu = SysD_State_Deactivating;
			break;
		case 'f':
			if (!strcmp(st, sds_state_names[SysD_State_Failed]))
				resu = SysD_State_Failed;
			break;
		case 'i':
			if (!strcmp(st, sds_state_names[SysD_State_Inactive]))
				resu = SysD_State_Inactive;
			break;
		case 'r':
			if (!strcmp(st, sds_state_names[SysD_State_Reloading]))
				resu = SysD_State_Reloading;
			break;
		default:
			break;
		}
		if (resu == NULL)
			errno = EBADMSG;
		free(st);
	}
	return resu;
}

static int job_wait(struct sd_bus *bus, struct sd_bus_message *job)
{
	int rc;
	sd_bus_error err = SD_BUS_ERROR_NULL;
	const char *jpath = NULL;
	char *jstate;
	struct timespec tispec;
	const int period_ms = 10;
	const int trial_s = 10;
	const int trial_count = (trial_s * 1000) / period_ms;
	const int period_ns = period_ms * 1000000;
	int trial;

	/* Get job path */
	rc = sd_bus_message_read_basic(job, 'o', &jpath);
	if (rc < 0)
		return rc;

	/* Wait for job to enter "running" state */
	rc = 0;
	for (trial = 1 ; trial <= trial_count ; trial++) {
		jstate = NULL;
		if(sd_bus_get_property_string(bus, sdb_destination, jpath, sdbi_job, sdbj_state, &err, &jstate) >= 0) {
			if(jstate && strcmp(jstate, sds_job_state_names[SysD_Job_State_Running]) == 0) {
				free(jstate);
				break;
			} else {
				tispec.tv_sec = 0;
				tispec.tv_nsec = period_ns;
				nanosleep(&tispec, NULL);
			}
			free(jstate);
		}
	}
	if(trial > trial_count)
		rc = -1;

	return rc;
}

static int unit_start(struct sd_bus *bus, const char *dpath)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, dpath, sdbi_unit, sdbm_start, &err, &ret, "s", "replace");
	if(ret) {
		rc = job_wait(bus, ret);
	}
	sd_bus_message_unref(ret);
	return rc;
}

static int unit_restart(struct sd_bus *bus, const char *dpath)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, dpath, sdbi_unit, sdbm_restart, &err, &ret, "s", "replace");
	if(ret) {
		rc = job_wait(bus, ret);
	}
	sd_bus_message_unref(ret);
	return rc;
}

static int unit_stop(struct sd_bus *bus, const char *dpath)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, dpath, sdbi_unit, sdbm_stop, &err, &ret, "s", "replace");
	sd_bus_message_unref(ret);
	return rc;
}

static int unit_start_name(struct sd_bus *bus, const char *name)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, sdb_path, sdbi_manager, sdbm_start_unit, &err, &ret, "ss", name, "replace");
	if(ret) {
		rc = job_wait(bus, ret);
	}
	sd_bus_message_unref(ret);
	return rc;
}

static int unit_restart_name(struct sd_bus *bus, const char *name)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, sdb_path, sdbi_manager, sdbm_restart_unit, &err, &ret, "ss", name, "replace");
	if(ret) {
		rc = job_wait(bus, ret);
	}
	sd_bus_message_unref(ret);
	return rc;
}

static int unit_stop_name(struct sd_bus *bus, const char *name)
{
	int rc;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = sd_bus_call_method(bus, sdb_destination, sdb_path, sdbi_manager, sdbm_stop_unit, &err, &ret, "ss", name, "replace");
	sd_bus_message_unref(ret);
	return rc;
}

/********************************************************************
 *
 *******************************************************************/

static int check_snprintf_result(int rc, size_t buflen)
{
	return (rc >= 0 && (size_t)rc >= buflen) ? seterrno(ENAMETOOLONG) : rc;
}

int systemd_get_units_dir(char *path, size_t pathlen, int isuser)
{
	int rc = snprintf(path, pathlen, "%s/%s",
			SYSTEMD_UNITS_ROOT,
			isuser ? "user" : "system");

	return check_snprintf_result(rc, pathlen);
}

int systemd_get_unit_path(char *path, size_t pathlen, int isuser, const char *unit, const char *uext)
{
	int rc = snprintf(path, pathlen, "%s/%s/%s.%s",
			SYSTEMD_UNITS_ROOT,
			isuser ? "user" : "system",
			unit,
			uext);

	return check_snprintf_result(rc, pathlen);
}

int systemd_get_wants_path(char *path, size_t pathlen, int isuser, const char *wanter, const char *unit, const char *uext)
{
	int rc = snprintf(path, pathlen, "%s/%s/%s.wants/%s.%s",
			SYSTEMD_UNITS_ROOT,
			isuser ? "user" : "system",
			wanter,
			unit,
			uext);

	return check_snprintf_result(rc, pathlen);
}

int systemd_get_wants_target(char *path, size_t pathlen, const char *unit, const char *uext)
{
	int rc = snprintf(path, pathlen, "../%s.%s", unit, uext);

	return check_snprintf_result(rc, pathlen);
}

int systemd_daemon_reload(int isuser)
{
	int rc;
	struct sd_bus *bus;
	struct sd_bus_message *ret = NULL;
	sd_bus_error err = SD_BUS_ERROR_NULL;

	rc = systemd_get_bus(isuser, &bus);
	if (rc >= 0) {
		/* TODO: asynchronous bind... */
		/* TODO: more diagnostic... */
		rc = sd_bus_call_method(bus, sdb_destination, sdb_path, sdbi_manager, sdbm_reload, &err, &ret, NULL);
		sd_bus_message_unref(ret);
	}
	return rc;
}

int systemd_unit_list(int isuser, int (*callback)(void *closure, const char *name, const char *path, int isuser), void *closure)
{
	DIR *dir;
	char path[PATH_MAX + 1];
	struct dirent *dent;
	int rc, isfile;
	size_t offset, len;
	struct stat st;

	/* get the path */
	rc = systemd_get_units_dir(path, sizeof path - 1, isuser);
	if (rc < 0)
		return rc;
	offset = (size_t)rc;

	/* open the directory */
	dir = opendir(path);
	if (!dir)
		return -1;

	/* prepare path */
	path[offset++] = '/';

	/* read the directory */
	for(;;) {
		/* get next entry */
		errno = 0;
		dent = readdir(dir);
		if (dent == NULL) {
			/* end or error */
			rc = (!errno) - 1;
			break;
		}

		/* is a file? */
		if (dent->d_type == DT_REG)
			isfile = 1;
		else if (dent->d_type != DT_UNKNOWN)
			isfile = 0;
		else {
			rc = fstatat(dirfd(dir), dent->d_name, &st, AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT);
			if (rc < 0)
				break;
			isfile = S_ISREG(st.st_mode);
		}

		/* calls the callback if is a file */
		if (isfile) {
			len = strlen(dent->d_name);
			if (offset + len >= sizeof path) {
				rc = seterrno(ENAMETOOLONG);
				break;
			}
			memcpy(&path[offset], dent->d_name, 1 + len);
			rc = callback(closure, &path[offset], path, isuser);
			if (rc)
				break;
		}
	}
	closedir(dir);
	return rc;
}

int systemd_unit_list_all(int (*callback)(void *closure, const char *name, const char *path, int isuser), void *closure)
{
	return systemd_unit_list(1, callback, closure) ? : systemd_unit_list(0, callback, closure);
}

char *systemd_unit_dpath_by_name(int isuser, const char *name, int load)
{
	struct sd_bus *bus;

	return systemd_get_bus(isuser, &bus) < 0 ? NULL : get_unit_dpath(bus, name, load);
}

char *systemd_unit_dpath_by_pid(int isuser, unsigned pid)
{
	struct sd_bus *bus;

	return systemd_get_bus(isuser, &bus) < 0 ? NULL : get_unit_dpath_by_pid(bus, pid);
}

int systemd_unit_start_dpath(int isuser, const char *dpath)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	return rc < 0 ? rc : unit_start(bus, dpath);
}

int systemd_unit_restart_dpath(int isuser, const char *dpath)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	return rc < 0 ? rc : unit_restart(bus, dpath);
}

int systemd_unit_stop_dpath(int isuser, const char *dpath)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	return rc < 0 ? rc : unit_stop(bus, dpath);
}

int systemd_unit_start_name(int isuser, const char *name)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	if (rc >= 0)
		rc = unit_start_name(bus, name);
	return rc;
}

int systemd_unit_restart_name(int isuser, const char *name)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	if (rc >= 0)
		rc = unit_restart_name(bus, name);
	return rc;
}

int systemd_unit_stop_name(int isuser, const char *name)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	if (rc >= 0)
		rc = unit_stop_name(bus, name);
	return rc;
}

int systemd_unit_stop_pid(int isuser, unsigned pid)
{
	int rc;
	struct sd_bus *bus;
	char *dpath;

	rc = systemd_get_bus(isuser, &bus);
	if (rc >= 0) {
		dpath = get_unit_dpath_by_pid(bus, pid);
		if (!dpath)
			rc = -1;
		else {
			rc = unit_stop(bus, dpath);
			free(dpath);
		}
	}
	return rc;
}

int systemd_unit_pid_of_dpath(int isuser, const char *dpath)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	return rc < 0 ? rc : unit_pid(bus, dpath);
}

enum SysD_State systemd_unit_state_of_dpath(int isuser, const char *dpath)
{
	int rc;
	struct sd_bus *bus;

	rc = systemd_get_bus(isuser, &bus);
	return rc < 0 ? SysD_State_INVALID : unit_state(bus, dpath);
}

const char *systemd_state_name(enum SysD_State state)
{
	return sds_state_names[state];
}