Debian Codegraph @

liblomiri-app-launch/jobs-systemd.cpp

raw
1 /*
2 * Copyright © 2016 Canonical Ltd.
3 *
4 * This program is free software: you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 3, as published
6 * by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranties of
10 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 * PURPOSE. See the GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * Authors:
17 * Ted Gould <[email protected]>
18 */
19
20 #include "jobs-systemd.h"
21 #include "application-impl-base.h"
22 #include "registry-impl.h"
23 #include "second-exec-core.h"
24 #include "string-util.h"
25 #include "utils.h"
26 #include "lomiri-app-launch-trace.h"
27
28 #include <gio/gio.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31
32 #include <algorithm>
33 #include <charconv>
34 #include <numeric>
35 #include <regex>
36 #include <lomiri/util/GlibMemory.h>
37
38 using namespace lomiri::util;
39
40 namespace lomiri
41 {
42 namespace app_launch
43 {
44 namespace jobs
45 {
46 namespace instance
47 {
48
49 class SystemD : public instance::Base
50 {
51 friend class manager::SystemD;
52
53 public:
54 explicit SystemD(const AppID& appId,
55 const std::string& job,
56 const std::string& instance,
57 const std::vector<Application::URL>& urls,
58 const std::shared_ptr<Registry::Impl>& registry);
59 virtual ~SystemD()
60 {
61 g_debug("Destroying a SystemD for '%s' instance '%s'", std::string(appId_).c_str(), instance_.c_str());
62 }
63
64 /* Query lifecycle */
65 pid_t primaryPid() override;
66 std::vector<pid_t> pids() override;
67
68 /* Manage lifecycle */
69 void stop() override;
70
71 }; // class SystemD
72
73 SystemD::SystemD(const AppID& appId,
74 const std::string& job,
75 const std::string& instance,
76 const std::vector<Application::URL>& urls,
77 const std::shared_ptr<Registry::Impl>& registry)
78 : Base(appId, job, instance, urls, registry)
79 {
80 g_debug("Creating a new SystemD for '%s' instance '%s'", std::string(appId).c_str(), instance.c_str());
81 }
82
83 pid_t SystemD::primaryPid()
84 {
85 auto manager = std::dynamic_pointer_cast<manager::SystemD>(registry_->jobs());
86 return manager->unitPrimaryPid(appId_, job_, instance_);
87 }
88
89 std::vector<pid_t> SystemD::pids()
90 {
91 auto manager = std::dynamic_pointer_cast<manager::SystemD>(registry_->jobs());
92 return manager->unitPids(appId_, job_, instance_);
93 }
94
95 void SystemD::stop()
96 {
97 auto manager = std::dynamic_pointer_cast<manager::SystemD>(registry_->jobs());
98 try {
99 manager->stopUnit(appId_, job_, instance_);
100 } catch (const std::runtime_error& e) {
101 g_warning("Error occurred while stopping unit: %s", e.what());
102 }
103 }
104
105 } // namespace instance
106
107 namespace manager
108 {
109
110 static const char* SYSTEMD_DBUS_ADDRESS{"org.freedesktop.systemd1"};
111 static const char* SYSTEMD_DBUS_IFACE_MANAGER{"org.freedesktop.systemd1.Manager"};
112 static const char* SYSTEMD_DBUS_PATH_MANAGER{"/org/freedesktop/systemd1"};
113 // static const char * SYSTEMD_DBUS_IFACE_UNIT{"org.freedesktop.systemd1.Unit"};
114 static const char* SYSTEMD_DBUS_IFACE_SERVICE{"org.freedesktop.systemd1.Service"};
115
116 SystemD::SystemD(const std::shared_ptr<Registry::Impl>& registry)
117 : Base(registry)
118 , handle_reloading(DBusSignalUnsubscriber{})
119 , handle_unitNew(DBusSignalUnsubscriber{})
120 , handle_unitRemoved(DBusSignalUnsubscriber{})
121 , handle_appFailed(DBusSignalUnsubscriber{})
122 {
123 auto gcgroup_root = getenv("LOMIRI_APP_LAUNCH_SYSTEMD_CGROUP_ROOT");
124 if (gcgroup_root == nullptr)
125 {
126 auto cpaths = {
127 g_build_filename("/sys", "fs", "cgroup", "systemd", nullptr), // cgroups v1
128 g_build_filename("/sys", "fs", "cgroup", nullptr) // cgroups v2
129 };
130
131 for (auto cpath : cpaths) {
132 if (cgroup_root_.empty() &&
133 g_file_test(cpath, static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)))
134 {
135 cgroup_root_ = cpath;
136 }
137
138 // Cleanup as we go
139 g_free(cpath);
140 }
141 }
142 else
143 {
144 cgroup_root_ = gcgroup_root;
145 }
146
147 if (getenv("LOMIRI_APP_LAUNCH_SYSTEMD_NO_RESET") != nullptr)
148 {
149 noResetUnits_ = true;
150 }
151
152 setupUserbus(registry);
153 }
154
155 void SystemD::setupUserbus(const std::shared_ptr<Registry::Impl>& reg)
156 {
157 auto cancel = reg->thread.getCancellable();
158 userbus_ = reg->thread.executeOnThread<std::shared_ptr<GDBusConnection>>([this, cancel]() {
159 GError* error = nullptr;
160 auto bus = std::shared_ptr<GDBusConnection>(
161 [&]() -> GDBusConnection* {
162 if (g_file_test(SystemD::userBusPath().c_str(), G_FILE_TEST_EXISTS))
163 {
164 return g_dbus_connection_new_for_address_sync(
165 ("unix:path=" + userBusPath()).c_str(), /* path to the user bus */
166 (GDBusConnectionFlags)(
167 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
168 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION), /* It is a message bus */
169 nullptr, /* observer */
170 cancel.get(), /* cancellable from the thread */
171 &error); /* error */
172 }
173 else
174 {
175 /* Fallback mostly for testing */
176 g_debug("Using session bus for systemd user bus");
177 return g_bus_get_sync(G_BUS_TYPE_SESSION, /* type */
178 cancel.get(), /* thread cancellable */
179 &error); /* error */
180 }
181 }(),
182 [](GDBusConnection* bus) { g_clear_object(&bus); });
183
184 if (error != nullptr)
185 {
186 std::string message = std::string("Unable to connect to user bus: ") + error->message;
187 g_error_free(error);
188 throw std::runtime_error(message);
189 }
190
191 /* If we don't subscribe, it doesn't send us signals */
192 g_dbus_connection_call(bus.get(), /* user bus */
193 SYSTEMD_DBUS_ADDRESS, /* bus name */
194 SYSTEMD_DBUS_PATH_MANAGER, /* path */
195 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
196 "Subscribe", /* method */
197 nullptr, /* params */
198 nullptr, /* ret type */
199 G_DBUS_CALL_FLAGS_NONE, /* flags */
200 -1, /* timeout */
201 cancel.get(), /* cancellable */
202 [](GObject* obj, GAsyncResult* res, gpointer user_data) {
203 GError* error{nullptr};
204 unique_glib(g_dbus_connection_call_finish(G_DBUS_CONNECTION(obj), res, &error));
205
206 if (error != nullptr)
207 {
208 if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
209 {
210 g_warning("Unable to subscribe to SystemD: %s", error->message);
211 }
212 g_error_free(error);
213 return;
214 }
215
216 g_debug("Subscribed to Systemd");
217 },
218 nullptr);
219
220 /* Setup reloading signal first to avoid race-condition. */
221 handle_reloading = managedDBusSignalConnection(
222 g_dbus_connection_signal_subscribe(bus.get(), /* bus */
223 nullptr, /* sender */
224 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
225 "Reloading", /* signal */
226 SYSTEMD_DBUS_PATH_MANAGER, /* path */
227 nullptr, /* arg0 */
228 G_DBUS_SIGNAL_FLAGS_NONE,
229 [](GDBusConnection*, const gchar*, const gchar*, const gchar*,
230 const gchar*, GVariant* params, gpointer user_data) -> void {
231 auto pthis = static_cast<SystemD*>(user_data);
232
233 if (!g_variant_check_format_string(params, "(b)", FALSE))
234 {
235 g_warning("Got 'Reloading' signal with unknown parameter type: %s",
236 g_variant_get_type_string(params));
237 return;
238 }
239
240 gboolean active{false};
241 g_variant_get(params, "(b)", &active);
242
243 pthis->systemdReloading(active);
244 }, /* callback */
245 this, /* user data */
246 nullptr), /* user data destroy */
247 bus);
248
249 /* Setup Unit add/remove signals */
250 handle_unitNew = managedDBusSignalConnection(
251 g_dbus_connection_signal_subscribe(bus.get(), /* bus */
252 nullptr, /* sender */
253 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
254 "UnitNew", /* signal */
255 SYSTEMD_DBUS_PATH_MANAGER, /* path */
256 nullptr, /* arg0 */
257 G_DBUS_SIGNAL_FLAGS_NONE,
258 [](GDBusConnection*, const gchar*, const gchar*, const gchar*,
259 const gchar*, GVariant* params, gpointer user_data) -> void {
260 auto pthis = static_cast<SystemD*>(user_data);
261
262 if (!g_variant_check_format_string(params, "(so)", FALSE))
263 {
264 g_warning("Got 'UnitNew' signal with unknown parameter type: %s",
265 g_variant_get_type_string(params));
266 return;
267 }
268
269 const gchar* unitname{nullptr};
270 const gchar* unitpath{nullptr};
271
272 g_variant_get(params, "(&s&o)", &unitname, &unitpath);
273
274 if (unitname == nullptr || unitpath == nullptr)
275 {
276 g_warning("Got 'UnitNew' signal with funky params %p, %p",
277 unitname, unitpath);
278 return;
279 }
280
281 try
282 {
283 pthis->parseUnit(unitname);
284 }
285 catch (std::runtime_error& e)
286 {
287 /* Not for UAL */
288 g_debug("Unable to parse unit: %s", unitname);
289 return;
290 }
291
292 try
293 {
294 pthis->unitNew(unitname, unitpath, pthis->userbus_);
295 }
296 catch (std::runtime_error& e)
297 {
298 g_warning("%s", e.what());
299 }
300 }, /* callback */
301 this, /* user data */
302 nullptr), /* user data destroy */
303 bus);
304
305 handle_unitRemoved = managedDBusSignalConnection(
306 g_dbus_connection_signal_subscribe(
307 bus.get(), /* bus */
308 nullptr, /* sender */
309 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
310 "UnitRemoved", /* signal */
311 SYSTEMD_DBUS_PATH_MANAGER, /* path */
312 nullptr, /* arg0 */
313 G_DBUS_SIGNAL_FLAGS_NONE,
314 [](GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params,
315 gpointer user_data) -> void {
316 auto pthis = static_cast<SystemD*>(user_data);
317
318 if (!g_variant_check_format_string(params, "(so)", FALSE))
319 {
320 g_warning("Got 'UnitRemoved' signal with unknown parameter type: %s",
321 g_variant_get_type_string(params));
322 return;
323 }
324
325 const gchar* unitname{nullptr};
326 const gchar* unitpath{nullptr};
327
328 g_variant_get(params, "(&s&o)", &unitname, &unitpath);
329
330 if (unitname == nullptr || unitpath == nullptr)
331 {
332 g_warning("Got 'UnitRemoved' signal with funky params %p, %p", unitname, unitpath);
333 return;
334 }
335
336 try
337 {
338 pthis->parseUnit(unitname);
339 }
340 catch (std::runtime_error& e)
341 {
342 /* Not for UAL */
343 g_debug("Unable to parse unit: %s", unitname);
344 return;
345 }
346
347 pthis->unitRemoved(unitname, unitpath);
348 }, /* callback */
349 this, /* user data */
350 nullptr), /* user data destroy */
351 bus);
352
353 getInitialUnits(bus, cancel);
354
355 return bus;
356 });
357 }
358
359 SystemD::~SystemD()
360 {
361 }
362
363 void SystemD::getInitialUnits(const std::shared_ptr<GDBusConnection>& bus, const std::shared_ptr<GCancellable>& cancel)
364 {
365 GError* error = nullptr;
366
367 auto callt = unique_glib(g_dbus_connection_call_sync(bus.get(), /* user bus */
368 SYSTEMD_DBUS_ADDRESS, /* bus name */
369 SYSTEMD_DBUS_PATH_MANAGER, /* path */
370 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
371 "ListUnits", /* method */
372 nullptr, /* params */
373 G_VARIANT_TYPE("(a(ssssssouso))"), /* ret type */
374 G_DBUS_CALL_FLAGS_NONE, /* flags */
375 -1, /* timeout */
376 cancel.get(), /* cancellable */
377 &error));
378
379 if (error != nullptr)
380 {
381 if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
382 {
383 g_warning("Unable to list SystemD units: %s", error->message);
384 }
385 g_error_free(error);
386 return;
387 }
388
389 auto call = unique_glib(g_variant_get_child_value(callt.get(), 0));
390
391 const gchar* id;
392 const gchar* description;
393 const gchar* loadState;
394 const gchar* activeState;
395 const gchar* subState;
396 const gchar* following;
397 const gchar* path;
398 guint32 jobId;
399 const gchar* jobType;
400 const gchar* jobPath;
401 auto iter = unique_glib(g_variant_iter_new(call.get()));
402 while (g_variant_iter_loop(iter.get(), "(&s&s&s&s&s&s&ou&s&o)", &id, &description, &loadState, &activeState,
403 &subState, &following, &path, &jobId, &jobType, &jobPath))
404 {
405 try
406 {
407 unitNew(id, jobPath, bus);
408 }
409 catch (std::runtime_error& e)
410 {
411 }
412 }
413 }
414
415 std::string SystemD::findEnv(const std::string& value, std::list<std::pair<std::string, std::string>>& env)
416 {
417 std::string retval;
418 auto entry = std::find_if(env.begin(), env.end(),
419 [&value](std::pair<std::string, std::string>& entry) { return entry.first == value; });
420
421 if (entry != env.end())
422 {
423 retval = entry->second;
424 }
425
426 return retval;
427 }
428
429 void SystemD::removeEnv(const std::string& value, std::list<std::pair<std::string, std::string>>& env)
430 {
431 auto entry = std::find_if(env.begin(), env.end(),
432 [&value](std::pair<std::string, std::string>& entry) { return entry.first == value; });
433
434 if (entry != env.end())
435 {
436 env.erase(entry);
437 }
438 }
439
440 int SystemD::envSize(std::list<std::pair<std::string, std::string>>& env)
441 {
442 int len = std::string{"Environment="}.length();
443
444 for (const auto& entry : env)
445 {
446 len += 3; /* two quotes, one space */
447 len += entry.first.length();
448 len += entry.second.length();
449 }
450
451 len -= 1; /* We account for a space each time but the first doesn't have */
452
453 return len;
454 }
455
456 std::vector<std::string> SystemD::parseExec(std::list<std::pair<std::string, std::string>>& env)
457 {
458 auto exec = findEnv("APP_EXEC", env);
459 if (exec.empty())
460 {
461 g_warning("Application exec line is empty?!?!?");
462 return {};
463 }
464 auto uris = findEnv("APP_URIS", env);
465
466 g_debug("Exec line: %s", exec.c_str());
467 g_debug("App URLS: %s", uris.c_str());
468
469 auto execarray = desktop_exec_parse(exec.c_str(), uris.c_str());
470
471 std::vector<std::string> retval;
472 for (unsigned int i = 0; i < execarray->len; i++)
473 {
474 auto cstr = g_array_index(execarray, gchar*, i);
475 if (cstr != nullptr)
476 {
477 retval.emplace_back(cstr);
478 }
479 }
480
481 /* This seems to work better than array_free(), I can't figure out why */
482 auto strv = (gchar**)g_array_free(execarray, FALSE);
483 g_strfreev(strv);
484
485 if (retval.empty())
486 {
487 g_warning("After parsing 'APP_EXEC=%s' we ended up with no tokens", exec.c_str());
488 }
489
490 /* See if we're doing apparmor by hand */
491 auto appexecpolicy = findEnv("APP_EXEC_POLICY", env);
492 if (!appexecpolicy.empty() && appexecpolicy != "unconfined")
493 {
494 retval.emplace(retval.begin(), "--");
495 retval.emplace(retval.begin(), appexecpolicy);
496 retval.emplace(retval.begin(), "-p");
497 retval.emplace(retval.begin(), AA_EXEC_PATH);
498 }
499
500 return retval;
501 }
502
503 /** Small helper that we can new/delete to work better with C stuff */
504 struct StartCHelper
505 {
506 std::shared_ptr<instance::SystemD> ptr;
507 std::shared_ptr<GDBusConnection> bus;
508 };
509
510 void SystemD::application_start_cb(GObject* obj, GAsyncResult* res, gpointer user_data)
511 {
512 auto data = static_cast<StartCHelper*>(user_data);
513
514 tracepoint(lomiri_app_launch, liblal_start_message_callback, std::string(data->ptr->appId_).c_str());
515
516 g_debug("Started Message Callback: %s", std::string(data->ptr->appId_).c_str());
517
518 GError* error{nullptr};
519
520 /* We don't care about the result but we need to make sure we don't
521 have a leak. */
522 unique_glib(g_dbus_connection_call_finish(G_DBUS_CONNECTION(obj), res, &error));
523
524 if (error != nullptr)
525 {
526 if (g_dbus_error_is_remote_error(error))
527 {
528 gchar* remote_error = g_dbus_error_get_remote_error(error);
529 g_debug("Remote error: %s", remote_error);
530 if (g_strcmp0(remote_error, "org.freedesktop.systemd1.UnitExists") == 0)
531 {
532 auto urls = instance::SystemD::urlsToStrv(data->ptr->urls_);
533 second_exec(data->bus.get(), /* DBus */
534 data->ptr->registry_->thread.getCancellable().get(), /* cancellable */
535 data->ptr->primaryPid(), /* primary pid */
536 std::string(data->ptr->appId_).c_str(), /* appid */
537 data->ptr->instance_.c_str(), /* instance */
538 urls.get()); /* urls */
539 }
540
541 g_free(remote_error);
542 }
543 else
544 {
545 if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
546 {
547 g_warning("Unable to emit event to start application: %s", error->message);
548 }
549 }
550 g_error_free(error);
551 }
552
553 delete data;
554 }
555
556 void SystemD::copyEnv(const std::string& envname, std::list<std::pair<std::string, std::string>>& env)
557 {
558 if (!findEnv(envname, env).empty())
559 {
560 g_debug("Already a value set for '%s' ignoring", envname.c_str());
561 return;
562 }
563
564 auto cvalue = getenv(envname.c_str());
565 g_debug("Copying Environment: %s", envname.c_str());
566 if (cvalue != nullptr)
567 {
568 std::string value{cvalue};
569 env.emplace_back(std::make_pair(envname, value));
570 }
571 else
572 {
573 g_debug("Unable to copy environment '%s'", envname.c_str());
574 }
575 }
576
577 void SystemD::copyEnvByPrefix(const std::string& prefix, std::list<std::pair<std::string, std::string>>& env)
578 {
579 for (unsigned int i = 0; environ[i] != nullptr; i++)
580 {
581 if (g_str_has_prefix(environ[i], prefix.c_str()))
582 {
583 std::string envname = environ[i];
584 envname.erase(envname.find('='));
585 copyEnv(envname, env);
586 }
587 }
588 }
589
590 std::shared_ptr<Application::Instance> SystemD::launch(
591 const AppID& appId,
592 const std::string& job,
593 const std::string& instance,
594 const std::vector<Application::URL>& urls,
595 launchMode mode,
596 std::function<std::list<std::pair<std::string, std::string>>(void)>& getenv)
597 {
598 if (appId.empty())
599 return {};
600
601 auto appJobs = getAllApplicationJobs();
602 bool isApplication = std::find(appJobs.begin(), appJobs.end(), job) != appJobs.end();
603
604 auto reg = getReg();
605 return reg->thread.executeOnThread<std::shared_ptr<instance::SystemD>>([&]() -> std::shared_ptr<instance::SystemD> {
606 auto manager = std::dynamic_pointer_cast<manager::SystemD>(reg->jobs());
607 std::string appIdStr{appId};
608 g_debug("Initializing params for an new instance::SystemD for: %s", appIdStr.c_str());
609
610 tracepoint(lomiri_app_launch, liblal_start, appIdStr.c_str());
611
612 int timeout = 1;
613 if (lomiri::app_launch::Registry::Impl::isWatchingAppStarting())
614 {
615 timeout = 0;
616 }
617
618 handshake_t* handshake{nullptr};
619
620 if (isApplication)
621 {
622 handshake = starting_handshake_start(appIdStr.c_str(), instance.c_str(), timeout);
623 if (handshake == nullptr)
624 {
625 g_warning("Unable to setup starting handshake");
626 }
627 }
628
629 /* Figure out the unit name for the job */
630 auto unitname = unitName(SystemD::UnitInfo{appIdStr, job, instance});
631
632 /* Build up our environment */
633 auto env = getenv();
634
635 env.emplace_back(std::make_pair("APP_ID", appIdStr)); /* Application ID */
636 env.emplace_back(std::make_pair("DESKTOP_FILE_HINT", appIdStr)); /* Application ID for .desktop matching */
637 env.emplace_back(std::make_pair("APP_LAUNCHER_PID", std::to_string(getpid()))); /* Who we are, for bugs */
638
639 copyEnv("DISPLAY", env);
640
641 for (const auto& prefix : {"DBUS_", "MIR_", "LOMIRI_APP_LAUNCH_"})
642 {
643 copyEnvByPrefix(prefix, env);
644 }
645
646 /* If we're in deb mode and launching legacy apps, they're gonna need
647 * more context, they really have no other way to get it. */
648 if (g_getenv("SNAP") == nullptr && appId.package.value().empty())
649 {
650 copyEnvByPrefix("QT_", env);
651 copyEnvByPrefix("XDG_", env);
652
653 /* If we're in Lomiri we don't want to pass it's platform, we want
654 * an application platform. */
655 removeEnv("QT_QPA_PLATFORM", env);
656 }
657
658 /* Mir socket if we don't have one in our env */
659 if (findEnv("MIR_SOCKET", env).empty())
660 {
661 env.emplace_back(std::make_pair("MIR_SOCKET", g_get_user_runtime_dir() + std::string{"/mir_socket"}));
662 }
663
664 if (!urls.empty())
665 {
666 auto accumfunc = [](const std::string& prev, Application::URL thisurl) -> std::string {
667 gchar* gescaped = g_shell_quote(thisurl.value().c_str());
668 std::string escaped;
669 if (gescaped != nullptr)
670 {
671 escaped = gescaped;
672 g_free(gescaped);
673 }
674 else
675 {
676 g_warning("Unable to escape URL: %s", thisurl.value().c_str());
677 return prev;
678 }
679
680 if (prev.empty())
681 {
682 return escaped;
683 }
684 else
685 {
686 return prev + " " + escaped;
687 }
688 };
689 auto urlstring = std::accumulate(urls.begin(), urls.end(), std::string{}, accumfunc);
690 env.emplace_back(std::make_pair("APP_URIS", urlstring));
691 }
692
693 if (mode == launchMode::TEST)
694 {
695 env.emplace_back(std::make_pair("QT_LOAD_TESTABILITY", "1"));
696 }
697
698 /* Convert to GVariant */
699 GVariantBuilder builder;
700 g_variant_builder_init(&builder, G_VARIANT_TYPE_TUPLE);
701
702 g_variant_builder_add_value(&builder, g_variant_new_string(unitname.c_str()));
703 g_variant_builder_add_value(&builder, g_variant_new_string("replace")); // Job mode
704
705 /* Parameter Array */
706 g_variant_builder_open(&builder, G_VARIANT_TYPE_ARRAY);
707
708 /* ExecStart */
709 auto commands = parseExec(env);
710 if (!commands.empty())
711 {
712 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
713 g_variant_builder_add_value(&builder, g_variant_new_string("ExecStart"));
714 g_variant_builder_open(&builder, G_VARIANT_TYPE_VARIANT);
715 g_variant_builder_open(&builder, G_VARIANT_TYPE_ARRAY);
716
717 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
718
719 gchar* pathexec = g_find_program_in_path(commands[0].c_str());
720 if (pathexec != nullptr)
721 {
722 g_variant_builder_add_value(&builder, g_variant_new_take_string(pathexec));
723 }
724 else
725 {
726 g_debug("Unable to find '%s' in PATH=%s", commands[0].c_str(), g_getenv("PATH"));
727 g_variant_builder_add_value(&builder, g_variant_new_string(commands[0].c_str()));
728 }
729
730 g_variant_builder_open(&builder, G_VARIANT_TYPE_ARRAY);
731 for (const auto& param : commands)
732 {
733 g_variant_builder_add_value(&builder, g_variant_new_string(param.c_str()));
734 }
735 g_variant_builder_close(&builder);
736
737 g_variant_builder_add_value(&builder, g_variant_new_boolean(FALSE));
738
739 g_variant_builder_close(&builder);
740 g_variant_builder_close(&builder);
741 g_variant_builder_close(&builder);
742 g_variant_builder_close(&builder);
743 }
744
745 /* RemainAfterExit */
746 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
747 g_variant_builder_add_value(&builder, g_variant_new_string("RemainAfterExit"));
748 g_variant_builder_open(&builder, G_VARIANT_TYPE_VARIANT);
749 g_variant_builder_add_value(&builder, g_variant_new_boolean(FALSE));
750 g_variant_builder_close(&builder);
751 g_variant_builder_close(&builder);
752
753 /* CollectMode */
754 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
755 g_variant_builder_add_value(&builder, g_variant_new_string("CollectMode"));
756 g_variant_builder_open(&builder, G_VARIANT_TYPE_VARIANT);
757 g_variant_builder_add_value(&builder, g_variant_new_string("inactive-or-failed"));
758 g_variant_builder_close(&builder);
759 g_variant_builder_close(&builder);
760
761 /* Type */
762 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
763 g_variant_builder_add_value(&builder, g_variant_new_string("Type"));
764 g_variant_builder_open(&builder, G_VARIANT_TYPE_VARIANT);
765 g_variant_builder_add_value(&builder, g_variant_new_string("simple"));
766 g_variant_builder_close(&builder);
767 g_variant_builder_close(&builder);
768
769 /* Working Directory */
770 if (!findEnv("APP_DIR", env).empty())
771 {
772 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
773 g_variant_builder_add_value(&builder, g_variant_new_string("WorkingDirectory"));
774 g_variant_builder_open(&builder, G_VARIANT_TYPE_VARIANT);
775 g_variant_builder_add_value(&builder, g_variant_new_string(findEnv("APP_DIR", env).c_str()));
776 g_variant_builder_close(&builder);
777 g_variant_builder_close(&builder);
778 }
779
780 /* Clean up env before shipping it */
781 for (const auto& rmenv :
782 {"APP_URIS", "APP_EXEC", "APP_EXEC_POLICY", "APP_LAUNCHER_PID",
783 "INSTANCE_ID", "MIR_SERVER_PLATFORM_PATH", "MIR_SERVER_PROMPT_FILE", "MIR_SERVER_HOST_SOCKET",
784 "LOMIRI_APP_LAUNCH_OOM_HELPER", "LOMIRI_APP_LAUNCH_LEGACY_ROOT"})
785 {
786 removeEnv(rmenv, env);
787 }
788
789 g_debug("Environment length: %d", envSize(env));
790
791 /* Environment */
792 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
793 g_variant_builder_add_value(&builder, g_variant_new_string("Environment"));
794 g_variant_builder_open(&builder, G_VARIANT_TYPE_VARIANT);
795 g_variant_builder_open(&builder, G_VARIANT_TYPE_ARRAY);
796 for (const auto& envvar : env)
797 {
798 if (!envvar.first.empty() && !envvar.second.empty())
799 {
800 g_variant_builder_add_value(&builder, g_variant_new_take_string(g_strdup_printf(
801 "%s=%s", envvar.first.c_str(), envvar.second.c_str())));
802 // g_debug("Setting environment: %s=%s", envvar.first.c_str(), envvar.second.c_str());
803 }
804 }
805
806 g_variant_builder_close(&builder);
807 g_variant_builder_close(&builder);
808 g_variant_builder_close(&builder);
809
810 if (isApplication) {
811 /*
812 * Conflicts - we do this to make sure apps will stop when Lomiri/
813 * display server dies, even if the application is SIGSTOP'ed.
814 */
815 g_variant_builder_open(&builder, G_VARIANT_TYPE_TUPLE);
816 g_variant_builder_add_value(&builder, g_variant_new_string("Conflicts"));
817 g_variant_builder_open(&builder, G_VARIANT_TYPE_VARIANT);
818 g_variant_builder_open(&builder, G_VARIANT_TYPE_ARRAY);
819 g_variant_builder_add_value(&builder, g_variant_new_string("lal-application-end.target"));
820 g_variant_builder_close(&builder);
821 g_variant_builder_close(&builder);
822 g_variant_builder_close(&builder);
823 }
824
825 /* Parameter Array */
826 g_variant_builder_close(&builder);
827
828 /* Dependent Units (none) */
829 g_variant_builder_add_value(&builder, g_variant_new_array(G_VARIANT_TYPE("(sa(sv))"), nullptr, 0));
830
831 auto retval = std::make_shared<instance::SystemD>(appId, job, instance, urls, reg);
832 auto chelper = new StartCHelper{};
833 chelper->ptr = retval;
834 chelper->bus = reg->_dbus;
835
836 tracepoint(lomiri_app_launch, handshake_wait, appIdStr.c_str());
837 starting_handshake_wait(handshake);
838 tracepoint(lomiri_app_launch, handshake_complete, appIdStr.c_str());
839
840 /* Call the job start function */
841 g_debug("Asking systemd to start task for: %s", appIdStr.c_str());
842 g_dbus_connection_call(manager->userbus_.get(), /* bus */
843 SYSTEMD_DBUS_ADDRESS, /* service name */
844 SYSTEMD_DBUS_PATH_MANAGER, /* Path */
845 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
846 "StartTransientUnit", /* method */
847 g_variant_builder_end(&builder), /* params */
848 G_VARIANT_TYPE("(o)"), /* return */
849 G_DBUS_CALL_FLAGS_NONE, /* flags */
850 -1, /* default timeout */
851 reg->thread.getCancellable().get(), /* cancellable */
852 application_start_cb, /* callback */
853 chelper /* object */
854 );
855
856 tracepoint(lomiri_app_launch, liblal_start_message_sent, appIdStr.c_str());
857
858 return retval;
859 });
860 }
861
862 std::shared_ptr<Application::Instance> SystemD::existing(const AppID& appId,
863 const std::string& job,
864 const std::string& instance,
865 const std::vector<Application::URL>& urls)
866 {
867 return std::make_shared<instance::SystemD>(appId, job, instance, urls, getReg());
868 }
869
870 std::vector<std::shared_ptr<instance::Base>> SystemD::instances(const AppID& appID, const std::string& job)
871 {
872 auto reg = getReg();
873
874 std::vector<std::shared_ptr<instance::Base>> instances;
875 std::vector<Application::URL> urls;
876
877 std::string sappid{appID};
878 for (const auto& unit : unitPaths)
879 {
880 const SystemD::UnitInfo& unitinfo = unit.first;
881
882 if (job != unitinfo.job)
883 {
884 continue;
885 }
886
887 if (sappid != unitinfo.appid)
888 {
889 continue;
890 }
891
892 instances.emplace_back(std::make_shared<instance::SystemD>(appID, job, unitinfo.inst, urls, reg));
893 }
894
895 g_debug("Found %d instances for AppID '%s'", int(instances.size()), std::string(appID).c_str());
896
897 return instances;
898 }
899
900 std::list<std::string> SystemD::runningAppIds(const std::list<std::string>& allJobs)
901 {
902 std::set<std::string> appids;
903
904 for (const auto& unit : unitPaths)
905 {
906 const SystemD::UnitInfo& unitinfo = unit.first;
907
908 if (std::find(allJobs.begin(), allJobs.end(), unitinfo.job) == allJobs.end())
909 {
910 continue;
911 }
912
913 appids.insert(unitinfo.appid);
914 }
915
916 return {appids.begin(), appids.end()};
917 }
918
919 std::string SystemD::userBusPath()
920 {
921 auto cpath = getenv("LOMIRI_APP_LAUNCH_SYSTEMD_PATH");
922 if (cpath != nullptr)
923 {
924 return cpath;
925 }
926 return std::string{"/run/user/"} + std::to_string(getuid()) + std::string{"/bus"};
927 }
928
929 /* TODO: Application job names */
930 const std::regex unitNaming{"^lomiri\\-app\\-launch\\-\\-(.*)\\-\\-(.*)\\-\\-([0-9]*)\\.service$"};
931
932 SystemD::UnitInfo SystemD::parseUnit(const std::string& unit) const
933 {
934 std::smatch match;
935 if (!std::regex_match(unit, match, unitNaming))
936 {
937 throw std::runtime_error{"Unable to parse unit name: " + unit};
938 }
939
940 return {match[2].str(), match[1].str(), match[3].str()};
941 }
942
943 // https://github.com/coreos/go-systemd/blob/v22.5.0/unit/escape.go#L36
944 //
945 // Replace the following characters with `\x%x`: Leading `.`,
946 // `-`, `\`, and anything not in this set: `:-_.\[0-9a-zA-Z]`
947 // Replace '/' with '-'.
948 //
949 // (Note that we're dealing with component, so the "leading `.`" part
950 // doesn't apply. Also we're allowing additionally '-' because we're not going
951 // to unescape the name back.)
952 static std::string escapeUnitComponent(const std::string & unescaped)
953 {
954 const std::string allowed = ":-_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
955
956 std::string escaped;
957 // Escaped string can only be longer, so reserve at least unescaped length.
958 escaped.reserve(unescaped.length());
959
960 for (size_t i = 0; i < unescaped.length(); i++) {
961 char c = unescaped[i];
962
963 if (c == '/') {
964 escaped += '-';
965 } else if (allowed.find(c) == std::string::npos) {
966 // https://stackoverflow.com/a/72132640
967 char buf[3] = { 0 };
968 std::to_chars(std::begin(buf), std::end(buf), (unsigned int)c, 16);
969
970 escaped += "\\x";
971 escaped += buf;
972 } else {
973 escaped += c;
974 }
975 }
976
977 return escaped;
978 }
979
980 std::string SystemD::unitName(const SystemD::UnitInfo& info) const
981 {
982 return std::string{"lomiri-app-launch--"} + info.job
983 + "--" + escapeUnitComponent(info.appid)
984 + "--" + info.inst
985 + ".service";
986 }
987
988 std::string SystemD::unitPath(const SystemD::UnitInfo& info)
989 {
990 auto reg = getReg();
991 auto data = unitPaths[info];
992
993 if (!data)
994 {
995 return {};
996 }
997
998 /* Execute on the thread so that we're sure that we're not in
999 a dbus call to get the value. No racey for you! */
1000 return reg->thread.executeOnThread<std::string>([&data]() { return data->unitpath; });
1001 }
1002
1003 void SystemD::systemdReloading(bool reloading)
1004 {
1005 bool wasReloading = systemdIsReloading_;
1006 systemdIsReloading_ = reloading;
1007
1008 if (wasReloading && !reloading) {
1009 /* Handle UnitRemoved without corresponding UnitNew. */
1010 auto it = unitPaths.begin();
1011 while (it != unitPaths.end()) {
1012 if (it->second->pendingRemoval)
1013 {
1014 auto info = it->first;
1015 it = unitPaths.erase(it);
1016 sig_jobStopped(info.job, info.appid, info.inst);
1017 }
1018 else
1019 {
1020 it++;
1021 }
1022 }
1023 }
1024 }
1025
1026 void SystemD::unitNew(const std::string& name,
1027 const std::string& path,
1028 const std::shared_ptr<GDBusConnection>& bus)
1029 {
1030 if (path == "/")
1031 {
1032 throw std::runtime_error{"Job path for unit is '/' so likely failed"};
1033 }
1034
1035 auto info = parseUnit(name);
1036
1037 g_debug("New Unit: %s", name.c_str());
1038
1039 auto reg = getReg();
1040
1041 auto data = std::make_shared<UnitData>();
1042 data->jobpath = path;
1043
1044 auto insertResult = unitPaths.insert(std::make_pair(info, data));
1045 if (!insertResult.second)
1046 {
1047 if (insertResult.first->second->pendingRemoval)
1048 {
1049 insertResult.first->second->pendingRemoval = false;
1050 return;
1051 }
1052 else
1053 {
1054 throw std::runtime_error{"Duplicate unit, not really new"};
1055 }
1056 }
1057
1058 /* We need to get the path, we're blocking everyone else on
1059 this call if they try to get the path. But we're just locking
1060 up the UAL thread so it should be a big deal. But if someone
1061 comes an asking at this point we'll think that we have the
1062 app, but not yet its path */
1063 GError* error{nullptr};
1064 auto call = unique_glib(g_dbus_connection_call_sync(bus.get(), /* user bus */
1065 SYSTEMD_DBUS_ADDRESS, /* bus name */
1066 SYSTEMD_DBUS_PATH_MANAGER, /* path */
1067 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
1068 "GetUnit", /* method */
1069 g_variant_new("(s)", name.c_str()), /* params */
1070 G_VARIANT_TYPE("(o)"), /* ret type */
1071 G_DBUS_CALL_FLAGS_NONE, /* flags */
1072 -1, /* timeout */
1073 reg->thread.getCancellable().get(), /* cancellable */
1074 &error));
1075
1076 if (error != nullptr)
1077 {
1078 std::string message = "Unable to get SystemD unit path for '" + name + "': " + error->message;
1079 g_error_free(error);
1080 throw std::runtime_error{message};
1081 }
1082
1083 /* Parse variant */
1084 gchar* gpath{nullptr};
1085 g_variant_get(call.get(), "(&o)", &gpath);
1086 if (gpath)
1087 {
1088 data->unitpath = gpath;
1089 }
1090
1091 sig_jobStarted(info.job, info.appid, info.inst);
1092 }
1093
1094 void SystemD::unitRemoved(const std::string& name, const std::string& path)
1095 {
1096 UnitInfo info = parseUnit(name);
1097
1098 auto it = unitPaths.find(info);
1099 if (it == unitPaths.end())
1100 return;
1101
1102 if (systemdIsReloading_)
1103 {
1104 it->second->pendingRemoval = true;
1105 }
1106 else
1107 {
1108 unitPaths.erase(it);
1109 sig_jobStopped(info.job, info.appid, info.inst);
1110 }
1111 }
1112
1113 pid_t SystemD::unitPrimaryPid(const AppID& appId, const std::string& job, const std::string& instance)
1114 {
1115 auto unitinfo = SystemD::UnitInfo{appId, job, instance};
1116 auto unitname = unitName(unitinfo);
1117 auto unitpath = unitPath(unitinfo);
1118
1119 if (unitpath.empty())
1120 {
1121 return 0;
1122 }
1123
1124 auto reg = getReg();
1125
1126 return reg->thread.executeOnThread<pid_t>([this, unitname, unitpath, reg]() {
1127 GError* error{nullptr};
1128 auto call = unique_glib(
1129 g_dbus_connection_call_sync(userbus_.get(), /* user bus */
1130 SYSTEMD_DBUS_ADDRESS, /* bus name */
1131 unitpath.c_str(), /* path */
1132 "org.freedesktop.DBus.Properties", /* interface */
1133 "Get", /* method */
1134 g_variant_new("(ss)", SYSTEMD_DBUS_IFACE_SERVICE, "MainPID"), /* params */
1135 G_VARIANT_TYPE("(v)"), /* ret type */
1136 G_DBUS_CALL_FLAGS_NONE, /* flags */
1137 -1, /* timeout */
1138 reg->thread.getCancellable().get(), /* cancellable */
1139 &error));
1140
1141 if (error != nullptr)
1142 {
1143 auto message =
1144 std::string{"Unable to get SystemD PID for '"} + unitname + std::string{"': "} + error->message;
1145 g_error_free(error);
1146 throw std::runtime_error(message);
1147 }
1148
1149 /* Parse variant */
1150 GVariantUPtr vpid{nullptr, GVariantDeleter{}};
1151 {
1152 GVariant* tmp{nullptr};
1153 g_variant_get(call.get(), "(v)", &tmp);
1154 vpid = unique_glib(tmp);
1155 }
1156
1157 pid_t pid;
1158 pid = g_variant_get_uint32(vpid.get());
1159
1160 return pid;
1161 });
1162 }
1163
1164 std::vector<pid_t> SystemD::unitPids(const AppID& appId, const std::string& job, const std::string& instance)
1165 {
1166 auto unitinfo = SystemD::UnitInfo{appId, job, instance};
1167 auto unitname = unitName(unitinfo);
1168 auto unitpath = unitPath(unitinfo);
1169
1170 if (unitpath.empty())
1171 {
1172 return {};
1173 }
1174
1175 auto reg = getReg();
1176
1177 auto cgrouppath = reg->thread.executeOnThread<std::string>([this, unitname, unitpath, reg]() {
1178 GError* error{nullptr};
1179 auto call = unique_glib(
1180 g_dbus_connection_call_sync(userbus_.get(), /* user bus */
1181 SYSTEMD_DBUS_ADDRESS, /* bus name */
1182 unitpath.c_str(), /* path */
1183 "org.freedesktop.DBus.Properties", /* interface */
1184 "Get", /* method */
1185 g_variant_new("(ss)", SYSTEMD_DBUS_IFACE_SERVICE, "ControlGroup"), /* params */
1186 G_VARIANT_TYPE("(v)"), /* ret type */
1187 G_DBUS_CALL_FLAGS_NONE, /* flags */
1188 -1, /* timeout */
1189 reg->thread.getCancellable().get(), /* cancellable */
1190 &error));
1191
1192 if (error != nullptr)
1193 {
1194 auto message = std::string{"Unable to get SystemD Control Group for '"} + unitname + std::string{"': "} +
1195 error->message;
1196 g_error_free(error);
1197 throw std::runtime_error(message);
1198 }
1199
1200 /* Parse variant */
1201 GVariantUPtr vstring{nullptr, GVariantDeleter{}};
1202 {
1203 GVariant* tmp{nullptr};
1204 g_variant_get(call.get(), "(v)", &tmp);
1205 vstring = unique_glib(tmp);
1206 }
1207
1208 if (vstring == nullptr)
1209 {
1210 return std::string{};
1211 }
1212
1213 std::string group;
1214 auto ggroup = g_variant_get_string(vstring.get(), nullptr);
1215 if (ggroup != nullptr)
1216 {
1217 group = ggroup;
1218 }
1219
1220 return group;
1221 });
1222
1223 GError* error = nullptr;
1224
1225 GCharUPtr pidstr{nullptr, &g_free};
1226
1227 // Try cgv1, then v2
1228 auto cgroup_interfaces = {
1229 unique_gchar(g_build_filename(cgroup_root_.c_str(), cgrouppath.c_str(), "tasks", nullptr)),
1230 unique_gchar(g_build_filename(cgroup_root_.c_str(), cgrouppath.c_str(), "cgroup.procs", nullptr))
1231 };
1232
1233 for (const auto& fullpath : cgroup_interfaces) {
1234 if (g_file_test(fullpath.get(), static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))) {
1235 g_debug("Getting PIDs from %s", fullpath.get());
1236 gchar* tmp = nullptr;
1237 g_file_get_contents(fullpath.get(), &tmp, nullptr, &error);
1238 pidstr = unique_gchar(tmp);
1239 break;
1240 }
1241 }
1242
1243 if (!pidstr) {
1244 g_set_error(&error, 0, ENOENT, "Couldn't find actual cgroup processes: %s", strerror(ENOENT));
1245 }
1246
1247 if (error != nullptr)
1248 {
1249 g_warning("Unable to read cgroup PID list: %s", error->message);
1250 g_error_free(error);
1251 return {};
1252 }
1253
1254 auto pidlines = unique_gcharv(g_strsplit(pidstr.get(), "\n", -1));
1255 std::vector<pid_t> pids;
1256
1257 for (auto i = 0; pidlines.get()[i] != nullptr; i++)
1258 {
1259 const gchar* pidline = pidlines.get()[i];
1260 if (pidline[0] != '\n')
1261 {
1262 auto pid = std::atoi(pidline);
1263 if (pid != 0)
1264 {
1265 pids.emplace_back(pid);
1266 }
1267 }
1268 }
1269
1270 return pids;
1271 }
1272
1273 void SystemD::stopUnit(const AppID& appId, const std::string& job, const std::string& instance)
1274 {
1275 auto unitname = unitName(SystemD::UnitInfo{appId, job, instance});
1276 auto reg = getReg();
1277
1278 reg->thread.executeOnThread<bool>([this, unitname, reg] {
1279 GError* error{nullptr};
1280 unique_glib(g_dbus_connection_call_sync(
1281 userbus_.get(), /* user bus */
1282 SYSTEMD_DBUS_ADDRESS, /* bus name */
1283 SYSTEMD_DBUS_PATH_MANAGER, /* path */
1284 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
1285 "StopUnit", /* method */
1286 g_variant_new(
1287 "(ss)", /* params */
1288 unitname.c_str(), /* param: specify unit */
1289 "replace-irreversibly"), /* param: replace the current job but don't allow us to be replaced */
1290 G_VARIANT_TYPE("(o)"), /* ret type */
1291 G_DBUS_CALL_FLAGS_NONE, /* flags */
1292 -1, /* timeout */
1293 reg->thread.getCancellable().get(), /* cancellable */
1294 &error));
1295
1296 if (error != nullptr)
1297 {
1298 auto message =
1299 std::string{"Unable to get SystemD to stop '"} + unitname + std::string{"': "} + error->message;
1300 g_error_free(error);
1301 throw std::runtime_error(message);
1302 }
1303
1304 return true;
1305 });
1306 }
1307
1308 core::Signal<const std::string&, const std::string&, const std::string&>& SystemD::jobStarted()
1309 {
1310 /* Ensure we're connecting to the signals */
1311 return sig_jobStarted;
1312 }
1313
1314 core::Signal<const std::string&, const std::string&, const std::string&>& SystemD::jobStopped()
1315 {
1316 /* Ensure we're connecting to the signals */
1317 return sig_jobStopped;
1318 }
1319
1320 struct FailedData
1321 {
1322 std::weak_ptr<Registry::Impl> registry;
1323 };
1324
1325 core::Signal<const std::string&, const std::string&, const std::string&, Registry::FailureType>& SystemD::jobFailed()
1326 {
1327 std::call_once(flag_appFailed, [this]() {
1328 auto reg = getReg();
1329 reg->thread.executeOnThread<bool>([this, reg]() {
1330 auto data = new FailedData{reg};
1331
1332 handle_appFailed = managedDBusSignalConnection(
1333 g_dbus_connection_signal_subscribe(
1334 userbus_.get(), /* bus */
1335 SYSTEMD_DBUS_ADDRESS, /* sender */
1336 "org.freedesktop.DBus.Properties", /* interface */
1337 "PropertiesChanged", /* signal */
1338 nullptr, /* path */
1339 SYSTEMD_DBUS_IFACE_SERVICE, /* arg0 */
1340 G_DBUS_SIGNAL_FLAGS_NONE,
1341 [](GDBusConnection*, const gchar*, const gchar* path, const gchar*, const gchar*, GVariant* params,
1342 gpointer user_data) -> void {
1343 auto data = static_cast<FailedData*>(user_data);
1344 auto reg = data->registry.lock();
1345
1346 if (!reg)
1347 {
1348 throw std::runtime_error{"Lost our connection with the registry"};
1349 }
1350
1351 auto manager = std::dynamic_pointer_cast<SystemD>(reg->jobs());
1352
1353 /* Check to see if this is a path we care about */
1354 bool pathfound{false};
1355 UnitInfo unitinfo;
1356 for (const auto& unit : manager->unitPaths)
1357 {
1358 if (unit.second->unitpath == path)
1359 {
1360 pathfound = true;
1361 unitinfo = unit.first;
1362 break;
1363 }
1364 }
1365 if (!pathfound)
1366 {
1367 return;
1368 }
1369
1370 /* Now see if it is a property we care about */
1371 auto vdict = unique_glib(g_variant_get_child_value(params, 1));
1372 GVariantDict dict;
1373 g_variant_dict_init(&dict, vdict.get());
1374
1375 if (g_variant_dict_contains(&dict, "Result") == FALSE)
1376 {
1377 /* We don't care about anything else */
1378 g_variant_dict_clear(&dict);
1379 return;
1380 }
1381
1382 /* Check to see if it just was successful */
1383 const gchar* value{nullptr};
1384 g_variant_dict_lookup(&dict, "Result", "&s", &value);
1385
1386 if (g_strcmp0(value, "success") == 0)
1387 {
1388 g_variant_dict_clear(&dict);
1389 return;
1390 }
1391 g_variant_dict_clear(&dict);
1392
1393 /* Reset the failure bit on the unit */
1394 manager->resetUnit(unitinfo);
1395
1396 /* Oh, we might want to do something now */
1397 auto reason{Registry::FailureType::CRASH};
1398 if (g_strcmp0(value, "exit-code") == 0)
1399 {
1400 reason = Registry::FailureType::START_FAILURE;
1401 }
1402
1403 manager->sig_jobFailed(unitinfo.job, unitinfo.appid, unitinfo.inst, reason);
1404 }, /* callback */
1405 data, /* user data */
1406 [](gpointer user_data) {
1407 auto data = static_cast<FailedData*>(user_data);
1408 delete data;
1409 }), /* user data destroy */
1410 userbus_);
1411
1412 return true;
1413 });
1414 });
1415
1416 return sig_jobFailed;
1417 }
1418
1419 /** Requests that systemd reset a unit that has been marked as
1420 failed so that we can continue to work with it. This includes
1421 starting it anew, which can fail if it is left in the failed
1422 state. */
1423 void SystemD::resetUnit(const UnitInfo& info)
1424 {
1425 if (noResetUnits_)
1426 {
1427 return;
1428 }
1429
1430 auto reg = getReg();
1431 auto unitname = unitName(info);
1432 auto bus = userbus_;
1433 auto cancel = reg->thread.getCancellable();
1434
1435 reg->thread.executeOnThread([bus, unitname, cancel] {
1436 if (g_cancellable_is_cancelled(cancel.get()))
1437 {
1438 return;
1439 }
1440
1441 g_dbus_connection_call(bus.get(), /* user bus */
1442 SYSTEMD_DBUS_ADDRESS, /* bus name */
1443 SYSTEMD_DBUS_PATH_MANAGER, /* path */
1444 SYSTEMD_DBUS_IFACE_MANAGER, /* interface */
1445 "ResetFailedUnit", /* method */
1446 g_variant_new("(s)", /* params */
1447 unitname.c_str()), /* param: specify unit */
1448 nullptr, /* ret type */
1449 G_DBUS_CALL_FLAGS_NONE, /* flags */
1450 -1, /* timeout */
1451 cancel.get(), /* cancellable */
1452 [](GObject* obj, GAsyncResult* res, gpointer user_data) {
1453 GError* error{nullptr};
1454 unique_glib(g_dbus_connection_call_finish(G_DBUS_CONNECTION(obj), res, &error));
1455
1456 if (error != nullptr)
1457 {
1458 if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
1459 {
1460 g_warning("Unable to reset failed unit: %s", error->message);
1461 }
1462 g_error_free(error);
1463 return;
1464 }
1465
1466 g_debug("Reset Failed Unit");
1467 },
1468 nullptr);
1469 });
1470 }
1471
1472 } // namespace manager
1473 } // namespace jobs
1474 } // namespace app_launch
1475 } // namespace lomiri