aboutsummaryrefslogtreecommitdiff
path: root/02/src/shell.c
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 05:31:06 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 06:14:42 +0000
commit9e1d304cac5367c3dbb1ca14700736680bd3a804 (patch)
tree31f328747acb934d365d423adfda144818ff5ad4 /02/src/shell.c
downloadlab-01-05-master.tar.gz
publishHEADmaster
Diffstat (limited to '02/src/shell.c')
-rw-r--r--02/src/shell.c1215
1 files changed, 1215 insertions, 0 deletions
diff --git a/02/src/shell.c b/02/src/shell.c
new file mode 100644
index 0000000..13666d7
--- /dev/null
+++ b/02/src/shell.c
@@ -0,0 +1,1215 @@
1// src/shell.c --- utility for providing access to protected folder
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#include <assert.h>
12#include <getopt.h>
13#include <stdlib.h>
14#include <errno.h>
15#include <unistd.h>
16#include <fcntl.h>
17#include <time.h>
18#include <sys/stat.h>
19#include <sys/mman.h>
20#include <glob.h>
21#include <stdio.h>
22#include <dirent.h>
23#include <readline/readline.h>
24#include <readline/history.h>
25
26#include "common.h"
27
28#define CONFDATA PREFIX"/confdata"
29
30int id;
31
32struct command_line {
33 struct string_builder expanded;
34 struct string_view command;
35 union {struct string_view *items, *args; };
36 union {uint32_t count, argc; };
37 uint32_t capacity;
38};
39
40struct string_builder confdata_log = {0};
41
42void
43append_confdata_log ()
44{
45 if (confdata_log.count) {
46 elevate ();
47 int fd = open (PREFIX"/log/confdata.log", O_CREAT | O_WRONLY | O_APPEND);
48 drop ();
49 write (fd, confdata_log.items, confdata_log.count);
50 close (fd);
51 DYNAMIC_ARRAY_RESET (confdata_log);
52 }
53}
54
55struct string_view
56canonicalize (struct string_view filename)
57{
58 static struct string_builder sb = {0};
59 STRING_BUILDER_RESET (sb);
60
61 static struct {
62 struct string_view *items;
63 uint32_t count;
64 uint32_t capacity;
65 } parts = {0};
66 DYNAMIC_ARRAY_RESET (parts);
67
68 bool ends_with_slash = filename.end[-1] == '/';
69
70 if (*filename.begin != '/') {
71 DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 128);
72 for (;;) {
73 if (getcwd (sb.string, sb.capacity)) {
74 sb.length = strlen (sb.string);
75 break;
76 }
77 if (errno != ERANGE)
78 return SVNULL;
79 DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 2*sb.capacity);
80 }
81 STRING_BUILDER_APPEND_CHAR (sb, '/');
82 }
83
84 STRING_BUILDER_APPEND_STRING_VIEW (sb, filename);
85 filename = SVSB (sb);
86
87 while (++filename.begin < filename.end) {
88 struct string_view part = string_view_pop_up_to (&filename, '/');
89 if (SVLEN (part) == 0) continue;
90 if (SVCMP (part, SVCSTR (".")) == 0) continue;
91 if (SVCMP (part, SVCSTR ("..")) == 0) {
92 if (parts.count == 0) return SVNULL;
93 parts.count -= 1;
94 continue;
95 }
96 DYNAMIC_ARRAY_APPEND (parts, part);
97 }
98
99 STRING_BUILDER_RESET (sb);
100 for (struct string_view *part = parts.items;
101 part < parts.items + parts.count; ++part) {
102 STRING_BUILDER_APPEND_CHAR (sb, '/');
103 STRING_BUILDER_APPEND_STRING_VIEW (sb, *part);
104 }
105
106 if (ends_with_slash)
107 STRING_BUILDER_APPEND_CHAR (sb, '/');
108
109 return SVSB (sb);
110}
111
112bool
113is_conf (struct string_view filename)
114{
115 elevate ();
116 char *canonical = realpath (filename.begin, NULL);
117 if (!canonical) {
118 struct string_view dirname = SVDUP0 (string_view_dirname (filename));
119 canonical = realpath (dirname.begin, NULL);
120 free ((void *) dirname.begin);
121 }
122 drop ();
123
124 if (canonical) {
125 bool starts_with = string_view_starts_with (SVCSTR (canonical), SVCSTR (CONFDATA));
126 free (canonical);
127 return starts_with;
128 }
129
130 return false;
131}
132
133bool
134authorize_conf (int id, struct string_view filename, enum access_rights ar)
135{
136 bool ret = true;
137 struct passwd passwd = load_passwd_file ();
138 struct passwd_entry *entry = lookup_id (passwd, id);
139 if (!entry) {
140 fprintf (stderr, "user no longer exists, switch user");
141 ret = false;
142 goto finish;
143 }
144
145 if ((ar & entry->access_rights) != ar) {
146 fprintf (stderr, "access denied '%.*s'\n", SVFMT (filename));
147 string_builder_printf (&passwd_log,
148 "%u user '%.*s' (%d) was denied access %c%c%c to '%.*s'\n",
149 time (NULL), SVFMT (entry->login), entry->id,
150 ar & AR_READ ? 'r' : '-',
151 ar & AR_WRITE ? 'w' : '-',
152 ar & AR_DELETE ? 'd' : '-', SVFMT (filename));
153 ret = false;
154 goto finish;
155 }
156 string_builder_printf (&passwd_log,
157 "%u user '%.*s' (%d) was granted access %c%c%c to '%.*s'\n",
158 time (NULL), SVFMT (entry->login), entry->id,
159 ar & AR_READ ? 'r' : '-',
160 ar & AR_WRITE ? 'w' : '-',
161 ar & AR_DELETE ? 'd' : '-', SVFMT (filename));
162
163 finish:
164 close_passwd_file (passwd);
165 return ret;
166}
167
168bool
169authorize_reg (struct string_view filename, enum access_rights ar)
170{
171 if (ar == 0) return true;
172
173 int how = 0;
174 how |= ar & AR_READ ? R_OK : 0;
175 how |= ar & (AR_WRITE | AR_DELETE) ? W_OK : 0;
176 if (access (filename.begin, how) == 0)
177 return true;
178
179 struct string_view dirname = SVDUP0 (string_view_dirname (filename));
180 int ret = access (dirname.begin, how);
181 free ((void *) dirname.begin);
182 if (ret == 0)
183 return true;
184
185 fprintf (stderr, "access denied '%.*s': %s\n",
186 SVFMT (filename), strerror (errno));
187 return false;
188}
189
190bool
191authorize (int id, struct string_view filename, enum access_rights ar)
192{
193 return is_conf (filename)
194 ? authorize_conf (id, filename, ar)
195 : authorize_reg (filename, ar);
196}
197
198bool
199authorize_known (int id, struct string_view filename,
200 enum access_rights ar, bool conf)
201{
202 return conf
203 ? authorize_conf (id, filename, ar)
204 : authorize_reg (filename, ar);
205}
206
207bool
208copy_file (struct string_view source, struct string_view destination)
209{
210 bool conf_source = is_conf (source);
211 bool conf_destination = is_conf (destination);
212
213 if (conf_source && !conf_destination) {
214 fprintf (stderr, "access denied: no one can copy out of confdata\n");
215 return false;
216 }
217
218 if (!authorize_known (id, source, AR_READ, conf_source )) return false;
219 if (!authorize_known (id, destination, AR_WRITE, conf_destination)) return false;
220
221 bool ret = true;
222 if (conf_source) elevate ();
223 int source_fd = open (source.begin, O_RDONLY);
224 if (conf_source) drop ();
225 if (source_fd == -1) {
226 fprintf (stderr, "error opening file for reading '%.*s': %s\n",
227 SVFMT (source), strerror (errno));
228 return false;
229 }
230
231 struct stat st;
232 if (fstat (source_fd, &st) == -1) {
233 fprintf (stderr, "error getting file stats for '%.*s': %s\n",
234 SVFMT (source), strerror (errno));
235 ret = false;
236 goto close_source;
237 }
238
239 if (!S_ISREG (st.st_mode)) {
240 fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source));
241 ret = false;
242 goto close_source;
243 }
244
245 if (conf_destination) elevate ();
246 int destination_fd = open (destination.begin, O_RDWR | O_CREAT | O_EXCL |
247 O_TRUNC, S_IRUSR | S_IWUSR);
248 if (conf_destination) drop ();
249 if (destination_fd == -1) {
250 fprintf (stderr, "error opening file for writing '%.*s': %s\n",
251 SVFMT (destination), strerror (errno));
252 ret = false;
253 goto close_source;
254 }
255
256 if (ftruncate (destination_fd, st.st_size) == -1) {
257 fprintf (stderr, "error setting file size for '%.*s': %s\n",
258 SVFMT (destination), strerror (errno));
259 ret = false;
260 goto close_destination;
261 }
262
263 void *source_map = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, source_fd, 0);
264 if (source_map == MAP_FAILED) {
265 fprintf (stderr, "error mapping source file '%.*s': %s\n",
266 SVFMT (source), strerror (errno));
267 ret = false;
268 goto close_destination;
269 }
270
271 void *destination_map = mmap (NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, destination_fd, 0);
272 if (destination_map == MAP_FAILED) {
273 fprintf (stderr, "error mapping destination file '%.*s': %s\n",
274 SVFMT (destination), strerror (errno));
275 ret = false;
276 goto munmap_source;
277 }
278
279 memcpy (destination_map, source_map, st.st_size);
280
281 if (conf_destination) {
282 elevate ();
283 char *canonical = realpath (destination.begin, NULL);
284 drop ();
285 assert (canonical);
286 string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n",
287 time (NULL), id, canonical + strlen (CONFDATA));
288 free (canonical);
289 }
290
291 munmap (destination_map, st.st_size);
292 munmap_source:
293 munmap (source_map, st.st_size);
294 close_destination:
295 close (destination_fd);
296 close_source:
297 close (source_fd);
298
299 elevate ();
300 if (conf_destination) chown (destination.begin, euid, egid);
301 else chown (destination.begin, ruid, rgid);
302 drop ();
303
304 return ret;
305}
306
307bool
308rename_file (struct string_view source, struct string_view destination)
309{
310 bool conf_source = is_conf (source);
311 bool conf_destination = is_conf (destination);
312
313 if (conf_source && !conf_destination) {
314 fprintf (stderr, "access denied: no one can rename out of confdata\n");
315 return false;
316 }
317
318 if (!authorize_known (id, source, AR_READ | AR_DELETE, conf_source)) return false;
319 if (!authorize_known (id, destination, AR_WRITE, conf_destination)) return false;
320
321 struct stat st;
322 if (stat (source.begin, &st) == -1) {
323 fprintf (stderr, "error getting file stats for '%.*s': %s\n",
324 SVFMT (source), strerror (errno));
325 return false;
326 }
327
328 if (!S_ISREG (st.st_mode)) {
329 fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source));
330 return false;
331 }
332
333 elevate ();
334 int res = access (destination.begin, F_OK);
335 drop ();
336 if (res == 0) {
337 fprintf (stderr, "destination file already exists '%.*s'\n", SVFMT (destination));
338 return false;
339 }
340
341 char *canonical = NULL;
342 if (conf_source || conf_destination) elevate ();
343 if (conf_source) canonical = realpath (source.begin, NULL);
344 res = rename (source.begin, destination.begin);
345 if (conf_source || conf_destination) drop ();
346 if (res == -1) {
347 fprintf (stderr, "error renaming '%.*s' to '%.*s': %s\n",
348 SVFMT (source), SVFMT (destination), strerror (errno));
349 free (canonical);
350 return false;
351 }
352
353 if (conf_destination) {
354 elevate ();
355 char *canonical = realpath (destination.begin, NULL);
356 drop ();
357 assert (canonical);
358 string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n",
359 time (NULL), id, canonical + strlen (CONFDATA));
360 free (canonical);
361 }
362
363 if (conf_source) {
364 assert (canonical);
365 string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n",
366 time (NULL), id, canonical + strlen (CONFDATA));
367 free (canonical);
368 }
369
370 elevate ();
371 if (conf_destination) chown (destination.begin, euid, egid);
372 else chown (destination.begin, ruid, rgid);
373 drop ();
374
375 return true;
376}
377
378int
379parse_command_line (struct command_line *cl, struct string_view line)
380{
381 DYNAMIC_ARRAY_RESET (cl->expanded);
382 DYNAMIC_ARRAY_RESET (*cl);
383 cl->command = SVNULL;
384
385 // printf ("line: %.*s\n", SVFMT (line));
386
387 const char *head = line.begin;
388 const char *end = line.end;
389 for (; head < end; ++head) {
390 if (*head == ' ' || *head == '\t') {
391 do head += 1;
392 while (head < end && (*head == ' ' || *head == '\t'));
393 if (head == end)
394 break;
395 if (cl->expanded.length)
396 STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0');
397 }
398
399 if (*head == '\'') {
400 head += 1;
401 if (head == end) return 0;
402 while (head < end && *head != '\'')
403 STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++);
404 if (head == end && (head[-1] != '\'' || head - 1 == line.begin)) return 0;
405 } else if (*head == '"') {
406 head += 1;
407 if (head == end) return 0;
408 if (*head == '!') {
409 STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA);
410 head += 1;
411 }
412 while (head < end && *head != '"')
413 STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++);
414 if (head == end && (head[-1] != '"' || head - 1 == line.begin)) return 0;
415 } else if (*head == '!' && (cl->expanded.length == 0 || DYNAMIC_ARRAY_LAST (cl->expanded) == '\0')) {
416 STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA);
417 } else {
418 STRING_BUILDER_APPEND_CHAR (cl->expanded, *head);
419 }
420 } STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0');
421
422 head = cl->expanded.string;
423 end = cl->expanded.string + cl->expanded.length;
424 cl->command.begin = head;
425 while (head < end && *head != '\0')
426 head += 1;
427 cl->command.end = head++;
428
429 if (SVLEN (cl->command) == 0) return 0;
430
431 while (head < end) {
432 struct string_view arg;
433 arg.begin = head;
434 do head += 1;
435 while (head < end && *head != '\0');
436 arg.end = head++;
437
438 const char *star = strchr (arg.begin, '*');
439 struct string_view trimmed = arg;
440 if (star) {
441 if (star == arg.begin) {
442 trimmed = SVCSTR (".");
443 } else {
444 trimmed = SVDUP0 ((struct string_view) {
445 .begin = arg.begin,
446 .end = star,
447 });
448 }
449 }
450
451 bool conf = is_conf (trimmed);
452 if (conf) elevate ();
453 glob_t globs;
454 if (glob (arg.begin, GLOB_MARK | GLOB_NOSORT | GLOB_BRACE | GLOB_TILDE_CHECK, NULL, &globs) != 0) {
455 DYNAMIC_ARRAY_APPEND (*cl, arg);
456 } else {
457 for (size_t i = 0; i < globs.gl_pathc; ++i) {
458 arg.begin = globs.gl_pathv[i];
459 arg.end = arg.begin + strlen (arg.begin);
460 DYNAMIC_ARRAY_APPEND (*cl, SVDUP0 (arg));
461 }
462 }
463 if (conf) drop ();
464
465 globfree (&globs);
466 }
467
468 // printf ("command: %.*s\n", SVFMT (cl->command));
469 // for (uint32_t i = 0; i < cl->argc; ++i)
470 // printf ("arg: %.*s\n", SVFMT (cl->args[i]));
471
472 return 1;
473}
474
475int
476command_exit (struct command_line cl)
477{
478 exit (0);
479}
480
481int
482command_help (struct command_line cl)
483{
484 puts ("Commands:");
485 puts (" help display information about builtin commands");
486 puts (" su LOGIN change user to LOGIN");
487 puts (" pwd print the name of the current working directory ");
488 puts (" whoami print effective user name");
489 puts (" echo [ARG]... write ARG(s) to the standard output");
490 puts (" ls [FILE]... list information about the FILE(s)");
491 puts (" cd [DIR] change the shell working directory");
492 puts (" mv SOURCE DEST rename SOURCE to DEST");
493 puts (" mv SOURCE... DIRECTORY move SOURCE(s) to DIRECTORY");
494 puts (" cp SOURCE DEST copy SOURCE to DEST");
495 puts (" cp SOURCE... DIRECTORY copy SOURCE(s) to DIRECTORY");
496 puts (" rm FILE... remove (unlink) the FILE(s)");
497 puts (" mkdir DIR... create the DIRECTORY(ies), if they do not already exist");
498 puts (" rmdir DIR... remove the DIRECTORY(ies), if they are empty");
499 puts (" cat [FILE]... concatenate FILE(s) to standard output");
500 puts (" append FILE append text from standard input to FILE");
501 puts ("");
502 puts ("Aliases:");
503 puts (" read -> cat");
504 puts (" copy -> cp");
505 puts (" remove -> rm");
506 puts ("");
507 return 0;
508}
509
510int
511command_su (struct command_line cl)
512{
513 if (cl.argc != 1) {
514 fprintf (stderr, "usage: %.*s LOGIN\n", SVFMT (cl.command));
515 return 1;
516 }
517
518 struct string_view login = cl.args[0];
519 int ret = 0;
520 struct passwd passwd = load_passwd_file ();
521 struct passwd_entry *entry;
522 if (getuid () == 0) {
523 entry = lookup_login (passwd, login);
524 if (!entry) {
525 fprintf (stderr, "user %.*s doesn't exist\n", SVFMT (login));
526 ret = 1;
527 goto close;
528 }
529 } else {
530 fputs ("Password: ", stdout);
531 struct string_view password = read_password ();
532 entry = authenticate (passwd, login, password);
533 if (!entry) {
534 ret = 1;
535 goto close;
536 }
537 }
538 id = entry->id;
539
540 close:
541 close_passwd_file (passwd);
542 return ret;
543}
544
545int
546command_pwd (struct command_line cl)
547{
548 size_t size = 256;
549
550 for (;;) {
551 char *buffer = (char *) malloc (size);
552 if (getcwd (buffer, size) == buffer) {
553 puts (buffer);
554 free (buffer);
555 return 0;
556 }
557 free (buffer);
558 if (errno != ERANGE)
559 return errno;
560 size *= 2;
561 }
562}
563
564int
565command_whoami (struct command_line cl)
566{
567 int ret = 0;
568 struct passwd passwd = load_passwd_file ();
569 struct passwd_entry *entry = lookup_id (passwd, id);
570 if (!entry) {
571 fprintf (stderr, "user with id %d no longed exists\n", id);
572 ret = 1;
573 goto close;
574 }
575
576 printf ("%d %.*s (%.*s) %c%c%c\n",
577 id, SVFMT (entry->login), SVFMT (entry->comment),
578 entry->access_rights & AR_READ ? 'r' : '-',
579 entry->access_rights & AR_WRITE ? 'w' : '-',
580 entry->access_rights & AR_DELETE ? 'd' : '-');
581
582 close:
583 close_passwd_file (passwd);
584 return ret;
585}
586
587int
588command_echo (struct command_line cl)
589{
590 if (cl.argc == 0)
591 return 0;
592
593 fputs (cl.args[0].begin, stdout);
594 for (uint32_t argind = 1; argind < cl.argc; ++argind) {
595 putchar (' ');
596 fputs (cl.args[argind].begin, stdout);
597 } putchar ('\n');
598
599 return 0;
600}
601
602int
603command_cd (struct command_line cl)
604{
605 struct string_view dir = cl.argc ? cl.args[0] : SVCSTR (CONFDATA);
606 bool conf = string_view_starts_with (dir, SVCSTR (CONFDATA));
607
608 if (conf) elevate ();
609 if (chdir (dir.begin) == -1) {
610 fprintf (stderr, "%.*s: cannot change directory to '%s': %s\n",
611 SVFMT (cl.command), dir.begin, strerror (errno));
612 }
613 if (conf) drop ();
614
615 return 0;
616}
617
618bool
619is_dir (struct string_view filename)
620{
621 struct stat st;
622
623 elevate ();
624 int res = stat (filename.begin, &st);
625 drop ();
626
627 if (res == -1)
628 return false;
629
630 return S_ISDIR (st.st_mode);
631}
632
633int
634command_mv (struct command_line cl)
635{
636 if (cl.argc < 2) {
637 fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command));
638 fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command));
639 return 1;
640 }
641
642 int ret = 0;
643
644 if (is_dir (cl.args[cl.argc - 1])) {
645 struct string_builder sb = {0};
646
647 struct string_view directory = cl.args[cl.argc - 1];
648 STRING_BUILDER_APPEND_STRING_VIEW (sb, directory);
649 if (DYNAMIC_ARRAY_LAST (sb) != '/')
650 STRING_BUILDER_APPEND_CHAR (sb, '/');
651
652 size_t directory_length = sb.length;
653 for (uint32_t i = 0; i < cl.argc - 1; ++i) {
654 sb.length = directory_length;
655 struct string_view source = cl.args[i];
656
657 struct string_view basename = string_view_basename (source);
658 STRING_BUILDER_APPEND_STRING_VIEW (sb, basename);
659 struct string_view destination = SVSB (sb);
660 STRING_BUILDER_APPEND_NULL (sb);
661
662 if (!rename_file (source, destination)) {
663 fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n",
664 SVFMT (source), SVFMT (destination));
665 ret = 1;
666 }
667 }
668
669 STRING_BUILDER_FREE (sb);
670 } else {
671 if (cl.argc != 2) {
672 fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command));
673 fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command));
674 return 1;
675 }
676
677 struct string_view source = cl.args[0];
678 struct string_view destination = cl.args[1];
679 if (!rename_file (source, destination)) {
680 fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n",
681 SVFMT (source), SVFMT (destination));
682 ret = 1;
683 }
684 }
685
686 return ret;
687}
688
689int
690command_cp (struct command_line cl)
691{
692 if (cl.argc < 2) {
693 fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command));
694 fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command));
695 return 1;
696 }
697
698 int ret = 0;
699
700 if (is_dir (cl.args[cl.argc - 1])) {
701 struct string_builder sb = {0};
702
703 struct string_view directory = cl.args[cl.argc - 1];
704 STRING_BUILDER_APPEND_STRING_VIEW (sb, directory);
705 if (DYNAMIC_ARRAY_LAST (sb) != '/')
706 STRING_BUILDER_APPEND_CHAR (sb, '/');
707
708 size_t directory_length = sb.length;
709 for (uint32_t i = 0; i < cl.argc - 1; ++i) {
710 sb.length = directory_length;
711 struct string_view source = cl.args[i];
712
713 struct string_view basename = string_view_basename (source);
714 STRING_BUILDER_APPEND_STRING_VIEW (sb, basename);
715 struct string_view destination = SVSB (sb);
716 STRING_BUILDER_APPEND_NULL (sb);
717
718 if (!copy_file (source, destination)) {
719 fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n",
720 SVFMT (source), SVFMT (destination));
721 ret = 1;
722 }
723 }
724
725 STRING_BUILDER_FREE (sb);
726 } else {
727 if (cl.argc != 2) {
728 fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command));
729 fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command));
730 return 1;
731 }
732
733 struct string_view source = cl.args[0];
734 struct string_view destination = cl.args[1];
735 if (!copy_file (source, destination)) {
736 fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n",
737 SVFMT (source), SVFMT (destination));
738 ret = 1;
739 }
740 }
741
742 return ret;
743}
744
745int
746command_rm (struct command_line cl)
747{
748 if (cl.argc == 0) {
749 fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command));
750 return 1;
751 }
752
753 int ret = 0;
754 for (uint32_t argind = 0; argind < cl.argc; ++argind) {
755 struct string_view file = cl.args[argind];
756 const char *filename = file.begin;
757
758 bool conf = is_conf (file);
759 if (!authorize_known (id, file, AR_DELETE, conf)) {
760 ret = 1;
761 continue;
762 }
763
764 char *canonical = NULL;
765 if (conf) {
766 elevate ();
767 canonical = realpath (filename, NULL);
768 }
769 int res = remove (filename);
770 if (conf) drop ();
771 if (res == -1) {
772 fprintf (stderr, "%.*s: cannot remove file '%s': %s\n",
773 SVFMT (cl.command), filename, strerror (errno));
774 ret = 1;
775 free (canonical);
776 } else if (conf) {
777 assert (canonical);
778 string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n",
779 time (NULL), id, canonical + strlen (CONFDATA));
780 free (canonical);
781 }
782 }
783
784 return ret;
785}
786
787int
788command_mkdir (struct command_line cl)
789{
790 if (cl.argc == 0) {
791 fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command));
792 return 1;
793 }
794
795 int ret = 0;
796 for (uint32_t argind = 0; argind < cl.argc; ++argind) {
797 const char *filename = cl.args[argind].begin;
798
799 bool conf = is_conf (cl.args[argind]);
800 if (!authorize_known (id, cl.args[argind], AR_WRITE, conf)) {
801 ret = 1;
802 continue;
803 }
804
805 if (conf) elevate ();
806 int res = mkdir (filename, S_IRUSR | S_IWUSR | S_IXUSR);
807 if (conf) drop ();
808 if (res == -1) {
809 fprintf (stderr, "%.*s: cannot create directory '%s': %s\n",
810 SVFMT (cl.command), filename, strerror (errno));
811 ret = 1;
812 } else if (conf) {
813 elevate ();
814 char *canonical = realpath (filename, NULL);
815 drop ();
816 assert (canonical);
817 string_builder_printf (&confdata_log, "%u user %d created directory '!%s'\n",
818 time (NULL), id, canonical + strlen (CONFDATA));
819 free (canonical);
820 }
821 }
822
823 return ret;
824}
825
826int
827command_rmdir (struct command_line cl)
828{
829 if (cl.argc == 0) {
830 fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command));
831 return 1;
832 }
833
834 int ret = 0;
835 for (uint32_t argind = 0; argind < cl.argc; ++argind) {
836 const char *filename = cl.args[argind].begin;
837
838 bool conf = is_conf (cl.args[argind]);
839 if (!authorize_known (id, cl.args[argind], AR_DELETE, conf)) {
840 ret = 1;
841 continue;
842 }
843 char *canonical = NULL;
844 if (conf) {
845 elevate ();
846 canonical = realpath (filename, NULL);
847 }
848 int res = rmdir (filename);
849 if (conf) drop ();
850 if (res == -1) {
851 fprintf (stderr, "%.*s: cannot remove directory '%s': %s\n",
852 SVFMT (cl.command), filename, strerror (errno));
853 ret = 1;
854 free (canonical);
855 } else if (conf) {
856 assert (canonical);
857 string_builder_printf (&confdata_log, "%u user %d removed directory '!%s'\n",
858 time (NULL), id, canonical + strlen (CONFDATA));
859 free (canonical);
860 }
861 }
862
863 return ret;
864}
865
866int
867command_cat (struct command_line cl)
868{
869 int ret = 0;
870 for (uint32_t argind = 0; argind < cl.argc; ++argind) {
871 struct string_view file = cl.args[argind];
872 bool conf = is_conf (file);
873 if (!authorize_known (id, file, AR_READ, conf)) continue;
874
875 const char *filename = file.begin;
876 if (conf) elevate ();
877 int fd = open (filename, O_RDONLY);
878 if (conf) drop ();
879 if (fd == -1) {
880 fprintf (stderr, "%.*s: cannot access '%s': %s\n",
881 SVFMT (cl.command), filename, strerror (errno));
882 ret = 1;
883 continue;
884 }
885
886 struct stat st;
887 int res = fstat (fd, &st);
888 if (res == -1) {
889 fprintf (stderr, "%.*s: cannot access '%s': %s\n",
890 SVFMT (cl.command), filename, strerror (errno));
891 ret = 2;
892 goto close;
893 }
894
895 void *contents = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
896 if (contents == NULL) {
897 ret = 3;
898 goto close;
899 }
900 write (0, contents, st.st_size);
901
902 if (conf) {
903 elevate ();
904 char *canonical = realpath (file.begin, NULL);
905 drop ();
906 assert (canonical);
907 string_builder_printf (&confdata_log, "%u user %d read file '!%s'\n",
908 time (NULL), id, canonical + strlen (CONFDATA));
909 free (canonical);
910 }
911
912 munmap (contents, st.st_size);
913 close:
914 close (fd);
915 }
916
917 drop ();
918
919 return ret;
920}
921
922int
923command_append (struct command_line cl)
924{
925 static struct string_builder sb = {0};
926
927 if (cl.argc != 1) {
928 fprintf (stderr, "usage: %.*s FILE\n", SVFMT (cl.command));
929 return 1;
930 }
931
932 struct string_view filename = cl.args[0];
933
934 bool conf = is_conf (filename);
935 if (!authorize_known (id, filename, AR_WRITE, conf))
936 return 1;
937
938 STRING_BUILDER_RESET (sb);
939 char *line;
940 while ((line = readline ("append> ")) != NULL) {
941 STRING_BUILDER_APPEND_CSTR (sb, line);
942 STRING_BUILDER_APPEND_CHAR (sb, '\n');
943 free (line);
944 }
945
946 int ret = 0;
947 if (sb.length) {
948 if (!authorize_known (id, filename, AR_WRITE, conf))
949 return 1;
950
951 if (conf) elevate ();
952 int fd = open (filename.begin, O_WRONLY | O_CREAT | O_APPEND);
953 if (conf) drop ();
954 if (fd == -1) {
955 fprintf (stderr, "failed to open '%.*s' for writing\n", SVFMT (filename));
956 return 1;
957 }
958
959 write (fd, sb.string, sb.length);
960
961 if (conf) {
962 elevate ();
963 char *canonical = realpath (filename.begin, NULL);
964 drop ();
965 assert (canonical);
966 string_builder_printf (&confdata_log, "%u user %d appended to file '!%s'\n",
967 time (NULL), id, canonical + strlen (CONFDATA));
968 free (canonical);
969 }
970
971 close (fd);
972 }
973
974 return 0;
975}
976
977int
978command_ls (struct command_line cl)
979{
980 if (cl.argc == 0)
981 DYNAMIC_ARRAY_APPEND (cl, SVCSTR ("."));
982
983 for (uint32_t argind = 0; argind < cl.argc; ++argind) {
984 struct string_view file = cl.args[argind];
985 const char *filename = file.begin;
986
987 bool conf = is_conf (file);
988 if (!authorize_known (id, file, AR_READ, conf))
989 continue;
990
991 if (conf) elevate ();
992 int fd = open (filename, O_RDONLY);
993 if (conf) drop ();
994 if (fd == -1) {
995 fprintf (stderr, "%.*s: cannot access '%s': %s\n",
996 SVFMT (cl.command), filename, strerror (errno));
997 continue;
998 }
999
1000 struct stat st;
1001 if (fstat (fd, &st) == -1) {
1002 fprintf (stderr, "%.*s: cannot access '%s': %s\n",
1003 SVFMT (cl.command), filename, strerror (errno));
1004 goto close;
1005 }
1006
1007 if (S_ISREG (st.st_mode)) {
1008 printf ("%s\n", filename);
1009 if (conf) {
1010 elevate ();
1011 char *canonical = realpath (filename, NULL);
1012 drop ();
1013 assert (canonical);
1014 string_builder_printf (&confdata_log, "%u user %d listed file '!%s'\n",
1015 time (NULL), id, canonical + strlen (CONFDATA));
1016 free (canonical);
1017 }
1018 goto close;
1019 }
1020
1021 DIR *dir = fdopendir (fd);
1022 if (dir == NULL) {
1023 fprintf (stderr, "%.*s: cannot access '%s': %s\n",
1024 SVFMT (cl.command), filename, strerror (errno));
1025 goto close;
1026 }
1027
1028 if (argind != 0) putchar ('\n');
1029 printf ("%s:\n", filename);
1030 struct dirent *entry;
1031 while ((entry = readdir (dir)) != NULL) {
1032 if (strcmp (entry->d_name, ".") == 0 ||
1033 strcmp (entry->d_name, "..") == 0) {
1034 continue;
1035 }
1036
1037 if (entry->d_type == DT_DIR)
1038 printf ("%s/\n", entry->d_name);
1039 else
1040 printf ("%s\n", entry->d_name);
1041 }
1042
1043 if (conf) {
1044 elevate ();
1045 char *canonical = realpath (filename, NULL);
1046 drop ();
1047 assert (canonical);
1048 string_builder_printf (&confdata_log, "%u user %d listed directory '!%s'\n",
1049 time (NULL), id, canonical + strlen (CONFDATA));
1050 free (canonical);
1051 }
1052
1053 closedir (dir);
1054 close:
1055 close (fd);
1056 }
1057
1058 return 0;
1059}
1060
1061const char *
1062prompt (int ret)
1063{
1064 static struct string_builder sb = {0};
1065
1066 STRING_BUILDER_RESET (sb);
1067 STRING_BUILDER_APPEND_CSTR (sb, "\e[36m[\e[34m");
1068
1069 struct passwd passwd = load_passwd_file ();
1070 struct passwd_entry *entry = lookup_id (passwd, id);
1071 if (entry) {
1072 STRING_BUILDER_APPEND_STRING_VIEW (sb, entry->login);
1073
1074#ifdef MAC
1075 STRING_BUILDER_APPEND_CSTR (sb, "\e[36m@");
1076 STRING_BUILDER_APPEND_CSTR (sb, entry->security_level == SL_COUNT - 1
1077 ? "\e[34m"
1078 : "\e[31m");
1079 STRING_BUILDER_APPEND_CSTR (sb, security_level_names[entry->security_level]);
1080#endif
1081 } else STRING_BUILDER_APPEND_CHAR (sb, '?');
1082 close_passwd_file (passwd);
1083
1084 STRING_BUILDER_APPEND_CSTR (sb, "\e[36m:\e[34m");
1085 struct string_view canonical = canonicalize (SVCSTR ("."));
1086 if (strncmp (canonical.begin, CONFDATA, strlen (CONFDATA)) == 0) {
1087 STRING_BUILDER_APPEND_CHAR (sb, '!');
1088 canonical.begin += strlen (CONFDATA);
1089 } STRING_BUILDER_APPEND_STRING_VIEW (sb, canonical);
1090
1091 STRING_BUILDER_APPEND_CSTR (sb, "\e[36m]\e[34m");
1092
1093 if (ret) string_builder_printf (&sb, " \e[31m%d", ret);
1094
1095 STRING_BUILDER_APPEND_CSTR (sb, ruid == euid ? " \e[31m#" : " \e[95m$");
1096 STRING_BUILDER_APPEND_CSTR (sb, "\e[0m ");
1097 STRING_BUILDER_TERMINATE (sb);
1098
1099 return sb.string;
1100}
1101
1102int
1103main (int argc, char *argv[])
1104{
1105 ruid = getuid ();
1106 rgid = getgid ();
1107 euid = geteuid ();
1108 egid = getegid ();
1109 drop ();
1110
1111 static struct option longopts[] = {
1112 { "help", no_argument, NULL, 'h' },
1113 { "password", required_argument, NULL, 'p' },
1114 {0}
1115 };
1116 char ch;
1117 struct string_view password = {0};
1118 while ((ch = getopt_long (argc, argv, ":hp:", longopts, NULL)) != -1) {
1119 switch (ch) {
1120 case 'h':
1121 printf ("Usage: %s [options] [LOGIN]\n", argv[0]);
1122 puts ("");
1123 puts ("Options:");
1124 puts (" -h, --help display this help message and exit");
1125 puts (" -p, --password PASSWORD password of the account (only if login was provided)");
1126 puts ("");
1127 exit (0);
1128 case 'p': password = SVCSTR (optarg); break;
1129 case '?': DIE ("unknown option %s", argv[optind - 1]);
1130 case ':': DIE ("missing argument for %s", argv[optind - 1]);
1131 default: DIE ("unexpected opt error");
1132 }
1133 }
1134
1135 struct passwd passwd = load_passwd_file ();
1136 struct passwd_entry *entry = NULL;
1137 if (argv[optind] != NULL) {
1138 if (argv[optind + 1] != NULL)
1139 DIE ("extra trailing arguments starting with: %s", argv[optind + 1]);
1140
1141 struct string_view login = SVCSTR (argv[optind]);
1142 if (ruid == 0) {
1143 entry = lookup_login (passwd, login);
1144 append_passwd_log ();
1145 if (!entry) {
1146 DIE ("user %.*s doesn't exist", SVFMT (login));
1147 }
1148 } else {
1149 if (password.begin == NULL) {
1150 fputs ("Password: ", stdout);
1151 password = read_password ();
1152 }
1153 entry = authenticate (passwd, login, password);
1154 append_passwd_log ();
1155 if (entry == NULL) exit (1);
1156 }
1157 } else {
1158 do {
1159 fputs ("Login: ", stdout); fflush (stdout);
1160 struct string_view login = read_login ();
1161 fputs ("Password: ", stdout); fflush (stdout);
1162 struct string_view password = read_password ();
1163 entry = authenticate (passwd, login, password);
1164 } while (entry == NULL);
1165 }
1166
1167 id = entry->id;
1168 printf ("Hello, %.*s! (%d)\n", SVFMT (entry->comment), id);
1169 close_passwd_file (passwd);
1170 printf ("Run 'help', to get a list of available commands.\n");
1171
1172 struct command_line cl = {0};
1173 int ret = 0;
1174 for (;;) {
1175 char *line = readline (prompt (ret));
1176 if (line == NULL) break;
1177 add_history (line);
1178 switch (parse_command_line (&cl, SVCSTR (line))) {
1179 case 1:
1180 if (SVCMP (cl.command, SVCSTR ("exit" )) == 0) ret = command_exit (cl);
1181 else if (SVCMP (cl.command, SVCSTR ("help" )) == 0) ret = command_help (cl);
1182 else if (SVCMP (cl.command, SVCSTR ("su" )) == 0) ret = command_su (cl);
1183 else if (SVCMP (cl.command, SVCSTR ("pwd" )) == 0) ret = command_pwd (cl);
1184 else if (SVCMP (cl.command, SVCSTR ("whoami")) == 0) ret = command_whoami (cl);
1185 else if (SVCMP (cl.command, SVCSTR ("echo" )) == 0) ret = command_echo (cl);
1186 else if (SVCMP (cl.command, SVCSTR ("ls" )) == 0) ret = command_ls (cl);
1187 else if (SVCMP (cl.command, SVCSTR ("cd" )) == 0) ret = command_cd (cl);
1188 else if (SVCMP (cl.command, SVCSTR ("mv" )) == 0) ret = command_mv (cl);
1189 else if (SVCMP (cl.command, SVCSTR ("cp" )) == 0) ret = command_cp (cl);
1190 else if (SVCMP (cl.command, SVCSTR ("rm" )) == 0) ret = command_rm (cl);
1191 else if (SVCMP (cl.command, SVCSTR ("mkdir" )) == 0) ret = command_mkdir (cl);
1192 else if (SVCMP (cl.command, SVCSTR ("rmdir" )) == 0) ret = command_rmdir (cl);
1193 else if (SVCMP (cl.command, SVCSTR ("cat" )) == 0) ret = command_cat (cl);
1194 else if (SVCMP (cl.command, SVCSTR ("read" )) == 0) ret = command_cat (cl);
1195 else if (SVCMP (cl.command, SVCSTR ("copy" )) == 0) ret = command_cp (cl);
1196 else if (SVCMP (cl.command, SVCSTR ("remove")) == 0) ret = command_rm (cl);
1197 else if (SVCMP (cl.command, SVCSTR ("append")) == 0) ret = command_append (cl);
1198 else puts ("unknown command, run `help' to get the list of available commands");
1199 break;
1200 case 0: break;
1201 case -1:
1202 putchar ('\n');
1203 exit (0);
1204 default:
1205 fputs ("invalid command line", stderr);
1206 break;
1207 } free (line);
1208 append_passwd_log ();
1209 append_confdata_log ();
1210 } putchar ('\n');
1211
1212 return EXIT_SUCCESS;
1213}
1214
1215// src/shell.c ends here