forked from t3rm1n4l/go-mega
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mega.go
1278 lines (1056 loc) · 24.4 KB
/
mega.go
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
package mega
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
mrand "math/rand"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
var client *http.Client
// Default settings
const (
API_URL = "https://eu.api.mega.co.nz"
BASE_DOWNLOAD_URL = "https://mega.co.nz"
RETRIES = 10
DOWNLOAD_WORKERS = 3
MAX_DOWNLOAD_WORKERS = 30
UPLOAD_WORKERS = 1
MAX_UPLOAD_WORKERS = 30
TIMEOUT = time.Second * 10
)
type config struct {
baseurl string
retries int
dl_workers int
ul_workers int
timeout time.Duration
}
func newConfig() config {
return config{
baseurl: API_URL,
retries: RETRIES,
dl_workers: DOWNLOAD_WORKERS,
ul_workers: UPLOAD_WORKERS,
timeout: TIMEOUT,
}
}
// Set mega service base url
func (c *config) SetAPIUrl(u string) {
if strings.HasSuffix(u, "/") {
u = strings.TrimRight(u, "/")
}
c.baseurl = u
}
// Set number of retries for api calls
func (c *config) SetRetries(r int) {
c.retries = r
}
// Set concurrent download workers
func (c *config) SetDownloadWorkers(w int) error {
if w <= MAX_DOWNLOAD_WORKERS {
c.dl_workers = w
return nil
}
return EWORKER_LIMIT_EXCEEDED
}
// Set connection timeout
func (c *config) SetTimeOut(t time.Duration) {
c.timeout = t
}
// Set concurrent upload workers
func (c *config) SetUploadWorkers(w int) error {
if w <= MAX_UPLOAD_WORKERS {
c.ul_workers = w
return nil
}
return EWORKER_LIMIT_EXCEEDED
}
type Mega struct {
config
// Sequence number
sn int64
// Server state sn
ssn string
// Session ID
sid []byte
// Master key
k []byte
// User handle
uh []byte
// Filesystem object
FS *MegaFS
}
// Filesystem node types
const (
FILE = 0
FOLDER = 1
ROOT = 2
INBOX = 3
TRASH = 4
)
// Filesystem node
type Node struct {
name string
hash string
parent *Node
children []*Node
ntype int
size int64
ts time.Time
meta NodeMeta
}
func (n *Node) removeChild(c *Node) bool {
index := -1
for i, v := range n.children {
if v.hash == c.hash {
index = i
break
}
}
if index >= 0 {
n.children[index] = n.children[len(n.children)-1]
n.children = n.children[:len(n.children)-1]
return true
}
return false
}
func (n *Node) addChild(c *Node) {
if n != nil {
n.children = append(n.children, c)
}
}
func (n Node) getChildren() []*Node {
return n.children
}
func (n Node) GetType() int {
return n.ntype
}
func (n Node) GetSize() int64 {
return n.size
}
func (n Node) GetTimeStamp() time.Time {
return n.ts
}
func (n Node) GetName() string {
return n.name
}
func (n Node) GetHash() string {
return n.hash
}
type NodeMeta struct {
key []byte
compkey []byte
iv []byte
mac []byte
}
// Mega filesystem object
type MegaFS struct {
root *Node
trash *Node
inbox *Node
sroots []*Node
lookup map[string]*Node
skmap map[string]string
mutex sync.Mutex
}
// Get filesystem root node
func (fs MegaFS) GetRoot() *Node {
fs.mutex.Lock()
defer fs.mutex.Unlock()
return fs.root
}
// Get filesystem trash node
func (fs MegaFS) GetTrash() *Node {
fs.mutex.Lock()
defer fs.mutex.Unlock()
return fs.trash
}
// Get inbox node
func (fs MegaFS) GetInbox() *Node {
fs.mutex.Lock()
defer fs.mutex.Unlock()
return fs.inbox
}
// Get a node pointer from its hash
func (fs MegaFS) HashLookup(h string) *Node {
fs.mutex.Lock()
defer fs.mutex.Unlock()
return fs.hashLookup(h)
}
func (fs MegaFS) hashLookup(h string) *Node {
if node, ok := fs.lookup[h]; ok {
return node
}
return nil
}
// Get the list of child nodes for a given node
func (fs MegaFS) GetChildren(n *Node) ([]*Node, error) {
fs.mutex.Lock()
defer fs.mutex.Unlock()
var empty []*Node
if n == nil {
return empty, EARGS
}
node := fs.hashLookup(n.hash)
if node == nil {
return empty, ENOENT
}
return node.getChildren(), nil
}
// Retreive all the nodes in the given node tree path by name
// This method returns array of nodes upto the matched subpath
// (in same order as input names array) even if the target node is not located.
func (fs MegaFS) PathLookup(root *Node, ns []string) ([]*Node, error) {
fs.mutex.Lock()
defer fs.mutex.Unlock()
if root == nil {
return nil, EARGS
}
var err error
var found bool = true
nodepath := []*Node{}
children := root.children
for _, name := range ns {
found = false
for _, n := range children {
if n.name == name {
nodepath = append(nodepath, n)
children = n.children
found = true
break
}
}
if found == false {
break
}
}
if found == false {
err = ENOENT
}
return nodepath, err
}
// Get top level directory nodes shared by other users
func (fs MegaFS) GetSharedRoots() []*Node {
fs.mutex.Lock()
defer fs.mutex.Unlock()
return fs.sroots
}
func newMegaFS() *MegaFS {
fs := &MegaFS{
lookup: make(map[string]*Node),
skmap: make(map[string]string),
}
return fs
}
func New() *Mega {
max := big.NewInt(0x100000000)
bigx, _ := rand.Int(rand.Reader, max)
cfg := newConfig()
client = newHttpClient(cfg.timeout)
mgfs := newMegaFS()
m := &Mega{
config: cfg,
sn: bigx.Int64(),
FS: mgfs,
}
return m
}
// API request method
func (m *Mega) api_request(r []byte) ([]byte, error) {
var err error
var resp *http.Response
var buf []byte
defer func() {
m.sn++
}()
url := fmt.Sprintf("%s/cs?id=%d", m.baseurl, m.sn)
if m.sid != nil {
url = fmt.Sprintf("%s&sid=%s", url, string(m.sid))
}
for i := 0; i < m.retries+1; i++ {
resp, err = client.Post(url, "application/json", bytes.NewBuffer(r))
if err == nil {
if resp.StatusCode == 200 {
goto success
} else {
resp.Body.Close()
}
err = errors.New("Http Status:" + resp.Status)
}
if err != nil {
continue
}
success:
buf, _ = ioutil.ReadAll(resp.Body)
resp.Body.Close()
if bytes.HasPrefix(buf, []byte("[")) == false && bytes.HasPrefix(buf, []byte("-")) == false {
return nil, EBADRESP
}
if len(buf) < 6 {
var emsg [1]ErrorMsg
err = json.Unmarshal(buf, &emsg)
if err != nil {
err = json.Unmarshal(buf, &emsg[0])
}
if err != nil {
return buf, EBADRESP
}
err = parseError(emsg[0])
if err == EAGAIN {
time.Sleep(time.Millisecond * time.Duration(10))
continue
}
return buf, err
}
if err == nil {
return buf, nil
}
}
return nil, err
}
// Authenticate and start a session
func (m *Mega) Login(email string, passwd string) error {
var msg [1]LoginMsg
var res [1]LoginResp
var err error
var result []byte
passkey := password_key(passwd)
uhandle := stringhash(email, passkey)
m.uh = make([]byte, len(uhandle))
copy(m.uh, uhandle)
msg[0].Cmd = "us"
msg[0].User = email
msg[0].Handle = string(uhandle)
req, _ := json.Marshal(msg)
result, err = m.api_request(req)
if err != nil {
return err
}
err = json.Unmarshal(result, &res)
if err != nil {
return err
}
m.k = base64urldecode([]byte(res[0].Key))
cipher, err := aes.NewCipher(passkey)
cipher.Decrypt(m.k, m.k)
m.sid = decryptSessionId([]byte(res[0].Privk), []byte(res[0].Csid), m.k)
if err != nil {
return err
}
err = m.getFileSystem()
return err
}
// Get user information
func (m Mega) GetUser() (UserResp, error) {
var msg [1]UserMsg
var res [1]UserResp
msg[0].Cmd = "ug"
req, _ := json.Marshal(msg)
result, err := m.api_request(req)
if err != nil {
return res[0], err
}
err = json.Unmarshal(result, &res)
return res[0], err
}
// Add a node into filesystem
func (m *Mega) addFSNode(itm FSNode) (*Node, error) {
var compkey, key []uint32
var attr FileAttr
var node, parent *Node
var err error
master_aes, _ := aes.NewCipher(m.k)
switch {
case itm.T == FOLDER || itm.T == FILE:
args := strings.Split(itm.Key, ":")
switch {
// File or folder owned by current user
case args[0] == itm.User:
buf := base64urldecode([]byte(args[1]))
blockDecrypt(master_aes, buf, buf)
compkey = bytes_to_a32(buf)
// Shared folder
case itm.SUser != "" && itm.SKey != "":
sk := base64urldecode([]byte(itm.SKey))
blockDecrypt(master_aes, sk, sk)
sk_aes, _ := aes.NewCipher(sk)
m.FS.skmap[itm.Hash] = itm.SKey
buf := base64urldecode([]byte(args[1]))
blockDecrypt(sk_aes, buf, buf)
compkey = bytes_to_a32(buf)
// Shared file
default:
k := m.FS.skmap[args[0]]
b := base64urldecode([]byte(k))
blockDecrypt(master_aes, b, b)
block, _ := aes.NewCipher(b)
buf := base64urldecode([]byte(args[1]))
blockDecrypt(block, buf, buf)
compkey = bytes_to_a32(buf)
}
switch {
case itm.T == FILE:
key = []uint32{compkey[0] ^ compkey[4], compkey[1] ^ compkey[5], compkey[2] ^ compkey[6], compkey[3] ^ compkey[7]}
default:
key = compkey
}
attr, err = decryptAttr(a32_to_bytes(key), []byte(itm.Attr))
// FIXME:
if err != nil {
attr.Name = "BAD ATTRIBUTE"
}
}
n, ok := m.FS.lookup[itm.Hash]
switch {
case ok:
node = n
default:
node = &Node{
ntype: itm.T,
size: itm.Sz,
ts: time.Unix(itm.Ts, 0),
}
m.FS.lookup[itm.Hash] = node
}
n, ok = m.FS.lookup[itm.Parent]
switch {
case ok:
parent = n
parent.removeChild(node)
parent.addChild(node)
default:
parent = nil
if itm.Parent != "" {
parent = &Node{
children: []*Node{node},
ntype: FOLDER,
}
m.FS.lookup[itm.Parent] = parent
}
}
switch {
case itm.T == FILE:
var meta NodeMeta
meta.key = a32_to_bytes(key)
meta.iv = a32_to_bytes([]uint32{compkey[4], compkey[5], 0, 0})
meta.mac = a32_to_bytes([]uint32{compkey[6], compkey[7]})
meta.compkey = a32_to_bytes(compkey)
node.meta = meta
case itm.T == FOLDER:
var meta NodeMeta
meta.key = a32_to_bytes(key)
meta.compkey = a32_to_bytes(compkey)
node.meta = meta
case itm.T == ROOT:
attr.Name = "Cloud Drive"
m.FS.root = node
case itm.T == INBOX:
attr.Name = "InBox"
m.FS.inbox = node
case itm.T == TRASH:
attr.Name = "Trash"
m.FS.trash = node
}
// Shared directories
if itm.SUser != "" && itm.SKey != "" {
m.FS.sroots = append(m.FS.sroots, node)
}
node.name = attr.Name
node.hash = itm.Hash
node.parent = parent
node.ntype = itm.T
return node, nil
}
// Get all nodes from filesystem
func (m *Mega) getFileSystem() error {
m.FS.mutex.Lock()
defer m.FS.mutex.Unlock()
var msg [1]FilesMsg
var res [1]FilesResp
msg[0].Cmd = "f"
msg[0].C = 1
req, _ := json.Marshal(msg)
result, err := m.api_request(req)
if err != nil {
return err
}
err = json.Unmarshal(result, &res)
if err != nil {
return err
}
for _, sk := range res[0].Ok {
m.FS.skmap[sk.Hash] = sk.Key
}
for _, itm := range res[0].F {
m.addFSNode(itm)
}
m.ssn = res[0].Sn
go m.pollEvents()
return nil
}
// Download file from filesystem
func (m Mega) DownloadFile(src *Node, dstpath string, progress *chan int) error {
m.FS.mutex.Lock()
defer m.FS.mutex.Unlock()
defer func() {
if progress != nil {
close(*progress)
}
}()
if src == nil {
return EARGS
}
var msg [1]DownloadMsg
var res [1]DownloadResp
var outfile *os.File
var mutex sync.Mutex
_, err := os.Stat(dstpath)
if os.IsExist(err) {
os.Remove(dstpath)
}
outfile, err = os.OpenFile(dstpath, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return err
}
msg[0].Cmd = "g"
msg[0].G = 1
msg[0].N = src.hash
request, _ := json.Marshal(msg)
result, err := m.api_request(request)
if err != nil {
return err
}
err = json.Unmarshal(result, &res)
if err != nil {
return err
}
resourceUrl := res[0].G
_, err = decryptAttr(src.meta.key, []byte(res[0].Attr))
aes_block, _ := aes.NewCipher(src.meta.key)
mac_data := a32_to_bytes([]uint32{0, 0, 0, 0})
mac_enc := cipher.NewCBCEncrypter(aes_block, mac_data)
t := bytes_to_a32(src.meta.iv)
iv := a32_to_bytes([]uint32{t[0], t[1], t[0], t[1]})
sorted_chunks := []int{}
chunks := getChunkSizes(int(res[0].Size))
chunk_macs := make([][]byte, len(chunks))
for k, _ := range chunks {
sorted_chunks = append(sorted_chunks, k)
}
sort.Ints(sorted_chunks)
workch := make(chan int)
errch := make(chan error, m.dl_workers)
wg := sync.WaitGroup{}
// Fire chunk download workers
for w := 0; w < m.dl_workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
// Wait for work blocked on channel
for id := range workch {
var resource *http.Response
var err error
mutex.Lock()
chk_start := sorted_chunks[id]
chk_size := chunks[chk_start]
mutex.Unlock()
chunk_url := fmt.Sprintf("%s/%d-%d", resourceUrl, chk_start, chk_start+chk_size-1)
for retry := 0; retry < m.retries+1; retry++ {
resource, err = client.Get(chunk_url)
if err == nil {
if resource.StatusCode == 200 {
break
} else {
resource.Body.Close()
}
}
}
var ctr_iv []uint32
var ctr_aes cipher.Stream
var chunk []byte
if err == nil {
ctr_iv = bytes_to_a32(src.meta.iv)
ctr_iv[2] = uint32(uint64(chk_start) / 0x1000000000)
ctr_iv[3] = uint32(chk_start / 0x10)
ctr_aes = cipher.NewCTR(aes_block, a32_to_bytes(ctr_iv))
chunk, err = ioutil.ReadAll(resource.Body)
}
if err != nil {
errch <- err
return
}
resource.Body.Close()
ctr_aes.XORKeyStream(chunk, chunk)
outfile.WriteAt(chunk, int64(chk_start))
enc := cipher.NewCBCEncrypter(aes_block, iv)
i := 0
block := []byte{}
chunk = paddnull(chunk, 16)
for i = 0; i < len(chunk); i += 16 {
block = chunk[i : i+16]
enc.CryptBlocks(block, block)
}
mutex.Lock()
if len(chunk_macs) > 0 {
chunk_macs[id] = make([]byte, 16)
copy(chunk_macs[id], block)
}
mutex.Unlock()
if progress != nil {
*progress <- chk_size
}
}
}()
}
// Place chunk download jobs to chan
err = nil
for id := 0; id < len(chunks) && err == nil; {
select {
case workch <- id:
id++
case err = <-errch:
}
}
close(workch)
wg.Wait()
if err != nil {
os.Remove(dstpath)
return err
}
for _, v := range chunk_macs {
mac_enc.CryptBlocks(mac_data, v)
}
outfile.Close()
tmac := bytes_to_a32(mac_data)
if bytes.Equal(a32_to_bytes([]uint32{tmac[0] ^ tmac[1], tmac[2] ^ tmac[3]}), src.meta.mac) == false {
return EMACMISMATCH
}
return nil
}
// Upload a file to the filesystem
func (m *Mega) UploadFile(srcpath string, parent *Node, name string, progress *chan int) (*Node, error) {
m.FS.mutex.Lock()
defer m.FS.mutex.Unlock()
defer func() {
if progress != nil {
close(*progress)
}
}()
if parent == nil {
return nil, EARGS
}
var msg [1]UploadMsg
var res [1]UploadResp
var cmsg [1]UploadCompleteMsg
var cres [1]UploadCompleteResp
var infile *os.File
var fileSize int64
var mutex sync.Mutex
parenthash := parent.hash
info, err := os.Stat(srcpath)
if err == nil {
fileSize = info.Size()
}
infile, err = os.OpenFile(srcpath, os.O_RDONLY, 0666)
if err != nil {
return nil, err
}
msg[0].Cmd = "u"
msg[0].S = fileSize
completion_handle := []byte{}
request, _ := json.Marshal(msg)
result, err := m.api_request(request)
if err != nil {
return nil, err
}
err = json.Unmarshal(result, &res)
if err != nil {
return nil, err
}
uploadUrl := res[0].P
ukey := []uint32{0, 0, 0, 0, 0, 0}
for i, _ := range ukey {
ukey[i] = uint32(mrand.Int31())
}
kbytes := a32_to_bytes(ukey[:4])
kiv := a32_to_bytes([]uint32{ukey[4], ukey[5], 0, 0})
aes_block, _ := aes.NewCipher(kbytes)
mac_data := a32_to_bytes([]uint32{0, 0, 0, 0})
mac_enc := cipher.NewCBCEncrypter(aes_block, mac_data)
iv := a32_to_bytes([]uint32{ukey[4], ukey[5], ukey[4], ukey[5]})
sorted_chunks := []int{}
chunks := getChunkSizes(int(fileSize))
chunk_macs := make([][]byte, len(chunks))
for k, _ := range chunks {
sorted_chunks = append(sorted_chunks, k)
}
sort.Ints(sorted_chunks)
workch := make(chan int)
errch := make(chan error, m.ul_workers)
wg := sync.WaitGroup{}
// Fire chunk upload workers
for w := 0; w < m.ul_workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for id := range workch {
mutex.Lock()
chk_start := sorted_chunks[id]
chk_size := chunks[chk_start]
mutex.Unlock()
ctr_iv := bytes_to_a32(kiv)
ctr_iv[2] = uint32(uint64(chk_start) / 0x1000000000)
ctr_iv[3] = uint32(chk_start / 0x10)
ctr_aes := cipher.NewCTR(aes_block, a32_to_bytes(ctr_iv))
chunk := make([]byte, chk_size)
n, _ := infile.ReadAt(chunk, int64(chk_start))
chunk = chunk[:n]
enc := cipher.NewCBCEncrypter(aes_block, iv)
i := 0
block := make([]byte, 16)
paddedchunk := paddnull(chunk, 16)
for i = 0; i < len(paddedchunk); i += 16 {
copy(block[0:16], paddedchunk[i:i+16])
enc.CryptBlocks(block, block)
}
mutex.Lock()
if len(chunk_macs) > 0 {
chunk_macs[id] = make([]byte, 16)
copy(chunk_macs[id], block)
}
mutex.Unlock()
var rsp *http.Response
var err error
ctr_aes.XORKeyStream(chunk, chunk)
chk_url := fmt.Sprintf("%s/%d", uploadUrl, chk_start)
reader := bytes.NewBuffer(chunk)
req, _ := http.NewRequest("POST", chk_url, reader)
chunk_resp := []byte{}
for retry := 0; retry < m.retries+1; retry++ {
rsp, err = client.Do(req)
if err == nil {
if rsp.StatusCode == 200 {
break
} else {
rsp.Body.Close()
}
}
}
chunk_resp, err = ioutil.ReadAll(rsp.Body)
if err != nil {
errch <- err
return
}
rsp.Body.Close()
if bytes.Equal(chunk_resp, nil) == false {
mutex.Lock()
completion_handle = chunk_resp
mutex.Unlock()
}
if progress != nil {
*progress <- chk_size
}
}
}()
}
err = nil
if len(chunks) == 0 {
// File size is zero
// Tell single worker to request for completion handle
sorted_chunks = append(sorted_chunks, 0)
chunks[0] = 0
workch <- 0
} else {
// Place chunk download jobs to chan
for id := 0; id < len(chunks) && err == nil; {
select {
case workch <- id:
id++
case err = <-errch:
}
}
}
close(workch)
wg.Wait()
if err != nil {
return nil, err
}
for _, v := range chunk_macs {
mac_enc.CryptBlocks(mac_data, v)
}
t := bytes_to_a32(mac_data)
meta_mac := []uint32{t[0] ^ t[1], t[2] ^ t[3]}
filename := filepath.Base(srcpath)
if name != "" {
filename = name
}
attr := FileAttr{filename}
attr_data, _ := encryptAttr(kbytes, attr)
key := []uint32{ukey[0] ^ ukey[4], ukey[1] ^ ukey[5],
ukey[2] ^ meta_mac[0], ukey[3] ^ meta_mac[1],
ukey[4], ukey[5], meta_mac[0], meta_mac[1]}
buf := a32_to_bytes(key)
master_aes, _ := aes.NewCipher(m.k)
iv = a32_to_bytes([]uint32{0, 0, 0, 0})
enc := cipher.NewCBCEncrypter(master_aes, iv)
enc.CryptBlocks(buf[:16], buf[:16])
enc = cipher.NewCBCEncrypter(master_aes, iv)
enc.CryptBlocks(buf[16:], buf[16:])
cmsg[0].Cmd = "p"
cmsg[0].T = parenthash
cmsg[0].N[0].H = string(completion_handle)
cmsg[0].N[0].T = FILE
cmsg[0].N[0].A = string(attr_data)
cmsg[0].N[0].K = string(base64urlencode(buf))
request, _ = json.Marshal(cmsg)
result, err = m.api_request(request)
if err != nil {
return nil, err
}
err = json.Unmarshal(result, &cres)
if err != nil {
return nil, err
}
node, err := m.addFSNode(cres[0].F[0])