omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / src / omega_path_check.h
| 1 | /* SPDX-License-Identifier: Apache-2.0 |
| 2 | * Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | * |
| 4 | * omega_path_check.h: a checked copy of a file system path that came from outside the program (an |
| 5 | * environment variable, a command's output, a caller's argument) before anything opens it. |
| 6 | * |
| 7 | * A path is accepted only when it is 1..cap-1 bytes long, every byte is in the POSIX portable file name set |
| 8 | * [A-Za-z0-9._-] or one of / + , = @ : ~ (no space, quote, control, shell or non-ASCII byte), and no |
| 9 | * component is "..". Absolute and relative paths are both accepted. The accepted path is copied byte by byte |
| 10 | * through omega_path_byte, so the bytes the caller later opens are exactly the bytes that were checked. |
| 11 | * A refused path leaves out as the empty string. |
| 12 | */ |
| 13 | #ifndef OMEGA_PATH_CHECK_H |
| 14 | #define OMEGA_PATH_CHECK_H |
| 15 | |
| 16 | #include <stddef.h> |
| 17 | |
| 18 | /* c when it may appear in a checked path, -1 otherwise */ |
| 19 | static inline int omega_path_byte(int c) { |
| 20 | if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) return c; |
| 21 | switch (c) { |
| 22 | case '.': case '_': case '-': case '/': case '+': case ',': case '=': case '@': case ':': case '~': |
| 23 | return c; |
| 24 | default: |
| 25 | return -1; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | /* 0 with out = in when in is an acceptable path shorter than cap; -1 with out = "" otherwise */ |
| 30 | static inline int omega_path_copy(char *out, size_t cap, const char *in) { |
| 31 | if (!out || cap == 0) return -1; |
| 32 | out[0] = '\0'; |
| 33 | if (!in || !in[0]) return -1; |
| 34 | size_t k = 0; |
| 35 | for (; in[k]; k++) { |
| 36 | int b = omega_path_byte((unsigned char)in[k]); |
| 37 | if (b < 0 || k + 1 >= cap) { |
| 38 | out[0] = '\0'; |
| 39 | return -1; |
| 40 | } |
| 41 | out[k] = (char)b; |
| 42 | } |
| 43 | out[k] = '\0'; |
| 44 | for (size_t i = 0; i < k;) { |
| 45 | size_t j = i; |
| 46 | while (j < k && out[j] != '/') j++; |
| 47 | if (j - i == 2 && out[i] == '.' && out[i + 1] == '.') { |
| 48 | out[0] = '\0'; |
| 49 | return -1; |
| 50 | } |
| 51 | i = j + 1; |
| 52 | } |
| 53 | return 0; |
| 54 | } |
| 55 | |
| 56 | #endif /* OMEGA_PATH_CHECK_H */ |