Fedora 30 packaging fix issu
[src/app-framework-binder.git] / src / afb-systemd.c
1 /*
2  * Copyright (C) 2015-2018 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <unistd.h>
21 #include <errno.h>
22
23 #include <systemd/sd-event.h>
24 #include <systemd/sd-bus.h>
25 #include <systemd/sd-daemon.h>
26
27 #include "afb-systemd.h"
28 #include "jobs.h"
29
30 static struct sd_bus *sdbusopen(struct sd_bus **p, int (*f)(struct sd_bus **))
31 {
32         if (*p == NULL) {
33                 int rc = f(p);
34                 if (rc < 0) {
35                         errno = -rc;
36                         *p = NULL;
37                 } else {
38                         rc = sd_bus_attach_event(*p, afb_systemd_get_event_loop(), 0);
39                         if (rc < 0) {
40                                 sd_bus_unref(*p);
41                                 errno = -rc;
42                                 *p = NULL;
43                         }
44                 }
45         }
46         return *p;
47 }
48
49 struct sd_event *afb_systemd_get_event_loop()
50 {
51         return jobs_get_sd_event();
52 }
53
54 struct sd_bus *afb_systemd_get_user_bus()
55 {
56         static struct sd_bus *result = NULL;
57         return sdbusopen((void*)&result, (void*)sd_bus_open_user);
58 }
59
60 struct sd_bus *afb_systemd_get_system_bus()
61 {
62         static struct sd_bus *result = NULL;
63         return sdbusopen((void*)&result, (void*)sd_bus_open_system);
64 }
65
66 static char **fds_names()
67 {
68         static char *null;
69         static char **names;
70
71         int rc;
72
73         if (!names) {
74                 rc = sd_listen_fds_with_names(1, &names);
75                 if (rc <= 0) {
76                         errno = -rc;
77                         names = &null;
78                 }
79         }
80         return names;
81 }
82
83 int afb_systemd_fds_init()
84 {
85         errno = 0;
86         fds_names();
87         return -!!errno;
88 }
89
90 int afb_systemd_fds_for(const char *name)
91 {
92         int idx;
93         char **names;
94
95         names = fds_names();
96         for (idx = 0 ; names[idx] != NULL ; idx++)
97                 if (!strcmp(name, names[idx]))
98                         return idx + SD_LISTEN_FDS_START;
99
100         errno = ENOENT;
101         return -1;
102 }
103