Merge the CLI and Daemon portable interface

This commit is contained in:
Andrea Mazzoleni 2026-06-24 00:15:15 +02:00
parent 3302518566
commit 3ce5a5b4e5
46 changed files with 4110 additions and 2042 deletions

3450
os/mingw.c Normal file

File diff suppressed because it is too large Load diff

630
os/mingw.h Normal file
View file

@ -0,0 +1,630 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Andrea Mazzoleni
#ifndef __PORTABLE_MINGW_H
#define __PORTABLE_MINGW_H
#ifdef __MINGW32__ /* Only for MingW */
#include <wchar.h>
#define SYSLOG "EventLog"
#define OS_LVL_CRITICAL 1
#define OS_LVL_ERROR 2
#define OS_LVL_WARNING 3
#define OS_LVL_INFO 4
#define OS_LVL_DEBUG 5
/* map Windows name to POSIX name */
#define strncasecmp _strnicmp
/****************************************************************************/
/* conversion */
/**
* Size in chars of conversion buffers for u8to16() and u16to8().
*/
#define CONV_MAX PATH_MAX
/**
* Convert a path to the Windows format.
*
* If only_is_required is 1, the extended-length format is used only if required.
*
* The exact operation done is:
* - If it's a '\\?\' or '\\.\' path, convert any '/' to '\'.
* - If it's a disk designator path, like 'D:\' or 'D:/', it prepends '\\?\' to the path and convert any '/' to '\'.
* - If it's a UNC path, like ''\\server'', it prepends '\\?\UNC\' to the path and convert any '/' to '\'.
* - Otherwise, only the UTF conversion is done. In this case Windows imposes a limit of 260 chars, and automatically convert any '/' to '\'.
*
* For more details see:
* Naming Files, Paths, and Namespaces
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#maxpath
*/
wchar_t* convert_arg(wchar_t* conv_buf, const char* src, int only_if_required);
#define convert(buf, a) convert_arg(buf, a, 0)
#define convert_if_required(buf, a) convert_arg(buf, a, 1)
/**
* Convert a generic string from UTF16 to UTF8.
* \param conv_buf Destination UTF-8 buffer of size CONV_MAX.
* \param src Source UTF-16 null-terminated string.
* \return The converted string. It never fails.
*/
char* u16tou8(char* conv_buf, const wchar_t* src);
/**
* Convert a generic string from UTF8 to UTF16.
* \param conv_buf Destination UTF-16 buffer of size CONV_MAX.
* \param src Source UTF-8 null-terminated string.
* \return The converted string. It never fails.
*/
wchar_t* u8tou16(wchar_t* conv_buf, const char* src);
/**
* Convert a generic string from UTF16 to UTF8.
* \param conv_buf Destination UTF-8 buffer.
* \param number_of_char Size of the destination buffer in bytes.
* \param src Source UTF-16 string.
* \param number_of_wchar Number of wide characters to convert.
* \param result_length_without_terminator Optional pointer to receive the converted length.
* \return The converted string, or 0 on failure.
*/
char* u16tou8_mayfail(char* conv_buf, size_t number_of_char, const wchar_t* src, size_t number_of_wchar, size_t* result_length_without_terminator);
/**
* Convert a generic string from UTF8 to UTF16.
* \param conv_buf Destination UTF-16 buffer.
* \param conv_size Size of the destination buffer in wchar_t elements.
* \param src Source UTF-8 string.
* \param number_of_char Number of bytes to convert (or -1 for null-terminated string).
* \param result_length_without_terminator Optional pointer to receive the converted length.
* \return The converted string, or 0 on failure.
*/
wchar_t* u8tou16_mayfail(wchar_t* conv_buf, size_t number_of_wchar, const char* src, size_t number_of_char, size_t* result_length_without_terminator);
/****************************************************************************/
/* file */
/**
* Redefines PATH_MAX to allow very long paths.
*/
#undef PATH_MAX
#define PATH_MAX 1024
/* Remap functions and types */
#undef fopen
#define fopen windows_fopen
#define FOPEN_TEXT "t"
#define FOPEN_BINARY "b"
#undef open
#define open windows_open
#define open_noatime windows_open
#undef stat
#define stat windows_stat
#undef lstat
#define lstat windows_lstat
#undef off_t
#define off_t off64_t
#undef fstat
#define fstat windows_fstat
#define HAVE_FTRUNCATE 1
#undef ftruncate
#define ftruncate windows_ftruncate
#define HAVE_FALLOCATE 1
#undef fallocate
#define fallocate windows_fallocate
#define HAVE_FSYNC 1
#undef fsync
#define fsync windows_fsync
#define sync windows_sync
#undef rename
#define rename windows_rename
#undef remove
#define remove windows_remove
#undef mkdir
#define mkdir(a, b) windows_mkdir(a)
#undef rmdir
#define rmdir windows_rmdir
#undef dirent
#define dirent windows_dirent
#undef DIR
#define DIR windows_dir
#undef opendir
#define opendir windows_opendir
#undef readdir
#define readdir windows_readdir
#undef closedir
#define closedir windows_closedir
#define HAVE_FUTIMENS 1
#undef futimens
#define futimens windows_futimens
#define HAVE_UTIMENSAT 1
#define AT_FDCWD -1
#define AT_SYMLINK_NOFOLLOW 1
#undef utimensat
#define utimensat windows_utimensat
#define O_NOFOLLOW 0
#define O_CLOEXEC 0
#define dirent_hidden windows_dirent_hidden
#define HAVE_STRUCT_DIRENT_D_STAT 1
#undef HAVE_STRUCT_DIRENT_D_INO
#define HAVE_STRUCT_STAT_ST_NLINK 1
#define dirent_lstat windows_dirent_lstat
#define stat_desc windows_stat_desc
#undef sleep
#define sleep windows_sleep
#undef usleep
#define usleep windows_usleep
/* 4==DIR, 5,6,7=free, 8==REG */
#define S_IFLNK 0x5000 /* Symbolic link to file */
#define S_ISLNK(m) (((m) & _S_IFMT) == S_IFLNK)
#define S_IFLNKDIR 0x6000 /* Symbolic link to directory */
#define S_ISLNKDIR(m) (((m) & _S_IFMT) == S_IFLNKDIR)
#define S_IFJUN 0x7000 /* Junction */
#define S_ISJUN(m) (((m) & _S_IFMT) == S_IFJUN)
#undef readlink
#define readlink windows_readlink
#undef symlink
#define symlink windows_symlink
#undef link
#define link windows_link
#undef strerror
#define strerror windows_strerror
#undef read
#define read windows_read
#undef write
#define write windows_write
#undef lseek
#define lseek windows_lseek
#undef pread
#define pread windows_pread
#undef pwrite
#define pwrite windows_pwrite
#define direct_size windows_direct_size
#define HAVE_DIRECT_IO 1
#define O_DIRECT 0x10000000
#define O_DSYNC 0x20000000
#undef gmtime_r
#define gmtime_r windows_gmtime_r
#undef localtime_r
#define localtime_r windows_localtime_r
#undef realpath
#define realpath windows_realpath
/**
* If nanoseconds are not supported, we report the special STAT_NSEC_INVALID value,
* to mark that it's undefined.
*/
#define STAT_NSEC_INVALID -1
/* We have nano second support */
#define STAT_NSEC(st) ((int)(st)->st_mtimensec)
static inline int WEXITSTATUS(DWORD status)
{
return status;
}
static inline int WTERMSIG(DWORD status)
{
/* identify most common crash reasons */
switch (status) {
case 0x40000015 : return SIGABRT; /* STATUS_FATAL_APP_EXIT */
case 0xC0000005 : return SIGSEGV; /* STATUS_ACCESS_VIOLATION */
case 0xC0000006 : return SIGSEGV; /* STATUS_IN_PAGE_ERROR */
case 0xC000001D : return SIGILL; /* STATUS_ILLEGAL_INSTRUCTION */
case 0xC00000FD : return SIGSEGV; /* STATUS_STACK_OVERFLOW */
case 0xC0000090 : return SIGFPE; /* STATUS_FLOAT_INVALID_OPERATION */
case 0xC0000094 : return SIGFPE; /* STATUS_INTEGER_DIVIDE_BY_ZERO */
case 0xC000013A : return SIGINT; /* STATUS_CONTROL_C_EXIT */
case 0xC0000409 : return SIGSEGV; /* STATUS_STACK_BUFFER_OVERRUN */
}
return 0;
}
static inline int WIFEXITED(DWORD status)
{
return status < 0xC0000000 && WTERMSIG(status) == 0;
}
static inline int WIFSIGNALED(DWORD status)
{
return WTERMSIG(status) != 0;
}
/**
* Generic stat information.
*/
struct windows_stat {
uint64_t st_ino;
int64_t st_size;
int64_t st_mtime;
int32_t st_mtimensec;
uint32_t st_mode;
uint32_t st_dev;
uint32_t st_nlink;
int st_hidden;
const char* st_desc;
int st_sync; /**< If the information are in sync with the file-system. */
};
/**
* Like the C fstat().
*/
int windows_fstat(int fd, struct windows_stat* st);
/**
* Like the C lstat(), but with some limitations.
*
* The st_ino field may be 0 if it's not possible to read it in a fast way.
* Specifically this always happens.
*
* In case of hardlinks, the size and the attributes of the file can
* be completely bogus, because changes made by other hardlinks are reported
* in the directory entry only when the file is opened.
*
* MSDN CreateHardLinks
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa363860%28v=vs.85%29.aspx
* 'When you create a hard link on the NTFS file system, the file attribute information'
* 'in the directory entry is refreshed only when the file is opened, or when'
* 'GetFileInformationByHandle is called with the handle of a specific file.'
*
* MSDN HardLinks and Junctions
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa365006%28v=vs.85%29.aspx
* 'However, the directory entry size and attribute information is updated only'
* 'for the link through which the change was made.'
*
* Use lstat_sync() to override these limitations.
*/
int windows_lstat(const char* file, struct windows_stat* st);
/**
* Like the C stat().
*/
int windows_stat(const char* file, struct windows_stat* st);
/**
* Like the C mkdir().
*/
int windows_mkdir(const char* file);
/**
* Like rmdir().
*/
int windows_rmdir(const char* file);
/**
* Like the C lstat(), but with some limitations.
*
* This call fills all the st_* fields of the stat struct,
* and if provided the pointer, also the physical offset.
*
* It doesn't work for all kinds of files and directories.
* You must call it only for regular files.
* For example, "C:\System Volume Information" cannot be accessed
* with error ERROR_ACCESS_DENIED.
*
* Note that instead lstat() works for all the files.
*/
#define HAVE_LSTAT_SYNC 1
int lstat_sync(const char* file, struct windows_stat* st, uint64_t* physical);
/**
* Like the C ftruncate().
*/
int windows_ftruncate(int fd, off64_t off);
/**
* Like the C fallocate().
*/
int windows_fallocate(int fd, int mode, off64_t off, off64_t len);
/**
* Like the C fsync().
*/
int windows_fsync(int fd);
/**
* Like the C sync().
*/
int windows_sync(void);
/**
* Like the C futimes().
*/
int windows_futimes(int fd, struct timeval tv[2]);
struct windows_timespec {
int64_t tv_sec;
int tv_nsec;
};
#define timespec windows_timespec
/**
* Like the C futimens().
*/
int windows_futimens(int fd, struct windows_timespec tv[2]);
/**
* Like the C utimensat().
*/
int windows_utimensat(int fd, const char* file, struct windows_timespec tv[2], int flags);
/**
* Like the C rename().
*/
int windows_rename(const char* a, const char* b);
/**
* Like the C remove().
*/
int windows_remove(const char* a);
/**
* Like the C fopen().
*/
FILE* windows_fopen(const char* file, const char* mode);
/**
* Like the C open().
*/
int windows_open(const char* file, int flags, ...);
/**
* Like the C dirent.
*/
struct windows_dirent {
char d_name[PATH_MAX];
struct windows_stat d_stat;
};
/**
* Like the C DIR.
*/
struct windows_dir_struct;
typedef struct windows_dir_struct windows_dir;
/**
* Like the C opendir().
*/
windows_dir* windows_opendir(const char* dir);
/**
* Like the C readdir().
*/
struct windows_dirent* windows_readdir(windows_dir* dirstream);
/**
* Like the C closedir().
*/
int windows_closedir(windows_dir* dirstream);
/**
* Convert a dirent record to a lstat record, but with some limitations.
*
* The st_mode field may be 0 if the file is a reparse point.
* Specifically this happens if we are using GetFileInformationByHandleEx()
* to read the directory stream.
*
* The st_ino field may be 0 if it's not possible to read it in a fast way.
* Specifically this happens if we are using FindFirst/FindNext to enumerate
* the directory.
*
* In such cases, call lstat_sync() to fill the missing fields.
*/
void windows_dirent_lstat(const struct windows_dirent* dd, struct windows_stat* st);
/**
* Like dirent_hidden().
*/
int windows_dirent_hidden(struct dirent* dd);
/**
* Like stat_desc().
*/
const char* windows_stat_desc(struct stat* st);
/**
* Like sleep().
*/
unsigned windows_sleep(unsigned seconds);
/**
* Like usleep().
*/
void windows_usleep(uint64_t useconds);
/**
* Like readlink().
*/
int windows_readlink(const char* file, char* buffer, size_t size);
/**
* Like symlink().
* Return ENOSYS if symlinks are not supported.
*/
int windows_symlink(const char* existing, const char* file);
/**
* Like symlink().
* Return ENOSYS if symlinks are not supported.
*/
int windows_symlink_directory(const char* existing, const char* file);
/**
* Like link().
*/
int windows_link(const char* existing, const char* file);
/**
* Like strerror().
*/
const char* windows_strerror(int err);
/**
* Like read().
*/
ssize_t windows_read(int f, void* buffer, size_t size);
/**
* Like write().
*/
ssize_t windows_write(int f, const void* buffer, size_t size);
/**
* Like lseek().
*/
off_t windows_lseek(int f, off_t offset, int whence);
/**
* Like pread().
*/
ssize_t windows_pread(int f, void* buffer, size_t size, off_t offset);
/**
* Like pwrite().
*/
ssize_t windows_pwrite(int f, const void* buffer, size_t size, off_t offset);
/**
* Like direct_size().
*/
size_t windows_direct_size(void);
/**
* Like gmtime_r().
*/
struct tm* windows_gmtime_r(const time_t* timer, struct tm* result);
/**
* Like localtime_r().
*/
struct tm* windows_localtime_r(const time_t* timer, struct tm* result);
/**
* Like realpath().
*/
char* windows_realpath(const char* path, char* resolved_path);
/**
* Like GetFileAttributes()
*/
int windows_get_file_attributes(const char* file);
/**
* Like SetFileAttributes()
*/
int windows_set_file_attributes(const char* file, int attributes);
/**
* Convert Windows error to errno.
*/
void windows_errno(DWORD error);
/**
* Return the executable directory.
*
* Ends with \
*/
const wchar_t* windows_exedir(void);
/**
* Return if we are in the Wine environment.
*/
int windows_is_wine(void);
/****************************************************************************/
/* thread */
#define HAVE_THREAD 1
typedef void* windows_thread_t;
typedef CRITICAL_SECTION windows_mutex_t;
typedef struct {
SRWLOCK srw;
BOOL exclusive;
} windows_rwlock_t;
typedef CONDITION_VARIABLE windows_cond_t;
typedef void* windows_key_t;
/* remap to pthread */
#define pid_t intptr_t
#define thread_id_t windows_thread_t
#define thread_mutex_t windows_mutex_t
#define thread_cond_t windows_cond_t
#define thread_rwlock_t windows_rwlock_t
#define thread_key_t windows_key_t
#define pthread_mutex_init windows_mutex_init
#define pthread_mutex_destroy windows_mutex_destroy
#define pthread_mutex_lock windows_mutex_lock
#define pthread_mutex_unlock windows_mutex_unlock
#define pthread_rwlock_init windows_rwlock_init
#define pthread_rwlock_destroy windows_rwlock_destroy
#define pthread_rwlock_rdlock windows_rwlock_rdlock
#define pthread_rwlock_wrlock windows_rwlock_wrlock
#define pthread_rwlock_unlock windows_rwlock_unlock
#define pthread_cond_init windows_cond_init
#define pthread_cond_destroy windows_cond_destroy
#define pthread_cond_signal windows_cond_signal
#define pthread_cond_broadcast windows_cond_broadcast
#define pthread_cond_wait windows_cond_wait
#define pthread_create windows_create
#define pthread_join windows_join
#define pthread_key_create windows_key_create
#define pthread_key_delete windows_key_delete
#define pthread_getspecific windows_getspecific
#define pthread_setspecific windows_setspecific
/**
* Like the pthread_* equivalent.
*/
int windows_mutex_init(windows_mutex_t* mutex, void* attr);
int windows_mutex_destroy(windows_mutex_t* mutex);
int windows_mutex_lock(windows_mutex_t* mutex);
int windows_mutex_unlock(windows_mutex_t* mutex);
int windows_rwlock_init(windows_rwlock_t* mutex, void* attr);
int windows_rwlock_destroy(windows_rwlock_t* mutex);
int windows_rwlock_rdlock(windows_rwlock_t* mutex);
int windows_rwlock_wrlock(windows_rwlock_t* mutex);
int windows_rwlock_unlock(windows_rwlock_t* mutex);
int windows_cond_init(windows_cond_t* cond, void* attr);
int windows_cond_destroy(windows_cond_t* cond);
int windows_cond_signal(windows_cond_t* cond);
int windows_cond_broadcast(windows_cond_t* cond);
int windows_cond_wait(windows_cond_t* cond, windows_mutex_t* mutex);
int windows_create(thread_id_t* thread, void* attr, void* (*func)(void*), void* arg);
int windows_join(thread_id_t thread, void** retval);
/**
* Windows thread variables
*
* WARNING: windows_key_create and windows_key_delete must be called from a monothread context
*/
int windows_key_create(windows_key_t* key, void (*destructor)(void*));
int windows_key_delete(windows_key_t key);
void* windows_getspecific(windows_key_t key);
int windows_setspecific(windows_key_t key, void* value);
/****************************************************************************/
/* service */
#if !HAVE_GETOPT_LONG
#error HAVE_GETOPT_LONG is required in Windows for the service options
#endif
/**
* Log into Eventlog
*/
void windows_eventlog(int level, const char* msg);
/**
* Signal that the service is starting and it needs more time.
*/
void windows_starting(void);
#endif
#endif

319
os/os.h Normal file
View file

@ -0,0 +1,319 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Andrea Mazzoleni
#ifndef __OS_H
#define __OS_H
/****************************************************************************/
/* syslog */
/**
* Log an informational syslog message.
* The message should start with a lowercase letter and must not terminate with \n.
* \param level One of OS_LVL_*.
* \param format Printf-like format string.
*/
void os_syslog(int level, const char* format, ...) __attribute__((format(attribute_printf, 2, 3)));
/****************************************************************************/
/* signal */
/**
* Enable or disable signal handling.
* \param enable 1 to enable signals, 0 to disable.
*/
void os_signal_set(int enable);
/**
* Initialize signal handling.
* \param handler_term Signal handler callback for termination signals (SIGTERM, SIGINT).
* \param handler_hup Signal handler callback for hangup signal (SIGHUP).
*/
void os_signal_init(void (*handler_term)(int sig), void (*handler_hup)(int sig));
/**
* Restore signal handlers after fork in child process.
* This resets signals to default handling.
*/
void os_signal_restore_after_fork(void);
/**
* Get string representation of signal number.
* \param sig Signal number.
* \return Signal name string.
*/
const char* os_signal_name(int sig);
/**
* Global variable to identify if Ctrl+C is pressed.
* \return 1 if Ctrl+C was pressed/interrupted, 0 otherwise.
*/
int os_signal_interrupt(void);
/****************************************************************************/
/* exec */
/**
* Opaque handle tracking a process execution stream and its process ID.
*
* This structure encapsulates a standard buffered I/O stream tied to the
* redirected standard output of a child process spawned via os_popen().
*/
#ifdef __MINGW32__
#define OS_FILE FILE
#else
typedef struct OS_FILE {
FILE* fp; /**< Standard I/O buffered stream wrapper. */
pid_t pid; /**< Process ID of the child process. */
} OS_FILE;
#endif
/**
* Spawns a child process and opens a buffered stream to read its stdout.
*
* This function acts as a safer alternative to standard popen(), accepting an
* explicit argument vector rather than evaluating a shell command string.
*
* The child process is completely isolated in its own process group (via setpgid)
* with its stdin and stderr redirected to /dev/null. The underlying pipe is
* created with O_CLOEXEC set to prevent leakage across concurrent forks.
*
* \param argv A NULL-terminated array of strings representing the argument vector.
* argv[0] must contain the absolute path to the verified executable.
* \return A pointer to an initialized OS_FILE structure on success, or NULL on failure.
*/
OS_FILE* os_popen(const char** argv);
/**
* Reads a line from an OS execution stream.
*
* Reads characters from the specified stream into the buffer string until
* (size - 1) characters are read, a newline character is read and transferred,
* or an end-of-file (EOF) condition is encountered. A terminating null
* character is appended.
*
* \param s Pointer to an array of chars where the string read is stored.
* \param size Maximum number of characters to be read (including the null character).
* \param stream Pointer to the OS_FILE tracking context.
* \return On success, returns the buffer pointer s. If EOF is reached or a read
* error occurs before any characters are read, returns NULL.
*/
char* os_fgets(char* s, int size, OS_FILE* stream);
/**
* Closes an execution stream and reaps the associated child process.
*
* Closes the underlying buffered standard I/O stream, releases the allocated
* tracking context container, and blocks until the associated child process
* terminates to prevent the creation of zombie processes.
*
* \param stream Pointer to the active OS_FILE context to close and free.
* \return The termination status of the child process on success, or -1 on failure.
*/
int os_pclose(OS_FILE* stream);
/**
* Spawn a new process with the specified argument vector, optionally capturing stdout and/or stderr.
* \param argv Array of command line arguments.
* \param stdout_read_fd Pointer to store file descriptor for stdout, or NULL to redirect to /dev/null.
* \param stderr_read_fd Pointer to store file descriptor for stderr, or NULL to redirect to /dev/null.
* \param run_as_user User to run script as (NULL for current user).
* \return Process ID of spawned process, or -1 on failure.
*/
pid_t os_spawn(char** argv, int* stdout_read_fd, int* stderr_read_fd, const char* run_as_user);
/**
* Wait for the child process to terminate.
* \param pid Process ID of the child process.
* \param status Pointer to store the exit status.
* \return Child PID on success, -1 on failure.
*/
pid_t os_wait(pid_t pid, int* status);
/**
* Terminate gracefully a process.
* \param pid Process ID of the process to terminate.
* \return 0 on success, -1 on failure.
*/
int os_term(pid_t pid);
/**
* Fork and execute a verified executable, discarding all I/O.
*
* Spawns @argv[0] in a new process with stdin, stdout and stderr all
* redirected to /dev/null. Use this for fire-and-forget tasks where the
* child's output is not needed.
*
* The child is placed in its own process group (setpgid) to isolate it
* from signals sent to the daemon's process group.
*
* \param argv NULL-terminated argument vector. argv[0] must be the absolute path
* to the executable.
* \return The child exit status on success, or -1 on failure.
*/
int os_spawn_and_wait(const char** argv);
/**
* Execute a system command with optional user context and input.
* \param command Command to execute.
* \param run_as_user User to run command as (NULL for current user).
* \param stdin_text Text to provide as stdin (NULL for no input).
* \return Exit status of command.
*/
int os_command(const char* command, const char* run_as_user, const char* stdin_text);
/**
* Execute a script file with specified user context.
* \param argv Array of command line arguments.
* \param envp Environment variables (NULL-terminated list of strings).
* \param run_as_user User to run script as (NULL for current user).
* \return Exit status of script.
*/
int os_script(char** argv, char** envp, const char* run_as_user);
/**
* Validates a string for exec.
* \param str The input string to validate.
* \return -1 if dangerous characters are detected, 0 otherwise.
*/
int os_validate_exec_input(const char* str);
/****************************************************************************/
/* fs */
/**
* Physical offset not yet read.
*/
#define FILEPHY_UNREAD_OFFSET 0
/**
* Special value returned when the file-system doesn't report any offset for unknown reason.
*/
#define FILEPHY_UNREPORTED_OFFSET 1
/**
* Special value returned when the file doesn't have a real offset.
* For example, because it's stored in the NTFS MFT.
*/
#define FILEPHY_WITHOUT_OFFSET 2
/**
* Value indicating real offsets. All offsets greater or equal at this one are real.
*/
#define FILEPHY_REAL_OFFSET 3
/**
* Get the physical address of the specified file.
* This is expected to be just a hint and not necessarily correct or unique.
* \param path The path of the file.
* \param size The size of the file.
* \param physical Pointer to store the physical offset.
* \return 0 on success, -1 on failure.
*/
int filephy(const char* path, uint64_t size, uint64_t* physical);
/****************************************************************************/
/* privileges */
/**
* Bracketed Privileges System:
* These functions allow the daemon to run with dropped effective privileges
* by default (euid/egid set to an unprivileged user like "nobody"), while
* temporarily escalating to root privileges for specific operations that require
* administrative permissions (e.g., config changes, executing SnapRAID commands,
* managing log files).
*/
/**
* Temporarily acquire root privileges.
* Restores the effective user and group ID of the calling thread to root (0).
*/
void os_privileges_acquire(void);
/**
* Release root privileges.
* Reverts the effective user and group ID of the calling thread to the unprivileged credentials.
*/
void os_privileges_release(void);
/**
* Drop effective privileges permanently to an unprivileged user (e.g., "nobody").
* Called after startup/initialization is complete to transition the daemon into
* the Bracketed Privileges execution mode.
*/
void os_privileges_drop(void);
/****************************************************************************/
/* os */
#define OS_INIT_OPT_AVOID_SLEEP 1 /**< Prevent the system to go to sleep */
#define OS_INIT_OPT_WINFIND 2 /**< Use the legacy Windows FindFirstFile interface instead of the new stream interface */
/**
* Initializes the system.
* \param opt System initialization options.
*/
void os_init(unsigned opt);
/**
* Deinitializes the system.
*/
void os_done(void);
/**
* Get the os_tick counter value.
*
* Note that the frequency is unspecified, because the time measure
* is meant to be used to compare the ratio between usage times.
* \return Monotonic clock tick value.
*/
uint64_t os_tick(void);
/**
* Get the os_tick counter value in millisecond.
* \return Monotonic clock value in milliseconds.
*/
uint64_t os_tick_ms(void);
/**
* Get the os_tick counter value in seconds.
* \return Monotonic clock value in seconds.
*/
uint64_t os_tick_sec(void);
/**
* Abort the process with a stacktrace.
*/
void os_abort(void) __noreturn;
/**
* Exit the process with failure.
*/
void os_exit(void) __noreturn;
/**
* Shutdown the system.
* \return 0 on success, -1 on failure.
*/
int os_shutdown(void);
/**
* Clear the screen.
*/
void os_clear(void);
/**
* Fill memory with pseudo-random values
* \param ptr Pointer to the memory buffer.
* \param size Size of the memory buffer.
* \return 0 on success, -1 on failure.
*/
int os_randomize(void* ptr, size_t size);
/**
* Get the optimal CPU for the speed test
* \return Optimal CPU index.
*/
int os_get_optimal_cpu(void);
#endif

312
os/portable.h Normal file
View file

@ -0,0 +1,312 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Andrea Mazzoleni
#ifndef __PORTABLE_H
#define __PORTABLE_H
#if HAVE_CONFIG_H
#include "config.h" /* Use " to include first in the same directory of this file */
#endif
/***************************************************************************/
/* Config */
#ifdef __MINGW32__
/**
* Enable the GNU printf functions instead of using the MSVCRT ones.
*
* Note that this is the default if _POSIX is also defined.
* To disable it you have to set it to 0.
*/
#define __USE_MINGW_ANSI_STDIO 1
/**
* Define the MSVCRT version targeting Windows 7.
*/
#define __MSVCRT_VERSION__ 0x0601
/**
* Include Windows 7 headers.
*
* Like for InitializeCriticalSection().
*/
#define _WIN32_WINNT 0x601
/**
* Enable the rand_s() function.
*/
#define _CRT_RAND_S
/**
* Undef as it clashes with windows.h declarations
*/
#undef DATADIR
#include <windows.h>
#endif
/**
* Specify the format attribute for printf.
*/
#ifdef __MINGW32__
#if defined(__USE_MINGW_ANSI_STDIO) && __USE_MINGW_ANSI_STDIO == 1
#define attribute_printf gnu_printf /* GNU format */
#define printf(...) __mingw_printf(__VA_ARGS__) /* to support %z in printf */
#else
#define attribute_printf ms_printf /* MSVCRT format */
#endif
#else
#define attribute_printf printf /* GNU format is the default one */
#endif
/**
* Compiler extension
*/
#ifndef __always_inline
#define __always_inline inline __attribute__((always_inline))
#endif
#ifndef __noreturn
#define __noreturn __attribute__((noreturn))
#endif
/**
* Architecture for inline assembly.
*/
#if HAVE_ASSEMBLY
#if defined(__i386__)
#define CONFIG_X86 1
#define CONFIG_X86_32 1
#endif
#if defined(__x86_64__)
#define CONFIG_X86 1
#define CONFIG_X86_64 1
#endif
#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32)
#define CONFIG_ARM_CRC 1
#endif
#endif
/**
* Includes some platform specific headers.
*/
#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#if HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#if HAVE_SYS_VFS_H
#include <sys/vfs.h>
#endif
#if HAVE_SYS_STATFS_H
#include <sys/statfs.h>
#endif
#if HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#if HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#if HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#if HAVE_LINUX_FS_H
#include <linux/fs.h>
#endif
#if HAVE_LINUX_BTRFS_H
#include <linux/btrfs.h>
#endif
#if HAVE_LINUX_FIEMAP_H
#include <linux/fiemap.h>
#endif
#if HAVE_BLKID_BLKID_H
#include <blkid/blkid.h>
#if HAVE_BLKID_DEVNO_TO_DEVNAME && HAVE_BLKID_GET_TAG_VALUE
#define HAVE_BLKID 1
#endif
#endif
/**
* Includes some standard headers.
*/
#include <stdio.h>
#include <stdlib.h> /* On many systems (e.g., Darwin), `stdio.h' is a prerequisite. */
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <limits.h>
#if HAVE_STDINT_H
#include <stdint.h>
#endif
#if HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif
#if HAVE_MACH_MACH_TIME_H
#include <mach/mach_time.h>
#endif
#if HAVE_DIRENT_H
#include <dirent.h>
#define NAMLEN(dirent) strlen((dirent)->d_name)
#else
#define dirent direct
#define NAMLEN(dirent) (dirent)->d_namlen
#if HAVE_SYS_NDIR_H
#include <sys/ndir.h>
#endif
#if HAVE_SYS_DIR_H
#include <sys/dir.h>
#endif
#if HAVE_NDIR_H
#include <ndir.h>
#endif
#endif
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#if HAVE_SYS_MKDEV
#include <sys/mkdev.h>
#endif
#if HAVE_SYS_SYSMACROS_H
#include <sys/sysmacros.h>
#endif
#if HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#if HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#if HAVE_GETOPT_H
#include <getopt.h>
#endif
#if HAVE_MATH_H
#include <math.h>
#endif
#if HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#ifdef HAVE_STRINGS
#include <strings.h>
#endif
#if HAVE_SYSLOG_H
#include <syslog.h>
#endif
#if HAVE_GRP_H
#include <grp.h>
#endif
#if HAVE_PWD_H
#include <pwd.h>
#endif
#if HAVE_SYS_SYSINFO_H
#include <sys/sysinfo.h>
#endif
#if HAVE_SYS_UTSNAME_H
#include <sys/utsname.h>
#endif
#if HAVE_ZLIB
#include <zlib.h>
#endif
#if HAVE_ZSTD
#include <zstd.h>
#endif
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <DiskArbitration/DiskArbitration.h>
#include <mach-o/dyld.h>
#endif
#if HAVE_IO_H
#include <io.h>
#endif
#if HAVE_GETOPT_LONG
#define SWITCH_GETOPT_LONG(a, b) a
#else
#define SWITCH_GETOPT_LONG(a, b) b
#endif
/**
* Enables lock file support.
*/
#if HAVE_FLOCK && HAVE_FTRUNCATE
#define HAVE_LOCKFILE 1
#endif
#ifdef HAVE_LINUX_CLOSE_RANGE_H
#include <linux/close_range.h>
#endif
/*
* Flags for open()
*/
#ifndef O_PATH
#ifdef O_SEARCH
#define O_PATH O_SEARCH /* macOS */
#else
#define O_PATH O_RDONLY /* POSIX */
#endif
#endif
/**
* Includes specific support for Windows or Linux.
*/
#ifdef __MINGW32__
#include "mingw.h"
#else
#include "unix.h"
#endif
#endif

1607
os/unix.c Normal file

File diff suppressed because it is too large Load diff

158
os/unix.h Normal file
View file

@ -0,0 +1,158 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Andrea Mazzoleni
#ifndef __UNIX_H
#define __UNIX_H
#ifdef __linux__
#define HAVE_LINUX_DEVICE 1 /**< In Linux enables special device support. */
#define HAVE_DIRECT_IO 1 /**< Support O_DIRECT in open(). */
#endif
#define SYSLOG "syslog"
#define OS_LVL_CRITICAL LOG_CRIT
#define OS_LVL_ERROR LOG_ERR
#define OS_LVL_WARNING LOG_WARNING
#define OS_LVL_INFO LOG_INFO
#define OS_LVL_DEBUG LOG_DEBUG
/* implement close_range for glibc 2.33 or earlier */
#if defined(__linux__) && !defined(HAVE_CLOSE_RANGE)
#include <sys/syscall.h>
#ifndef __NR_close_range
#define __NR_close_range 436
#endif
#define close_range close_range_impl
static inline int close_range_impl(unsigned int first, unsigned int last, unsigned int flags)
{
return (int)syscall(__NR_close_range, first, last, flags);
}
#define HAVE_CLOSE_RANGE 1
#endif
#ifndef WEXITSTATUS
#define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
#endif
#ifndef WIFEXITED
#define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
#endif
#define FOPEN_TEXT ""
#define FOPEN_BINARY ""
#define O_BINARY 0 /**< Not used in Unix. */
#define O_SEQUENTIAL 0 /**< In Unix posix_fadvise() shall be used. */
/**
* If nanoseconds are not supported, we report the special STAT_NSEC_INVALID value,
* to mark that it's undefined.
*/
#define STAT_NSEC_INVALID -1
/* Check if we have nanoseconds support */
#if HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
#define STAT_NSEC(st) ((int)(st)->st_mtim.tv_nsec) /* Linux */
#elif HAVE_STRUCT_STAT_ST_MTIMENSEC
#define STAT_NSEC(st) ((int)(st)->st_mtimensec) /* NetBSD */
#elif HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
#define STAT_NSEC(st) ((int)(st)->st_mtimespec.tv_nsec) /* FreeBSD, Mac OS X */
#else
#define STAT_NSEC(st) STAT_NSEC_INVALID
#endif
#if HAVE_POSIX_FADVISE
/**
* Wrapper around posix_fadvise() that handles ENOENT by converting it to
* ENOSYS.
*
* Why can posix_fadvise() return ENOENT?
*
* According to POSIX and the Linux kernel's standard fadvise64 implementation
* (mm/fadvise.c), posix_fadvise() should only return EBADF (bad file
* descriptor), ESPIPE (fd refers to a pipe or FIFO), or EINVAL (invalid
* advice value or arguments). ENOENT is never generated by the kernel's
* generic path.
*
* However, the VFS layer allows individual filesystems to provide their own
* .fadvise() method, which is called instead of (or in addition to) the
* generic implementation. Certain filesystem drivers can return ENOENT in
* this method for reasons that are completely unrelated to the file not
* existing (the file is clearly open, we have a valid fd):
*
* - NFS: A stale NFS inode can be revalidated against the server while
* fadvise is being processed. If the server-side file has been removed or
* renamed, the revalidation discovers the inode is gone and returns
* -ENOENT, even though the client still holds an open file descriptor.
*
* - FUSE-based filesystems (mergerfs, sshfs, rclone, etc.): The FUSE daemon
* receives the fadvise request and may forward it to an underlying backend.
* If that backend cannot find the file (e.g., the backing path has changed,
* the FUSE daemon is partially initialised, or the daemon translates the
* request and the target layer returns an error), the daemon may return
* ENOENT to the kernel.
*
* - Overlayfs (used by Docker, Podman, LXC): The overlayfs .fadvise()
* implementation delegates to the lower or upper layer. If the lookup
* through the overlay stack fails to find the real inode (e.g., the upper
* directory entry is absent and the lower copy is in a weird state), the
* delegation can return ENOENT.
*
* - Other network or virtual filesystems: Any out-of-tree or in-tree
* filesystem that implements .fadvise() and performs a path or inode
* lookup as part of processing the hint can propagate ENOENT if that
* internal lookup fails.
*
* Because posix_fadvise() is always an advisory hint, it never affects
* correctness, only performance, it is safe to treat unexpected errors,
* including ENOENT, as "not supported" (ENOSYS) and continue.
*/
int posix_fadvise_wrapper(int fd, off_t offset, off_t len, int advice);
#endif
#if !HAVE_EACCESS
/**
* Check effective user's permissions for a file.
* Conceptually identical to access(), but uses the effective UID/GID.
*/
int eaccess(const char* pathname, int mode);
#endif
/**
* Open a file with the O_NOATIME flag to avoid to update the access time.
*/
int open_noatime(const char* file, int flags);
/**
* Check if the specified file is hidden.
*/
int dirent_hidden(struct dirent* dd);
/**
* Return a description of the file type.
*/
const char* stat_desc(struct stat* st);
/**
* Return the alignment requirement for direct IO.
*/
size_t direct_size(void);
/****************************************************************************/
/* thread */
#if HAVE_PTHREAD_H
#include <pthread.h>
#endif
#if HAVE_PTHREAD
#define HAVE_THREAD 1
typedef pthread_t thread_id_t;
typedef pthread_mutex_t thread_mutex_t;
typedef pthread_cond_t thread_cond_t;
typedef pthread_key_t thread_key_t;
typedef pthread_rwlock_t thread_rwlock_t;
#endif
#endif