-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpfsupload.c
1659 lines (1588 loc) · 57.6 KB
/
pfsupload.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
/* Copyright (c) 2014 Anton Titov.
* Copyright (c) 2014 pCloud Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of pCloud Ltd nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL pCloud Ltd BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "plibs.h"
#include "pstatus.h"
#include "ptimer.h"
#include "psettings.h"
#include "pfsupload.h"
#include "plist.h"
#include "pnetlibs.h"
#include "pfstasks.h"
#include "pfileops.h"
#include "ppagecache.h"
#include "pssl.h"
#include "pfsxattr.h"
#include "pupload.h"
#include "pfscrypto.h"
#include "pcache.h"
#include <string.h>
typedef struct {
psync_list list;
binresult *res;
uint64_t id;
uint64_t type;
psync_folderid_t folderid;
psync_folderid_t sfolderid;
psync_fileid_t fileid;
const char *text1;
const char *text2;
int64_t int1;
int64_t int2;
unsigned char ccreat;
unsigned char needprocessing;
unsigned char status;
} fsupload_task_t;
static pthread_mutex_t upload_mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t upload_cond=PTHREAD_COND_INITIALIZER;
static uint64_t current_upload_taskid=0;
static uint32_t upload_wakes=0;
static int large_upload_running=0;
static int stop_current_upload=0;
static psync_list *current_upload_batch=NULL;
static const uint32_t requiredstatuses[]={
PSTATUS_COMBINE(PSTATUS_TYPE_AUTH, PSTATUS_AUTH_PROVIDED),
PSTATUS_COMBINE(PSTATUS_TYPE_RUN, PSTATUS_RUN_RUN),
PSTATUS_COMBINE(PSTATUS_TYPE_ONLINE, PSTATUS_ONLINE_ONLINE),
PSTATUS_COMBINE(PSTATUS_TYPE_ACCFULL, PSTATUS_ACCFULL_QUOTAOK)
};
static const uint32_t requiredstatusesnooverquota[]={
PSTATUS_COMBINE(PSTATUS_TYPE_AUTH, PSTATUS_AUTH_PROVIDED),
PSTATUS_COMBINE(PSTATUS_TYPE_RUN, PSTATUS_RUN_RUN),
PSTATUS_COMBINE(PSTATUS_TYPE_ONLINE, PSTATUS_ONLINE_ONLINE)
};
static int psync_send_task_mkdir(psync_socket *api, fsupload_task_t *task){
if (task->text2){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", task->folderid), P_STR("name", task->text1), P_STR("timeformat", "timestamp"),
P_BOOL("encrypted", 1), P_STR("key", task->text2)};
if (likely_log(send_command_no_res(api, "createfolderifnotexists", params)==PTR_OK))
return 0;
else
return -1;
}
else{
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", task->folderid), P_STR("name", task->text1), P_STR("timeformat", "timestamp")};
if (likely_log(send_command_no_res(api, "createfolderifnotexists", params)==PTR_OK))
return 0;
else
return -1;
}
}
static void handle_mkdir_api_error(uint64_t result, fsupload_task_t *task){
psync_sql_res *res;
debug(D_ERROR, "createfolderifnotexists returned error %u", (unsigned)result);
psync_process_api_error(result);
switch (result){
case 2002: /* parent does not exists */
case 2003: /* access denied */
res=psync_sql_prep_statement("UPDATE fstask SET folderid=0 WHERE id=?");
psync_sql_bind_uint(res, 1, task->id);
psync_sql_run_free(res);
break;
case 2001: /* invalid name */
res=psync_sql_prep_statement("UPDATE fstask SET text1=\"Invalid Name Requested\" WHERE id=?");
psync_sql_bind_uint(res, 1, task->id);
psync_sql_run_free(res);
break;
default:
break;
}
}
static int psync_process_task_mkdir(fsupload_task_t *task){
const binresult *meta;
uint64_t result;
psync_folderid_t folderid;
result=psync_find_result(task->res, "result", PARAM_NUM)->num;
if (result){
handle_mkdir_api_error(result, task);
return -1;
}
meta=psync_find_result(task->res, "metadata", PARAM_HASH);
folderid=psync_find_result(meta, "folderid", PARAM_NUM)->num;
task->int2=folderid;
psync_ops_create_folder_in_db(meta);
psync_fstask_folder_created(task->folderid, task->id, folderid, task->text1);
psync_fs_task_to_folder(task->id, folderid);
if (task->text2 && psync_find_result(task->res, "created", PARAM_BOOL)->num){
psync_sql_res *res;
unsigned char *enckey;
size_t enckeylen;
enckey=psync_base64_decode((const unsigned char *)task->text2, strlen(task->text2), &enckeylen);
if (likely_log(enckey)){
res=psync_sql_prep_statement("REPLACE INTO cryptofolderkey (folderid, enckey) VALUES (?, ?)");
psync_sql_bind_uint(res, 1, folderid);
psync_sql_bind_blob(res, 2, (char *)enckey, enckeylen);
psync_sql_run_free(res);
psync_free(enckey);
}
}
debug(D_NOTICE, "folder %lu/%s created", (unsigned long)task->folderid, task->text1);
return 0;
}
static int psync_send_task_rmdir(psync_socket *api, fsupload_task_t *task){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", task->sfolderid), P_STR("timeformat", "timestamp")};
if (likely_log(send_command_no_res(api, "deletefolder", params)==PTR_OK))
return 0;
else
return -1;
}
static int handle_rmdir_api_error(uint64_t result, fsupload_task_t *task){
debug(D_ERROR, "deletefolder returned error %u", (unsigned)result);
psync_process_api_error(result);
switch (result){
case 2005: /* folder does not exist, kind of success */
//psync_ops_delete_folder_from_db(task->sfolderid);
psync_fstask_folder_deleted(task->folderid, task->id, task->text1);
return 0;
case 2003: /* access denied, skip*/
case 2006: /* not empty */
case 2028: /* folder is shared */
psync_fstask_folder_deleted(task->folderid, task->id, task->text1);
return 0;
default:
return -1;
}
}
static int psync_process_task_rmdir(fsupload_task_t *task){
uint64_t result;
result=psync_find_result(task->res, "result", PARAM_NUM)->num;
if (result)
return handle_rmdir_api_error(result, task);
psync_ops_delete_folder_from_db(psync_find_result(task->res, "metadata", PARAM_HASH));
psync_fstask_folder_deleted(task->folderid, task->id, task->text1);
debug(D_NOTICE, "folder %lu/%s deleted", (unsigned long)task->folderid, task->text1);
return 0;
}
static int psync_send_task_creat_upload_small(psync_socket *api, fsupload_task_t *task, psync_file_t fd, psync_stat_t *st){
unsigned char *data;
uint64_t size;
size_t len;
size=psync_stat_size(st);
if (task->text2){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", task->folderid), P_STR("filename", task->text1),
P_BOOL("nopartial", 1), /*P_STR("ifhash", "new"), */P_STR("timeformat", "timestamp"),
P_NUM("mtime", psync_stat_mtime(st)), P_BOOL("encrypted", 1), P_STR("key", task->text2)};
data=prepare_command_data_alloc("uploadfile", params, size, size, &len);
}
else{
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", task->folderid), P_STR("filename", task->text1),
P_BOOL("nopartial", 1), /*P_STR("ifhash", "new"), */P_STR("timeformat", "timestamp"), P_NUM("mtime", psync_stat_mtime(st))};
data=prepare_command_data_alloc("uploadfile", params, size, size, &len);
}
if (unlikely_log(psync_file_read(fd, data+len, size)!=size) || unlikely_log(psync_fs_get_file_writeid(task->id)!=task->int1)){
psync_free(data);
return -1;
}
size+=len;
if (unlikely_log(psync_socket_writeall_upload(api, data, size)!=size)){
psync_free(data);
return -1;
}
else{
psync_free(data);
return 0;
}
}
static int large_upload_creat_send_write(psync_socket *api, psync_uploadid_t uploadid, uint64_t offset, uint64_t length){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadoffset", offset), P_NUM("uploadid", uploadid)};
if (unlikely_log(!do_send_command(api, "upload_write", strlen("upload_write"), params, ARRAY_SIZE(params), length, 0)))
return -1;
else
return 0;
}
static int clean_uploads_for_task(psync_socket *api, psync_uploadid_t taskid){
psync_sql_res *sql;
psync_full_result_int *fr;
binresult *res;
uint32_t i;
int ret;
ret=0;
sql=psync_sql_query_rdlock("SELECT uploadid FROM fstaskupload WHERE fstaskid=?");
psync_sql_bind_uint(sql, 1, taskid);
fr=psync_sql_fetchall_int(sql);
for (i=0; i<fr->rows; i++){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadid", psync_get_result_cell(fr, i, 0))};
res=send_command(api, "upload_delete", params);
if (!res){
ret=-1;
break;
}
else
psync_free(res);
}
sql=psync_sql_prep_statement("DELETE FROM fstaskupload WHERE fstaskid=?");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_run_free(sql);
return ret;
}
/* releases api ONLY on error */
static int large_upload_check_checksum(psync_socket *api, uint64_t uploadid, const unsigned char *filehash){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadid", uploadid)};
binresult *res;
uint64_t result;
res=send_command(api, "upload_info", params);
if (unlikely_log(!res)){
psync_apipool_release_bad(api);
return -1;
}
result=psync_find_result(res, "result", PARAM_NUM)->num;
if (unlikely(result)){
debug(D_WARNING, "upload_info returned %lu", (long unsigned)result);
psync_free(res);
psync_apipool_release(api);
psync_process_api_error(result);
return -1;
}
if (memcmp(filehash, psync_find_result(res, PSYNC_CHECKSUM, PARAM_STR)->str, PSYNC_HASH_DIGEST_HEXLEN)){
debug(D_WARNING, "upload_info returned different checksum");
psync_free(res);
psync_apipool_release(api);
return -1;
}
psync_free(res);
return 0;
}
static int handle_upload_api_error_taskid(uint64_t result, uint64_t taskid){
psync_sql_res *res;
psync_process_api_error(result);
switch (result){
case 2005: /* folder does not exists */
case 2003: /* access denied */
res=psync_sql_prep_statement("UPDATE fstask SET folderid=0 WHERE id=?");
psync_sql_bind_uint(res, 1, taskid);
psync_sql_run_free(res);
return -1;
case 2001: /* invalid filename */
res=psync_sql_prep_statement("UPDATE fstask SET text1=\"Invalid Name Requested\" WHERE id=?");
psync_sql_bind_uint(res, 1, taskid);
psync_sql_run_free(res);
return -1;
case 2008:{ /* overquota */
int locked=psync_sql_islocked();
if (locked)
psync_sql_commit_transaction();
assert(!psync_sql_islocked());
psync_milisleep(PSYNC_SLEEP_ON_DISK_FULL);
if (locked)
psync_sql_start_transaction();
return -1;
}
case 2124: /* crypto expired */
res=psync_sql_prep_statement("UPDATE fstask SET status=1 WHERE id=?");
psync_sql_bind_uint(res, 1, taskid);
psync_sql_run_free(res);
return -1;
default:
return -1;
}
}
static int handle_upload_api_error(uint64_t result, fsupload_task_t *task){
debug(D_ERROR, "uploadfile returned error %u", (unsigned)result);
return handle_upload_api_error_taskid(result, task->id);
}
static void set_key_for_fileid(psync_fileid_t fileid, uint64_t hash, const char *key){
char buff[16];
psync_sql_res *res;
unsigned char *enckey;
size_t enckeylen;
enckey=psync_base64_decode((const unsigned char *)key, strlen(key), &enckeylen);
if (likely_log(enckey)){
res=psync_sql_prep_statement("REPLACE INTO cryptofilekey (fileid, hash, enckey) VALUES (?, ?, ?)");
psync_sql_bind_uint(res, 1, fileid);
psync_sql_bind_uint(res, 2, hash);
psync_sql_bind_blob(res, 3, (char *)enckey, enckeylen);
psync_sql_run_free(res);
psync_free(enckey);
}
psync_get_string_id(buff, "DKEY", fileid);
psync_cache_del(buff);
}
static int save_meta(const binresult *meta, psync_folderid_t folderid, const char *name, uint64_t taskid, uint64_t writeid, int newfile,
uint64_t oldhash, const char *key){
psync_sql_res *sql;
uint64_t hash, size;
psync_fileid_t fileid;
fileid=psync_find_result(meta, "fileid", PARAM_NUM)->num;
hash=psync_find_result(meta, "hash", PARAM_NUM)->num;
size=psync_find_result(meta, "size", PARAM_NUM)->num;
psync_sql_start_transaction();
if (psync_fs_update_openfile(taskid, writeid, fileid, hash, size, psync_find_result(meta, "created", PARAM_NUM)->num)){
psync_sql_rollback_transaction();
debug(D_NOTICE, "upload of %s cancelled due to writeid mismatch", name);
return -1;
}
if (newfile){
psync_ops_create_file_in_db(meta);
psync_pagecache_creat_to_pagecache(taskid, hash);
psync_fstask_file_created(folderid, taskid, name, fileid);
psync_fs_task_to_file(taskid, fileid);
}
else{
psync_ops_update_file_in_db(meta);
psync_pagecache_modify_to_pagecache(taskid, hash, oldhash);
psync_fstask_file_modified(folderid, taskid, name, fileid);
}
if (key)
set_key_for_fileid(fileid, hash, key);
sql=psync_sql_prep_statement("DELETE FROM fstaskdepend WHERE dependfstaskid=?");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_run_free(sql);
if (psync_sql_affected_rows())
psync_fsupload_wake();
sql=psync_sql_prep_statement("DELETE FROM fstaskupload WHERE fstaskid=?");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_run_free(sql);
sql=psync_sql_prep_statement("UPDATE fstask SET fileid=? WHERE fileid=?");
psync_sql_bind_uint(sql, 1, fileid);
psync_sql_bind_int(sql, 2, -(psync_fsfileid_t)taskid);
psync_sql_run_free(sql);
sql=psync_sql_prep_statement("UPDATE fstask SET status=3 WHERE id=? AND int1=?");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_bind_uint(sql, 2, writeid);
psync_sql_run_free(sql);
if (!psync_sql_affected_rows()){
debug(D_BUG, "upload of %s cancelled due to writeid mismatch, psync_fs_update_openfile should have catched that", name);
psync_sql_rollback_transaction();
return -1;
}
psync_sql_commit_transaction();
debug(D_NOTICE, "file %lu/%s uploaded", (unsigned long)folderid, name);
psync_status_recalc_to_upload_async();
return 0;
}
static int large_upload_save(psync_socket *api, uint64_t uploadid, psync_folderid_t folderid, const char *name,
uint64_t taskid, uint64_t writeid, int newfile, uint64_t oldhash, const char *key, const char *filepath){
binresult *res;
psync_stat_t st;
uint64_t result;
int ret;
if (psync_stat(filepath, &st)){
debug(D_WARNING, "could not stat file %s", filepath);
psync_apipool_release(api);
return -1;
}
if (key){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", folderid), P_STR("name", name), P_NUM("uploadid", uploadid),
P_STR("timeformat", "timestamp"), P_NUM("mtime", psync_stat_mtime(&st)), P_BOOL("encrypted", 1), P_STR("key", key)};
res=send_command(api, "upload_save", params);
}
else{
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("folderid", folderid), P_STR("name", name), P_NUM("uploadid", uploadid),
/*P_STR("ifhash", "new"), */P_STR("timeformat", "timestamp"), P_NUM("mtime", psync_stat_mtime(&st))};
res=send_command(api, "upload_save", params);
}
if (unlikely_log(!res)){
psync_apipool_release_bad(api);
return -1;
}
psync_apipool_release(api);
result=psync_find_result(res, "result", PARAM_NUM)->num;
if (unlikely(result)){
debug(D_WARNING, "upload_save returned %lu", (long unsigned)result);
psync_free(res);
handle_upload_api_error_taskid(result, taskid);
return -1;
}
ret=save_meta(psync_find_result(res, "metadata", PARAM_HASH), folderid, name, taskid, writeid, newfile, oldhash, key);
psync_free(res);
return ret;
}
static void perm_fail_upload_task(uint64_t taskid){
psync_sql_res *sql;
debug(D_WARNING, "failed task %lu", (unsigned long)taskid);
psync_sql_start_transaction();
sql=psync_sql_prep_statement("DELETE FROM fstaskdepend WHERE dependfstaskid=?");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_run_free(sql);
if (psync_sql_affected_rows())
psync_fsupload_wake();
sql=psync_sql_prep_statement("DELETE FROM fstask WHERE fileid=?");
psync_sql_bind_int(sql, 1, -(psync_fsfileid_t)taskid);
psync_sql_run_free(sql);
sql=psync_sql_prep_statement("DELETE FROM fstask WHERE id=?");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_run_free(sql);
psync_fs_task_deleted(taskid);
psync_sql_commit_transaction();
}
static int copy_file(psync_socket *api, psync_fileid_t fileid, uint64_t hash, psync_folderid_t folderid, const char *name, uint64_t taskid, uint64_t writeid){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("fileid", fileid), P_NUM("hash", hash), P_NUM("tofolderid", folderid),
P_STR("toname", name), P_STR("timeformat", "timestamp")};
binresult *res;
const binresult *meta;
uint64_t result;
int ret;
res=send_command(api, "copyfile", params);
if (unlikely(!res))
return -1;
result=psync_find_result(res, "result", PARAM_NUM)->num;
if (unlikely(result)){
psync_free(res);
debug(D_WARNING, "command copyfile returned code %u", (unsigned)result);
psync_process_api_error(result);
return 0;
}
meta=psync_find_result(res, "metadata", PARAM_HASH);
ret=save_meta(meta, folderid, name, taskid, writeid, 1, 0, NULL);
psync_free(res);
if (ret) // ret*2-1?
return -1;
else
return 1;
}
static int copy_file_if_exists(psync_socket *api, const unsigned char *hashhex, uint64_t fsize, psync_folderid_t folderid, const char *name,
uint64_t taskid, uint64_t writeid){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("size", fsize), P_LSTR(PSYNC_CHECKSUM, hashhex, PSYNC_HASH_DIGEST_HEXLEN)};
binresult *res;
const binresult *metas, *meta;
uint64_t result;
int ret;
res=send_command(api, "getfilesbychecksum", params);
if (unlikely(!res))
return -1;
result=psync_find_result(res, "result", PARAM_NUM)->num;
if (unlikely(result)){
psync_free(res);
debug(D_WARNING, "command getfilesbychecksum returned code %u", (unsigned)result);
psync_process_api_error(result);
return 0;
}
metas=psync_find_result(res, "metadata", PARAM_ARRAY);
if (!metas->length){
psync_free(res);
return 0;
}
meta=metas->array[0];
ret=copy_file(api, psync_find_result(meta, "fileid", PARAM_NUM)->num, psync_find_result(meta, "hash", PARAM_NUM)->num, folderid, name, taskid, writeid);
if (ret==1)
debug(D_NOTICE, "file %lu/%s copied to %lu/%s instead of uploading due to matching checksum",
(long unsigned)psync_find_result(meta, "parentfolderid", PARAM_NUM)->num, psync_find_result(meta, "name", PARAM_STR)->str,
(long unsigned)folderid, name);
psync_free(res);
return ret;
}
static int large_upload_creat(uint64_t taskid, psync_folderid_t folderid, const char *name, const char *filename,
psync_uploadid_t uploadid, uint64_t writeid, const char *key){
psync_sql_res *sql;
psync_socket *api;
binresult *res;
void *buff;
uint64_t usize, fsize, result, asize;
size_t rd;
ssize_t rrd;
psync_file_t fd;
int ret;
unsigned char uploadhash[PSYNC_HASH_DIGEST_HEXLEN], filehash[PSYNC_HASH_DIGEST_HEXLEN], fileparthash[PSYNC_HASH_DIGEST_HEXLEN];
debug(D_NOTICE, "uploading %s as %lu/%s (uploadid=%lu)", filename, (unsigned long)folderid, name, (unsigned long)uploadid);
asize=0;
if (uploadid){
ret=psync_get_upload_checksum(uploadid, uploadhash, &usize);
if (ret!=PSYNC_NET_OK){
if (ret==PSYNC_NET_TEMPFAIL)
return -1;
else
uploadid=0;
}
}
if (uploadid)
ret=psync_get_local_file_checksum_part(filename, filehash, &fsize, fileparthash, usize);
else
ret=psync_get_local_file_checksum(filename, filehash, &fsize);
if (ret){
perm_fail_upload_task(taskid);
debug(D_WARNING, "could not open local file %s, skipping task", filename);
return 0;
}
if (uploadid && memcmp(fileparthash, uploadhash, PSYNC_HASH_DIGEST_HEXLEN))
uploadid=0;
api=psync_apipool_get();
if (unlikely(!api))
return -1;
if (!key){
ret=copy_file_if_exists(api, filehash, fsize, folderid, name, taskid, writeid);
if (ret!=0){
if (ret==1){
psync_apipool_release(api);
return 0;
}
else{
psync_apipool_release_bad(api);
return -1;
}
}
}
if (!uploadid || usize>fsize){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("filesize", fsize)};
usize=0;
res=send_command(api, "upload_create", params);
if (!res)
goto err0;
result=psync_find_result(res, "result", PARAM_NUM)->num;
if (unlikely(result)){
psync_free(res);
psync_apipool_release(api);
debug(D_WARNING, "upload_create returned %lu", (unsigned long)result);
psync_process_api_error(result);
if (psync_handle_api_result(result)==PSYNC_NET_TEMPFAIL)
return -1;
else
return 0;
}
uploadid=psync_find_result(res, "uploadid", PARAM_NUM)->num;
psync_free(res);
sql=psync_sql_prep_statement("INSERT INTO fstaskupload (fstaskid, uploadid) VALUES (?, ?)");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_bind_uint(sql, 2, uploadid);
psync_sql_run_free(sql);
}
fd=psync_file_open(filename, P_O_RDONLY, 0);
if (unlikely_log(fd==INVALID_HANDLE_VALUE))
goto ret0;
if (usize){
debug(D_NOTICE, "resuming from offset %lu", (unsigned long)usize);
if (unlikely_log(psync_file_seek(fd, usize, P_SEEK_SET)==-1))
goto ret01;
}
if (large_upload_creat_send_write(api, uploadid, usize, fsize-usize))
goto err1;
buff=psync_malloc(PSYNC_COPY_BUFFER_SIZE);
if (usize){
asize=usize;
psync_upload_add_bytes_uploaded(asize);
}
while (usize<fsize){
if (unlikely(stop_current_upload)){
debug(D_NOTICE, "got stop for file %s", name);
goto err2;
}
psync_wait_statuses_array(requiredstatuses, ARRAY_SIZE(requiredstatuses));
if (fsize-usize>PSYNC_COPY_BUFFER_SIZE)
rd=PSYNC_COPY_BUFFER_SIZE;
else
rd=fsize-usize;
rrd=psync_file_read(fd, buff, rd);
if (unlikely_log(rrd<=0))
goto err2;
usize+=rrd;
if (unlikely_log(psync_socket_writeall_upload(api, buff, rrd)!=rrd))
goto err2;
asize+=rrd;
psync_upload_add_bytes_uploaded(rrd);
}
psync_free(buff);
psync_file_close(fd);
res=get_result(api);
if (unlikely_log(!res))
goto err0;
result=psync_find_result(res, "result", PARAM_NUM)->num;
psync_free(res);
if (result){
debug(D_WARNING, "upload_write returned error %lu", (long unsigned)result);
psync_process_api_error(result);
if (result==2068){
if (clean_uploads_for_task(api, taskid))
psync_apipool_release_bad(api);
else
psync_apipool_release(api);
}
psync_process_api_error(result);
goto errs;
}
// large_upload_check_checksum releases api on failure
if (large_upload_check_checksum(api, uploadid, filehash))
goto errs;
if (psync_fs_get_file_writeid(taskid)!=writeid){
debug(D_NOTICE, "%s changed while uploading as %lu/%s", filename, (unsigned long)folderid, name);
psync_apipool_release(api);
goto errs;
}
if (asize){
psync_upload_sub_bytes_uploaded(asize);
asize=0;
}
return large_upload_save(api, uploadid, folderid, name, taskid, writeid, 1, 0, key, filename);
ret01:
psync_file_close(fd);
ret0:
psync_apipool_release(api);
perm_fail_upload_task(taskid);
if (asize)
psync_upload_sub_bytes_uploaded(asize);
return 0;
err2:
psync_free(buff);
err1:
psync_file_close(fd);
err0:
psync_apipool_release_bad(api);
errs:
if (asize)
psync_upload_sub_bytes_uploaded(asize);
return PRINT_RETURN(-1);
}
static int64_t i64min(int64_t a, int64_t b){
return a<b?a:b;
}
static int upload_modify_send_copy_from(psync_socket *api, psync_uploadid_t uploadid, uint64_t offset, uint64_t length,
psync_fileid_t fileid, uint64_t hash, uint64_t *upl){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadoffset", offset), P_NUM("uploadid", uploadid),
P_NUM("fileid", fileid), P_NUM("hash", hash), P_NUM("offset", offset), P_NUM("count", length)};
debug(D_NOTICE, "copying %lu bytes from fileid %lu hash %lu at offset %lu", (unsigned long)length, (unsigned long)fileid, (unsigned long) hash, (unsigned long)offset);
if (unlikely_log(!send_command_no_res(api, "upload_writefromfile", params)))
return PSYNC_NET_TEMPFAIL;
else{
*upl+=length;
psync_upload_add_bytes_uploaded(length);
return PSYNC_NET_OK;
}
}
static int upload_modify_send_local(psync_socket *api, psync_uploadid_t uploadid, uint64_t offset, uint64_t length, psync_file_t fd, uint64_t *upl){
binparam params[]={P_STR("auth", psync_my_auth), P_NUM("uploadoffset", offset), P_NUM("uploadid", uploadid)};
void *buff;
uint64_t bw;
size_t rd;
ssize_t rrd;
debug(D_NOTICE, "uploading %lu byte from local file at offset %lu", (unsigned long)length, (unsigned long)offset);
if (unlikely_log(psync_file_seek(fd, offset, P_SEEK_SET)==-1) ||
unlikely_log(!do_send_command(api, "upload_write", strlen("upload_write"), params, ARRAY_SIZE(params), length, 0)))
return PSYNC_NET_TEMPFAIL;
bw=0;
buff=psync_malloc(PSYNC_COPY_BUFFER_SIZE);
while (bw<length){
if (unlikely(stop_current_upload)){
debug(D_NOTICE, "got stop");
goto err0;
}
psync_wait_statuses_array(requiredstatuses, ARRAY_SIZE(requiredstatuses));
if (length-bw>PSYNC_COPY_BUFFER_SIZE)
rd=PSYNC_COPY_BUFFER_SIZE;
else
rd=length-bw;
rrd=psync_file_read(fd, buff, rd);
if (unlikely_log(rrd<=0)){
if (rrd==0)
goto errp;
else
goto err0;
}
bw+=rrd;
if (unlikely_log(psync_socket_writeall_upload(api, buff, rrd)!=rrd))
goto err0;
*upl+=rrd;
psync_upload_add_bytes_uploaded(rrd);
}
psync_free(buff);
return PSYNC_NET_OK;
err0:
psync_free(buff);
return PSYNC_NET_TEMPFAIL;
errp:
psync_free(buff);
return PSYNC_NET_PERMFAIL;
}
static int upload_modify_read_req(psync_socket *api){
binresult *res;
uint64_t result;
res=get_result(api);
if (!res)
return PSYNC_NET_TEMPFAIL;
result=psync_find_result(res, "result", PARAM_NUM)->num;
psync_free(res);
if (result){
debug(D_WARNING, "got %lu from upload_writefromfile or upload_write", (unsigned long)result);
psync_process_api_error(result);
return psync_handle_api_result(result);
}
else
return PSYNC_NET_OK;
}
int upload_modify(uint64_t taskid, psync_folderid_t folderid, const char *name, const char *filename, const char *indexname, psync_fileid_t fileid,
uint64_t hash, uint64_t writeid, const char *key){
binparam aparams[]={P_STR("auth", psync_my_auth)};
psync_interval_tree_t *tree, *cinterval;
psync_socket *api;
binresult *res;
psync_sql_res *sql;
int64_t fsize, coff, len;
uint64_t result, asize;
psync_uploadid_t uploadid;
psync_uint_t reqs;
psync_file_t fd;
psync_fs_err_t err;
int ret;
debug(D_NOTICE, "uploading modified file %s as %lu/%s", filename, (unsigned long)folderid, name);
asize=0;
fd=psync_file_open(indexname, P_O_RDONLY, 0);
if (unlikely(fd==INVALID_HANDLE_VALUE)){
err=psync_fs_err();
debug(D_WARNING, "can not open %s", indexname);
if (err==P_NOENT){
perm_fail_upload_task(taskid);
return 0;
}
else
return -1;
}
tree=NULL;
if (unlikely_log((fsize=psync_file_size(fd))==-1 || psync_fs_load_interval_tree(fd, fsize, &tree)==-1)){
psync_interval_tree_free(tree);
psync_file_close(fd);
return -1;
}
psync_file_close(fd);
api=psync_apipool_get();
if (unlikely_log(!api))
goto err1;
if (unlikely_log(clean_uploads_for_task(api, taskid)))
goto err2;
res=send_command(api, "upload_create", aparams);
if (unlikely_log(!res))
goto err2;
result=psync_find_result(res, "result", PARAM_NUM)->num;
if (unlikely(result)){
psync_free(res);
psync_apipool_release(api);
psync_interval_tree_free(tree);
debug(D_WARNING, "upload_create returned %lu", (unsigned long)result);
psync_process_api_error(result);
if (psync_handle_api_result(result)==PSYNC_NET_TEMPFAIL)
return -1;
else
return 0;
}
uploadid=psync_find_result(res, "uploadid", PARAM_NUM)->num;
psync_free(res);
sql=psync_sql_prep_statement("INSERT INTO fstaskupload (fstaskid, uploadid) VALUES (?, ?)");
psync_sql_bind_uint(sql, 1, taskid);
psync_sql_bind_uint(sql, 2, uploadid);
psync_sql_run_free(sql);
fd=psync_file_open(filename, P_O_RDONLY, 0);
if (unlikely(fd==INVALID_HANDLE_VALUE)){
err=psync_fs_err();
debug(D_WARNING, "can not open %s", filename);
psync_apipool_release(api);
psync_interval_tree_free(tree);
if (err==P_NOENT){
perm_fail_upload_task(taskid);
return 0;
}
else
return -1;
}
fsize=psync_file_size(fd);
if (unlikely_log(fsize==-1))
goto err3;
coff=0;
reqs=0;
cinterval=psync_interval_tree_get_first(tree);
while (coff<fsize){
if (reqs && (psync_socket_pendingdata(api) || psync_select_in(&api->sock, 1, 0)!=SOCKET_ERROR)){
if ((ret=upload_modify_read_req(api))){
if (unlikely_log(ret==PSYNC_NET_PERMFAIL))
perm_fail_upload_task(taskid);
goto err3;
}
else
reqs--;
}
if (cinterval){
if (cinterval->from>coff){
len=i64min(cinterval->from, fsize)-coff;
ret=upload_modify_send_copy_from(api, uploadid, coff, len, fileid, hash, &asize);
reqs++;
coff+=len;
}
else if (cinterval->from<=coff && cinterval->to>coff){
ret=upload_modify_send_local(api, uploadid, coff, i64min(cinterval->to, fsize)-coff, fd, &asize);
reqs++;
coff=cinterval->to;
cinterval=psync_interval_tree_get_next(cinterval);
}
else{
debug(D_BUG, "broken interval tree");
break;
}
}
else{
ret=upload_modify_send_copy_from(api, uploadid, coff, fsize-coff, fileid, hash, &asize);
reqs++;
coff=fsize;
}
if (ret){
if (unlikely_log(ret==PSYNC_NET_PERMFAIL))
perm_fail_upload_task(taskid);
goto err3;
}
if (unlikely(stop_current_upload)){
debug(D_NOTICE, "got stop for file %s", name);
goto err3;
}
}
psync_file_close(fd);
while (reqs--)
if ((ret=upload_modify_read_req(api))){
if (unlikely_log(ret==PSYNC_NET_PERMFAIL))
perm_fail_upload_task(taskid);
goto err2;
}
psync_interval_tree_free(tree);
psync_upload_sub_bytes_uploaded(asize);
if (psync_fs_get_file_writeid(taskid)!=writeid){
debug(D_NOTICE, "%s changed while uploading as %lu/%s", filename, (unsigned long)folderid, name);
psync_apipool_release(api);
return -1;
}
return large_upload_save(api, uploadid, folderid, name, taskid, writeid, 0, hash, key, filename);
err3:
psync_file_close(fd);
err2:
psync_apipool_release_bad(api);
err1:
psync_interval_tree_free(tree);
psync_upload_sub_bytes_uploaded(asize);
return -1;
}
static void large_upload(){
uint64_t taskid, type, writeid;
psync_uploadid_t uploadid;
psync_folderid_t folderid;
psync_fileid_t fileid;
uint64_t hash;
const char *cname;
char *name, *filename, *indexname, *key;
size_t len;
psync_sql_res *res;
psync_variant_row row;
psync_uint_row urow;
int ret;
char fileidhex[sizeof(psync_fsfileid_t)*2+2];
debug(D_NOTICE, "started");
while (1){
psync_wait_statuses_array(requiredstatuses, ARRAY_SIZE(requiredstatuses));
res=psync_sql_query("SELECT id, type, folderid, text1, text2, int1, fileid, int2 FROM fstask WHERE status=2 AND "
"type IN ("NTO_STR(PSYNC_FS_TASK_CREAT)", "NTO_STR(PSYNC_FS_TASK_MODIFY)") ORDER BY id LIMIT 1");
row=psync_sql_fetch_row(res);
if (!row){
large_upload_running=0;
current_upload_taskid=0;
psync_sql_free_result(res);
break;
}
taskid=psync_get_number(row[0]);
type=psync_get_number(row[1]);
folderid=psync_get_number(row[2]);
if (psync_is_null(row[4]))
key=NULL;
else{
cname=psync_get_lstring(row[4], &len);
len++;
key=psync_new_cnt(char, len);
memcpy(key, cname, len);
}
cname=psync_get_lstring(row[3], &len);
writeid=psync_get_number(row[5]);
fileid=psync_get_number(row[6]);
hash=psync_get_number_or_null(row[7]);
len++;
name=psync_new_cnt(char, len);
memcpy(name, cname, len);
current_upload_taskid=taskid;
stop_current_upload=0;
psync_sql_free_result(res);
psync_binhex(fileidhex, &taskid, sizeof(psync_fsfileid_t));
fileidhex[sizeof(psync_fsfileid_t)]='d';
fileidhex[sizeof(psync_fsfileid_t)+1]=0;
cname=psync_setting_get_string(_PS(fscachepath));
filename=psync_strcat(cname, PSYNC_DIRECTORY_SEPARATOR, fileidhex, NULL);
fileidhex[sizeof(psync_fsfileid_t)]='i';
indexname=psync_strcat(cname, PSYNC_DIRECTORY_SEPARATOR, fileidhex, NULL);
res=psync_sql_query_rdlock("SELECT uploadid FROM fstaskupload WHERE fstaskid=? ORDER BY uploadid DESC LIMIT 1");
psync_sql_bind_uint(res, 1, taskid);
if ((urow=psync_sql_fetch_rowint(res)))
uploadid=urow[0];
else
uploadid=0;
psync_sql_free_result(res);
psync_upload_inc_uploads();
if (type==PSYNC_FS_TASK_CREAT)
ret=large_upload_creat(taskid, folderid, name, filename, uploadid, writeid, key);
else if (type==PSYNC_FS_TASK_MODIFY)
ret=upload_modify(taskid, folderid, name, filename, indexname, fileid, hash, writeid, key);
else{
ret=0;
debug(D_BUG, "wrong type %lu for task %lu", (unsigned long)type, (unsigned long)taskid);
res=psync_sql_prep_statement("DELETE FROM fstask WHERE id=?");
psync_sql_bind_uint(res, 1, taskid);
psync_sql_run_free(res);
}
psync_upload_dec_uploads();
if (ret)
psync_milisleep(PSYNC_SLEEP_ON_FAILED_UPLOAD);
psync_free(indexname);
psync_free(filename);
psync_free(name);
psync_free(key);
}
debug(D_NOTICE, "exited");
}
static int psync_sent_task_creat_upload_large(fsupload_task_t *task){
psync_sql_res *res;
res=psync_sql_prep_statement("UPDATE fstask SET status=2 WHERE id=? AND status=0");
psync_sql_bind_uint(res, 1, task->id);
//psync_fs_uploading_openfile(task->id);
if (!large_upload_running){
large_upload_running=1;
psync_run_thread("large file fs upload", large_upload);
}
psync_sql_run_free(res);
return 0;
}
void psync_fsupload_stop_upload_locked(uint64_t taskid){
psync_sql_res *res;
if (current_upload_taskid==taskid)
stop_current_upload=1;