summaryrefslogtreecommitdiff
path: root/support/shell-container.c
blob: 28437e4206ba23f59e27d42eaffdf0f36e49843f (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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/* Minimal /bin/sh for in-container use.
   Copyright (C) 2018-2023 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C 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.

   The GNU C 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 Lesser General Public
   License along with the GNU C Library; if not, see
   <https://www.gnu.org/licenses/>.  */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <sys/sysmacros.h>
#include <ctype.h>
#include <utime.h>
#include <errno.h>
#include <error.h>

#include <support/support.h>
#include <support/timespec.h>

/* Design considerations

 General rule: optimize for developer time, not run time.

 Specifically:

 * Don't worry about slow algorithms
 * Don't worry about free'ing memory
 * Don't implement anything the testsuite doesn't need.
 * Line and argument counts are limited, see below.

*/

#define MAX_ARG_COUNT 100
#define MAX_LINE_LENGTH 1000

/* Debugging is enabled via --debug, which must be the first argument.  */
static int debug_mode = 0;
#define dprintf if (debug_mode) fprintf

/* Emulate the "/bin/true" command.  Arguments are ignored.  */
static int
true_func (char **argv)
{
  return 0;
}

/* Emulate the "/bin/echo" command.  Options are ignored, arguments
   are printed to stdout.  */
static int
echo_func (char **argv)
{
  int i;

  for (i = 0; argv[i]; i++)
    {
      if (i > 0)
	putchar (' ');
      fputs (argv[i], stdout);
    }
  putchar ('\n');

  return 0;
}

/* Emulate the "/bin/cp" command.  Options are ignored.  Only copies
   one source file to one destination file.  Directory destinations
   are not supported.  */
static int
copy_func (char **argv)
{
  char *sname = argv[0];
  char *dname = argv[1];
  int sfd = -1, dfd = -1;
  struct stat st;
  int ret = 1;

  sfd = open (sname, O_RDONLY);
  if (sfd < 0)
    {
      fprintf (stderr, "cp: unable to open %s for reading: %s\n",
	       sname, strerror (errno));
      return 1;
    }

  if (fstat (sfd, &st) < 0)
    {
      fprintf (stderr, "cp: unable to fstat %s: %s\n",
	       sname, strerror (errno));
      goto out;
    }

  dfd = open (dname, O_WRONLY | O_TRUNC | O_CREAT, 0600);
  if (dfd < 0)
    {
      fprintf (stderr, "cp: unable to open %s for writing: %s\n",
	       dname, strerror (errno));
      goto out;
    }

  if (support_copy_file_range (sfd, 0, dfd, 0, st.st_size, 0) != st.st_size)
    {
      fprintf (stderr, "cp: cannot copy file %s to %s: %s\n",
	       sname, dname, strerror (errno));
      goto out;
    }

  ret = 0;
  chmod (dname, st.st_mode & 0777);

out:
  if (sfd >= 0)
    close (sfd);
  if (dfd >= 0)
    close (dfd);

  return ret;

}

/* Emulate the 'exit' builtin.  The exit value is optional.  */
static int
exit_func (char **argv)
{
  int exit_val = 0;

  if (argv[0] != 0)
    exit_val = atoi (argv[0]) & 0xff;
  exit (exit_val);
  return 0;
}

/* Emulate the "/bin/kill" command.  Options are ignored.  */
static int
kill_func (char **argv)
{
  int signum = SIGTERM;
  int i;

  for (i = 0; argv[i]; i++)
    {
      pid_t pid;
      if (strcmp (argv[i], "$$") == 0)
	pid = getpid ();
      else
	pid = atoi (argv[i]);
      kill (pid, signum);
    }
  return 0;
}

/* Emulate the "/bin/sleep" command.  No suffix support.  Options are
   ignored.  */
static int
sleep_func (char **argv)
{
  if (argv[0] == NULL)
    {
      fprintf (stderr, "sleep: missing operand\n");
      return 1;
    }
  char *endptr = NULL;
  double sec = strtod (argv[0], &endptr);
  if (endptr == argv[0] || errno == ERANGE || sec < 0)
    {
      fprintf (stderr, "sleep: invalid time interval '%s'\n", argv[0]);
      return 1;
    }
  struct timespec ts = dtotimespec (sec);
  if (nanosleep (&ts, NULL) < 0)
    {
      fprintf (stderr, "sleep: failed to nanosleep: %s\n", strerror (errno));
      return 1;
    }
  return 0;
}

/* This is a list of all the built-in commands we understand.  */
static struct {
  const char *name;
  int (*func) (char **argv);
} builtin_funcs[] = {
  { "true", true_func },
  { "echo", echo_func },
  { "cp", copy_func },
  { "exit", exit_func },
  { "kill", kill_func },
  { "sleep", sleep_func },
  { NULL, NULL }
};

/* Run one tokenized command.  argv[0] is the command.  argv is
   NULL-terminated.  */
static void
run_command_array (char **argv)
{
  int i, j;
  pid_t pid;
  int status;
  int (*builtin_func) (char **args);

  if (argv[0] == NULL)
    return;

  builtin_func = NULL;

  int new_stdin = 0;
  int new_stdout = 1;
  int new_stderr = 2;

  dprintf (stderr, "run_command_array starting\n");
  for (i = 0; argv[i]; i++)
    dprintf (stderr, "   argv [%d] `%s'\n", i, argv[i]);

  for (j = i = 0; argv[i]; i++)
    {
      if (strcmp (argv[i], "<") == 0 && argv[i + 1])
	{
	  new_stdin = open (argv[i + 1], O_WRONLY|O_CREAT|O_TRUNC, 0777);
	  ++i;
	  continue;
	}
      if (strcmp (argv[i], ">") == 0 && argv[i + 1])
	{
	  new_stdout = open (argv[i + 1], O_WRONLY|O_CREAT|O_TRUNC, 0777);
	  ++i;
	  continue;
	}
      if (strcmp (argv[i], ">>") == 0 && argv[i + 1])
	{
	  new_stdout = open (argv[i + 1], O_WRONLY|O_CREAT|O_APPEND, 0777);
	  ++i;
	  continue;
	}
      if (strcmp (argv[i], "2>") == 0 && argv[i + 1])
	{
	  new_stderr = open (argv[i + 1], O_WRONLY|O_CREAT|O_TRUNC, 0777);
	  ++i;
	  continue;
	}
      argv[j++] = argv[i];
    }
  argv[j] = NULL;


  for (i = 0; builtin_funcs[i].name != NULL; i++)
    if (strcmp (argv[0], builtin_funcs[i].name) == 0)
       builtin_func = builtin_funcs[i].func;

  dprintf (stderr, "builtin %p argv0 `%s'\n", builtin_func, argv[0]);

  pid = fork ();
  if (pid < 0)
    {
      fprintf (stderr, "sh: fork failed\n");
      exit (1);
    }

  if (pid == 0)
    {
      if (new_stdin != 0)
	{
	  dup2 (new_stdin, 0);
	  close (new_stdin);
	}
      if (new_stdout != 1)
	{
	  dup2 (new_stdout, 1);
	  close (new_stdout);
	}
      if (new_stderr != 2)
	{
	  dup2 (new_stderr, 2);
	  close (new_stderr);
	}

      if (builtin_func != NULL)
	exit (builtin_func (argv + 1));

      execvp (argv[0], argv);

      fprintf (stderr, "sh: execing %s failed: %s",
	       argv[0], strerror (errno));
      exit (127);
    }

  waitpid (pid, &status, 0);

  dprintf (stderr, "exiting run_command_array\n");

  if (WIFEXITED (status))
    {
      int rv = WEXITSTATUS (status);
      if (rv)
	exit (rv);
    }
  else if (WIFSIGNALED (status))
    {
      int sig = WTERMSIG (status);
      raise (sig);
    }
  else
    exit (1);
}

/* Run one command-as-a-string, by tokenizing it.  Limited to
   MAX_ARG_COUNT arguments.  Simple substitution is done of $1 to $9
   (as whole separate tokens) from iargs[].  Quoted strings work if
   the quotes wrap whole tokens; i.e. "foo bar" but not foo" bar".  */
static void
run_command_string (const char *cmdline, const char **iargs)
{
  char *args[MAX_ARG_COUNT+1];
  int ap = 0;
  const char *start, *end;
  int nargs;

  for (nargs = 0; iargs[nargs] != NULL; ++nargs)
    ;

  dprintf (stderr, "run_command_string starting: '%s'\n", cmdline);

  while (ap < MAX_ARG_COUNT)
    {
      /* If the argument is quoted, this is the quote character, else NUL.  */
      int in_quote = 0;

      /* Skip whitespace up to the next token.  */
      while (*cmdline && isspace (*cmdline))
	cmdline ++;
      if (*cmdline == 0)
	break;

      start = cmdline;
      /* Check for quoted argument.  */
      in_quote = (*cmdline == '\'' || *cmdline == '"') ? *cmdline : 0;

      /* Skip to end of token; either by whitespace or matching quote.  */
      dprintf (stderr, "in_quote %d\n", in_quote);
      while (*cmdline
	     && (!isspace (*cmdline) || in_quote))
	{
	  if (*cmdline == in_quote
	      && cmdline != start)
	    in_quote = 0;
	  dprintf (stderr, "[%c]%d ", *cmdline, in_quote);
	  cmdline ++;
	}
      dprintf (stderr, "\n");

      /* Allocate space for this token and store it in args[].  */
      end = cmdline;
      dprintf (stderr, "start<%s> end<%s>\n", start, end);
      args[ap] = (char *) xmalloc (end - start + 1);
      memcpy (args[ap], start, end - start);
      args[ap][end - start] = 0;

      /* Strip off quotes, if found.  */
      dprintf (stderr, "args[%d] = <%s>\n", ap, args[ap]);
      if (args[ap][0] == '\''
	  && args[ap][strlen (args[ap])-1] == '\'')
	{
	  args[ap][strlen (args[ap])-1] = 0;
	  args[ap] ++;
	}

      else if (args[ap][0] == '"'
	  && args[ap][strlen (args[ap])-1] == '"')
	{
	  args[ap][strlen (args[ap])-1] = 0;
	  args[ap] ++;
	}

      /* Replace positional parameters like $4.  */
      else if (args[ap][0] == '$'
	       && isdigit (args[ap][1])
	       && args[ap][2] == 0)
	{
	  int a = args[ap][1] - '1';
	  if (0 <= a && a < nargs)
	    args[ap] = strdup (iargs[a]);
	}

      ap ++;

      if (*cmdline == 0)
	break;
    }

  /* Lastly, NULL terminate the array and run it.  */
  args[ap] = NULL;
  run_command_array (args);
}

/* Run a script by reading lines and passing them to the above
   function.  */
static void
run_script (const char *filename, const char **args)
{
  char line[MAX_LINE_LENGTH + 1];
  dprintf (stderr, "run_script starting: '%s'\n", filename);
  FILE *f = fopen (filename, "r");
  if (f == NULL)
    {
      fprintf (stderr, "sh: %s: %s\n", filename, strerror (errno));
      exit (1);
    }
  while (fgets (line, sizeof (line), f) != NULL)
    {
      if (line[0] == '#')
	{
	  dprintf (stderr, "comment: %s\n", line);
	  continue;
	}
      run_command_string (line, args);
    }
  fclose (f);
}

int
main (int argc, const char **argv)
{
  int i;

  if (strcmp (argv[1], "--debug") == 0)
    {
      debug_mode = 1;
      --argc;
      ++argv;
    }

  dprintf (stderr, "container-sh starting:\n");
  for (i = 0; i < argc; i++)
    dprintf (stderr, "  argv[%d] is `%s'\n", i, argv[i]);

  if (strcmp (argv[1], "-c") == 0)
    {
      if (strcmp (argv[2], "--") == 0)
		run_command_string (argv[3], argv+4);
      else
		run_command_string (argv[2], argv+3);
    }
  else
    run_script (argv[1], argv+2);

  dprintf (stderr, "normal exit 0\n");
  return 0;
}