Debian Codegraph @

liblomiri-app-launch/snapd-info.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 "snapd-info.h"
21
22 #include "registry-impl.h"
23
24 #include <curl/curl.h>
25 #include <vector>
26
27 namespace lomiri
28 {
29 namespace app_launch
30 {
31 namespace snapd
32 {
33
34 /** Initializes the info object which mostly means checking what is overridden
35 by environment variables (mostly for testing) and making sure there is a
36 snapd socket available to us. */
37 Info::Info()
38 {
39 auto snapdEnv = g_getenv("LOMIRI_APP_LAUNCH_SNAPD_SOCKET");
40 if (G_UNLIKELY(snapdEnv != nullptr))
41 {
42 snapdSocket = snapdEnv;
43 }
44 else
45 {
46 snapdSocket = "/run/snapd.socket";
47 }
48
49 auto snapcBasedir = g_getenv("LOMIRI_APP_LAUNCH_SNAP_BASEDIR");
50 if (G_UNLIKELY(snapcBasedir != nullptr))
51 {
52 snapBasedir = snapcBasedir;
53 }
54 else
55 {
56 snapBasedir = "/snap";
57 }
58
59 if (g_file_test(snapdSocket.c_str(), G_FILE_TEST_EXISTS))
60 {
61 snapdExists = true;
62 }
63 }
64
65 /** Gets package information out of snapd by using the REST
66 interface and turning the JSON object into a C++ Struct
67
68 \param package Name of the package to look for
69 */
70 std::shared_ptr<Info::PkgInfo> Info::pkgInfo(const AppID::Package &package) const
71 {
72 if (!snapdExists)
73 {
74 return {};
75 }
76
77 if (package.value().empty())
78 {
79 return {};
80 }
81
82 try
83 {
84 auto snapnode = snapdJson("/v2/snaps/" + package.value());
85 auto snapobject = json_node_get_object(snapnode.get());
86 if (snapobject == nullptr)
87 {
88 throw std::runtime_error("Results returned by snapd were not a valid JSON object");
89 }
90
91 /******************************************/
92 /* Validation of the object we got */
93 /******************************************/
94 for (const auto &member : {"apps"})
95 {
96 if (!json_object_has_member(snapobject, member))
97 {
98 throw std::runtime_error("Snap JSON didn't have a '" + std::string(member) + "'");
99 }
100 }
101
102 for (const auto &member : {"name", "status", "revision", "type", "version"})
103 {
104 if (!json_object_has_member(snapobject, member))
105 {
106 throw std::runtime_error("Snap JSON didn't have a '" + std::string(member) + "'");
107 }
108
109 auto node = json_object_get_member(snapobject, member);
110 if (json_node_get_node_type(node) != JSON_NODE_VALUE)
111 {
112 throw std::runtime_error{"Snap JSON had a '" + std::string(member) + "' but it's an object!"};
113 }
114
115 if (json_node_get_value_type(node) != G_TYPE_STRING)
116 {
117 throw std::runtime_error{"Snap JSON had a '" + std::string(member) + "' but it's not a string!"};
118 }
119 }
120
121 std::string namestr = json_object_get_string_member(snapobject, "name");
122 if (namestr != package.value())
123 {
124 throw std::runtime_error("Snapd returned information for snap '" + namestr + "' when we asked for '" +
125 package.value() + "'");
126 }
127
128 std::string statusstr = json_object_get_string_member(snapobject, "status");
129 if (statusstr != "active")
130 {
131 throw std::runtime_error("Snap is not in the 'active' state.");
132 }
133
134 std::string typestr = json_object_get_string_member(snapobject, "type");
135 if (typestr != "app")
136 {
137 throw std::runtime_error("Specified snap is not an application, we only support applications");
138 }
139
140 /******************************************/
141 /* Validation complete — build the object */
142 /******************************************/
143
144 auto pkgstruct = std::make_shared<PkgInfo>();
145 pkgstruct->name = namestr;
146 pkgstruct->version = json_object_get_string_member(snapobject, "version");
147 std::string revisionstr = json_object_get_string_member(snapobject, "revision");
148 pkgstruct->revision = revisionstr;
149
150 /* TODO: Seems like snapd should give this to us */
151 auto gdir = g_build_filename(snapBasedir.c_str(), namestr.c_str(), revisionstr.c_str(), nullptr);
152 pkgstruct->directory = gdir;
153 g_free(gdir);
154
155 auto appsarray = json_object_get_array_member(snapobject, "apps");
156 for (unsigned int i = 0; i < json_array_get_length(appsarray); i++)
157 {
158 auto appobj = json_array_get_object_element(appsarray, i);
159 if (json_object_has_member(appobj, "name"))
160 {
161 auto appname = json_object_get_string_member(appobj, "name");
162 if (appname)
163 {
164 pkgstruct->appnames.insert(appname);
165 }
166 }
167 }
168
169 return pkgstruct;
170 }
171 catch (std::runtime_error &e)
172 {
173 g_debug("Unable to get snap information for '%s': %s", package.value().c_str(), e.what());
174 return {};
175 }
176 }
177
178 /** Function that acts as the return from cURL to add data to
179 our storage vector.
180
181 \param ptr incoming data
182 \param size block size
183 \param nmemb number of blocks
184 \param userdata our local vector to store things in
185 */
186 static size_t snapd_writefunc(char *ptr, size_t size, size_t nmemb, void *userdata)
187 {
188 auto data = static_cast<std::vector<char> *>(userdata);
189 data->insert(data->end(), ptr, ptr + (size * nmemb));
190 return size * nmemb;
191 }
192
193 /** Asks the snapd process for some JSON. This function parses the basic
194 response JSON that snapd returns and will error if a return code error
195 is in the JSON. It then passes on the "result" part of the response
196 to the caller.
197
198 \param endpoint End of the URL to pass to snapd
199 */
200 std::shared_ptr<JsonNode> Info::snapdJson(const std::string &endpoint) const
201 {
202 /* Setup the CURL connection and suck some data */
203 CURL *curl = curl_easy_init();
204 if (curl == nullptr)
205 {
206 throw std::runtime_error("Unable to create new cURL connection");
207 }
208
209 std::vector<char> data;
210
211 /* Configure the command */
212 // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
213 curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
214 curl_easy_setopt(curl, CURLOPT_URL, ("http://snapd" + endpoint).c_str());
215 curl_easy_setopt(curl, CURLOPT_UNIX_SOCKET_PATH, snapdSocket.c_str());
216 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
217 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, snapd_writefunc);
218
219 /* Overridable timeout */
220 if (g_getenv("LOMIRI_APP_LAUNCH_DISABLE_SNAPD_TIMEOUT") == nullptr)
221 {
222 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 100L);
223 }
224
225 /* Run the actual request (blocking) */
226 auto res = curl_easy_perform(curl);
227
228 if (res != CURLE_OK)
229 {
230 curl_easy_cleanup(curl);
231 throw std::runtime_error("snapd HTTP server returned an error: " + std::string(curl_easy_strerror(res)));
232 }
233 else
234 {
235 g_debug("Got %d bytes from snapd", int(data.size()));
236 }
237
238 curl_easy_cleanup(curl);
239
240 /* Cool, we have data */
241 auto parser = std::shared_ptr<JsonParser>(json_parser_new(), [](JsonParser *parser) { g_clear_object(&parser); });
242 GError *error = nullptr;
243 json_parser_load_from_data(parser.get(), /* parser */
244 data.data(), /* array */
245 data.size(), /* size */
246 &error); /* error */
247
248 if (error != nullptr)
249 {
250 std::string message{"Can not parse JSON: " + std::string(error->message)};
251 g_error_free(error);
252 throw std::runtime_error{message};
253 }
254
255 auto root = json_parser_get_root(parser.get());
256 auto rootobj = json_node_get_object(root);
257
258 if (rootobj == nullptr)
259 {
260 throw std::runtime_error("Root of JSON result isn't an object");
261 }
262
263 /* Check members */
264 for (const auto &member : {"status-code", "result"})
265 {
266 if (!json_object_has_member(rootobj, member))
267 {
268 throw std::runtime_error("Resulting JSON didn't have a '" + std::string(member) + "'");
269 }
270 }
271
272 for (const auto &member : {"status", "type"})
273 {
274 if (!json_object_has_member(rootobj, member))
275 {
276 throw std::runtime_error("Snap JSON didn't have a '" + std::string(member) + "'");
277 }
278
279 auto node = json_object_get_member(rootobj, member);
280 if (json_node_get_node_type(node) != JSON_NODE_VALUE)
281 {
282 throw std::runtime_error{"Snap JSON had a '" + std::string(member) + "' but it's an object!"};
283 }
284
285 if (json_node_get_value_type(node) != G_TYPE_STRING)
286 {
287 throw std::runtime_error{"Snap JSON had a '" + std::string(member) + "' but it's not a string!"};
288 }
289 }
290
291 auto status = json_object_get_int_member(rootobj, "status-code");
292 if (status != 200)
293 {
294 throw std::runtime_error("Status code is: " + std::to_string(status));
295 }
296
297 std::string statusstr = json_object_get_string_member(rootobj, "status");
298 if (statusstr != "OK")
299 {
300 throw std::runtime_error("Status string is: " + statusstr);
301 }
302
303 std::string typestr = json_object_get_string_member(rootobj, "type");
304 if (typestr != "sync")
305 {
306 throw std::runtime_error("We only support 'sync' results right now, but we got a: " + typestr);
307 }
308
309 auto result = std::shared_ptr<JsonNode>(json_node_ref(json_object_get_member(rootobj, "result")), json_node_unref);
310
311 return result;
312 }
313
314 /** Looks through all the plugs in the interfaces and runs a function
315 based on them. Avoids pulling objects out of the parsed JSON structure
316 from Snappy and making sure they have the same lifecycle as the parser
317 object which seems to destroy them when it dies.
318
319 \param plugfunc Function to execute on each plug
320 */
321 void Info::forAllPlugs(std::function<void(JsonObject *plugobj)> plugfunc) const
322 {
323 if (!snapdExists)
324 {
325 return;
326 }
327
328 auto interfacesnode = snapdJson("/v2/interfaces");
329 auto interface = json_node_get_object(interfacesnode.get());
330 if (interface == nullptr)
331 {
332 throw std::runtime_error("Interfaces result isn't an object: " + Registry::Impl::printJson(interfacesnode));
333 }
334
335 for (const auto &member : {"plugs", "slots"})
336 {
337 if (!json_object_has_member(interface, member))
338 {
339 throw std::runtime_error("Interface JSON didn't have a '" + std::string(member) + "'");
340 }
341 }
342
343 auto plugarray = json_object_get_array_member(interface, "plugs");
344 for (unsigned int i = 0; i < json_array_get_length(plugarray); i++)
345 {
346 auto ifaceobj = json_array_get_object_element(plugarray, i);
347 try
348 {
349 for (const auto &member : {"snap", "interface", "apps"})
350 {
351 if (!json_object_has_member(ifaceobj, member))
352 {
353 throw std::runtime_error("Interface JSON didn't have a '" + std::string(member) + "'");
354 }
355 }
356
357 plugfunc(ifaceobj);
358 }
359 catch (std::runtime_error &e)
360 {
361 /* We'll check the others even if one is bad */
362 // g_debug("Malformed inteface instance: %s", e.what());
363 continue;
364 }
365 }
366 }
367
368 /** Gets all the apps that are available for a given interface. It asks snapd
369 for the list of interfaces and then finds this one, turning it into a set
370 of AppIDs
371
372 \param in_interface Which interface to get the set of apps for
373 */
374 std::set<AppID> Info::appsForInterface(const std::string &in_interface) const
375 {
376 bool interfacefound = false;
377 std::set<AppID> appids;
378
379 try
380 {
381 forAllPlugs([this, &interfacefound, &appids, in_interface](JsonObject *ifaceobj) {
382 std::string interfacename = json_object_get_string_member(ifaceobj, "interface");
383 if (interfacename != in_interface)
384 {
385 return;
386 }
387
388 interfacefound = true;
389
390 auto cname = json_object_get_string_member(ifaceobj, "snap");
391 if (cname == nullptr)
392 {
393 return;
394 }
395 std::string snapname(cname);
396
397 auto pkginfo = pkgInfo(AppID::Package::from_raw(snapname));
398 if (!pkginfo)
399 {
400 return;
401 }
402
403 std::string revision = pkginfo->revision;
404
405 auto apps = json_object_get_array_member(ifaceobj, "apps");
406 for (unsigned int k = 0; apps != nullptr && k < json_array_get_length(apps); k++)
407 {
408 std::string appname = json_array_get_string_element(apps, k);
409
410 appids.emplace(AppID(AppID::Package::from_raw(snapname), /* package */
411 AppID::AppName::from_raw(appname), /* appname */
412 AppID::Version::from_raw(revision))); /* version */
413 }
414 });
415
416 if (!interfacefound)
417 {
418 g_debug("Unable to find information on interface '%s'", in_interface.c_str());
419 }
420 }
421 catch (std::runtime_error &e)
422 {
423 g_warning("Unable to get interface information: %s", e.what());
424 }
425
426 return appids;
427 }
428
429 /** Finds all the interfaces for a specific appid
430
431 \param appid AppID to search for
432 */
433 std::set<std::string> Info::interfacesForAppId(const AppID &appid) const
434 {
435
436 std::set<std::string> interfaces;
437
438 try
439 {
440 forAllPlugs([&interfaces, appid](JsonObject *ifaceobj) {
441 auto snapname = json_object_get_string_member(ifaceobj, "snap");
442 if (snapname != appid.package.value())
443 {
444 return;
445 }
446
447 auto cinterfacename = json_object_get_string_member(ifaceobj, "interface");
448 if (cinterfacename == nullptr)
449 {
450 return;
451 }
452
453 std::string interfacename(cinterfacename);
454
455 auto apps = json_object_get_array_member(ifaceobj, "apps");
456 for (unsigned int k = 0; k < json_array_get_length(apps); k++)
457 {
458 std::string appname = json_array_get_string_element(apps, k);
459 if (appname == appid.appname.value())
460 {
461 interfaces.insert(interfacename);
462 }
463 }
464 });
465 }
466 catch (std::runtime_error &e)
467 {
468 g_warning("Unable to get interface information: %s", e.what());
469 }
470
471 return interfaces;
472 }
473
474 } // namespace snapd
475 } // namespace app_launch
476 } // namespace lomiri