-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpfs.c
3587 lines (3319 loc) · 97 KB
/
pfs.c
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
#define FUSE_USE_VERSION 26
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <fuse.h>
#include <ctype.h>
#include <errno.h>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include "common.h"
#include "settings.h"
#define SETTING_BUFF 4096
#define INITIAL_COND_TIMEOUT_SEC 3
#if !defined(MINGW) && !defined(_WIN32)
# include <sys/mman.h>
# include <signal.h>
#endif
#include "binapi.h"
#include "pfs.h"
#if defined(MINGW) || defined(_WIN32)
#define sleep(x) Sleep(1000*(x))
#define milisleep(x) Sleep((x))
#define index(str, c) strchr(str, c)
#define rindex(str, c) strrchr(str, c)
struct tm *gmtime_r(const time_t *timep, struct tm *result)
{
struct tm * res = gmtime(timep);
*result = *res;
return result;
}
int dumb_socketpair(SOCKET socks[2], int make_overlapped);
#ifndef ENOTCONN
# define ENOTCONN 107
#endif
#ifndef ST_NOSUID
# define ST_NOSUID 2
#endif
char mount_point;
#else
#define milisleep(x) usleep((x)*1000)
#endif
pfs_settings fs_settings={
.pagesize=64*1024,
.cachesize=1024*1024*1024,
.readaheadmin=64*1024,
.readaheadmax=8*1024*1024,
.readaheadmaxsec=12,
.maxunackedbytes=256*1024,
.usessl=0,
.timeout=30,
.retrycnt=5
};
static time_t cachesec=30;
static time_t laststatfs=0;
static int checkifhashmatch=0;
static const char *cachefile=NULL;
static uint64_t quota, usedquota;
static char *auth="";
uid_t myuid=0;
gid_t mygid=0;
static int fs_inited = 0;
#define PAGE_GC_PERCENT 10
#define FS_MAX_WRITE 256*1024
#define HASH_SIZE 4099
#define TASK_TYPE_WAIT 1
#define TASK_TYPE_CALL 2
#define MAX_FILE_STREAMS 16
#define NOT_CONNECTED_ERR -ENOTCONN
#define list_add(list, elem) do {(elem)->next=(list); (elem)->prev=&(list); (list)=(elem); if ((elem)->next) (elem)->next->prev=&(elem)->next;} while (0)
#define list_del(elem) do {*(elem)->prev=(elem)->next; if ((elem)->next) (elem)->next->prev=(elem)->prev;} while (0)
#define new(type) (type *)malloc(sizeof(type))
#define md5_debug(_str, _len) ({unsigned char __md5b[16]; char *__ret, *__ptr; int __i; MD5((unsigned char *)(_str), (_len), __md5b); __ret=malloc(34);\
__ptr=__ret; for (__i=0; __i<16; __i++){*__ptr++=hexdigits[__md5b[__i]/16];*__ptr++=hexdigits[__md5b[__i]%16];}\
*__ptr=0; __ret;})
#define dec_refcnt(_en) do {if (--(_en)->tfile.refcnt==0 && (_en)->isdeleted) {free_file_cache(_en); free(_en->name); free(_en);} } while (0)
#define fd_magick_start(__of) {\
binparam fdparam;\
char __buff[32];\
int __useidx;\
if ((__of)->fd){\
fdparam.paramtype=PARAM_NUM;\
fdparam.paramnamelen=2;\
fdparam.paramname="fd";\
fdparam.un.num=(__of)->fd;\
__useidx=0;\
}\
else {\
int __idx;\
pthread_mutex_lock(&indexlock);\
__idx=(int64_t)filesopened-(int64_t)(__of)->openidx;\
fdparam.paramtype=PARAM_STR;\
fdparam.paramnamelen=2;\
fdparam.paramname="fd";\
fdparam.opts=sprintf(__buff, "-%d", __idx);\
fdparam.un.str=__buff;\
__useidx=1;\
}\
#define fd_magick_stop() \
if (__useidx)\
pthread_mutex_unlock(&indexlock);\
}
typedef void (*task_callback)(void *, binresult *);
typedef struct _task {
struct _task *next;
uint64_t taskid;
binresult *result;
pthread_mutex_t *mutex;
pthread_cond_t *cond;
task_callback call;
uint32_t type;
char ready;
} task;
struct _node;
struct _openfile;
struct _cacheentry;
typedef struct _file {
uint64_t fileid;
uint64_t size;
uint64_t hash;
struct _cacheentry *cache;
uint32_t refcnt;
} file;
typedef struct {
uint64_t folderid;
struct _node **nodes;
uint32_t nodecnt;
uint32_t nodealloc;
uint32_t foldercnt;
} folder;
typedef struct _node {
struct _node *next;
struct _node **prev;
struct _node *parent;
char *name;
time_t createtime;
time_t modifytime;
union {
folder tfolder;
file tfile;
};
char isfolder;
char isdeleted;
char hidefromlisting;
} node;
typedef struct {
uint32_t frompage;
uint32_t topage;
size_t length;
size_t id;
} offstream;
typedef struct _openfile{
uint64_t fd;
uint64_t unackdata;
uint64_t openidx;
node *file;
pthread_mutex_t mutex;
pthread_cond_t cond;
offstream streams[MAX_FILE_STREAMS];
size_t laststreamid;
size_t bytesthissec;
size_t currentspeed;
time_t currentsec;
uint32_t unackcomd;
uint32_t refcnt;
uint32_t connectionid;
int error;
int waitref;
int waitcmd;
char issetting;
} openfile;
#define ismodified bytesthissec
#define currentsize laststreamid
typedef struct {
size_t pagesize;
size_t cachesize;
size_t numpages;
size_t headersize;
} cacheheader;
typedef struct _cacheentry{
struct _cacheentry *next;
struct _cacheentry **prev;
uint64_t fileid;
uint64_t filehash;
time_t lastuse;
time_t fetchtime;
pthread_cond_t cond;
uint32_t realsize;
uint32_t offset;
uint32_t pageid;
uint16_t sleeping;
uint16_t locked;
char free;
char waiting;
} cacheentry;
typedef struct {
cacheentry *page;
openfile *of;
uint32_t tries;
} pagefile;
typedef struct {
openfile *of;
off_t offset;
size_t length;
uint32_t tries;
char buff[];
} writetask;
#define wait_for_allowed_calls() do {pthread_mutex_lock(&calllock); pthread_mutex_unlock(&calllock); } while (0)
static cacheheader *cachehead;
static cacheentry *cacheentries;
static void *cachepages;
static cacheentry *freecache=NULL;
static uint64_t taskid=1;
static uint64_t filesopened=0;
static task *tasks=NULL;
static pthread_mutex_t calllock=PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t pageslock=PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t taskslock=PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t writelock=PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t indexlock=PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t datamutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t datacond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t treelock=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t treecond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t wakelock=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t wakecond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t unacklock=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t unackcond=PTHREAD_COND_INITIALIZER;
static size_t unackedbytes=0;
static size_t unackedsleepers=0;
static int unsigned treesleep=0;
static int processingtask=0;
static uint32_t connectionid=0;
static int need_reconnect=0;
static int diffwakefd, datawakefd;
static time_t timeoff;
static node *rootfolder;
static node *files[HASH_SIZE];
static node *folders[HASH_SIZE];
static apisock *sock, *diffsock;
static const char *hexdigits="0123456789abcdef";
#define cmd(_cmd, ...) \
({\
binparam __params[]={__VA_ARGS__}; \
do_cmd(_cmd, strlen(_cmd), NULL, 0, __params, sizeof(__params)/sizeof(binparam), NULL, NULL); \
})
#define cmd_data(_cmd, _data, _datalen, ...) \
({\
binparam __params[]={__VA_ARGS__}; \
do_cmd(_cmd, strlen(_cmd), _data, _datalen, __params, sizeof(__params)/sizeof(binparam), NULL, NULL); \
})
#define cmd_callback(_cmd, _callbackf, _callbackptr, ...) \
({\
binparam __params[]={__VA_ARGS__}; \
do_cmd(_cmd, strlen(_cmd), NULL, 0, __params, sizeof(__params)/sizeof(binparam), _callbackf, _callbackptr); \
})
#define cmd_data_callback(_cmd, _data, _datalen, _callbackf, _callbackptr, ...) \
({\
binparam __params[]={__VA_ARGS__}; \
do_cmd(_cmd, strlen(_cmd), _data, _datalen, __params, sizeof(__params)/sizeof(binparam), _callbackf, _callbackptr); \
})
static void time_format(time_t tm, char *result){
static const char month_names[12][4]={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
static const char day_names[7][4] ={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
struct tm dt;
int unsigned y;
gmtime_r(&tm, &dt);
memcpy(result, day_names[dt.tm_wday], 3);
result+=3;
*result++=',';
*result++=' ';
*result++=dt.tm_mday/10+'0';
*result++=dt.tm_mday%10+'0';
*result++=' ';
memcpy(result, month_names[dt.tm_mon], 3);
result+=3;
*result++=' ';
y=dt.tm_year+1900;
*result++='0'+y/1000;
y=y%1000;
*result++='0'+y/100;
y=y%100;
*result++='0'+y/10;
y=y%10;
*result++='0'+y;
*result++=' ';
*result++=dt.tm_hour/10+'0';
*result++=dt.tm_hour%10+'0';
*result++=':';
*result++=dt.tm_min/10+'0';
*result++=dt.tm_min%10+'0';
*result++=':';
*result++=dt.tm_sec/10+'0';
*result++=dt.tm_sec%10+'0';
memcpy(result, " +0000", 7); // copies the null byte
}
void do_debug(const char *file, const char *function, int unsigned line, int unsigned level, const char *fmt, ...){
static const struct {
int unsigned level;
const char *name;
} debug_levels[]=DEBUG_LEVELS;
static FILE *log=NULL;
char dttime[32], format[512];
va_list ap;
const char *errname;
int unsigned i;
unsigned int pid;
time_t currenttime;
errname="BAD_ERROR_CODE";
for (i=0; i<sizeof(debug_levels)/sizeof(debug_levels[0]); i++)
if (debug_levels[i].level==level){
errname=debug_levels[i].name;
break;
}
if (!log){
log=fopen(DEBUG_FILE, "a+");
if (!log)
return;
}
time(¤ttime);
time_format(currenttime, dttime);
#if !defined(MINGW) && !defined(_WIN32)
pid = (unsigned int)pthread_self();
#else
pid = (unsigned int)pthread_self().p;
#endif
snprintf(format, sizeof(format), "%s pid %u %s: %s:%u (function %s): %s\n", dttime, pid, errname, file, line, function, fmt);
format[sizeof(format)-1]=0;
va_start(ap, fmt);
vfprintf(log, format, ap);
va_end(ap);
fflush(log);
}
static binresult *do_find_res(binresult *res, const char *key){
int unsigned i;
if (!res || res->type!=PARAM_HASH)
return NULL;
for (i=0; i<res->length; i++)
if (!strcmp(res->hash[i].key, key))
return res->hash[i].value;
return NULL;
}
#define find_res_check do_find_res
#define find_res(res, key) ({\
binresult *res__=res;\
const char *key__=key;\
if (!res__)\
debug(D_WARNING, "find_res called with NULL result");\
res__=do_find_res(res__, key__);\
if (!res__)\
debug(D_ERROR, "find_res could not find key %s", key__);\
res__;\
})
#if defined(MINGW) || defined(_WIN32)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#ifndef _TIMEZONE_DEFINED /* also in sys/time.h */
#define _TIMEZONE_DEFINED
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
#endif /* _TIMEZONE_DEFINED */
int gettimeofday(struct timeval *tv, struct timezone *tz){
FILETIME ft;
uint64_t tmpres = 0;
static int tzflag = 0;
if (NULL != tv){
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
tmpres /= 10; /*convert into microseconds*/
/*converting file time to unix epoch*/
tmpres -= DELTA_EPOCH_IN_MICROSECS;
tv->tv_sec = (long)(tmpres / 1000000UL);
tv->tv_usec = (long)(tmpres % 1000000UL);
}
if (NULL != tz){
if (!tzflag){
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
#endif
static int pthread_cond_wait_sec(pthread_cond_t *cond, pthread_mutex_t *mutex, time_t sec){
struct timespec abstime;
struct timeval now;
// Sorry - this may not compile on win
gettimeofday(&now, NULL);
abstime.tv_sec=now.tv_sec+sec;
abstime.tv_nsec=now.tv_usec*1000UL;
return pthread_cond_timedwait(cond, mutex, &abstime);
}
static int pthread_cond_wait_timeout(pthread_cond_t *cond, pthread_mutex_t *mutex){
if (fs_settings.timeout)
return pthread_cond_wait_sec(cond, mutex, fs_settings.timeout);
else
return pthread_cond_wait(cond, mutex);
}
// needs to returns connected pipes (or sockets), generally pipefd[0] will be used for reading and pipefd[1] for writing
static int get_pipe(int pipefd[2]){
#ifdef WIN32
return dumb_socketpair((SOCKET*)pipefd, 1);
#else
return pipe(pipefd);
#endif
}
// should work on all platforms with select
static int ready_read(int cnt, int *socks, struct timeval *timeout){
fd_set rfds;
int max, i, ret;
FD_ZERO(&rfds);
max=0;
for (i=0; i<cnt; i++){
if (socks[i]>max)
max=socks[i];
FD_SET(socks[i], &rfds);
}
max++;
do {
ret=select(max, &rfds, NULL, NULL, timeout);
} while (ret==-1 && errno==EINTR);
if (ret<=0){
return -1;
}
for (i=0; i<cnt; i++)
if (FD_ISSET(socks[i], &rfds))
return i;
// should not happen
return 0;
}
// read & write may need to be send/recv on some platforms, on ones that support pipe, send/recv are not appropriate
ssize_t pipe_read(int fd, void *buf, size_t count){
#ifdef WIN32
return recv(fd, buf, count, 0);
#else
return read(fd, buf, count);
#endif // WIN32
}
ssize_t pipe_write(int fd, const void *buf, size_t count){
#ifdef WIN32
return send(fd, buf, count, 0);
#else
return write(fd, buf, count);
#endif // WIN32
}
static int try_to_wake_diff(){
pipe_write(diffwakefd, "W", 1);
return 0;
}
static int try_to_wake_data(){
int res;
debug(D_NOTICE, "try_to_wake_data - in");
pthread_mutex_lock(&wakelock);
pipe_write(datawakefd, "w", 1);
res=pthread_cond_wait_sec(&wakecond, &wakelock, 15);
pthread_mutex_unlock(&wakelock);
debug(D_NOTICE, "try_to_wake_data - out %d", res);
return res;
}
static int remove_task(task *ptask, uint64_t id){
task *t, **pt;
pthread_mutex_lock(&taskslock);
t=tasks;
pt=&tasks;
while (t){
if (t==ptask && t->taskid==id){
*pt=t->next;
break;
}
pt=&t->next;
t=t->next;
}
pthread_mutex_unlock(&taskslock);
return t!=NULL;
}
static binresult *do_cmd(const char *command, size_t cmdlen, const void *data, size_t datalen, binparam *params, size_t paramcnt,
task_callback callback, void *callbackptr){
uint64_t myid;
pthread_mutex_t mymutex;
pthread_cond_t mycond;
binparam nparams[paramcnt+1];
task mytask, *ptask;
binresult *res;
int cnt;
debug(D_NOTICE, "Do-cmd enter %s, %c", command, callback?'C':'D');
pthread_mutex_init(&mymutex, NULL);
pthread_cond_init(&mycond, NULL);
if (callback){
ptask=new(task);
ptask->type=TASK_TYPE_CALL;
ptask->call=callback;
ptask->result=(binresult *)callbackptr;
}
else{
ptask=&mytask;
ptask->mutex=&mymutex;
ptask->cond=&mycond;
ptask->type=TASK_TYPE_WAIT;
ptask->ready=0;
pthread_mutex_lock(&mymutex);
}
pthread_mutex_lock(&taskslock);
myid=ptask->taskid=taskid++;
ptask->next=tasks;
tasks=ptask;
pthread_mutex_unlock(&taskslock);
debug(D_NOTICE, "Do-cmd send %lu", (long unsigned int)myid);
memcpy(nparams+1, params, paramcnt*sizeof(binparam));
nparams[0].paramname="id";
nparams[0].paramnamelen=2;
nparams[0].paramtype=PARAM_NUM;
nparams[0].un.num=ptask->taskid;
debug(D_NOTICE, "Do-cmd - pre-writelock");
pthread_mutex_lock(&writelock);
debug(D_NOTICE, "Do-cmd - writelocked");
res=NULL;
cnt=0;
while (!res && cnt++<=3){
debug(D_NOTICE, "Do-cmd - sending data...");
if (datalen)
res=do_send_command(sock, command, cmdlen, nparams, paramcnt+1, datalen, 0);
else
res=do_send_command(sock, command, cmdlen, nparams, paramcnt+1, -1, 0);
if (!res && try_to_wake_data()){
debug(D_WARNING, "Do-cmd - failed to send data for command %s - reconnecting %d", command, cnt);
/*
reconnect_if_needed is designed to be called only from the receive_thread, all others can just call try_to_wake_data(),
doing both actually runs reconnect_if_needed() in both threads which is generally not a good idea.
reconnect_if_needed();
*/
break;
}
}
if (res && datalen){
if (writeall(sock, data, datalen)){
debug(D_WARNING, "Do-cmd - writeall failed for command %s", command);
res=NULL;
}
}
debug(D_NOTICE, "Do-cmd - pre writeUNlock");
pthread_mutex_unlock(&writelock);
debug(D_NOTICE, "Do-cmd - writeUNlocked");
if (!callback){
if (res){
debug(D_NOTICE, "##### Do-cmd wait %s, %" PRIu64, command, myid);
if (pthread_cond_wait_sec(&mycond, &mymutex, INITIAL_COND_TIMEOUT_SEC)){
debug(D_WARNING, "##### Do-cmd wait %s, %" PRIu64 " first timeout, try to wake", command, myid);
if (try_to_wake_data() || pthread_cond_wait_timeout(&mycond, &mymutex)){
if (remove_task(ptask, myid))
debug(D_WARNING, "##### Do-cmd %s, %" PRIu64 " second timeout, task removed", command, myid);
else
debug(D_WARNING, "##### Do-cmd %s, %" PRIu64 " second timeout, task not", command, myid);
pthread_mutex_unlock(&mymutex);
pthread_cond_destroy(&mycond);
pthread_mutex_destroy(&mymutex);
return NULL;
}
}
debug(D_NOTICE, "##### Do-cmd got %s", command);
res=ptask->result;
}
else
res=NULL;
pthread_mutex_unlock(&mymutex);
}
else if (!res){
if (remove_task(ptask, myid)){
free(ptask);
callback(callbackptr, NULL);
}
}
pthread_cond_destroy(&mycond);
pthread_mutex_destroy(&mymutex);
debug(D_NOTICE, "Do-cmd exit %s, %p", command, res);
return res;
}
static void cancel_tasks(task *t){
task *t2, *tn;
debug(D_WARNING, "called");
t2=NULL;
// reverse list so oldest tasks get cancelled/rescheduled first
while (t){
tn=t->next;
t->next=t2;
t2=t;
t=tn;
}
while (t2){
t=t2;
t2=t->next;
debug(D_WARNING, "cancelling task %lu.", (unsigned long)t->taskid);
if (t->type==TASK_TYPE_WAIT){
t->result=NULL;
debug(D_NOTICE, "task TASK_TYPE_WAIT");
pthread_mutex_lock(t->mutex);
pthread_cond_signal(t->cond);
pthread_mutex_unlock(t->mutex);
debug(D_NOTICE, "task TASK_TYPE_WAIT signalled");
}
else if (t->type==TASK_TYPE_CALL){
debug(D_NOTICE, "task TASK_TYPE_CALL - %p", t);
t->call((void *)t->result, NULL);
free(t);
debug(D_NOTICE, "task TASK_TYPE_CALL called");
}
}
debug(D_NOTICE, "leave");
}
static void cancel_all_and_reconnect(){
binresult *res;
task *t;
apisock null;
debug(D_WARNING, "cancel_all_and_reconnect");
// cancel_all();
null.ssl=NULL;
null.sock=-1;
pthread_mutex_lock(&taskslock);
pthread_mutex_lock(&writelock);
debug(D_NOTICE, "cancel_all_and_reconnect - after write lock");
api_close(sock);
do{
if (fs_settings.usessl)
sock=api_connect_ssl();
else
sock=api_connect();
if (!sock){
debug(D_WARNING, "cancel_all_and_reconnect - failed to connect");
sock=&null;
pthread_mutex_unlock(&writelock);
pthread_mutex_unlock(&taskslock);
sleep(1);
// cancel_all();
pthread_mutex_lock(&taskslock);
pthread_mutex_lock(&writelock);
sock=NULL;
}
else {
res=send_command(sock, "userinfo", P_STR("auth", auth));
if (!res){
debug(D_WARNING, "cancel_all_and_reconnect - failed to login");
api_close(sock);
sock=NULL;
}
else {
if (find_res(res, "result")->num!=0){
debug(D_ERROR, "cancel_all_and_reconnect - problem on login, exiting");
pthread_mutex_unlock(&writelock);
pthread_mutex_unlock(&taskslock);
exit(1);
}
free(res);
}
}
} while (!sock);
// sleep(1); - why do we need that sleep?
t=tasks;
tasks=NULL;
pthread_mutex_unlock(&writelock);
pthread_mutex_unlock(&taskslock);
pthread_mutex_lock(&indexlock);
connectionid++;
pthread_mutex_unlock(&indexlock);
cancel_tasks(t);
debug(D_NOTICE, "cancel_all_and_reconnect leave");
}
static void stop_and_wait_pending(){
int c=2;
pthread_mutex_lock(&calllock);
pthread_mutex_lock(&taskslock);
while (tasks || processingtask || c--){
pthread_mutex_unlock(&taskslock);
milisleep(10);
pthread_mutex_lock(&taskslock);
}
pthread_mutex_unlock(&taskslock);
}
static void resume_tasks(){
pthread_mutex_unlock(&calllock);
}
static void reconnect_if_needed(){
binresult *res;
struct timeval timeout;
debug(D_NOTICE, "data thread awake");
pthread_mutex_lock(&writelock);
res=send_command_nb(sock, "nop");
pthread_mutex_unlock(&writelock);
if (!res){
debug(D_WARNING, "reconnecting data because write failed");
return cancel_all_and_reconnect();
}
timeout.tv_sec=RECONNECT_TIMEOUT;
timeout.tv_usec=0;
if (ready_read(1, &sock->sock, &timeout)!=0){
debug(D_WARNING, "reconnecting data because socket timeouted");
return cancel_all_and_reconnect();
}
debug(D_NOTICE, "no reconnection needed, socket alive");
}
static void *receive_thread(void *ptr){
binresult *res, *id, *sub;
task *t, **pt;
struct timeval timeout;
int wakefds[2], monitorfds[2], r, rhasdata;
char b;
if (get_pipe(wakefds))
return NULL;
datawakefd=wakefds[1];
monitorfds[0]=wakefds[0];
while (1){
monitorfds[1]=sock->sock;
if (hasdata(sock))
r=1;
else{
if (tasks){
timeout.tv_sec=RECONNECT_TIMEOUT;
timeout.tv_usec=0;
r=ready_read(2, monitorfds, &timeout);
if (r==-1){
debug(D_WARNING, "read socket timeouted, reconnecting");
cancel_all_and_reconnect();
continue;
}
}
else{
timeout.tv_sec=1;
timeout.tv_usec=0;
r=ready_read(2, monitorfds, &timeout);
if (r==-1)
continue;
}
}
if (r==1)
res=get_result(sock);
else if (r==0){
pipe_read(wakefds[0], &b, 1);
debug(D_WARNING, "wake message received, calling reconnect_if_needed");
reconnect_if_needed();
pthread_mutex_lock(&wakelock);
pthread_cond_broadcast(&wakecond);
pthread_mutex_unlock(&wakelock);
continue;
}
else{
debug(D_BUG, "ready_read returned %d, should not happen", r);
break; // should not happen
}
if (!res){
debug(D_WARNING, "get_result returned NULL, reconnecting");
cancel_all_and_reconnect();
continue;
}
id=find_res_check(res, "id");
if (!id || id->type!=PARAM_NUM){
free(res);
debug(D_WARNING, "receive_thread - no ID, could be a nop or truncate");
continue;
}
debug(D_NOTICE, "receive_thread received %lu", (unsigned long)id->num);
pthread_mutex_lock(&taskslock);
pt=&tasks;
t=tasks;
while (t){
if (t->taskid==id->num){
*pt=t->next;
processingtask++;
break;
}
pt=&t->next;
t=t->next;
}
pthread_mutex_unlock(&taskslock);
if (!t){
free(res);
debug(D_BUG, "could not find task %lu", (long unsigned)id->num);
continue;
}
sub=find_res_check(res, "data");
rhasdata=sub && sub->type==PARAM_DATA;
/* !!! IMPORTANT !!!
* if we have TASK_TYPE_WAIT, t is on the stack of the thread waiting on t->cond, therefore no free
* if we have TASK_TYPE_CALL, t is allcated and we need to free. callback does not have to free the result
*/
if (t->type==TASK_TYPE_WAIT){
t->result=res;
if (rhasdata){
pthread_mutex_lock(&datamutex);
}
pthread_mutex_lock(t->mutex);
pthread_cond_signal(t->cond);
pthread_mutex_unlock(t->mutex);
if (rhasdata){
pthread_cond_wait(&datacond, &datamutex);
pthread_mutex_unlock(&datamutex);
}
}
else if (t->type==TASK_TYPE_CALL){
// debug(D_NOTICE, "receive thread calling task - %p\n", t);
t->call((void *)t->result, res);
// debug(D_NOTICE, "receive thread task called - %p\n", t);
free(res);
free(t);
}
else
free(res);
pthread_mutex_lock(&taskslock);
processingtask--;
pthread_mutex_unlock(&taskslock);
if (need_reconnect){
need_reconnect=0;
cancel_all_and_reconnect();
}
// debug(D_NOTICE, "receive_thread - end loop\n");
}
return NULL;
}
static void send_event_message(uint64_t diffid, uint32_t utype, ...){
struct iovec iovs[64];
va_list ap;
const char *str;
size_t len, msglen;
uint32_t ulen;
int o;
va_start(ap, utype);
msglen=0;
o=3;
while ((str=va_arg(ap, const char *))) {
len=strlen(str);
msglen+=len;
iovs[o].iov_base=(char *)str;
iovs[o].iov_len=len;
o++;
}
va_end(ap);
ulen=msglen;
iovs[0].iov_base=&diffid;
iovs[0].iov_len=sizeof(diffid);
iovs[1].iov_base=&utype;
iovs[1].iov_len=sizeof(utype);
iovs[2].iov_base=&ulen;
iovs[2].iov_len=sizeof(ulen);
event_writev(iovs, o);
}
static node *get_file_by_id(uint64_t fileid){
node *f;
f=files[fileid%HASH_SIZE];
while (f){
if (f->tfile.fileid==fileid)
return f;
f=f->next;
}
return NULL;
}
static node *get_folder_by_id(uint64_t folderid){
node *f;
f=folders[folderid%HASH_SIZE];
while (f){
if (f->tfolder.folderid==folderid)
return f;
f=f->next;
}
return NULL;
}
#if defined(MINGW) || defined(_WIN32)
static void build_full_path(char** full_path, node *f){
if (f->parent){
build_full_path(full_path, f->parent);
(*full_path)[0] = '/';
strcpy(*full_path+1, f->name);
(*full_path) += strlen(f->name)+1;
}
}
#define PIPE_NAME L"\\\\.\\pipe\\pfsnotifypipe"
#define SHCNE_CREATE (0x00000002)
#define SHCNE_DELETE (0x00000004)
#define SHCNE_MKDIR (0x00000008)
#define SHCNE_RMDIR (0x00000010)
#define SHCNE_ATTRIBUTES (0x00000800)
#define SHCNE_UPDATEDIR (0x00001000)
#define SHCNE_UPDATEITEM (0x00002000)
typedef struct
{