summaryrefslogtreecommitdiff
path: root/src/encryption.c
blob: c7928d8efbec0ff80e30646183631d9e82466be9 (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
#define _GNU_SOURCE

#include "encryption.h"
#include "shared.h"

#include <sodium.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <unistd.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <stdio.h>

int checkSodium(void) {
    int ret = sodium_init();
    if(ret < 0)
        error(1, ENOTSUP, "Couldn't initialize sodium for some reason. Quitting...");

    return ret;
}

// To encrypt:
// 1- Create a temp file with the correct name in the root folder of the partition being encrypted
    // 1.1- Detect the partition and find the root folder
    // 1.2- Create the temp file with the correct name 
// 2- Encrypt the file's contents to the temp file
    // 2.1- Open the file
    // 2.2- Stream the file's contents into some encryption algo
    // 2.3- Pipe the output of the encryption into the temp file
// 3- Once the file has been encrypted, hard link it back to the original location
// 4- Delete the original file
// 5- Delete the temp file


int maketmp(const char *dest, const char *format, ...) {
    char *filename = NULL, *fullpath = NULL;
    struct stat fb;
    int fd = -1;
    va_list ap;

    // Make sure the destination exists and is a directory
    if(stat(dest, &fb) < 0)
        return -1;
    if(!S_ISDIR(fb.st_mode))
        return -2;

    // Get the first half of the filename
    va_start(ap, format);
    if(vasprintf(&filename, format, ap) < 0)
        return -3;
    va_end(ap);

    // Get the second half of the filename
    int fps = asprintf(&fullpath, "%s%s", dest, filename); // Hack to not duplicate `free(filename)`
    free(filename);
    if(fps < 0)
        return -4;

    // Open the temp file
    if((fd = open(dest, (O_WRONLY | O_CLOEXEC | O_CREAT | O_TMPFILE), S_IWUSR)) < 0)
        fd = -5;

    free(fullpath);
    return fd;
}



int main(int argc, char *argv[]) {
    if(argc != 3)
        error(1, 0, "USAGE: <dest> <filename>");


    int fd = maketmp(argv[1], "%s.test", argv[2]);
    if(fd < 0)
        error(1, errno, "Couldn't open temp file");

    return 0;
}