-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzsfx.cpp
2580 lines (2289 loc) · 76.1 KB
/
zsfx.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
/*
zsfx
Windows 32/64 self extracting for ZPAQ archives,
with multithread support and everything, just like zpaq 7.15
Embedded in zpaqfranz for Windows
Written by Franco Corbelli
https://github.com/fcorbelli
Lots of improvements to do
Targets
Windows 64 (g++ 7.3.0)
g++ -O3 zsfx.cpp libzpaq.cpp -o zsfx -static
(more aggressive) 10.3.0 beware of -flto
g++ -Os zsfx.cpp libzpaq.cpp -o zsfx -static -fno-rtti -Wl,--gc-sections -fdata-sections -flto
Windows 32 (g++ 7.3.0)
c:\mingw32\bin\g++ -m32 -O3 zsfx.cpp libzpaq.cpp -o zsfx32 -pthread -static
(more aggressive) 10.3.0 -flto
c:\mingw32\bin\g++ -m32 -Os zsfx.cpp libzpaq.cpp -o zsfx32 -pthread -static -fno-rtti -Wl,--gc-sections -flto
*/
#define ZSFX_VERSION "55.1"
#define _FILE_OFFSET_BITS 64 // In Linux make sizeof(off_t) == 8
#define UNICODE // For Windows
#include "libzpaq.h"
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <string>
#include <vector>
#include <map>
#include <windows.h>
#include <io.h>
#include <conio.h>
using std::string;
using std::vector;
using std::map;
using libzpaq::StringBuffer;
// Global variables
string g_franzo_start;
string g_franzo_end;
int64_t g_global_start=0; // set to mtime() at start of main()
int64_t g_startzpaq=0; // where the data begin
#define DEBUGX // define to see a lot of things
string extractfilename(const string& i_string)
{
size_t i = i_string.rfind('/', i_string.length());
if (i != string::npos)
return(i_string.substr(i+1, i_string.length() - i));
return(i_string);
}
string extractfilepath(const string& i_string)
{
size_t i = i_string.rfind('/', i_string.length());
if (i != string::npos)
return(i_string.substr(0, i+1));
return("");
}
string prendinomefileebasta(const string& s)
{
string nomefile=extractfilename(s);
size_t i = nomefile.rfind('.', nomefile.length());
if (i != string::npos)
return(nomefile.substr(0,i));
return(nomefile);
}
inline char * migliaia(uint64_t n)
{
static char retbuf[30];
char *p = &retbuf[sizeof(retbuf)-1];
unsigned int i = 0;
*p = '\0';
do
{
if(i%3 == 0 && i != 0)
*--p = '.';
*--p = '0' + n % 10;
n /= 10;
i++;
} while(n != 0);
return p;
}
// Handle errors in libzpaq and elsewhere
void libzpaq::error(const char* msg)
{
if (strstr(msg, "ut of memory"))
throw std::bad_alloc();
printf("%s\n",msg);
exit(0);
}
using libzpaq::error;
typedef DWORD ThreadReturn;
typedef HANDLE ThreadID;
void run(ThreadID& tid, ThreadReturn(*f)(void*), void* arg)
{
tid=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)f, arg, 0, NULL);
if (tid==NULL)
error("CreateThread failed");
}
void join(ThreadID& tid)
{
WaitForSingleObject(tid, INFINITE);
}
typedef HANDLE Mutex;
void init_mutex(Mutex& m)
{
m=CreateMutex(NULL, FALSE, NULL);
}
void lock(Mutex& m)
{
WaitForSingleObject(m, INFINITE);
}
void release(Mutex& m)
{
ReleaseMutex(m);
}
void destroy_mutex(Mutex& m)
{
CloseHandle(m);
}
// In Windows, convert 16-bit wide string to UTF-8 and \ to /
string wtou(const wchar_t* s)
{
assert(sizeof(wchar_t)==2); // Not true in Linux
assert((wchar_t)(-1)==65535);
string r;
if (!s) return r;
for (; *s; ++s) {
if (*s=='\\') r+='/';
else if (*s<128) r+=*s;
else if (*s<2048) r+=192+*s/64, r+=128+*s%64;
else r+=224+*s/4096, r+=128+*s/64%64, r+=128+*s%64;
}
return r;
}
// In Windows, convert UTF-8 string to wide string ignoring
// invalid UTF-8 or >64K. Convert "/" to slash (default "\").
std::wstring utow(const char* ss, char slash='\\')
{
assert(sizeof(wchar_t)==2);
assert((wchar_t)(-1)==65535);
std::wstring r;
if (!ss) return r;
const unsigned char* s=(const unsigned char*)ss;
for (; s && *s; ++s) {
if (s[0]=='/') r+=slash;
else if (s[0]<128) r+=s[0];
else if (s[0]>=192 && s[0]<224 && s[1]>=128 && s[1]<192)
r+=(s[0]-192)*64+s[1]-128, ++s;
else if (s[0]>=224 && s[0]<240 && s[1]>=128 && s[1]<192
&& s[2]>=128 && s[2]<192)
r+=(s[0]-224)*4096+(s[1]-128)*64+s[2]-128, s+=2;
}
return r;
}
bool fileexists(const string& i_filename)
{
HANDLE myhandle;
WIN32_FIND_DATA findfiledata;
std::wstring wpattern=utow(i_filename.c_str());
myhandle=FindFirstFile(wpattern.c_str(),&findfiledata);
if (myhandle!=INVALID_HANDLE_VALUE)
{
FindClose(myhandle);
return true;
}
return false;
}
// Print a UTF-8 string to f (stdout, stderr) so it displays properly
void printUTF8(const char* s, FILE* f=stdout)
{
assert(f);
assert(s);
const HANDLE h=(HANDLE)_get_osfhandle(_fileno(f));
DWORD ft=GetFileType(h);
if (ft==FILE_TYPE_CHAR) {
fflush(f);
std::wstring w=utow(s, '/'); // Windows console: convert to UTF-16
DWORD n=0;
WriteConsole(h, w.c_str(), w.size(), &n, 0);
}
else // stdout redirected to file
fprintf(f, "%s", s);
}
// Return relative time in milliseconds
int64_t mtime()
{
int64_t t=GetTickCount();
if (t<g_global_start)
t+=0x100000000LL;
return t;
}
/////////////////////////////// File //////////////////////////////////
typedef HANDLE FP;
const FP FPNULL=INVALID_HANDLE_VALUE;
typedef enum {RB, WB, RBPLUS, WBPLUS} MODE; // fopen modes
// Open file. Only modes "rb", "wb", "rb+" and "wb+" are supported.
FP fopen(const char* filename, MODE mode) {
assert(filename);
DWORD access=0;
if (mode!=WB) access=GENERIC_READ;
if (mode!=RB) access|=GENERIC_WRITE;
DWORD disp=OPEN_ALWAYS; // wb or wb+
if (mode==RB || mode==RBPLUS) disp=OPEN_EXISTING;
DWORD share=FILE_SHARE_READ;
if (mode==RB) share|=FILE_SHARE_WRITE|FILE_SHARE_DELETE;
return CreateFile(utow(filename).c_str(), access, share,
NULL, disp, FILE_ATTRIBUTE_NORMAL, NULL);
}
// Close file
int fclose(FP fp)
{
return CloseHandle(fp) ? 0 : EOF;
}
// Read nobj objects of size size into ptr. Return number of objects read.
size_t fread(void* ptr, size_t size, size_t nobj, FP fp) {
DWORD r=0;
ReadFile(fp, ptr, size*nobj, &r, NULL);
if (size>1) r/=size;
return r;
}
// Write nobj objects of size size from ptr to fp. Return number written.
size_t fwrite(const void* ptr, size_t size, size_t nobj, FP fp) {
DWORD r=0;
WriteFile(fp, ptr, size*nobj, &r, NULL);
if (size>1) r/=size;
return r;
}
// Move file pointer by offset. origin is SEEK_SET (from start), SEEK_CUR,
// (from current position), or SEEK_END (from end).
int fseeko(FP fp, int64_t offset, int origin) {
if (origin==SEEK_SET) origin=FILE_BEGIN;
else if (origin==SEEK_CUR) origin=FILE_CURRENT;
else if (origin==SEEK_END) origin=FILE_END;
LONG h=uint64_t(offset)>>32;
SetFilePointer(fp, offset&0xffffffffull, &h, origin);
return GetLastError()!=NO_ERROR;
}
// Get file position
int64_t ftello(FP fp) {
LONG h=0;
DWORD r=SetFilePointer(fp, 0, &h, FILE_CURRENT);
return r+(uint64_t(h)<<32);
}
// Return true if a file or directory (UTF-8 without trailing /) exists.
bool exists(string filename)
{
int len=filename.size();
if (len<1) return false;
if (filename[len-1]=='/') filename=filename.substr(0, len-1);
return GetFileAttributes(utow(filename.c_str()).c_str())
!=INVALID_FILE_ATTRIBUTES;
}
// Print last error message
void printerr(const char* filename)
{
fflush(stdout);
int err=GetLastError();
printUTF8(filename, stderr);
if (err==ERROR_FILE_NOT_FOUND)
fprintf(stderr, ": file not found\n");
else if (err==ERROR_PATH_NOT_FOUND)
fprintf(stderr, ": path not found\n");
else if (err==ERROR_ACCESS_DENIED)
fprintf(stderr, ": access denied\n");
else if (err==ERROR_SHARING_VIOLATION)
fprintf(stderr, ": sharing violation\n");
else if (err==ERROR_BAD_PATHNAME)
fprintf(stderr, ": bad pathname\n");
else if (err==ERROR_INVALID_NAME)
fprintf(stderr, ": invalid name\n");
else if (err==ERROR_NETNAME_DELETED)
fprintf(stderr, ": network name no longer available\n");
else
fprintf(stderr, ": Windows error %d\n", err);
}
// Close fp if open. Set date and attributes unless 0
void close(const char* filename, int64_t date, int64_t attr, FP fp=FPNULL) {
assert(filename);
const bool ads=strstr(filename, ":$DATA")!=0; // alternate data stream?
if (date>0 && !ads) {
if (fp==FPNULL)
fp=CreateFile(utow(filename).c_str(),
FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (fp!=FPNULL) {
SYSTEMTIME st;
st.wYear=date/10000000000LL%10000;
st.wMonth=date/100000000%100;
st.wDayOfWeek=0; // ignored
st.wDay=date/1000000%100;
st.wHour=date/10000%100;
st.wMinute=date/100%100;
st.wSecond=date%100;
st.wMilliseconds=0;
FILETIME ft;
SystemTimeToFileTime(&st, &ft);
SetFileTime(fp, NULL, NULL, &ft);
}
}
if (fp!=FPNULL) CloseHandle(fp);
if ((attr&255)=='w' && !ads)
SetFileAttributes(utow(filename).c_str(), attr>>8);
}
// Print file open error and throw exception
void ioerr(const char* msg)
{
printerr(msg);
exit(0);
}
// Create directories as needed. For example if path="/tmp/foo/bar"
// then create directories /, /tmp, and /tmp/foo unless they exist.
// Set date and attributes if not 0.
void makepath(string path, int64_t date=0, int64_t attr=0) {
for (unsigned i=0; i<path.size(); ++i) {
if (path[i]=='\\' || path[i]=='/') {
path[i]=0;
CreateDirectory(utow(path.c_str()).c_str(), 0);
path[i]='/';
}
}
// Set date and attributes
string filename=path;
if (filename!="" && filename[filename.size()-1]=='/')
filename=filename.substr(0, filename.size()-1); // remove trailing slash
close(filename.c_str(), date, attr);
}
/////////////////////////////// Archive ///////////////////////////////
// Convert non-negative decimal number x to string of at least n digits
string itos(int64_t x, int n=1) {
assert(x>=0);
assert(n>=0);
string r;
for (; x || n>0; x/=10, --n) r=string(1, '0'+x%10)+r;
return r;
}
// Replace * and ? in fn with part or digits of part
string subpart(string fn, int part) {
for (int j=fn.size()-1; j>=0; --j) {
if (fn[j]=='?')
fn[j]='0'+part%10, part/=10;
else if (fn[j]=='*')
fn=fn.substr(0, j)+itos(part)+fn.substr(j+1), part=0;
}
return fn;
}
// Base of InputArchive and OutputArchive
class ArchiveBase {
protected:
libzpaq::AES_CTR* aes; // NULL if not encrypted
FP fp; // currently open file or FPNULL
public:
ArchiveBase(): aes(0), fp(FPNULL) {}
~ArchiveBase() {
if (aes) delete aes;
if (fp!=FPNULL) fclose(fp);
}
bool isopen() {return fp!=FPNULL;}
};
// An InputArchive supports encrypted reading
class InputArchive: public ArchiveBase, public libzpaq::Reader {
vector<int64_t> sz; // part sizes
int64_t off; // current offset
string fn; // filename, possibly multi-part with wildcards
public:
// Open filename. If password then decrypt input.
InputArchive(const char* filename, const char* password=0);
// Read and return 1 byte or -1 (EOF)
int get() {
error("get() not implemented");
return -1;
}
// Read up to len bytes into obuf at current offset. Return 0..len bytes
// actually read. 0 indicates EOF.
int read(char* obuf, int len) {
int nr=fread(obuf, 1, len, fp);
if (nr==0) {
seek(0, SEEK_CUR);
nr=fread(obuf, 1, len, fp);
}
if (nr==0) return 0;
if (aes) aes->encrypt(obuf, nr, off);
off+=nr;
return nr;
}
// Like fseeko()
void seek(int64_t p, int whence);
// Like ftello()
int64_t tell() {
return off;
}
#if defined(DEBUG)
int64_t tello()
{
return ftello(fp);
}
#endif
};
// Like fseeko. If p is out of range then close file.
void InputArchive::seek(int64_t p, int whence) {
if (!isopen()) return;
// Compute new offset
if (whence==SEEK_SET) off=p;
else if (whence==SEEK_CUR) off+=p;
else if (whence==SEEK_END) {
off=p;
for (unsigned i=0; i<sz.size(); ++i) off+=sz[i];
}
// Optimization for single file to avoid close and reopen
if (sz.size()==1)
{
fseeko(fp, off+g_startzpaq, SEEK_SET);
return;
}
// Seek across multiple files
assert(sz.size()>1);
int64_t sum=0;
unsigned i;
for (i=0;; ++i) {
sum+=sz[i];
if (sum>off || i+1>=sz.size()) break;
}
const string next=subpart(fn, i+1);
fclose(fp);
fp=fopen(next.c_str(), RB);
if (fp==FPNULL) ioerr(next.c_str());
fseeko(fp, off-sum+g_startzpaq, SEEK_END);
}
// Open for input. Decrypt with password and using the salt in the
// first 32 bytes. If filename has wildcards then assume multi-part
// and read their concatenation.
InputArchive::InputArchive(const char* filename, const char* password):
off(0), fn(filename) {
assert(filename);
// Get file sizes
const string part0=subpart(filename, 0);
for (unsigned i=1; ; ++i) {
const string parti=subpart(filename, i);
if (i>1 && parti==part0) break;
fp=fopen(parti.c_str(), RB);
if (fp==FPNULL) break;
fseeko(fp, 0, SEEK_END);
sz.push_back(ftello(fp));
fclose(fp);
}
// Open first part
const string part1=subpart(filename, 1);
fp=fopen(part1.c_str(), RB);
if (!isopen()) ioerr(part1.c_str());
assert(fp!=FPNULL);
seek(0,SEEK_SET); /// go to right position
// Get encryption salt
if (password)
{
#if defined(DEBUG)
printf("Prendo il sale\n");
printf("Z1 tello %ld\n",ftello(fp));
#endif
char salt[32], key[32];
if (fread(salt, 1, 32, fp)!=32) error("cannot read salt");
#if defined(DEBUG)
printf("Sale ");
for (int i=0;i<32;i++)
printf("%02X",(unsigned char)salt[i]);
printf("\n");
#endif
libzpaq::stretchKey(key, password, salt);
aes=new libzpaq::AES_CTR(key, 32, salt);
off=32;
#if defined(DEBUG)
printf("Off vale ora %d\n",off);
#endif
}
}
///////////////////////// System info /////////////////////////////////
// Guess number of cores. In 32 bit mode, max is 2.
int numberOfProcessors() {
int rc=0; // result
// In Windows return %NUMBER_OF_PROCESSORS%
const char* p=getenv("NUMBER_OF_PROCESSORS");
if (p) rc=atoi(p);
if (rc<1) rc=1;
if (sizeof(char*)==4 && rc>2) rc=2;
return rc;
}
////////////////////////////// misc ///////////////////////////////////
// For libzpaq output to a string less than 64K chars
struct StringWriter: public libzpaq::Writer {
string s;
void put(int c) {
if (s.size()>=65535) error("string too long");
s+=char(c);
}
};
// In Windows convert upper case to lower case.
inline int tolowerW(int c) {
if (c>='A' && c<='Z') return c-'A'+'a';
return c;
}
// Return true if strings a == b or a+"/" is a prefix of b
// or a ends in "/" and is a prefix of b.
// Match ? in a to any char in b.
// Match * in a to any string in b.
// In Windows, not case sensitive.
bool ispath(const char* a, const char* b) {
for (; *a; ++a, ++b) {
const int ca=tolowerW(*a);
const int cb=tolowerW(*b);
if (ca=='*') {
while (true) {
if (ispath(a+1, b)) return true;
if (!*b) return false;
++b;
}
}
else if (ca=='?') {
if (*b==0) return false;
}
else if (ca==cb && ca=='/' && a[1]==0)
return true;
else if (ca!=cb)
return false;
}
return *b==0 || *b=='/';
}
// Read 4 byte little-endian int and advance s
unsigned btoi(const char* &s) {
s+=4;
return (s[-4]&255)|((s[-3]&255)<<8)|((s[-2]&255)<<16)|((s[-1]&255)<<24);
}
// Read 8 byte little-endian int and advance s
int64_t btol(const char* &s) {
uint64_t r=btoi(s);
return r+(uint64_t(btoi(s))<<32);
}
/////////////////////////////// Jidac /////////////////////////////////
// A Jidac object represents an archive contents: a list of file
// fragments with hash, size, and archive offset, and a list of
// files with date, attributes, and list of fragment pointers.
// Methods add to, extract from, compare, and list the archive.
// enum for version
static const int64_t DEFAULT_VERSION=99999999999999LL; // unless -until
// fragment hash table entry
struct HT {
unsigned char sha1[20]; // fragment hash
int usize; // uncompressed size, -1 if unknown, -2 if not init
HT(const char* s=0, int u=-2) {
if (s) memcpy(sha1, s, 20);
else memset(sha1, 0, 20);
usize=u;
}
};
// filename entry
struct DT {
int64_t date; // decimal YYYYMMDDHHMMSS (UT) or 0 if deleted
int64_t size; // size or -1 if unknown
int64_t attr; // first 8 attribute bytes
int64_t data; // sort key or frags written. -1 = do not write
vector<unsigned> ptr; // fragment list
DT(): date(0), size(0), attr(0), data(0) {}
};
typedef map<string, DT> DTMap;
// list of blocks to extract
struct Block {
int64_t offset; // location in archive
int64_t usize; // uncompressed size, -1 if unknown (streaming)
int64_t bsize; // compressed size
vector<DTMap::iterator> files; // list of files pointing here
unsigned start; // index in ht of first fragment
unsigned size; // number of fragments to decompress
unsigned frags; // number of fragments in block
unsigned extracted; // number of fragments decompressed OK
enum {READY, WORKING, GOOD, BAD} state;
Block(unsigned s, int64_t o): offset(o), usize(-1), bsize(0), start(s),
size(0), frags(0), extracted(0), state(READY) {}
};
// Version info
struct VER {
int64_t date; // Date of C block, 0 if streaming
int64_t lastdate; // Latest date of any block
int64_t offset; // start of transaction C block
int64_t data_offset; // start of first D block
int64_t csize; // size of compressed data, -1 = no index
int updates; // file updates
int deletes; // file deletions
unsigned firstFragment;// first fragment ID
VER() {memset(this, 0, sizeof(*this));}
};
// Windows API functions not in Windows XP to be dynamically loaded
typedef HANDLE (WINAPI* FindFirstStreamW_t)
(LPCWSTR, STREAM_INFO_LEVELS, LPVOID, DWORD);
FindFirstStreamW_t findFirstStreamW=0;
typedef BOOL (WINAPI* FindNextStreamW_t)(HANDLE, LPVOID);
FindNextStreamW_t findNextStreamW=0;
/// we want the fullpath too!
string getmyname()
{
wchar_t buffer[MAX_PATH];
GetModuleFileName(NULL,buffer,MAX_PATH);
return (wtou(buffer));
}
// Do everything
class Jidac
{
public:
int doCommand(int argc, char** argv);
friend ThreadReturn decompressThread(void* arg);
friend ThreadReturn testThread(void* arg);
friend struct ExtractJob;
string archive; // archive name
private:
string exename;
string myname;
string myoutput;
// Command line arguments
char command; // command 'a', 'x', or 'l'
vector<string> files; // filename args
int all; // -all option
bool force; // -force option
char password_string[32]; // hash of -key argument
const char* password; // points to password_string or NULL
bool noattributes; // -noattributes option
vector<string> notfiles; // list of prefixes to exclude
string nottype; // -not =...
vector<string> onlyfiles; // list of prefixes to include
int summary; // summary option if > 0, detailed if -1
int threads; // default is number of cores
vector<string> tofiles; // -to option
int64_t date; // now as decimal YYYYMMDDHHMMSS (UT)
int64_t version; // version number or 14 digit date
// Archive state
int64_t dhsize; // total size of D blocks according to H blocks
int64_t dcsize; // total size of D blocks according to C blocks
vector<HT> ht; // list of fragments
DTMap dt; // set of files in archive
vector<Block> block; // list of data blocks to extract
vector<VER> ver; // version info
// Commands
int extract(); // extract, return 1 if error else 0
int sfx(string i_thecommands); // make a sfx
void usage(); // help
string findcommand(int64_t& o_offset);
void getpasswordifempty();
// Support functions
string rename(string name); // rename from -to
int64_t read_archive(const char* arc, int *errors=0); // read arc
bool isselected(const char* filename, bool rn=false);// files, -only, -not
bool equal(DTMap::const_iterator p, const char* filename);
};
/// no buffer overflow protection etc etc
string getline(string i_default)
{
size_t maxline = 255+1;
char* line = (char*)malloc(maxline); // sfx module, keep it small
char* p_line = line;
int c;
if (line==NULL)
error("744: allocating memory");
if (i_default!="")
printf("%s",i_default.c_str());
while((unsigned)(p_line-line)<maxline)
{
c = fgetc(stdin);
if(c==EOF)
break;
if((*p_line++ = c)=='\n')
break;
}
*--p_line = '\0';
return line;
}
// Print help message
void Jidac::usage()
{
printf("\nGitHub https://github.com/fcorbelli/zsfx\n\n");
printf("Usage 1: %s x nameofzpaqfile (...zpaq extraction switches) (-output mynewsfx.exe)\n",exename.c_str());
printf("Ex 1: %s x z:\\1.zpaq [z:\\1.exe will ask for -to from console] \n",exename.c_str());
printf("Ex 1: %s x z:\\1.zpaq -to .\\xtracted\\\n",exename.c_str());
printf("Ex 1: %s x z:\\1.zpaq -to y:\\testme\\ -output z:\\mynewsfx.exe",exename.c_str());
printf("\n\n");
printf("Usage 2: Autoextract .zpaq with the same name of the .exe (if any)\n");
printf("Ex 2: c:\\pluto\\testme.exe (a copy of %s.exe) will autoextract c:\\pluto\\testme.zpaq\n",exename.c_str());
printf("\nFilenames zsfx.exe/zsfx32.exe are reserved, do NOT rename\n");
printf("Switches -all -force -noattributes -not -only -to -summary -threads -until\n");
exit(1);
}
// return a/b such that there is exactly one "/" in between, and
// in Windows, any drive letter in b the : is removed and there
// is a "/" after.
string append_path(string a, string b) {
int na=a.size();
int nb=b.size();
if (nb>1 && b[1]==':') { // remove : from drive letter
if (nb>2 && b[2]!='/') b[1]='/';
else b=b[0]+b.substr(2), --nb;
}
if (nb>0 && b[0]=='/') b=b.substr(1);
if (na>0 && a[na-1]=='/') a=a.substr(0, na-1);
return a+"/"+b;
}
// Rename name using tofiles[]
string Jidac::rename(string name) {
if (files.size()==0 && tofiles.size()>0) // append prefix tofiles[0]
name=append_path(tofiles[0], name);
else { // replace prefix files[i] with tofiles[i]
const int n=name.size();
for (unsigned i=0; i<files.size() && i<tofiles.size(); ++i) {
const int fn=files[i].size();
if (fn<=n && files[i]==name.substr(0, fn))
return tofiles[i]+name.substr(fn);
}
}
return name;
}
void scambia(string& i_str)
{
int n=i_str.length();
for (int i=0;i<n/2;i++)
std::swap(i_str[i],i_str[n-i-1]);
}
bool myreplace(string& i_str, const string& i_from, const string& i_to)
{
size_t start_pos = i_str.find(i_from);
if(start_pos == std::string::npos)
return false;
i_str.replace(start_pos, i_from.length(), i_to);
return true;
}
string getpassword()
{
string myresult="";
printf("\nEnter password :");
char carattere;
while (1)
{
carattere=getch();
if(carattere=='\r')
break;
printf("*");
myresult+=carattere;
}
printf("\n");
return myresult;
}
FILE* freadopen(const char* i_filename)
{
std::wstring widename=utow(i_filename);
FILE* myfp=_wfopen(widename.c_str(), L"rb" );
if (myfp==NULL)
{
printf( "\nfreadopen cannot open:");
printUTF8(i_filename);
printf("\n");
return 0;
}
return myfp;
}
bool check_if_password(string i_filename)
{
FILE* inFile = freadopen(i_filename.c_str());
if (inFile==NULL)
{
int err=GetLastError();
printf("\n2057: ERR <%s> kind %d\n",i_filename.c_str(),err);
exit(0);
}
char s[4]={0};
if (g_startzpaq)
fseek(inFile,g_startzpaq,SEEK_SET);
const int nr=fread(s,1,4,inFile);
/// for (int i=0;i<4;i++)
/// printf("%d %c %d\n",i,s[i],s[i]);
fclose(inFile);
if (nr>0 && memcmp(s, "7kSt", 4) && (memcmp(s, "zPQ", 3) || s[3]<1))
return true;
return false;
}
void explode(string i_string,char i_delimiter,vector<string>& array)
{
///printf("1\n");
// printf("Delimiter %c\n",i_delimiter);
// printf("2\n");
//printf("String %s\n",i_string.c_str());
unsigned int i=0;
while(i<i_string.size())
{
string temp="";
/// printf("entro %02d %c %d\n",i,i_string[i],(int)(i_string[i]!=i_delimiter));
while ((i_string[i]!=i_delimiter) && (i<i_string.size()))
{
temp+=i_string[i];
i++;
}
array.push_back(temp);
i++;
if (i>=i_string.size())
break;
}
}
void Jidac::getpasswordifempty()
{
if (password==NULL)
if (check_if_password(archive))
{
printf("Archive seems encrypted (or corrupted)");
string spassword=getpassword();
if (spassword!="")
{
libzpaq::SHA256 sha256;
for (unsigned int i=0;i<spassword.size();i++)
sha256.put(spassword[i]);
memcpy(password_string, sha256.result(), 32);
password=password_string;
}
}
}
// Parse the command line. Return 1 if error else 0.
int Jidac::doCommand(int argc, char** argv)
{
/// Random 40-bytes long tags. Note: inverting is mandatory
g_franzo_start="dnE3pipUzeiUo8BMxVKlQTIfLjmskQbhlqBobVVr";
scambia(g_franzo_start);
g_franzo_end="xzUpA6PsHSE0N5Xe4ctJ2Gz7QTNLDyOXAp4kiEOo";
scambia(g_franzo_end);
// Initialize options to default values
command=0;
force=false;
all=0;
password=0; // no password
noattributes=false;
summary=0; // detailed: -1
threads=0; // 0 = auto-detect
version=DEFAULT_VERSION;
date=0;
myoutput="";
#if defined(_WIN64)
exename="zsfx";
#else
exename="zsfx32";
#endif
/// note: argv[0] does not have path.
myname=argv[0];
myname=extractfilename(myname);
if (!strstr(myname.c_str(), ".exe"))
myname+=".exe";
///printf("myname is |%s|\n",myname.c_str());
#if defined(_WIN64)
printf("zsfx(franz) v" ZSFX_VERSION " by Franco Corbelli - compiled " __DATE__ "\n");
#else
printf("zsfx32(franz) v" ZSFX_VERSION " by Franco Corbelli - compiled " __DATE__ "\n");
#endif
g_startzpaq=0;
bool autoextract=(archive!="");
bool flagbuilder=(myname=="zsfx.exe")||(myname=="zsfx32.exe");
libzpaq::Array<char*> argp(100);
if (!autoextract)
if (!flagbuilder)
{
string comandi=findcommand(g_startzpaq);
printf("Extracting from EXE with parameters: x %s\n",comandi.c_str());
//printf("Extracting from EXE\n");
///printf("Start %ld\n",startzpaq);
if (g_startzpaq==0)
{
printf("860:Something is WRONG\n");
exit(0);
}
/*
printf("ARGC prima vale %d\n",argc);
for (int i=0;i<argc;i++)
{
printf("XXXXX %d %s\n",i,argv[i]);
}
*/