James Kuszmaul | 82f6c04 | 2021-01-17 11:30:16 -0800 | [diff] [blame^] | 1 | /** |
| 2 | * @file fs.c File-system functions |
| 3 | * |
| 4 | * Copyright (C) 2010 Creytiv.com |
| 5 | */ |
| 6 | #include <stdlib.h> |
| 7 | #include <string.h> |
| 8 | #include <sys/stat.h> |
| 9 | #include <sys/types.h> |
| 10 | #include <fcntl.h> |
| 11 | #ifdef HAVE_UNISTD_H |
| 12 | #include <unistd.h> |
| 13 | #endif |
| 14 | #ifdef HAVE_PWD_H |
| 15 | #include <pwd.h> |
| 16 | #endif |
| 17 | #ifdef WIN32 |
| 18 | #include <windows.h> |
| 19 | #include <shlobj.h> |
| 20 | #include <direct.h> |
| 21 | #include <lmaccess.h> |
| 22 | #endif |
| 23 | #include <re_types.h> |
| 24 | #include <re_fmt.h> |
| 25 | #include <re_sys.h> |
| 26 | |
| 27 | |
| 28 | /** |
| 29 | * Create a directory with full path |
| 30 | * |
| 31 | * @param path Directory path |
| 32 | * @param mode Access permissions |
| 33 | * |
| 34 | * @return 0 if success, otherwise errorcode |
| 35 | */ |
| 36 | int fs_mkdir(const char *path, uint16_t mode) |
| 37 | { |
| 38 | int ret; |
| 39 | |
| 40 | if (!path) |
| 41 | return EINVAL; |
| 42 | |
| 43 | #if defined (WIN32) |
| 44 | (void)mode; |
| 45 | ret = _mkdir(path); |
| 46 | #else |
| 47 | ret = mkdir(path, mode); |
| 48 | #endif |
| 49 | if (ret < 0) |
| 50 | return errno; |
| 51 | |
| 52 | return 0; |
| 53 | } |
| 54 | |
| 55 | |
| 56 | /** |
| 57 | * Get the home directory for the current user |
| 58 | * |
| 59 | * @param path String to write home directory |
| 60 | * @param sz Size of path string |
| 61 | * |
| 62 | * @return 0 if success, otherwise errorcode |
| 63 | */ |
| 64 | int fs_gethome(char *path, size_t sz) |
| 65 | { |
| 66 | #ifdef WIN32 |
| 67 | char win32_path[MAX_PATH]; |
| 68 | |
| 69 | if (!path || !sz) |
| 70 | return EINVAL; |
| 71 | |
| 72 | if (S_OK != SHGetFolderPath(NULL, |
| 73 | CSIDL_APPDATA | CSIDL_FLAG_CREATE, |
| 74 | NULL, |
| 75 | 0, |
| 76 | win32_path)) { |
| 77 | return ENOENT; |
| 78 | } |
| 79 | |
| 80 | str_ncpy(path, win32_path, sz); |
| 81 | |
| 82 | return 0; |
| 83 | |
| 84 | #elif defined(HAVE_PWD_H) |
| 85 | const char *loginname; |
| 86 | struct passwd *pw; |
| 87 | |
| 88 | if (!path || !sz) |
| 89 | return EINVAL; |
| 90 | |
| 91 | loginname = sys_username(); |
| 92 | if (!loginname) |
| 93 | return ENOENT; |
| 94 | |
| 95 | pw = getpwnam(loginname); |
| 96 | if (!pw) |
| 97 | return errno; |
| 98 | |
| 99 | str_ncpy(path, pw->pw_dir, sz); |
| 100 | |
| 101 | return 0; |
| 102 | #else |
| 103 | (void)path; |
| 104 | (void)sz; |
| 105 | return ENOSYS; |
| 106 | #endif |
| 107 | } |