From b27e9dd37d67d5a74ae307ae25a41361c1d22cfd Mon Sep 17 00:00:00 2001 From: Tristan Riehs Date: Sat, 3 Jan 2026 22:36:58 +0100 Subject: Handle decryption when exporting --- src/main.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/main.c b/src/main.c index 1593db5..10805f2 100644 --- a/src/main.c +++ b/src/main.c @@ -252,9 +252,19 @@ static void __strbuild(char *buf, int size, assert(len >= 0); } -/* Convenience wrapper for __strbuild. */ +/* Convenience wrappers for __strbuild. */ #define strbuild(buf, fmt, ...) \ __strbuild(buf, sizeof(buf), __FILE__, __LINE__, fmt, __VA_ARGS__) +#define strbuild_with_size(buf, size, fmt, ...) \ + __strbuild(buf, size, __FILE__, __LINE__, fmt, __VA_ARGS__) + +static int str_has_suffix(const char *str, const char *suffix) +{ + int str_len = strlen(str); + int suffix_len = strlen(suffix); + return ((str_len > suffix_len) + && (strcmp(str + str_len - suffix_len, suffix) == 0)); +} /* Compute something that identifies the content of FILE. Algorithm by Dan Bernstein from http://www.cse.yorku.ca/~oz/hash.html via @@ -381,6 +391,38 @@ static void ftag_file_get_extension(char *out, int size, const char *file) sqlite3_close(db); } +/* Get the path to FILE in the ftag database. */ +static void ftag_file_get_path(char *out, int size, const char *file) +{ + struct stat st; + int rc; + /* look for the encrypted version first */ + strbuild_with_size(out, size, "%s/files/%s.gpg", FTAG_ROOT, file); + rc = stat(out, &st); + if (rc == 0) { + return; + } + else if (rc == -1 && errno != ENOENT) { + fprintf(stderr, "stat: %s:", out); + perror(""); + exit(EXIT_FAILURE); + } + /* look for the clear version after */ + out[strlen(out) - 4] = '\0'; /* remove ".gpg" extension */ + rc = stat(out, &st); + if (rc == 0) { + return; + } + else if (rc == -1 && errno != ENOENT) { + fprintf(stderr, "stat: %s:", out); + perror(""); + exit(EXIT_FAILURE); + } + fprintf(stderr, + "ftag export: cannot find \"%s\" in the database\n", file); + exit(EXIT_FAILURE); +} + static void ftag_export(int argc, char **argv) { if (argc != 1) { @@ -412,12 +454,17 @@ static void ftag_export(int argc, char **argv) while ((line_len = getline(&line, &line_size, stdin)) != -1) { remove_ending_newline(line); ftag_file_get_extension(extension, sizeof(extension), line); - strbuild(in, "%s/files/%s", FTAG_ROOT, line); + ftag_file_get_path(in, sizeof(in), line); + if (strlen(extension) > 0) strbuild(out, "%s/%s.%s", tmp_dir, line, extension); else strbuild(out, "%s/%s", tmp_dir, line); - copy_file(in, out); + + if (str_has_suffix(in, ".gpg")) + copy_file_with_encryption(in, out, DECRYPT); + else + copy_file(in, out); } free(line); -- cgit v1.2.3