aboutsummaryrefslogtreecommitdiff
path: root/02/src
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
downloadlab-01-05-9e1d304cac5367c3dbb1ca14700736680bd3a804.tar.gz
publishHEADmaster
Diffstat (limited to '02/src')
-rw-r--r--02/src/bruteforce.c43
-rw-r--r--02/src/common.c463
-rw-r--r--02/src/common.h107
-rw-r--r--02/src/cracking.c138
-rw-r--r--02/src/cracking.h35
-rw-r--r--02/src/dynamic-array.h68
-rw-r--r--02/src/measure.c70
-rw-r--r--02/src/passwdctl.c493
-rw-r--r--02/src/shell.c1215
-rw-r--r--02/src/string-builder.c58
-rw-r--r--02/src/string-builder.h56
-rw-r--r--02/src/string-view.c147
-rw-r--r--02/src/string-view.h46
13 files changed, 2939 insertions, 0 deletions
diff --git a/02/src/bruteforce.c b/02/src/bruteforce.c
new file mode 100644
index 0000000..38dfd0f
--- /dev/null
+++ b/02/src/bruteforce.c
@@ -0,0 +1,43 @@
1// src/bruteforce.c --- utility to bruteforce shell password
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 <stddef.h>
12
13#include "cracking.h"
14
15int
16main (int argc, char *argv[])
17{
18 if (argc != 2) {
19 fprintf (stderr, "Usage: %s LOGIN\n", argv[0]);
20 exit (EXIT_FAILURE);
21 }
22
23 struct shell shell = spawn_shell ();
24 struct string_view login = SVCSTR (argv[1]);
25 struct string_builder password = {0};
26 STRING_BUILDER_APPEND_STRING_VIEW (password, SVCSTR ("A"));
27
28 for (size_t attmept = 0;; ++attmept) {
29 if (attmept % 10000 == 0)
30 printf ("Trying: %.*s\n", SBFMT (password));
31
32 if (test_credentials (shell, login, SVSB (password)))
33 break;
34
35 password_bump (&password);
36 }
37
38 printf ("Found: %.*s\n", SVFMT (SVSB (password)));
39
40 return EXIT_SUCCESS;
41}
42
43// src/bruteforce.c ends here
diff --git a/02/src/common.c b/02/src/common.c
new file mode 100644
index 0000000..05a0e49
--- /dev/null
+++ b/02/src/common.c
@@ -0,0 +1,463 @@
1#include "common.h"
2
3#include <termios.h>
4#include <fcntl.h>
5#include <unistd.h>
6
7#include <openssl/rand.h>
8#include <openssl/err.h>
9
10struct string_builder passwd_log = {0};
11
12uid_t ruid;
13gid_t rgid;
14uid_t euid;
15gid_t egid;
16
17char
18encode6 (unsigned char b6)
19{
20 if (b6 < ('9' - '.' + 1) ) return '.' + b6;
21 if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) ) return 'A' + b6 - ('9' - '.' + 1);
22 if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) + ('z' - 'a' + 1)) return 'a' + b6 - ('9' - '.' + 1) - ('Z' - 'A' + 1);
23 printf ("0x%X\n", b6);
24 assert (!"out of range");
25 return -1;
26}
27
28unsigned char
29decode6 (char c)
30{
31 if ('.' <= c && c <= '9') return c - '.';
32 if ('A' <= c && c <= 'Z') return c - 'A' + ('9' - '.' + 1);
33 if ('a' <= c && c <= 'z') return c - 'a' + ('9' - '.' + 1) + ('Z' - 'A' + 1);
34 assert (!"out of range");
35 return -1;
36}
37
38void
39encode (char *into, const unsigned char* from, unsigned int size)
40{
41 for (; size >= 3; size -= 3) {
42 // 012345670123456701234567
43 // 012345012345012345012345
44 into[0] = encode6 ( from[0] >> 2);
45 into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4);
46 into[2] = encode6 ((from[1] & 0b00001111) << 2 | from[2] >> 6);
47 into[3] = encode6 ((from[2] & 0b00111111));
48
49 from += 3;
50 into += 4;
51 }
52 if (size == 2) {
53 into[0] = encode6 ( from[0] >> 2);
54 into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4);
55 into[2] = encode6 ((from[1] & 0b00001111) << 2);
56 } else if (size == 1) {
57 into[0] = encode6 ( from[0] >> 2);
58 into[1] = encode6 ((from[0] & 0b00000011) << 4);
59 }
60}
61
62void
63decode (unsigned char *into, struct string_view from)
64{
65 size_t len;
66
67 for (len = SVLEN (from); len >= 4; len -= 4) {
68 // 012345012345012345012345
69 // 012345670123456701234567
70
71 unsigned char d1 = decode6 (from.begin[0]);
72 unsigned char d2 = decode6 (from.begin[1]);
73 unsigned char d3 = decode6 (from.begin[2]);
74 unsigned char d4 = decode6 (from.begin[3]);
75
76 into[0] = d1 << 2 | d2 >> 4;
77 into[1] = (d2 & 0b001111) << 4 | d3 >> 2;
78 into[2] = d3 << 6 | d4;
79
80 from.begin += 4;
81 into += 3;
82 }
83 if (len == 3) {
84 unsigned char d1 = decode6 (from.begin[0]);
85 unsigned char d2 = decode6 (from.begin[1]);
86 unsigned char d3 = decode6 (from.begin[2]);
87
88 into[0] = d1 << 2 | d2 >> 4;
89 into[1] = (d2 & 0b001111) << 4 | d3 >> 2;
90 } else if (len == 2) {
91 unsigned char d1 = decode6 (from.begin[0]);
92 unsigned char d2 = decode6 (from.begin[1]);
93
94 into[0] = d1 << 2 | d2 >> 4;
95 } else assert ("!unreachable");
96}
97
98void
99generate_salt (unsigned char salt[PASSWORD_SALT_SIZE])
100{
101 if (RAND_bytes (salt, PASSWORD_SALT_SIZE) != 1) {
102 DIE ("error generating salt: RAND_bytes: %s",
103 ERR_reason_error_string (ERR_get_error ()));
104 }
105}
106
107unsigned char *
108hash_password (unsigned char hash[SHA_DIGEST_LENGTH],
109 struct string_view password,
110 const unsigned char salt[PASSWORD_SALT_SIZE])
111{
112 EVP_MD_CTX *mdctx = EVP_MD_CTX_new ();
113 if (mdctx == NULL) {
114 DIE ("error hashing creating context: EVP_MD_CTX_new: %s",
115 ERR_reason_error_string (ERR_get_error ()));
116 }
117
118 if (EVP_DigestInit_ex (mdctx, EVP_sha1 (), NULL) != 1) {
119 DIE ("error initializing digest: EVP_DigestInit_ex: %s",
120 ERR_reason_error_string (ERR_get_error ()));
121 }
122
123 if (EVP_DigestUpdate (mdctx, password.begin, SVLEN (password)) != 1) {
124 DIE ("error updating digest with password: EVP_DigestUpdate: %s",
125 ERR_reason_error_string (ERR_get_error ()));
126 }
127
128 if (EVP_DigestUpdate (mdctx, salt, PASSWORD_SALT_SIZE) != 1) {
129 DIE ("error updating digest with salt: EVP_DigestUpdate: %s",
130 ERR_reason_error_string (ERR_get_error ()));
131 }
132
133 unsigned int hash_len;
134 if (EVP_DigestFinal_ex(mdctx, hash, &hash_len) != 1) {
135 DIE ("error finalizing digest: EVP_DigestFinal_ex: %s",
136 ERR_reason_error_string (ERR_get_error ()));
137 }
138
139 EVP_MD_CTX_free (mdctx);
140
141 return hash;
142}
143
144struct string_view
145encode_password (struct string_view password)
146{
147 static char encoded[PASSWORD_ENCODED_LENGTH + 1] = {
148 [0] = '$',
149 [1] = '1',
150 [2] = '$',
151 [3 + PASSWORD_SALT_LENGTH] = '$',
152 };
153
154 char *salt_encoded = (void *) &encoded[3];
155 char *hash_encoded = (void *) &encoded[3 + PASSWORD_SALT_LENGTH + 1];
156
157 unsigned char salt[PASSWORD_SALT_SIZE];
158 generate_salt (salt);
159 encode (salt_encoded, salt, sizeof (salt));
160
161 unsigned char hash[SHA_DIGEST_LENGTH];
162 hash_password (hash, password, salt);
163 encode (hash_encoded, hash, SHA_DIGEST_LENGTH);
164
165 return (struct string_view) { encoded, encoded + PASSWORD_ENCODED_LENGTH };
166}
167
168bool
169check_password (struct string_view password,
170 struct string_view encoded_password)
171{
172 if (*encoded_password.begin++ != '$') return false;
173 if (*encoded_password.begin++ != '1') return false;
174 if (*encoded_password.begin++ != '$') return false;
175
176 struct string_view encoded_salt = {
177 .begin = encoded_password.begin,
178 .end = encoded_password.begin += PASSWORD_SALT_LENGTH,
179 };
180 if (*encoded_password.begin++ != '$') return false;
181
182 struct string_view encoded_hash = {
183 .begin = encoded_password.begin,
184 .end = encoded_password.begin + PASSWORD_HASH_LENGTH,
185 };
186
187 unsigned char decoded_salt[PASSWORD_SALT_SIZE];
188 decode (decoded_salt, encoded_salt);
189
190 unsigned char hash[SHA_DIGEST_LENGTH];
191 hash_password (hash, password, decoded_salt);
192
193 unsigned char decoded_hash[SHA_DIGEST_LENGTH];
194 decode (decoded_hash, encoded_hash);
195
196 return memcmp (hash, decoded_hash, sizeof (hash)) == 0;
197}
198
199int
200fscan_passwd_entry (FILE *stream, struct passwd_entry *entry)
201{
202 *entry = (struct passwd_entry) {0};
203
204 int c;
205 do c = getc (stream);
206 while (c == '\n');
207 if (c == EOF)
208 return 0;
209 ungetc (c, stream);
210
211 char buffer[256 + 1];
212
213 fscanf (stream, "%32[a-zA-Z0-9]", buffer);
214 if (getc (stream) != ':') return -1;
215 entry->login = string_view_strdup (buffer);
216
217 fread (buffer, 1, PASSWORD_ENCODED_LENGTH, stream);
218 if (getc (stream) != ':') return -1;
219 buffer[PASSWORD_ENCODED_LENGTH] = '\0';
220 entry->encoded_password = string_view_strdup (buffer);
221
222 fscanf (stream, "%d", &entry->id);
223 if (getc (stream) != ':') return -1;
224
225 fscanf (stream, "%d", (int *) &entry->access_rights);
226 if (entry->access_rights > 0b111) return -1;
227 if (getc (stream) != ':') return -1;
228
229 int len = 0;
230 fscanf (stream, "%256[^:\n]%n", buffer, &len);
231 if (len)
232 entry->comment = SVDUP0 ((struct string_view) { buffer, buffer + len });
233
234 return 1;
235}
236
237void
238fprint_passwd_entry (FILE *stream, const struct passwd_entry *entry)
239{
240 if (entry->id < 0)
241 DIE ("id < 0");
242
243 struct string_view comment;
244 if (entry->comment.begin) {
245 comment.begin = entry->comment.begin;
246 comment.end = entry->comment.end;
247 } else {
248 comment.begin = "";
249 comment.end = comment.begin;
250 }
251
252 fprintf (stream, "%.*s:%.*s:%d:%d:%.*s\n",
253 SVFMT (entry->login),
254 SVFMT (entry->encoded_password),
255 entry->id,
256 entry->access_rights,
257 SVFMT (comment));
258}
259
260void
261lock_passwd_file (struct passwd passwd)
262{
263 if (lockf (fileno (passwd.stream), F_TLOCK, 0) != 0)
264 DIE ("unable to lock passwd file: %s", strerror (errno));
265}
266
267void
268unlock_passwd_file (struct passwd passwd)
269{
270 if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0)
271 DIE ("unable to unlock passwd file: %s", strerror (errno));
272}
273
274struct passwd
275load_passwd_file (void)
276{
277 elevate ();
278 struct passwd passwd = {
279 .stream = fopen (PREFIX"/etc/passwd", "r+"),
280 };
281 drop ();
282
283 if (passwd.stream == NULL)
284 DIE ("unable to open passwd file: %s", strerror (errno));
285
286 if (lockf (fileno (passwd.stream), F_TEST, 0) != 0)
287 DIE ("passwd file is locked: %s", strerror (errno));
288
289 for (int i = 0;; ++i) {
290 struct passwd_entry entry;
291 int ret = fscan_passwd_entry (passwd.stream, &entry);
292 if (ret == -1)
293 DIE (PREFIX"/etc/passwd:%d: failed to parse entry", i);
294 if (ret == 0)
295 break;
296 DYNAMIC_ARRAY_APPEND (passwd, entry);
297 }
298
299 return passwd;
300}
301
302void
303save_passwd_file (struct passwd passwd)
304{
305 ftruncate (fileno (passwd.stream), 0);
306 rewind (passwd.stream);
307 for (struct passwd_entry *entry = passwd.items;
308 entry < passwd.items + passwd.count; ++entry) {
309 fprint_passwd_entry (passwd.stream, entry);
310 } fflush (passwd.stream);
311}
312
313void
314close_passwd_file (struct passwd passwd)
315{
316 for (uint32_t i = 0; i < passwd.count; ++i) {
317 free ((void *) passwd.items[i].login.begin);
318 free ((void *) passwd.items[i].encoded_password.begin);
319 free ((void *) passwd.items[i].comment.begin);
320 }
321 DYNAMIC_ARRAY_FREE (passwd);
322
323 if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0)
324 DIE ("unable to unlock passwd file: %s", strerror (errno));
325
326 fclose (passwd.stream);
327}
328
329struct string_view
330read_password ()
331{
332 static char password[PASSWORD_MAX_LENGTH + 2];
333
334 struct termios term_orig;
335 tcgetattr (fileno (stdin), &term_orig);
336 struct termios term_noecho = term_orig;
337 term_noecho.c_lflag &= ~ECHO;
338 tcsetattr (fileno (stdin), 0, &term_noecho);
339
340 if (fgets (password, sizeof (password), stdin) == NULL) {
341 tcsetattr (fileno (stdin), 0, &term_orig);
342 putchar ('\n');
343 exit (0);
344 } tcsetattr (fileno (stdin), 0, &term_orig);
345
346 putchar ('\n');
347 size_t len = strlen (password) - 1;
348 if (password[len] != '\n')
349 DIE ("password too long");
350 password[len] = '\0';
351
352 return (struct string_view) { password, password + len };
353}
354
355struct string_view
356read_login ()
357{
358 static char login[LOGIN_MAX_LENGTH + 2];
359
360 if (fgets (login, sizeof (login), stdin) == NULL) {
361 putchar ('\n');
362 exit (0);
363 }
364
365 size_t len = strlen (login) - 1;
366 if (login[len] != '\n')
367 DIE ("login too long");
368 login[len] = '\0';
369
370 return (struct string_view) { login, login + len };
371}
372
373struct passwd_entry *
374authenticate (struct passwd passwd,
375 struct string_view login,
376 struct string_view password)
377{
378 struct passwd_entry *entry = lookup_login (passwd, login);
379
380 if (!entry) {
381 fprintf (stderr, "user %.*s not found\n", SVFMT (login));
382 return NULL;
383 }
384
385 if (!check_password (password, entry->encoded_password)) {
386 fputs ("authentication failure\n", stderr);
387 string_builder_printf (&passwd_log, "%u user %.*s supplied incorrect password\n",
388 time (NULL), SVFMT (entry->login));
389 return NULL;
390 }
391
392 string_builder_printf (&passwd_log, "%u authenticated user %.*s %d\n",
393 time (NULL), SVFMT (entry->login), entry->id);
394
395 return entry;
396}
397
398void
399append_passwd_log ()
400{
401 if (passwd_log.count) {
402 elevate ();
403 int fd = open (PREFIX"/log/passwd.log", O_CREAT | O_WRONLY | O_APPEND);
404 drop ();
405 write (fd, passwd_log.items, passwd_log.count);
406 close (fd);
407 DYNAMIC_ARRAY_RESET (passwd_log);
408 }
409}
410
411struct passwd_entry *
412lookup_login (struct passwd passwd, struct string_view login)
413{
414 for (struct passwd_entry *entry = passwd.items;
415 entry < passwd.items + passwd.count; ++entry) {
416 if (SVCMP (login, entry->login) != 0)
417 continue;
418
419 string_builder_printf (&passwd_log, "%u user '%.*s' (%d) was looked up\n",
420 time (NULL), SVFMT (entry->login), entry->id);
421
422 return entry;
423 }
424
425 string_builder_printf (&passwd_log, "%u user '%.*s' lookup failed\n",
426 time (NULL), SVFMT (login));
427
428 return NULL;
429}
430
431struct passwd_entry *
432lookup_id (struct passwd passwd, int id)
433{
434 for (struct passwd_entry *entry = passwd.items;
435 entry < passwd.items + passwd.count; ++entry) {
436 if (id != entry->id)
437 continue;
438
439 string_builder_printf (&passwd_log, "%u user %d was looked up\n",
440 time (NULL), id);
441
442 return entry;
443 }
444
445 string_builder_printf (&passwd_log, "%u user %d lookup failed\n",
446 time (NULL), id);
447
448 return NULL;
449}
450
451void
452elevate (void)
453{
454 if (euid != ruid) seteuid (euid);
455 if (egid != rgid) setegid (egid);
456}
457
458void
459drop (void)
460{
461 if (euid != ruid) seteuid (ruid);
462 if (egid != rgid) setegid (rgid);
463}
diff --git a/02/src/common.h b/02/src/common.h
new file mode 100644
index 0000000..0edc629
--- /dev/null
+++ b/02/src/common.h
@@ -0,0 +1,107 @@
1// common.h --- common functions
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#ifndef INCLUDED_COMMON_H
12#define INCLUDED_COMMON_H
13
14#include <stddef.h>
15#include <stdint.h>
16#include <stdio.h>
17#include <stdbool.h>
18
19#include <openssl/sha.h>
20
21#include "string-view.h"
22#include "string-builder.h"
23
24#define PREFIX "/usr/local/practice2"
25
26#define STRINGIFY(ARG) #ARG
27#define TO_STRING(ARG) STRINGIFY (ARG)
28
29#define DIE(FMT, ...) do { \
30 fprintf (stderr, "fatal: " FMT "\n" __VA_OPT__ (,) __VA_ARGS__); \
31 exit (EXIT_FAILURE); \
32 } while (0)
33
34#define LOGIN_MAX_LENGTH 32
35#define LOGIN_REGEX "[a-zA-Z][-_a-zA-Z0-9]*"
36
37#define COMMENT_MAX_LENGTH 256
38#define COMMENT_REGEX "[^:\n]*"
39
40#define PASSWORD_MAX_LENGTH 256
41#define PASSWORD_SALT_SIZE 12
42#define PASSWORD_SALT_LENGTH 16
43#define PASSWORD_HASH_LENGTH 27
44#define PASSWORD_ENCODED_LENGTH (3 + PASSWORD_SALT_LENGTH + 1 + PASSWORD_HASH_LENGTH)
45#define PASSWORD_REGEX "[a-zA-Z][a-zA-Z0-9!@#$%^&*()]*"
46
47extern struct string_builder passwd_log;
48
49extern uid_t ruid;
50extern gid_t rgid;
51extern uid_t euid;
52extern gid_t egid;
53
54struct passwd_entry {
55 struct string_view login;
56 struct string_view encoded_password;
57 int id;
58 enum access_rights {
59 AR_READ = 1 << 0,
60 AR_WRITE = 1 << 1,
61 AR_DELETE = 1 << 2,
62 } access_rights;
63 struct string_view comment;
64};
65
66struct passwd {
67 struct passwd_entry *items;
68 uint32_t count;
69 uint32_t capacity;
70 FILE *stream;
71};
72
73char encode6 (unsigned char b6);
74unsigned char decode6 (char c);
75void encode (char *into, const unsigned char* from, unsigned int size);
76void decode (unsigned char *into, struct string_view from);
77
78void generate_salt (unsigned char salt[PASSWORD_SALT_SIZE]);
79unsigned char *hash_password (unsigned char hash[SHA_DIGEST_LENGTH],
80 struct string_view password,
81 const unsigned char salt[PASSWORD_SALT_SIZE]);
82struct string_view encode_password (struct string_view password);
83bool check_password (struct string_view password,
84 struct string_view encoded_password);
85
86int fscan_passwd_entry (FILE *, struct passwd_entry *);
87void fprint_passwd_entry (FILE *, const struct passwd_entry *);
88struct passwd load_passwd_file (void);
89void save_passwd_file (struct passwd);
90void close_passwd_file (struct passwd);
91
92struct string_view read_password (void);
93struct string_view read_login (void);
94
95void append_passwd_log (void);
96
97struct passwd_entry *lookup_login (struct passwd, struct string_view login);
98struct passwd_entry *lookup_id (struct passwd, int id);
99
100struct passwd_entry *authenticate (struct passwd, struct string_view login, struct string_view password);
101
102void elevate (void);
103void drop (void);
104
105#endif // INCLUDED_COMMON_H
106
107// common.h ends here
diff --git a/02/src/cracking.c b/02/src/cracking.c
new file mode 100644
index 0000000..25afcb5
--- /dev/null
+++ b/02/src/cracking.c
@@ -0,0 +1,138 @@
1#include <pty.h>
2#include <termios.h>
3#include <sys/wait.h>
4
5#include "cracking.h"
6
7void
8password_bump (STRING_BUILDER sb)
9{
10 if ('A' <= sb->string[0] && sb->string[0] < 'Z' ||
11 'a' <= sb->string[0] && sb->string[0] < 'z') {
12 sb->string[0] += 1;
13 return;
14 }
15
16 if (sb->string[0] == 'Z') {
17 sb->string[0] = 'a';
18 return;
19 }
20
21 sb->string[0] = 'A';
22
23 size_t index = 1;
24
25again:
26 if (index == sb->length) {
27 STRING_BUILDER_APPEND_CHAR (*sb, '!');
28 return;
29 }
30
31 if ('0' <= sb->string[index] && sb->string[index] < '9' ||
32 'A' <= sb->string[index] && sb->string[index] < 'Z' ||
33 'a' <= sb->string[index] && sb->string[index] < 'z') {
34 sb->string[index] += 1;
35 return;
36 }
37
38 switch (sb->string[index]) {
39 case '!': sb->string[index] = '@'; return;
40 case '@': sb->string[index] = '#'; return;
41 case '#': sb->string[index] = '$'; return;
42 case '$': sb->string[index] = '%'; return;
43 case '%': sb->string[index] = '^'; return;
44 case '^': sb->string[index] = '&'; return;
45 case '&': sb->string[index] = '*'; return;
46 case '*': sb->string[index] = '('; return;
47 case '(': sb->string[index] = ')'; return;
48 case ')': sb->string[index] = '0'; return;
49
50 case '9': sb->string[index] = 'A'; return;
51 case 'Z': sb->string[index] = 'a'; return;
52 }
53
54 sb->string[index] = '!';
55
56 index += 1;
57 goto again;
58}
59
60bool
61test_credentials (struct shell shell,
62 struct string_view login,
63 struct string_view password)
64{
65 fprintf (shell.out, "%.*s\n%.*s\n", SVFMT (login), SVFMT (password));
66 for (;;) {
67 int c = getc (shell.in);
68 if (c == '\n')
69 break;
70 }
71 int c = getc (shell.in);
72 if (c == 'H')
73 return true;
74
75 ungetc (c, shell.in);
76 return false;
77}
78
79struct shell
80spawn_shell (void)
81{
82 struct shell shell;
83
84 int fd_master;
85 int fd_slave;
86
87 if (openpty (&fd_master, &fd_slave, NULL, NULL, NULL) == -1) {
88 perror ("openpty");
89 exit (EXIT_FAILURE);
90 }
91
92 shell.pid = fork ();
93 if (shell.pid == -1) {
94 perror ("fork");
95 exit (EXIT_FAILURE);
96 }
97
98 if (shell.pid == 0) {
99 close (fd_master);
100
101 if (dup2 (fd_slave, STDIN_FILENO) == -1) {
102 perror ("dup2 stdin");
103 _exit (1);
104 }
105
106 if (dup2 (fd_slave, STDOUT_FILENO) == -1) {
107 perror ("dup2 stdout");
108 _exit (1);
109 }
110
111 close (fd_slave);
112 close (STDERR_FILENO);
113
114 struct termios term;
115 tcgetattr (STDIN_FILENO, &term);
116 term.c_lflag &= ~ECHO;
117 tcsetattr (STDIN_FILENO, 0, &term);
118
119 execlp ("shell", "shell", NULL);
120 perror ("execlp");
121 _exit (1);
122 }
123
124 close (fd_slave);
125
126 shell.out = fdopen (fd_master, "w");
127 shell.in = fdopen (fd_master, "r");
128
129 return shell;
130}
131
132void
133close_shell (struct shell shell)
134{
135 fclose (shell.in);
136 fclose (shell.out);
137 waitpid (shell.pid, NULL, 0);
138}
diff --git a/02/src/cracking.h b/02/src/cracking.h
new file mode 100644
index 0000000..0173dbb
--- /dev/null
+++ b/02/src/cracking.h
@@ -0,0 +1,35 @@
1/// src/cracking.h --- password cracking utilities
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7/// Commentary:
8//
9/// Code:
10
11#ifndef INCLUDED_CRACKING_H
12#define INCLUDED_CRACKING_H
13
14#include <stdio.h>
15#include <unistd.h>
16
17#include "string-builder.h"
18#include "string-view.h"
19
20struct shell {
21 FILE *in;
22 FILE *out;
23 pid_t pid;
24};
25
26void password_bump (STRING_BUILDER);
27bool test_credentials (struct shell,
28 struct string_view login,
29 struct string_view password);
30struct shell spawn_shell (void);
31void close_shell (struct shell);
32
33#endif // INCLUDED_CRACKING_H
34
35/// src/cracking.h ends here
diff --git a/02/src/dynamic-array.h b/02/src/dynamic-array.h
new file mode 100644
index 0000000..ed5cb32
--- /dev/null
+++ b/02/src/dynamic-array.h
@@ -0,0 +1,68 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include <stdlib.h>
5#include <assert.h>
6
7#define MALLOC malloc
8#define REALLOC realloc
9#define FREE free
10#define ASSERT assert
11
12#ifndef DYNAMIC_ARRAY_INIT_CAP
13#define DYNAMIC_ARRAY_INIT_CAP 256
14#endif
15
16#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
17 ({ \
18 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
19 if ((DYNAMIC_ARRAY).capacity == 0) \
20 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
21 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
22 (DYNAMIC_ARRAY).capacity *= 2; \
23 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
24 (DYNAMIC_ARRAY).capacity * \
25 sizeof (*(DYNAMIC_ARRAY).items)); \
26 ASSERT((DYNAMIC_ARRAY).items); \
27 } \
28 })
29
30#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
31 ({ \
32 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
33 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
34 (DYNAMIC_ARRAY).capacity * \
35 sizeof (*(DYNAMIC_ARRAY).items)); \
36 ASSERT((DYNAMIC_ARRAY).items); \
37 \
38 })
39
40#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
43 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
44 })
45
46#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
47 ({ \
48 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
49 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
50 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
51 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
52 })
53
54#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \
55 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1]
56
57#define DYNAMIC_ARRAY_POP(DYNAMIC_ARRAY) \
58 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count--]
59
60#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
61
62#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
63
64#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
65 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
66 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
67
68#endif
diff --git a/02/src/measure.c b/02/src/measure.c
new file mode 100644
index 0000000..72633bc
--- /dev/null
+++ b/02/src/measure.c
@@ -0,0 +1,70 @@
1// src/measure.c --- utility to measure time to bruteforce
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 <stddef.h>
12#include <time.h>
13#include <math.h>
14
15#include "cracking.h"
16
17int
18main (int argc, char *argv[])
19{
20 if (argc != 2) {
21 fprintf (stderr, "Usage: %s LOGIN\n", argv[0]);
22 fprintf (stderr, "Note: LOGIN shouldn't have password of length 3 or 4\n");
23 exit (EXIT_FAILURE);
24 }
25
26 struct shell shell = spawn_shell ();
27 clock_t start, end;
28
29 struct string_view login = SVCSTR (argv[1]);
30 struct string_builder password = {0};
31 STRING_BUILDER_APPEND_STRING_VIEW (password, SVCSTR ("A!!"));
32
33 start = clock();
34 while (password.length == 3) {
35 test_credentials (shell, login, SVSB (password));
36 password_bump (&password);
37 } end = clock();
38 double time3 = (end - start) /(double) CLOCKS_PER_SEC;
39
40 double per_try3 = time3/(52*72*72);
41 double time4_expected = per_try3*(52*pow (72, 3));
42 printf ("Tried all 3 letter passwords in: %fs\n", time3);
43 printf ("Expected time to try all 4 letter passwords: %f min\n", time4_expected/60);
44
45 start = clock();
46 while (password.length == 4) {
47 test_credentials (shell, login, SVSB (password));
48 password_bump (&password);
49 } end = clock();
50 double time4 = (end - start) /(double) CLOCKS_PER_SEC;
51
52 double per_try4 = time4/(52*72*72*72);
53 double per_try = (per_try3 + per_try4)/2;
54
55 double time5 = per_try*(52*pow (72, 4));
56 double time6 = per_try*(52*pow (72, 5));
57 double time7 = per_try*(52*pow (72, 6));
58 double time8 = per_try*(52*pow (72, 7));
59
60 printf ("Real time to try 3 letter passwords: %fs\n", time3);
61 printf ("Real time to try 4 letter passwords: %fs\n", time4);
62 printf ("Estimated time to try 5 letter passwords: %fs\n", time5);
63 printf ("Estimated time to try 6 letter passwords: %fs\n", time6);
64 printf ("Estimated time to try 7 letter passwords: %fs\n", time7);
65 printf ("Estimated time to try 8 letter passwords: %fs\n", time8);
66
67 return EXIT_SUCCESS;
68}
69
70// src/measure.c ends here
diff --git a/02/src/passwdctl.c b/02/src/passwdctl.c
new file mode 100644
index 0000000..f0ab1a8
--- /dev/null
+++ b/02/src/passwdctl.c
@@ -0,0 +1,493 @@
1// src/passwdctl.c --- utility to manage access to protected directory
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 <stdbool.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#include <assert.h>
16#include <getopt.h>
17#include <regex.h>
18#include <unistd.h>
19
20#include <openssl/evp.h>
21#include <openssl/err.h>
22
23#include "dynamic-array.h"
24#include "string-builder.h"
25#include "string-view.h"
26#include "common.h"
27
28#define SUBCOMMANDS() \
29 X (ADD, "add") \
30 X (MODIFY, "mod") \
31 X (DELETE, "del")
32
33#define X(SYM, STR) SUBCOMMAND_##SYM,
34enum subcommand {
35 SUBCOMMANDS ()
36};
37#undef X
38
39#define X(SYM, STR) [SUBCOMMAND_##SYM] = STR,
40char *const subcommand_tokens[] = {
41 SUBCOMMANDS ()
42 NULL
43};
44#undef X
45
46regex_t login_regex;
47regex_t comment_regex;
48regex_t password_regex;
49
50struct string_view
51parse_password (struct string_view sv)
52{
53 if (regexec (&password_regex, sv.begin, 0, NULL, 0) != 0)
54 DIE ("password doesn't match regex %s", PASSWORD_REGEX);
55
56 return sv;
57}
58
59int
60parse_id (const char *cstr)
61{
62 int id;
63 size_t read;
64 sscanf (cstr, "%d%ln", &id, &read);
65
66 if (id < 0) DIE ("invalid id");
67 if (read != strlen (cstr)) DIE ("invalid id");
68
69 return id;
70}
71
72enum access_rights
73parse_access_right (const char *cstr)
74{
75 enum access_rights ar = 0;
76
77 while (*cstr) {
78 switch (*cstr++) {
79 case 'r': ar |= AR_READ; break;
80 case 'w': ar |= AR_WRITE; break;
81 case 'd': ar |= AR_DELETE; break;
82 default: DIE ("invalid access right: %c", cstr[-1]);
83 }
84 }
85
86 return ar;
87}
88
89struct string_view
90parse_comment (const char *cstr)
91{
92 struct string_view sv = SVCSTR (cstr);
93
94 if (SVLEN (sv) > COMMENT_MAX_LENGTH)
95 DIE ("comment too long");
96
97 if (regexec (&comment_regex, cstr, 0, NULL, 0) != 0)
98 DIE ("comment doesn't match regex " COMMENT_REGEX);
99
100 return sv;
101}
102
103struct string_view
104parse_login (const char *cstr)
105{
106 struct string_view sv = SVCSTR (cstr);
107
108 if (SVLEN (sv) > LOGIN_MAX_LENGTH)
109 DIE ("login too long");
110
111 if (regexec (&login_regex, cstr, 0, NULL, 0) != 0)
112 DIE ("login doesn't match regex " LOGIN_REGEX);
113
114 return sv;
115}
116
117const char *
118regex_error (const regex_t *comp, int errcode)
119{
120 static char *error = NULL;
121 size_t size = regerror (errcode, comp, NULL, 0);
122 error = realloc (error, size);
123 regerror (errcode, comp, error, size);
124 return error;
125}
126
127void
128usage (const char *progname)
129{
130 printf ("Usage: %s [options] COMMAND [ARGS]\n", progname);
131 puts ("");
132 puts ("Options:");
133 puts (" -h, --help display this help message and exit");
134 puts ("");
135 puts ("Commands:");
136 puts (" add LOGIN add new account");
137 puts (" mod LOGIN modify existing account");
138 puts (" del LOGIN delete account");
139 puts ("");
140}
141
142void
143usage_add (const char *progname)
144{
145 printf ("Usage: %s add [options] LOGIN\n", progname);
146 puts ("");
147 puts ("Options:");
148 puts (" -h, --help display this help message and exit");
149 puts (" -p, --password PASSWORD password of the new account");
150 puts (" -i, --id ID ID of the new account");
151 puts (" -a, --access-rights {r|w|d}... access right of the new account");
152 puts (" -c, --comment COMMENT comment of the new account");
153 puts ("");
154}
155
156void
157usage_mod (const char *progname)
158{
159 printf ("Usage: %s mod [options] LOGIN\n", progname);
160 puts ("");
161 puts ("Options:");
162 puts (" -h, --help display this help message and exit");
163 puts (" -l, --login NEW_LOGIN new login for the account");
164 puts (" -p, --password PASSWORD new password for the account");
165 puts (" -P prompt for new password for the account");
166 puts (" -i, --id ID new ID for the account");
167 puts (" -a, --access-rights {r|w|d}... new access rights for the account");
168 puts (" -c, --comment COMMENT new comment for the account");
169 puts ("");
170}
171
172void
173usage_del (const char *progname)
174{
175 printf ("Usage: %s del [options] LOGIN\n", progname);
176 puts ("");
177 puts ("Options:");
178 puts (" -h, --help display this help message and exit");
179 puts ("");
180}
181
182int
183main (int argc, char *argv[])
184{
185 ruid = getuid ();
186 euid = geteuid ();
187 seteuid (ruid);
188
189 ERR_load_crypto_strings ();
190
191 const char *progname = argv[0];
192 if (progname == NULL)
193 DIE ("unable to get program name");
194
195 char **subcommand = &argv[1];
196 if (*subcommand == NULL) {
197 usage (progname);
198 exit (1);
199 }
200
201 int errcode;
202 errcode = regcomp (&login_regex, "^" LOGIN_REGEX "$", REG_NOSUB);
203 if (errcode != 0) {
204 DIE ("unable to compile login regex: %s",
205 regex_error (&login_regex, errcode));
206 }
207
208 errcode = regcomp (&password_regex, "^" PASSWORD_REGEX "$", REG_NOSUB);
209 if (errcode != 0) {
210 DIE ("unable to compile password regex: %s",
211 regex_error (&password_regex, errcode));
212 }
213
214 errcode = regcomp (&comment_regex, "^" COMMENT_REGEX "$", REG_NOSUB);
215 if (errcode != 0) {
216 DIE ("unable to compile comment regex: %s",
217 regex_error (&comment_regex, errcode));
218 }
219
220 char *value;
221 switch (getsubopt (subcommand, subcommand_tokens, &value)) {
222 case SUBCOMMAND_ADD: {
223 static struct option longopts[] = {
224 { "help", no_argument, NULL, 'h' },
225 { "password", required_argument, NULL, 'p' },
226 { "id", required_argument, NULL, 'i' },
227 { "access-rights", required_argument, NULL, 'a' },
228 { "comment", required_argument, NULL, 'c' },
229 {0}
230 };
231 char ch;
232 struct passwd_entry new_entry = { .id = -1 };
233 optind = 2;
234 while ((ch = getopt_long (argc, argv, ":hp:i:a:c:", longopts, NULL)) != -1) {
235 switch (ch) {
236 case 'h':
237 usage_add (progname);
238 exit (0);
239 case 'p':
240 new_entry.encoded_password =
241 SVDUP (encode_password (parse_password (SVCSTR (optarg))));
242 break;
243 case 'i': new_entry.id = parse_id (optarg); break;
244 case 'a': new_entry.access_rights = parse_access_right (optarg); break;
245 case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break;
246 case '?': DIE ("unknown option -%c", optopt);
247 case ':': DIE ("missing argument for %s", argv[optind - 1]);
248 default: DIE ("unexpected opt error");
249 }
250 }
251
252 if (argv[optind] == NULL) {
253 fprintf (stderr, "error: no login provided\n");
254 usage_add (progname);
255 exit (1);
256 }
257
258 if (argv[optind + 1] != NULL)
259 DIE ("extra trailing arguments starting with: %s", argv[optind + 1]);
260
261 if (getuid () != 0)
262 DIE ("permission denied");
263
264 new_entry.login = SVDUP (SVCSTR (argv[optind]));
265
266 if (new_entry.encoded_password.begin == NULL) {
267 fputs ("Password: ", stdout);
268 struct string_view password = duplicate_string_view_as_cstr (parse_password (read_password ()));
269 fputs ("Repeat password: ", stdout);
270 struct string_view repeated = read_password ();
271 if (string_view_compare (password, repeated) != 0)
272 DIE ("passwords don't match");
273
274 new_entry.encoded_password = SVDUP (encode_password (password));
275 }
276
277 struct passwd passwd = load_passwd_file ();
278
279 int max_id = -1;
280 for (struct passwd_entry *entry = passwd.items;
281 entry < passwd.items + passwd.count; ++entry) {
282 if (SVCMP (new_entry.login, entry->login) == 0)
283 DIE ("user %.*s already exists", SVFMT (entry->login));
284 if (new_entry.id == entry->id)
285 DIE ("user with id %d already exists", entry->id);
286 if (entry->id > max_id)
287 max_id = entry->id;
288 }
289
290 if (new_entry.id < 0)
291 new_entry.id = max_id + 1;
292
293 DYNAMIC_ARRAY_APPEND (passwd, new_entry);
294 save_passwd_file (passwd);
295
296 string_builder_printf (&passwd_log, "%u added user %.*s %d",
297 time (NULL), SVFMT (new_entry.login), new_entry.id);
298 if (new_entry.comment.begin)
299 string_builder_printf (&passwd_log, " (%.*s)", SVFMT (new_entry.comment));
300 string_builder_printf (&passwd_log, " with access rights %c%c%c\n",
301 new_entry.access_rights & AR_READ ? 'r' : '-',
302 new_entry.access_rights & AR_WRITE ? 'w' : '-',
303 new_entry.access_rights & AR_DELETE ? 'd' : '-');
304
305 close_passwd_file (passwd);
306 } break;
307
308 case SUBCOMMAND_MODIFY: { // [-p --password=] [-i -id=] [-c --comment=] login
309 static struct option longopts[] = {
310 { "help", no_argument, NULL, 'h' },
311 { "login", required_argument, NULL, 'l' },
312 { "password", required_argument, NULL, 'p' },
313 { "id", required_argument, NULL, 'i' },
314 { "access-rights", required_argument, NULL, 'a' },
315 { "comment", required_argument, NULL, 'c' },
316 {0}
317 };
318 char ch;
319 struct passwd_entry new_entry = { .id = -1 };
320 bool prompt_for_new_password = false;
321 optind = 2;
322 while ((ch = getopt_long (argc, argv, ":hl:p:Pi:a:c:", longopts, NULL)) != -1) {
323 switch (ch) {
324 case 'h':
325 usage_mod (progname);
326 exit (0);
327 case 'l': new_entry.login = SVDUP (parse_login (optarg)); break;
328 case 'p':
329 new_entry.encoded_password =
330 SVDUP (encode_password (parse_password (SVCSTR (optarg))));
331 break;
332 case 'P': prompt_for_new_password = true; break;
333 case 'i': new_entry.id = parse_id (optarg); break;
334 case 'a': new_entry.access_rights = parse_access_right (optarg); break;
335 case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break;
336 case '?': DIE ("unknown option -%c", optopt);
337 case ':': DIE ("missing argument for %s", argv[optind - 1]);
338 default: DIE ("unexpected opt error");
339 }
340 }
341
342 if (argv[optind] == NULL) {
343 fprintf (stderr, "error: no login provided\n");
344 usage_mod (progname);
345 exit (1);
346 }
347
348 if (argv[optind + 1] != NULL)
349 DIE ("extra trailing arguments starting with: %s", argv[optind + 1]);
350
351 struct string_view login = SVCSTR (argv[optind]);
352 struct passwd_entry *entry;
353
354 struct passwd passwd = load_passwd_file ();
355
356 if (getuid () == 0) {
357 entry = lookup_login (passwd, login);
358 if (!entry)
359 DIE ("user %.*s not found", SVFMT (login));
360
361 string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:",
362 time (NULL), SVFMT (entry->login), entry->id);
363
364 if (new_entry.id != -1) {
365 if (lookup_id (passwd, new_entry.id))
366 DIE ("user with id %d already exists", new_entry.id);
367 entry->id = new_entry.id;
368 string_builder_printf (&passwd_log, " new id %d,", entry->id);
369 }
370
371 if (new_entry.access_rights != 0) {
372 entry->access_rights = new_entry.access_rights;
373 string_builder_printf (&passwd_log, " new access rights %c%c%c,",
374 entry->access_rights & AR_READ ? 'r' : '-',
375 entry->access_rights & AR_WRITE ? 'w' : '-',
376 entry->access_rights & AR_DELETE ? 'd' : '-');
377 }
378 } else {
379 if (new_entry.id != -1)
380 DIE ("permission to change id denied");
381 if (new_entry.access_rights != 0)
382 DIE ("permission to change access rights denied");
383
384 fputs ("Password: ", stdout);
385 struct string_view password = parse_password (read_password ());
386 entry = authenticate (passwd, login, password);
387 if (!entry) exit (1);
388 string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:",
389 time (NULL), SVFMT (entry->login), entry->id);
390 }
391
392
393 if (prompt_for_new_password) {
394 fputs ("New password: ", stdout);
395 struct string_view password = SVDUP (parse_password (read_password ()));
396 fputs ("Repeat password: ", stdout);
397 struct string_view repeated = read_password ();
398 if (string_view_compare (password, repeated) != 0)
399 DIE ("passwords don't match");
400 entry->encoded_password = SVDUP (encode_password (password));
401 string_builder_printf (&passwd_log, " changed password,");
402 } else if (new_entry.encoded_password.begin != NULL) {
403 entry->encoded_password = new_entry.encoded_password;
404 string_builder_printf (&passwd_log, " changed password,");
405 }
406
407 if (new_entry.comment.begin != NULL) {
408 entry->comment = new_entry.comment;
409 string_builder_printf (&passwd_log, " new comment `%.*s',", SVFMT (entry->comment));
410 }
411
412 if (new_entry.login.begin != NULL) {
413 entry->login = new_entry.login;
414 string_builder_printf (&passwd_log, " new login %.*s,", SVFMT (entry->login));
415 }
416
417 if (DYNAMIC_ARRAY_LAST (passwd_log) != ',')
418 DIE ("no modifications supplied");
419 DYNAMIC_ARRAY_LAST (passwd_log) = '\n';
420
421 save_passwd_file (passwd);
422 close_passwd_file (passwd);
423 } break;
424
425 case SUBCOMMAND_DELETE: { // login
426 static struct option longopts[] = {
427 { "help", no_argument, NULL, 'h' },
428 {0}
429 };
430
431 char ch;
432 optind = 2;
433 while ((ch = getopt_long (argc, argv, ":h", longopts, NULL)) != -1) {
434 switch (ch) {
435 case 'h':
436 usage_del (progname);
437 exit (0);
438 case '?': DIE ("unknown option -%c", optopt);
439 case ':': DIE ("missing argument for %s", argv[optind - 1]);
440 default: DIE ("unexpected opt error");
441 }
442 }
443
444 if (argv[optind] == NULL) {
445 fprintf (stderr, "error: no login provided\n");
446 usage_del (progname);
447 exit (1);
448 }
449
450 if (argv[optind + 1] != NULL)
451 DIE ("extra trailing arguments starting with: %s", argv[optind + 1]);
452
453 if (getuid () != 0)
454 DIE ("permission denied");
455
456 struct string_view login = SVDUP (SVCSTR (argv[optind]));
457 struct passwd passwd = load_passwd_file ();
458
459 struct passwd_entry *entry;
460 for (entry = passwd.items; entry < passwd.items + passwd.count; ++entry) {
461 if (SVCMP (login, entry->login) == 0)
462 break;
463 }
464
465 if (entry == passwd.items + passwd.count)
466 DIE ("user %.*s doesn't exist", SVFMT (login));
467
468 string_builder_printf (&passwd_log, "%u deleted user %.*s with id %d",
469 time (NULL), SVFMT (entry->login), entry->id);
470 if (entry->comment.begin)
471 string_builder_printf (&passwd_log, " (%.*s)", SVFMT (entry->comment));
472 DYNAMIC_ARRAY_APPEND (passwd_log, '\n');
473
474 if (entry + 1 != passwd.items + passwd.count) {
475 memmove (entry, entry + 1,
476 (passwd.count - (entry + 1 - passwd.items))*sizeof (*entry));
477 } passwd.count -= 1;
478
479 save_passwd_file (passwd);
480 close_passwd_file (passwd);
481 } break;
482
483 default:
484 usage (progname);
485 exit (strcmp (value, "-h") != 0 && strcmp (value, "--help") != 0);
486 }
487
488 append_passwd_log ();
489
490 return EXIT_SUCCESS;
491}
492
493// src/passwdctl.c ends here
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
diff --git a/02/src/string-builder.c b/02/src/string-builder.c
new file mode 100644
index 0000000..9e70d10
--- /dev/null
+++ b/02/src/string-builder.c
@@ -0,0 +1,58 @@
1#include "string-builder.h"
2#include <stdarg.h>
3#include <stdio.h>
4
5void
6string_builder_append_ntimes (STRING_BUILDER sb, char c, size_t n)
7{
8 DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, n);
9 memset (sb->items + sb->count, c, n);
10 sb->count += n;
11}
12
13void
14string_builder_append_cstrs (STRING_BUILDER sb, ...)
15{
16 va_list args;
17
18 va_start (args, sb);
19 const char *arg = va_arg (args, const char *);
20 while (arg) {
21 STRING_BUILDER_APPEND_CSTR(*sb, arg);
22 arg = va_arg (args, const char *);
23 } va_end (args);
24}
25
26void
27string_builder_printf (STRING_BUILDER sb, const char *format, ...)
28{
29 va_list args;
30
31 va_start (args, format);
32 int size = vsnprintf (NULL, 0, format, args);
33 va_end (args);
34 ASSERT (size >= 0);
35
36 DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, size + 1);
37 va_start (args, format);
38 vsnprintf (&sb->items[sb->count], size + 1, format, args);
39 va_end (args);
40 sb->count += size;
41}
42
43bool
44string_builder_getline (STRING_BUILDER sb)
45{
46 for (;;) {
47 int c = getchar ();
48
49 if (c == EOF)
50 return false;
51 if (c == '\n')
52 break;
53
54 STRING_BUILDER_APPEND_CHAR (*sb, c);
55 }
56
57 return true;
58}
diff --git a/02/src/string-builder.h b/02/src/string-builder.h
new file mode 100644
index 0000000..18367da
--- /dev/null
+++ b/02/src/string-builder.h
@@ -0,0 +1,56 @@
1#ifndef INCLUDED_STRING_BUILDER_H
2#define INCLUDED_STRING_BUILDER_H
3
4#include <stddef.h>
5#include <string.h>
6#include <stdbool.h>
7#include "dynamic-array.h"
8
9struct string_builder {
10 union { char *items, *string; };
11 union { size_t count, length; };
12 size_t capacity;
13};
14#define STRING_BUILDER struct string_builder *
15
16#define SBFMT(SB) (int) (SB).length, (SB).string
17
18#define STRING_BUILDER_APPEND_CHAR(SB, CHAR) \
19 DYNAMIC_ARRAY_APPEND (SB, (char) CHAR)
20
21#define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE) \
22 DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE)
23
24#define STRING_BUILDER_APPEND_CSTR(SB, CSTR) \
25 ({ \
26 const char *s = (CSTR); \
27 size_t n = strlen (s); \
28 DYNAMIC_ARRAY_APPEND_MANY(SB, s, n); \
29 })
30
31#define STRING_BUILDER_APPEND_CSTRS(SB, ...) \
32 string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL)
33
34#define STRING_BUILDER_APPEND_STRING_VIEW(SB, SV) \
35 DYNAMIC_ARRAY_APPEND_MANY(SB, (SV).begin, SVLEN (SV));
36
37#define STRING_BUILDER_APPEND_NULL(SB) \
38 DYNAMIC_ARRAY_APPEND (SB, '\0')
39
40#define STRING_BUILDER_TERMINATE(SB) ({ \
41 DYNAMIC_ARRAY_ENSURE_CAPACITY (SB, 1); \
42 (SB).string[(SB).length] = '\0'; \
43 })
44
45#define STRING_BUILDER_RESET(SB) \
46 DYNAMIC_ARRAY_RESET (SB)
47
48#define STRING_BUILDER_FREE(SB) \
49 DYNAMIC_ARRAY_FREE(SB)
50
51void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n);
52void string_builder_append_cstrs (STRING_BUILDER, ...);
53void string_builder_printf (STRING_BUILDER, const char *format, ...);
54bool string_builder_getline (STRING_BUILDER);
55
56#endif
diff --git a/02/src/string-view.c b/02/src/string-view.c
new file mode 100644
index 0000000..ef84f69
--- /dev/null
+++ b/02/src/string-view.c
@@ -0,0 +1,147 @@
1#include "string-view.h"
2#include <string.h>
3#include <stdlib.h>
4
5size_t
6string_view_length (struct string_view sv)
7{
8 return sv.end - sv.begin;
9}
10
11struct string_view
12string_view_from_cstr (const char *cstr)
13{
14 return (struct string_view) {
15 .begin = cstr,
16 .end = cstr + strlen (cstr),
17 };
18}
19
20struct string_view
21duplicate_string_view (struct string_view sv)
22{
23 size_t len = SVLEN (sv);
24
25 struct string_view result = {
26 .begin = malloc (len),
27 };
28 result.end = result.begin + len;
29
30 memcpy ((void *) result.begin, sv.begin, len);
31
32 return result;
33}
34
35struct string_view
36duplicate_string_view_as_cstr (struct string_view sv)
37{
38 size_t len = SVLEN (sv);
39
40 struct string_view result = {
41 .begin = malloc (len + 1),
42 };
43 result.end = result.begin + len;
44
45 memcpy ((void *) result.begin, sv.begin, len);
46 ((char *) result.begin)[len] = '\0';
47
48 return result;
49}
50
51struct string_view
52string_view_strdup (const char *cstr)
53{
54 struct string_view sv;
55 size_t len = strlen (cstr);
56 sv.begin = malloc (len + 1),
57 sv.end = sv.begin + len;
58
59 memcpy ((void *) sv.begin, cstr, len);
60 ((char *) sv.begin)[len] = '\0';
61
62 return sv;
63}
64
65int
66string_view_compare (struct string_view lhs, struct string_view rhs)
67{
68 if (SVLEN (lhs) != SVLEN (rhs))
69 return SVLEN (lhs) - SVLEN (rhs);
70
71 return memcmp (lhs.begin, rhs.begin, SVLEN (lhs));
72}
73
74bool
75string_view_starts_with (struct string_view sv, struct string_view prefix)
76{
77 if (SVLEN (sv) < SVLEN (prefix))
78 return false;
79
80 return memcmp (sv.begin, prefix.begin, SVLEN (prefix)) == 0;
81}
82
83struct string_view
84string_view_dirname (struct string_view sv)
85{
86 while (sv.end != sv.begin && sv.end[-1] == '/')
87 sv.end -= 1;
88
89 while (sv.end != sv.begin && sv.end[-1] != '/')
90 sv.end -= 1;
91
92 while (sv.end != sv.begin && sv.end[-1] == '/')
93 sv.end -= 1;
94
95 if (sv.end == sv.begin)
96 return SVCSTR (".");
97
98 return sv;
99}
100
101struct string_view
102string_view_basename (struct string_view sv)
103{
104 const char *head = sv.end;
105
106 while (head > sv.begin && head[-1] == '/')
107 head -= 1;
108
109 while (head > sv.begin && head[-1] != '/')
110 head -= 1;
111
112 if (head != sv.begin)
113 sv.begin = head;
114
115 return sv;
116}
117
118// pops all if c was not found
119struct string_view
120string_view_pop_up_to (struct string_view *sv, char c)
121{
122 const char *head = sv->begin;
123
124 while (head < sv->end && *head != c)
125 head += 1;
126
127 struct string_view result = { .begin = sv->begin };
128 result.end = sv->begin = head;
129
130 return result;
131}
132
133struct string_view
134string_view_pop_n (struct string_view *sv, size_t n)
135{
136 struct string_view result = {
137 .begin = sv->begin,
138 .end = sv->begin + n,
139 };
140
141 if (result.end > sv->end)
142 result.end = sv->end;
143
144 sv->begin = result.end;
145
146 return result;
147}
diff --git a/02/src/string-view.h b/02/src/string-view.h
new file mode 100644
index 0000000..fa42d77
--- /dev/null
+++ b/02/src/string-view.h
@@ -0,0 +1,46 @@
1// src/string-view.h
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// Commentary:
8//
9// Code:
10
11#ifndef INCLUDED_STRING_VIEW_H
12#define INCLUDED_STRING_VIEW_H
13
14#include <stddef.h>
15#include <stdbool.h>
16
17struct string_view {
18 const char *begin;
19 const char *end;
20};
21
22#define SVNULL ((struct string_view) {0})
23#define SVLEN string_view_length
24#define SVFMT(SV) (int) SVLEN (SV), (SV).begin
25#define SVCSTR string_view_from_cstr
26#define SVDUP duplicate_string_view
27#define SVDUP0 duplicate_string_view_as_cstr
28#define SVSTRDUP string_view_strdup
29#define SVCMP string_view_compare
30#define SVSB(SB) ((struct string_view) { (SB).string, (SB).string + (SB).length })
31
32size_t string_view_length (struct string_view sv);
33struct string_view string_view_from_cstr (const char *cstr);
34struct string_view duplicate_string_view (struct string_view sv);
35struct string_view duplicate_string_view_as_cstr (struct string_view sv);
36struct string_view string_view_strdup (const char *cstr);
37int string_view_compare (struct string_view lhs, struct string_view rhs);
38bool string_view_starts_with (struct string_view sv, struct string_view prefix);
39struct string_view string_view_dirname (struct string_view);
40struct string_view string_view_basename (struct string_view);
41struct string_view string_view_pop_up_to (struct string_view *, char);
42struct string_view string_view_pop_n (struct string_view *, size_t n);
43
44#endif // INCLUDED_STRING_VIEW_H
45
46// src/string-view.h ends here