-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyncAPI.js
1756 lines (1552 loc) · 58 KB
/
SyncAPI.js
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
(async () => {
/**
* Dependences
*/
// npm install dotenv
const dotenv = require("dotenv")
dotenv.config()
// npm install bcrypt
const bCrypt = require('bcrypt')
// npm install got (request is deprecated)
const got = require('got')
// npm install hash.js
const hash = require('hash.js')
// npm install sjcl
const sjcl = require('sjcl')
// npm install fuse-native
const Fuse = require('fuse-native')
// npm install scanf
const scanf = require('scanf')
// npm install pidcrypt
require("pidcrypt/seedrandom")
const pidCrypt = require('pidcrypt')
require("pidcrypt/rsa")
require("pidcrypt/asn1")
const pidCryptUtil = require('pidcrypt/pidcrypt_util');
// npm install prompt-sync
const prompt = require('prompt-sync')()
const crypto = require('crypto')
const pathmodule = require('path')
const util = require('util');
const fs = require('fs');
/**
* Variables
*/
const api_url = 'https://cp.sync.com/api/?command='
const username = process.env.EMAIL
const password = process.env.PASSWORD
const flag2FA = process.env.FLAG_2FA
const displayID = process.env.DISPLAY_ID
const mtSpeed = process.env.MTSPEED
const retryCount = process.env.RETRYCOUNT
const logEmptyDirectories = process.env.LOG_EMPTY_DIRECTORIES
let GCM_PACKET_SIZE = 128 * 1024;
let GCM_PAYLOAD_SIZE = 128 * 1024 - 36;
let CHUNK_SIZE = 10485760
// Buffering in percent of the file size
let percentBuffering = 25
/**
* Sleep method
*/
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));
/**
* Workaround for modules not available in sjcl
*/
/** @fileOverview Bit array codec implementations.
*
* @author Emily Stark
* @author Mike Hamburg
* @author Dan Boneh
*/
/**
* Arrays of bytes
* @namespace
*/
sjcl.codec.bytes = {
/** Convert from a bitArray to an array of bytes. */
fromBits: function (arr) {
var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp;
for (i=0; i<bl/8; i++) {
if ((i&3) === 0) {
tmp = arr[i/4];
}
out.push(tmp >>> 24);
tmp <<= 8;
}
return out;
},
/** Convert from an array of bytes to a bitArray. */
toBits: function (bytes) {
var out = [], i, tmp=0;
for (i=0; i<bytes.length; i++) {
tmp = tmp << 8 | bytes[i];
if ((i&3) === 3) {
out.push(tmp);
tmp = 0;
}
}
if (i&3) {
out.push(sjcl.bitArray.partial(8*(i&3), tmp));
}
return out;
}
};
/**
* Functions for login
*/
async function getSalt(username) {
const data = await got.post(api_url + 'getloginsalt', {
json: {
username_b64: new Buffer(username).toString('base64')
}
}).json()
return data.salt
}
async function getHashedPassword(salt, password) {
const sha1pass = hash.sha1().update(password).digest('hex')
let mangle = hash.sha256().update(sha1pass + sha1pass.substring(4, 24)).digest('hex')
return bCrypt.hashSync(mangle, salt)
}
/**
* Decrypts data using a string password that is keystretched
* @param {String} b64_crypted A num-prefixed b64 string
* @param {String|Array} password The AES key
* @param {Integer} iterations iterations for keystretch
* @return {Promise} [description]
*/
async function passwordDecrypt(b64_crypted, password, iterations) {
if (b64_crypted.substring(0, 3) === '30:') {
const raw = sjcl.codec.base64.toBits(b64_crypted.substring(3))
salt = raw.splice(0, 3)
iv = raw.splice(0, 3)
key = sjcl.misc.pbkdf2(password, salt, iterations, 32 * 8, sjcl.misc.hmac)
aes = new sjcl.cipher.aes(key)
try {
return sjcl.codec.utf8String.fromBits(
sjcl.mode.gcm.decrypt(aes, raw, iv, [], 96)
)
} catch (ex) {
console.error(ex)
}
} else {
console.error('SyncCryptLegacy.passwordDecrypt() failed');
console.error('Badly formatted password');
console.error('badly formatted passwd encrypted string ' + b64_crypted);
}
}
async function userkeyDecrypt(encKey, password) {
try {
// must use cryptlegacy because people's passwords will contain weird chars
return await passwordDecrypt(
encKey,
password,
10000
);
} catch (ex) {
console.error('Error decrypting user keys', ex);
console.error(2140);
}
}
async function storeKeys(keys, password) {
const meta = await userkeyDecrypt(
keys.enc_meta_key,
password
)
const priv = await userkeyDecrypt(
keys.enc_priv_key,
password
)
return [meta, priv]
}
async function authenticate(usernameRaw, password) {
let username = usernameRaw.toLowerCase()
const hashPass = await getHashedPassword(await getSalt(username), password)
try {
// If 2FA flag is set redefine two_fa for the OTP code
let two_fa = ''
if (flag2FA == "true") {
two_fa = prompt('2FA: ')
}
const accessData = await got.post(api_url + 'sessionnew', {
json: {
username: username,
password: hashPass,
twofacode: two_fa
}
}).json()
const keys = await got.post(api_url + 'getuserkeys', {
json : {
username: username,
password: hashPass,
}
}).json()
return [accessData, await storeKeys(keys, password)]
} catch (ex) {
console.error("Error in authenticate")
console.error(ex)
}
}
/**
* Functions for operations
*/
/**
* @ngdoc method
* @name list
* @methodOf sync.service:PathApi
* @description
* Gets a path listing for a given sync id.
* @param {integer=} sync_id The pid to get the path listing for.
* @param {integer=} hist_id The current hist id that we have.
* @param {integer=} show_deleted switch to show deleted files, 1 = yes
* @returns {pathlist} the pathlist that contains all the path
*/
async function list(sync_id, hist_id=0, showdeleted=0) {
let servtime = Date.now()
let signature = await getApiHmac(
accessData['access_secret'],
[
accessData['access_token'],
accessData['uid'],
accessData['web_device_id'],
servtime,
].join('')
)
try {
// Make listing until offset_metaname_digest_old and last_metaname_digest actual are the same
let data_final
let offset_metaname_digest_old = 0
while ( true ) {
let data = await got.post(api_url + 'pathlist', {
json: {
showdeleted: showdeleted,
hist_id: hist_id,
sync_id: sync_id,
offset_metaname_digest: offset_metaname_digest_old,
servtime: servtime,
access_token: accessData['access_token'],
signature: signature
}
}).json()
// Compare
//~ console.log("OLD: " + offset_metaname_digest_old)
//~ console.log("NEW: " + data['last_metaname_digest'])
if(offset_metaname_digest_old == data['last_metaname_digest']) {
break
} else {
// Assign first time JSON if undefined
if (data_final == undefined) {
data_final = data['pathlist']
} else {
data_final = data_final.concat(data['pathlist'])
}
offset_metaname_digest_old = data['last_metaname_digest']
}
}
return data_final
} catch (ex) {
console.error(ex)
}
}
/**
* @ngdoc method
* @name batchDumpDirs
* @methodOf sync.service:PathApi
* @description
* Gets a list of directories recursively from the specified sync id. The
* array that is returned is ordered from parent -> child and should be
* operated in order. If this is a delete/purge however, the array should
* be reversed
*
* @param {Integer} sync_id The path item to be copied
* @param {Integer} active_level active -1 == deleted files, > 0 are active
* @returns {Promise} The promise from the API call
*/
async function batchDumpDirs(sync_id, active_level="1") {
let servtime = Date.now()
let signature = await getApiHmac(
accessData['access_secret'],
[
accessData['access_token'],
accessData['uid'],
accessData['web_device_id'],
servtime,
].join('')
)
try {
return await got.post(api_url + 'batchdumpdirs', {
json: {
active_level: active_level,
sync_id: sync_id,
servtime: servtime,
access_token: accessData['access_token'],
signature: signature
}
}).json()
} catch (ex) {
console.error(ex)
}
}
/**
* @ngdoc method
* @name get
* @methodOf sync.service:PathApi
* @description
* Gets information for a specific path item
* @param {integer} sync_id The sync id to retrieve
* @returns {Promise} The promise from the API call
*/
async function get(sync_id) {
let servtime = Date.now()
let signature = await getApiHmac(
accessData['access_secret'],
[
accessData['access_token'],
accessData['uid'],
accessData['web_device_id'],
servtime,
].join('')
)
try {
return await got.post(api_url + 'pathget', {
json: {
sync_id: sync_id,
servtime: servtime,
access_token: accessData['access_token'],
signature: signature
}
}).json()
} catch (ex) {
console.error(ex)
}
}
function mkDownloadUrl(tItem, offset=0, reqLength=0) {
// console.error('MAKE DOWNLOAD URL = ' + this.hosts['web'][0])
let urlParts = [ 'https://cp.sync.com', '/mfs', '/proxyapi.fcgi?command=download',
'&cachekey=', tItem['cachekey'],
//~ '&blobtype=', tItem.blobtype,
'&blobtype=btFILE',
'&offset=', offset,
'&engine=', 'cp-' + 2,
'&userid=', accessData['uid'],
'&deviceid=', accessData['web_device_id'],
'&devicetypeid=3'
];
// no length dl all
if (reqLength) {
urlParts.push('&length=' + reqLength);
}
return urlParts.join('')
}
/**
* @ngdoc method
* @name getData
* @methodOf sync.service:PathApi
* @description
* Gets the encryption keys and path data for a given item. Typically
* called before a download.
* @param {Array.Object} pathitems List of items to get data for
* @param {Integer=} pubkey_id If the user is authenticated, the pubkey
* id will be sent to ensure the correct
* key is retrieved.
* @returns {Promise} The promise from the API call
*/
async function getData(needKeys, pubkey=null) {
// var data = (User.isAuthenticated())
// ? { pathitems: pathitems, pubkey: User.get('pubkey_id') }
// : { pathitems: pathitems };
let servtime = Date.now()
let signature = await getApiHmac(
accessData['access_secret'],
[
accessData['access_token'],
accessData['uid'],
accessData['web_device_id'],
servtime,
].join('')
)
try {
return await got.post(api_url + 'pathdata', {
json: {
pathitems: needKeys,
pubkey: accessData['pubkey_id'],
servtime: servtime,
access_token: accessData['access_token'],
signature: signature
}
}).json()
} catch (ex) {
console.error(ex)
}
};
/**
* Functions to ease the code
*/
async function getApiHmac(key, data) {
const hmac = crypto.createHmac('sha1', key)
hmac.update(data)
return hmac.digest("hex")
}
function stringToBytes(str) {
return sjcl.codec.utf8String.toBits(str);
}
function bytesToHex(bits) {
return sjcl.codec.hex.fromBits(bits);
}
function b64ToBytes(b64) {
return sjcl.codec.base64.toBits(b64);
}
function bytesToString(bits) {
return sjcl.codec.utf8String.fromBits(bits);
}
function bytesToB64(bits) {
return sjcl.codec.base64.fromBits(bits);
}
/**
* @ngdoc method
* @name arraybufferToBytes
* @methodOf sync.service:SyncCryptLegacy
* @description
* This function doesn't do anything. It's needed because legacy (sjcl)
* requires it's own "bitArray" instead of array buffers.
* @param {ArrayBuffer} buffer [description]
* @return {Array} SJCL's bitArray
*/
function arraybufferToBytes(buffer) {
const bytes = new Uint8Array(buffer);
return sjcl.codec.bytes.toBits(bytes);
}
/**
* @ngdoc method
* @name getPartialBytes
* @methodOf sync.service:SyncCryptLegacy
* @description
* Gets partial bits from the given data source.
* @param {Array} array [description]
* @param {Integer} byteStart [description]
* @param {Integer} byteEnd [description]
* @return {Array} [description]
*/
function getPartialBytes(data, byteStart, byteEnd) {
byteStart = byteStart / 32;
byteEnd = (byteEnd) ? byteEnd / 32 : data.length;
return data.slice(byteStart, byteEnd);
}
function shareKeyToBytes(sharekey) {
const bytes = b64ToBytes(sharekey);
return bytes;
}
/**
* Functions related to decrypt not related with login
*/
/**
* This method will always return a string. Whether it fails or not.
* @param encName The encrypted name b64 num prefix
* @param sharekey the b64 of the decrypted share key
*/
async function filenameDecrypt(encName, sharekey=null) {
const encNameBytes = b64ToBytes(encName.split(':')[1])
const key = b64ToBytes(meta)
try {
// Must use CryptMethodLegacy due to UTF8 characters being 32bit words
const rawBytes = getPartialBytes(encNameBytes, 96)
const iv = getPartialBytes(encNameBytes, 0, 96);
try {
const nameBytes = await symmetricDecrypt(
getPartialBytes(key, 256),
rawBytes,
iv
);
return bytesToString(nameBytes);
} catch (ex) {
console.error(`Unable to decrypt the file name ${encName}`, ex);
fname = encName;
}
return fname;
} catch (ex) {
console.error('An error occurred in filenameDecrypt', ex);
}
}
/**
* Encrypts data using symmetric encryption via asmCrypto
* @param {Array} key The AES key
* @param {Array} crypted [description]
* @param {Array} iv [description]
* @param {Array|null} header [description]
* @return {Promise} [description]
*/
async function symmetricDecrypt(key, crypted, iv, header) {
try {
header = header || [];
const aes = new sjcl.cipher.aes(key);
return sjcl.mode.gcm.decrypt(aes, crypted, iv, header, 96);
} catch (ex) {
console.error('SyncCryptLegacy.symmetricDecrypt() failed');
console.error(ex);
}
}
/**
* File Data decrypt
* @param {Array} data [description]
* @param {Array|String} key [description]
* @param {Integer} offset [description]
* @return {Promise}
*/
async function filedataDecrypt(data, key, offset=0) {
let header = getPartialBytes(data, 0, 96),
iv = getPartialBytes(data, 96, 192),
encdata = getPartialBytes(data, 192);
if (!checkHeaderOffset(header, offset)) {
throw new ErrCode(2020);
}
let decrypt_data = await symmetricDecrypt(
getPartialBytes(key, 0, 256),
encdata,
iv,
header
);
//~ return bytesToB64(decrypt_data)
return bytesToB64(decrypt_data)
}
/**
* Checks if packed in header offset matches the expected offset
* @param {Array|ArrayBuffer} header [description]
* @param {Integer} offset [description]
* @return {Boolean}
*/
function checkHeaderOffset(
header,
offset
) {
let isValid = true;
if (offset % GCM_PACKET_SIZE !== 0) {
console.error(
'offset is not a multiple of ' + GCM_PACKET_SIZE
);
isValid = false;
}
let expected_offset =
(offset / GCM_PACKET_SIZE) * GCM_PAYLOAD_SIZE;
let stored_offset = unpackHeader(header);
if (expected_offset != stored_offset && stored_offset > -1) {
isValid = false;
console.error(
'offset mismatch: want ' +
expected_offset +
' got ' +
stored_offset +
' header:' +
header
);
}
//~ else {
//~ console.log('offset: want ' + expected_offset +
//~ ' got ' + stored_offset +
//~ ' header:' + header);
//~ }
return isValid;
}
/**
* @ngdoc method
* @name unpackHeader
* @methodOf sync.service:SyncCryptBuffer
* @description
* Unpacks the header array and returns the encrypted offset stored within
* @param {Uint8Array} header [description]
* @return {Integer} [description]
*/
function unpackHeader(header) {
const a = new Uint8Array(header);
let hi = (a[2] << 8) | (a[3] << 0);
let lo = (a[4] << 24) | (a[5] << 16) | (a[6] << 8) | (a[7] << 0);
// force to floating point
hi = hi * 1.0;
lo = lo * 1.0;
return hi * (0xFFFFFFFF + 1) + lo;
}
/**
* Decrypts a data key
* @param encDataKey base64 number prefix of encrypted data key
* @param sharekey base64 of the share key (decrypted)
*/
async function datakeyDecrypt(encDataKey, sharekey) {
const bytes = b64ToBytes(
encDataKey.split(':')[1]
);
try {
return await decryptDataKey(sharekey, bytes);
} catch (ex) {
console.error('Unable to decrypt data key');
console.error(ex)
}
}
async function decryptDataKey(sharekey, bytes) {
const sharekeyBytes = shareKeyToBytes(sharekey);
if (sharekeyBytes === null) {
throw new ErrCode(2015);
}
const iv = getPartialBytes(bytes, 0, 96),
rawDk = getPartialBytes(bytes, 96);
const datakey = await symmetricDecrypt(
getPartialBytes(sharekeyBytes, 0, 256),
rawDk,
iv
);
// need to return b64??
//~ return bytesToB64(datakey);
return datakey;
}
async function sharekeyDecrypt(
encShareKey,
shareKeyId
) {
const pk = priv;
try {
const sharekeyB64 = await asymmetricDecrypt(
pk,
encShareKey
);
return sharekeyB64;
} catch (ex) {
console.errr(
'Error attempting asymmetric decryption' +
' for ' +
shareKeyId +
' ' +
encShareKey,
ex
);
}
}
/**
* Decrypts a crypted string with RSA. Uses PidCrypt's RSA functions.
* @param {String} privkey In PEM format with new lines replaced with
* '%' signs.
* @param {String} crypted Base64 string
* @return {Promise} [description]
*/
async function asymmetricDecrypt(privkey, crypted) {
try {
const cert = cleanCertificate(privkey);
const rsa = new pidCrypt.RSA(),
key = pidCryptUtil.decodeBase64(cert),
asn = pidCrypt.ASN1.decode(pidCryptUtil.toByteArray(key)),
tree = asn.toHexTree();
const data = pidCryptUtil.decodeBase64(pidCryptUtil.stripLineFeeds(crypted));
rsa.setPrivateKeyFromASN(tree);
const ret = pidCryptUtil.encodeBase64(
rsa.decrypt(pidCryptUtil.convertToHex(data))
);
return Promise.resolve(ret);
} catch (ex) {
// if errcode 2024 when inviting share, it typically means the enc_password
// field is invalid.
console.error('Error in asymmetric decrypt for ' + crypted, ex);
console.error('SyncCryptLegacy.asymmetricDecrypt() failed');
}
}
/**
* Cleans a certificate and ensures it's formatted in the correct method.
*
* The certificiate must have all new line chars replaced with '%' signs
*
* @param {String} privkey [description]
* @return {String} [description]
*/
function cleanCertificate(privkey) {
privkey = privkey.split('%').join('\n');
let cert = '', len, i;
const lines = privkey.split('\n');
for (i = 0, len = lines.length; i < len; i++) {
switch (lines[i].substr(0, 9)) {
case '-----BEGI': break;
case '-----END ': break;
default:
cert += lines[i].replace(/(\r\n|\n|\r)/gm, ' ');
}
}
return cert;
}
/**
* Login
*/
let infos = await authenticate(username, password)
/**
* Store data from login in a decrypted format
*/
const accessData = infos[0]
const meta = infos[1][0]
const priv = infos[1][1]
/**
* Download and decrypt file
*/
async function download_decrypt_id(id) {
let getfile = await get(id)
//~ console.log(getfile)
let filename = await filenameDecrypt(getfile['enc_name'])
console.log(filename)
let data = await getData([getfile])
//~ console.log(data)
let datakey_id = getfile['id']
let sharekey_id = data['datakeys'][datakey_id]['share_key_id']
let sharekey_dec = await sharekeyDecrypt(data['sharekeys'][sharekey_id], sharekey_id)
let datakey_enc = data['datakeys'][datakey_id]['enc_data_key']
let datakey = await datakeyDecrypt(datakey_enc, sharekey_dec)
// Based if filesize is smaller or larger than GCM PACKET we can download in one time or not
if (getfile['size'] < GCM_PACKET_SIZE) {
//~ console.log("smaller file than GCM PACKET")
const fileStream = fs.createWriteStream(filename)
// size is size encrypted but we miss the "36" that close the gcm payload
var download_url = mkDownloadUrl(getfile, 0, getfile['size']+36)
console.log(download_url)
let data_enc = await got(download_url).buffer()
let data_bytes_enc = arraybufferToBytes(data_enc)
fileStream.write(Buffer(await filedataDecrypt(data_bytes_enc, datakey), 'base64'), offset)
} else {
//~ console.log("larger file than GCM PACKET")
var offset = 0
// CHUNK_SIZE + 1 GCM_PACKET_SIZE
var length = CHUNK_SIZE + GCM_PACKET_SIZE
// If filesize is smaller than a chunk we use GCM_PACKET_SIZE instead
if (getfile['size'] < length){
//~ console.log("Filesize is smaller than a chunk, use GCM_PACKET_SIZE instead")
length = GCM_PACKET_SIZE
}
const fileStream = fs.createWriteStream(filename)
while (offset <= getfile['size']) {
var download_url = mkDownloadUrl(getfile, offset, length)
//~ console.log("Download started")
console.log(download_url)
let data_buffer_enc = await got(download_url).buffer()
//~ console.log("Download End")
let start = 0
let cryptoffset = offset + 0
while (start < data_buffer_enc.length) {
let end = start + GCM_PACKET_SIZE
//~ console.log(data_buffer_enc.length)
//~ console.log('Decrypt...')
//~ console.log(start)
//~ console.log(end)
let data_enc = data_buffer_enc.slice(start, end)
let data_bytes_enc = arraybufferToBytes(data_enc)
fileStream.write(Buffer(await filedataDecrypt(data_bytes_enc, datakey), 'base64'), cryptoffset)
start = start + GCM_PACKET_SIZE
cryptoffset = cryptoffset + GCM_PACKET_SIZE
}
offset = offset + length
if (getfile['size'] - offset < length) {
if (length == GCM_PACKET_SIZE) {
//~ console.log("Calculate last remaining to be downloaded in GCM_PACKET_SIZE")
// Amount of GCM payload we got
let gcm_packets_payloads = Math.ceil( (getfile['size'] / GCM_PAYLOAD_SIZE) )
// For each GCM packets we multiply by 36 for adding authenticated messages
let additionnal_authenticated_messages = gcm_packets_payloads * 36
length = ( getfile['size'] - offset ) + additionnal_authenticated_messages
} else {
//~ console.log("We cannot download a full chunk anymore, use GCM_PACKET_SIZE")
length = GCM_PACKET_SIZE
}
}
//~ console.log("next offset: " + offset)
//~ console.log("next length: " + length)
}
}
}
/**
* Download chunk
*/
async function downloadChunk(getfile, offset, length) {
let download_url = mkDownloadUrl(getfile, offset, length)
//~ console.log(download_url)
return await got(download_url).buffer()
}
/**
* Decrypt chunk
*/
async function decryptChunk(data_buffer_enc, datakey) {
let decryptArray = []
let decryptPos = 0
// We decrypt by GCM_PACKET_SIZE
while (decryptPos < data_buffer_enc.length) {
let decryptLen = decryptPos + GCM_PACKET_SIZE
let data_enc = data_buffer_enc.slice(decryptPos, decryptLen)
let data_bytes_enc = arraybufferToBytes(data_enc)
decryptArray.push(Buffer(await filedataDecrypt(data_bytes_enc, datakey), 'base64'))
decryptPos = decryptPos + GCM_PACKET_SIZE
}
return Buffer.concat(decryptArray)
}
/**
* Download and decrypt to file new
*/
async function download_decrypt_to_file(id, fd) {
// Variables for download chunk
let getfile = await get(id)
let filename = await filenameDecrypt(getfile['enc_name'])
let size = getfile['size']
let sizeTotal = (Math.ceil(size / GCM_PAYLOAD_SIZE) * 36) + size
//~ console.log(filename)
//~ let fullChunkSize = CHUNK_SIZE + GCM_PACKET_SIZE
let fullChunkSize = GCM_PACKET_SIZE
let downloadOffset = 0
let downloadLen = (sizeTotal - downloadOffset) > fullChunkSize ? fullChunkSize : (sizeTotal - downloadOffset)
//~ const fileStream = fs.createWriteStream(filename)
const fileStream = fs.createWriteStream(null, {fd: fd})
// Handle error
fileStream.on("error", function(err) {
// Don't care about any errors for now
// TODO only skip if err code is EBADF
if(err) {
console.log(err)
if(err.code == "EBADF") flagWhile = false
}
})
let flagWhile = true
// For 1 CHUNK_SIZE it's about 81 GCM_PACKET_SIZE
let nbMT = 81 * mtSpeed
let listMT = []
// Variables needed for decryption
let data = await getData([getfile])
let datakey_id = getfile['id']
let sharekey_id = data['datakeys'][datakey_id]['share_key_id']
let sharekey_dec = await sharekeyDecrypt(data['sharekeys'][sharekey_id], sharekey_id)
let datakey_enc = data['datakeys'][datakey_id]['enc_data_key']
let datakey = await datakeyDecrypt(datakey_enc, sharekey_dec)
async function multithread(getfile, downloadOffset, downloadLen) {
// Download chunk
let chunkEncrypted = await downloadChunk(getfile, downloadOffset, downloadLen)
return await decryptChunk(chunkEncrypted, datakey)
}
while( ((sizeTotal - downloadOffset) > 0) && (flagWhile == true) ) {
for(let i = 0; i < nbMT; i = i + 1) {
// Quit if downloadLen == 0 it means we not have anymore to download
if (downloadLen == 0) {
break
}
// Launch process
//~ console.log("multithread(" + getfile + ", " + downloadOffset + ", "+ downloadLen + ")")
listMT.push(multithread(getfile, downloadOffset, downloadLen))
// Update downloadOffset and downloadLen
downloadOffset += downloadLen
downloadLen = (sizeTotal - downloadOffset) > fullChunkSize ? fullChunkSize : (sizeTotal - downloadOffset)
//~ console.log("downloadOffset: " + downloadOffset)
//~ console.log("downloadLen: " + downloadLen)
}
for(let i = 0; i < nbMT; i = i + 1) {
// Write decryptedChunk
//~ console.log("Wait for " + i)
let data = await listMT.shift()
// Write only if data != undefined
if(data != undefined) {
fileStream.write(data)
}
}
}
}
/**
* Download and decrypt to file new
*/
async function download_decrypt_chunk(id, offset) {
// Variables for download chunk
let getfile = await get(id)
let size = getfile['size']
let sizeTotal = (Math.ceil(size / GCM_PAYLOAD_SIZE) * 36) + size
let fullChunkSize = CHUNK_SIZE + GCM_PACKET_SIZE
let downloadOffset = offset
// Calculate maximum downloadLen
// Maximum we can download as length is fullChunkSize
// fullChunkSize - (downloadOffset % fullChunkSize)
let downloadLen = (fullChunkSize - (downloadOffset % fullChunkSize))
// Check if we still get enough to be downloaded for downloadLen
downloadLen = (sizeTotal - downloadOffset) < downloadLen ? (sizeTotal - downloadOffset) : downloadLen
// Download chunk
let chunkEncrypted = await downloadChunk(getfile, downloadOffset, downloadLen)
// Variables needed for decryption
let data = await getData([getfile])
let datakey_id = getfile['id']
let sharekey_id = data['datakeys'][datakey_id]['share_key_id']
let sharekey_dec = await sharekeyDecrypt(data['sharekeys'][sharekey_id], sharekey_id)
let datakey_enc = data['datakeys'][datakey_id]['enc_data_key']
let datakey = await datakeyDecrypt(datakey_enc, sharekey_dec)