1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <errno.h>
4 #include <getopt.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 
9 #include "sd-daemon.h"
10 
11 #include "alloc-util.h"
12 #include "env-util.h"
13 #include "format-util.h"
14 #include "log.h"
15 #include "main-func.h"
16 #include "parse-util.h"
17 #include "pretty-print.h"
18 #include "string-util.h"
19 #include "strv.h"
20 #include "terminal-util.h"
21 #include "time-util.h"
22 #include "user-util.h"
23 #include "util.h"
24 
25 static bool arg_ready = false;
26 static pid_t arg_pid = 0;
27 static const char *arg_status = NULL;
28 static bool arg_booted = false;
29 static uid_t arg_uid = UID_INVALID;
30 static gid_t arg_gid = GID_INVALID;
31 static bool arg_no_block = false;
32 
help(void)33 static int help(void) {
34         _cleanup_free_ char *link = NULL;
35         int r;
36 
37         r = terminal_urlify_man("systemd-notify", "1", &link);
38         if (r < 0)
39                 return log_oom();
40 
41         printf("%s [OPTIONS...] [VARIABLE=VALUE...]\n"
42                "\n%sNotify the init system about service status updates.%s\n\n"
43                "  -h --help            Show this help\n"
44                "     --version         Show package version\n"
45                "     --ready           Inform the init system about service start-up completion\n"
46                "     --pid[=PID]       Set main PID of daemon\n"
47                "     --uid=USER        Set user to send from\n"
48                "     --status=TEXT     Set status text\n"
49                "     --booted          Check if the system was booted up with systemd\n"
50                "     --no-block        Do not wait until operation finished\n"
51                "\nSee the %s for details.\n",
52                program_invocation_short_name,
53                ansi_highlight(),
54                ansi_normal(),
55                link);
56 
57         return 0;
58 }
59 
manager_pid(void)60 static pid_t manager_pid(void) {
61         const char *e;
62         pid_t pid;
63         int r;
64 
65         /* If we run as a service managed by systemd --user the $MANAGERPID environment variable points to
66          * the service manager's PID. */
67         e = getenv("MANAGERPID");
68         if (!e)
69                 return 0;
70 
71         r = parse_pid(e, &pid);
72         if (r < 0) {
73                 log_warning_errno(r, "$MANAGERPID is set to an invalid PID, ignoring: %s", e);
74                 return 0;
75         }
76 
77         return pid;
78 }
79 
parse_argv(int argc,char * argv[])80 static int parse_argv(int argc, char *argv[]) {
81 
82         enum {
83                 ARG_READY = 0x100,
84                 ARG_VERSION,
85                 ARG_PID,
86                 ARG_STATUS,
87                 ARG_BOOTED,
88                 ARG_UID,
89                 ARG_NO_BLOCK
90         };
91 
92         static const struct option options[] = {
93                 { "help",      no_argument,       NULL, 'h'           },
94                 { "version",   no_argument,       NULL, ARG_VERSION   },
95                 { "ready",     no_argument,       NULL, ARG_READY     },
96                 { "pid",       optional_argument, NULL, ARG_PID       },
97                 { "status",    required_argument, NULL, ARG_STATUS    },
98                 { "booted",    no_argument,       NULL, ARG_BOOTED    },
99                 { "uid",       required_argument, NULL, ARG_UID       },
100                 { "no-block",  no_argument,       NULL, ARG_NO_BLOCK  },
101                 {}
102         };
103 
104         int c, r;
105 
106         assert(argc >= 0);
107         assert(argv);
108 
109         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
110 
111                 switch (c) {
112 
113                 case 'h':
114                         return help();
115 
116                 case ARG_VERSION:
117                         return version();
118 
119                 case ARG_READY:
120                         arg_ready = true;
121                         break;
122 
123                 case ARG_PID:
124                         if (isempty(optarg) || streq(optarg, "auto")) {
125                                 arg_pid = getppid();
126 
127                                 if (arg_pid <= 1 ||
128                                     arg_pid == manager_pid()) /* Don't send from PID 1 or the service
129                                                                * manager's PID (which might be distinct from
130                                                                * 1, if we are a --user instance), that'd just
131                                                                * be confusing for the service manager */
132                                         arg_pid = getpid();
133                         } else if (streq(optarg, "parent"))
134                                 arg_pid = getppid();
135                         else if (streq(optarg, "self"))
136                                 arg_pid = getpid();
137                         else {
138                                 r = parse_pid(optarg, &arg_pid);
139                                 if (r < 0)
140                                         return log_error_errno(r, "Failed to parse PID %s.", optarg);
141                         }
142 
143                         break;
144 
145                 case ARG_STATUS:
146                         arg_status = optarg;
147                         break;
148 
149                 case ARG_BOOTED:
150                         arg_booted = true;
151                         break;
152 
153                 case ARG_UID: {
154                         const char *u = optarg;
155 
156                         r = get_user_creds(&u, &arg_uid, &arg_gid, NULL, NULL, 0);
157                         if (r == -ESRCH) /* If the user doesn't exist, then accept it anyway as numeric */
158                                 r = parse_uid(u, &arg_uid);
159                         if (r < 0)
160                                 return log_error_errno(r, "Can't resolve user %s: %m", optarg);
161 
162                         break;
163                 }
164 
165                 case ARG_NO_BLOCK:
166                         arg_no_block = true;
167                         break;
168 
169                 case '?':
170                         return -EINVAL;
171 
172                 default:
173                         assert_not_reached();
174                 }
175         }
176 
177         if (optind >= argc &&
178             !arg_ready &&
179             !arg_status &&
180             !arg_pid &&
181             !arg_booted) {
182                 help();
183                 return -EINVAL;
184         }
185 
186         return 1;
187 }
188 
run(int argc,char * argv[])189 static int run(int argc, char* argv[]) {
190         _cleanup_free_ char *status = NULL, *cpid = NULL, *n = NULL;
191         _cleanup_strv_free_ char **final_env = NULL;
192         char* our_env[4];
193         unsigned i = 0;
194         pid_t source_pid;
195         int r;
196 
197         log_show_color(true);
198         log_parse_environment();
199         log_open();
200 
201         r = parse_argv(argc, argv);
202         if (r <= 0)
203                 return r;
204 
205         if (arg_booted) {
206                 r = sd_booted();
207                 if (r < 0)
208                         log_debug_errno(r, "Failed to determine whether we are booted with systemd, assuming we aren't: %m");
209                 else
210                         log_debug("The system %s booted with systemd.", r ? "was" : "was not");
211 
212                 return r <= 0;
213         }
214 
215         if (arg_ready)
216                 our_env[i++] = (char*) "READY=1";
217 
218         if (arg_status) {
219                 status = strjoin("STATUS=", arg_status);
220                 if (!status)
221                         return log_oom();
222 
223                 our_env[i++] = status;
224         }
225 
226         if (arg_pid > 0) {
227                 if (asprintf(&cpid, "MAINPID="PID_FMT, arg_pid) < 0)
228                         return log_oom();
229 
230                 our_env[i++] = cpid;
231         }
232 
233         our_env[i++] = NULL;
234 
235         final_env = strv_env_merge(our_env, argv + optind);
236         if (!final_env)
237                 return log_oom();
238 
239         if (strv_isempty(final_env))
240                 return 0;
241 
242         n = strv_join(final_env, "\n");
243         if (!n)
244                 return log_oom();
245 
246         /* If this is requested change to the requested UID/GID. Note that we only change the real UID here, and leave
247            the effective UID in effect (which is 0 for this to work). That's because we want the privileges to fake the
248            ucred data, and sd_pid_notify() uses the real UID for filling in ucred. */
249 
250         if (arg_gid != GID_INVALID &&
251             setregid(arg_gid, GID_INVALID) < 0)
252                 return log_error_errno(errno, "Failed to change GID: %m");
253 
254         if (arg_uid != UID_INVALID &&
255             setreuid(arg_uid, UID_INVALID) < 0)
256                 return log_error_errno(errno, "Failed to change UID: %m");
257 
258         if (arg_pid > 0)
259                 source_pid = arg_pid;
260         else {
261                 /* Pretend the message originates from our parent, given that we are typically called from a
262                  * shell script, i.e. we are not the main process of a service but only a child of it. */
263                 source_pid = getppid();
264                 if (source_pid <= 1 ||
265                     source_pid == manager_pid()) /* safety check: don't claim we'd send anything from PID 1
266                                                   * or the service manager itself */
267                         source_pid = 0;
268         }
269         r = sd_pid_notify(source_pid, false, n);
270         if (r < 0)
271                 return log_error_errno(r, "Failed to notify init system: %m");
272         if (r == 0)
273                 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
274                                        "No status data could be sent: $NOTIFY_SOCKET was not set");
275 
276         if (!arg_no_block) {
277                 r = sd_notify_barrier(0, 5 * USEC_PER_SEC);
278                 if (r < 0)
279                         return log_error_errno(r, "Failed to invoke barrier: %m");
280                 if (r == 0)
281                         return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
282                                                "No status data could be sent: $NOTIFY_SOCKET was not set");
283         }
284 
285         return 0;
286 }
287 
288 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
289