aboutsummaryrefslogtreecommitdiff
path: root/libbutl/host-os-release.cxx
blob: f13f62ce1dbcaea168c715eaa45da6b095045bfa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// file      : libbutl/host-os-release.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbutl/host-os-release.hxx>

#include <sstream>
#include <stdexcept> // runtime_error

#include <libbutl/path.hxx>
#include <libbutl/path-io.hxx>
#include <libbutl/utility.hxx>
#include <libbutl/process.hxx>
#include <libbutl/fdstream.hxx>
#include <libbutl/filesystem.hxx>    // file_exists()
#include <libbutl/string-parser.hxx> // parse_quoted()

#ifdef _WIN32
#  include <libbutl/win32-utility.hxx>
#endif

using namespace std;

namespace butl
{
  // Note: exported for access from the test.
  //
  LIBBUTL_SYMEXPORT os_release
  host_os_release_linux (path f = {})
  {
    os_release r;

    // According to os-release(5), we should use /etc/os-release and fallback
    // to /usr/lib/os-release if the former does not exist. It also lists the
    // fallback values for individual variables, in case some are not present.
    //
    auto exists = [] (const path& f)
    {
      try
      {
        return file_exists (f);
      }
      catch (const system_error& e)
      {
        ostringstream os;
        os << "unable to stat path " << f << ": " << e;
        throw runtime_error (os.str ());
      }
    };

    if (!f.empty ()
        ? exists (f)
        : (exists (f = path ("/etc/os-release")) ||
           exists (f = path ("/usr/lib/os-release"))))
    {
      try
      {
        ifdstream ifs (f, ifdstream::badbit);

        string l;
        for (uint64_t ln (1); !eof (getline (ifs, l)); ++ln)
        {
          trim (l);

          // Skip blanks lines and comments.
          //
          if (l.empty () || l[0] == '#')
            continue;

          // The variable assignments are in the "shell style" and so can be
          // quoted/escaped. For now we only handle quoting, which is what all
          // the instances seen in the wild seems to use.
          //
          size_t p (l.find ('='));
          if (p == string::npos)
            continue;

          string n (l, 0, p);
          l.erase (0, p + 1);

          using string_parser::parse_quoted;
          using string_parser::invalid_string;

          try
          {
            if (n == "ID_LIKE")
            {
              r.like_ids.clear ();

              vector<string> vs (parse_quoted (l, true /* unquote */));
              for (const string& v: vs)
              {
                for (size_t b (0), e (0); next_word (v, b, e); )
                {
                  r.like_ids.push_back (string (v, b, e - b));
                }
              }
            }
            else if (string* p = (n == "ID"               ?  &r.name_id :
                                  n == "VERSION_ID"       ?  &r.version_id :
                                  n == "VARIANT_ID"       ?  &r.variant_id :
                                  n == "NAME"             ?  &r.name :
                                  n == "VERSION_CODENAME" ?  &r.version_codename :
                                  n == "VARIANT"          ?  &r.variant :
                                  nullptr))
            {
              vector<string> vs (parse_quoted (l, true /* unquote */));
              switch (vs.size ())
              {
              case 0:  *p =  ""; break;
              case 1:  *p = move (vs.front ()); break;
              default: throw invalid_string (0, "multiple values");
              }
            }
          }
          catch (const invalid_string& e)
          {
            ostringstream os;
            os << "invalid " << n << " value in " << f << ':' << ln << ": "
               << e;
            throw runtime_error (os.str ());
          }
        }

        ifs.close ();
      }
      catch (const ios::failure& e)
      {
        ostringstream os;
        os << "unable to read from " << f << ": " << e;
        throw runtime_error (os.str ());
      }
    }

    // Assign fallback values.
    //
    if (r.name_id.empty ()) r.name_id = "linux";
    if (r.name.empty ())    r.name    = "Linux";

    return r;
  }

  static os_release
  host_os_release_macos ()
  {
    // Run sw_vers -productVersion to get Mac OS version.
    //
    try
    {
      process pr;
      try
      {
        fdpipe pipe (fdopen_pipe ());

        pr = process_start (0, pipe, 2, "sw_vers", "-productVersion");

        pipe.out.close ();
        ifdstream is (move (pipe.in), fdstream_mode::skip, ifdstream::badbit);

        // The output should be one line containing the version.
        //
        optional<string> v;
        for (string l; !eof (getline (is, l)); )
        {
          if (l.empty () || v)
          {
            v = nullopt;
            break;
          }

          v = move (l);
        }

        is.close (); // Detect errors.

        if (pr.wait ())
        {
          if (!v)
            throw runtime_error ("unexpected sw_vers -productVersion output");

          return os_release {"macos", {}, move (*v), "", "Mac OS", "", ""};
        }

      }
      catch (const ios::failure& e)
      {
        if (pr.wait ())
        {
          ostringstream os;
          os << "error reading sw_vers output: " << e;
          throw runtime_error (os.str ());
        }

        // Fall through.
      }

      // We should only get here if the child exited with an error status.
      //
      assert (!pr.wait ());
      throw runtime_error ("process sw_vers exited with non-zero code");
    }
    catch (const process_error& e)
    {
      ostringstream os;
      os << "unable to execute sw_vers: " << e;
      throw runtime_error (os.str ());
    }
  }

  static os_release
  host_os_release_windows ()
  {
#ifdef _WIN32
    // The straightforward way to get the version would be the GetVersionEx()
    // Win32 function. However, if the application is built with a certain
    // assembly manifest, this function will return the version the
    // application was built for rather than what's actually running.
    //
    // The other plausible options are to call the `ver` program and parse it
    // output (of questionable regularity) or to call RtlGetVersion(). The
    // latter combined with GetProcAddress() seems to be a widely-used
    // approach, so we are going with that (seeing that we employ a similar
    // technique in quite a few places).
    //
    HMODULE nh (GetModuleHandle ("ntdll.dll"));
    if (nh == nullptr)
      throw runtime_error ("unable to get handle to ntdll.dll");

    using RtlGetVersion = LONG /*NTSTATUS*/ (WINAPI*)(PRTL_OSVERSIONINFOW);

    RtlGetVersion gv (
      function_cast<RtlGetVersion> (
        GetProcAddress (nh, "RtlGetVersion")));

    // RtlGetVersion() is available from Windows 2000 which is way before
    // anything we might possibly care about (e.g., XP or 7).
    //
    if (gv == nullptr)
      throw runtime_error ("unable to get address of RtlGetVersion()");

    RTL_OSVERSIONINFOW vi;
    vi.dwOSVersionInfoSize = sizeof (vi);
    gv (&vi); // Always succeeds, according to documentation.

    // Ok, the real mess starts here. Here is how the commonly known Windows
    // versions correspond to the major/minor/build numbers and how we will
    // map them (note that there are also Server versions in the mix; see the
    // OSVERSIONINFOEXW struct documentation for the complete picture):
    //
    //                        major  minor  build      mapped
    // Windows 11             10     0      >=22000    11
    // Windows 10             10     0      <22000     10
    // Windows 8.1             6     3                 8.1
    // Windows 8               6     2                 8
    // Windows 7               6     1                 7
    // Windows Vista           6     0                 6
    // Windows XP Pro/64-bit   5     2                 5.2
    // Windows XP              5     1                 5.1
    // Windows 2000            5     0                 5
    //
    // Based on this it's probably not wise to try to map any future versions
    // automatically.
    //
    string v;
    if (vi.dwMajorVersion == 10 && vi.dwMinorVersion == 0)
    {
      v = vi.dwBuildNumber >= 22000 ? "11" : "10";
    }
    else if (vi.dwMajorVersion == 6 && vi.dwMinorVersion == 3) v = "8.1";
    else if (vi.dwMajorVersion == 6 && vi.dwMinorVersion == 2) v = "8";
    else if (vi.dwMajorVersion == 6 && vi.dwMinorVersion == 1) v = "7";
    else if (vi.dwMajorVersion == 6 && vi.dwMinorVersion == 0) v = "6";
    else if (vi.dwMajorVersion == 5 && vi.dwMinorVersion == 2) v = "5.2";
    else if (vi.dwMajorVersion == 5 && vi.dwMinorVersion == 1) v = "5.1";
    else if (vi.dwMajorVersion == 5 && vi.dwMinorVersion == 0) v = "5";
    else throw ("unknown windows version " +
                std::to_string (vi.dwMajorVersion) + '.' +
                std::to_string (vi.dwMinorVersion) + '.' +
                std::to_string (vi.dwBuildNumber));

    return os_release {"windows", {}, move (v), "", "Windows", "", ""};
#else
    throw runtime_error ("unexpected host operating system");
#endif
  }

  optional<os_release>
  host_os_release (const target_triplet& h)
  {
    const string& c (h.class_);
    const string& s (h.system);

    if (c == "linux")
      return host_os_release_linux ();

    if (c == "macos")
      return host_os_release_macos ();

    if (c == "windows")
      return host_os_release_windows ();

    if (c == "bsd")
    {
      // @@ TODO: ideally we would want to run uname and obtain the actual
      //    version we are runnig on rather than what we've been built for.
      //    (Think also how this will affect tests).
      //
      if (s == "freebsd")
        return os_release {"freebsd", {}, h.version, "", "FreeBSD", "", ""};

      if (s == "netbsd")
        return os_release {"netbsd", {}, h.version, "", "NetBSD", "", ""};

      if (s == "openbsd")
        return os_release {"openbsd", {}, h.version, "", "OpenBSD", "", ""};

      // Assume some other BSD.
      //
      return os_release {s, {}, h.version, "", s, "", ""};
    }

    return nullopt;
  }
}