support for hidding sidecar files.
[rrq/fuse_xattrs.git] / utils.c
1 /*
2   fuse_xattrs - Add xattrs support using sidecar files
3
4   Copyright (C) 2016  Felipe Barriga Richards <felipe {at} felipebarriga.cl>
5
6   This program can be distributed under the terms of the GNU GPL.
7   See the file COPYING.
8 */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "utils.h"
15 #include "fuse_xattrs_config.h"
16
17 char *prepend_source_directory(const char *a, const char *b) {
18     size_t len = strlen(a) + strlen(b) + 1;
19     char *dst = (char*) malloc(sizeof(char) * len);
20     sprintf(dst, "%s%s", a, b);
21
22     return dst;
23 }
24
25 char *get_sidecar_path(const char *path)
26 {
27     const size_t path_len = strlen(path);
28     const size_t sidecar_ext_len = strlen(BINARY_SIDECAR_EXT); // this can be optimized
29     const size_t sidecar_path_len = path_len + sidecar_ext_len + 1;
30     char *sidecar_path = (char *) malloc(sidecar_path_len);
31     memset(sidecar_path, '\0', sidecar_path_len);
32     memcpy(sidecar_path, path, path_len);
33     memcpy(sidecar_path + path_len, BINARY_SIDECAR_EXT, sidecar_ext_len);
34
35     return sidecar_path;
36 }
37
38 // TODO: make it work for binary data
39 char *sanitize_value(const char *value, size_t value_size)
40 {
41     char *sanitized = malloc(value_size + 1);
42     memcpy(sanitized, value, value_size);
43     sanitized[value_size] = '\0';
44     return sanitized;
45 }
46
47
48 const size_t BINARY_SIDECAR_EXT_SIZE = strlen(BINARY_SIDECAR_EXT);
49
50 const int filename_is_sidecar(const char *string) {
51     if(string == NULL)
52         return 0;
53
54     size_t size = strlen(string);
55     if (size <= BINARY_SIDECAR_EXT_SIZE)
56         return 0;
57
58     if (memcmp(string+size-BINARY_SIDECAR_EXT_SIZE, BINARY_SIDECAR_EXT, BINARY_SIDECAR_EXT_SIZE) == 0) {
59         return 1;
60     }
61
62     return 0;
63 }
64
65 enum namespace get_namespace(const char *name) {
66     if (strncmp(name, "user.", strlen("user.")) == 0) {
67         return USER;
68     }
69
70     if (strncmp(name, "system.", strlen("system.")) == 0) {
71         return SYSTEM;
72     }
73
74     if (strncmp(name, "security.", strlen("security.")) == 0) {
75         return SECURITY;
76     }
77
78     if (strncmp(name, "trusted.", strlen("trusted.")) == 0) {
79         return TRUSTED;
80     }
81
82     error_print("invalid namespace for key: %s\n", name);
83     return ERROR;
84 }