merge: resolve dev (quality refactor) into security-fixes
- file.c split layout retained; security-hardened secure-fs helpers (open_secure_parent/to_disk_secure/rename_secure/stat_secure) now live in file.c with file_ prefix and are shared with file_receive.c - file_receive.c takes the security branch's bounded allocations (receive_data_limited, data_decompress_limited, size checks) and STATUS_ERROR signaling - file_send.c gains the data consistency check on file->data - client_validation.c: stricter --tls requiring --ca, log_message style - utils.c: hardened openat/mkdirat mkdir_r from security branch
This commit is contained in:
+195
-189
@@ -11,6 +11,7 @@
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -59,7 +60,7 @@ static bool parse_positive_int(const char* s, int* out_val) {
|
||||
static int set_string_option(char** dest, const char* value, const char* option_name) {
|
||||
char* dup = str_dup(value);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for %s\n", option_name);
|
||||
log_message(LOG_LEVEL_ERROR, "memory allocation failed for %s", option_name);
|
||||
return -1;
|
||||
}
|
||||
free(*dest);
|
||||
@@ -70,7 +71,7 @@ static int set_string_option(char** dest, const char* value, const char* option_
|
||||
/* Parse a string as a positive integer into *dest. Returns true on success, false on error. */
|
||||
static int set_positive_int_option(int* dest, const char* value, const char* option_name) {
|
||||
if (!parse_positive_int(value, dest)) {
|
||||
fprintf(stderr, "Error: %s must be a positive integer\n", option_name);
|
||||
log_message(LOG_LEVEL_ERROR, "%s must be a positive integer", option_name);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
@@ -79,7 +80,7 @@ static int set_positive_int_option(int* dest, const char* value, const char* opt
|
||||
/* Parse a string as a non-negative integer into *dest. Returns true on success, false on error. */
|
||||
static int set_nonneg_int_option(int* dest, const char* value, const char* option_name) {
|
||||
if (!parse_nonneg_int(value, dest)) {
|
||||
fprintf(stderr, "Error: %s must be a non-negative integer\n", option_name);
|
||||
log_message(LOG_LEVEL_ERROR, "%s must be a non-negative integer", option_name);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
@@ -87,105 +88,187 @@ static int set_nonneg_int_option(int* dest, const char* value, const char* optio
|
||||
|
||||
static int read_patterns_from_file(const char* filepath, char*** patterns, int* count);
|
||||
|
||||
/* Parse a string as an unsigned long long. Returns 0 on success, -1 on error. */
|
||||
static int parse_ull_arg(const char* val, unsigned long long* out, const char* optname) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long v = strtoull(val, &end, 10);
|
||||
if (errno != 0 || *end != '\0') {
|
||||
log_message(LOG_LEVEL_ERROR, "%s must be a non-negative integer", optname);
|
||||
return -1;
|
||||
}
|
||||
*out = v;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Append a duplicated pattern to a growable pattern array. Returns 0 on success, -1 on error. */
|
||||
static int config_add_pattern(char*** patterns, int* count, const char* value,
|
||||
const char* optname) {
|
||||
char** tmp = realloc(*patterns, (*count + 1) * sizeof(char*));
|
||||
if (!tmp) {
|
||||
log_message(LOG_LEVEL_ERROR, "memory allocation failed for %s", optname);
|
||||
return -1;
|
||||
}
|
||||
*patterns = tmp;
|
||||
char* dup = str_dup(value);
|
||||
if (!dup) {
|
||||
log_message(LOG_LEVEL_ERROR, "memory allocation failed for %s", optname);
|
||||
return -1;
|
||||
}
|
||||
(*patterns)[(*count)++] = dup;
|
||||
return 0;
|
||||
}
|
||||
|
||||
typedef enum {
|
||||
OPT_FLAG,
|
||||
OPT_STRING,
|
||||
OPT_POS_INT,
|
||||
OPT_NONNEG_INT,
|
||||
OPT_ULL,
|
||||
} OptKind;
|
||||
|
||||
typedef struct {
|
||||
const char* name;
|
||||
const char* alias;
|
||||
OptKind kind;
|
||||
size_t offset; /* offsetof of the target field in Config */
|
||||
} OptionEntry;
|
||||
|
||||
/* Options that map directly onto a Config field with no side effects. */
|
||||
static const OptionEntry OPTION_TABLE[] = {
|
||||
{"--dry-run", "-n", OPT_FLAG, offsetof(Config, dry_run)},
|
||||
{"--delete", NULL, OPT_FLAG, offsetof(Config, use_delete)},
|
||||
{"--incremental", NULL, OPT_FLAG, offsetof(Config, use_incremental)},
|
||||
{"--delta", NULL, OPT_FLAG, offsetof(Config, use_delta)},
|
||||
{"--save-to-disk", NULL, OPT_FLAG, offsetof(Config, save_to_disk)},
|
||||
{"--progress", NULL, OPT_FLAG, offsetof(Config, show_progress)},
|
||||
{"--tls", NULL, OPT_FLAG, offsetof(Config, use_tls)},
|
||||
{"--backup", NULL, OPT_FLAG, offsetof(Config, backup)},
|
||||
{"--stats", NULL, OPT_FLAG, offsetof(Config, stats)},
|
||||
{"--partial", NULL, OPT_FLAG, offsetof(Config, partial)},
|
||||
{"--links", "-l", OPT_FLAG, offsetof(Config, follow_symlinks)},
|
||||
{"--copy-links", NULL, OPT_FLAG, offsetof(Config, copy_links)},
|
||||
{"--safe-links", NULL, OPT_FLAG, offsetof(Config, safe_links)},
|
||||
{"--copy-unsafe-links", NULL, OPT_FLAG, offsetof(Config, copy_unsafe_links)},
|
||||
{"--sparse", "-S", OPT_FLAG, offsetof(Config, preserve_sparse)},
|
||||
{"--inplace", NULL, OPT_FLAG, offsetof(Config, inplace)},
|
||||
{"--checksum", NULL, OPT_FLAG, offsetof(Config, checksum)},
|
||||
|
||||
{"--source-dir", NULL, OPT_STRING, offsetof(Config, send_directory)},
|
||||
{"--dest-dir", NULL, OPT_STRING, offsetof(Config, receive_root_directory)},
|
||||
{"--server-host", NULL, OPT_STRING, offsetof(Config, server_host)},
|
||||
{"--cert", NULL, OPT_STRING, offsetof(Config, tls_cert)},
|
||||
{"--key", NULL, OPT_STRING, offsetof(Config, tls_key)},
|
||||
{"--ca", NULL, OPT_STRING, offsetof(Config, tls_ca)},
|
||||
{"--backup-dir", NULL, OPT_STRING, offsetof(Config, backup_dir)},
|
||||
{"--fastsync-server-path", NULL, OPT_STRING, offsetof(Config, fastsync_server_path)},
|
||||
{"--partial-dir", NULL, OPT_STRING, offsetof(Config, partial_dir)},
|
||||
{"--suffix", NULL, OPT_STRING, offsetof(Config, suffix)},
|
||||
|
||||
{"--timeout", NULL, OPT_POS_INT, offsetof(Config, timeout)},
|
||||
{"--contimeout", NULL, OPT_POS_INT, offsetof(Config, contimeout)},
|
||||
{"--max-depth", NULL, OPT_NONNEG_INT, offsetof(Config, max_depth)},
|
||||
|
||||
{"--max-size", NULL, OPT_ULL, offsetof(Config, max_size)},
|
||||
{"--min-size", NULL, OPT_ULL, offsetof(Config, min_size)},
|
||||
};
|
||||
|
||||
static bool opt_is(const char* arg, const char* name, const char* alias) {
|
||||
return strcmp(arg, name) == 0 || (alias && strcmp(arg, alias) == 0);
|
||||
}
|
||||
|
||||
static const OptionEntry* find_table_option(const char* arg) {
|
||||
for (size_t i = 0; i < sizeof(OPTION_TABLE) / sizeof(OPTION_TABLE[0]); i++)
|
||||
if (opt_is(arg, OPTION_TABLE[i].name, OPTION_TABLE[i].alias))
|
||||
return &OPTION_TABLE[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int apply_table_option(Config* config, const OptionEntry* entry, const char* value) {
|
||||
void* field = (char*)config + entry->offset;
|
||||
switch (entry->kind) {
|
||||
case OPT_FLAG:
|
||||
*(bool*)field = true;
|
||||
return 0;
|
||||
case OPT_STRING:
|
||||
return set_string_option((char**)field, value, entry->name);
|
||||
case OPT_POS_INT:
|
||||
return set_positive_int_option((int*)field, value, entry->name);
|
||||
case OPT_NONNEG_INT:
|
||||
return set_nonneg_int_option((int*)field, value, entry->name);
|
||||
case OPT_ULL: {
|
||||
unsigned long long v;
|
||||
if (parse_ull_arg(value, &v, entry->name) != 0)
|
||||
return -1;
|
||||
*(unsigned long long*)field = v;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Parse CLI arguments into config. Returns 0 on success, -1 on error, 1 for help/clean-exit. */
|
||||
int parse_args(Config* config, int argc, char* argv[], int* positional_args,
|
||||
int* positional_count) {
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--help") == 0) {
|
||||
const OptionEntry* entry = find_table_option(argv[i]);
|
||||
if (entry) {
|
||||
if (entry->kind != OPT_FLAG) {
|
||||
if (i + 1 >= argc) {
|
||||
log_message(LOG_LEVEL_ERROR, "missing argument for %s", entry->name);
|
||||
return -1;
|
||||
}
|
||||
if (apply_table_option(config, entry, argv[++i]) != 0)
|
||||
return -1;
|
||||
} else if (apply_table_option(config, entry, NULL) != 0) {
|
||||
return -1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (opt_is(argv[i], "--help", NULL)) {
|
||||
print_usage();
|
||||
return 1;
|
||||
} else if (strcmp(argv[i], "-V") == 0 || strcmp(argv[i], "--version") == 0) {
|
||||
} else if (opt_is(argv[i], "-V", "--version")) {
|
||||
printf("fastsync version %s\n", PROTOCOL_VERSION);
|
||||
return 1;
|
||||
} else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--archive") == 0) {
|
||||
} else if (opt_is(argv[i], "-a", "--archive")) {
|
||||
config->use_compression = true;
|
||||
config->use_multithreading = true;
|
||||
config->use_metadata = true;
|
||||
log_message(LOG_LEVEL_INFO, "Enabled archive mode (-c -m -M)");
|
||||
} else if (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--dry-run") == 0) {
|
||||
config->dry_run = true;
|
||||
} else if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) {
|
||||
} else if (opt_is(argv[i], "-p", NULL) && i + 1 < argc) {
|
||||
if (set_positive_int_option(&config->ssh_port, argv[++i], "-p") != 0)
|
||||
return -1;
|
||||
if (config->ssh_port > 65535) {
|
||||
log_message(LOG_LEVEL_ERROR, "SSH port must be 1-65535\n");
|
||||
log_message(LOG_LEVEL_ERROR, "SSH port must be 1-65535");
|
||||
return -1;
|
||||
}
|
||||
} else if (strcmp(argv[i], "--delete") == 0) {
|
||||
config->use_delete = true;
|
||||
} else if (strcmp(argv[i], "--exclude") == 0 && i + 1 < argc) {
|
||||
char** tmp = realloc(config->exclude_patterns, (config->exclude_count + 1) * sizeof(char*));
|
||||
if (!tmp) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --exclude\n");
|
||||
} else if (opt_is(argv[i], "--exclude", NULL) && i + 1 < argc) {
|
||||
if (config_add_pattern(&config->exclude_patterns, &config->exclude_count, argv[++i],
|
||||
"--exclude") != 0)
|
||||
return -1;
|
||||
}
|
||||
config->exclude_patterns = tmp;
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --exclude\n");
|
||||
} else if (opt_is(argv[i], "--include", NULL) && i + 1 < argc) {
|
||||
if (config_add_pattern(&config->include_patterns, &config->include_count, argv[++i],
|
||||
"--include") != 0)
|
||||
return -1;
|
||||
}
|
||||
config->exclude_patterns[config->exclude_count++] = dup;
|
||||
} else if (strcmp(argv[i], "--include") == 0 && i + 1 < argc) {
|
||||
char** tmp = realloc(config->include_patterns, (config->include_count + 1) * sizeof(char*));
|
||||
if (!tmp) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --include\n");
|
||||
} else if (opt_is(argv[i], "--delta-block", NULL) && i + 1 < argc) {
|
||||
unsigned long long val;
|
||||
if (parse_ull_arg(argv[++i], &val, "--delta-block") != 0)
|
||||
return -1;
|
||||
}
|
||||
config->include_patterns = tmp;
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --include\n");
|
||||
return -1;
|
||||
}
|
||||
config->include_patterns[config->include_count++] = dup;
|
||||
} else if (strcmp(argv[i], "--max-size") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long val = strtoull(argv[++i], &end, 10);
|
||||
if (errno != 0 || *end != '\0') {
|
||||
fprintf(stderr, "Error: --max-size must be a non-negative integer\n");
|
||||
return -1;
|
||||
}
|
||||
config->max_size = val;
|
||||
} else if (strcmp(argv[i], "--min-size") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long val = strtoull(argv[++i], &end, 10);
|
||||
if (errno != 0 || *end != '\0') {
|
||||
fprintf(stderr, "Error: --min-size must be a non-negative integer\n");
|
||||
return -1;
|
||||
}
|
||||
config->min_size = val;
|
||||
} else if (strcmp(argv[i], "--incremental") == 0) {
|
||||
config->use_incremental = true;
|
||||
} else if (strcmp(argv[i], "--delta") == 0) {
|
||||
config->use_delta = true;
|
||||
} else if (strcmp(argv[i], "--delta-block") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long val = strtoull(argv[++i], &end, 10);
|
||||
if (errno != 0 || *end != '\0') {
|
||||
fprintf(stderr, "Error: --delta-block must be a positive integer\n");
|
||||
return -1;
|
||||
}
|
||||
if (val >= DELTA_BLOCK_SIZE_MIN && val <= DELTA_BLOCK_SIZE_MAX)
|
||||
config->delta_block_size = (uint32_t)val;
|
||||
else
|
||||
fprintf(stderr, "Warning: --delta-block value %llu out of range, using default\n", val);
|
||||
} else if (strcmp(argv[i], "--delta-max") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long val = strtoull(argv[++i], &end, 10);
|
||||
if (errno != 0 || *end != '\0') {
|
||||
fprintf(stderr, "Error: --delta-max must be a positive integer\n");
|
||||
log_message(LOG_LEVEL_WARNING, "--delta-block value %llu out of range, using default", val);
|
||||
} else if (opt_is(argv[i], "--delta-max", NULL) && i + 1 < argc) {
|
||||
unsigned long long val;
|
||||
if (parse_ull_arg(argv[++i], &val, "--delta-max") != 0)
|
||||
return -1;
|
||||
}
|
||||
if (val >= DELTA_MIN_FILE_SIZE)
|
||||
config->delta_max_file_size = val;
|
||||
else
|
||||
fprintf(stderr, "Warning: --delta-max value %llu too small, using default\n", val);
|
||||
} else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "-z") == 0) {
|
||||
log_message(LOG_LEVEL_WARNING, "--delta-max value %llu too small, using default", val);
|
||||
} else if (opt_is(argv[i], "-c", "-z")) {
|
||||
config->use_compression = true;
|
||||
log_message(LOG_LEVEL_INFO, "Enabled Compression");
|
||||
if (i + 1 < argc) {
|
||||
@@ -193,7 +276,7 @@ int parse_args(Config* config, int argc, char* argv[], int* positional_args,
|
||||
long level = strtol(argv[i + 1], &end_ptr, 10);
|
||||
if (*end_ptr == '\0') {
|
||||
if (level < 1 || level > 22) {
|
||||
fprintf(stderr, "Error: compression level must be 1-22\n");
|
||||
log_message(LOG_LEVEL_ERROR, "compression level must be 1-22");
|
||||
return -1;
|
||||
}
|
||||
config->compression_level = (int)level;
|
||||
@@ -201,91 +284,51 @@ int parse_args(Config* config, int argc, char* argv[], int* positional_args,
|
||||
i++;
|
||||
}
|
||||
}
|
||||
} else if (strcmp(argv[i], "--source-dir") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->send_directory, argv[++i], "--source-dir") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--dest-dir") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->receive_root_directory, argv[++i], "--dest-dir") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--save-to-disk") == 0) {
|
||||
config->save_to_disk = true;
|
||||
} else if (strcmp(argv[i], "-M") == 0 || strcmp(argv[i], "--preserve") == 0) {
|
||||
} else if (opt_is(argv[i], "-M", "--preserve")) {
|
||||
config->use_metadata = true;
|
||||
log_message(LOG_LEVEL_INFO, "Enabled metadata preservation");
|
||||
} else if (strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--sendfile") == 0) {
|
||||
} else if (opt_is(argv[i], "-f", "--sendfile")) {
|
||||
config->use_sendfile = true;
|
||||
log_message(LOG_LEVEL_INFO, "Enabled sendfile");
|
||||
} else if (strcmp(argv[i], "-m") == 0) {
|
||||
} else if (opt_is(argv[i], "-m", NULL)) {
|
||||
config->use_multithreading = true;
|
||||
log_message(LOG_LEVEL_INFO, "Enabled Multithreading");
|
||||
} else if (strcmp(argv[i], "-s") == 0) {
|
||||
} else if (opt_is(argv[i], "-s", NULL)) {
|
||||
config->use_chunk_serialization = true;
|
||||
log_message(LOG_LEVEL_INFO, "Enabled Chunk Serialization");
|
||||
} else if (strcmp(argv[i], "--server-host") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->server_host, argv[++i], "--server-host") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--server-port") == 0 && i + 1 < argc) {
|
||||
} else if (opt_is(argv[i], "--server-port", NULL) && i + 1 < argc) {
|
||||
if (!parse_positive_int(argv[++i], &config->server_port)) {
|
||||
fprintf(stderr, "Error: invalid --server-port value: %s\n", argv[i]);
|
||||
log_message(LOG_LEVEL_ERROR, "invalid --server-port value: %s", argv[i]);
|
||||
return -1;
|
||||
}
|
||||
if (config->server_port > 65535) {
|
||||
fprintf(stderr, "Error: server port must be 1-65535\n");
|
||||
log_message(LOG_LEVEL_ERROR, "server port must be 1-65535");
|
||||
return -1;
|
||||
}
|
||||
} else if (strcmp(argv[i], "--bwlimit") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long kbps = strtoull(argv[++i], &end, 10);
|
||||
if (errno != 0 || *end != '\0' || kbps == 0) {
|
||||
fprintf(stderr, "Error: --bwlimit must be a positive integer\n");
|
||||
} else if (opt_is(argv[i], "--bwlimit", NULL) && i + 1 < argc) {
|
||||
unsigned long long kbps;
|
||||
if (parse_ull_arg(argv[++i], &kbps, "--bwlimit") != 0)
|
||||
return -1;
|
||||
if (kbps == 0) {
|
||||
log_message(LOG_LEVEL_ERROR, "--bwlimit must be a positive integer");
|
||||
return -1;
|
||||
}
|
||||
if (kbps > ULLONG_MAX / 1024) {
|
||||
fprintf(stderr, "Error: --bwlimit value too large\n");
|
||||
log_message(LOG_LEVEL_ERROR, "--bwlimit value too large");
|
||||
return -1;
|
||||
}
|
||||
io_set_bwlimit(kbps * 1024);
|
||||
log_message(LOG_LEVEL_INFO, "Set bandwidth limit to %llu KB/s", kbps);
|
||||
} else if (strcmp(argv[i], "--progress") == 0) {
|
||||
config->show_progress = true;
|
||||
} else if (strcmp(argv[i], "--chunk-size") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long val = strtoull(argv[++i], &end, 10);
|
||||
if (errno != 0 || *end != '\0' || val == 0) {
|
||||
fprintf(stderr, "Error: --chunk-size must be a positive integer\n");
|
||||
} else if (opt_is(argv[i], "--chunk-size", NULL) && i + 1 < argc) {
|
||||
unsigned long long val;
|
||||
if (parse_ull_arg(argv[++i], &val, "--chunk-size") != 0)
|
||||
return -1;
|
||||
if (val == 0) {
|
||||
log_message(LOG_LEVEL_ERROR, "--chunk-size must be a positive integer");
|
||||
return -1;
|
||||
}
|
||||
config->chunk_size = val;
|
||||
} else if (strcmp(argv[i], "--tls") == 0) {
|
||||
config->use_tls = true;
|
||||
} else if (strcmp(argv[i], "--cert") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->tls_cert, argv[++i], "--cert") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--key") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->tls_key, argv[++i], "--key") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--ca") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->tls_ca, argv[++i], "--ca") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--timeout") == 0 && i + 1 < argc) {
|
||||
if (set_positive_int_option(&config->timeout, argv[++i], "--timeout") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--contimeout") == 0 && i + 1 < argc) {
|
||||
if (set_positive_int_option(&config->contimeout, argv[++i], "--contimeout") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--backup") == 0) {
|
||||
config->backup = true;
|
||||
} else if (strcmp(argv[i], "--backup-dir") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->backup_dir, argv[++i], "--backup-dir") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--stats") == 0) {
|
||||
config->stats = true;
|
||||
} else if (strcmp(argv[i], "--max-depth") == 0 && i + 1 < argc) {
|
||||
if (set_nonneg_int_option(&config->max_depth, argv[++i], "--max-depth") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--log-file") == 0 && i + 1 < argc) {
|
||||
} else if (opt_is(argv[i], "--log-file", NULL) && i + 1 < argc) {
|
||||
if (config->log_file) {
|
||||
fclose(config->log_file);
|
||||
config->log_file = NULL;
|
||||
@@ -293,55 +336,29 @@ int parse_args(Config* config, int argc, char* argv[], int* positional_args,
|
||||
}
|
||||
FILE* lf = fopen(argv[++i], "a");
|
||||
if (!lf) {
|
||||
fprintf(stderr, "Error: could not open log file '%s': %s\n", argv[i], strerror(errno));
|
||||
log_message(LOG_LEVEL_ERROR, "could not open log file '%s': %s", argv[i], strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
config->log_file = lf;
|
||||
log_set_file(lf);
|
||||
} else if (strcmp(argv[i], "--exclude-from") == 0 && i + 1 < argc) {
|
||||
} else if (opt_is(argv[i], "--exclude-from", NULL) && i + 1 < argc) {
|
||||
if (read_patterns_from_file(argv[++i], &config->exclude_patterns, &config->exclude_count) !=
|
||||
0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--include-from") == 0 && i + 1 < argc) {
|
||||
} else if (opt_is(argv[i], "--include-from", NULL) && i + 1 < argc) {
|
||||
if (read_patterns_from_file(argv[++i], &config->include_patterns, &config->include_count) !=
|
||||
0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--partial") == 0) {
|
||||
config->partial = true;
|
||||
} else if (strcmp(argv[i], "--fastsync-server-path") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->fastsync_server_path, argv[++i], "--fastsync-server-path") !=
|
||||
0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
|
||||
} else if (opt_is(argv[i], "-v", "--verbose")) {
|
||||
set_log_level(LOG_LEVEL_DEBUG);
|
||||
} else if (strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "--links") == 0) {
|
||||
config->follow_symlinks = true;
|
||||
} else if (strcmp(argv[i], "--copy-links") == 0) {
|
||||
config->copy_links = true;
|
||||
} else if (strcmp(argv[i], "--safe-links") == 0) {
|
||||
config->safe_links = true;
|
||||
} else if (strcmp(argv[i], "--copy-unsafe-links") == 0) {
|
||||
config->copy_unsafe_links = true;
|
||||
} else if (strcmp(argv[i], "-S") == 0 || strcmp(argv[i], "--sparse") == 0) {
|
||||
config->preserve_sparse = true;
|
||||
} else if (strcmp(argv[i], "--inplace") == 0) {
|
||||
config->inplace = true;
|
||||
} else if (strcmp(argv[i], "--partial-dir") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->partial_dir, argv[++i], "--partial-dir") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--suffix") == 0 && i + 1 < argc) {
|
||||
if (set_string_option(&config->suffix, argv[++i], "--suffix") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "-T") == 0 && i + 1 < argc) {
|
||||
} else if (opt_is(argv[i], "-T", NULL) && i + 1 < argc) {
|
||||
if (set_positive_int_option(&config->timeout, argv[++i], "-T") != 0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--checksum") == 0) {
|
||||
config->checksum = true;
|
||||
} else if (strcmp(argv[i], "--compress-level") == 0 && i + 1 < argc) {
|
||||
} else if (opt_is(argv[i], "--compress-level", NULL) && i + 1 < argc) {
|
||||
if (set_positive_int_option(&config->compression_level, argv[++i], "--compress-level") != 0)
|
||||
return -1;
|
||||
if (config->compression_level < 1 || config->compression_level > 22) {
|
||||
fprintf(stderr, "Error: --compress-level must be between 1 and 22\n");
|
||||
log_message(LOG_LEVEL_ERROR, "--compress-level must be between 1 and 22");
|
||||
return -1;
|
||||
}
|
||||
} else if (argv[i][0] == '-') {
|
||||
@@ -364,7 +381,7 @@ int parse_args(Config* config, int argc, char* argv[], int* positional_args,
|
||||
static int read_patterns_from_file(const char* filepath, char*** patterns, int* count) {
|
||||
FILE* fp = fopen(filepath, "r");
|
||||
if (!fp) {
|
||||
fprintf(stderr, "Error: could not open pattern file '%s': %s\n", filepath, strerror(errno));
|
||||
log_message(LOG_LEVEL_ERROR, "could not open pattern file '%s': %s", filepath, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
char* line = NULL;
|
||||
@@ -381,22 +398,11 @@ static int read_patterns_from_file(const char* filepath, char*** patterns, int*
|
||||
p[--len] = '\0';
|
||||
if (len == 0)
|
||||
continue;
|
||||
char** tmp = realloc(*patterns, (*count + 1) * sizeof(char*));
|
||||
if (!tmp) {
|
||||
fprintf(stderr, "Error: memory allocation failed for pattern file\n");
|
||||
if (config_add_pattern(patterns, count, p, "pattern file") != 0) {
|
||||
free(line);
|
||||
fclose(fp);
|
||||
return -1;
|
||||
}
|
||||
*patterns = tmp;
|
||||
char* dup = str_dup(p);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for pattern file\n");
|
||||
free(line);
|
||||
fclose(fp);
|
||||
return -1;
|
||||
}
|
||||
(*patterns)[(*count)++] = dup;
|
||||
}
|
||||
free(line);
|
||||
fclose(fp);
|
||||
@@ -413,7 +419,7 @@ int main(int argc, char* argv[]) {
|
||||
int exit_code = 0;
|
||||
Config* config = config_create();
|
||||
if (!config) {
|
||||
fprintf(stderr, "Error: failed to allocate config\n");
|
||||
log_message(LOG_LEVEL_ERROR, "failed to allocate config");
|
||||
return 1;
|
||||
}
|
||||
config->save_to_disk = save_to_disk;
|
||||
@@ -434,20 +440,20 @@ int main(int argc, char* argv[]) {
|
||||
free(config->receive_root_directory);
|
||||
config->send_directory = str_dup(argv[positional_args[0]]);
|
||||
if (!config->send_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
log_message(LOG_LEVEL_ERROR, "memory allocation failed");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
config->receive_root_directory = str_dup(argv[positional_args[1]]);
|
||||
if (!config->receive_root_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
log_message(LOG_LEVEL_ERROR, "memory allocation failed");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
config->save_to_disk = true;
|
||||
config_parse_ssh_dest(config);
|
||||
} else if (positional_count == 1) {
|
||||
fprintf(stderr, "Error: missing destination argument\n");
|
||||
log_message(LOG_LEVEL_ERROR, "missing destination argument");
|
||||
print_usage();
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
@@ -455,7 +461,7 @@ int main(int argc, char* argv[]) {
|
||||
if (!config->send_directory && env_source) {
|
||||
config->send_directory = str_dup(env_source);
|
||||
if (!config->send_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
log_message(LOG_LEVEL_ERROR, "memory allocation failed");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
@@ -463,7 +469,7 @@ int main(int argc, char* argv[]) {
|
||||
if (!config->receive_root_directory && env_dest) {
|
||||
config->receive_root_directory = str_dup(env_dest);
|
||||
if (!config->receive_root_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
log_message(LOG_LEVEL_ERROR, "memory allocation failed");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
+47
-49
@@ -42,7 +42,7 @@ static ScannerOptions scanner_options_from_config(const Config* config, int num_
|
||||
static Client* connect_transfer_client(const Config* config) {
|
||||
if (config->transport == TRANSPORT_SSH) {
|
||||
if (config->use_sendfile) {
|
||||
fprintf(stderr, "Error: -f/--sendfile is not supported with SSH transport\n");
|
||||
log_message(LOG_LEVEL_ERROR, "-f/--sendfile is not supported with SSH transport");
|
||||
return NULL;
|
||||
}
|
||||
return client_connect_ssh(config->ssh_destination, config->ssh_port,
|
||||
@@ -384,8 +384,8 @@ static int send_chunks_multithreaded(void* pipeline_context) {
|
||||
Client* client = connect_transfer_client(context->config);
|
||||
if (!client) {
|
||||
if (context->config->transport == TRANSPORT_TCP)
|
||||
fprintf(stderr, "Error: could not connect to server%s\n",
|
||||
context->config->use_tls ? " via TLS" : "");
|
||||
log_message(LOG_LEVEL_ERROR, "could not connect to server%s",
|
||||
context->config->use_tls ? " via TLS" : "");
|
||||
pipeline_cancel(context);
|
||||
mark_sender_done(context);
|
||||
return thrd_error;
|
||||
@@ -432,7 +432,7 @@ static int send_chunks_multithreaded(void* pipeline_context) {
|
||||
return thrd_error;
|
||||
}
|
||||
if (send_chunk(client, current_chunk, context->config) != 0) {
|
||||
fprintf(stderr, "Error: unexpected error while sending chunk\n");
|
||||
log_message(LOG_LEVEL_ERROR, "unexpected error while sending chunk");
|
||||
chunk_destroy(current_chunk);
|
||||
pipeline_cancel(context);
|
||||
disconnect_transfer_client(client);
|
||||
@@ -544,6 +544,17 @@ static int load_files_multithreaded(void* pipeline_context) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Print a one-line transfer progress report to stderr. `suffix` ends the
|
||||
line (e.g. "Done.\n") or is "" for in-place refresh. Shared by the
|
||||
single-threaded loop and the multithreaded progress thread. */
|
||||
static void print_transfer_progress(unsigned long long total_bytes, time_t start,
|
||||
const char* suffix) {
|
||||
double elapsed = difftime(time(NULL), start);
|
||||
double rate = elapsed > 0.0 ? total_bytes / (1048576.0 * elapsed) : 0.0;
|
||||
fprintf(stderr, "\rSent %.1f MB (%.1f MB/s) %s", total_bytes / 1048576.0, rate, suffix);
|
||||
fflush(stderr);
|
||||
}
|
||||
|
||||
/* Progress-reporting thread for multithreaded send. Runs in parallel with
|
||||
the scanner/loader/sender threads and prints periodic progress to stderr. */
|
||||
static int progress_thread_fn(void* arg) {
|
||||
@@ -558,20 +569,14 @@ static int progress_thread_fn(void* arg) {
|
||||
mtx_unlock(&context->mutex_progress);
|
||||
|
||||
if (done) {
|
||||
time_t now = time(NULL);
|
||||
double elapsed = difftime(now, start);
|
||||
double rate = elapsed > 0.0 ? total / (1048576.0 * elapsed) : 0.0;
|
||||
fprintf(stderr, "\rSent %.1f MB (%.1f MB/s) Done.\n", total / 1048576.0, rate);
|
||||
print_transfer_progress(total, start, "Done.\n");
|
||||
break;
|
||||
}
|
||||
|
||||
time_t now = time(NULL);
|
||||
if (now - last_progress >= 1) {
|
||||
last_progress = now;
|
||||
double elapsed = difftime(now, start);
|
||||
double rate = elapsed > 0.0 ? total / (1048576.0 * elapsed) : 0.0;
|
||||
fprintf(stderr, "\rSent %.1f MB (%.1f MB/s) ", total / 1048576.0, rate);
|
||||
fflush(stderr);
|
||||
print_transfer_progress(total, start, "");
|
||||
}
|
||||
|
||||
struct timespec ts = {0, 100 * 1000000L}; /* 100 ms */
|
||||
@@ -587,36 +592,29 @@ int send_files(Config* config) {
|
||||
Client* client = connect_transfer_client(config);
|
||||
if (!client) {
|
||||
if (config->transport == TRANSPORT_TCP)
|
||||
fprintf(stderr, "Error: could not connect to server%s\n", config->use_tls ? " via TLS" : "");
|
||||
log_message(LOG_LEVEL_ERROR, "could not connect to server%s",
|
||||
config->use_tls ? " via TLS" : "");
|
||||
return 1;
|
||||
}
|
||||
ProtocolSession session;
|
||||
protocol_session_init(&session, client->file_descriptor, client->file_descriptor);
|
||||
protocol_session_set_ssl(&session, (SSL*)client->ssl);
|
||||
protocol_session_bind(&session);
|
||||
if (!config_send(client->file_descriptor, config)) {
|
||||
disconnect_transfer_client(client);
|
||||
protocol_session_unbind();
|
||||
return 1;
|
||||
}
|
||||
int ret = 1;
|
||||
DirectoryScanner* scanner = NULL;
|
||||
ArrayList* manifest = NULL;
|
||||
if (!config_send(client->file_descriptor, config))
|
||||
goto send_fail;
|
||||
ScannerOptions scanner_options = scanner_options_from_config(config, 0);
|
||||
DirectoryScanner* scanner =
|
||||
directory_scanner_create_with_options(config->send_directory, &scanner_options);
|
||||
scanner = directory_scanner_create_with_options(config->send_directory, &scanner_options);
|
||||
manifest = create_transfer_manifest(config);
|
||||
if (!scanner || (config->use_delete && !manifest))
|
||||
goto send_fail;
|
||||
Chunk* current_chunk;
|
||||
unsigned long long total_bytes = 0;
|
||||
int total_files = 0;
|
||||
time_t last_progress = 0;
|
||||
time_t start = time(NULL);
|
||||
ArrayList* manifest = create_transfer_manifest(config);
|
||||
if (!scanner || (config->use_delete && !manifest)) {
|
||||
if (scanner)
|
||||
directory_scanner_destroy(scanner);
|
||||
if (manifest)
|
||||
array_list_delete(manifest);
|
||||
disconnect_transfer_client(client);
|
||||
protocol_session_unbind();
|
||||
return 1;
|
||||
}
|
||||
while ((current_chunk = directory_scanner_next(scanner)) != NULL) {
|
||||
unsigned long long chunk_bytes = 0;
|
||||
for (int i = 0; i < current_chunk->element_count; i++) {
|
||||
@@ -628,16 +626,21 @@ int send_files(Config* config) {
|
||||
goto send_fail;
|
||||
}
|
||||
if (!config->use_sendfile) {
|
||||
bool load_ok = true;
|
||||
for (int i = 0; i < current_chunk->element_count; i++) {
|
||||
File* f = current_chunk->items[i];
|
||||
if (f->data->size > STREAM_THRESHOLD && !config->use_compression)
|
||||
continue;
|
||||
if (!file_load_data(f)) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to load file data");
|
||||
chunk_destroy(current_chunk);
|
||||
goto send_fail;
|
||||
load_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!load_ok) {
|
||||
chunk_destroy(current_chunk);
|
||||
goto send_fail;
|
||||
}
|
||||
}
|
||||
if (send_chunk(client, current_chunk, config) != 0) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to send chunk");
|
||||
@@ -652,10 +655,7 @@ int send_files(Config* config) {
|
||||
time_t now = time(NULL);
|
||||
if (now - last_progress >= 1) {
|
||||
last_progress = now;
|
||||
double elapsed = difftime(now, start);
|
||||
double rate = elapsed > 0 ? total_bytes / (1048576.0 * elapsed) : 0;
|
||||
fprintf(stderr, "\rSent %.1f MB (%.1f MB/s) ", total_bytes / 1048576.0, rate);
|
||||
fflush(stderr);
|
||||
print_transfer_progress(total_bytes, start, "");
|
||||
}
|
||||
}
|
||||
chunk_destroy(current_chunk);
|
||||
@@ -672,28 +672,26 @@ int send_files(Config* config) {
|
||||
manifest = NULL;
|
||||
}
|
||||
bool ok = finalize_transfer(client);
|
||||
double elapsed_total = difftime(time(NULL), start);
|
||||
if (config->show_progress) {
|
||||
double rate = elapsed_total > 0 ? total_bytes / (1048576.0 * elapsed_total) : 0;
|
||||
fprintf(stderr, "\rSent %.1f MB (%.1f MB/s) Done.\n", total_bytes / 1048576.0, rate);
|
||||
}
|
||||
if (config->show_progress)
|
||||
print_transfer_progress(total_bytes, start, "Done.\n");
|
||||
if (config->stats) {
|
||||
double elapsed_total = difftime(time(NULL), start);
|
||||
double rate = elapsed_total > 0 ? total_bytes / (1048576.0 * elapsed_total) : 0;
|
||||
fprintf(stderr, "Stats: %d files, %.1f MB, %.1f MB/s\n", total_files, total_bytes / 1048576.0,
|
||||
rate);
|
||||
}
|
||||
directory_scanner_destroy(scanner);
|
||||
disconnect_transfer_client(client);
|
||||
protocol_session_unbind();
|
||||
return ok ? 0 : 1;
|
||||
ret = ok ? 0 : 1;
|
||||
|
||||
send_fail:
|
||||
/* Single cleanup path for all exits. The manifest is intentionally deleted
|
||||
here even on success without --delete, fixing a pre-existing leak. */
|
||||
if (manifest)
|
||||
array_list_delete(manifest);
|
||||
directory_scanner_destroy(scanner);
|
||||
if (scanner)
|
||||
directory_scanner_destroy(scanner);
|
||||
disconnect_transfer_client(client);
|
||||
protocol_session_unbind();
|
||||
return 1;
|
||||
return ret;
|
||||
}
|
||||
|
||||
int send_files_multithreaded(Config** config_ptr) {
|
||||
@@ -750,7 +748,7 @@ int send_files_multithreaded(Config** config_ptr) {
|
||||
sender_created = (thrd_create(&sender, send_chunks_multithreaded, context) == thrd_success);
|
||||
|
||||
if (!scanner_created || !loader_created || !sender_created) {
|
||||
perror("Error creating threads.\n");
|
||||
log_perror("Error creating threads");
|
||||
pipeline_cancel(context);
|
||||
mtx_lock(&context->mutex_progress);
|
||||
context->sender_done = true;
|
||||
@@ -770,7 +768,7 @@ int send_files_multithreaded(Config** config_ptr) {
|
||||
if (config->show_progress) {
|
||||
progress_created = (thrd_create(&progress, progress_thread_fn, context) == thrd_success);
|
||||
if (!progress_created) {
|
||||
perror("Error creating progress thread.\n");
|
||||
log_perror("Error creating progress thread");
|
||||
/* Non-fatal; continue without progress reporting */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,38 @@
|
||||
#include "client_validation.h"
|
||||
#include "log.h"
|
||||
#include "usage.h"
|
||||
#include <stdio.h>
|
||||
|
||||
/* Validate config after parsing. Returns true if valid. */
|
||||
bool validate_config(const Config* config) {
|
||||
if (!config->send_directory || !config->receive_root_directory) {
|
||||
fprintf(stderr, "Error: source and destination directories are required\n");
|
||||
log_message(LOG_LEVEL_ERROR, "source and destination directories are required");
|
||||
print_usage();
|
||||
return false;
|
||||
}
|
||||
if (config->use_sendfile && (config->use_chunk_serialization || config->use_compression)) {
|
||||
fprintf(stderr, "Error: -f/--sendfile cannot be combined with -c (compression) or -s (chunk "
|
||||
"serialization)\n");
|
||||
log_message(LOG_LEVEL_ERROR, "-f/--sendfile cannot be combined with -c (compression) or -s "
|
||||
"(chunk serialization)");
|
||||
return false;
|
||||
}
|
||||
if (config->transport == TRANSPORT_SSH && config->use_sendfile) {
|
||||
fprintf(stderr, "Error: -f/--sendfile is not supported with SSH transport\n");
|
||||
log_message(LOG_LEVEL_ERROR, "-f/--sendfile is not supported with SSH transport");
|
||||
return false;
|
||||
}
|
||||
if (config->use_incremental && config->use_chunk_serialization) {
|
||||
fprintf(stderr, "Error: --incremental is not supported with -s (chunk serialization)\n");
|
||||
log_message(LOG_LEVEL_ERROR, "--incremental is not supported with -s (chunk serialization)");
|
||||
return false;
|
||||
}
|
||||
if (config->use_delta && !config->use_incremental) {
|
||||
fprintf(stderr, "Error: --delta requires --incremental\n");
|
||||
log_message(LOG_LEVEL_ERROR, "--delta requires --incremental");
|
||||
return false;
|
||||
}
|
||||
if (config->use_delta && config->use_chunk_serialization) {
|
||||
fprintf(stderr, "Error: --delta cannot be combined with -s (chunk serialization)\n");
|
||||
log_message(LOG_LEVEL_ERROR, "--delta cannot be combined with -s (chunk serialization)");
|
||||
return false;
|
||||
}
|
||||
if (config->use_delta && config->use_sendfile) {
|
||||
fprintf(stderr, "Error: --delta cannot be combined with -f (sendfile)\n");
|
||||
log_message(LOG_LEVEL_ERROR, "--delta cannot be combined with -f (sendfile)");
|
||||
return false;
|
||||
}
|
||||
if (config->append || config->append_verify) {
|
||||
@@ -42,7 +43,7 @@ bool validate_config(const Config* config) {
|
||||
}
|
||||
if (config->use_tls) {
|
||||
if (!config->tls_cert || !config->tls_key || !config->tls_ca) {
|
||||
fprintf(stderr, "Error: --tls requires --cert, --key, and --ca\n");
|
||||
log_message(LOG_LEVEL_ERROR, "--tls requires --cert, --key, and --ca");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+223
-198
@@ -1,3 +1,4 @@
|
||||
#include "log.h"
|
||||
#include "scanner.h"
|
||||
#include "array_list.h"
|
||||
#include "chunk.h"
|
||||
@@ -226,7 +227,7 @@ static int open_next_directory(DirectoryScanner* scanner) {
|
||||
free(de);
|
||||
scanner->current_dir = opendir(scanner->current_path);
|
||||
if (scanner->current_dir == NULL) {
|
||||
perror("Could not open directory");
|
||||
log_perror("Could not open directory");
|
||||
free(scanner->current_path);
|
||||
scanner->current_path = NULL;
|
||||
scanner->failed = true;
|
||||
@@ -412,18 +413,11 @@ static void parallel_scanner_creation_failed(ParallelScanner* ps) {
|
||||
mtx_unlock(&ps->result_mutex);
|
||||
}
|
||||
|
||||
ParallelScanner* parallel_scanner_create_with_options(const char* root_directory,
|
||||
const ScannerOptions* options) {
|
||||
if (!root_directory || !options)
|
||||
return NULL;
|
||||
ParallelScanner* ps = calloc(1, sizeof(ParallelScanner));
|
||||
if (!ps)
|
||||
return NULL;
|
||||
/* Initialize result queue and synchronization primitives. Returns true on success. */
|
||||
static bool parallel_scanner_init(ParallelScanner* ps) {
|
||||
ps->result_queue = queue_create(100, chunk_destroy);
|
||||
if (!ps->result_queue) {
|
||||
free(ps);
|
||||
return NULL;
|
||||
}
|
||||
if (!ps->result_queue)
|
||||
return false;
|
||||
atomic_init(&ps->cancelled, false);
|
||||
int init = 0;
|
||||
bool ok = true;
|
||||
@@ -448,14 +442,220 @@ ParallelScanner* parallel_scanner_create_with_options(const char* root_directory
|
||||
if (init >= 1)
|
||||
mtx_destroy(&ps->result_mutex);
|
||||
queue_destroy(ps->result_queue);
|
||||
free(ps);
|
||||
ps->result_queue = NULL;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Split files into chunks of roughly chunk_size bytes. Returns the first chunk (also stored
|
||||
* chunks beyond the first are enqueued on `queue`). Nulls out consumed entries in `files`.
|
||||
* Sets *failed on allocation/enqueue errors. */
|
||||
static Chunk* batch_files(ArrayList* files, unsigned long long chunk_size, Queue* queue,
|
||||
bool* failed) {
|
||||
Chunk* first = NULL;
|
||||
if (files->size <= 0)
|
||||
return NULL;
|
||||
ArrayList* batch = array_list_create(NULL);
|
||||
if (!batch) {
|
||||
*failed = true;
|
||||
return NULL;
|
||||
}
|
||||
unsigned long long batch_size = 0;
|
||||
for (int i = 0; i < files->size; i++) {
|
||||
File* f = (File*)files->items[i];
|
||||
if (!array_list_add(batch, f)) {
|
||||
*failed = true;
|
||||
break;
|
||||
}
|
||||
batch_size += f->data->size;
|
||||
if (batch_size >= chunk_size || i == files->size - 1) {
|
||||
void** items = array_list_to_array(batch);
|
||||
if (!items) {
|
||||
*failed = true;
|
||||
array_list_delete(batch);
|
||||
batch = NULL;
|
||||
break;
|
||||
}
|
||||
Chunk* c = chunk_create((File**)items, batch->size);
|
||||
free(items);
|
||||
if (!c) {
|
||||
*failed = true;
|
||||
array_list_delete(batch);
|
||||
batch = NULL;
|
||||
break;
|
||||
}
|
||||
int batch_start = i - batch->size + 1;
|
||||
for (int j = batch_start; j <= i; j++)
|
||||
files->items[j] = NULL;
|
||||
batch->item_destroyer = NULL;
|
||||
array_list_delete(batch);
|
||||
batch = NULL;
|
||||
if (!first) {
|
||||
first = c;
|
||||
} else {
|
||||
if (!queue_enqueue(queue, c)) {
|
||||
chunk_destroy(c);
|
||||
*failed = true;
|
||||
}
|
||||
}
|
||||
if (i < files->size - 1) {
|
||||
batch = array_list_create(NULL);
|
||||
if (!batch) {
|
||||
*failed = true;
|
||||
break;
|
||||
}
|
||||
batch_size = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (batch) {
|
||||
batch->item_destroyer = NULL;
|
||||
array_list_delete(batch);
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
/* Scan one root-directory entry into either the subdirs or files list. */
|
||||
static void scan_root_entry(const ScannerOptions* options, const char* root_directory,
|
||||
const struct dirent* entry, ArrayList* root_files, ArrayList* subdirs,
|
||||
ParallelScanner* ps) {
|
||||
ScannerEntry inspected;
|
||||
int inspection =
|
||||
scanner_inspect_entry(options, root_directory, root_directory, entry->d_name, &inspected);
|
||||
if (inspection < 0) {
|
||||
ps->failed = true;
|
||||
return;
|
||||
}
|
||||
if (inspection == 0)
|
||||
return;
|
||||
char* cur_path = inspected.path;
|
||||
struct stat st = inspected.stats;
|
||||
if (inspected.is_directory) {
|
||||
if (!array_list_add(subdirs, cur_path)) {
|
||||
free(cur_path);
|
||||
ps->failed = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
File* file = file_create(cur_path);
|
||||
free(cur_path);
|
||||
if (!file) {
|
||||
ps->failed = true;
|
||||
return;
|
||||
}
|
||||
file->data->size = st.st_size;
|
||||
if (options->use_metadata)
|
||||
file->metadata = file_metadata_create(&st);
|
||||
if (options->use_metadata && !file->metadata) {
|
||||
file_destroy(file);
|
||||
ps->failed = true;
|
||||
return;
|
||||
}
|
||||
if (!array_list_add(root_files, file)) {
|
||||
file_destroy(file);
|
||||
ps->failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* Scan the root directory itself, collecting root files and subdirectories.
|
||||
* Returns false if the root directory could not be opened. */
|
||||
static bool scan_root_directory(ParallelScanner* ps, const char* root_directory,
|
||||
const ScannerOptions* options, ArrayList* root_files,
|
||||
ArrayList* subdirs) {
|
||||
DIR* dir = opendir(root_directory);
|
||||
if (!dir) {
|
||||
perror("Could not open root directory for parallel scan");
|
||||
parallel_scanner_destroy(ps);
|
||||
log_perror("Could not open root directory for parallel scan");
|
||||
return false;
|
||||
}
|
||||
const struct dirent* entry;
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
|
||||
continue;
|
||||
scan_root_entry(options, root_directory, entry, root_files, subdirs, ps);
|
||||
}
|
||||
closedir(dir);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Spawn worker threads, one per group of subdirectories. */
|
||||
static void spawn_parallel_workers(ParallelScanner* ps, ArrayList* subdirs,
|
||||
const ScannerOptions* options, unsigned long long cs) {
|
||||
if (subdirs->size <= 0)
|
||||
return;
|
||||
int n = options->num_threads > 0 ? options->num_threads : 4;
|
||||
if (n > subdirs->size)
|
||||
n = subdirs->size;
|
||||
|
||||
ps->num_threads = n;
|
||||
ps->expected_threads = n;
|
||||
ps->threads = calloc(n, sizeof(thrd_t));
|
||||
if (!ps->threads) {
|
||||
ps->num_threads = 0;
|
||||
ps->expected_threads = 0;
|
||||
ps->failed = true;
|
||||
return;
|
||||
}
|
||||
int dirs_per_thread = subdirs->size / n;
|
||||
int remainder = subdirs->size % n;
|
||||
int start = 0;
|
||||
ps->num_threads = 0;
|
||||
for (int t = 0; t < n; t++) {
|
||||
int count = dirs_per_thread + (t < remainder ? 1 : 0);
|
||||
if (count == 0)
|
||||
break;
|
||||
ParallelWorkerArg* wa = calloc(1, sizeof(ParallelWorkerArg));
|
||||
if (!wa) {
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
wa->ps = ps;
|
||||
wa->dirs = calloc(count, sizeof(char*));
|
||||
if (!wa->dirs) {
|
||||
free(wa);
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
bool dup_ok = true;
|
||||
for (int j = 0; j < count; j++) {
|
||||
wa->dirs[j] = str_dup((char*)subdirs->items[start + j]);
|
||||
if (!wa->dirs[j])
|
||||
dup_ok = false;
|
||||
}
|
||||
if (!dup_ok) {
|
||||
for (int j = 0; j < count; j++)
|
||||
free(wa->dirs[j]);
|
||||
free(wa->dirs);
|
||||
free(wa);
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
wa->dir_count = count;
|
||||
wa->options = *options;
|
||||
wa->options.chunk_size = cs;
|
||||
start += count;
|
||||
if (thrd_create(&ps->threads[t], parallel_worker_thread, wa) != thrd_success) {
|
||||
for (int j = 0; j < count; j++)
|
||||
free(wa->dirs[j]);
|
||||
free(wa->dirs);
|
||||
free(wa);
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
ps->num_threads++;
|
||||
ps->created_threads++;
|
||||
}
|
||||
}
|
||||
|
||||
ParallelScanner* parallel_scanner_create_with_options(const char* root_directory,
|
||||
const ScannerOptions* options) {
|
||||
if (!root_directory || !options)
|
||||
return NULL;
|
||||
ParallelScanner* ps = calloc(1, sizeof(ParallelScanner));
|
||||
if (!ps)
|
||||
return NULL;
|
||||
if (!parallel_scanner_init(ps)) {
|
||||
free(ps);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -464,201 +664,26 @@ ParallelScanner* parallel_scanner_create_with_options(const char* root_directory
|
||||
if (!root_files || !subdirs) {
|
||||
array_list_delete(root_files);
|
||||
array_list_delete(subdirs);
|
||||
closedir(dir);
|
||||
parallel_scanner_destroy(ps);
|
||||
return NULL;
|
||||
}
|
||||
const struct dirent* entry;
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
|
||||
continue;
|
||||
ScannerEntry inspected;
|
||||
int inspection =
|
||||
scanner_inspect_entry(options, root_directory, root_directory, entry->d_name, &inspected);
|
||||
if (inspection < 0) {
|
||||
ps->failed = true;
|
||||
continue;
|
||||
}
|
||||
if (inspection == 0)
|
||||
continue;
|
||||
char* cur_path = inspected.path;
|
||||
struct stat st = inspected.stats;
|
||||
if (inspected.is_directory) {
|
||||
if (!array_list_add(subdirs, cur_path)) {
|
||||
free(cur_path);
|
||||
ps->failed = true;
|
||||
}
|
||||
} else {
|
||||
File* file = file_create(cur_path);
|
||||
free(cur_path);
|
||||
if (!file) {
|
||||
ps->failed = true;
|
||||
continue;
|
||||
}
|
||||
file->data->size = st.st_size;
|
||||
if (options->use_metadata)
|
||||
file->metadata = file_metadata_create(&st);
|
||||
if (options->use_metadata && !file->metadata) {
|
||||
file_destroy(file);
|
||||
ps->failed = true;
|
||||
continue;
|
||||
}
|
||||
if (!array_list_add(root_files, file)) {
|
||||
file_destroy(file);
|
||||
ps->failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!scan_root_directory(ps, root_directory, options, root_files, subdirs)) {
|
||||
array_list_delete(root_files);
|
||||
array_list_delete(subdirs);
|
||||
parallel_scanner_destroy(ps);
|
||||
return NULL;
|
||||
}
|
||||
closedir(dir);
|
||||
|
||||
unsigned long long cs = options->chunk_size > 0 ? options->chunk_size : DESIRED_CHUNK_SIZE;
|
||||
if (root_files->size > 0) {
|
||||
ArrayList* batch = array_list_create(NULL);
|
||||
if (!batch) {
|
||||
ps->failed = true;
|
||||
array_list_delete(root_files);
|
||||
array_list_delete(subdirs);
|
||||
parallel_scanner_destroy(ps);
|
||||
return NULL;
|
||||
}
|
||||
unsigned long long batch_size = 0;
|
||||
Chunk* first = NULL;
|
||||
for (int i = 0; i < root_files->size; i++) {
|
||||
File* f = (File*)root_files->items[i];
|
||||
if (!array_list_add(batch, f)) {
|
||||
ps->failed = true;
|
||||
break;
|
||||
}
|
||||
batch_size += f->data->size;
|
||||
if (batch_size >= cs || i == root_files->size - 1) {
|
||||
void** items = array_list_to_array(batch);
|
||||
if (!items) {
|
||||
ps->failed = true;
|
||||
array_list_delete(batch);
|
||||
batch = NULL;
|
||||
break;
|
||||
}
|
||||
Chunk* c = chunk_create((File**)items, batch->size);
|
||||
free(items);
|
||||
if (!c) {
|
||||
ps->failed = true;
|
||||
array_list_delete(batch);
|
||||
batch = NULL;
|
||||
break;
|
||||
}
|
||||
int batch_start = i - batch->size + 1;
|
||||
for (int j = batch_start; j <= i; j++)
|
||||
root_files->items[j] = NULL;
|
||||
batch->item_destroyer = NULL;
|
||||
array_list_delete(batch);
|
||||
batch = NULL;
|
||||
if (!first) {
|
||||
first = c;
|
||||
} else {
|
||||
if (!queue_enqueue(ps->result_queue, c)) {
|
||||
chunk_destroy(c);
|
||||
ps->failed = true;
|
||||
}
|
||||
}
|
||||
if (i < root_files->size - 1) {
|
||||
batch = array_list_create(NULL);
|
||||
if (!batch) {
|
||||
ps->failed = true;
|
||||
break;
|
||||
}
|
||||
batch_size = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (batch) {
|
||||
batch->item_destroyer = NULL;
|
||||
array_list_delete(batch);
|
||||
}
|
||||
ps->initial_chunk = first;
|
||||
}
|
||||
ps->initial_chunk = batch_files(root_files, cs, ps->result_queue, &ps->failed);
|
||||
array_list_delete(root_files);
|
||||
|
||||
int n = options->num_threads > 0 ? options->num_threads : 4;
|
||||
if (n > subdirs->size)
|
||||
n = subdirs->size > 0 ? subdirs->size : 1;
|
||||
|
||||
if (subdirs->size > 0) {
|
||||
ps->num_threads = n;
|
||||
ps->expected_threads = n;
|
||||
ps->threads = calloc(n, sizeof(thrd_t));
|
||||
if (!ps->threads) {
|
||||
array_list_delete(subdirs);
|
||||
parallel_scanner_destroy(ps);
|
||||
return NULL;
|
||||
}
|
||||
int dirs_per_thread = subdirs->size / n;
|
||||
int remainder = subdirs->size % n;
|
||||
int start = 0;
|
||||
ps->num_threads = 0;
|
||||
for (int t = 0; t < n; t++) {
|
||||
int count = dirs_per_thread + (t < remainder ? 1 : 0);
|
||||
if (count == 0)
|
||||
break;
|
||||
ParallelWorkerArg* wa = calloc(1, sizeof(ParallelWorkerArg));
|
||||
if (!wa) {
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
wa->ps = ps;
|
||||
wa->dirs = calloc(count, sizeof(char*));
|
||||
if (!wa->dirs) {
|
||||
free(wa);
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
bool dup_ok = true;
|
||||
for (int j = 0; j < count; j++) {
|
||||
wa->dirs[j] = str_dup((char*)subdirs->items[start + j]);
|
||||
if (!wa->dirs[j])
|
||||
dup_ok = false;
|
||||
}
|
||||
if (!dup_ok) {
|
||||
for (int j = 0; j < count; j++)
|
||||
free(wa->dirs[j]);
|
||||
free(wa->dirs);
|
||||
free(wa);
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
wa->dir_count = count;
|
||||
wa->options = *options;
|
||||
wa->options.chunk_size = cs;
|
||||
start += count;
|
||||
if (thrd_create(&ps->threads[t], parallel_worker_thread, wa) != thrd_success) {
|
||||
for (int j = 0; j < count; j++)
|
||||
free(wa->dirs[j]);
|
||||
free(wa->dirs);
|
||||
free(wa);
|
||||
parallel_scanner_creation_failed(ps);
|
||||
break;
|
||||
}
|
||||
ps->num_threads++;
|
||||
ps->created_threads++;
|
||||
}
|
||||
}
|
||||
spawn_parallel_workers(ps, subdirs, options, cs);
|
||||
array_list_delete(subdirs);
|
||||
return ps;
|
||||
}
|
||||
|
||||
ParallelScanner* parallel_scanner_create(const char* root_directory, bool use_metadata,
|
||||
unsigned long long chunk_size, char** exclude_patterns,
|
||||
int exclude_count, char** include_patterns,
|
||||
int include_count, unsigned long long max_size,
|
||||
unsigned long long min_size, int max_depth,
|
||||
int num_threads, bool follow_symlinks, bool copy_links,
|
||||
bool safe_links, bool copy_unsafe_links, bool checksum) {
|
||||
ScannerOptions options = {use_metadata, chunk_size, exclude_patterns, exclude_count,
|
||||
include_patterns, include_count, max_size, min_size,
|
||||
max_depth, num_threads, follow_symlinks, copy_links,
|
||||
safe_links, copy_unsafe_links, checksum};
|
||||
return parallel_scanner_create_with_options(root_directory, &options);
|
||||
}
|
||||
|
||||
Chunk* parallel_scanner_next(ParallelScanner* ps) {
|
||||
if (ps->initial_chunk) {
|
||||
Chunk* c = ps->initial_chunk;
|
||||
|
||||
@@ -77,13 +77,6 @@ Chunk* directory_scanner_next(DirectoryScanner* scanner);
|
||||
bool directory_scanner_failed(const DirectoryScanner* scanner);
|
||||
void directory_scanner_destroy(DirectoryScanner* scanner);
|
||||
|
||||
ParallelScanner* parallel_scanner_create(const char* root_directory, bool use_metadata,
|
||||
unsigned long long chunk_size, char** exclude_patterns,
|
||||
int exclude_count, char** include_patterns,
|
||||
int include_count, unsigned long long max_size,
|
||||
unsigned long long min_size, int max_depth,
|
||||
int num_threads, bool follow_symlinks, bool copy_links,
|
||||
bool safe_links, bool copy_unsafe_links, bool checksum);
|
||||
ParallelScanner* parallel_scanner_create_with_options(const char* root_directory,
|
||||
const ScannerOptions* options);
|
||||
Chunk* parallel_scanner_next(ParallelScanner* scanner);
|
||||
|
||||
Reference in New Issue
Block a user