-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathESP32-targz-lib.cpp
2074 lines (1687 loc) · 62.2 KB
/
ESP32-targz-lib.cpp
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
/*\
MIT License
Copyright (c) 2020-now tobozo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
ESP32-tgz is a wrapper to uzlib.h and untar.h third party libraries.
Those libraries have been adapted and/or modified to fit this project's needs
and are bundled with their initial license files.
- uzlib: https://github.com/pfalcon/uzlib
- untar: https://github.com/dsoprea/TinyUntar
Tradeoffs :
- speed: fast decompression needs 32Kb memory
- memory: reducing memory use by dropping the gz_dictionary is VERY slow and prevents tar->gz->filesystem direct streaming
- space: limited filesystems (<512KB spiffs) need tar->gz->filesystem direct streaming
\*/
#include "ESP32-targz-lib.h"
struct TarGzIO
{
Stream *gz;
Stream *tar;
Stream *output;
size_t gz_size;
size_t tar_size;
size_t output_size;
};
TarGzIO tarGzIO;
static fs::File untarredFile;
static fs::FS *tarFS = nullptr;
TAR::entry_callbacks_t tarCallbacks;
void* (*tgz_malloc)(size_t size) = nullptr;
void* (*tgz_calloc)(size_t n, size_t size) = nullptr;
void* (*tgz_realloc)(void *ptr, size_t size) = nullptr;
bool tgz_use_psram = false;
void (*tgzLogger)( const char* format, ...) = nullptr;
static size_t (*fstotalBytes)() = nullptr;
static size_t (*fsfreeBytes)() = nullptr;
static void (*fsSetupSizeTools)( fsTotalBytesCb cbt, fsFreeBytesCb cbf ) = nullptr;
static void (*tarProgressCallback)( uint8_t progress ) = nullptr;
static void (*tarMessageCallback)( const char* format, ...) = nullptr;
static void (*gzMessageCallback)( const char* format, ...) = nullptr;
static void (*tarStatusProgressCallback)( const char* name, size_t size, size_t total_unpacked ) = nullptr;
static void (*gzProgressCallback)( uint8_t progress ) = nullptr;
static bool (*gzWriteCallback)( unsigned char* buff, size_t buffsize ) = nullptr;
static bool (*tarSkipThisEntryOut)( TAR::header_translated_t *proper ) = nullptr;
static bool (*tarSkipThisEntryIn)( TAR::header_translated_t *proper ) = nullptr;
static bool tarSkipThisEntry = false;
static const char* tarDestFolder = nullptr;
static unsigned char __attribute__((aligned(4))) *output_buffer = nullptr; // gz write buffer
static unsigned char *uzlib_gzip_dict = nullptr; // gz dictionnary buffer
static struct GZ::TINF_DATA uzLibDecompressor; // uzlib object
static tarGzErrorCode _error = ESP32_TARGZ_OK;
static bool targz_halt_on_error = false;
static bool firstblock = true; // for gzProcessTarBuffer
static bool lastblock = false; // for gzProcessTarBuffer
static size_t tarCurrentFileSize = 0;
static size_t tarCurrentFileSizeProgress = 0;
static int32_t untarredBytesCount = 0;
static size_t totalFiles = 0;
static size_t totalFolders = 0;
static int64_t uzlib_bytesleft = 0;
static uint32_t output_position = 0; //position in output_buffer
static uint16_t blockmod = GZIP_BUFF_SIZE / TAR_BLOCK_SIZE;
static uint16_t gzTarBlockPos = 0;
static size_t tarReadGzStreamBytes = 0;
static bool tarBlockIsUpdateData = false;
size_t min_output_buffer_size = 512;
#if defined ESP32
static bool unTarDoHealthChecks = true; // set to false for faster writes
#endif
#if defined ESP8266
static bool unTarDoHealthChecks = false; // ESP8266 is unstable with health checks
#endif
static bool halt_on_error()
{
return targz_halt_on_error;
}
static void targz_system_halt()
{
log_e("System halted after error code #%d", _error); while(1) { yield(); }
}
static void setError( tarGzErrorCode code )
{
_error = code;
if( _error != ESP32_TARGZ_OK && halt_on_error() ) targz_system_halt();
}
BaseUnpacker::BaseUnpacker()
{
fstotalBytes = nullptr;
fsfreeBytes = nullptr;
fsSetupSizeTools = nullptr;
tarFS = nullptr;
tarDestFolder = nullptr;
output_buffer = nullptr;
_error = ESP32_TARGZ_OK;
tarCurrentFileSize = 0;
tarCurrentFileSizeProgress = 0;
untarredBytesCount = 0;
totalFiles = 0;
totalFolders = 0;
uzlib_gzip_dict = nullptr;
uzlib_bytesleft = 0;
output_position = 0; //position in output_buffer
blockmod = GZIP_BUFF_SIZE / TAR_BLOCK_SIZE;
gzTarBlockPos = 0;
tarReadGzStreamBytes = 0;
tgz_malloc = malloc;
tgz_calloc = calloc;
tgz_realloc = realloc;
tgz_use_psram = false;
}
#ifdef ESP32
bool BaseUnpacker::setPsram( bool enable )
{
if( enable ) {
if( psramInit() ) {
tgz_malloc = ps_malloc;
tgz_calloc = ps_calloc;
tgz_realloc = ps_realloc;
tgz_use_psram = true;
log_d("Enabled Psram for uzlib dictionary");
unTarDoHealthChecks = false;
return true;
}
} else {
tgz_malloc = malloc;
tgz_calloc = calloc;
tgz_realloc = realloc;
log_d("Disabled Psram for uzlib dictionary");
return true;
}
return false;
}
#endif
void BaseUnpacker::setGeneralError( tarGzErrorCode code )
{
setError( code );
}
void BaseUnpacker::haltOnError( bool halt )
{
targz_halt_on_error = halt;
}
int8_t BaseUnpacker::tarGzGetError()
{
return (int8_t)_error;
}
void BaseUnpacker::tarGzClearError()
{
_error = ESP32_TARGZ_OK;
}
bool BaseUnpacker::tarGzHasError()
{
return _error != ESP32_TARGZ_OK;
}
void BaseUnpacker::defaultTarStatusProgressCallback( const char* name, size_t size, size_t total_unpacked )
{
Serial.printf("[TAR] %-64s %8d bytes - %8d Total bytes\n", name, size, total_unpacked );
}
// unpack sourceFS://fileName.tar contents to destFS::/destFolder/
void BaseUnpacker::defaultProgressCallback( uint8_t progress )
{
static int8_t uzLibLastProgress = -1;
if( uzLibLastProgress != progress ) {
if( uzLibLastProgress == -1 ) {
Serial.print("Progress: 0% ▓");
}
uzLibLastProgress = progress;
switch( progress ) {
//case 0: Serial.print("0% ▓"); break;
case 25: Serial.print(" 25% ");break;
case 50: Serial.print(" 50% ");break;
case 75: Serial.print(" 75% ");break;
case 100: Serial.print("▓ 100%\n"); uzLibLastProgress = -1; break;
default: if( progress > 0 && progress < 100) Serial.print( "▓" ); break;
}
}
}
// progress callback for TAR, leave empty for less console output
void BaseUnpacker::tarNullProgressCallback( CC_UNUSED uint8_t progress )
{
// print( message );
}
// progress callback for GZ, leave empty for less console output
void BaseUnpacker::targzNullProgressCallback( CC_UNUSED uint8_t progress )
{
// printf("Progress: %d", progress );
}
// error/warning/info NULL logger, for less console output
void BaseUnpacker::targzNullLoggerCallback( CC_UNUSED const char* format, ...)
{
//va_list args;
//va_start(args, format);
//vprintf(format, args);
//va_end(args);
}
// error/warning/info FULL logger, for more console output
void BaseUnpacker::targzPrintLoggerCallback(const char* format, ...)
{
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
// set totalBytes() function callback
void BaseUnpacker::setFsTotalBytesCb( fsTotalBytesCb cb )
{
log_d("Assigning setFsTotalBytesCb callback : 0x%8x", (uint)cb );
fstotalBytes = cb;
}
// set freelBytes() function callback
void BaseUnpacker::setFsFreeBytesCb( fsFreeBytesCb cb )
{
log_d("Assigning setFsFreeBytesCb callback : 0x%8x", (uint)cb );
fsfreeBytes = cb;
}
// set logger callback
void BaseUnpacker::setLoggerCallback( genericLoggerCallback cb )
{
log_d("Assigning debug logger callback : 0x%8x", (uint)cb );
tgzLogger = cb;
}
// private (enables)
void BaseUnpacker::initFSCallbacks()
{
if( fsSetupSizeTools && fstotalBytes && fsfreeBytes ) {
log_d("Setting up fs size tools");
fsSetupSizeTools( fstotalBytes, fsfreeBytes );
} else {
log_d("Skipping fs size tools setup");
}
}
// public (assigns)
void BaseUnpacker::setupFSCallbacks( fsTotalBytesCb cbt, fsFreeBytesCb cbf )
{
setFsTotalBytesCb( cbt );
setFsFreeBytesCb( cbf );
if( fsSetupSizeTools != NULL ) {
log_d("deleting fsSetupSizeTools");
fsSetupSizeTools = NULL;
}
log_d("Assigning lambda to fsSetupSizeTools");
fsSetupSizeTools = []( fsTotalBytesCb cbt, fsFreeBytesCb cbf ) {
log_d("Calling fsSetupSizeTools lambda");
setFsTotalBytesCb( cbt );
setFsFreeBytesCb( cbf );
};
}
// generate hex view in the console, one call per line
void BaseUnpacker::hexDumpData( const char* buff, size_t buffsize, uint32_t output_size )
{
static size_t totalBytes = 0;
String bytesStr = "";
String binaryStr = "";
char byteToStr[32];
for( size_t i=0; i<buffsize; i++ ) {
sprintf( byteToStr, "%02X", buff[i] );
bytesStr += String( byteToStr ) + String(" ");
if( isprint( buff[i] ) ) {
binaryStr += String( buff[i] );
} else {
binaryStr += ".";
}
}
sprintf( byteToStr, "[0x%04X - 0x%04X] ", totalBytes, totalBytes+buffsize);
totalBytes += buffsize;
if( buffsize < output_size ) {
for( size_t i=0; i<output_size-buffsize; i++ ) {
bytesStr += "-- ";
binaryStr += ".";
}
}
Serial.println( byteToStr + bytesStr + " " + binaryStr );
}
// show the contents of a given file as a hex dump
void BaseUnpacker::hexDumpFile( fs::FS &fs, const char* filename, uint32_t output_size )
{
File binFile = fs.open( filename, FILE_READ );
//log_w("File size : %d", binFile.size() );
// only dump small files
if( binFile.size() > 0 ) {
//size_t output_size = 32;
Serial.printf("Showing file %s (%d bytes) md5: %s\n", filename, binFile.size(), MD5Sum::fromFile( binFile ) );
binFile.seek(0);
char* buff = new char[output_size];
uint8_t bytes_read = binFile.readBytes( buff, output_size );
while( bytes_read > 0 ) {
hexDumpData( buff, bytes_read, output_size );
bytes_read = binFile.readBytes( buff, output_size );
}
} else {
Serial.printf("Ignoring file %s (%d bytes)", filename, binFile.size() );
}
binFile.close();
}
// get a directory listing of a given filesystem
#if defined ESP32
void BaseUnpacker::tarGzListDir( fs::FS &fs, const char * dirName, uint8_t levels, bool hexDump )
{
File root = fs.open( dirName, FILE_READ );
if( !root ) {
log_e("[ERROR] in tarGzListDir: Can't open %s dir", dirName );
if( halt_on_error() ) targz_system_halt();
return;
}
if( !root.isDirectory() ) {
log_e("[ERROR] in tarGzListDir: %s is not a directory", dirName );
if( halt_on_error() ) targz_system_halt();
return;
}
File file = root.openNextFile();
while( file ) {
if( file.isDirectory() ) {
Serial.printf( "[DIR] %s\n", file.name() );
if( levels && levels > 0 ) {
tarGzListDir( fs, file.name(), levels -1, hexDump );
}
} else {
Serial.printf( "[FILE] %-32s %8d bytes - md5:%s\n", file.name(), file.size(), MD5Sum::fromFile( file ) );
if( hexDump ) {
hexDumpFile( fs, file.name() );
}
}
file = root.openNextFile();
}
}
#elif defined ESP8266
void BaseUnpacker::printDirectory(fs::FS &fs, File dir, int numTabs, uint8_t levels, bool hexDump)
{
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print(" ");
}
if (entry.isDirectory()) {
if( levels > 0 ) {
Serial.printf( "[DIR] %s\n", entry.name() );
printDirectory(fs, entry, numTabs + 1, levels-1, hexDump );
}
} else {
if( entry.size() > 0 ) {
Serial.printf( "[FILE] %-32s %8d bytes - md5:%s\n", entry.name(), entry.size(), MD5Sum::fromFile( entry ) );
} else {
Serial.printf( "[????] %-32s \n", entry.name() );
}
if( hexDump ) {
hexDumpFile( fs, entry.name() );
}
}
entry.close();
}
}
void BaseUnpacker::tarGzListDir(fs::FS &fs, const char * dirname, uint8_t levels, bool hexDump)
{
//void( hexDump ); // not used (yet?) with ESP82
Serial.printf("Listing directory %s with level %d\n", dirname, levels);
File root = fs.open(dirname, "r");
if( !root.isDirectory() ){
log_e( "%s is not a directory", dirname );
return;
}
printDirectory(fs, root, 0, levels, hexDump );
return;
}
#endif // defined( ESP8266 )
TarUnpacker::TarUnpacker()
{
#if __has_include(<PSRamFS.h>)
log_w("Implicitely disabling health checks on PSRamFS");
unTarDoHealthChecks = false; // disable that with psramFS
#endif
}
void TarUnpacker::setTarStatusProgressCallback( tarStatusProgressCb cb )
{
tarStatusProgressCallback = cb;
}
// set progress callback for TAR
void TarUnpacker::setTarProgressCallback( genericProgressCallback cb )
{
log_d("Assigning tar progress callback : 0x%8x", (uint)cb );
tarProgressCallback = cb;
}
// set tar unpacker message callback
void TarUnpacker::setTarMessageCallback( genericLoggerCallback cb )
{
log_d("Assigning tar message callback : 0x%8x", (uint)cb );
tarMessageCallback = cb;
}
// exclude / include based on tar header properties (filename, size, type)
void TarUnpacker::setTarExcludeFilter( tarExcludeFilter cb )
{
log_d("Assigning tar filename exclude filter callback : 0x%8x", (uint)cb );
tarSkipThisEntryOut = cb;
}
void TarUnpacker::setTarIncludeFilter( tarIncludeFilter cb )
{
log_d("Assigning tar filename include filter callback : 0x%8x", (uint)cb );
tarSkipThisEntryIn = cb;
}
// safer but slower
void TarUnpacker::setTarVerify( bool verify )
{
log_d("Setting tar verify : %s", verify ? "true" : "false" );
#if __has_include(<PSRamFS.h>)
log_w("Implicitely ignoring health checks on PSRamFS");
unTarDoHealthChecks = false; // disable that with psramFS
#else
unTarDoHealthChecks = verify;
#endif
}
int TarUnpacker::tarHeaderCallBack( TAR::header_translated_t *proper, CC_UNUSED int entry_index, CC_UNUSED void *context_data )
{
dump_header(proper);
static size_t totalsize = 0;
tarSkipThisEntry = false;
if( tarSkipThisEntryOut ) {
if( tarSkipThisEntryOut( proper ) ) {
tgzLogger("[TAR] Skipping: %s (filter 'Out' matches)\n", proper->filename );
tarSkipThisEntry = true;
}
}
if( tarSkipThisEntryIn ) {
if( !tarSkipThisEntryIn( proper ) ) {
tgzLogger("[TAR] Skipping: %s (filter 'In' does not match)\n", proper->filename );
tarSkipThisEntry = true;
}
}
// https://github.com/tobozo/ESP32-targz/issues/33
if( proper->type == TAR::T_NORMAL || proper->type == TAR::T_EXTENDED ) {
if( fstotalBytes && fsfreeBytes ) {
size_t freeBytes = fsfreeBytes();
if( freeBytes < proper->filesize ) {
// Abort before the partition is smashed!
log_e("[TAR ERROR] Not enough space left on device (%llu bytes required / %d bytes available)!", proper->filesize, freeBytes );
return ESP32_TARGZ_FS_FULL_ERROR;
}
} else {
#if defined WARN_LIMITED_FS
log_w("[TAR WARNING] Can't check target medium for free space (required:%llu, free:\?\?), will try to expand anyway", proper->filesize );
#endif
}
if( !tarSkipThisEntry ) {
char file_path[256] = {0};
memset( file_path, 0, 256 );
// avoid double slashing root path
if( strcmp( tarDestFolder, FOLDER_SEPARATOR ) != 0 ) {
strcat(file_path, tarDestFolder);
}
// only append slash if destination folder does not end with a slash
if( file_path[strlen(file_path)-1] != FOLDER_SEPARATOR[0] ) {
strcat(file_path, FOLDER_SEPARATOR);
}
strcat(file_path, proper->filename);
if( tarFS->exists( file_path ) ) {
// file will be truncated
/*
untarredFile = tarFS->open( file_path, FILE_READ );
bool isdir = untarredFile.isDirectory();
untarredFile.close();
if( isdir ) {
log_d("[TAR DEBUG] Keeping %s folder", file_path);
} else {
log_d("[TAR DEBUG] Deleting %s as it is in the way", file_path);
tarFS->remove( file_path );
}
*/
} else {
// create directory (recursively if necessary)
mkdirp( tarFS, file_path );
}
//TODO: limit this check to SPIFFS/LittleFS only
if( strlen( file_path ) > 32 ) {
// WARNING: SPIFFS LIMIT
#if defined WARN_LIMITED_FS
log_w("[TAR WARNING] file path is longer than 32 chars (SPIFFS limit) and may fail: %s", file_path);
setError( ESP32_TARGZ_TAR_ERR_FILENAME_TOOLONG ); // don't break untar for that
#endif
} else {
log_d("[TAR] Creating %s", file_path);
}
untarredFile = tarFS->open(file_path, FILE_WRITE);
if(!untarredFile) {
log_e("[ERROR] in tarHeaderCallBack: Could not open [%s] for write.", file_path);
setError( ESP32_TARGZ_FS_ERROR );
return ESP32_TARGZ_FS_ERROR;
}
tarGzIO.output = &untarredFile;
} else {
log_v("[TAR FILTER] Skipped file/folder creation for: %s.", proper->filename);
}
tarCurrentFileSize = proper->filesize; // for progress
tarCurrentFileSizeProgress = 0; // for progress
totalsize += proper->filesize;
if( tarStatusProgressCallback && !tarSkipThisEntry ) {
tarStatusProgressCallback( proper->filename, proper->filesize, totalsize );
}
if( totalsize == proper->filesize && !tarSkipThisEntry )
tarProgressCallback( 0 );
} else {
switch( proper->type ) {
case TAR::T_HARDLINK: log_d("Ignoring hard link to %s.", proper->filename); break;
case TAR::T_SYMBOLIC: log_d("Ignoring sym link to %s.", proper->filename); break;
case TAR::T_CHARSPECIAL: log_d("Ignoring special char."); break;
case TAR::T_BLOCKSPECIAL: log_d("Ignoring special block."); break;
case TAR::T_DIRECTORY: log_d("Entering %s directory.", proper->filename);
//tarMessageCallback( "Entering %s directory\n", proper->filename );
if( tarStatusProgressCallback && !tarSkipThisEntry ) {
tarStatusProgressCallback( proper->filename, 0, totalsize );
}
totalFolders++;
break;
case TAR::T_FIFO: log_d("Ignoring FIFO request."); break;
case TAR::T_CONTIGUOUS: log_d("Ignoring contiguous data to %s.", proper->filename); break;
case TAR::T_GLOBALEXTENDED: log_d("Ignoring global extended data."); break;
//case TAR::T_EXTENDED: log_d("Ignoring extended data."); break;
case TAR::T_OTHER: default: log_d("Ignoring unrelevant data."); break;
}
}
return ESP32_TARGZ_OK;
}
int TarUnpacker::tarEndCallBack( TAR::header_translated_t *proper, CC_UNUSED int entry_index, CC_UNUSED void *context_data)
{
int ret = ESP32_TARGZ_OK;
if( untarredFile ) {
char tmp_path[256] = {0};
if( unTarDoHealthChecks ) {
memset( tmp_path, 0, 256 );
snprintf( tmp_path, 256, "%s", untarredFile.name() );
size_t pos = untarredFile.position();
untarredFile.close();
// health check 1: file existence
if( !tarFS->exists( tmp_path ) ) {
log_e("[TAR ERROR] File %s was not created although it was properly decoded, path is too long ?", tmp_path );
return ESP32_TARGZ_FS_WRITE_ERROR;
}
// health check 2: compare stream buffer position with speculated file size
if( pos != proper->filesize ) {
log_e("[TAR ERROR] File size and data size do not match (%d vs %d)!", (int)pos, (int)proper->filesize);
return ESP32_TARGZ_FS_WRITE_ERROR;
}
// health check 3: reopen file to check size on filesystem
untarredFile = tarFS->open(tmp_path, FILE_READ);
size_t tmpsize = untarredFile.size();
if( !untarredFile ) {
log_e("[TAR ERROR] Failed to re-open %s for size reading", tmp_path);
return ESP32_TARGZ_FS_READSIZE_ERROR;
}
// health check 4: see if everyone (buffer, stream, filesystem) agree
if( tmpsize == 0 || proper->filesize != tmpsize || pos != tmpsize ) {
log_e("[TAR ERROR] Byte sizes differ between written file %s (%d), tar headers (%d) and/or stream buffer (%d) !!", tmp_path, (int)tmpsize, (int)proper->filesize, (int)pos );
untarredFile.close();
return ESP32_TARGZ_FS_ERROR;
}
log_d("Expanded %s (%d bytes)", tmp_path, (int)tmpsize );
}
untarredFile.close();
static size_t totalsize = 0;
if( proper->type != TAR::T_DIRECTORY ) {
totalsize += proper->filesize;
}
tarProgressCallback( 100 );
log_d("Total expanded bytes: %d, heap free: %d", (int)totalsize, ESP.getFreeHeap() );
tarMessageCallback( "%s", proper->filename );
} else {
if( tarSkipThisEntry ) {
log_v("[TAR FILTER] Skipped file close for: %s.", proper->filename);
} else {
log_v("[TAR INFO] tarEndCallBack: nofile for `%s`", proper->filename );
}
}
totalFiles++;
return ret;
}
int TarUnpacker::tarHeaderUpdateCallBack(TAR::header_translated_t *proper, int entry_index, void *context_data)
{
dump_header(proper);
static size_t totalsize = 0;
// https://github.com/tobozo/ESP32-targz/issues/33
if( proper->type == TAR::T_NORMAL || proper->type == TAR::T_EXTENDED ) {
int partition = -1;
if( String( proper->filename ).endsWith("ino.bin") ) {
// partition = app
partition = U_FLASH;
} else if( String( proper->filename ).endsWith("spiffs.bin")
|| String( proper->filename ).endsWith("mklittlefs.bin") ) {
partition = U_PART;
} else {
// not relevant to Update
return ESP32_TARGZ_OK;
}
// check that proper->filesize is smaller than partition available size
if( !Update.begin( proper->filesize/*UPDATE_SIZE_UNKNOWN*/, partition ) ) {
setError( (tarGzErrorCode)(Update.getError()-20) ); // "-20" offset is Update error id to esp32-targz error id
return (Update.getError()-20);
}
tarCurrentFileSize = proper->filesize; // for progress
tarCurrentFileSizeProgress = 0; // for progress
tarBlockIsUpdateData = true;
totalsize += proper->filesize;
if( tarStatusProgressCallback ) {
tarStatusProgressCallback( proper->filename, proper->filesize, totalsize );
}
if( totalsize == proper->filesize )
tarProgressCallback( 0 );
}/* else {
switch( proper->type ) {
case TAR::T_HARDLINK: log_d("Ignoring hard link to %s.", proper->filename); break;
case TAR::T_SYMBOLIC: log_d("Ignoring sym link to %s.", proper->filename); break;
case TAR::T_CHARSPECIAL: log_d("Ignoring special char."); break;
case TAR::T_BLOCKSPECIAL: log_d("Ignoring special block."); break;
case TAR::T_DIRECTORY: log_d("Entering %s directory.", proper->filename);
//tarMessageCallback( "Entering %s directory\n", proper->filename );
if( tarStatusProgressCallback ) {
tarStatusProgressCallback( proper->filename, 0, totalsize );
}
totalFolders++;
break;
case TAR::T_FIFO: log_d("Ignoring FIFO request."); break;
case TAR::T_CONTIGUOUS: log_d("Ignoring contiguous data to %s.", proper->filename); break;
case TAR::T_GLOBALEXTENDED: log_d("Ignoring global extended data."); break;
case TAR::T_EXTENDED: log_d("Ignoring extended data."); break;
case TAR::T_OTHER: default: log_d("Ignoring unrelevant data."); break;
}
}*/
return ESP32_TARGZ_OK;
}
int TarUnpacker::tarEndUpdateCallBack( TAR::header_translated_t *proper, int entry_index, void *context_data)
{
int ret = ESP32_TARGZ_OK;
if ( !Update.end( true ) ) {
Update.printError(Serial);
log_e( "Update Error Occurred. Error #: %u", Update.getError() );
setError( (tarGzErrorCode)(Update.getError()-20) ); // "-20" offset is Update error id to esp32-targz error id
return (Update.getError()-20);
}
if ( !Update.isFinished() ) {
log_e("Update incomplete");
setError( ESP32_TARGZ_UPDATE_INCOMPLETE );
return ESP32_TARGZ_UPDATE_INCOMPLETE;
}
log_d("Update finished !");
Update.end();
tarBlockIsUpdateData = false;
tarProgressCallback( 100 );
//log_d("Total expanded bytes: %d, heap free: %d", (int)totalsize, ESP.getFreeHeap() );
tarMessageCallback( "%s", proper->filename );
totalFiles++;
return ret;
}
int TarUnpacker::tarStreamWriteUpdateCallback(TAR::header_translated_t *proper, int entry_index, void *context_data, unsigned char *block, int length)
{
if( tarBlockIsUpdateData ) {
int wlen = Update.write( block, length );
if( wlen != length ) {
//tgzLogger("\n");
log_e("[TAR ERROR] Written length differs from buffer length (unpacked bytes:%d, expected: %d, returned: %d)!\n", untarredBytesCount, length, wlen );
return ESP32_TARGZ_FS_ERROR;
}
untarredBytesCount+=wlen;
// file unpack progress
log_v("[TAR INFO] tarStreamWriteCallback wrote %d bytes to %s", length, proper->filename );
tarCurrentFileSizeProgress += wlen;
if( tarCurrentFileSize > 0 ) {
// this is a per-file progress, not an overall progress !
int32_t progress = (100*tarCurrentFileSizeProgress) / tarCurrentFileSize;
if( progress != 100 && progress != 0 ) {
tarProgressCallback( progress );
}
}
}
return ESP32_TARGZ_OK;
}
// tinyUntarReadCallback
int TarUnpacker::tarStreamReadCallback( unsigned char* buff, size_t buffsize )
{
return tarGzIO.tar->readBytes( buff, buffsize );
}
int TarUnpacker::tarStreamWriteCallback(TAR::header_translated_t *proper, int entry_index, void *context_data, unsigned char *block, int length)
{
if( tarSkipThisEntry ) {
log_v("[TAR FILTER] Skipping data bits from: %s.", proper->filename);
untarredBytesCount += length;
tarCurrentFileSizeProgress += length;
return ESP32_TARGZ_OK;
}
if( tarGzIO.output ) {
int wlen = tarGzIO.output->write( block, length );
if( wlen != length ) {
//tgzLogger("\n");
log_e("[TAR ERROR] Written length differs from buffer length (unpacked bytes:%d, expected: %d, returned: %d)!\n", untarredBytesCount, length, wlen );
return ESP32_TARGZ_FS_ERROR;
}
untarredBytesCount+=wlen;
// file unpack progress
log_v("[TAR INFO] tarStreamWriteCallback wrote %d bytes to %s", length, proper->filename );
tarCurrentFileSizeProgress += wlen;
if( tarCurrentFileSize > 0 ) {
// this is a per-file progress, not an overall progress !
int32_t progress = (100*tarCurrentFileSizeProgress) / tarCurrentFileSize;
if( progress != 100 && progress != 0 ) {
tarProgressCallback( progress );
}
}
}
return ESP32_TARGZ_OK;
}
// unpack sourceFS://fileName.tar contents to destFS::/destFolder/
bool TarUnpacker::tarExpander( fs::FS &sourceFS, const char* fileName, fs::FS &destFS, const char* destFolder )
{
tarGzClearError();
initFSCallbacks();
tarFS = &destFS;
tarDestFolder = destFolder;
if (!tgzLogger ) {
setLoggerCallback( targzPrintLoggerCallback );
}
if( !tarProgressCallback ) {
setTarProgressCallback( tarNullProgressCallback );
}
if( !tarMessageCallback ) {
setTarMessageCallback( targzNullLoggerCallback );
}
if( !sourceFS.exists( fileName ) ) {
log_e("Error: file %s does not exist or is not reachable", fileName);
setError( ESP32_TARGZ_FS_ERROR );
return false;
}
if( !destFS.exists( tarDestFolder ) ) {
destFS.mkdir( tarDestFolder );
}
tgzLogger("[TAR] Expanding %s to folder %s\n", fileName, destFolder );
untarredBytesCount = 0;
tarCallbacks = {
tarHeaderCallBack,
tarStreamReadCallback,
tarStreamWriteCallback,
tarEndCallBack
};
fs::File tarFile = sourceFS.open( fileName, FILE_READ );
tarGzIO.tar_size = tarFile.size();
tarGzIO.tar = &tarFile;
//tinyUntarReadCallback = &tarStreamReadCallback;
TAR::tar_error_logger = tgzLogger;
TAR::tar_debug_logger = tgzLogger; // comment this out if too verbose
totalFiles = 0;
totalFolders = 0;
//tarProgressCallback( 0 );
int res = TAR::read_tar( &tarCallbacks, NULL );
if( res != TAR_OK ) {
log_e("[ERROR] operation aborted while expanding tar file %s (return code #%d", fileName, res-30);
setError( (tarGzErrorCode)(res-30) );
return false;
}
//tarProgressCallback( 100 );
return true;
}
GzUnpacker::GzUnpacker()
{
}
// set progress callback for GZ
void GzUnpacker::setGzProgressCallback( genericProgressCallback cb )
{
log_d("Assigning GZ progress callback : 0x%8x", (uint)cb );
gzProgressCallback = cb;
}
// set logger callback
void GzUnpacker::setGzMessageCallback( genericLoggerCallback cb )
{
log_d("Assigning debug logger callback : 0x%8x", (uint)cb );
gzMessageCallback = cb;
}
void GzUnpacker::setStreamWriter( gzStreamWriter cb )
{
gzWriteCallback = cb;
}
void GzUnpacker::gzExpanderCleanup()
{
if( uzlib_gzip_dict != nullptr ) {
if( tgz_use_psram ) {
free( uzlib_gzip_dict );
} else {
delete( uzlib_gzip_dict );