1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2  *
3  * This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "LSBUtils.h"
8 
9 #include <unistd.h>
10 #include "base/process_util.h"
11 #include "mozilla/FileUtils.h"
12 
13 namespace mozilla::widget::lsb {
14 
15 static const char* gLsbReleasePath = "/usr/bin/lsb_release";
16 
GetLSBRelease(nsACString & aDistributor,nsACString & aDescription,nsACString & aRelease,nsACString & aCodename)17 bool GetLSBRelease(nsACString& aDistributor, nsACString& aDescription,
18                    nsACString& aRelease, nsACString& aCodename) {
19   if (access(gLsbReleasePath, R_OK) != 0) return false;
20 
21   int pipefd[2];
22   if (pipe(pipefd) == -1) {
23     NS_WARNING("pipe() failed!");
24     return false;
25   }
26 
27   std::vector<std::string> argv = {gLsbReleasePath, "-idrc"};
28 
29   base::LaunchOptions options;
30   options.fds_to_remap.push_back({pipefd[1], STDOUT_FILENO});
31   options.wait = true;
32 
33   base::ProcessHandle process;
34   bool ok = base::LaunchApp(argv, options, &process);
35   close(pipefd[1]);
36   if (!ok) {
37     NS_WARNING("Failed to spawn lsb_release!");
38     close(pipefd[0]);
39     return false;
40   }
41 
42   ScopedCloseFile stream(fdopen(pipefd[0], "r"));
43   if (!stream) {
44     NS_WARNING("Could not wrap fd!");
45     close(pipefd[0]);
46     return false;
47   }
48 
49   char dist[256], desc[256], release[256], codename[256];
50   if (fscanf(stream,
51              "Distributor ID:\t%255[^\n]\n"
52              "Description:\t%255[^\n]\n"
53              "Release:\t%255[^\n]\n"
54              "Codename:\t%255[^\n]\n",
55              dist, desc, release, codename) != 4) {
56     NS_WARNING("Failed to parse lsb_release!");
57     return false;
58   }
59 
60   aDistributor.Assign(dist);
61   aDescription.Assign(desc);
62   aRelease.Assign(release);
63   aCodename.Assign(codename);
64   return true;
65 }
66 
67 }  // namespace mozilla::widget::lsb
68