Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1914 lines (1801 loc) · 71.9 KB
/
Copy pathmain.cpp
File metadata and controls
1914 lines (1801 loc) · 71.9 KB
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
//
// proc_pe - an AutoBleem scanner processor that turns PE app packages (.mod) into AutoBleem Apps.
//
// A package is a Debian archive (ar: debian-binary, control.tar.{gz,xz}, data.tar.xz) holding launcher folders:
// media/project_eris/etc/project_eris/SUP/launchers/<dir>/ with a launcher.cfg and a launch.sh. Each folder
// that the compatibility list allows becomes one App, Apps/pe-<launcher_filename>/: the folder byte for byte
// as the package has it, plus three generated files - app.ini, readme.txt and run.sh (the contract in the
// README). A package converted from a Mods folder (--mods) moves to Mods/done/ afterwards (replacing a copy
// there; never deleted; done/ is never scanned; a failed package stays in Mods and is tried again); a single
// --mod file stays where it is. The launcher's runtime (rc/pe_run.sh) runs the folder's own launch.sh. This
// program never executes anything from a package.
//
// pe --version "#PE app packages V<Version> - <what it does>"
// pe --ismine --mod <file> exit 0 = mine (a .mod in the ar format), 1 = not mine
// pe --start --mods <Mods dir> [--apps <dir>] [--packages <dir>] every *.mod in the folder
// pe --start --mod <file> [--apps <dir>] [--packages <dir>] one package
//
// The Apps folder is --apps, else $AB_APPS_DIR, else Apps/ next to the Mods folder; Packages/ (game data) is
// --packages, else $AB_PACKAGES_DIR, else next to Apps/. The compatibility list is
// --compat, else $AB_PE_COMPAT, else rc/pe_compat.ini under $AB_ROOT (or $AB_ROOT/Autobleem), else the copy
// built in. What it prints (one line at a time, flushed): #Starting - <title>, #Converting <file>, n/m, 0..100,
// #Adding <title>, #WARN - <text>, and at the end #DONE (exit 0) or #ERROR - <text> (exit 1).
//
// The rules it keeps, which every processor must keep:
// - atomic: a package is unpacked into Apps/.pe_tmp/ first (same filesystem) and a folder is renamed into
// Apps/ only when complete. It can be killed at any moment and started again: it clears .pe_tmp first, and
// puts a folder that a killed replacement had moved aside back.
// - idempotent: a package already converted (its marker in Apps/.pe_state/ and its Apps still there with the
// same PeSource and Version) is not even unpacked - #Starting and #DONE only.
// - it never overwrites what it did not make: an Apps folder without PeSource in its app.ini is left alone;
// a package with the same or an older Version than the installed one changes nothing; a newer Version
// replaces the folder but keeps every file of the old folder that the new package does not ship (saves,
// game data - merged in, at any depth).
// - safe unpacking: only the launcher folders are unpacked; a name with "..", an absolute name or a
// backslash anywhere in the package refuses the whole package; a link must point inside its own launcher
// folder (and is stored as a copy - the stick is FAT); size limits on a file, a package and the entry count.
//
#include "miniz.h"
#include "ab_names.h"
#include "archive.h"
#include "archive_entry.h"
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
using namespace std;
namespace {
const char *Version = PE_VERSION; // package/processor.ini's Version=, through CMake
const char *Description = "Turns PE app packages (.mod) into Apps";
// the launcher folders inside a package's data
const char *LauncherPrefix = "media/project_eris/etc/project_eris/SUP/launchers/";
// limits: a launcher folder is a program and its data, on a FAT stick (4 GB a file)
const uint64_t MaxFileSize = 2048ull * 1024 * 1024;
const uint64_t MaxPackageSize = 3072ull * 1024 * 1024;
const size_t MaxEntries = 50000;
const size_t MaxPathLength = 1000;
const size_t MaxNameLength = 255;
const size_t MaxMemberInMemory = 8 * 1024 * 1024; // the control archive, in memory
// the pad output of a launcher the list has no pad= for: the console's pad as a real device, which every mod reaches
// (its own SDL, a static one, or raw evdev); the shim's "psc" is a choice the user makes in the launcher
const string DefaultPadMode = "psc-kernel";
// the compatibility list, as the launcher ships it (rc/pe_compat.ini); used when no file is found
const char *BuiltInCompat =
"[backupinternallaunch]\nblock=1\nreason=deletes the console's own games\n"
"[editinternallaunch]\nblock=1\nreason=deletes the console's own games\n"
"[restoreinternallaunch]\nblock=1\nreason=deletes the console's own games\n"
"[bootmenu]\nskip=1\n[folder]\nskip=1\n[gamemanager]\nskip=1\n[pehome]\nskip=1\n[retroarch]\nskip=1\n"
"[openbor]\nskip=1\nreason=AutoBleem has its own App\n"
"[doom]\nskip=1\nreason=AutoBleem has its own App\n"
"[amiberry]\nskip=1\nreason=AutoBleem has its own App\n";
//******************
// the protocol's output
//******************
// every line is flushed at once: the launcher shows progress as it comes, and a pipe is block-buffered
void say(const string &line) {
fputs(line.c_str(), stdout);
fputc('\n', stdout);
fflush(stdout);
}
//******************
// a little portable filesystem (UTF-8 paths on every system)
//******************
#ifdef _WIN32
wstring wide(const string &s) {
int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
wstring w(n > 0 ? n - 1 : 0, L'\0');
if (n > 1)
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, &w[0], n);
return w;
}
string narrow(const wstring &w) {
int n = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr);
string s(n > 0 ? n - 1 : 0, '\0');
if (n > 1)
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, &s[0], n, nullptr, nullptr);
return s;
}
#endif
struct Entry {
string name;
bool isDir; // a real folder: a link to one is not
bool isLink; // a symbolic link (a reparse point on Windows): never followed
};
vector<Entry> listDir(const string &dir) {
vector<Entry> out;
#ifdef _WIN32
WIN32_FIND_DATAW data;
HANDLE h = FindFirstFileW(wide(dir + "/*").c_str(), &data);
if (h == INVALID_HANDLE_VALUE)
return out;
do {
string name = narrow(data.cFileName);
if (name == "." || name == "..")
continue;
bool link = (data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
out.push_back({name, !link && (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0, link});
} while (FindNextFileW(h, &data));
FindClose(h);
#else
DIR *d = opendir(dir.c_str());
if (!d)
return out;
while (dirent *e = readdir(d)) {
string name = e->d_name;
if (name == "." || name == "..")
continue;
struct stat st;
bool known = lstat((dir + "/" + name).c_str(), &st) == 0;
out.push_back({name, known && S_ISDIR(st.st_mode), known && S_ISLNK(st.st_mode)});
}
closedir(d);
#endif
sort(out.begin(), out.end(), [](const Entry &a, const Entry &b) { return a.name < b.name; });
return out;
}
bool exists(const string &path) {
#ifdef _WIN32
return GetFileAttributesW(wide(path).c_str()) != INVALID_FILE_ATTRIBUTES;
#else
struct stat st;
return lstat(path.c_str(), &st) == 0;
#endif
}
bool isDir(const string &path) {
#ifdef _WIN32
DWORD a = GetFileAttributesW(wide(path).c_str());
return a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY) && !(a & FILE_ATTRIBUTE_REPARSE_POINT);
#else
struct stat st;
return lstat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
#endif
}
bool makeDirs(const string &path) {
if (path.empty() || isDir(path))
return true;
size_t slash = path.find_last_of('/');
if (slash != string::npos && slash > 0 && !makeDirs(path.substr(0, slash)))
return false;
#ifdef _WIN32
return CreateDirectoryW(wide(path).c_str(), nullptr) || isDir(path);
#else
return mkdir(path.c_str(), 0777) == 0 || isDir(path);
#endif
}
bool removeFile(const string &path) {
#ifdef _WIN32
return DeleteFileW(wide(path).c_str()) != 0;
#else
return unlink(path.c_str()) == 0;
#endif
}
bool removeEmptyDir(const string &path) {
#ifdef _WIN32
return RemoveDirectoryW(wide(path).c_str()) != 0;
#else
return rmdir(path.c_str()) == 0;
#endif
}
bool renameFile(const string &from, const string &to) {
#ifdef _WIN32
return MoveFileW(wide(from).c_str(), wide(to).c_str()) != 0;
#else
return rename(from.c_str(), to.c_str()) == 0;
#endif
}
void setMode(const string &path, unsigned mode) {
#ifndef _WIN32
chmod(path.c_str(), static_cast<mode_t>(mode & 0777));
#else
(void)path;
(void)mode;
#endif
}
FILE *openFile(const string &path, const char *mode) {
#ifdef _WIN32
return _wfopen(wide(path).c_str(), wide(mode).c_str());
#else
return fopen(path.c_str(), mode);
#endif
}
int seekFile(FILE *f, int64_t offset, int whence) {
#ifdef _WIN32
return _fseeki64(f, offset, whence);
#else
return fseeko(f, static_cast<off_t>(offset), whence);
#endif
}
int64_t tellFile(FILE *f) {
#ifdef _WIN32
return _ftelli64(f);
#else
return static_cast<int64_t>(ftello(f));
#endif
}
int64_t fileSize(const string &path) {
FILE *f = openFile(path, "rb");
if (!f)
return -1;
int64_t size = seekFile(f, 0, SEEK_END) == 0 ? tellFile(f) : -1;
fclose(f);
return size;
}
// the whole file, or false when it cannot be read (or is bigger than `limit`)
bool readTextFile(const string &path, string &text, size_t limit = 1024 * 1024) {
FILE *f = openFile(path, "rb");
if (!f)
return false;
text.clear();
char buf[8192];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
text.append(buf, n);
if (text.size() > limit) {
fclose(f);
return false;
}
}
fclose(f);
return true;
}
bool writeTextFile(const string &path, const string &text) {
FILE *f = openFile(path, "wb");
if (!f)
return false;
bool ok = fwrite(text.data(), 1, text.size(), f) == text.size();
return fclose(f) == 0 && ok;
}
bool copyFile(const string &from, const string &to) {
FILE *in = openFile(from, "rb");
if (!in)
return false;
FILE *out = openFile(to, "wb");
if (!out) {
fclose(in);
return false;
}
char buf[65536];
size_t n;
bool ok = true;
while (ok && (n = fread(buf, 1, sizeof(buf), in)) > 0)
ok = fwrite(buf, 1, n, out) == n;
fclose(in);
return fclose(out) == 0 && ok;
}
// the scratch folder's name appears in every path removeTree is allowed to delete
const char *TmpName = ".pe_tmp";
// A folder and everything in it, links not followed (a link is removed, never what it points at). Only ever
// used on what this program made inside Apps/.pe_tmp: any other path is refused.
bool removeTree(const string &path) {
string guard = string("/") + TmpName;
bool inTmp = path.find(guard + "/") != string::npos ||
(path.size() >= guard.size() && path.compare(path.size() - guard.size(), guard.size(), guard) == 0);
if (!inTmp)
return false;
bool ok = true;
for (const Entry &e : listDir(path)) {
string child = path + "/" + e.name;
if (e.isDir)
ok = removeTree(child) && ok;
else
ok = removeFile(child) && ok;
}
return removeEmptyDir(path) && ok;
}
string lower(string s) {
for (char &c : s)
c = static_cast<char>(tolower(static_cast<unsigned char>(c)));
return s;
}
bool endsWith(const string &s, const string &suffix) {
return s.size() >= suffix.size() && lower(s.substr(s.size() - suffix.size())) == suffix;
}
bool startsWith(const string &s, const string &prefix) {
return s.compare(0, prefix.size(), prefix) == 0;
}
string fileName(const string &path) {
size_t slash = path.find_last_of("/\\");
return slash == string::npos ? path : path.substr(slash + 1);
}
string dirName(const string &path) {
size_t slash = path.find_last_of("/\\");
return slash == string::npos ? "." : path.substr(0, slash);
}
string withoutSlash(string path) {
while (path.size() > 1 && (path.back() == '/' || path.back() == '\\'))
path.pop_back();
return path;
}
string trim(const string &s) {
size_t a = 0, b = s.size();
while (a < b && isspace(static_cast<unsigned char>(s[a])))
++a;
while (b > a && isspace(static_cast<unsigned char>(s[b - 1])))
--b;
return s.substr(a, b - a);
}
// the lines of a text, any of LF, CRLF or CR ending them
vector<string> splitLines(const string &text) {
vector<string> lines;
string line;
for (size_t i = 0; i < text.size(); ++i) {
char c = text[i];
if (c == '\r' || c == '\n') {
if (c == '\r' && i + 1 < text.size() && text[i + 1] == '\n')
++i;
lines.push_back(line);
line.clear();
} else {
line += c;
}
}
if (!line.empty())
lines.push_back(line);
return lines;
}
//******************
// text that reaches the user
//******************
// A value that is shown (a title, an author, the readme): no control characters, and the product the packages
// were made for is called "PE" - its name does not appear in anything this program writes.
string shown(const string &raw, size_t limit) {
string s;
for (char c : raw)
s += (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) ? ' ' : c;
for (const char *name : {"project eris", "project_eris"}) {
size_t at;
while ((at = lower(s).find(name)) != string::npos)
s.replace(at, strlen(name), "PE");
}
s = trim(s);
if (s.size() > limit)
s.resize(limit);
return s;
}
//******************
// the shell-style files: launcher.cfg, and the compatibility list
//******************
// `name="value"` lines, read as data and never run: CRLF, blanks and #comments are tolerated, a value is in
// double or single quotes or bare, and nothing in it is expanded.
map<string, string> parseShellVars(const string &text) {
map<string, string> vars;
for (string line : splitLines(text)) {
line = trim(line);
if (line.empty() || line[0] == '#')
continue;
if (startsWith(line, "export ") || startsWith(line, "export\t"))
line = trim(line.substr(7));
size_t eq = line.find('=');
if (eq == string::npos || eq == 0)
continue;
string key = trim(line.substr(0, eq));
bool keyOk = !key.empty();
for (char c : key)
keyOk = keyOk && (isalnum(static_cast<unsigned char>(c)) || c == '_');
if (!keyOk)
continue;
string value = trim(line.substr(eq + 1));
if (!value.empty() && (value[0] == '"' || value[0] == '\'')) {
char quote = value[0];
size_t end = value.rfind(quote);
string inner = end > 0 ? value.substr(1, end - 1) : value.substr(1);
if (quote == '"') { // \" and \\ only
string un;
for (size_t i = 0; i < inner.size(); ++i) {
if (inner[i] == '\\' && i + 1 < inner.size() && (inner[i + 1] == '"' || inner[i + 1] == '\\'))
++i;
un += inner[i];
}
inner = un;
}
value = inner;
} else {
size_t space = value.find_first_of(" \t");
if (space != string::npos)
value.resize(space);
}
vars[key] = value;
}
return vars;
}
struct CompatRule {
bool block = false;
bool skip = false;
string reason;
string pad; // the App's PadMode (a launcher's default pad identity)
// the App's Dpad2Analog= / Analog2Dpad= ("1" / "0"; "" = not set): the d-pad also moves the stick / the stick
// also presses the d-pad
string dpad2analog;
string analog2dpad;
};
// "1" / "0" for a value that says on / off, else ""
string flagValue(const string &value) {
string v = lower(value);
if (v == "1" || v == "true" || v == "yes" || v == "on")
return "1";
if (v == "0" || v == "false" || v == "no" || v == "off")
return "0";
return "";
}
// [section] / key=value, section names lower-cased
map<string, CompatRule> parseCompat(const string &text) {
map<string, CompatRule> rules;
CompatRule *current = nullptr;
for (string line : splitLines(text)) {
line = trim(line);
if (line.empty() || line[0] == ';' || line[0] == '#')
continue;
if (line[0] == '[' && line.back() == ']') {
current = &rules[lower(trim(line.substr(1, line.size() - 2)))];
continue;
}
size_t eq = line.find('=');
if (!current || eq == string::npos)
continue;
string key = lower(trim(line.substr(0, eq)));
string value = trim(line.substr(eq + 1));
if (key == "block")
current->block = value == "1";
else if (key == "skip")
current->skip = value == "1";
else if (key == "reason")
current->reason = value;
else if (key == "pad")
current->pad = lower(value);
else if (key == "dpad2analog")
current->dpad2analog = flagValue(value);
else if (key == "analog2dpad")
current->analog2dpad = flagValue(value);
}
return rules;
}
map<string, CompatRule> loadCompat(const string &explicitPath) {
vector<string> candidates;
if (!explicitPath.empty())
candidates.push_back(explicitPath);
if (const char *env = getenv("AB_PE_COMPAT"))
candidates.push_back(env);
if (const char *root = getenv("AB_ROOT")) {
candidates.push_back(string(root) + "/rc/pe_compat.ini");
candidates.push_back(string(root) + "/Autobleem/rc/pe_compat.ini");
}
for (const string &path : candidates) {
string text;
if (!path.empty() && readTextFile(path, text))
return parseCompat(text);
}
return parseCompat(BuiltInCompat);
}
//******************
// the package: an ar archive
//******************
struct ArMember {
string name;
int64_t offset; // of the data
int64_t size;
};
// the members of the ar archive in `f`: false when it is not one
bool readAr(FILE *f, int64_t total, vector<ArMember> &members) {
char magic[8];
if (seekFile(f, 0, SEEK_SET) != 0 || fread(magic, 1, 8, f) != 8 || memcmp(magic, "!<arch>\n", 8) != 0)
return false;
int64_t pos = 8;
while (pos + 60 <= total) {
char h[60];
if (seekFile(f, pos, SEEK_SET) != 0 || fread(h, 1, 60, f) != 60 || h[58] != '`' || h[59] != '\n')
return false;
string name(h, 16);
while (!name.empty() && (name.back() == ' ' || name.back() == '/'))
name.pop_back();
string sizeText(h + 48, 10);
int64_t size = 0;
for (char c : trim(sizeText)) {
if (!isdigit(static_cast<unsigned char>(c)))
return false;
size = size * 10 + (c - '0');
}
pos += 60;
if (size < 0 || pos + size > total)
return false;
members.push_back({name, pos, size});
pos += size + (size & 1);
}
return true;
}
const ArMember *findMember(const vector<ArMember> &members, const string &prefix) {
for (const ArMember &m : members) {
if (startsWith(m.name, prefix))
return &m;
}
return nullptr;
}
// A gzip stream (header, deflate, trailer) in memory, unpacked with miniz's inflate into at most `limit` bytes.
bool gunzip(const vector<unsigned char> &in, size_t limit, vector<unsigned char> &out) {
if (in.size() < 18 || in[0] != 0x1f || in[1] != 0x8b || in[2] != 8)
return false;
unsigned flags = in[3];
size_t pos = 10;
if (flags & 4) { // FEXTRA
if (pos + 2 > in.size())
return false;
pos += 2 + (in[pos] | (in[pos + 1] << 8));
}
for (unsigned bit : {8u, 16u}) { // FNAME, FCOMMENT: zero-terminated
if (flags & bit) {
while (pos < in.size() && in[pos] != 0)
++pos;
++pos;
}
}
if (flags & 2) // FHCRC
pos += 2;
if (pos + 8 > in.size())
return false;
out.assign(limit, 0);
size_t n = tinfl_decompress_mem_to_mem(out.data(), out.size(), in.data() + pos, in.size() - pos - 8, 0);
if (n == TINFL_DECOMPRESS_MEM_TO_MEM_FAILED)
return false;
out.resize(n);
return true;
}
//******************
// tar.xz / tar through libarchive, from a byte range of a file or from memory
//******************
struct Input {
FILE *file = nullptr;
int64_t pos = 0; // in the range, 0 .. size
int64_t size = 0;
int64_t start = 0;
const vector<unsigned char> *memory = nullptr;
vector<unsigned char> buffer = vector<unsigned char>(65536);
function<void(int64_t)> onProgress;
};
class TarReader {
public:
explicit TarReader(Input &input) : in(input) {
a = archive_read_new();
archive_read_support_filter_xz(a);
archive_read_support_format_tar(a);
ab_archive_names_utf8(a);
archive_read_set_read_callback(a, onRead);
archive_read_set_skip_callback(a, onSkip);
archive_read_set_callback_data(a, &in);
if (archive_read_open1(a) != ARCHIVE_OK) {
why = failure("not a tar archive this program can read");
archive_read_free(a);
a = nullptr;
}
}
~TarReader() {
if (a)
archive_read_free(a);
}
TarReader(const TarReader &) = delete;
TarReader &operator=(const TarReader &) = delete;
archive *a = nullptr;
string why;
// what went wrong, in libarchive's words when it has some
string failure(const string &what) const {
const char *detail = a ? archive_error_string(a) : nullptr;
return detail ? what + " (" + detail + ")" : what;
}
private:
Input ∈
static la_ssize_t onRead(archive *, void *data, const void **buf) {
Input *i = static_cast<Input *>(data);
int64_t left = i->size - i->pos;
if (left <= 0)
return 0;
size_t want = static_cast<size_t>(min<int64_t>(left, static_cast<int64_t>(i->buffer.size())));
if (i->memory) {
*buf = i->memory->data() + i->pos;
i->pos += static_cast<int64_t>(want);
return static_cast<la_ssize_t>(want);
}
if (seekFile(i->file, i->start + i->pos, SEEK_SET) != 0)
return -1;
size_t n = fread(i->buffer.data(), 1, want, i->file);
if (n == 0)
return -1;
*buf = i->buffer.data();
i->pos += static_cast<int64_t>(n);
if (i->onProgress)
i->onProgress(i->pos);
return static_cast<la_ssize_t>(n);
}
static la_int64_t onSkip(archive *, void *data, la_int64_t request) {
Input *i = static_cast<Input *>(data);
int64_t n = min<int64_t>(request, i->size - i->pos);
i->pos += n;
if (i->onProgress && !i->memory)
i->onProgress(i->pos);
return n;
}
};
// the entry's names, UTF-8
string entryPath(archive_entry *e) {
#ifdef _WIN32
const char *p = archive_entry_pathname_utf8(e);
#else
const char *p = archive_entry_pathname(e); // UTF-8 already (ab_archive_names_utf8)
#endif
return p ? p : "";
}
string entryHardlink(archive_entry *e) {
#ifdef _WIN32
const char *p = archive_entry_hardlink_utf8(e);
#else
const char *p = archive_entry_hardlink(e);
#endif
return p ? p : "";
}
string entrySymlink(archive_entry *e) {
#ifdef _WIN32
const char *p = archive_entry_symlink_utf8(e);
#else
const char *p = archive_entry_symlink(e);
#endif
return p ? p : "";
}
//******************
// names inside the package
//******************
// A package path made plain: "./a//b/" -> "a/b". False for a name that could write outside the folder it is
// unpacked to (absolute, a ".." part, a backslash or a drive colon) or is absurdly long.
bool plainPath(const string &raw, string &out) {
if (raw.empty() || raw[0] == '/' || raw.find('\\') != string::npos || raw.find(':') != string::npos ||
raw.size() > MaxPathLength)
return false;
out.clear();
size_t start = 0;
while (start <= raw.size()) {
size_t slash = raw.find('/', start);
string part = raw.substr(start, slash == string::npos ? string::npos : slash - start);
if (part == "..")
return false;
if (part.size() > MaxNameLength)
return false;
if (!part.empty() && part != ".")
out += (out.empty() ? "" : "/") + part;
if (slash == string::npos)
break;
start = slash + 1;
}
return true;
}
// `target` of a link at `rel` (both inside one launcher folder, '/' separated) -> the target's own path inside
// the folder; false when it leaves the folder
bool resolveInside(const string &rel, const string &target, string &out) {
if (target.empty() || target[0] == '/' || target.find('\\') != string::npos)
return false;
vector<string> parts;
size_t start = 0;
string base = dirName(rel) == "." ? "" : dirName(rel);
string full = (base.empty() ? "" : base + "/") + target;
while (start <= full.size()) {
size_t slash = full.find('/', start);
string part = full.substr(start, slash == string::npos ? string::npos : slash - start);
if (part == "..") {
if (parts.empty())
return false;
parts.pop_back();
} else if (!part.empty() && part != ".") {
parts.push_back(part);
}
if (slash == string::npos)
break;
start = slash + 1;
}
out.clear();
for (const string &p : parts)
out += (out.empty() ? "" : "/") + p;
return !out.empty();
}
//******************
// the control file
//******************
struct Control {
string version;
string maintainer;
string type;
string category; // the package type ("Category: games"), as the packer wrote it: see packageCategory()
string platform; // the machine ("Platform: SONYPSC armhf", "RPI armhf"), as the packer wrote it: see execKey()
string title; // the first line of Description
vector<string> description; // the lines after it (continuation lines, ' .' as an empty line)
};
Control parseControl(const string &text) {
Control c;
string key;
for (const string &line : splitLines(text)) {
if (line.empty())
continue;
if (line[0] == ' ' || line[0] == '\t') {
string body = trim(line);
if (key == "description") {
c.description.push_back(body == "." ? "" : body);
// "Type: USB_MOD" is a continuation line of the Description
if (startsWith(lower(body), "type:"))
c.type = trim(body.substr(5));
if (startsWith(lower(body), "category:"))
c.category = trim(body.substr(9));
if (startsWith(lower(body), "platform:"))
c.platform = trim(body.substr(9));
}
continue;
}
size_t colon = line.find(':');
if (colon == string::npos)
continue;
key = lower(line.substr(0, colon));
string value = trim(line.substr(colon + 1));
if (key == "version" && c.version.empty())
c.version = value;
else if (key == "maintainer")
c.maintainer = value;
else if (key == "type")
c.type = value;
else if (key == "category")
c.category = value;
else if (key == "platform")
c.platform = value;
else if (key == "description")
c.title = value;
}
return c;
}
// the control file out of a package's ar members: false and `why` when there is none
bool readControl(FILE *f, const vector<ArMember> &members, Control &control, string &why) {
const ArMember *m = findMember(members, "control.tar");
if (!m) {
why = "not a PE app package (no control archive)";
return false;
}
string tarName = lower(m->name);
vector<unsigned char> raw;
Input in;
in.file = f;
in.start = m->offset;
in.size = m->size;
vector<unsigned char> plain;
if (endsWith(tarName, ".gz")) {
if (static_cast<size_t>(m->size) > MaxMemberInMemory) {
why = "its control archive is too big";
return false;
}
raw.resize(static_cast<size_t>(m->size));
if (seekFile(f, m->offset, SEEK_SET) != 0 || fread(raw.data(), 1, raw.size(), f) != raw.size() ||
!gunzip(raw, MaxMemberInMemory, plain)) {
why = "its control archive cannot be unpacked";
return false;
}
in.memory = &plain;
in.size = static_cast<int64_t>(plain.size());
} else if (!endsWith(tarName, ".xz") && !endsWith(tarName, ".tar")) {
why = "its control archive is packed in a way this program does not read";
return false;
}
TarReader reader(in);
if (!reader.a) {
why = reader.why;
return false;
}
archive_entry *entry;
int r;
while ((r = archive_read_next_header(reader.a, &entry)) == ARCHIVE_OK || r == ARCHIVE_WARN) {
string name;
if (!plainPath(entryPath(entry), name) || name != "control" || archive_entry_filetype(entry) != AE_IFREG)
continue;
string text;
const void *buf;
size_t n;
la_int64_t offset;
while (archive_read_data_block(reader.a, &buf, &n, &offset) == ARCHIVE_OK) {
text.append(static_cast<const char *>(buf), n);
if (text.size() > 256 * 1024) {
why = "its control file is too big";
return false;
}
}
control = parseControl(text);
if (control.version.empty()) {
why = "its control file has no Version";
return false;
}
return true;
}
why = "it has no control file";
return false;
}
// Debian's version order, the part that matters here: digits compare as numbers, letters as letters, '~' first
int compareVersions(const string &a, const string &b) {
auto order = [](char c) {
if (c == '~')
return -1;
if (isalpha(static_cast<unsigned char>(c)))
return static_cast<int>(c);
return static_cast<int>(c) + 256;
};
size_t i = 0, j = 0;
while (i < a.size() || j < b.size()) {
while ((i < a.size() && !isdigit(static_cast<unsigned char>(a[i]))) ||
(j < b.size() && !isdigit(static_cast<unsigned char>(b[j])))) {
int ca = (i < a.size() && !isdigit(static_cast<unsigned char>(a[i]))) ? order(a[i]) : 0;
int cb = (j < b.size() && !isdigit(static_cast<unsigned char>(b[j]))) ? order(b[j]) : 0;
if (ca != cb)
return ca < cb ? -1 : 1;
if (i < a.size() && !isdigit(static_cast<unsigned char>(a[i])))
++i;
if (j < b.size() && !isdigit(static_cast<unsigned char>(b[j])))
++j;
}
while (i < a.size() && a[i] == '0')
++i;
while (j < b.size() && b[j] == '0')
++j;
size_t si = i, sj = j;
while (i < a.size() && isdigit(static_cast<unsigned char>(a[i])))
++i;
while (j < b.size() && isdigit(static_cast<unsigned char>(b[j])))
++j;
if (i - si != j - sj)
return i - si < j - sj ? -1 : 1;
int c = a.compare(si, i - si, b, sj, j - sj);
if (c != 0)
return c < 0 ? -1 : 1;
}
return 0;
}
//******************
// the Apps folder: what a converted package leaves
//******************
struct Paths {
string apps;
string packages; // Packages/: where a game-data mod is unpacked to (made only when there is one)
string tmp; // Apps/.pe_tmp: unpacking and replacing happen here, on the same filesystem as Apps
string state; // Apps/.pe_state: one small marker per package
};
Paths pathsFor(const string &apps, const string &packages) {
return {apps, packages, apps + "/" + TmpName, apps + "/.pe_state"};
}
// A folder moved aside in .pe_tmp to be replaced is "<name>.old"; one of Packages/ carries this prefix, because
// Apps/ and Packages/ both have a pe-<name>.
const char *PackagesAside = "Packages~";
// A killed run left unpacked folders in .pe_tmp (cleared) - and maybe a folder it had moved aside to replace
// it, with nothing in its place (put back).
void recover(const Paths &p) {
for (const Entry &e : listDir(p.tmp)) {
string path = p.tmp + "/" + e.name;
if (e.isDir && endsWith(e.name, ".old")) {
string base = e.name.substr(0, e.name.size() - 4);
string final = startsWith(base, PackagesAside) ? p.packages + "/" + base.substr(strlen(PackagesAside))
: p.apps + "/" + base;
if (!exists(final) && makeDirs(dirName(final)))
renameFile(path, final);
}
}
removeTree(p.tmp);
}
struct AppIni {
map<string, string> keys; // lower-cased names
string get(const string &k) const {
auto it = keys.find(k);
return it == keys.end() ? "" : it->second;
}
};
AppIni readAppIni(const string &folder) {
AppIni ini;
string text;
if (!readTextFile(folder + "/app.ini", text))
return ini;
for (const string &line : splitLines(text)) {
size_t eq = line.find('=');
if (eq != string::npos && !line.empty() && line[0] != ';' && line[0] != '#')
ini.keys[lower(trim(line.substr(0, eq)))] = trim(line.substr(eq + 1));
}
return ini;
}
// package.ini (the packages spec, 2.2): lines of key=value, a '#' starts a comment anywhere on a line
AppIni readPackageIni(const string &folder) {
AppIni ini;
string text;
if (!readTextFile(folder + "/package.ini", text, 65536))
return ini;
for (string line : splitLines(text)) {
size_t hash = line.find('#');
if (hash != string::npos)
line.resize(hash);
size_t eq = line.find('=');
if (eq != string::npos && !line.empty() && line[0] != ';')
ini.keys[lower(trim(line.substr(0, eq)))] = trim(line.substr(eq + 1));
}
return ini;
}
struct Marker {
string version;