/
u16x16.go
742 lines (674 loc) · 18.7 KB
/
u16x16.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
package xlU_go
import (
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt" // DEBUG
xr "github.com/jddixon/rnglib_go"
xu "github.com/jddixon/xlUtil_go"
xf "github.com/jddixon/xlUtil_go/lfs"
"golang.org/x/crypto/sha3"
"os"
"path/filepath"
)
// CLASS, so to speak ///////////////////////////////////////////////
type U16x16 struct {
path string // all parameters are private
inDir string
tmpDir string
rng *xr.PRNG
}
// Create a new 16x16 file system, ORing perm into the default permissions.
// If perm is 0, the default is to allow user and group access.
// If the root is U, then this creates U/, U/tmp, U/in, and the top-level
// hex directories U/x
func NewU16x16(path string, perm os.FileMode) (udir *U16x16, err error) {
// TODO: validate path
var (
inDir, tmpDir string
)
err = os.MkdirAll(path, 0750|perm)
if err == nil {
inDir = filepath.Join(path, "in")
err = os.MkdirAll(inDir, 0770|perm)
if err == nil {
tmpDir = filepath.Join(path, "tmp")
err = os.MkdirAll(tmpDir, 0700)
if err == nil {
for i := 0; i < 16; i++ {
hexDir := fmt.Sprintf("%x", i)
hexPath := filepath.Join(path, hexDir)
err = os.MkdirAll(hexPath, 0750|perm)
if err != nil {
break
}
}
}
}
}
udir = &U16x16{
path: path,
rng: xr.MakeSimpleRNG(),
inDir: inDir,
tmpDir: tmpDir,
}
return
}
func (u *U16x16) GetDirStruc() DirStruc { return DIR16x16 }
func (u *U16x16) GetPath() string { return u.path }
func (u *U16x16) GetRNG() *xr.PRNG { return u.rng }
// HEX KEY FUNCTIONS ================================================
// DEPRECATED
func (u *U16x16) Exists(key string) (found bool, err error) {
return u.HexKeyExists(key)
}
func (u *U16x16) HexKeyExists(key string) (found bool, err error) {
path, err := u.GetPathForHexKey(key)
if err == nil {
found, err = xf.PathExists(path)
}
return
}
// DEPRECATED
func (u *U16x16) FileLen(key string) (length int64, err error) {
return u.HexKeyFileLen(key)
}
func (u *U16x16) HexKeyFileLen(key string) (length int64, err error) {
path, err := u.GetPathForHexKey(key)
if err == nil {
var info os.FileInfo
info, err = os.Stat(path) // ERRORS IGNORED
if err == nil {
length = info.Size()
}
}
return
}
// DEPRECATED
func (u *U16x16) GetPathForKey(key string) (path string, err error) {
return u.GetPathForHexKey(key)
}
// Returns a path to a file with the content key passed.
func (u *U16x16) GetPathForHexKey(key string) (path string, err error) {
if key == "" {
err = EmptyKey
} else {
topSubDir := key[0:1]
lowerDir := key[1:2]
path = filepath.Join(u.path, topSubDir, lowerDir, key[2:])
}
return
}
// BINARY KEY FUNCTIONS =============================================
// DEPRECATED
func (u *U16x16) KeyExists(key []byte) (found bool, err error) {
return u.ByteKeyExists(key)
}
func (u *U16x16) ByteKeyExists(key []byte) (found bool, err error) {
path, err := u.GetPathForByteKey(key)
if err == nil {
found, err = xf.PathExists(path)
}
return
}
// DEPRECATED
func (u *U16x16) KeyFileLen(key []byte) (length int64, err error) {
return u.ByteKeyFileLen(key)
}
func (u *U16x16) ByteKeyFileLen(key []byte) (length int64, err error) {
path, err := u.GetPathForByteKey(key)
if err == nil {
var info os.FileInfo
info, err = os.Stat(path)
if err == nil {
length = info.Size()
}
}
return
}
// DEPRECATED
func (u *U16x16) GetPathForBinaryKey(key []byte) (path string, err error) {
return u.GetPathForByteKey(key)
}
// Returns a path to a file with the content key passed.
//
func (u *U16x16) GetPathForByteKey(key []byte) (path string, err error) {
if key == nil {
err = NilKey
} else {
strKey := hex.EncodeToString(key)
path, err = u.GetPathForHexKey(strKey)
}
return
}
// SHA1/SHA3 NEUTRAL FUNCTIONS ======================================
// - CopyAndPut -----------------------------------------------------
// Copy the file at path to a randomly-named temporary file under U/tmp.
// If that operation succeeds, we then attempt to rename the file into
// the appropriate U data subdirectory. If the file is already present,
// we silently discard the copy. Returns the length of the file in bytes
// and any error.
//
// CopyAndPut1 and 3 return the actual content hash; this doesn't.
//
func (u *U16x16) CopyAndPut(pathToFile string, key []byte) (
length int64, err error) {
if pathToFile == "" {
err = EmptyPath
} else if key == nil {
err = NilKey
} else {
strKey := hex.EncodeToString(key)
switch len(strKey) {
case xu.SHA1_HEX_LEN:
length, _, err = u.CopyAndPut1(pathToFile, strKey)
case xu.SHA3_HEX_LEN:
length, _, err = u.CopyAndPut3(pathToFile, strKey)
default:
err = BadKeyLength
}
}
return
}
// - GetData --------------------------------------------------------
// Retrieves file contents using a binary key. The key is the SHA1
// or SHA3 hash of the file contents.
//
func (u *U16x16) GetData(key []byte) (data []byte, err error) {
if key == nil {
err = NilKey
} else {
strKey := hex.EncodeToString(key)
switch len(strKey) {
case xu.SHA1_HEX_LEN:
data, err = u.GetData1(strKey)
case xu.SHA3_HEX_LEN:
data, err = u.GetData3(strKey)
default:
err = BadKeyLength
}
}
return
}
// - Put ------------------------------------------------------------
// Given a local temporary file, either rename it into U or just silently
// delete it if the data is already present in U. Returns the length
// of the file and any error.
//
// Put1 and 3 return the actual content hash; this doesn't.
//
func (u *U16x16) Put(tmpFile string, key []byte) (length int64, err error) {
if tmpFile == "" {
err = EmptyPath
} else if key == nil {
err = NilKey
} else {
strKey := hex.EncodeToString(key)
switch len(strKey) {
case xu.SHA1_HEX_LEN:
length, _, err = u.Put1(tmpFile, strKey)
case xu.SHA3_HEX_LEN:
length, _, err = u.Put3(tmpFile, strKey)
default:
err = BadKeyLength
}
}
return
}
// - PutData --------------------------------------------------------
// Write data into the store using a binary key.
//
func (u *U16x16) PutData(data []byte, key []byte) (
length int64, hash []byte, err error) {
if key == nil {
err = NilKey
} else {
var strHash string
strKey := hex.EncodeToString(key)
switch len(strKey) {
case xu.SHA1_HEX_LEN:
length, strHash, err = u.PutData1(data, strKey)
case xu.SHA3_HEX_LEN:
length, strHash, err = u.PutData3(data, strKey)
default:
err = BadKeyLength
}
if err == nil {
hash, err = hex.DecodeString(strHash)
}
}
return
}
// SHA1 CODE ========================================================
// CopyAndPut1 ------------------------------------------------------
func (u *U16x16) CopyAndPut1(path, key string) (
written int64, hash string, err error) {
// the temporary file MUST be created on the same device
// xxx POSSIBLE RACE CONDITION
tmpFileName := filepath.Join(u.tmpDir, u.rng.NextFileName(16))
found, err := xf.PathExists(tmpFileName)
for found {
tmpFileName = filepath.Join(u.tmpDir, u.rng.NextFileName(16))
found, err = xf.PathExists(tmpFileName)
}
written, err = CopyFile(tmpFileName, path) // dest <== src
if err == nil {
written, hash, err = u.Put1(tmpFileName, key)
}
return
}
// - GetData1 --------------------------------------------------------
func (u *U16x16) GetData1(key string) (data []byte, err error) {
var (
found bool
path string
src *os.File
)
path, err = u.GetPathForKey(key)
if err == nil {
found, err = xf.PathExists(path)
}
if err == nil && !found {
err = FileNotFound
}
if err == nil {
src, err = os.Open(path)
}
if err == nil {
defer src.Close()
var count int
// XXX THIS WILL NOT WORK FOR LARGER FILES! It will ignore
// anything over 128 KB
data = make([]byte, DEFAULT_BUFFER_SIZE)
count, err = src.Read(data)
// XXX COUNT IS IGNORED
_ = count
}
return
}
// - Put1 ------------------------------------------------------------
// tmp is the path to a local file which will be renamed into U (or deleted
// if it is already present in U)
// u.path is an absolute or relative path to a U directory organized 16x16
// key is an sha1 content hash.
// If the operation succeeds we return the length of the file (which must
// not be zero. Otherwise we return 0.
// we don't do much checking.
//
func (u *U16x16) Put1(inFile, key string) (
length int64, hash string, err error) {
var (
found bool
fullishPath string
topSubDir, lowerDir, targetDir string
)
hash, err = FileHexSHA1(inFile)
if err != nil {
fmt.Printf("DEBUG: FileHexSHA1 returned error %v\n", err)
return
}
if hash != key {
fmt.Printf("expected %s to have key %s, but the content key is %s\n",
inFile, key, hash)
err = errors.New("IllegalArgument: Put1: key does not match content")
return
}
info, err := os.Stat(inFile)
if err != nil {
return
}
length = info.Size()
topSubDir = hash[0:1]
lowerDir = hash[1:2]
targetDir = filepath.Join(u.path, topSubDir, lowerDir)
found, err = xf.PathExists(targetDir)
if err == nil && !found {
// XXX MODE IS SUSPECT
err = os.MkdirAll(targetDir, 0775)
}
if err == nil {
fullishPath = filepath.Join(targetDir, key[2:])
found, err = xf.PathExists(fullishPath)
}
if err == nil {
if found {
// drop the temporary input file
err = os.Remove(inFile)
} else {
// rename the temporary file into U
err = os.Rename(inFile, fullishPath)
if err == nil {
err = os.Chmod(fullishPath, 0444)
}
}
}
return
}
// PutData1 ---------------------------------------------------------
func (u *U16x16) PutData1(data []byte, key string) (
length int64, hash string, err error) {
var fullishPath string
var found bool
s := sha1.New()
s.Write(data)
hash = hex.EncodeToString(s.Sum(nil))
if hash != key {
fmt.Printf("expected data to have key %s, but content key is %s",
key, hash)
err = errors.New("content/key mismatch")
return
}
length = int64(len(data))
topSubDir := hash[0:1]
lowerDir := hash[1:2]
targetDir := filepath.Join(u.path, topSubDir, lowerDir)
found, err = xf.PathExists(targetDir)
if err == nil && !found {
// MODE QUESTIONABLE
err = os.MkdirAll(targetDir, 0775)
}
if err == nil {
fullishPath = filepath.Join(targetDir, key[2:])
found, err = xf.PathExists(fullishPath)
if err == nil && !found {
var dest *os.File
dest, err = os.Create(fullishPath)
if err == nil {
var count int
defer dest.Close()
count, err = dest.Write(data)
if err == nil {
length = int64(count)
}
}
}
}
return
}
// SHA3 CODE ========================================================
//- CopyAndPut3 -----------------------------------------------------
// Copy the file at path to a randomly-named temporary file under U/tmp.
// If that operation succeeds, we then attempt to rename the file into
// the appropriate U data subdirectory. If the file is already present,
// we silently discard the copy. Returns the length of the file in bytes,
// its actual content hash, and any error.
//
func (u *U16x16) CopyAndPut3(path, key string) (
written int64, hash string, err error) {
// the temporary file MUST be created on the same device
// xxx POSSIBLE RACE CONDITION
tmpFileName := filepath.Join(u.tmpDir, u.rng.NextFileName(16))
found, _ := xf.PathExists(tmpFileName) // XXX error ignored
for found {
tmpFileName = filepath.Join(u.tmpDir, u.rng.NextFileName(16))
found, _ = xf.PathExists(tmpFileName)
}
written, err = CopyFile(tmpFileName, path) // dest <== src
if err == nil {
written, hash, err = u.Put3(tmpFileName, key)
}
return
}
// - GetData3 --------------------------------------------------------
func (u *U16x16) GetData3(key string) (data []byte, err error) {
var (
found bool
path string
)
path, err = u.GetPathForKey(key)
if err == nil {
found, err = xf.PathExists(path)
}
if err == nil && !found {
err = FileNotFound
}
if err == nil {
var src *os.File
if src, err = os.Open(path); err != nil {
return
}
defer src.Close()
var count int
// XXX THIS WILL NOT WORK FOR LARGER FILES! It will ignore
// anything over 128 KB
data = make([]byte, DEFAULT_BUFFER_SIZE)
count, err = src.Read(data)
// XXX COUNT IS IGNORED
_ = count
}
return
}
// - Put3 ------------------------------------------------------------
// inFile is the path to a local file which will be renamed into U (or deleted
// if it is already present in U)
// u.path is an absolute or relative path to a U directory organized 16x16
// key is an sha3 content hash.
// If the operation succeeds we return the length of the file (which must
// not be zero. Otherwise we return 0.
// We don't do much checking.
//
func (u *U16x16) Put3(inFile, key string) (
length int64, hash string, err error) {
var fullishPath string
hash, err = FileHexSHA3(inFile)
if err != nil {
fmt.Printf("DEBUG: FileHexSHA3 returned error %v\n", err)
return
}
if hash != key {
fmt.Printf("expected %s to have key %s, but the content key is %s\n",
inFile, key, hash)
err = errors.New("IllegalArgument: Put3: key does not match content")
return
}
info, err := os.Stat(inFile)
if err != nil {
return
}
length = info.Size()
topSubDir := hash[0:1]
lowerDir := hash[1:2]
targetDir := filepath.Join(u.path, topSubDir, lowerDir)
found, err := xf.PathExists(targetDir)
if err == nil && !found {
// XXX MODE IS SUSPECT
err = os.MkdirAll(targetDir, 0775)
}
if err == nil {
var found bool
fullishPath = filepath.Join(targetDir, key[2:])
found, err = xf.PathExists(fullishPath)
if err == nil {
if found {
// drop the temporary input file
err = os.Remove(inFile)
} else {
// rename the temporary file into U
err = os.Rename(inFile, fullishPath)
}
}
}
if err == nil {
err = os.Chmod(fullishPath, 0444)
}
return
}
// - PutData3 --------------------------------------------------------
func (u *U16x16) PutData3(data []byte, key string) (length int64, hash string, err error) {
s := sha3.New256()
s.Write(data)
hash = hex.EncodeToString(s.Sum(nil))
if hash != key {
fmt.Printf("expected data to have key %s, but content key is %s",
key, hash)
err = errors.New("content/key mismatch")
return
}
length = int64(len(data))
topSubDir := hash[0:1]
lowerDir := hash[1:2]
targetDir := filepath.Join(u.path, topSubDir, lowerDir)
found, err := xf.PathExists(targetDir)
if err == nil && !found {
err = os.MkdirAll(targetDir, 0775)
}
fullishPath := filepath.Join(targetDir, key[2:])
found, err = xf.PathExists(fullishPath)
if !found {
var dest *os.File
dest, err = os.Create(fullishPath)
if err == nil {
var count int
defer dest.Close()
count, err = dest.Write(data)
if err == nil {
length = int64(count)
}
}
}
return
}
// SHA2 CODE ========================================================
//- CopyAndPut2 -----------------------------------------------------
// Copy the file at path to a randomly-named temporary file under U/tmp.
// If that operation succeeds, we then attempt to rename the file into
// the appropriate U data subdirectory. If the file is already present,
// we silently discard the copy. Returns the length of the file in bytes,
// its actual content hash, and any error.
//
func (u *U16x16) CopyAndPut2(path, key string) (
written int64, hash string, err error) {
// the temporary file MUST be created on the same device
// xxx POSSIBLE RACE CONDITION
tmpFileName := filepath.Join(u.tmpDir, u.rng.NextFileName(16))
found, _ := xf.PathExists(tmpFileName) // XXX error ignored
for found {
tmpFileName = filepath.Join(u.tmpDir, u.rng.NextFileName(16))
found, _ = xf.PathExists(tmpFileName)
}
written, err = CopyFile(tmpFileName, path) // dest <== src
if err == nil {
written, hash, err = u.Put2(tmpFileName, key)
}
return
}
// - GetData2 --------------------------------------------------------
func (u *U16x16) GetData2(key string) (data []byte, err error) {
var (
found bool
path string
)
path, err = u.GetPathForKey(key)
if err == nil {
found, err = xf.PathExists(path)
}
if err == nil && !found {
err = FileNotFound
}
if err == nil {
var src *os.File
if src, err = os.Open(path); err != nil {
return
}
defer src.Close()
var count int
// XXX THIS WILL NOT WORK FOR LARGER FILES! It will ignore
// anything over 128 KB
data = make([]byte, DEFAULT_BUFFER_SIZE)
count, err = src.Read(data)
// XXX COUNT IS IGNORED
_ = count
}
return
}
// - Put2 ------------------------------------------------------------
// inFile is the path to a local file which will be renamed into U (or deleted
// if it is already present in U)
// u.path is an absolute or relative path to a U directory organized 16x16
// key is an sha3 content hash.
// If the operation succeeds we return the length of the file (which must
// not be zero. Otherwise we return 0.
// We don't do much checking.
//
func (u *U16x16) Put2(inFile, key string) (
length int64, hash string, err error) {
var fullishPath string
hash, err = FileHexSHA2(inFile)
if err != nil {
fmt.Printf("DEBUG: FileHexSHA2 returned error %v\n", err)
return
}
if hash != key {
fmt.Printf("expected %s to have key %s, but the content key is %s\n",
inFile, key, hash)
err = errors.New("IllegalArgument: Put2: key does not match content")
return
}
info, err := os.Stat(inFile)
if err != nil {
return
}
length = info.Size()
topSubDir := hash[0:1]
lowerDir := hash[1:2]
targetDir := filepath.Join(u.path, topSubDir, lowerDir)
found, err := xf.PathExists(targetDir)
if err == nil && !found {
// XXX MODE IS SUSPECT
err = os.MkdirAll(targetDir, 0775)
}
if err == nil {
var found bool
fullishPath = filepath.Join(targetDir, key[2:])
found, err = xf.PathExists(fullishPath)
if err == nil {
if found {
// drop the temporary input file
err = os.Remove(inFile)
} else {
// rename the temporary file into U
err = os.Rename(inFile, fullishPath)
}
}
}
if err == nil {
err = os.Chmod(fullishPath, 0444)
}
return
}
// - PutData2 --------------------------------------------------------
func (u *U16x16) PutData2(data []byte, key string) (length int64, hash string, err error) {
s := sha256.New()
s.Write(data)
hash = hex.EncodeToString(s.Sum(nil))
if hash != key {
fmt.Printf("expected data to have key %s, but content key is %s",
key, hash)
err = errors.New("content/key mismatch")
return
}
length = int64(len(data))
topSubDir := hash[0:1]
lowerDir := hash[1:2]
targetDir := filepath.Join(u.path, topSubDir, lowerDir)
found, err := xf.PathExists(targetDir)
if err == nil && !found {
err = os.MkdirAll(targetDir, 0775)
}
fullishPath := filepath.Join(targetDir, key[2:])
found, err = xf.PathExists(fullishPath)
if !found {
var dest *os.File
dest, err = os.Create(fullishPath)
if err == nil {
var count int
defer dest.Close()
count, err = dest.Write(data)
if err == nil {
length = int64(count)
}
}
}
return
}