LCOV - code coverage report
Current view: top level - cmdline - main.c (source / functions) Hit Total Coverage
Test: lcov.info Lines: 51 61 83.6 %
Date: 2026-03-15 15:58:19 Functions: 2 2 100.0 %

          Line data    Source code
       1             : /*
       2             :  * Copyright (C) 2025 Andrea Mazzoleni
       3             :  *
       4             :  * This program is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 3 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * This program is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "portable.h"
      19             : 
      20             : #include "snapraid.h"
      21             : 
      22             : #define MODE_DEFAULT 0
      23             : #define MODE_SPINDOWN 1
      24             : 
      25             : #ifdef _WIN32
      26             : #define COMMAND_LINE_MAX 32767
      27             : 
      28             : static int needs_quote(const WCHAR* arg)
      29             : {
      30             :         while (*arg) {
      31             :                 if (*arg == L' ' || *arg == L'\t' || *arg == L'"')
      32             :                         return 1;
      33             :                 ++arg;
      34             :         }
      35             : 
      36             :         return 0;
      37             : }
      38             : 
      39             : #define charcat(c) \
      40             :         do { \
      41             :                 if (pos + 1 >= size) { \
      42             :                         return -1; \
      43             :                 } \
      44             :                 cmd[pos++] = (c); \
      45             :         } while (0)
      46             : 
      47             : static int argcat(WCHAR* cmd, int size, int pos, const WCHAR* arg)
      48             : {
      49             :         int has_quote;
      50             : 
      51             :         /* space separator */
      52             :         if (pos != 0)
      53             :                 charcat(L' ');
      54             : 
      55             :         has_quote = needs_quote(arg);
      56             : 
      57             :         if (!has_quote) {
      58             :                 while (*arg)
      59             :                         charcat(*arg++);
      60             :         } else {
      61             :                 /* starting quote */
      62             :                 charcat(L'"');
      63             : 
      64             :                 while (*arg) {
      65             :                         int bl = 0;
      66             :                         while (*arg == L'\\') {
      67             :                                 ++arg;
      68             :                                 ++bl;
      69             :                         }
      70             : 
      71             :                         if (*arg == 0) {
      72             :                                 /* double backslashes before closing quote */
      73             :                                 bl = bl * 2;
      74             :                                 while (bl--)
      75             :                                         charcat(L'\\');
      76             :                         } else if (*arg == '"') {
      77             :                                 /* double backslashes + escape the quote */
      78             :                                 bl = bl * 2 + 1;
      79             :                                 while (bl--)
      80             :                                         charcat(L'\\');
      81             :                                 charcat(L'"');
      82             :                                 ++arg;
      83             :                         } else {
      84             :                                 /* normal backslashes */
      85             :                                 while (bl--)
      86             :                                         charcat(L'\\');
      87             :                                 charcat(*arg);
      88             :                                 ++arg;
      89             :                         }
      90             :                 }
      91             : 
      92             :                 /* ending quote */
      93             :                 charcat(L'"');
      94             :         }
      95             : 
      96             :         return pos;
      97             : }
      98             : 
      99             : static char* argutf8(const WCHAR* arg)
     100             : {
     101             :         size_t len = wcslen(arg);
     102             :         char* utf8_arg;
     103             :         DWORD utf8_len;
     104             :         DWORD res;
     105             : 
     106             :         utf8_len = WideCharToMultiByte(CP_UTF8, 0, arg, len + 1 /* include final null */, 0, 0, 0, 0);
     107             : 
     108             :         utf8_arg = malloc(utf8_len);
     109             :         if (!utf8_arg)
     110             :                 return 0;
     111             : 
     112             :         res = WideCharToMultiByte(CP_UTF8, 0, arg, len + 1 /* include final null */, utf8_arg, utf8_len, 0, 0);
     113             :         if (res != utf8_len)
     114             :                 return 0;
     115             : 
     116             :         return utf8_arg;
     117             : }
     118             : 
     119             : /* Global variable to store child process handle */
     120             : static HANDLE child_process = NULL;
     121             : 
     122             : /* Console control handler - forwards Ctrl+C, Ctrl+Break to child */
     123             : static BOOL WINAPI console_handler(DWORD ctrl_type)
     124             : {
     125             :         /* if no child, default behavior */
     126             :         if (child_process == NULL)
     127             :                 return FALSE;
     128             : 
     129             :         switch (ctrl_type) {
     130             :         case CTRL_C_EVENT :
     131             :         case CTRL_BREAK_EVENT :
     132             :                 /*
     133             :                  * Return TRUE to prevent parent termination. The child process
     134             :                  * will receive these events automatically because it's attached
     135             :                  * to the same console, so we don't need to forward them.
     136             :                  */
     137             :                 return TRUE; /* signal handled, don't terminate parent */
     138             :         case CTRL_CLOSE_EVENT :
     139             :         case CTRL_LOGOFF_EVENT :
     140             :         case CTRL_SHUTDOWN_EVENT :
     141             :                 /*
     142             :                  * Return TRUE to prevent our termination while child handles shutdown.
     143             :                  * The child receives these events automatically (same console).
     144             :                  * Note: Windows will forcibly kill us after a timeout regardless
     145             :                  * of returning TRUE: ~5 seconds for CLOSE_EVENT and LOGOFF_EVENT,
     146             :                  * ~5-20 seconds for SHUTDOWN_EVENT (configurable in registry).
     147             :                  */
     148             :                 return TRUE; /* signal handled, but Windows will kill us after timeout */
     149             :         default :
     150             :                 return FALSE;
     151             :         }
     152             : }
     153             : 
     154             : int main(int argc, char* argv[])
     155             : {
     156             :         int wide_argc;
     157             :         WCHAR** wide_argv;
     158             :         int utf8_argc;
     159             :         char** utf8_argv;
     160             :         WCHAR app_buffer[COMMAND_LINE_MAX];
     161             :         WCHAR cmd_buffer[COMMAND_LINE_MAX];
     162             :         DWORD res;
     163             :         int i;
     164             :         int pos;
     165             :         int mode;
     166             :         int ret;
     167             : 
     168             :         (void)argc;
     169             :         (void)argv;
     170             : 
     171             :         res = GetModuleFileNameW(NULL, app_buffer, sizeof(app_buffer));
     172             :         if (res == 0 || res >= sizeof(app_buffer)) {
     173             :                 exit(EXIT_FAILURE);
     174             :         }
     175             : 
     176             :         wide_argv = CommandLineToArgvW(GetCommandLineW(), &wide_argc);
     177             :         if (!wide_argv) {
     178             :                 exit(EXIT_FAILURE);
     179             :         }
     180             : 
     181             :         utf8_argc = 0;
     182             :         utf8_argv = malloc((wide_argc + 1) * sizeof(void*));
     183             :         if (!utf8_argv) {
     184             :                 exit(EXIT_FAILURE);
     185             :         }
     186             : 
     187             :         pos = argcat(cmd_buffer, sizeof(cmd_buffer), 0, app_buffer);
     188             :         if (pos < 0) {
     189             :                 exit(EXIT_FAILURE);
     190             :         }
     191             : 
     192             :         utf8_argv[0] = argutf8(app_buffer);
     193             :         if (!utf8_argv[0]) {
     194             :                 exit(EXIT_FAILURE);
     195             :         }
     196             :         utf8_argc = 1;
     197             : 
     198             :         mode = MODE_DEFAULT;
     199             :         for (i = 1; i < wide_argc; i++) {
     200             :                 if (wcscmp(wide_argv[i], L"-s") == 0 || wcscmp(wide_argv[i], L"--spin-down-on-error") == 0) {
     201             :                         mode = MODE_SPINDOWN;
     202             :                 } else {
     203             :                         pos = argcat(cmd_buffer, sizeof(cmd_buffer), pos, wide_argv[i]);
     204             :                         if (pos < 0) {
     205             :                                 exit(EXIT_FAILURE);
     206             :                         }
     207             :                         utf8_argv[utf8_argc] = argutf8(wide_argv[i]);
     208             :                         if (!utf8_argv[utf8_argc]) {
     209             :                                 exit(EXIT_FAILURE);
     210             :                         }
     211             :                         ++utf8_argc;
     212             :                 }
     213             :         }
     214             :         utf8_argv[utf8_argc] = 0;
     215             :         cmd_buffer[pos] = 0;
     216             : 
     217             :         LocalFree(wide_argv);
     218             : 
     219             :         if (mode == MODE_DEFAULT) {
     220             :                 ret = snapraid_main(utf8_argc, utf8_argv);
     221             :         } else {
     222             :                 STARTUPINFOW si;
     223             :                 PROCESS_INFORMATION pi;
     224             :                 DWORD wait;
     225             : 
     226             :                 /* install console control handler */
     227             :                 if (!SetConsoleCtrlHandler(console_handler, TRUE)) {
     228             :                         fprintf(stderr, "Failed to set console handler\n");
     229             :                         exit(EXIT_FAILURE);
     230             :                 }
     231             : 
     232             :                 ZeroMemory(&si, sizeof(si));
     233             :                 si.cb = sizeof(si);
     234             :                 ZeroMemory(&pi, sizeof(pi));
     235             : 
     236             :                 if (!CreateProcessW(app_buffer, cmd_buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
     237             :                         fprintf(stderr, "Failed to exec SnapRAID\n");
     238             :                         exit(EXIT_FAILURE);
     239             :                 }
     240             : 
     241             :                 /* store child process handle for signal handler */
     242             :                 child_process = pi.hProcess;
     243             : 
     244             :                 wait = WaitForSingleObject(pi.hProcess, INFINITE);
     245             :                 if (wait != WAIT_OBJECT_0) {
     246             :                         fprintf(stderr, "WaitForSingleObject failed: %lu\n", (unsigned long)GetLastError());
     247             :                         TerminateProcess(pi.hProcess, 1);
     248             :                         CloseHandle(pi.hThread);
     249             :                         CloseHandle(pi.hProcess);
     250             :                         return 1;
     251             :                 }
     252             : 
     253             :                 /* clear child process handle */
     254             :                 child_process = NULL;
     255             : 
     256             :                 if (!GetExitCodeProcess(pi.hProcess, &res)) {
     257             :                         fprintf(stderr, "GetExitCodeProcess failed: %lu\n", (unsigned long)GetLastError());
     258             :                         CloseHandle(pi.hThread);
     259             :                         CloseHandle(pi.hProcess);
     260             :                         return 1;
     261             :                 }
     262             : 
     263             :                 CloseHandle(pi.hThread);
     264             :                 CloseHandle(pi.hProcess);
     265             : 
     266             :                 ret = res;
     267             : 
     268             :                 if (ret != 0) {
     269             :                         char* spindown_argv[3];
     270             :                         spindown_argv[0] = utf8_argv[0];
     271             :                         spindown_argv[1] = "down";
     272             :                         spindown_argv[2] = 0;
     273             : 
     274             :                         /* sync all disks */
     275             :                         printf("Flush...\n");
     276             :                         if (sync() != 0)
     277             :                                 printf("WARNING! Failed to flush disks!\n");
     278             : 
     279             :                         snapraid_main(2, spindown_argv);
     280             :                 }
     281             :         }
     282             : 
     283             :         for (i = 0; i < utf8_argc; ++i)
     284             :                 free(utf8_argv[i]);
     285             :         free(utf8_argv);
     286             : 
     287             :         return ret;
     288             : }
     289             : #else
     290             : 
     291             : char full_argv0[PATH_MAX];
     292             : 
     293           1 : const char* get_argv0(const char* argv0)
     294             : {
     295           1 :         ssize_t len = readlink("/proc/self/exe", full_argv0, sizeof(full_argv0) - 1);
     296           1 :         if (len != -1) {
     297           1 :                 full_argv0[len] = '\0';
     298           1 :                 return full_argv0;
     299             :         } else {
     300             : #ifdef __APPLE__
     301             :                 uint32_t size = sizeof(full_argv0);
     302             :                 if (_NSGetExecutablePath(full_argv0, &size) == 0)
     303             :                         return full_argv0;
     304             : #endif
     305             :         }
     306           0 :         return argv0;
     307             : }
     308             : 
     309             : /* global variable to store child PID for signal handler */
     310             : static volatile pid_t child_pid = 0;
     311             : 
     312             : /* signal handler that forwards signals to child */
     313             : /* LCOV_EXCL_START */
     314             : static void forward_signal(int sig)
     315             : {
     316             :         if (child_pid > 0) {
     317             :                 kill(child_pid, sig);
     318             :         }
     319             : }
     320             : /* LCOV_EXCL_STOP */
     321             : 
     322         303 : int main(int argc, char* argv[])
     323             : {
     324             :         int mode;
     325             :         int i, j;
     326             :         int ret;
     327             : 
     328         303 :         mode = MODE_DEFAULT;
     329         303 :         j = 1;
     330        4467 :         for (i = 1; i < argc; ++i) {
     331        4164 :                 if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--spin-down-on-error") == 0) {
     332           1 :                         mode = MODE_SPINDOWN;
     333             :                 } else {
     334        4163 :                         argv[j] = argv[i];
     335        4163 :                         ++j;
     336             :                 }
     337             :         }
     338         303 :         argc = j;
     339         303 :         argv[argc] = 0;
     340             : 
     341         303 :         if (mode == MODE_DEFAULT) {
     342         302 :                 ret = snapraid_main(argc, argv);
     343             :         } else {
     344             :                 struct sigaction sa;
     345             : 
     346             :                 /* set up signal handler to ignore signals */
     347           1 :                 sa.sa_handler = forward_signal;
     348           1 :                 sigemptyset(&sa.sa_mask);
     349           1 :                 sa.sa_flags = SA_RESTART; /* restart interrupted system calls */
     350             : 
     351             :                 /* install forwarding handler for signals */
     352           1 :                 sigaction(SIGINT, &sa, NULL); /* Ctrl+C */
     353           1 :                 sigaction(SIGQUIT, &sa, NULL); /* Ctrl+\ */
     354           1 :                 sigaction(SIGTERM, &sa, NULL); /* termination */
     355           1 :                 sigaction(SIGHUP, &sa, NULL); /* hangup */
     356           1 :                 sigaction(SIGUSR1, &sa, NULL); /* user-defined 1 */
     357           1 :                 sigaction(SIGUSR2, &sa, NULL); /* user-defined 2 */
     358             : 
     359           1 :                 pid_t pid = fork();
     360           2 :                 if (pid == -1) {
     361             :                         /* LCOV_EXCL_START */
     362             :                         perror("Failed to fork SnapRAID");
     363             :                         exit(EXIT_FAILURE);
     364             :                         /* LCOV_EXCL_STOP */
     365             :                 }
     366             : 
     367           2 :                 if (pid == 0) {
     368             :                         /* child process */
     369             : 
     370             :                         /* restore default signal handlers */
     371           1 :                         signal(SIGINT, SIG_DFL);
     372           1 :                         signal(SIGQUIT, SIG_DFL);
     373           1 :                         signal(SIGTERM, SIG_DFL);
     374           1 :                         signal(SIGHUP, SIG_DFL);
     375           1 :                         signal(SIGUSR1, SIG_DFL);
     376           1 :                         signal(SIGUSR2, SIG_DFL);
     377             : 
     378           1 :                         execvp(get_argv0(argv[0]), argv);
     379             : 
     380             :                         /* here it's an error */
     381             :                         /* LCOV_EXCL_START */
     382             :                         perror("Failed to exec SnapRAID");
     383             :                         exit(EXIT_FAILURE);
     384             :                         /* LCOV_EXCL_STOP */
     385             :                 } else {
     386             :                         /* parent process */
     387             :                         int status;
     388             : 
     389             :                         /* store child PID so signal handler can forward signals */
     390           1 :                         child_pid = pid;
     391             : 
     392             :                         do {
     393           1 :                                 ret = waitpid(pid, &status, 0);
     394           1 :                         } while (ret == -1 && errno == EINTR); /* retry if interrupted by signal */
     395             : 
     396           1 :                         if (ret == -1) {
     397             :                                 /* LCOV_EXCL_START */
     398             :                                 perror("Failed to wait for SnapRAID");
     399             :                                 exit(EXIT_FAILURE);
     400             :                                 /* LCOV_EXCL_STOP */
     401             :                         }
     402             : 
     403             :                         /* clear child PID */
     404           1 :                         child_pid = 0;
     405             : 
     406             :                         /* restore default signal handlers */
     407           1 :                         signal(SIGINT, SIG_DFL);
     408           1 :                         signal(SIGQUIT, SIG_DFL);
     409           1 :                         signal(SIGTERM, SIG_DFL);
     410           1 :                         signal(SIGHUP, SIG_DFL);
     411           1 :                         signal(SIGUSR1, SIG_DFL);
     412           1 :                         signal(SIGUSR2, SIG_DFL);
     413             : 
     414           1 :                         if (WIFEXITED(status)) {
     415           1 :                                 ret = WEXITSTATUS(status);
     416           0 :                         } else if (WIFSIGNALED(status)) {
     417             :                                 /* terminated by signal */
     418           0 :                                 ret = 128 + WTERMSIG(status);
     419             :                         } else {
     420           0 :                                 ret = -1;
     421             :                         }
     422             : 
     423           1 :                         if (ret != 0) {
     424             :                                 char* spindown_argv[3];
     425           0 :                                 spindown_argv[0] = argv[0];
     426           0 :                                 spindown_argv[1] = "down";
     427           0 :                                 spindown_argv[2] = 0;
     428             : 
     429             :                                 /* ignore sigpipe to allow spindown even if the terminal is closed */
     430           0 :                                 signal(SIGPIPE, SIG_IGN);
     431             : 
     432             :                                 /* sync all disks */
     433           0 :                                 printf("Flush...\n");
     434             : 
     435           0 :                                 snapraid_main(2, spindown_argv);
     436             :                         }
     437             :                 }
     438             :         }
     439             : 
     440         270 :         return ret;
     441             : }
     442             : #endif
     443             : 

Generated by: LCOV version 1.0