File: foundry-shell.c

package info (click to toggle)
foundry 1.1~beta-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 15,552 kB
  • sloc: ansic: 167,487; xml: 417; makefile: 21; sh: 19; javascript: 10
file content (361 lines) | stat: -rw-r--r-- 11,153 bytes parent folder | download | duplicates (2)
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/* foundry-shell.c
 *
 * Copyright 2024 Christian Hergert <chergert@redhat.com>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#include "config.h"

#include <gio/gio.h>

#include "foundry-debug.h"
#include "foundry-shell-private.h"
#include "foundry-util-private.h"

static const char *user_shell = "/bin/sh";
static const char *user_default_path = SAFE_PATH;
static DexPromise *shell_init;

gboolean
foundry_shell_supports_dash_c (const char *shell)
{
  if (shell == NULL)
    return FALSE;

  return strcmp (shell, "bash") == 0 || g_str_has_suffix (shell, "/bash") ||
#if 0
         /* Fish does apparently support -l and -c in testing, but it is causing
          * issues with users, so we will disable it for now so that we fallback
          * to using `sh -l -c ''` instead.
          */
         strcmp (shell, "fish") == 0 || g_str_has_suffix (shell, "/fish") ||
#endif
         strcmp (shell, "zsh") == 0 || g_str_has_suffix (shell, "/zsh") ||
         strcmp (shell, "dash") == 0 || g_str_has_suffix (shell, "/dash") ||
         strcmp (shell, "tcsh") == 0 || g_str_has_suffix (shell, "/tcsh") ||
         strcmp (shell, "sh") == 0 || g_str_has_suffix (shell, "/sh");
}

/**
 * foundry_shell_supports_dash_login:
 * @shell: the name of the shell, such as `sh` or `/bin/sh`
 *
 * Checks if the shell is known to support login semantics. Originally,
 * this meant `--login`, but now is meant to mean `-l` as more shells
 * support `-l` than `--login` (notably dash).
 *
 * Returns: %TRUE if @shell likely supports `-l`.
 */
gboolean
foundry_shell_supports_dash_login (const char *shell)
{
  if (shell == NULL)
    return FALSE;

  return strcmp (shell, "bash") == 0 || g_str_has_suffix (shell, "/bash") ||
#if 0
         strcmp (shell, "fish") == 0 || g_str_has_suffix (shell, "/fish") ||
#endif
         strcmp (shell, "zsh") == 0 || g_str_has_suffix (shell, "/zsh") ||
         strcmp (shell, "dash") == 0 || g_str_has_suffix (shell, "/dash") ||
#if 0
         /* tcsh supports -l and -c but not combined! To do that, you'd have
          * to instead launch the login shell like `-tcsh -c 'command'`, which
          * is possible, but we lack the abstractions for that currently.
          */
         strcmp (shell, "tcsh") == 0 || g_str_has_suffix (shell, "/tcsh") ||
#endif
         strcmp (shell, "sh") == 0 || g_str_has_suffix (shell, "/sh");
}

static void
foundry_guess_shell_communicate_cb (GObject      *object,
                                    GAsyncResult *result,
                                    gpointer      user_data)
{
  GSubprocess *subprocess = (GSubprocess *)object;
  g_autoptr(GTask) task = user_data;
  g_autoptr(GError) error = NULL;
  g_autofree char *stdout_buf = NULL;
  const char *key;

  FOUNDRY_ENTRY;

  g_assert (G_IS_SUBPROCESS (subprocess));
  g_assert (G_IS_ASYNC_RESULT (result));
  g_assert (G_IS_TASK (task));

  key = g_task_get_task_data (task);

  if (!g_subprocess_communicate_utf8_finish (subprocess, result, &stdout_buf, NULL, &error))
    {
      g_task_return_error (task, g_steal_pointer (&error));
      FOUNDRY_EXIT;
    }

  if (stdout_buf != NULL)
    g_strstrip (stdout_buf);

  g_debug ("Guessed %s as \"%s\"", key, stdout_buf);

  if (foundry_str_equal0 (key, "SHELL"))
    {
      if (stdout_buf[0] == '/')
        user_shell = g_steal_pointer (&stdout_buf);
    }
  else if (foundry_str_equal0 (key, "PATH"))
    {
      if (!foundry_str_empty0 (stdout_buf))
        user_default_path = g_steal_pointer (&stdout_buf);
    }
  else
    {
      g_critical ("Unknown key %s", key);
    }

  g_task_return_boolean (task, TRUE);

  FOUNDRY_EXIT;
}

static void
_foundry_guess_shell (GCancellable        *cancellable,
                      GAsyncReadyCallback  callback,
                      gpointer             user_data)
{
  g_autoptr(GTask) task = NULL;
  g_autoptr(GSubprocessLauncher) launcher = NULL;
  g_autoptr(GSubprocess) subprocess = NULL;
  g_autoptr(GPtrArray) args = NULL;
  g_autofree char *command = NULL;
  g_autoptr(GError) error = NULL;
  g_auto(GStrv) argv = NULL;

  FOUNDRY_ENTRY;

  g_assert (!cancellable || G_IS_CANCELLABLE (cancellable));

  task = g_task_new (NULL, cancellable, callback, user_data);
  g_task_set_task_data (task, g_strdup ("SHELL"), g_free);

#ifdef __APPLE__
  command = g_strdup_printf ("sh -c 'dscacheutil -q user -a name %s | grep ^shell: | cut -f 2 -d \" \"'",
                             g_get_user_name ());
#else
  command = g_strdup_printf ("sh -c 'getent passwd %s | head -n1 | cut -f 7 -d :'",
                             g_get_user_name ());
#endif

  if (!g_shell_parse_argv (command, NULL, &argv, &error))
    {
      g_task_return_error (task, g_steal_pointer (&error));
      FOUNDRY_EXIT;
    }

  /*
   * We don't use the runtime shell here, because we want to know
   * what the host thinks the user shell should be.
   */
  launcher = g_subprocess_launcher_new (G_SUBPROCESS_FLAGS_STDOUT_PIPE);
  g_subprocess_launcher_set_cwd (launcher, g_get_home_dir ());

  args = g_ptr_array_new ();

  if (_foundry_in_container ())
    {
      g_ptr_array_add (args, (char *)"flatpak-spawn");
      g_ptr_array_add (args, (char *)"--host");
      g_ptr_array_add (args, (char *)"--watch-bus");
    }

  for (guint i = 0; argv[i]; i++)
    g_ptr_array_add (args, argv[i]);
  g_ptr_array_add (args, NULL);

  if (!(subprocess = g_subprocess_launcher_spawnv (launcher, (const char * const *)args->pdata, &error)))
    g_task_return_error (task, g_steal_pointer (&error));
  else
    g_subprocess_communicate_utf8_async (subprocess,
                                         NULL,
                                         cancellable,
                                         foundry_guess_shell_communicate_cb,
                                         g_steal_pointer (&task));

  FOUNDRY_EXIT;
}

static void
_foundry_guess_user_path (GCancellable        *cancellable,
                          GAsyncReadyCallback  callback,
                          gpointer             user_data)
{
  g_autoptr(GSubprocessLauncher) launcher = NULL;
  g_autoptr(GSubprocess) subprocess = NULL;
  g_autoptr(GPtrArray) argv = NULL;
  g_autoptr(GTask) task = NULL;
  g_autoptr(GError) error = NULL;

  FOUNDRY_ENTRY;

  g_assert (!cancellable || G_IS_CANCELLABLE (cancellable));

  argv = g_ptr_array_new ();

  task = g_task_new (NULL, cancellable, callback, user_data);
  g_task_set_task_data (task, g_strdup ("PATH"), g_free);

  /* This works by running 'echo $PATH' on the host, preferably
   * through the user $SHELL we discovered.
   */
  launcher = g_subprocess_launcher_new (G_SUBPROCESS_FLAGS_STDOUT_PIPE);
  g_subprocess_launcher_set_cwd (launcher, g_get_home_dir ());

  if (_foundry_in_container ())
    {
      g_ptr_array_add (argv, (char *)"flatpak-spawn");
      g_ptr_array_add (argv, (char *)"--host");
      g_ptr_array_add (argv, (char *)"--watch-bus");
    }

  if (foundry_shell_supports_dash_c (user_shell))
    {
      g_ptr_array_add (argv, (char *)user_shell);
      if (foundry_shell_supports_dash_login (user_shell))
        g_ptr_array_add (argv, (char *)"-l");
      g_ptr_array_add (argv, (char *)"-c");
      g_ptr_array_add (argv, (char *)"echo $PATH");
    }
  else
    {
      g_ptr_array_add (argv, (char *)"/bin/sh");
      g_ptr_array_add (argv, (char *)"-l");
      g_ptr_array_add (argv, (char *)"-c");
      g_ptr_array_add (argv, (char *)"echo $PATH");
    }

  g_ptr_array_add (argv, NULL);

  if (!(subprocess = g_subprocess_launcher_spawnv (launcher, (const char * const *)argv->pdata, &error)))
    g_task_return_error (task, g_steal_pointer (&error));
  else
    g_subprocess_communicate_utf8_async (subprocess,
                                         NULL,
                                         NULL,
                                         foundry_guess_shell_communicate_cb,
                                         g_steal_pointer (&task));

  FOUNDRY_EXIT;
}

/**
 * foundry_shell_get_default:
 *
 * Gets the user preferred shell on the host.
 *
 * If the background shell discovery has not yet finished due to
 * slow or misconfigured getent on the host, this will provide a
 * sensible fallback.
 *
 * Returns: (not nullable): a shell such as "/bin/sh"
 */
const char *
foundry_shell_get_default (void)
{
  return user_shell;
}

/**
 * foundry_shell_get_default_path:
 *
 * Gets the default `$PATH` on the system for the user on the host.
 *
 * This value is sniffed during startup and will default to `SAFE_PATH`
 * configured when building Builder until that value has been discovered.
 *
 * Returns: (not nullable): a string such as "/bin:/usr/bin"
 */
const char *
foundry_shell_get_default_path (void)
{
  return user_default_path;
}

static void
foundry_shell_init_guess_path_cb (GObject      *object,
                                  GAsyncResult *result,
                                  gpointer      user_data)
{
  g_autoptr(DexPromise) promise = user_data;
  g_autoptr(GError) error = NULL;

  FOUNDRY_ENTRY;

  g_assert (object == NULL);
  g_assert (G_IS_TASK (result));
  g_assert (DEX_IS_PROMISE (promise));

  if (!g_task_propagate_boolean (G_TASK (result), &error))
    g_message ("Failed to guess user $PATH using $SHELL %s: %s",
               user_shell, error->message);

  if (error != NULL)
    dex_promise_reject (promise, g_steal_pointer (&error));
  else
    dex_promise_resolve_boolean (promise, TRUE);

  FOUNDRY_EXIT;
}

static void
foundry_shell_init_guess_shell_cb (GObject      *object,
                                   GAsyncResult *result,
                                   gpointer      user_data)
{
  g_autoptr(DexPromise) promise = user_data;
  g_autoptr(GError) error = NULL;

  FOUNDRY_ENTRY;

  g_assert (object == NULL);
  g_assert (G_IS_TASK (result));
  g_assert (DEX_IS_PROMISE (promise));

  if (!g_task_propagate_boolean (G_TASK (result), &error))
    g_message ("Failed to guess user $SHELL: %s", error->message);

  _foundry_guess_user_path (NULL,
                            foundry_shell_init_guess_path_cb,
                            g_steal_pointer (&promise));

  FOUNDRY_EXIT;
}

DexFuture *
_foundry_shell_init (void)
{
  FOUNDRY_ENTRY;

  if (g_once_init_enter (&shell_init))
    {
      g_once_init_leave (&shell_init, dex_promise_new ());
      _foundry_guess_shell (NULL,
                            foundry_shell_init_guess_shell_cb,
                            dex_ref (shell_init));
    }

  FOUNDRY_RETURN (dex_ref (DEX_FUTURE (shell_init)));
}