// common.h --- common functions // // Copyright (c) 2026 Martin Michalec // // SPDX-License-Identifier: MIT // // Commentary: // // Code: #ifndef INCLUDED_COMMON_H #define INCLUDED_COMMON_H #include #include #include #include #include #include "string-view.h" #include "string-builder.h" #define PREFIX "/usr/local/practice3" #define STRINGIFY(ARG) #ARG #define TO_STRING(ARG) STRINGIFY (ARG) #define DIE(FMT, ...) do { \ fprintf (stderr, "fatal: " FMT "\n", ## __VA_ARGS__); \ exit (EXIT_FAILURE); \ } while (0) #define LOGIN_MAX_LENGTH 32 #define LOGIN_REGEX "[a-zA-Z][-_a-zA-Z0-9]*" #define COMMENT_MAX_LENGTH 256 #define COMMENT_REGEX "[^:\n]*" #define PASSWORD_MAX_LENGTH 256 #define PASSWORD_SALT_SIZE 12 #define PASSWORD_SALT_LENGTH 16 #define PASSWORD_HASH_LENGTH 27 #define PASSWORD_ENCODED_LENGTH (3 + PASSWORD_SALT_LENGTH + 1 + PASSWORD_HASH_LENGTH) #define PASSWORD_REGEX "[a-zA-Z][a-zA-Z0-9!@#$%^&*()]*" extern struct string_builder passwd_log; extern uid_t ruid; extern gid_t rgid; extern uid_t euid; extern gid_t egid; enum access_rights { AR_READ = 1 << 0, AR_WRITE = 1 << 1, AR_DELETE = 1 << 2, }; enum security_level { SL_TOP_SECRET, SL_SECRET, SL_CONFIDENTIAL, SL_UNCLASSIFIED, SL_COUNT }; extern const char *security_level_names[SL_COUNT]; struct passwd_entry { struct string_view login; struct string_view encoded_password; enum security_level security_level; int id; struct string_view comment; }; struct passwd { struct passwd_entry *items; uint32_t count; uint32_t capacity; FILE *stream; }; char encode6 (unsigned char b6); unsigned char decode6 (char c); void encode (char *into, const unsigned char* from, unsigned int size); void decode (unsigned char *into, struct string_view from); void generate_salt (unsigned char salt[PASSWORD_SALT_SIZE]); unsigned char *hash_password (unsigned char hash[SHA_DIGEST_LENGTH], struct string_view password, const unsigned char salt[PASSWORD_SALT_SIZE]); struct string_view encode_password (struct string_view password); bool check_password (struct string_view password, struct string_view encoded_password); int fscan_passwd_entry (FILE *, struct passwd_entry *); void fprint_passwd_entry (FILE *, const struct passwd_entry *); struct passwd load_passwd_file (void); void save_passwd_file (struct passwd); void close_passwd_file (struct passwd); struct string_view read_password (void); struct string_view read_login (void); void append_passwd_log (void); struct passwd_entry *lookup_login (struct passwd, struct string_view login); struct passwd_entry *lookup_id (struct passwd, int id); struct passwd_entry *authenticate (struct passwd, struct string_view login, struct string_view password); void elevate (void); void drop (void); #endif // INCLUDED_COMMON_H // common.h ends here