Debian Codegraph @

liblomiri-app-launch/helper.cpp

raw
1 /*
2 * Copyright © 2016-2017 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 <algorithm>
21 #include <list>
22 #include <numeric>
23
24 #include <lomiri/util/GObjectMemory.h>
25 #include <lomiri/util/GlibMemory.h>
26 #include <lomiri/util/ResourcePtr.h>
27
28 #include "helper-impl.h"
29 #include "registry-impl.h"
30 #include "signal-unsubscriber.h"
31
32 #include "lomiri-app-launch.h"
33
34 extern "C" {
35 #include "proxy-socket-demangler.h"
36 #include <gio/gunixfdlist.h>
37 }
38
39 using namespace lomiri::util;
40
41 namespace lomiri
42 {
43 namespace app_launch
44 {
45 namespace helper_impls
46 {
47
48 /**********************
49 * Instance
50 **********************/
51
52 BaseInstance::BaseInstance(const Helper::Type& type, const std::shared_ptr<jobs::instance::Base>& inst)
53 : impl{inst}
54 , type_(type)
55 {
56 }
57
58 BaseInstance::BaseInstance(const Helper::Type& type, const std::shared_ptr<Application::Instance>& inst)
59 : impl{std::dynamic_pointer_cast<jobs::instance::Base>(inst)}
60 , type_(type)
61 {
62 }
63
64 bool BaseInstance::isRunning()
65 {
66 return impl->isRunning();
67 }
68
69 void BaseInstance::stop()
70 {
71 impl->stop();
72 }
73
74 /**********************
75 * Helper Class
76 **********************/
77
78 Base::Base(const Helper::Type& type, const AppID& appid, const std::shared_ptr<Registry::Impl>& registry)
79 : _type(type)
80 , _appid(appid)
81 , registry_(registry)
82 {
83 }
84
85 AppID Base::appId() const
86 {
87 return _appid;
88 }
89
90 bool Base::hasInstances()
91 {
92 return instances().size() > 0;
93 }
94
95 std::vector<std::shared_ptr<Helper::Instance>> Base::instances()
96 {
97 auto insts = registry_->jobs()->instances(_appid, _type.value());
98 std::vector<std::shared_ptr<Helper::Instance>> wrapped{insts.size()};
99
100 std::transform(insts.begin(), insts.end(), wrapped.begin(), [this](std::shared_ptr<jobs::instance::Base>& inst) {
101 return std::make_shared<BaseInstance>(_type, inst);
102 });
103
104 return wrapped;
105 }
106
107 /** Find an instance that we already know the ID of */
108 std::shared_ptr<Helper::Instance> Base::existingInstance(const std::string& instanceid)
109 {
110 auto appinst = registry_->jobs()->existing(_appid, _type.value(), instanceid, {});
111
112 return std::make_shared<BaseInstance>(_type, appinst);
113 }
114
115 std::string genInstanceId()
116 {
117 return std::to_string(g_get_real_time());
118 }
119
120 std::vector<Application::URL> appURL(const std::vector<Helper::URL>& in)
121 {
122 std::vector<Application::URL> out;
123
124 for (const auto& hurl : in)
125 {
126 out.push_back(Application::URL::from_raw(hurl.value()));
127 }
128
129 return out;
130 }
131
132 bool Base::isSnapPackage()
133 {
134 std::shared_ptr<snapd::Info::PkgInfo> pkginfo;
135
136 pkginfo = registry_->snapdInfo.pkgInfo(_appid.package);
137
138 return pkginfo && pkginfo->revision == _appid.version.value() &&
139 pkginfo->appnames.find(_appid.appname) != pkginfo->appnames.end();
140 }
141
142 /** Sets up the executable environment variable based on the appid and
143 * the type of helper. We look for the exec-tool, but if we can't find
144 * it we're cool with that and we just execute the helper. If we do find
145 * an exec-tool we'll use that to fill in the parameters. For legacy appid's
146 * we'll allow the exec-tool to set everything. */
147 std::list<std::pair<std::string, std::string>> Base::defaultEnv()
148 {
149 std::list<std::pair<std::string, std::string>> envs{};
150 auto csnapenv = getenv("SNAP");
151 std::string helperpath;
152 if (csnapenv != nullptr)
153 {
154 helperpath = std::string{csnapenv} + "/" HELPER_EXEC_TOOL_DIR "/" + _type.value() + "/exec-tool";
155 }
156 else
157 {
158 helperpath = HELPER_EXEC_TOOL_DIR "/" + _type.value() + "/exec-tool";
159 }
160
161 std::list<std::string> exec;
162 /* We have an exec tool that'll give us params */
163 bool haveExecTool = g_file_test(helperpath.c_str(), G_FILE_TEST_IS_EXECUTABLE);
164 if (haveExecTool)
165 {
166 const char* chelperenv = getenv("LOMIRI_APP_LAUNCH_HELPER_HELPER");
167 if (chelperenv == nullptr)
168 {
169 chelperenv = HELPER_HELPER_TOOL;
170 }
171
172 if (csnapenv != nullptr)
173 {
174 exec.push_back(std::string{csnapenv} + "/" + chelperenv);
175 }
176 else
177 {
178 exec.push_back(std::string{"/"} + chelperenv);
179 }
180 exec.push_back(helperpath);
181 }
182 else
183 {
184 if (_appid.package.value().empty())
185 {
186 throw std::runtime_error{
187 "Executing a helper that isn't package, but doesn't have an exec-tool. We can't do that. Sorry. Bad "
188 "things will happen."};
189 }
190 }
191
192 /* This is kinda hard coded for snaps right now, we don't have
193 * another posibility today other than really custom stuff. But
194 * if we do, we'll need to abstract this. */
195 /* Insert package executable */
196 if (isSnapPackage())
197 {
198 std::string snapdir{"/snap/bin/"};
199
200 if (_appid.package.value() == _appid.appname.value())
201 {
202 exec.push_back(snapdir + _appid.package.value());
203 }
204 else
205 {
206 exec.push_back(snapdir + _appid.package.value() + "." + _appid.appname.value());
207 }
208 }
209 else if (!haveExecTool)
210 {
211 throw std::runtime_error{"Error: Missing trusted helper for " + _type.value() + " at " + helperpath};
212 }
213
214 exec.push_back("--");
215 exec.push_back("%U");
216
217 envs.emplace_back(
218 std::make_pair("APP_EXEC", std::accumulate(exec.begin(), exec.end(), std::string{},
219 [](const std::string& accum, const std::string& addon) {
220 return accum.empty() ? addon : accum + " " + addon;
221 })));
222
223 envs.emplace_back(std::make_pair("HELPER_TYPE", _type.value()));
224 /* apply AppArmor policy except for Snap or legacy apps */
225 envs.emplace_back(std::make_pair("HELPER_POLICY",
226 (!isSnapPackage() && !_appid.package.value().empty()) ?
227 std::string(_appid) : std::string("unconfined")));
228
229 return envs;
230 }
231
232 std::shared_ptr<Helper::Instance> Base::launch(std::vector<Helper::URL> urls)
233 {
234 auto defaultenv = defaultEnv();
235 std::function<std::list<std::pair<std::string, std::string>>()> envfunc = [defaultenv]() { return defaultenv; };
236
237 return std::make_shared<BaseInstance>(
238 _type,
239 registry_->jobs()->launch(_appid, _type.value(), genInstanceId(), appURL(urls),
240 jobs::manager::launchMode::STANDARD, envfunc));
241 }
242
243 #ifdef LAL_USE_MIRCLIENT
244 class MirFDProxy
245 {
246 public:
247 std::shared_ptr<Registry::Impl> reg_;
248 ResourcePtr<int, void (*)(int)> mirfd;
249 std::shared_ptr<proxySocketDemangler> skel;
250 ManagedSignalConnection<proxySocketDemangler> handle;
251 std::string path;
252 std::string name;
253 guint timeout{0};
254
255 MirFDProxy(MirPromptSession* session, const AppID& appid, const std::shared_ptr<Registry::Impl>& reg)
256 : reg_(reg)
257 , mirfd(0,
258 [](int fp) {
259 if (fp != 0)
260 close(fp);
261 })
262 , handle(SignalUnsubscriber<proxySocketDemangler>{})
263 , name(g_dbus_connection_get_unique_name(reg->_dbus.get()))
264 {
265 if (appid.empty())
266 {
267 throw std::runtime_error{"Invalid AppID"};
268 }
269
270 /* Get the Mir FD */
271 std::promise<int> promise;
272 mir_prompt_session_new_fds_for_prompt_providers(
273 session, 1,
274 [](MirPromptSession* session, size_t count, int const* fdin, void* user_data) {
275 auto promise = static_cast<std::promise<int>*>(user_data);
276
277 if (count != 1)
278 {
279 g_warning("Mir trusted session returned %d FDs instead of one", (int)count);
280 promise->set_value(0);
281 return;
282 }
283
284 promise->set_value(fdin[0]);
285 },
286 &promise);
287
288 mirfd.reset(promise.get_future().get());
289
290 if (mirfd.get() == 0)
291 {
292 throw std::runtime_error{"Unable to Mir FD from Prompt Session"};
293 }
294
295 /* Setup the DBus interface */
296 std::tie(skel, handle, path) = reg->thread.executeOnThread<std::tuple<
297 std::shared_ptr<proxySocketDemangler>, ManagedSignalConnection<proxySocketDemangler>, std::string>>(
298 [this, appid, reg]() {
299 auto skel = share_gobject(proxy_socket_demangler_skeleton_new());
300 auto handle = managedSignalConnection<proxySocketDemangler>(
301 g_signal_connect(G_OBJECT(skel.get()), "handle-get-mir-socket", G_CALLBACK(staticProxyCb), this),
302 skel);
303
304 /* Find a path to export on */
305 auto dbusAppid = appid.dbusID();
306 std::string path;
307
308 while (path.empty())
309 {
310 GError* error = nullptr;
311 std::string tryname = "/com/lomiri/LomiriAppLaunch/" + dbusAppid + "/" + std::to_string(rand());
312
313 g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(skel.get()), reg->_dbus.get(),
314 tryname.c_str(), &error);
315
316 if (error == nullptr)
317 {
318 path = tryname;
319 }
320 else
321 {
322 if (!g_error_matches(error, G_DBUS_ERROR, G_DBUS_ERROR_OBJECT_PATH_IN_USE))
323 {
324 std::string message = "Unable to export Mir trusted proxy: " + std::string{error->message};
325 g_clear_error(&error);
326 throw std::runtime_error{message};
327 }
328 g_clear_error(&error);
329 }
330 }
331
332 return std::make_tuple(skel, std::move(handle), path);
333 });
334 }
335
336 ~MirFDProxy()
337 {
338 g_debug("Mir Prompt Proxy shutdown");
339 g_dbus_interface_skeleton_unexport(G_DBUS_INTERFACE_SKELETON(skel.get()));
340 }
341
342 void setTimeout(guint timeoutin)
343 {
344 timeout = timeoutin;
345 }
346
347 bool proxyCb(GDBusMethodInvocation* invocation)
348 {
349 if (mirfd.get() == 0)
350 {
351 g_warning("Mir FD proxy called with no FDs!");
352 return false;
353 }
354
355 GError* error = nullptr;
356 std::unique_ptr<GUnixFDList, decltype(&g_object_unref)> list(g_unix_fd_list_new(), &g_object_unref);
357 g_unix_fd_list_append(list.get(), mirfd.get(), &error);
358
359 if (error != nullptr)
360 {
361 g_warning("Unable to pass FD %d: %s", mirfd.get(), error->message);
362 g_error_free(error);
363 return false;
364 }
365
366 /* Index into fds */
367 auto handle = g_variant_new_handle(0);
368 auto tuple = g_variant_new_tuple(&handle, 1);
369 g_dbus_method_invocation_return_value_with_unix_fd_list(invocation, tuple, list.get());
370 mirfd.dealloc();
371
372 /* Remove the timeout on the mainloop */
373 auto reg = reg_;
374 auto timeoutlocal = timeout;
375
376 reg->thread.executeOnThread([reg, timeoutlocal]() { reg->thread.removeSource(timeoutlocal); });
377
378 return true;
379 }
380
381 static gboolean staticProxyCb(GObject* obj, GDBusMethodInvocation* invocation, gpointer user_data)
382 {
383 return static_cast<MirFDProxy*>(user_data)->proxyCb(invocation) ? TRUE : FALSE;
384 }
385
386 std::string getPath()
387 {
388 return path;
389 }
390
391 std::string getName()
392 {
393 return name;
394 }
395 };
396
397 std::shared_ptr<Helper::Instance> Base::launch(MirPromptSession* session, std::vector<Helper::URL> urls)
398 {
399 std::shared_ptr<MirFDProxy> proxy;
400 try
401 {
402 proxy = std::make_shared<MirFDProxy>(session, _appid, registry_);
403 }
404 catch (std::runtime_error& e)
405 {
406 g_warning("Error setting up Mir FD Proxy: %s", e.what());
407 return {};
408 }
409
410 auto defaultenvs = defaultEnv();
411 std::function<std::list<std::pair<std::string, std::string>>()> envfunc = [defaultenvs, proxy]() {
412 auto envs = defaultenvs;
413
414 envs.emplace_back(std::make_pair("LOMIRI_APP_LAUNCH_DEMANGLE_PATH", proxy->getPath()));
415 envs.emplace_back(std::make_pair("LOMIRI_APP_LAUNCH_DEMANGLE_NAME", proxy->getName()));
416
417 return envs;
418 };
419
420 /* This will maintain a reference to the proxy for two
421 seconds. And then it'll be dropped. */
422 proxy->setTimeout(registry_->thread.timeout(std::chrono::seconds{2}, [proxy]() { g_debug("Mir Proxy Timeout"); }));
423
424 return std::make_shared<BaseInstance>(
425 _type,
426 registry_->jobs()->launch(_appid, _type.value(), genInstanceId(), appURL(urls),
427 jobs::manager::launchMode::STANDARD, envfunc));
428 }
429 #endif
430
431 } // namespace helper_impl
432
433 /***************************/
434 /* Helper Public Functions */
435 /***************************/
436
437 std::shared_ptr<Helper> Helper::create(Type type, AppID appid, std::shared_ptr<Registry> registry)
438 {
439 return registry->impl->createHelper(type, appid, registry->impl);
440 }
441
442 bool Helper::operator==(const Helper& b) const
443 {
444 auto ja = dynamic_cast<const helper_impls::Base*>(this);
445 auto jb = dynamic_cast<const helper_impls::Base*>(&b);
446
447 return ja->appId() == jb->appId() && ja->getType() == jb->getType();
448 }
449
450 bool Helper::operator!=(const Helper& b) const
451 {
452 auto ja = dynamic_cast<const helper_impls::Base*>(this);
453 auto jb = dynamic_cast<const helper_impls::Base*>(&b);
454
455 return ja->appId() != jb->appId() || ja->getType() != jb->getType();
456 }
457
458 bool Helper::Instance::operator==(const Helper::Instance& b) const
459 {
460 auto ja = dynamic_cast<const helper_impls::BaseInstance*>(this);
461 auto jb = dynamic_cast<const helper_impls::BaseInstance*>(&b);
462
463 return ja->getAppId() == jb->getAppId() && /* AppID */
464 ja->getType() == jb->getType() && /* Type */
465 ja->getInstanceId() == jb->getInstanceId(); /* Instance ID */
466 }
467
468 bool Helper::Instance::operator!=(const Helper::Instance& b) const
469 {
470 auto ja = dynamic_cast<const helper_impls::BaseInstance*>(this);
471 auto jb = dynamic_cast<const helper_impls::BaseInstance*>(&b);
472
473 return ja->getAppId() != jb->getAppId() || /* AppID */
474 ja->getType() != jb->getType() || /* Type */
475 ja->getInstanceId() != jb->getInstanceId(); /* Instance ID */
476 }
477
478 /* Hardcore socket stuff */
479 #include <sys/socket.h>
480 #include <sys/types.h>
481 #include <sys/un.h>
482
483 void Helper::setExec(std::vector<std::string> exec)
484 {
485 auto cenv = getenv("LOMIRI_APP_LAUNCH_HELPER_EXECTOOL_SETEXEC_SOCKET");
486 if (cenv == nullptr)
487 {
488 throw std::runtime_error{"Unable to find a socket to write exec information to."};
489 }
490
491 class SmartSocket
492 {
493 public:
494 int fd;
495 SmartSocket()
496 : fd(socket(AF_UNIX, SOCK_STREAM, 0))
497 {
498 }
499 ~SmartSocket()
500 {
501 close(fd);
502 }
503 };
504
505 SmartSocket sock;
506 if (sock.fd <= 0)
507 {
508 throw std::runtime_error{"Unable to create socket to systemd-helper-helper"};
509 }
510
511 struct sockaddr_un socketaddr = {0};
512 socketaddr.sun_family = AF_UNIX;
513 strncpy(socketaddr.sun_path, cenv, sizeof(socketaddr.sun_path) - 1);
514 socketaddr.sun_path[0] = 0;
515
516 if (connect(sock.fd, (const struct sockaddr*)&socketaddr, sizeof(struct sockaddr_un)) < 0)
517 {
518 throw std::runtime_error{"Unable to connecto to socket of systemd-helper-helper"};
519 }
520
521 for (const auto& item : exec)
522 {
523 auto citem = item.c_str();
524 int writesize = write(sock.fd, citem, strlen(citem) + 1);
525
526 if (writesize <= 0)
527 {
528 throw std::runtime_error{"Error writing to systemd-helper-helper socket"};
529 }
530 }
531 }
532
533 } // namespace app_launch
534 } // namespace lomiri