-
Notifications
You must be signed in to change notification settings - Fork 6
/
syncfs.cpp
2385 lines (2112 loc) · 69.9 KB
/
syncfs.cpp
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Z-Backup File System
Copyright (C) 2015 Kevin Atkinson
Based on the Big Brother File System
Copyright (C) 2012 Joseph J. Pfeiffer, Jr., Ph.D. <[email protected]>
This program can be distributed under the terms of the GNU GPLv3.
See the file COPYING.
This code is derived from function prototypes found /usr/include/fuse/fuse.h
Copyright (C) 2001-2007 Miklos Szeredi <[email protected]>
His code is licensed under the LGPLv2.
A copy of that code is included in the file fuse.h
*/
#include "params.h"
#include "remote.h"
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <fuse.h>
#include <libgen.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/xattr.h>
#include <signal.h>
#include <stdarg.h>
#include <assert.h>
#include <string>
#include <vector>
#include <utility>
#include <limits>
using std::string;
using std::vector;
#ifdef NDEBUG
// CMake can enable NDEBUG, something that is rarely done in the Unix
// world. I am not alone in considering -DNDEBUG to be EBW =
// (Evil, Bad, and Wrong). See
// https://lists.debian.org/debian-devel/2013/02/msg00351.html This
// check is to guard against that.
#error NDEBUG builds are unsupported
#endif
#include "sqlite3.hpp"
#include "json.hpp"
typedef int64_t FileId;
typedef int64_t ContentId;
enum OpenState {Closed, OpenedRO, OpenedRW};
#include "queries-gen.hpp"
//////////////////////////////////////////////////////////////////////////////
//
// Global state
//
#define SCHEMA_VERSION "3"
static const char * rootdir = NULL;
FILE * logfile = NULL;
RemoteState remote_state;
//RemoteOps remote = file_remote;
RemoteOps remote = drive_remote;
bool LOG_SQL = false;
//////////////////////////////////////////////////////////////////////////////
//
// Database State and Mutex
//
pthread_mutex_t db_mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
sqlite3 * db = NULL;
std::vector<SqlStmtBase *> sql_stmts;
// FileID == -1 if local, < -1 if proc file
std::vector<FileId> opened_files;
std::vector<const char *> proc_file_content;
#define PENDING_MAX_SIZE (2*1024)
#define PENDING_FH_START 4000000000u
struct ScopedMutex {
pthread_mutex_t * mutex;
bool locked;
ScopedMutex(pthread_mutex_t * m, bool start_locked = true) : mutex(m), locked(false) {if (start_locked) lock();}
ScopedMutex(ScopedMutex && other) : mutex(other.mutex), locked(other.locked) {other.mutex = NULL;}
ScopedMutex & operator=(ScopedMutex & other) = delete;
~ScopedMutex() {if (mutex) unlock();}
//void unlock() {if (locked && mutex == &db_mutex) db_locked = false; if (locked) pthread_mutex_unlock(mutex); locked = false; }
//void lock() {if (!locked) pthread_mutex_lock(mutex); locked = true; if (mutex == &db_mutex) db_locked = true; }
void unlock() {if (locked) pthread_mutex_unlock(mutex); locked = false; }
void lock() {if (!locked) pthread_mutex_lock(mutex); locked = true; }
void yield () {assert(locked); unlock(); lock(); }
};
struct DbMutex : public ScopedMutex {
DbMutex(bool start_locked = true) : ScopedMutex(&db_mutex, start_locked) {}
};
bool exiting = false;
class Worker {
public:
const char * worker_name;
pthread_t thread;
pthread_cond_t cond;
void * start();
void notify() {
assert(db_locked);
more_to_do_now = true;
if (!waiting) return;
pthread_cond_signal(&cond);
waiting = false;
}
protected:
bool waiting;
bool more_to_do_now;
int more_to_do;
int error_backoff;
virtual bool do_work(DbMutex &lock) = 0; // returns true if the function should
// be called again without waiting
Worker(const char * name)
: worker_name(name), cond(PTHREAD_COND_INITIALIZER),
waiting (false), more_to_do_now(false), more_to_do(), error_backoff() {}
public:
void create() {
pthread_create(&thread, NULL, thread_start, this);
}
static void * thread_start(void *);
};
// The checksum thread computes checksums for modified files
class LocalPartThread : public Worker {
public:
LocalPartThread() : Worker("local part thread") {}
protected:
bool do_work(DbMutex &lock);
} * local_part_thread = NULL;
// The cleanup thread removes files locally that are no longer needed
// and also upload files, giving priority to files that could be
// removed after uploading
class UploaderThread : public Worker {
public:
UploaderThread() : Worker("uploader thread") {}
protected:
bool do_work(DbMutex &lock);
} * uploader_thread = NULL;
// The extra_uploader thread is an optional thread that uploads files
// giving priority to smaller files
class ExtraUploaderThread : public Worker {
public:
ExtraUploaderThread() : Worker("extra uploader thread") {}
protected:
bool do_work(DbMutex &lock);
} * extra_uploader_thread = NULL;
// The metadata thread pushes other changes not handled by other threads
class MetadataThread : public Worker {
public:
MetadataThread() : Worker("metadata thread") {}
protected:
bool do_work(DbMutex &lock);
} * metadata_thread = NULL;
void log_msg(const char *format, ...)
__attribute__ ((format (printf, 1, 2)));
static void check_schema(bool reset_db) {
FILE * f = NULL;
f = fopen(".var/schema_version", "r");
if (reset_db) goto create;
if (!f && errno == ENOENT) goto create;
if (!f) goto error;
{
char * str;
size_t sz = 0;
auto len = getline(&str, &sz, f);
if (len == -1 && ferror(f)) goto error;
if (len == 0 || len == -1) goto create;
if (str[len-1] == '\n') str[len-1] = '\0';
if (strcmp(str, SCHEMA_VERSION) != 0) {
fprintf(stderr, "Schema version mismatch (existing: %s, need: %s) please reset the database.\n", str, SCHEMA_VERSION);
exit (-1);
}
}
/* all good */
fclose(f);
return;
create: {
if (f) fclose(f);
FILE * f = fopen(".var/schema_version", "w");
if (!f) goto error;
int res = fprintf(f, "%s\n", SCHEMA_VERSION);
if (res < 0) goto error;
fclose(f);
return;
}
error: {
if (f) fclose(f);
fprintf(stderr, "Problem when reading or writing file: .var/schema_version\n");
exit (-1);
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Policy functions
//
#define UPLOAD_WAIT 30
#define REMOVE_WAIT 90
//#define TMP_SIZE_OFFLOAD 128*1024
#define MIN_BACKOFF_ERROR 5
#define MAX_BACKOFF_ERROR 320
struct PathInfo {
std::string path; // NOTE: A String is an overkill here
bool prefix_match;
PathInfo(const char * p) : path(p) {
prefix_match = path.back() == '/' ? true : false;
}
};
template <typename T>
struct MatchPath : public std::vector<std::pair<PathInfo,T> > {
typedef std::vector<std::pair<PathInfo,T> > Base;
typedef typename Base::const_iterator iterator;
typedef typename Base::value_type value_type;
MatchPath() {}
MatchPath(std::initializer_list<value_type> init)
: Base(init) {prioritize();}
MatchPath& operator=(std::initializer_list<typename Base::value_type> init) {
Base::operator=(init);
prioritize();
return *this;
}
const T * match(const char * to_match, iterator & i) const {
while (i != this->end()) {
auto & key = i->first;
if (key.prefix_match) {
if (strncmp(key.path.c_str(), to_match, key.path.size()) == 0)
return &(i++)->second;
} else {
if (key.path == to_match)
return &(i++)->second;
}
++i;
}
return NULL;
}
const T * match(const char * to_match) const {
iterator i = this->begin();
return match(to_match, i);
}
void prioritize(int skip = 0) {
auto lt = [](const value_type & a, const value_type & b) -> bool {
if (a.first.path.size() > b.first.path.size()) return true;
if (a.first.path.size() < b.first.path.size()) return false;
return a.first.path < b.first.path;
};
std::sort(this->begin() + skip, this->end(), lt);
}
};
struct LocalOnly {
MatchPath<bool> data;
// LocalOnly() {
// data = {{"/", false}, {"/.etc/", true},{"/.var/", true}};
// }
bool operator()(const char * path) {
//log_msg("local only?? %s\n", path);
return *data.match(path);
}
} local_only;
enum Access {NotAllowed, ReadOnly, CreateOnly, ReadWrite};
struct PathAccess {
MatchPath<Access> data;
// PathAccess() {
// data = {
// {"/", NotAllowed},
// {"/info", CreateOnly},
// {"/tmp", CreateOnly}, {"/tmp/", ReadWrite},
// {"/backups", CreateOnly}, {"/backups/", ReadWrite},
// {"/bundles", CreateOnly}, {"/bundles/", CreateOnly},
// {"/index", CreateOnly}, {"/index/", CreateOnly},
// {"/.var/", ReadOnly}, {"/.etc/", ReadWrite}
// };
// }
Access operator()(const char * path) const {
return *data.match(path);
}
} path_access;
Access dir_access(const char * path) {
unsigned sz = strlen(path);
char dir[sz + 2];
memcpy(dir, path, sz);
dir[sz] = '/';
dir[sz+1] = '\0';
auto i = path_access.data.cbegin();
auto val = ReadOnly;
while (auto v = path_access.data.match(dir,i)) {
if (*v == CreateOnly || *v == ReadWrite) val = ReadWrite;
}
return val;
}
#define FOREVER INT_MAX
struct ShouldUpload {
struct Val {
int32_t min_wait; // time to wait after the file is closed for writing
int32_t max_wait; // upload after this time, even if file is less than if_larger_than;
int64_t keep_size;
};
MatchPath<Val> data;
// ShouldUpload() {
// data = {{"/tmp/", {-1,-1,TMP_SIZE_OFFLOAD}},
// {"/", {UPLOAD_WAIT, FOREVER, 0}}};
// }
// should path be uploaded to the server?
// return -1 if the path should never be upload
// 0 to upload it now
// > 0 to possible upload it latter, returns the number of seconds to wait until we should ask again
// INT_MAX possible to upload latter once conditions change
int operator()(FileId id, const char * path, time_t atime, time_t mtime, int size, time_t now) const {
if (local_only(path))
return -1;
auto i = data.begin();
Val val = {-1, -1, -1};
while (auto v = data.match(path, i)) {
if (val.min_wait == -1 && v->min_wait != -1) val.min_wait = v->min_wait;
if (val.max_wait == -1 && v->max_wait != -1) val.max_wait = v->max_wait;
if (val.keep_size == -1 && v->keep_size != -1) val.keep_size = v->keep_size;
}
if (val.keep_size != 0) {
if (now - mtime >= val.max_wait) return 0;
if (size < val.keep_size) return val.max_wait;
}
if (now - mtime < val.min_wait) return val.min_wait;
return 0;
}
} should_upload;
struct MayRemove {
struct Val {
int32_t wait; // time to wait after the file is last closed
};
MatchPath<Val> data;
// MayRemove() {
// data = {{"/tmp/", {REMOVE_WAIT}},
// {"/bundles/", {REMOVE_WAIT}},
// {"/", {FOREVER}}};
// }
// should the local copy of path be removed?
// returns the same values as upload_path
int operator()(FileId id, const char * path, time_t atime, time_t mtime, int size, time_t now) const {
if (local_only(path))
return -1;
auto i = data.begin();
Val val = {-1};
while (auto v = data.match(path, i)) {
if (val.wait == -1 && v->wait != -1) val.wait = v->wait;
}
if (val.wait == FOREVER) return -1;
if (now - atime < val.wait) return val.wait;
return 0;
}
} may_remove;
//////////////////////////////////////////////////////////////////////////////
//
// Misc helper bits
//
void init_db(const char * dir, bool reset_db);
void close_db();
// Report errors to logfile and give -errno to caller
static int syncfs_error(const char *str)
{
int ret = -errno;
log_msg(" ERROR %s: %s\n", str, strerror(errno));
return ret;
}
static bool path_writable(const char * path) {
return path_access(path) == ReadWrite;
}
enum AccessMode {READ, MOD_DIR, MOD_FILE};
// FIXME: Make boolean, if false then code should return -EPERM (not EACCESS)
bool access_ok(const char *path, AccessMode mode)
{
auto access = path_access(path);
bool res = true;
if (access == ReadWrite) {
/* all okay */
} else if (access == CreateOnly) {
if (mode == MOD_FILE) res = false;
} else if (access == ReadOnly) {
if (mode != READ) res = false;
} else {
res = false;
}
if (!res)
log_msg(" ERROR %s: %s\n", path, strerror(EPERM));
return res;
}
#define CHECKPATH(path, mode) if (!access_ok(path, mode)) return -EPERM;
// All the paths I see are relative to the root of the mounted
// filesystem. In order to get to the underlying filesystem, I need to
// have the mountpoint. I'll save it away early on in main(), and then
// whenever I need a path for something I'll call this to construct
// it.
static void syncfs_fullpath(char fpath[PATH_MAX], const char *path)
{
strcpy(fpath, rootdir);
strncat(fpath, path, PATH_MAX); // ridiculously long paths will
// break here
}
void log_msg(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vfprintf(logfile, format, ap);
}
//////////////////////////////////////////////////////////////////////////////
//
// Fuse functions
//
////////
//
// Operations on directories (that don't access the database)
//
/** Create a directory */
int syncfs_mkdir(const char *path, mode_t mode)
{
int retstat = 0;
char fpath[PATH_MAX];
CHECKPATH(path, MOD_DIR);
log_msg("\nsyncfs_mkdir(path=\"%s\", mode=0%3o)\n",
path, mode);
syncfs_fullpath(fpath, path);
retstat = mkdir(fpath, mode);
if (retstat < 0)
retstat = syncfs_error("syncfs_mkdir mkdir");
return retstat;
}
/** Remove a directory */
int syncfs_rmdir(const char *path)
{
int retstat = 0;
char fpath[PATH_MAX];
CHECKPATH(path, MOD_DIR);
log_msg("syncfs_rmdir(path=\"%s\")\n",
path);
syncfs_fullpath(fpath, path);
retstat = rmdir(fpath);
if (retstat < 0)
retstat = syncfs_error("syncfs_rmdir rmdir");
return retstat;
}
//////////
//
// Operations on Open Files.
// (None of which involve accessing the database).
//
/** Read data from an open file */
int pending_read(char *buf, size_t size, off_t offset, struct fuse_file_info *fi);
int syncfs_read(const char *, char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
int retstat = 0;
//log_msg("syncfs_read(fh=%lld, size=%d, offset=%lld)\n", fi->fh, size,offset);
if (fi->fh >= PENDING_FH_START)
return pending_read(buf,size,offset,fi);
retstat = pread(fi->fh, buf, size, offset);
if (retstat < 0)
retstat = syncfs_error("syncfs_read read");
return retstat;
}
/** Write data to an open file */
int syncfs_write(const char *, const char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
int retstat = 0;
retstat = pwrite(fi->fh, buf, size, offset);
if (retstat < 0)
retstat = syncfs_error("syncfs_write pwrite");
return retstat;
}
/** Change the size of an open file */
int syncfs_ftruncate(const char *, off_t newsize, struct fuse_file_info *fi)
{
int retstat = 0;
//log_msg("\nsyncfs_ftruncate(newsize=%lld, fh=%d)\n", newsize, (int)fi->fh);
retstat = ftruncate(fi->fh, newsize);
if (retstat < 0)
retstat = syncfs_error("syncfs_ftruncate ftruncate");
return retstat;
}
/* Get attributes from an open file */
int pending_getattr(struct stat *statbuf, struct fuse_file_info *fi);
int syncfs_fgetattr(const char *, struct stat *statbuf, struct fuse_file_info *fi)
{
int retstat = 0;
log_msg("\nsyncfs_fgetattr(statbuf=%p, fh=%d)\n", statbuf, (int)fi->fh);
if (fi->fh >= PENDING_FH_START)
return pending_getattr(statbuf,fi);
retstat = fstat(fi->fh, statbuf);
if (retstat < 0)
retstat = syncfs_error("syncfs_fgetattr fstat");
return retstat;
}
/** Synchronize file contents
*
* If the datasync parameter is non-zero, then only the user data
* should be flushed, not the meta data.
*
*/
int syncfs_fsync(const char *, int datasync, struct fuse_file_info *fi)
{
int retstat = 0;
//log_msg("\nsyncfs_fsync(datasync=%d, fh=0x%d)\n", datasync, (int)fi->fh);
if (datasync)
retstat = fdatasync(fi->fh);
else
retstat = fsync(fi->fh);
if (retstat < 0)
syncfs_error("syncfs_fsync fsync");
return retstat;
}
//////////
//
// Operations that involve the database
//
auto sql_get_fid = SQL("select fid from fileinfo where dir=? and name =?");
auto sql_is_local = SQL("select local from fileinfo where dir=? and name=?");
/** Remove a file */
auto sql_unlink = SQL("update fileinfo set dir=NULL, name=NULL, local=NULL where dir=? and name=?");
int syncfs_unlink(const char *path)
{
int retstat = 0;
char fpath[PATH_MAX];
CHECKPATH(path, MOD_DIR);
log_msg("\nsyncfs_unlink(path=\"%s\")\n",
path);
syncfs_fullpath(fpath, path);
if (local_only(path)) {
retstat = unlink(fpath);
if (retstat < 0)
return syncfs_error("syncfs_unlink (local) unlink");
return 0;
}
DbMutex lock;
try {
bool local;
sql_is_local(Path(path)).get(local);
if (local) {
retstat = unlink(fpath);
if (retstat < 0)
return syncfs_error("syncfs_unlink unlink");
}
sql_unlink.exec1(Path(path));
metadata_thread->notify();
return 0;
} catch (SqlError & err) {
log_msg(" ERROR: sql error: unlink %s: %s\n", path, err.msg.c_str());
return -EIO;
}
}
// both path and newpath are fs-relative
auto sql_exists = SQL("select fid from fileinfo where dir=? and name=?");
auto sql_rename = SQL("update fileinfo set dir=?, name=?, writable=? where dir=? and name=?");
//bool fdb_rename(const char *path, const char *newpath, DbMutex &);
int syncfs_rename(const char *path, const char *newpath)
{
int retstat = 0;
char fpath[PATH_MAX];
char fnewpath[PATH_MAX];
CHECKPATH(path, MOD_DIR);
CHECKPATH(newpath, MOD_DIR);
log_msg("\nsyncfs_rename(fpath=\"%s\", newpath=\"%s\")\n",
path, newpath);
syncfs_fullpath(fpath, path);
syncfs_fullpath(fnewpath, newpath);
if (local_only(path) && local_only (newpath)) {
retstat = rename(fpath, fnewpath);
if (retstat < 0)
return syncfs_error("syncfs_rename unlink");
return 0;
} else if (local_only(path) || local_only (newpath)) {
return -EPERM;
}
DbMutex lock;
try {
SqlTrans trans;
bool local;
auto exists = sql_exists(Path(path));
if (exists.step()) {
sql_is_local(Path(path)).get(local);
sql_unlink.exec_nocheck(Path(newpath));
sql_rename.exec1(Path(newpath), path_writable(newpath), Path(path));
} else {
// we have a directory
// rename each path individually
auto res = SELECT("select dir,name from fileinfo where dir is not null");
auto orig_len = strlen(path);
std::string newp;
while (res.step()) {
if (strncmp(res->dir, path, orig_len) != 0) continue;
newp = newpath;
newp += res->dir + orig_len;
newp += res->name;
//printf("=== %s%s => %s\n", dir,name, newp.c_str());
sql_unlink.exec_nocheck(Path(newp.c_str()));
sql_rename.exec1(Path(newp.c_str()), path_writable(newp.c_str()), res->dir, res->name);
local = true;
}
}
if (local) {
retstat = rename(fpath, fnewpath);
if (retstat < 0)
return syncfs_error("syncfs_rename rename");
}
trans.commit();
metadata_thread->notify();
return 0;
} catch (SqlError & err) {
log_msg(" ERROR: sql error: rename %s -> %s: %s\n", path, newpath, err.msg.c_str());
return -EIO;
}
}
/** File open operation
*
* No creation, or truncation flags (O_CREAT, O_EXCL, O_TRUNC)
* will be passed to open(). Open should check if the operation
* is permitted for the given flags. Optionally open may also
* return an arbitrary filehandle in the fuse_file_info structure,
* which will be passed to all file operations.
*
*/
FileId fdb_open(const char * path, OpenState open_state) {
FileId fid;
sql_get_fid(Path(path)).get(fid);
EXEC("update fileinfo set opened=max($open_state,opened),open_count=open_count + 1 where fid=$fid");
return fid;
}
FileId fdb_create(const char * path) {
return SQL("insert into fileinfo (dir, name, local, mtime, atime, opened, open_count, writable)"
"values (?1,?2,1,?3,?3,2,1,?4)").exec1(Path(path),time(NULL),path_writable(path));
}
auto sql_release_file = SQL("update fileinfo set opened=0, open_count = 0, atime=? where fid=?");
void update_file_after_mod(FileId fid, ssize_t size, time_t mtime) {
auto cid = EXEC("insert into contentinfo (size) values ($size)");
EXEC("update fileinfo set cid=$cid,mtime=$mtime where fid=$fid");
}
int fdb_close(FileId fid, int fd, bool cleanup = false) {
try {
int open_count,opened;
SELECT("open_count,opened from fileinfo where fid=$fid").get(open_count,opened);
struct stat st;
auto now = time(NULL);
if (open_count == 1) {
sql_release_file.exec1(now, fid);
if (fd >= 0 && opened == OpenedRW && !cleanup) {
fstat(fd, &st);
update_file_after_mod(fid, st.st_size, st.st_mtime);
}
} else {
EXEC("update fileinfo set open_count = open_count -1, atime=$now where fid=$fid");
}
return 0;
} catch (SqlError & err) {
log_msg(" ERROR: sql error on file close: %s\n", err.msg.c_str());
return -EIO;
}
}
int fetch_path(const char * path, FileId id, DbMutex & lock);
int pending_open(struct fuse_file_info *fi);
int syncfs_open(const char *path, struct fuse_file_info *fi)
{
int retstat = 0;
FileId fid = 0;
int fd = -1;
char fpath[PATH_MAX];
bool readonly = !((fi->flags & O_WRONLY) == O_WRONLY || (fi->flags & O_RDWR) == O_RDWR);
CHECKPATH(path, readonly ? READ : MOD_FILE);
log_msg("\nsyncfs_open(path\"%s\")\n", path);
if (strcmp(path, "/.proc/pending")== 0)
return pending_open(fi);
syncfs_fullpath(fpath, path);
DbMutex lock;
try {
if (local_only(path))
fid = -1;
else
fid = fdb_open(path, readonly ? OpenedRO : OpenedRW);
bool local;
if (fid == -1)
local = true;
else
sql_is_local(Path(path)).get(local);
if (!local) {
auto ret = fetch_path(fpath, fid, lock);
if (ret != 0) {
retstat = -EIO;
goto err;
}
}
fd = open(fpath, fi->flags);
if (fd < 0) {
retstat = syncfs_error("syncfs_open open");
goto err;
}
fi->fh = fd;
log_msg(" fd = %d\n", fd);
if (fid != -1 && !readonly)
// mark the file as being modified and should be be uploaded until closed
EXEC("update fileinfo set cid=NULL where fid=$fid");
} catch (SqlError & err) {
log_msg(" ERROR: sql error: open %s: %s\n", path, err.msg.c_str());
retstat = -EIO;
goto err;
}
if ((unsigned)fd >= opened_files.size()) opened_files.resize(fd + 1);
opened_files[fd] = fid;
return 0;
err:
if (fid > 0) fdb_close(fid, fd, true);
if (fd >= 0) close(fd);
return retstat;
}
/* Create and open a file */
int syncfs_create(const char *path, mode_t mode, struct fuse_file_info *fi)
{
char fpath[PATH_MAX];
int fd;
CHECKPATH(path, MOD_DIR);
log_msg("\nsyncfs_create(path=\"%s\", mode=0%03o)\n",
path, mode);
DbMutex lock;
syncfs_fullpath(fpath, path);
fd = creat(fpath, mode);
if (fd < 0)
return syncfs_error("syncfs_create creat");
fi->fh = fd;
log_msg(" fh = %d\n", fd);
FileId fid = 0;
try {
if (local_only(path))
fid = -1;
else
fid = fdb_create(path);
} catch (SqlError & err) {
close(fd);
log_msg(" ERROR: sql error: create %s: %s\n", path, err.msg.c_str());
return -EIO;
}
if ((unsigned)fd >= opened_files.size()) opened_files.resize(fd + 1);
opened_files[fd] = fid;
return 0;
}
/** Release an open file
*
* Release is called when there are no more references to an open
* file: all file descriptors are closed and all memory mappings
* are unmapped.
*
* For every open() call there will be exactly one release() call
* with the same flags and file descriptor. It is possible to
* have a file opened more than once, in which case only the last
* release will mean, that no more reads/writes will happen on the
* file. The return value of release is ignored.
*/
int pending_release(fuse_file_info *fi);
int syncfs_release(const char * path, struct fuse_file_info *fi)
{
int retstat = 0;
log_msg("\nsyncfs_release(fh=%d path=%s)\n", (int)fi->fh, path);
if (fi->fh >= PENDING_FH_START)
return pending_release(fi);
DbMutex lock;
int fd = fi->fh;
FileId fid = 0;
if (fd < (int)opened_files.size()) {
fid = opened_files[fd];
opened_files[fd] = 0;
}
if (fid == 0) {
log_msg(" ERROR: can not find fid for opened file: %s\n", path);
return -EIO;
}
if (fid != -1)
retstat = fdb_close(fid, fd);
if (retstat != 0)
return retstat;
retstat = close(fi->fh);
if (retstat != 0)
return syncfs_error("syncfs_release close");
local_part_thread->notify();
return 0;
}
/** Get file attributes. */
int fdb_getattr(const char *path, struct stat *statbuf);
int syncfs_getattr(const char *path, struct stat *statbuf)
{
int retstat = 0;
char fpath[PATH_MAX];
log_msg("\nsyncfs_getattr(path=\"%s\", statbuf=%p)\n",
path, statbuf);
if (strcmp(path, "/.proc") == 0) {
statbuf->st_mode = S_IFDIR | 0755;
statbuf->st_nlink = 2;
return 0;
} else if (strcmp(path, "/.proc/pending") == 0) {
statbuf->st_mode = S_IFREG | 0444;
statbuf->st_size = 0;
return 0;
} else if (strncmp(path, "/.proc/", 7) == 0) {
return -ENOENT;
}
int ret = fdb_getattr(path, statbuf);
// retstat is 0 on success, -1 on error, 1 if stat still needs to be called, 2 for a local only file
if (ret == 0) return 0;
if (ret < 0) return -EIO;
syncfs_fullpath(fpath, path);
if (ret > 0)
retstat = lstat(fpath, statbuf);
if (retstat != 0 && errno == ENOENT)
retstat = -errno;
else if (retstat != 0)
retstat = syncfs_error("syncfs_getattr lstat");
if (S_ISDIR(statbuf->st_mode)) {
auto access = dir_access(path);
if (access == ReadOnly)
statbuf->st_mode &= 0770555;
} else if (ret == 2) {
auto access = path_access(path);
if (access == NotAllowed)
statbuf->st_mode &= 0770000;
else if (access == CreateOnly || access == ReadOnly)
statbuf->st_mode &= 0770555;
}
return retstat;
}
// returns -1 on error, 0 if result, 1 if no result
int fdb_getattr(const char * path, struct stat *statbuf) {
if (local_only(path)) return 2;
try {
DbMutex lock;
auto res = SQL("select writable,size,atime,mtime "
"from fileinfo join contentinfo using (cid) "
"where dir=? and name=? and opened < 2")(Path(path));
if (res.step()) {
bool writable;
res.get(writable, statbuf->st_size, statbuf->st_atime, statbuf->st_mtime);
statbuf->st_mode = S_IFREG | (writable ? 0644 : 0444);
statbuf->st_nlink = 1;
statbuf->st_blocks = statbuf->st_size / 512 + (statbuf->st_size % 512 == 0 ? 0 : 1);
statbuf->st_ctime = statbuf->st_mtime;
return 0;
} else {
return 1;
}
} catch (SqlError & err) {
log_msg(" ERROR: sql error: fdb_getattr: %s\n", err.msg.c_str());
return 0;
}