Serenity Operating System
1/*
2 * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice, this
9 * list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "Service.h"
28#include <AK/HashMap.h>
29#include <AK/JsonArray.h>
30#include <AK/JsonObject.h>
31#include <LibCore/ConfigFile.h>
32#include <LibCore/LocalSocket.h>
33#include <fcntl.h>
34#include <grp.h>
35#include <libgen.h>
36#include <pwd.h>
37#include <sched.h>
38#include <signal.h>
39#include <stdio.h>
40#include <sys/ioctl.h>
41#include <sys/stat.h>
42#include <unistd.h>
43
44struct UidAndGids {
45 uid_t uid;
46 gid_t gid;
47 Vector<gid_t> extra_gids;
48};
49
50static HashMap<String, UidAndGids>* s_user_map;
51static HashMap<pid_t, Service*> s_service_map;
52
53void Service::for_each(Function<void(Service&)> callback)
54{
55 for (auto& s : s_service_map)
56 callback(*s.value);
57}
58
59void Service::resolve_user()
60{
61 if (s_user_map == nullptr) {
62 s_user_map = new HashMap<String, UidAndGids>;
63 for (struct passwd* passwd = getpwent(); passwd; passwd = getpwent()) {
64 Vector<gid_t> extra_gids;
65 for (struct group* group = getgrent(); group; group = getgrent()) {
66 for (size_t m = 0; group->gr_mem[m]; ++m) {
67 if (!strcmp(group->gr_mem[m], passwd->pw_name))
68 extra_gids.append(group->gr_gid);
69 }
70 }
71 endgrent();
72 s_user_map->set(passwd->pw_name, { passwd->pw_uid, passwd->pw_gid, move(extra_gids) });
73 }
74 endpwent();
75 }
76
77 auto user = s_user_map->get(m_user);
78 if (!user.has_value()) {
79 dbg() << "Failed to resolve user name " << m_user;
80 ASSERT_NOT_REACHED();
81 }
82 m_uid = user.value().uid;
83 m_gid = user.value().gid;
84 m_extra_gids = user.value().extra_gids;
85}
86
87Service* Service::find_by_pid(pid_t pid)
88{
89 auto it = s_service_map.find(pid);
90 if (it == s_service_map.end())
91 return nullptr;
92 return (*it).value;
93}
94
95static int ensure_parent_directories(const char* path)
96{
97 ASSERT(path[0] == '/');
98
99 char* parent_buffer = strdup(path);
100 const char* parent = dirname(parent_buffer);
101
102 int rc = 0;
103 while (true) {
104 int rc = mkdir(parent, 0755);
105
106 if (rc == 0)
107 break;
108
109 if (errno != ENOENT)
110 break;
111
112 ensure_parent_directories(parent);
113 };
114
115 free(parent_buffer);
116 return rc;
117}
118
119void Service::setup_socket()
120{
121 ASSERT(!m_socket_path.is_null());
122 ASSERT(m_socket_fd == -1);
123
124 ensure_parent_directories(m_socket_path.characters());
125 (void)unlink(m_socket_path.characters());
126
127 // Note: we use SOCK_CLOEXEC here to make sure we don't leak every socket to
128 // all the clients. We'll make the one we do need to pass down !CLOEXEC later
129 // after forking off the process.
130 m_socket_fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
131 if (m_socket_fd < 0) {
132 perror("socket");
133 ASSERT_NOT_REACHED();
134 }
135
136#ifdef __serenity__
137 if (fchown(m_socket_fd, m_uid, m_gid) < 0) {
138 perror("fchown");
139 ASSERT_NOT_REACHED();
140 }
141
142 if (fchmod(m_socket_fd, m_socket_permissions) < 0) {
143 perror("fchmod");
144 ASSERT_NOT_REACHED();
145 }
146#endif
147
148 auto socket_address = Core::SocketAddress::local(m_socket_path);
149 auto un = socket_address.to_sockaddr_un();
150 int rc = bind(m_socket_fd, (const sockaddr*)&un, sizeof(un));
151 if (rc < 0) {
152 dbg() << "Failed to bind on " << m_socket_path;
153 perror("bind");
154 ASSERT_NOT_REACHED();
155 }
156
157#ifndef __serenity__
158 if (chown(m_socket_path.characters(), m_uid, m_gid) < 0) {
159 perror("fchown");
160 ASSERT_NOT_REACHED();
161 }
162
163 if (chmod(m_socket_path.characters(), m_socket_permissions) < 0) {
164 perror("fchmod");
165 ASSERT_NOT_REACHED();
166 }
167#endif
168
169 rc = listen(m_socket_fd, 5);
170 if (rc < 0) {
171 perror("listen");
172 ASSERT_NOT_REACHED();
173 }
174}
175
176void Service::setup_notifier()
177{
178 ASSERT(m_lazy);
179 ASSERT(m_socket_fd >= 0);
180 ASSERT(!m_socket_notifier);
181
182 m_socket_notifier = Core::Notifier::construct(m_socket_fd, Core::Notifier::Event::Read, this);
183 m_socket_notifier->on_ready_to_read = [this] {
184 dbg() << "Ready to read on behalf of " << name();
185 remove_child(*m_socket_notifier);
186 m_socket_notifier = nullptr;
187 spawn();
188 };
189}
190
191void Service::activate()
192{
193 ASSERT(m_pid < 0);
194
195 if (m_lazy)
196 setup_notifier();
197 else
198 spawn();
199}
200
201void Service::spawn()
202{
203 dbg() << "Spawning " << name();
204
205 m_run_timer.start();
206 m_pid = fork();
207
208 if (m_pid < 0) {
209 perror("fork");
210 ASSERT_NOT_REACHED();
211 } else if (m_pid == 0) {
212 // We are the child.
213 sigset_t mask;
214
215 sigemptyset(&mask);
216 sigprocmask(SIG_SETMASK, &mask, NULL);
217
218 if (setsid() == -1) {
219 perror("setsid");
220 ASSERT_NOT_REACHED();
221 }
222
223 if (!m_working_directory.is_null()) {
224 if (chdir(m_working_directory.characters()) < 0) {
225 perror("chdir");
226 ASSERT_NOT_REACHED();
227 }
228 }
229
230 struct sched_param p;
231 p.sched_priority = m_priority;
232 int rc = sched_setparam(0, &p);
233 if (rc < 0) {
234 perror("sched_setparam");
235 ASSERT_NOT_REACHED();
236 }
237
238 if (!m_stdio_file_path.is_null()) {
239 close(STDIN_FILENO);
240 int fd = open_with_path_length(m_stdio_file_path.characters(), m_stdio_file_path.length(), O_RDWR, 0);
241 ASSERT(fd <= 0);
242 if (fd < 0) {
243 perror("open");
244 ASSERT_NOT_REACHED();
245 }
246 dup2(STDIN_FILENO, STDOUT_FILENO);
247 dup2(STDIN_FILENO, STDERR_FILENO);
248
249 if (isatty(STDIN_FILENO)) {
250 ioctl(STDIN_FILENO, TIOCSCTTY);
251 }
252 } else {
253 if (isatty(STDIN_FILENO)) {
254 ioctl(STDIN_FILENO, TIOCNOTTY);
255 }
256 close(STDIN_FILENO);
257 close(STDOUT_FILENO);
258 close(STDERR_FILENO);
259
260 int fd = open("/dev/null", O_RDWR);
261 ASSERT(fd == STDIN_FILENO);
262 dup2(STDIN_FILENO, STDOUT_FILENO);
263 dup2(STDIN_FILENO, STDERR_FILENO);
264 }
265
266 if (!m_socket_path.is_null()) {
267 ASSERT(m_socket_fd > 2);
268 dup2(m_socket_fd, 3);
269 // The new descriptor is !CLOEXEC here.
270 // This is true even if m_socket_fd == 3.
271 setenv("SOCKET_TAKEOVER", "1", true);
272 }
273
274 if (!m_user.is_null()) {
275 setlogin(m_user.characters());
276 if (setgroups(m_extra_gids.size(), m_extra_gids.data()) < 0 ||
277#ifdef __serenity__
278 setgid(m_gid) < 0 || setuid(m_uid) < 0
279#else
280 setresgid(m_gid, m_gid, m_gid) < 0 || setresuid(m_uid, m_uid, m_uid) < 0
281#endif
282 ) {
283 dbgprintf("Failed to drop privileges (GID=%u, UID=%u)\n", m_gid, m_uid);
284 exit(1);
285 }
286
287 auto* pwd = getpwuid(getuid());
288 String path = pwd ? pwd->pw_dir : "/";
289 setenv("HOME", path.characters(), true);
290 endpwent();
291 if (chdir(path.characters()) == -1)
292 chdir("/");
293 }
294
295 char* argv[m_extra_arguments.size() + 2];
296 argv[0] = const_cast<char*>(m_executable_path.characters());
297 for (size_t i = 0; i < m_extra_arguments.size(); i++)
298 argv[i + 1] = const_cast<char*>(m_extra_arguments[i].characters());
299 argv[m_extra_arguments.size() + 1] = nullptr;
300
301 rc = execv(argv[0], argv);
302 perror("exec");
303 ASSERT_NOT_REACHED();
304 } else {
305 // We are the parent.
306 s_service_map.set(m_pid, this);
307 }
308}
309
310void Service::kill(int signal)
311{
312 m_dying = true;
313 ::kill(m_pid, signal);
314}
315
316void Service::did_exit(int exit_code)
317{
318 ASSERT(m_pid > 0);
319
320 dbg() << "Service " << name() << " has exited with exit code " << exit_code;
321
322 s_service_map.remove(m_pid);
323 m_pid = -1;
324
325 if (!m_keep_alive || m_dying)
326 return;
327
328 int run_time_in_msec = m_run_timer.elapsed();
329 bool exited_successfully = exit_code == 0;
330
331 if (!exited_successfully && run_time_in_msec < 1000) {
332 switch (m_restart_attempts) {
333 case 0:
334 dbg() << "Trying again";
335 break;
336 case 1:
337 dbg() << "Third time's a charm?";
338 break;
339 default:
340 dbg() << "Giving up on " << name() << ". Good luck!";
341 return;
342 }
343 m_restart_attempts++;
344 }
345
346 activate();
347}
348
349Service::Service(const Core::ConfigFile& config, const StringView& name)
350 : Core::Object(nullptr)
351{
352 ASSERT(config.has_group(name));
353
354 set_name(name);
355 m_executable_path = config.read_entry(name, "Executable", this->name().characters());
356 if (!m_executable_path.starts_with("/"))
357 m_executable_path = String::format("/bin/%s", m_executable_path.characters());
358 m_extra_arguments = config.read_entry(name, "Arguments", "").split(' ');
359 m_stdio_file_path = config.read_entry(name, "StdIO");
360
361 String prio = config.read_entry(name, "Priority");
362 if (prio == "low")
363 m_priority = 10;
364 else if (prio == "normal" || prio.is_null())
365 m_priority = 30;
366 else if (prio == "high")
367 m_priority = 50;
368 else
369 ASSERT_NOT_REACHED();
370
371 m_keep_alive = config.read_bool_entry(name, "KeepAlive");
372 m_lazy = config.read_bool_entry(name, "Lazy");
373
374 m_user = config.read_entry(name, "User");
375 if (!m_user.is_null())
376 resolve_user();
377
378 m_socket_path = config.read_entry(name, "Socket");
379 if (!m_socket_path.is_null()) {
380 auto socket_permissions_string = config.read_entry(name, "SocketPermissions", "0600");
381 m_socket_permissions = strtol(socket_permissions_string.characters(), nullptr, 8) & 04777;
382 setup_socket();
383 }
384
385 m_working_directory = config.read_entry(name, "WorkingDirectory");
386}
387
388void Service::save_to(JsonObject& json)
389{
390 Core::Object::save_to(json);
391
392 json.set("executable_path", m_executable_path);
393
394 // FIXME: This crashes Inspector.
395 /*
396 JsonArray extra_args;
397 for (String& arg : m_extra_arguments)
398 extra_args.append(arg);
399 json.set("extra_arguments", move(extra_args));
400 */
401
402 json.set("stdio_file_path", m_stdio_file_path);
403 json.set("priority", m_priority);
404 json.set("keep_alive", m_keep_alive);
405 json.set("socket_path", m_socket_path);
406 json.set("socket_permissions", m_socket_permissions);
407 json.set("lazy", m_lazy);
408 json.set("user", m_user);
409 json.set("uid", m_uid);
410 json.set("gid", m_gid);
411
412 if (m_pid > 0)
413 json.set("pid", m_pid);
414 else
415 json.set("pid", nullptr);
416
417 json.set("restart_attempts", m_restart_attempts);
418 json.set("working_directory", m_working_directory);
419}