Encrypt data blocks being stored to S3.
[bluesky.git] / bluesky / inode.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2009  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 #include <stdint.h>
10 #include <glib.h>
11 #include <string.h>
12
13 #include "bluesky.h"
14
15 /* Core filesystem.  Different proxies, such as the NFSv3 one, interface to
16  * this, but the core actually tracks the data which is stored.  So far we just
17  * implement an in-memory filesystem, but eventually this will be state which
18  * is persisted to the cloud. */
19
20 /* Return the current time, in microseconds since the epoch. */
21 int64_t bluesky_get_current_time()
22 {
23     GTimeVal t;
24     g_get_current_time(&t);
25     return (int64_t)t.tv_sec * 1000000 + t.tv_usec;
26 }
27
28 /* Update an inode to indicate that a modification was made.  This increases
29  * the change counter, updates the ctime to the current time, and optionally
30  * updates the mtime. */
31 void bluesky_inode_update_ctime(BlueSkyInode *inode, gboolean update_mtime)
32 {
33     int64_t now = bluesky_get_current_time();
34     inode->change_count++;
35     inode->ctime = now;
36     if (update_mtime)
37         inode->mtime = now;
38 }
39
40 /* Compute the HMAC keyed-hash function using the given hash algorithm, data,
41  * and key. */
42 void compute_hmac(GChecksumType algo,
43                   const guchar *data, gsize data_len,
44                   const guchar *key, gsize key_len,
45                   guint8 *buffer, gsize *digest_len)
46 {
47     int block_size;
48
49     switch (algo) {
50     case G_CHECKSUM_MD5:
51     case G_CHECKSUM_SHA1:
52     case G_CHECKSUM_SHA256:
53         block_size = 64;
54         break;
55     default:
56         g_error("Unknown hash algorithm for HMAC: %d\n", algo);
57     }
58
59     gsize digest_size = g_checksum_type_get_length(algo);
60
61     guchar keybuf[block_size];
62     memset(keybuf, 0, block_size);
63     memcpy(keybuf, key, MIN(block_size, key_len));
64     for (int i = 0; i < block_size; i++)
65         keybuf[i] ^= 0x36;
66
67     GChecksum *csum1 = g_checksum_new(algo);
68     g_checksum_update(csum1, keybuf, block_size);
69     g_checksum_update(csum1, data, data_len);
70     guint8 digest[digest_size];
71     g_checksum_get_digest(csum1, digest, &digest_size);
72
73     memset(keybuf, 0, block_size);
74     memcpy(keybuf, key, MIN(block_size, key_len));
75     for (int i = 0; i < block_size; i++)
76         keybuf[i] ^= 0x5c;
77
78     GChecksum *csum2 = g_checksum_new(algo);
79     g_checksum_update(csum2, keybuf, block_size);
80     g_checksum_update(csum2, digest, digest_size);
81
82     g_checksum_get_digest(csum2, buffer, digest_len);
83
84     g_checksum_free(csum1);
85     g_checksum_free(csum2);
86 }
87
88 /* Unfortunately a glib hash table is only guaranteed to be able to store
89  * 32-bit keys if we use the key directly.  If we want 64-bit inode numbers,
90  * we'll have to allocate memory to store the 64-bit inumber, and use a pointer
91  * to it.  Rather than allocate the memory for the key, we'll just include a
92  * pointer to the 64-bit inum stored in the inode itself, so that we don't need
93  * to do any more memory management.  */
94 static guint bluesky_fs_key_hash_func(gconstpointer key)
95 {
96     uint64_t inum = *(const uint64_t *)key;
97     return (guint)inum;
98 }
99
100 static gboolean bluesky_fs_key_equal_func(gconstpointer a, gconstpointer b)
101 {
102     uint64_t i1 = *(const uint64_t *)a;
103     uint64_t i2 = *(const uint64_t *)b;
104     return i1 == i2;
105 }
106
107 /* Filesystem-level operations.  A filesystem is like a directory tree that we
108  * are willing to export. */
109 BlueSkyFS *bluesky_new_fs(gchar *name)
110 {
111     BlueSkyFS *fs = g_new0(BlueSkyFS, 1);
112     fs->lock = g_mutex_new();
113     fs->name = g_strdup(name);
114     fs->inodes = g_hash_table_new(bluesky_fs_key_hash_func,
115                                   bluesky_fs_key_equal_func);
116     fs->next_inum = BLUESKY_ROOT_INUM + 1;
117     fs->store = s3store_new();
118
119     return fs;
120 }
121
122 /* Inode reference counting. */
123 void bluesky_inode_ref(BlueSkyInode *inode)
124 {
125     g_atomic_int_inc(&inode->refcount);
126 }
127
128 void bluesky_inode_unref(BlueSkyInode *inode)
129 {
130     if (g_atomic_int_dec_and_test(&inode->refcount)) {
131         g_error("Reference count for inode %lld dropped to zero!\n",
132                 inode->inum);
133     }
134 }
135
136 /* Allocate a fresh inode number which has not been used before within a
137  * filesystem. */
138 uint64_t bluesky_fs_alloc_inode(BlueSkyFS *fs)
139 {
140     uint64_t inum;
141
142     g_mutex_lock(fs->lock);
143     inum = fs->next_inum;
144     fs->next_inum++;
145     g_mutex_unlock(fs->lock);
146
147     return inum;
148 }
149
150 BlueSkyInode *bluesky_new_inode(uint64_t inum, BlueSkyFS *fs,
151                                 BlueSkyFileType type)
152 {
153     BlueSkyInode *i = g_new0(BlueSkyInode, 1);
154
155     i->lock = g_mutex_new();
156     i->refcount = 1;
157     i->type = type;
158     i->fs = fs;
159     i->inum = inum;
160
161     switch (type) {
162     case BLUESKY_REGULAR:
163         i->blocks = g_array_new(FALSE, TRUE, sizeof(BlueSkyBlock));
164         break;
165     case BLUESKY_DIRECTORY:
166         i->dirents = g_sequence_new(bluesky_dirent_destroy);
167         i->dirhash = g_hash_table_new(g_str_hash, g_str_equal);
168         break;
169     case BLUESKY_BLOCK:
170     case BLUESKY_CHARACTER:
171     case BLUESKY_SYMLINK:
172     case BLUESKY_SOCKET:
173     case BLUESKY_FIFO:
174         break;
175     }
176
177     return i;
178 }
179
180 /* Retrieve an inode from the filesystem.  Eventually this will be a cache and
181  * so we might need to go fetch the inode from elsewhere; for now all
182  * filesystem state is stored here. */
183 BlueSkyInode *bluesky_get_inode(BlueSkyFS *fs, uint64_t inum)
184 {
185     BlueSkyInode *inode = NULL;
186
187     g_mutex_lock(fs->lock);
188     inode = (BlueSkyInode *)g_hash_table_lookup(fs->inodes, &inum);
189     g_mutex_unlock(fs->lock);
190
191     return inode;
192 }
193
194 /* Insert an inode into the filesystem inode cache. */
195 void bluesky_insert_inode(BlueSkyFS *fs, BlueSkyInode *inode)
196 {
197     g_mutex_lock(fs->lock);
198     g_hash_table_insert(fs->inodes, &inode->inum, inode);
199     g_mutex_unlock(fs->lock);
200 }
201
202 /* Mark a given block dirty and make sure that data is faulted in so that it
203  * can be written to. */
204 void bluesky_block_touch(BlueSkyInode *inode, uint64_t i)
205 {
206     g_return_if_fail(i < inode->blocks->len);
207     BlueSkyBlock *block = &g_array_index(inode->blocks, BlueSkyBlock, i);
208
209     switch (block->type) {
210     case BLUESKY_BLOCK_ZERO:
211         block->data = bluesky_string_new(g_malloc0(BLUESKY_BLOCK_SIZE),
212                                          BLUESKY_BLOCK_SIZE);
213         break;
214     case BLUESKY_BLOCK_REF:
215         bluesky_block_fetch(inode->fs, block);
216         g_assert(block->type == BLUESKY_BLOCK_CACHED);
217         /* Fall through */
218     case BLUESKY_BLOCK_CACHED:
219     case BLUESKY_BLOCK_DIRTY:
220         block->data = bluesky_string_dup(block->data);
221         break;
222     }
223
224     block->type = BLUESKY_BLOCK_DIRTY;
225 }
226
227 /* Set the size of a file.  This will truncate or extend the file as needed.
228  * Newly-allocated bytes are zeroed. */
229 void bluesky_file_truncate(BlueSkyInode *inode, uint64_t size)
230 {
231     g_return_if_fail(size <= BLUESKY_MAX_FILE_SIZE);
232
233     if (size == inode->size)
234         return;
235
236     uint64_t blocks = (size + BLUESKY_BLOCK_SIZE - 1) / BLUESKY_BLOCK_SIZE;
237
238     if (blocks > inode->blocks->len) {
239         /* Need to add new blocks to the end of a file.  New block structures
240          * are automatically zeroed, which initializes them to be pointers to
241          * zero blocks so we don't need to do any more work. */
242         g_array_set_size(inode->blocks, blocks);
243     } else if (blocks < inode->blocks->len) {
244         /* Delete blocks from a file.  Must reclaim memory. */
245         for (guint i = inode->blocks->len; i < blocks; i++) {
246             BlueSkyBlock *b = &g_array_index(inode->blocks, BlueSkyBlock, i);
247             g_free(b->ref);
248             bluesky_string_unref(b->data);
249         }
250         g_array_set_size(inode->blocks, blocks);
251     }
252
253     /* If the file size is being decreased, ensure that any trailing data in
254      * the last block is zeroed. */
255     if (size < inode->size) {
256         BlueSkyBlock *b = &g_array_index(inode->blocks, BlueSkyBlock,
257                                          blocks - 1);
258         if (b->type != BLUESKY_BLOCK_ZERO) {
259             bluesky_block_touch(inode, blocks - 1);
260             int end_offset = size % BLUESKY_BLOCK_SIZE;
261             if (end_offset > 0) {
262                 memset(&b->data->data[end_offset], 0,
263                        BLUESKY_BLOCK_SIZE - end_offset);
264             }
265         }
266     }
267
268     inode->size = size;
269     bluesky_inode_update_ctime(inode, 1);
270 }
271
272 void bluesky_file_write(BlueSkyInode *inode, uint64_t offset,
273                         const char *data, gint len)
274 {
275     g_return_if_fail(inode->type == BLUESKY_REGULAR);
276     g_return_if_fail(offset < inode->size);
277     g_return_if_fail(len <= inode->size - offset);
278
279     if (len == 0)
280         return;
281
282     while (len > 0) {
283         uint64_t block_num = offset / BLUESKY_BLOCK_SIZE;
284         gint block_offset = offset % BLUESKY_BLOCK_SIZE;
285         gint bytes = MIN(BLUESKY_BLOCK_SIZE - block_offset, len);
286
287         bluesky_block_touch(inode, block_num);
288         BlueSkyBlock *b = &g_array_index(inode->blocks, BlueSkyBlock,
289                                          block_num);
290         memcpy(&b->data->data[block_offset], data, bytes);
291         bluesky_block_flush(inode->fs, b);
292
293         offset += bytes;
294         data += bytes;
295         len -= bytes;
296     }
297
298     bluesky_inode_update_ctime(inode, 1);
299 }
300
301 void bluesky_file_read(BlueSkyInode *inode, uint64_t offset,
302                        char *buf, gint len)
303 {
304     g_return_if_fail(inode->type == BLUESKY_REGULAR);
305     g_return_if_fail(offset < inode->size);
306     g_return_if_fail(len <= inode->size - offset);
307
308     while (len > 0) {
309         uint64_t block_num = offset / BLUESKY_BLOCK_SIZE;
310         gint block_offset = offset % BLUESKY_BLOCK_SIZE;
311         gint bytes = MIN(BLUESKY_BLOCK_SIZE - block_offset, len);
312
313         BlueSkyBlock *b = &g_array_index(inode->blocks, BlueSkyBlock,
314                                          block_num);
315         switch (b->type) {
316         case BLUESKY_BLOCK_ZERO:
317             memset(buf, 0, bytes);
318             break;
319         case BLUESKY_BLOCK_REF:
320             bluesky_block_fetch(inode->fs, b);
321             /* Fall through */
322         case BLUESKY_BLOCK_CACHED:
323         case BLUESKY_BLOCK_DIRTY:
324             memcpy(buf, &b->data->data[block_offset], bytes);
325             break;
326         }
327
328         offset += bytes;
329         buf += bytes;
330         len -= bytes;
331     }
332 }
333
334 /* Read the given block from cloud-backed storage if the data is not already
335  * cached. */
336 void bluesky_block_fetch(BlueSkyFS *fs, BlueSkyBlock *block)
337 {
338     if (block->type != BLUESKY_BLOCK_REF)
339         return;
340
341     g_print("Fetching block from %s\n", block->ref);
342     BlueSkyRCStr *string = s3store_get(fs->store, block->ref);
343
344     bluesky_string_unref(block->data);
345     block->data = string;
346     block->type = BLUESKY_BLOCK_CACHED;
347 }
348
349 /* Write the given block to cloud-backed storage and mark it clean. */
350 void bluesky_block_flush(BlueSkyFS *fs, BlueSkyBlock *block)
351 {
352     if (block->type != BLUESKY_BLOCK_DIRTY)
353         return;
354
355     BlueSkyRCStr *data = block->data;
356     data = bluesky_crypt_encrypt(data, fs->encryption_key);
357
358     GChecksum *csum = g_checksum_new(G_CHECKSUM_SHA256);
359     g_checksum_update(csum, data->data, data->len);
360     gchar *name = g_strdup(g_checksum_get_string(csum));
361
362     g_print("Flushing block as %s\n", name);
363     s3store_put(fs->store, name, data);
364     g_free(block->ref);
365     block->ref = name;
366
367     /* block->type = BLUESKY_BLOCK_CACHED; */
368     bluesky_string_unref(block->data);
369     block->data = NULL;
370     block->type = BLUESKY_BLOCK_REF;
371
372     g_checksum_free(csum);
373     bluesky_string_unref(data);
374 }