forked from GangZhuo/BaiduPCS
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shell.c
7019 lines (6482 loc) · 194 KB
/
shell.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
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <locale.h>
#ifdef WIN32
# include <conio.h>
# include <direct.h>
# include <WinSock2.h>
# include <Windows.h>
# include "pcs/openssl_aes.h"
# include "pcs/openssl_md5.h"
# define snprintf _snprintf
# define vsnprintf _vsnprintf
#else
# include <unistd.h>
# include <termios.h>
# include <pthread.h>
# include <openssl/aes.h>
# include <openssl/md5.h>
#endif
#include "pcs/pcs_mem.h"
#include "pcs/cJSON.h"
#include "pcs/pcs_utils.h"
#include "pcs/pcs.h"
#include "rb_tree/red_black_tree.h"
#include "version.h"
#include "dir.h"
#include "utils.h"
#include "arg.h"
#include "cache.h"
#ifdef WIN32
# include "pcs/utf8.h"
#ifndef __MINGW32__
# define lseek _lseek
# define fileno _fileno
# define fseeko _fseeki64
# define ftello _ftelli64
#endif
#endif
#include "shell.h"
#define USAGE "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
#define TIMEOUT 60
#define CONNECTTIMEOUT 1
#define DEFAULT_THREAD_NUM 5
#define MAX_THREAD_NUM 10000
#define MIN_SLICE_SIZE (512 * 1024) /*最小分片大小*/
#define MAX_SLICE_SIZE (10 * 1024 * 1024) /*最大分片大小*/
#define MAX_FFLUSH_SIZE (10 * 1024 * 1024) /*最大缓存大小*/
#define MIN_UPLOAD_SLICE_SIZE (512 * 1024) /*最小分片大小*/
#define MAX_UPLOAD_SLICE_SIZE (10 * 1024 * 1024) /*最大分片大小*/
#define MAX_UPLOAD_SLICE_COUNT 1024
#define convert_to_real_speed(speed) ((speed) * 1024)
#define convert_to_real_cache_size(size) ((size) * 1024)
#define PCS_CONTEXT_ENV "PCS_CONTEXT"
#define PCS_COOKIE_ENV "PCS_COOKIE"
#define PCS_CAPTCHA_ENV "PCS_CAPTCHA"
#define TEMP_FILE_SUFFIX ".pcs_temp"
#define DECRYPT_FILE_SUFFIX ".decrypt"
#define ENCRYPT_FILE_SUFFIX ".encrypt"
#define SLICE_FILE_SUFFIX ".slice"
//#define PCS_DEFAULT_CONTEXT_FILE "/tmp/pcs_context.json"
#define THREAD_STATE_MAGIC (((int)'T' << 24) | ((int)'S' << 16) | ((int)'H' << 8) | ((int)'T'))
#ifndef PCS_BUFFER_SIZE
# define PCS_BUFFER_SIZE (AES_BLOCK_SIZE * 1024)
#endif
#ifdef _WIN32
# define NONE
# define RED
# define LIGHT_RED
# define GREEN
# define LIGHT_GREEN
# define BLUE
# define LIGHT_BLUE
# define DARY_GRAY
# define CYAN
# define LIGHT_CYAN
# define PURPLE
# define LIGHT_PURPLE
# define BROWN
# define YELLOW
# define LIGHT_GRAY
# define WHITE
#else
# define NONE "\033[m"
# define RED "\033[0;32;31m"
# define LIGHT_RED "\033[1;31m"
# define GREEN "\033[0;32;32m"
# define LIGHT_GREEN "\033[1;32m"
# define BLUE "\033[0;32;34m"
# define LIGHT_BLUE "\033[1;34m"
# define DARY_GRAY "\033[1;30m"
# define CYAN "\033[0;36m"
# define LIGHT_CYAN "\033[1;36m"
# define PURPLE "\033[0;35m"
# define LIGHT_PURPLE "\033[1;35m"
# define BROWN "\033[0;33m"
# define YELLOW "\033[1;33m"
# define LIGHT_GRAY "\033[0;37m"
# define WHITE "\033[1;37m"
#endif
#define PRINT_PAGE_SIZE 20 /*列出目录或列出比较结果时,分页大小*/
#define OP_NONE 0
#define OP_EQ 1 /*文件相同*/
#define OP_LEFT 2 /*文件应更新到左边*/
#define OP_RIGHT 4 /*文件应更新到右边*/
#define OP_CONFUSE 8 /*困惑,不知道如何更新*/
#define OP_ST_NONE 0
#define OP_ST_SUCC 1 /*操作成功*/
#define OP_ST_FAIL 2 /*操作失败*/
#define OP_ST_SKIP 4 /*跳过本操作*/
#define OP_ST_CONFUSE 8 /*困惑操作*/
#define OP_ST_PROCESSING 16 /*正在执行操作*/
#define FLAG_NONE 0
#define FLAG_ON_LOCAL 1
#define FLAG_ON_REMOTE 2
#define FLAG_PARENT_NOT_ON_REMOTE 4
#define PCS_SECURE_NONE ((int)0)
#define PCS_SECURE_PLAINTEXT ((int)1)
#define PCS_SECURE_AES_CBC_128 ((int)128)
#define PCS_SECURE_AES_CBC_192 ((int)192)
#define PCS_SECURE_AES_CBC_256 ((int)256)
#define PCS_AES_MAGIC (0x41455300)
#define DOWNLOAD_STATUS_OK 0
#define DOWNLOAD_STATUS_PENDDING 1
#define DOWNLOAD_STATUS_WRITE_FILE_FAIL 2
#define DOWNLOAD_STATUS_FAIL 3
#define DOWNLOAD_STATUS_DOWNLOADING 4
#define UPLOAD_STATUS_OK 0
#define UPLOAD_STATUS_PENDDING 1
#define UPLOAD_STATUS_WRITE_FILE_FAIL 2
#define UPLOAD_STATUS_FAIL 3
#define UPLOAD_STATUS_UPLOADING 4
/* 文件元数据*/
typedef struct MyMeta MyMeta;
struct MyMeta
{
char *path; /*文件路径*/
time_t local_mtime; /*本地文件的修改时间*/
int local_isdir; /*本地文件是否是目录。0表示不是目录;非0值表示本地文件是目录*/
int local_filecount; /*当本地是目录时,存储目录下文件的数目。递归统计。*/
char *remote_path; /*文件路径*/
time_t remote_mtime; /*文件在网盘中的最后修改时间*/
int remote_isdir; /*文件在网盘中是以文件存在还是以目录存在。0表示以文件存在;非0值表示以目录存在*/
char *md5;
int flag;
int op; /*需要执行的操作*/
int op_st; /*操作的结果*/
char *msg; /*操作失败时的错误消息*/
MyMeta *parent; /*父目录的元数据*/
void *userdata; /*用户数据*/
};
struct DownloadThreadState;
struct DownloadState
{
FILE *pf;
int64_t downloaded_size; /*已经下载的字节数*/
curl_off_t resume_from; /*断点续传时,从这个位置开始续传*/
time_t time; /*最后一次在屏幕打印信息的时间*/
size_t speed; /*用于统计下载速度*/
int64_t file_size; /*完整的文件的字节大小*/
ShellContext *context;
void *mutex;
int num_of_running_thread; /*已经启动的线程数量*/
int num_of_slice; /*分片数量*/
char **pErrMsg;
int status;
const char *remote_file;
struct DownloadThreadState *threads;
cathe_t cache;
};
struct DownloadThreadState
{
struct DownloadState *ds;
curl_off_t start;
curl_off_t end;
curl_off_t postion;
int status;
Pcs *pcs;
int tid;
struct DownloadThreadState *next;
};
struct RBEnumerateState
{
int first, second, other;
int print_op; /* 允许打印的 OP 标记。
* 例如:"OP_EQ | OP_LEFT | OP_RIGHT"
* 将只打印 op 为 OP_EQ, OP_LEFT 和 OP_RIGHT 三项的节点
*/
int print_flag;
int print_fail;
int no_print_op;
int no_print_flag;
rb_red_blk_tree *tree;
ShellContext *context;
int page_size;
int cnt_total;
int cnt_valid_total;
int cnt_left;
int cnt_right;
int cnt_eq;
int cnt_confuse;
int cnt_none;
int cnt_fail;
int printed_count;
int page_index;
int page_enable;
const char *local_basedir;
const char *remote_basedir;
/*在打印meta后调用一次*/
int (*process)(MyMeta *meta, struct RBEnumerateState *s, void *state);
void *processState;
int dry_run;
const char *prefixion;
};
struct PcsAesHead
{
int magic; /*Should be AES*/
int bits;
int polish;
int reserve;
};
struct ScanLocalFileState
{
rb_red_blk_tree *rb;
int total;
};
struct UploadThreadState;
struct UploadState {
FILE *pf;
char *path;
char *slice_file;
int64_t uploaded_size; /*已经下载的字节数*/
time_t time; /*最后一次在屏幕打印信息的时间*/
size_t speed; /*用于统计下载速度*/
int64_t file_size; /*完整的文件的字节大小*/
ShellContext *context;
void *mutex;
int num_of_running_thread; /*已经启动的线程数量*/
int num_of_slice; /*分片数量*/
char **pErrMsg;
int status;
struct UploadThreadState *threads;
};
struct UploadThreadState {
struct UploadState *us;
curl_off_t start;
curl_off_t end;
int status;
size_t uploaded_size;
Pcs *pcs;
char md5[33]; /*上传成功后的分片MD5值*/
int tid;
struct UploadThreadState *next;
};
static const char *app_name = NULL;
/*
* 检查是否登录
* msg - 检测到未登录时的打印消息。传入NULL的话,则使用默认消息。
*/
static PcsBool is_login(ShellContext *context, const char *msg);
#ifdef WIN32
/*判断当前操作系统编码是否是UTF-8编码*/
int u8_is_utf8_sys()
{
UINT codepage = GetConsoleCP();
return codepage == 65001;
}
/*多字节字符转换成UTF-8编码*/
int u8_mbs_toutf8(char *dest, int sz, const char *src, int srcsz)
{
wchar_t *unicode;
int wchars, err;
wchars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src, srcsz, NULL, 0);
if (wchars == 0) {
fprintf(stderr, "Unicode translation error %d\n", GetLastError());
return -1;
}
unicode = (wchar_t *)alloca((wchars + 1) * sizeof(unsigned short));
err = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src, srcsz, unicode, wchars);
if (err != wchars) {
fprintf(stderr, "Unicode translation error %d\n", GetLastError());
return -1;
}
unicode[wchars] = L'\0';
return u8_toutf8(dest, sz, unicode, wchars);
}
int u8_mbs_toutf8_size(const char *src, int srcsz)
{
wchar_t *unicode;
int wchars, err;
wchars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src, srcsz, NULL, 0);
if (wchars == 0) {
fprintf(stderr, "Unicode translation error %d\n", GetLastError());
return -1;
}
unicode = (wchar_t *)alloca((wchars + 1) * sizeof(unsigned short));
err = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src, srcsz, unicode, wchars);
if (err != wchars) {
fprintf(stderr, "Unicode translation error %d\n", GetLastError());
return -1;
}
unicode[wchars] = L'\0';
//wprintf(L"UNICODE: %ls\n", unicode);
return u8_size(unicode, wchars);
}
int u8_tombs(char *dest, int sz, const char *src, int srcsz)
{
int unicode_size;
wchar_t *unicode;
//int unicode_len;
int /*chars,*/ err;
unicode_size = u8_wc_size(src, srcsz);
unicode = (wchar_t *)alloca((unicode_size + 1) * sizeof(unsigned short));
unicode[unicode_size] = L'\0';
u8_toucs(unicode, unicode_size, src, srcsz);
err = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode, unicode_size, dest, sz, NULL, NULL);
if (err < 1)
{
fprintf(stderr, "Unicode translation error %d\n", GetLastError());
return -1;
}
return err;
}
int u8_tombs_size(const char *src, int srcsz)
{
int unicode_size;
wchar_t *unicode;
//int unicode_len;
int /*chars,*/ err;
unicode_size = u8_wc_size(src, srcsz);
unicode = (wchar_t *)alloca((unicode_size + 1) * sizeof(unsigned short));
unicode[unicode_size] = L'\0';
u8_toucs(unicode, unicode_size, src, srcsz);
err = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode, unicode_size, NULL, 0, NULL, NULL);
return err;
}
char *mbs2utf8(const char *s)
{
int sl = strlen(s);
int sz = u8_mbs_toutf8_size(s, sl);
char *res = 0;
res = (char *)pcs_malloc(sz + 1);
if (!res)
return 0;
memset(res, 0, sz + 1);
u8_mbs_toutf8(res, sz, s, sl);
return res;
}
char *utf82mbs(const char *s)
{
int sl = strlen(s);
int sz = u8_tombs_size(s, sl);
char *res = 0;
res = (char *)pcs_malloc(sz + 1);
if (!res)
return 0;
memset(res, 0, sz + 1);
u8_tombs(res, sz, s, sl);
return res;
}
# define printf u8_printf
# define sleep(s) Sleep((s) * 1000)
int truncate(const char *file, int64_t size)
{
HANDLE hFile;
hFile = CreateFile(file, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile) {
LARGE_INTEGER li = {0};
li.QuadPart = (LONGLONG)size;
SetFilePointer(hFile, li.LowPart, &li.HighPart, FILE_BEGIN);
SetEndOfFile(hFile);
CloseHandle(hFile);
return 0;
}
return -1;
}
#else
/*判断当前操作系统编码是否是UTF-8编码*/
int u8_is_utf8_sys()
{
return 1;
}
char *mbs2utf8(const char *s)
{
return pcs_utils_strdup(s);
}
char *utf82mbs(const char *s)
{
return pcs_utils_strdup(s);
}
#endif
#pragma region 加解密文件
static inline int get_secure_method(ShellContext *context)
{
if (!context->secure_method) return -1;
if (!strcmp(context->secure_method, "aes-cbc-128")) return PCS_SECURE_AES_CBC_128;
if (!strcmp(context->secure_method, "aes-cbc-192")) return PCS_SECURE_AES_CBC_192;
if (!strcmp(context->secure_method, "aes-cbc-256")) return PCS_SECURE_AES_CBC_256;
return -1;
}
static inline void readToAesHead(const char *buf, struct PcsAesHead *head)
{
head->magic = readInt(buf);
head->bits = readInt(&buf[4]);
head->polish = readInt(&buf[8]);
head->reserve = readInt(&buf[12]);
}
static int get_file_secure_method(const char *src)
{
FILE *srcFile;
int64_t file_sz;
size_t sz;
unsigned char buf[PCS_BUFFER_SIZE];
struct PcsAesHead head = { 0 };
srcFile = fopen(src, "rb");
if (!srcFile) {
//fprintf(stderr, "Error: Can't open the source file: %s\n", src);
return -1;
}
fseeko(srcFile, 0, SEEK_END);
file_sz = ftello(srcFile);
fseeko(srcFile, 0, SEEK_SET);
if (file_sz < 32) {
fclose(srcFile);
return PCS_SECURE_PLAINTEXT;
}
sz = fread(buf, 1, 16, srcFile);
if (sz != 16) {
//fprintf(stderr, "Error: Can't read the source file: %s\n", src);
fclose(srcFile);
return -1;
}
readToAesHead(buf, &head);
if (head.magic != PCS_AES_MAGIC || (head.bits != PCS_SECURE_AES_CBC_128 && head.bits != PCS_SECURE_AES_CBC_192 && head.bits != PCS_SECURE_AES_CBC_256)) {
fclose(srcFile);
return PCS_SECURE_PLAINTEXT;
}
fclose(srcFile);
if (((file_sz - 32) % AES_BLOCK_SIZE) != 0) {
//fprintf(stderr, "Error: The file is not a encrypt file or is broken.\n");
return -1;
}
return head.bits;
}
static int encrypt_file(const char *src, const char *dst, int secure_method, const char *secure_key, char **pErrMsg)
{
MD5_CTX md5;
unsigned char md5_value[16], buf[PCS_BUFFER_SIZE], out_buf[PCS_BUFFER_SIZE];
FILE *srcFile, *dstFile;
char *tmp_local_path;
int64_t file_sz;
size_t buf_sz, sz;
int polish;
AES_KEY aes = { 0 };
unsigned char key[AES_BLOCK_SIZE] = { 0 };
unsigned char iv[AES_BLOCK_SIZE] = { 0 };
int rc;
rc = AES_set_encrypt_key(pcs_md5_string_raw(secure_key), secure_method, &aes);
if (rc < 0) {
fprintf(stderr, "Error: Can't set encrypt key.\n");
return -1;
}
MD5_Init(&md5);
srcFile = fopen(src, "rb");
if (!srcFile) {
fprintf(stderr, "Error: Can't open the source file: %s\n", src);
return -1;
}
tmp_local_path = (char *)pcs_malloc(strlen(src) + strlen(ENCRYPT_FILE_SUFFIX) + 1);
strcpy(tmp_local_path, src);
strcat(tmp_local_path, ENCRYPT_FILE_SUFFIX);
dstFile = fopen(tmp_local_path, "wb");
if (!dstFile) {
fprintf(stderr, "Error: Can't create the temp file: %s\n", tmp_local_path);
fclose(srcFile);
pcs_free(tmp_local_path);
return -1;
}
fseeko(srcFile, 0, SEEK_END);
file_sz = ftello(srcFile);
fseeko(srcFile, 0, SEEK_SET);
polish = 0;
if (file_sz % AES_BLOCK_SIZE == 0) {
polish = 0;
}
else {
polish = (int)((file_sz / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE - file_sz);
}
int2Buffer(PCS_AES_MAGIC, buf);
int2Buffer(secure_method, &buf[4]);
int2Buffer(polish, &buf[8]);
int2Buffer(0, &buf[12]);
sz = fwrite(buf, 1, 16, dstFile);
if (sz != 16) {
fprintf(stderr, "Error: Write data to %s error. \n", dst);
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
while ((sz = fread(buf, 1, PCS_BUFFER_SIZE, srcFile)) > 0) {
MD5_Update(&md5, buf, sz);
if ((sz % AES_BLOCK_SIZE) != 0) {
buf_sz = (size_t)((sz / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE);
memset(&buf[sz], 0, buf_sz - sz);
}
else {
buf_sz = sz;
}
// encrypt (iv will change)
AES_cbc_encrypt(buf, out_buf, buf_sz, &aes, iv, AES_ENCRYPT);
sz = fwrite(out_buf, 1, buf_sz, dstFile);
if (sz != buf_sz) {
fprintf(stderr, "Error: Write data to %s error. \n", dst);
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
}
MD5_Final(md5_value, &md5);
sz = fwrite(md5_value, 1, 16, dstFile);
if (sz != 16) {
fprintf(stderr, "Error: Write data to %s error. \n", dst);
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(dst);
if (rename(tmp_local_path, dst)) {
fprintf(stderr, "Error: The file have been encrypted at %s, but can't rename to %s.\n You should be rename manual.\n", tmp_local_path, dst);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
pcs_free(tmp_local_path);
//printf("Success\n");
return 0;
}
static int decrypt_file(const char *src, const char *dst, const char *secure_key, char **pErrMsg)
{
struct PcsAesHead head = { 0 };
MD5_CTX md5;
unsigned char md5_value[16], buf[PCS_BUFFER_SIZE], out_buf[PCS_BUFFER_SIZE];
char *tmp_local_path;
FILE *srcFile, *dstFile;
int64_t file_sz;
size_t sz, buf_sz;
AES_KEY aes = { 0 };
unsigned char key[AES_BLOCK_SIZE] = { 0 };
unsigned char iv[AES_BLOCK_SIZE] = { 0 };
int rc, i;
MD5_Init(&md5);
srcFile = fopen(src, "rb");
if (!srcFile) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Can't open the source file: %s\n", src);
}
return -1;
}
tmp_local_path = (char *)pcs_malloc(strlen(src) + strlen(DECRYPT_FILE_SUFFIX) + 1);
strcpy(tmp_local_path, src);
strcat(tmp_local_path, DECRYPT_FILE_SUFFIX);
dstFile = fopen(tmp_local_path, "wb");
if (!dstFile) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Can't create the temp file: %s\n", tmp_local_path);
}
fclose(srcFile);
pcs_free(tmp_local_path);
return -1;
}
fseeko(srcFile, 0, SEEK_END);
file_sz = ftello(srcFile);
fseeko(srcFile, 0, SEEK_SET);
if (file_sz < 32 || ((file_sz - 32) % AES_BLOCK_SIZE) != 0) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: The file is not a encrypt file or is broken.\n");
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
sz = fread(buf, 1, 16, srcFile);
if (sz != 16) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Can't read the source file: %s\n", src);
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
readToAesHead(buf, &head);
if (head.magic != PCS_AES_MAGIC || (head.bits != 128 && head.bits != 192 && head.bits != 256)) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: The file is not a encrypt file or is broken.\n");
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
rc = AES_set_decrypt_key(pcs_md5_string_raw(secure_key), head.bits, &aes);
if (rc < 0) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Can't set decrypt key.\n");
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
file_sz -= 32;
if (file_sz < PCS_BUFFER_SIZE) {
buf_sz = (size_t)file_sz;
}
else {
buf_sz = PCS_BUFFER_SIZE;
}
while ((sz = fread(buf, 1, buf_sz, srcFile)) > 0) {
if (sz != buf_sz) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Can't read the source file: %s\n", src);
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
AES_cbc_encrypt(buf, out_buf, buf_sz, &aes, iv, AES_DECRYPT);
if (file_sz == (int64_t)buf_sz) {
buf_sz -= head.polish;
file_sz = (int64_t)buf_sz;
}
MD5_Update(&md5, out_buf, buf_sz);
sz = fwrite(out_buf, 1, buf_sz, dstFile);
if (sz != buf_sz) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Write data to %s error. \n", dst);
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
file_sz -= (int64_t)buf_sz;
if (file_sz == 0) break;
if (file_sz < PCS_BUFFER_SIZE) {
buf_sz = (size_t)file_sz;
}
else {
buf_sz = PCS_BUFFER_SIZE;
}
}
MD5_Final(md5_value, &md5);
sz = fread(buf, 1, 16, srcFile);
if (sz != 16) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Can't read the source file: %s\n", src);
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
for (i = 0; i < 16; i++) {
if (md5_value[i] != buf[i]) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf("Error: Wrong key or broken file\n");
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
}
fclose(srcFile);
fclose(dstFile);
DeleteFileRecursive(dst);
if (rename(tmp_local_path, dst)) {
if (pErrMsg) {
if (*pErrMsg) pcs_free(*pErrMsg);
(*pErrMsg) = pcs_utils_sprintf(
"Error: The file have been decrypted at %s, but can't rename to %s.\n You should be rename manual.\n", tmp_local_path, dst);
}
//DeleteFileRecursive(tmp_local_path);
pcs_free(tmp_local_path);
return -1;
}
pcs_free(tmp_local_path);
//printf("Success\n");
return 0;
}
static int get_data_secure_method(const char *buffer, size_t buffer_size)
{
struct PcsAesHead head = { 0 };
if (!buffer) {
return -1;
}
if (buffer_size < 32) {
return PCS_SECURE_PLAINTEXT;
}
readToAesHead((char *)buffer, &head);
if (head.magic != PCS_AES_MAGIC || (head.bits != PCS_SECURE_AES_CBC_128 && head.bits != PCS_SECURE_AES_CBC_192 && head.bits != PCS_SECURE_AES_CBC_256)) {
return PCS_SECURE_PLAINTEXT;
}
if (((buffer_size - 32) % AES_BLOCK_SIZE) != 0) {
//fprintf(stderr, "Error: The file is not a encrypt file or is broken.\n");
return -1;
}
return head.bits;
}
static int encrypt_data(const char *src, size_t src_size, char **dst, size_t *dst_size,
int secure_method, const char *secure_key)
{
int rc;
MD5_CTX md5;
AES_KEY aes = { 0 };
unsigned char key[AES_BLOCK_SIZE] = { 0 };
unsigned char iv[AES_BLOCK_SIZE] = { 0 };
int blockCount;
size_t outsz;
char *out_buf, *md5_value;
int i;
const char *pin;
char *pout, buf[32];
rc = AES_set_encrypt_key(pcs_md5_string_raw(secure_key), secure_method, &aes);
if (rc < 0) {
fprintf(stderr, "Error: Can't set encrypt key.\n");
return -1;
}
blockCount = src_size / AES_BLOCK_SIZE;
if ((src_size % AES_BLOCK_SIZE) != 0) {
blockCount++;
}
outsz = blockCount * AES_BLOCK_SIZE + 32;
out_buf = (unsigned char *)pcs_malloc(outsz);
if (!out_buf) {
fprintf(stderr, "Error: can't alloc memory.\n");
return -1;
}
pout = out_buf;
int2Buffer(PCS_AES_MAGIC, pout);
int2Buffer(secure_method, pout + 4);
int2Buffer((int)(outsz - src_size - 32), pout + 8);
int2Buffer(0, pout + 12);
pout += 16;
pin = src;
MD5_Init(&md5);
for (i = 0; i < blockCount; i++) {
if ((size_t)((i + 1) * AES_BLOCK_SIZE) > src_size) {
MD5_Update(&md5, pin, src_size - i * AES_BLOCK_SIZE);
memcpy(buf, pin, src_size - i * AES_BLOCK_SIZE);
memset(buf + src_size - i * AES_BLOCK_SIZE, 0, AES_BLOCK_SIZE - (src_size - i * AES_BLOCK_SIZE));
// encrypt (iv will change)
AES_cbc_encrypt(buf, pout, AES_BLOCK_SIZE, &aes, iv, AES_ENCRYPT);
pout += AES_BLOCK_SIZE;
}
else {
MD5_Update(&md5, pin, AES_BLOCK_SIZE);
// encrypt (iv will change)
AES_cbc_encrypt(pin, pout, AES_BLOCK_SIZE, &aes, iv, AES_ENCRYPT);
pin += AES_BLOCK_SIZE;
pout += AES_BLOCK_SIZE;
}
}
md5_value = pout;
MD5_Final(md5_value, &md5);
*dst = out_buf;
*dst_size = outsz;
return 0;
}
static int decrypt_data(const char *src, size_t src_size, char **dst, size_t *dst_size,
const char *secure_key)
{
int rc;
struct PcsAesHead head = { 0 };
MD5_CTX md5;
AES_KEY aes = { 0 };
unsigned char key[AES_BLOCK_SIZE] = { 0 };
unsigned char iv[AES_BLOCK_SIZE] = { 0 };
char md5_value[16], *pout, *outbuf;
const char *pin;
int blockCount;
int i;
size_t outsz;
MD5_Init(&md5);
if (src_size < 32 || ((src_size - 32) % AES_BLOCK_SIZE) != 0) {
return -1;
}
readToAesHead(src, &head);
if (head.magic != PCS_AES_MAGIC || (head.bits != 128 && head.bits != 192 && head.bits != 256)) {
return -1;
}
rc = AES_set_decrypt_key(pcs_md5_string_raw(secure_key), head.bits, &aes);
if (rc < 0) {
return -1;
}
outsz = src_size - 32 - head.polish;
outbuf = (char *)pcs_malloc(src_size);
pin = src + 16;
pout = outbuf;
blockCount = (src_size - 32) / AES_BLOCK_SIZE;
for (i = 0; i < blockCount;i++) {
AES_cbc_encrypt(pin, pout, AES_BLOCK_SIZE, &aes, iv, AES_DECRYPT);
if ((size_t)(i + 1) * AES_BLOCK_SIZE > outsz)
MD5_Update(&md5, pout, AES_BLOCK_SIZE - head.polish);
else
MD5_Update(&md5, pout, AES_BLOCK_SIZE);
pin += AES_BLOCK_SIZE;
pout += AES_BLOCK_SIZE;
}
MD5_Final(md5_value, &md5);
for (i = 0; i < 16; i++) {
if (md5_value[i] != pin[i]) {
pcs_free(outbuf);
return -1;
}
}
*dst = outbuf;
*dst_size = outsz;
return 0;
}
#pragma endregion
#pragma region 获取默认路径
/*获取上下文存储文件路径*/
static const char *contextfile()
{
static char filename[1024] = { 0 };
char *env_value = getenv(PCS_CONTEXT_ENV);
if (env_value) return env_value;
if (!filename[0]) {
#ifdef WIN32
strcpy(filename, getenv("UserProfile"));
strcat(filename, "\\.pcs");
CreateDirectoryRecursive(filename);
strcat(filename, "\\pcs.context");
#else
strcpy(filename, getenv("HOME"));
strcat(filename, "/.pcs");
CreateDirectoryRecursive(filename);
strcat(filename, "/pcs.context");
#endif
}
return filename;
}
/*返回COOKIE文件路径*/
static const char *cookiefile()
{
static char filename[1024] = { 0 };
char *env_value = getenv(PCS_COOKIE_ENV);
if (env_value) return env_value;
if (!filename[0]){ /*如果已经处理过,则直接返回*/
#ifdef WIN32
strcpy(filename, getenv("UserProfile"));
strcat(filename, "\\.pcs");
CreateDirectoryRecursive(filename);
strcat(filename, "\\");
strcat(filename, "default.cookie");
#else
strcpy(filename, getenv("HOME"));
strcat(filename, "/.pcs");
CreateDirectoryRecursive(filename);