-
Notifications
You must be signed in to change notification settings - Fork 0
/
sd_listen_fds_with_names.c
73 lines (63 loc) · 1.43 KB
/
sd_listen_fds_with_names.c
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
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "systemd/sd-daemon.h"
#include "sd_listen_fds_internal.h"
#define UNKNOWN "unknown"
int sd_listen_fds_with_names(int unset, char ***names) {
const char *value;
size_t i, count = 0;
char **ar = NULL;
int fds, r = 0;
if (names && (value = getenv(LISTEN_FDNAMES))) {
const char *name;
for (name = value; name; name = strchr(name + 1, ':'))
count++;
if (!(ar = calloc(count + 1, sizeof *ar))) {
r = -errno; goto bailearly;
}
name = value;
for (i = 0; i < count; i++) {
const char *next;
next = strchr(name, ':');
if (!next)
next = name + strlen(name);
if (!(ar[i] = malloc(next - name + 1))) {
r = -errno; goto bailearly;
}
memcpy(ar[i], name, next - name);
ar[i][next - name] = '\0';
name = next + 1;
}
}
bailearly: /* call sd_listen_fds to unset variables even if we're bailing */
fds = sd_listen_fds(unset);
if (fds < 0)
r = fds;
if (r < 0)
goto bail;
if (count && count != (unsigned)fds) {
r = -EINVAL; goto bail;
}
if (!count && fds && names) {
if (!(ar = calloc(fds + 1, sizeof *ar))) {
r = errno; goto bail;
}
for (i = 0; i < (unsigned)fds; i++) {
if (!(ar[i] = malloc(sizeof UNKNOWN))) {
r = errno; goto bail;
}
memcpy(ar[i], UNKNOWN, sizeof UNKNOWN);
}
}
r = fds;
bail:
if (names)
*names = ar;
if (r <= 0) {
for (i = 0; i < count; i++)
free(ar[i]);
free(ar);
}
return r;
}