deployd/server/cmd.c
Arija A. d878187ccd
Begin work on client
Signed-off-by: Arija A. <ari@ari.lt>
2025-07-24 02:38:50 +03:00

132 lines
2.7 KiB
C

#include "include/conf.h"
#include "include/cmd.h"
#include <ctype.h>
#ifdef DP_WITH_READLINE
#include <stdio.h>
#include <readline/history.h>
#include <readline/readline.h>
#else
#include <stdio.h>
#include <string.h>
#endif
int dp_parse_line(char *line, char *argv[], int max_args) {
int argc = 0;
char *ptr = line;
while (*ptr && argc < max_args) {
/* Skip whitespace */
while (*ptr && (*ptr == ' ' || *ptr == '\t')) {
++ptr;
}
if (!*ptr) {
break;
}
if (*ptr == '"') {
++ptr;
argv[argc++] = ptr;
while (*ptr && *ptr != '"') {
++ptr;
}
if (*ptr == '"') {
*ptr = '\0';
++ptr;
}
} else {
argv[argc++] = ptr;
while (*ptr && *ptr != ' ' && *ptr != '\t') {
++ptr;
}
if (*ptr) {
*ptr = '\0';
++ptr;
}
}
}
return argc;
}
size_t dp_read_line(const char *prompt, char *input, size_t input_size) {
if (input_size == 0) {
return 0;
}
#ifdef DP_WITH_READLINE
char *line = readline(prompt);
if (!line) {
return false;
}
if (*line) {
add_history(line);
}
strncpy(input, line, input_size - 1);
input[input_size - 1] = '\0';
free(line);
return strlen(input);
#else
if (prompt) {
(void)fputs(prompt, stdout);
(void)fflush(stdout);
}
if (!fgets(input, (int)input_size, stdin)) {
return false;
}
size_t len = strlen(input);
while (len > 0 && (input[len - 1] == '\n' || input[len - 1] == '\r')) {
input[--len] = '\0';
}
return len;
#endif
}
uint64_t dp_parse_duration_to_seconds(const char *str) {
if (!str) {
return 0;
}
if (strcmp(str, "0") == 0) {
return 0;
}
size_t len = strlen(str);
if (len < 2) {
return 0; // invalid, treat as no expiration
}
char unit = (char)tolower(str[len - 1]);
char number_part[32] = {0};
if (len - 1 >= sizeof(number_part)) {
return 0;
}
memcpy(number_part, str, len - 1);
number_part[len - 1] = 0;
int num = atoi(number_part);
if (num <= 0) {
return 0;
}
switch (unit) {
case 'h': return (uint64_t)num * (uint64_t)3600ULL;
case 'd': return (uint64_t)num * (uint64_t)86400ULL;
case 'm': return (uint64_t)num * (uint64_t)30ULL * (uint64_t)86400ULL;
case 'y': return (uint64_t)num * (uint64_t)365ULL * (uint64_t)86400ULL;
default: return 0;
}
}