forked from jeffpar/pcjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiskimage.js
2268 lines (2177 loc) · 90.5 KB
/
diskimage.js
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
/**
* @fileoverview Command-line interface to disk image processing module
* @author Jeff Parsons <[email protected]>
* @copyright © 2012-2023 Jeff Parsons
* @license MIT <https://www.pcjs.org/LICENSE.txt>
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*/
import fs from "fs";
import os from "os";
import crypto from "crypto";
import glob from "glob";
import path from "path";
import got from "got";
import BASConvert from "../bascon/bascon.js";
import PCJSLib from "../modules/pcjslib.js";
import StreamZip from "../modules/streamzip.js";
// import StreamZip from "node-stream-zip";
import DataBuffer from "../../machines/modules/v1/databuffer.js";
import JSONLib from "../../machines/modules/v2/jsonlib.js";
import Device from "../../machines/modules/v3/device.js";
import DiskInfo from "../../machines/pcx86/modules/v3/diskinfo.js";
import CharSet from "../../machines/pcx86/modules/v3/charset.js";
let device = new Device("node");
let printf = device.printf.bind(device);
let sprintf = device.sprintf.bind(device);
let pcjslib = new PCJSLib();
let moduleDir, rootDir;
let nMaxDefault = 512, nMaxInit, nMaxCount, sFileIndex, useServer;
function printError(err, filename)
{
let msg = err.message;
if (filename) msg = path.basename(filename) + ": " + msg;
printf("error: %s\n", msg);
}
/*
* List of archive file types to expand when "--expand" is specified.
*/
let asArchiveFileExts = [".ARC", ".ZIP"]; // order must match StreamZip.TYPE_* constants
/*
* List of text file types to convert line endings from LF to CR+LF when "--normalize" is specified.
* A warning is always displayed when we replace line endings in any file being copied to a disk image.
*
* NOTE: Some files, like ".BAS" files, aren't always ASCII, which is why we now call isText() on all
* these file contents first.
*/
let asTextFileExts = [".MD", ".ME", ".BAS", ".BAT", ".RAT", ".ASM", ".LRF", ".MAK", ".TXT", ".XML"];
/**
* compareDisks(sDisk1, sDisk2)
*
* @param {string} sDisk1
* @param {string} sDisk2
* @returns {boolean} (true if the contents of this buffer are equal to the contents of the specified buffer, false otherwise)
*/
function compareDisks(sDisk1, sDisk2)
{
/*
* Passing null for the encoding parameter tells readFile() to return a buffer (which, in our case, is a DataBuffer).
*/
let db1 = readFile(sDisk1, null);
let db2 = readFile(sDisk2, null);
return db1 && db2 && db1.compare(db2) || false;
}
/**
* createDisk(diskFile, diskette, argv, done)
*
* @param {string} diskFile
* @param {Object} diskette
* @param {Array} argv
* @param {function(DiskInfo)} [done]
* @returns {DiskInfo|null}
*/
function createDisk(diskFile, diskette, argv, done)
{
let di;
let sArchiveFolder = "archive/";
if (path.dirname(diskFile).endsWith("/disks")) {
sArchiveFolder = "../archive/";
}
let sArchiveFile = path.join(path.dirname(diskFile), sArchiveFolder, path.basename(diskFile).replace(".json", ".img"));
if (diskette.archive) {
/*
* The "archive" property determines what we look for in an "archive/" folder alongside the JSON disk image:
*
* 1) If it begins with a period, then we assume it's a file extension (eg, ".img", ".psi", etc)
* 2) If it's "folder", then the name of the diskette is used as a folder name (with trailing slash)
* 3) Anything else is more or less used as-is (and unless it contains a period, we add a trailing slash)
*/
if (diskette.archive[0] == '/') {
sArchiveFile = path.sep + diskette.archive.slice(1);
} else if (diskette.archive[0] == '.') {
if (diskette.archive != ".img") {
sArchiveFile = sArchiveFile.replace(".img", diskette.archive.toUpperCase());
}
} else if (diskette.archive == "folder") {
sArchiveFile = sArchiveFile.replace(".img", path.sep);
} else {
sArchiveFile = path.join(path.dirname(sArchiveFile), diskette.archive) + (diskette.archive.indexOf(".") < 0 && !diskette.archive.endsWith(path.sep)? path.sep : "");
}
} else if (!existsFile(sArchiveFile)) {
/*
* Try automatically switching from a "--disk" to a "--dir" operation if there's no IMG file.
*/
sArchiveFile = sArchiveFile.replace(".img", path.sep);
}
let name = path.basename(sArchiveFile);
let sectorIDs = diskette.argv['sectorID'] || argv['sectorID'];
let sectorErrors = diskette.argv['sectorError'] || argv['sectorError'];
let suppData = diskette.argv['suppData'] || argv['suppData'];
if (suppData) suppData = readFile(suppData);
let fDir = false, arcType = 0, sExt = path.parse(sArchiveFile).ext.toLowerCase();
if (sArchiveFile.endsWith(path.sep)) {
fDir = true;
diskette.command = "--dir=" + name;
}
else if (sExt == ".arc") {
arcType = 1;
diskette.command = "--arc=" + name;
}
else if (sExt == ".zip") {
arcType = 2;
diskette.command = "--zip=" + name;
}
else {
diskette.command = "--disk=" + name;
}
diskette.archive = sArchiveFile;
printf("checking archive: %s\n", sArchiveFile);
if (fDir || arcType) {
let arcOffset = +argv['offset'] || 0;
let label = diskette.label || argv['label'];
let password = argv['password'];
let normalize = diskette.normalize || argv['normalize'];
let target = getTargetValue(diskette.format);
let verbose = argv['verbose'];
di = readDir(sArchiveFile, arcType, arcOffset, label, password, normalize, target, undefined, verbose, done, sectorIDs, sectorErrors, suppData);
} else {
di = readDisk(sArchiveFile, false, sectorIDs, sectorErrors, suppData);
if (di && done) {
done(di);
}
}
return di;
}
/**
* dumpSector(di, sector, offset, limit)
*
* @param {DiskInfo} di
* @param {Sector} sector
* @param {number} [offset]
* @param {number} [limit]
* @returns {string}
*/
function dumpSector(di, sector, offset = 0, limit = -1)
{
let sBytes = "", sChars = "", sLines = "";
if (limit < 0) limit = di.cbSector;
while (offset < limit) {
let b = di.read(sector, offset);
if (b < 0) break;
if (!sLines || offset % 16 == 0) sLines += sprintf("%#06x ", offset);
sBytes += sprintf("%02x ", b);
sChars += (b >= 0x20 && b < 0x7f? String.fromCharCode(b) : '.');
if (++offset % 16 == 0) {
sLines += sprintf("%48s %16s\n", sBytes, sChars);
sBytes = sChars = "";
}
}
if (sBytes) sLines += sprintf("%-48s %-16s\n", sBytes, sChars);
return sLines;
}
/**
* checkArchive(sPath, fExt)
*
* @param {string} sPath
* @param {boolean} fExt (true to check path for archive extension only)
* @returns {string|undefined}
*/
function checkArchive(sPath, fExt)
{
let sArchive;
for (let sExt of [".ZIP", ".zip", ".ARC", ".arc"]) {
if (fExt) {
if (sPath.endsWith(sExt)) {
sArchive = sPath; // sPath.slice(0, -sExt.length);
break;
}
continue;
}
let sFile = sPath.endsWith(sExt)? sPath : (sPath + sExt);
if (existsFile(sFile)) {
sArchive = sFile;
break;
}
}
return sArchive;
}
/**
* existsDir(sDir, fError)
*
* @param {string} sDir
* @param {boolean} [fError]
* @returns {boolean}
*/
function existsDir(sDir, fError = true)
{
try {
sDir = getFullPath(sDir);
let stat = fs.statSync(sDir);
return stat.isDirectory();
} catch(err) {
if (fError) printError(err);
}
return false;
}
/**
* existsFile(sFile, fError)
*
* This is really "existsFileOrDir()"; if you need to know which, call existsDir() afterward.
*
* @param {string} sFile
* @param {boolean} [fError]
* @returns {boolean}
*/
function existsFile(sFile, fError = true)
{
try {
sFile = getFullPath(sFile);
return fs.existsSync(sFile);
} catch(err) {
if (fError) printError(err);
}
return false;
}
/**
* getHash(data, type)
*
* @param {Array.<number>|string|DataBuffer} data
* @param {string} [type] (eg, "md5")
* @returns {string}
*/
function getHash(data, type = "md5")
{
let db;
if (data instanceof DataBuffer) {
db = data;
} else {
db = new DataBuffer(data);
}
return crypto.createHash(type).update(db.buffer).digest('hex');
}
/**
* getFullPath(sFile)
*
* @param {string} sFile
* @returns {string}
*/
function getFullPath(sFile)
{
if (sFile[0] == '~') {
sFile = os.homedir() + sFile.substr(1);
}
else {
sFile = getServerPath(sFile);
}
return sFile;
}
/**
* getDiskServer(diskFile)
*
* @param {string} diskFile
* @returns {string|undefined}
*/
function getDiskServer(diskFile)
{
let match = diskFile.match(/^\/(disks\/|)(diskettes|gamedisks|miscdisks|harddisks|decdisks|pcsigdisks|cdroms|private)\//);
return match && (match[1] + match[2]);
}
/**
* getServerPath(sFile)
*
* @param {string} sFile
* @returns {string}
*/
function getServerPath(sFile)
{
/*
* In addition to disk server paths, we had to add /machines (for diskette config files) and /software
* (for Markdown files containing supplementary copy-protection disk data).
*/
let match = sFile.match(/^\/(disks\/|)(machines|software|diskettes|gamedisks|miscdisks|harddisks|decdisks|pcsigdisks|cdroms|private)(\/.*)$/);
if (match) {
sFile = path.join(rootDir, (match[2] == "machines" || match[2] == "software"? "" : "disks"), match[2], match[3]);
}
return sFile;
}
/**
* getTargetValue(sTarget)
*
* Target is normally a number in Kb (eg, 360 for a 360K diskette); you can also add a suffix (eg, K or M).
* K is assumed, whereas M will automatically produce a Kb value equal to the specified Mb value (eg, 10M is
* equivalent to 10240K).
*
* @param {string} sTarget
* @returns {number} (target Kb for disk image, 0 if no target)
*/
function getTargetValue(sTarget)
{
let target = 0;
if (sTarget) {
let match = sTarget.match(/^(PC|)([0-9]+)([KM]*)/i);
if (match) {
target = +match[2];
if (match[3].toUpperCase() == 'M') {
target *= 1024;
}
}
}
return target;
}
/**
* isArchiveFile(sFile)
*
* @param {string} sFile
* @returns {number} StreamZip TYPE value, or 0 if not an archive file
*/
function isArchiveFile(sFile)
{
let sExt = path.parse(sFile).ext.toUpperCase();
return asArchiveFileExts.indexOf(sExt) + 1;
}
/**
* isBASICFile(sFile)
*
* @param {string} sFile
* @returns {boolean} true if the filename has a ".BAS" extension
*/
function isBASICFile(sFile)
{
let ext = path.parse(sFile).ext;
return ext && ext.toUpperCase() == ".BAS";
}
/**
* isTextFile(sFile)
*
* @param {string} sFile
* @returns {boolean} true if the filename contains a known text file extension, false if unknown
*/
function isTextFile(sFile)
{
let sFileUC = sFile.toUpperCase();
for (let i = 0; i < asTextFileExts.length; i++) {
if (sFileUC.endsWith(asTextFileExts[i])) return true;
}
return false;
}
/**
* makeDir(sDir, recursive, deleteFile)
*
* The deleteFile parameter is never true unless '--overwrite' was specified; it is only intended
* to come into play when using '--expand' along with '--extract', because if any earlier '--extract'
* did NOT use '--expand', then any archives inside the source disk/archive will have been extracted
* as a file rather than a directory -- in which case, we must delete the file before we can create
* a directory.
*
* @param {string} sDir
* @param {boolean} [recursive]
* @param {boolean} [deleteFile] (delete any existing file with the same name as the directory)
* @returns {boolean} true if successful (or the directory already exists), false if error
*/
function makeDir(sDir, recursive = false, deleteFile = false)
{
let success = true;
if (existsFile(sDir, false) && !existsDir(sDir, false) && deleteFile) {
try {
fs.unlinkSync(sDir);
} catch(err) {
printError(err);
success = false;
}
}
if (success && !existsFile(sDir, false)) {
try {
fs.mkdirSync(sDir, {recursive});
} catch(err) {
printError(err);
success = false;
}
}
return success;
}
/**
* convertBASICFile(db, fNormalize, sPath)
*
* @param {DataBuffer} db (the contents of the BASIC file)
* @param {boolean} [fNormalize] (true if we should convert characters from CP437 to UTF-8, revert line-endings, and omit EOF)
* @param {string} [sPath] (for informational purposes only, since we're working entirely with the DataBuffer)
* @returns {DataBuffer}
*/
function convertBASICFile(db, fNormalize, sPath)
{
let converter = new BASConvert(db, fNormalize, sPath, printf);
return converter.convert();
}
/**
* extractFile(sDir, subDir, sPath, attr, date, db, argv, noExpand, files)
*
* @param {string} sDir
* @param {string} subDir
* @param {string} sPath
* @param {number} attr
* @param {Date} date
* @param {Buffer} db
* @param {Object} argv
* @param {boolean} [noExpand]
* @param {Array.<fileData>} [files]
*/
function extractFile(sDir, subDir, sPath, attr, date, db, argv, noExpand, files)
{
/*
* OS X / macOS loves to scribble bookkeeping data on any read-write diskettes or diskette images that
* it mounts, so if we see any of those remnants (which we use to limit to "(attr & DiskInfo.ATTR.HIDDEN)"
* but no longer assume they always will hidden), then we ignore them.
*
* This is why I make all my IMG files read-only and also write-protect physical diskettes before inserting
* them into a drive. Other operating systems pose similar threats. For example, Windows 9x likes to modify
* the 8-byte OEM signature field of a diskette's boot sector with unique volume-tracking identifiers.
*/
if (sPath.endsWith("~1.TRA") || sPath.endsWith("TRASHE~1") || sPath.indexOf("FSEVEN~1") >= 0) {
return true;
}
sPath = path.join(sDir, subDir, sPath);
let sFile = sPath.substr(sDir != '.' && sDir.length? sDir.length + 1 : 0);
let fSuccess = false;
let dir = path.dirname(sPath);
makeDir(getFullPath(dir), true, argv['overwrite']);
if (attr & DiskInfo.ATTR.SUBDIR) {
fSuccess = makeDir(getFullPath(sPath), true);
} else if (!(attr & DiskInfo.ATTR.VOLUME)) {
let fPrinted = false;
let fQuiet = argv['quiet'];
if (argv['expand'] && !noExpand) {
let arcType = isArchiveFile(sFile);
if (arcType) {
if (!fQuiet) printf("expanding: %s\n", sFile);
if (arcType == StreamZip.TYPE_ZIP && db.readUInt8(0) == 0x1A) {
/*
* How often does this happen? I don't know, but look at CCTRAN.ZIP on PC-SIG DISK2631. #ZipAnomalies
*/
arcType = StreamZip.TYPE_ARC;
printf("warning: overriding %s as type ARC (%d)\n", sFile, arcType);
}
if (arcType == StreamZip.TYPE_ZIP && db.readUInt32LE(0) == 0x08074B50) {
// db = db.slice(0, db.length - 4);
printf("warning: ZIP extended header signature detected (%#08x)\n", 0x08074B50);
}
let zip = new StreamZip({
file: sFile,
password: argv['password'],
buffer: db.buffer,
arcType: arcType,
storeEntries: true,
nameEncoding: "ascii",
printfDebug: printf,
holdErrors: true
}).on('ready', () => {
let aFileData = getArchiveFiles(zip, argv['verbose']);
for (let file of aFileData) {
extractFile(sDir, sFile, file.path, file.attr, file.date, file.data, argv, false, file.files);
}
zip.close();
}).on('error', (err) => {
printError(err, sFile);
/*
* Since this implies a failure to extract anything from the archive, we'll call ourselves
* back with noExpand set to true, so that we simply extract the archive without expanding it.
*/
extractFile(sDir, subDir, sFile, attr, date, db, argv, true);
});
zip.open();
/*
* If we 'expand' the contents of an archive, then we likely don't want to also save the
* archive itself, so we return now. If you do want both, we'll have to add a new option.
*/
return true;
}
}
if (argv['collection'] && existsFile(sPath) && !argv['overwrite']) {
if (!fPrinted && !fQuiet) printf("extracted: %s\n", sFile);
return true;
}
if (!fQuiet) printf("extracting: %s\n", sFile);
/*
* Originally, "normalize" was just an import option (to fix line endings of known text files on
* disks we created); however, I'm going to make it an export option as well, and not just to revert
* line endings, but to also address the fact that there are a lot of old "tokenized" BASIC files out
* in the world, and they are much easier to work with locally in their "de-tokenized" form.
*/
if (argv['normalize']) {
/*
* BASIC files are dealt with separately, because there are 3 kinds: ASCII (for which we call
* modernize()), tokenized (which we convert to ASCII and automatically normalize in the process),
* and protected (which we decrypt and then de-tokenize).
*/
if (isBASICFile(sPath)) {
/*
* In addition to "de-tokenizing", we're also setting convertBASICFile()'s normalize parameter
* to true, to convert characters from CP437 to UTF-8, revert line-endings, and omit EOF. We're
* currently combining both features as part of the "normalize" process.
*/
db = convertBASICFile(db, true, sPath);
}
else if (isTextFile(sPath)) {
db = BASConvert.modernize(db, true);
}
}
fSuccess = writeFile(getFullPath(sPath), db, true, argv['overwrite'], !!(attr & DiskInfo.ATTR.READONLY), argv['quiet']);
}
if (fSuccess) {
fs.utimesSync(getFullPath(sPath), date, date);
if (files) {
for (let file of files) {
if (!extractFile(sDir, subDir, file.path, file.attr, file.date, file.data, argv, false, file.files)) {
fSuccess = false;
break;
}
}
}
}
return fSuccess;
}
/**
* mapDiskToServer(diskFile)
*
* @param {string} diskFile
* @param {boolean} [fRemote] (true to return remote address)
* @returns {string}
*/
function mapDiskToServer(diskFile, fRemote)
{
if (useServer || !existsFile(getFullPath(diskFile)) || fRemote) {
diskFile = diskFile.replace(/^\/disks\/(diskettes|gamedisks|miscdisks|harddisks|decdisks|pcsigdisks|pcsig[0-9a-z]*-disks|private)\//, "https://$1.pcjs.org/").replace(/^\/disks\/cdroms\/([^/]*)\//, "https://$1.pcjs.org/");
}
return diskFile;
}
/**
* printFileDesc(diskFile, diskName, desc)
*
* @param {string} diskFile
* @param {string} diskName
* @param {Object} desc
*/
function printFileDesc(diskFile, diskName, desc)
{
printf("%-32s %-12s %s %s %7d %s\n", desc[DiskInfo.FILEDESC.HASH] || "-".repeat(32), desc[DiskInfo.FILEDESC.NAME], desc[DiskInfo.FILEDESC.DATE], desc[DiskInfo.FILEDESC.ATTR], desc[DiskInfo.FILEDESC.SIZE] || 0, diskName + ':' + desc[DiskInfo.FILEDESC.PATH]);
}
/**
* printManifest(diskFile, diskName, manifest)
*
* @param {string} diskFile
* @param {string} diskName
* @param {Array.<FILEDESC>} manifest
*/
function printManifest(diskFile, diskName, manifest)
{
manifest.forEach(function printManifestFile(desc) {
printFileDesc(diskFile, diskName, desc);
});
}
/**
* processDisk(di, diskFile, argv, diskette)
*
* @param {DiskInfo} di
* @param {string} diskFile
* @param {Array} argv
* @param {Object} [diskette] (if present, then we were invoked by readCollection(), so any --output option should be ignored)
*/
function processDisk(di, diskFile, argv, diskette)
{
di.setArgs(argv.slice(1).join(' '));
/*
* Any "--format=xxx" acts as a filter function; if the disk's format doesn't contain
* the specified format, we skip the disk.
*/
if (typeof argv['format'] == "string") {
let sFormat = di.getFormat();
if (sFormat.indexOf(argv['format']) < 0) {
printf("warning: specified format (\"%s\") does not match disk format (\"%s\")\n", argv['format'], sFormat);
return;
}
}
if (!argv['quiet']) {
printf("processing: %s (%d bytes, checksum %d, hash %s)\n", di.getName(), di.getSize(), di.getChecksum(), di.getHash());
}
let sFindName = argv['file'];
if (typeof sFindName == "string") {
let sFindText = argv['find'];
if (typeof sFindText != "string") sFindText = undefined;
/*
* TODO: Implement support for finding text in findFile()....
*/
let desc = di.findFile(sFindName, sFindText);
if (desc) {
printFileDesc(di.getName(), desc);
if (argv['index']) {
/*
* We cheat and search for matching hash values in the provided index; this is much faster than laboriously
* opening and searching all the other disk images, even when they DO contain pre-generated file tables.
*/
if (sFileIndex === undefined) {
sFileIndex = readFile(argv['index']);
if (!sFileIndex) sFileIndex = null;
}
let cMatches = 0;
if (sFileIndex) {
let re = new RegExp("^" + desc[DiskInfo.FILEDESC.HASH] + ".*$", "gm"), match;
while ((match = re.exec(sFileIndex))) {
if (match[0].indexOf(diskFile) >= 0) continue;
if (!cMatches++) printf("see also:\n");
printf("%s\n", match[0]);
}
}
if (!cMatches) printf("no matches\n");
}
}
}
let chs = argv['dump'];
if (chs) {
if (typeof chs != "string") {
printf("specify --dump=C:H:S[:N]\n");
} else {
let values = chs.split(':');
let iCylinder = +values[0], iHead = +values[1], idSector = +values[2], nSectors = +values[3] || 1;
while (nSectors-- > 0) {
let sector = di.seek(iCylinder, iHead, idSector);
if (!sector) {
printf("unable to find %d:%d:%d\n", iCylinder, iHead, idSector);
break;
}
let sLines = sprintf("CHS=%d:%d:%d\n", iCylinder, iHead, idSector);
sLines += dumpSector(di, sector, 0);
printf("%s\n", sLines);
idSector++;
}
}
}
if (argv['list']) {
let sLines = "";
let iVolume = +argv['volume'];
if (isNaN(iVolume)) iVolume = -1;
if (argv['list'] == "unused") {
let lba = -1;
while ((lba = di.getUnusedSector(iVolume, lba)) >= 0) {
let sector = di.getSector(lba);
let offset = di.getUnusedSectorData(sector);
sLines += sprintf("\nLBA=%d\n", lba);
/*
* There are two partial sector usage cases: the current sector contains the last N bytes of a file,
* or the sector is COMPLETELY unused (ie, offset is zero). When would a file have a completely unused
* sector? When the disk's cluster size is 2 or more sectors. If a file ends somewhere in the middle
* of a cluster, leaving 1 or more sectors in that cluster unused, we still "flag" all the sectors in
* the cluster as belonging to the file.
*
* This is why we don't differentiate those cases on the basis of whether there's an associated file,
* but simply on whether the offset is zero.
*/
if (offset) {
let iFile = sector[DiskInfo.SECTOR.FILE_INDEX];
device.assert(iFile != undefined);
let file = di.fileTable[iFile];
let cbPartial = file.size - sector[DiskInfo.SECTOR.FILE_OFFSET];
sLines += sprintf("last %d bytes of %s:\n", cbPartial, file.path);
sLines += dumpSector(di, sector, 0, offset);
}
sLines += sprintf("unused %d bytes:\n", di.cbSector - offset);
sLines += dumpSector(di, sector, offset);
}
if (!sLines) sLines = "no unused data space on disk";
} else {
/*
* Other --list options include: "metadata", "sorted"
*/
sLines = di.getFileListing(iVolume, 0, argv['list']) || "\tno listing available\n";
}
printf("%s\n", sLines);
}
if (argv['extract']) {
let extractDir = argv['extdir'];
if (typeof extractDir != "string") {
extractDir = "";
} else {
extractDir = extractDir.replace("%d", path.dirname(diskFile));
}
let manifest = di.getFileManifest(null, false); // pass true for sorted manifest
manifest.forEach(function extractDiskFile(desc) {
/*
* Parse each file descriptor in much the same way that buildFileTableFromJSON() does. That function
* doesn't get the file's CONTENTS, because it's working with the file descriptors that have been stored
* in a JSON file (where CONTENTS would be redundant and a waste of space). Here, we call getFileManifest(),
* which calls getFileDesc(true), which returns a complete file descriptor that includes CONTENTS.
*/
let sPath = desc[DiskInfo.FILEDESC.PATH];
if (sPath[0] == path.sep) sPath = sPath.substr(1); // PATH should ALWAYS start with a slash, but let's be safe
let name = path.basename(sPath);
let size = desc[DiskInfo.FILEDESC.SIZE] || 0;
let attr = +desc[DiskInfo.FILEDESC.ATTR];
/*
* We call parseDate() requesting a *local* date from the timestamp, because that's exactly how we're going
* to use it: as a local file modification time. We used to deal exclusively in UTC dates, unpolluted
* by timezone information, but here we don't really have a choice. Trying to fix the date after the fact,
* by adding Date.getTimezoneOffset(), doesn't always work either, probably due to Daylight Savings Time issues;
* best not to go down that rabbit hole.
*/
let date = device.parseDate(desc[DiskInfo.FILEDESC.DATE], true);
let contents = desc[DiskInfo.FILEDESC.CONTENTS] || [];
let db = new DataBuffer(contents);
device.assert(size == db.length);
let extractFolder = (typeof argv['extract'] != "string")? di.getName() : "";
if (extractFolder || name == argv['extract']) {
let fSuccess = false;
if (argv['collection'] && !extractDir) {
extractFolder = getFullPath(path.join(path.dirname(diskFile), "archive", extractFolder));
if (diskFile.indexOf("/private") == 0 && diskFile.indexOf("/disks") > 0) {
extractFolder = extractFolder.replace("/disks/archive", "/archive");
}
}
extractFile(path.join(extractDir, extractFolder), "", sPath, attr, date, db, argv);
}
});
}
if (argv['manifest']) {
let manifest = di.getFileManifest(getHash, argv['sorted'], argv['metadata']);
printManifest(diskFile, di.getName(), manifest);
}
/*
* If --rewrite, then rewrite the JSON disk image. --overwrite is implicit.
*/
if (argv['rewrite']) {
if (diskFile.endsWith(".json")) {
writeDisk(diskFile, di, argv['legacy'], 0, true, argv['quiet'], undefined, argv['source']);
}
}
/*
* If --checkdisk, then let's load the corresponding archived disk image (.IMG) as well, convert it to JSON,
* load the JSON as a disk image, save it as a temp .IMG, and verify that temp image and archived image are identical.
*
* You must ALSO specify --rebuild if you want the JSON disk image updated as well.
*/
if (argv['checkdisk'] && diskette) {
if (diskette.format) {
let matchFormat = diskette.format.match(/PC([0-9]+)K/);
if (matchFormat) {
let diskSize = di.getSize();
if (+matchFormat[1] * 1024 != diskSize) {
printf("warning: format '%s' does not match disk size (%d) for %s\n", diskette.format, diskSize, diskFile);
}
}
}
/*
* If a JSON disk image was originally built from kryoflux data AND included special args (eg, for copy-protection),
* then don't bother with the rebuild, because those disks can't be saved as IMG disk images.
*/
if (diskFile.endsWith(".json") && !(diskette.kryoflux && diskette.args)) {
if (typeof argv['checkdisk'] == "string" && diskFile.indexOf(argv['checkdisk']) < 0) return;
createDisk(diskFile, diskette, argv, function(diTemp) {
let sTempJSON = path.join(rootDir, "tmp", path.basename(diskFile).replace(/\.[a-z]+$/, "") + ".json");
diTemp.setArgs(sprintf("%s --output %s%s", diskette.command, sTempJSON, diskette.args));
writeDisk(sTempJSON, diTemp, argv['legacy'], 0, true, true, undefined, diskette.source);
let warning = false;
if (diskette.archive.endsWith(".img")) {
let json = diTemp.getJSON();
diTemp.buildDiskFromJSON(json);
let sTempIMG = sTempJSON.replace(".json",".img");
writeDisk(sTempIMG, diTemp, true, 0, true, true, undefined, diskette.source);
if (!compareDisks(sTempIMG, diskette.archive)) {
printf("warning: %s unsuccessfully rebuilt\n", diskette.archive);
warning = true;
} else {
fs.unlinkSync(sTempIMG);
}
}
if (!warning) {
if (argv['rebuild']) {
printf("rebuilding %s\n", diskFile);
fs.renameSync(sTempJSON, getFullPath(diskFile));
} else {
fs.unlinkSync(sTempJSON);
}
}
});
}
}
/*
* If --checkpage, then get the disk's listing and see if it's up-to-date in the website's index.md.
*
* Additionally, if the page doesn't have a machine, add one, tailored to the software's requirements as best we can.
*
* You must ALSO specify --rebuild if you want the index.md updated (or created) as well.
*/
if (argv['checkpage'] && diskette && !diskette.hidden && !diskette.demos) {
/*
* We don't need/want any software pages checked/built for private diskette collections.
*
* The PCSIG08 software pages (originally at /software/pcx86/shareware/pcsig08/ and later moved
* to /software/pcx86/sw/misc/pcsig08/) were hand-generated, so it would take some extra effort
* to automatically rebuild those. However, those pages no longer use their own set of diskette
* images at pcsig8a-disks.pcjs.org and pcsig8b-disks.pcjs.org, and the pages themselves are now
* deprecated in favor of the more complete set of pages at /software/pcx86/sw/misc/pcsig/, so the
* "pcsig8" exception below is a bit moot now.
*/
if (diskFile.indexOf("/private") >= 0 || diskFile.indexOf("/pcsig8") >= 0) return;
if (typeof argv['checkpage'] == "string") {
if (argv['verbose']) printf("checking %s for '%s'...\n", diskFile, argv['checkpage']);
if (diskFile.indexOf(argv['checkpage']) < 0) return;
}
let sListing = di.getFileListing(0, 4);
if (!sListing) return;
let sIndex = "", sIndexNew = "", sAction = "";
let sHeading = "\n### Directory of " + diskette.name + "\n";
let sIndexFile = path.join(path.dirname(diskFile.replace(/\/(disks\/|)(diskettes|gamedisks|miscdisks|harddisks|pcsigdisks|pcsig[0-9a-z-]*-disks|private)\//, "/software/")), "index.md");
if (existsFile(sIndexFile)) {
sIndex = sIndexNew = readFile(sIndexFile);
sAction = "updated";
} else {
if (diskette.title) {
let sTitle = diskette.title;
if (sTitle.match(/[#:[\]{}]/)) {
sTitle = '"' + sTitle + '"';
}
let permalink = path.dirname(diskette.path.replace(/^\/(disks\/|)[^/]+/, "/software")) + path.sep;
sIndexNew = "---\nlayout: page\ntitle: " + sTitle + "\npermalink: " + permalink + "\n---\n";
sIndexNew += sHeading + sListing;
sAction = "created";
}
}
/*
* Step 1: make sure there's a machine present to load/examine/test the software.
*/
let sMachineEmbed = "";
let matchFrontMatter = sIndexNew.match(/^---\n([\s\S]*?\n)---\n/);
if (matchFrontMatter && diskette) {
let sFrontMatter = matchFrontMatter[1];
let matchMachines = sFrontMatter.match(/^machines: *\n([\s\S]*?\n)(\S|$)/m);
if (matchMachines) {
/*
* If this was a generated machine and --rebuild is set, then we'll regenerate it.
*/
if (matchMachines[1].indexOf("autoGen: true") >= 0 && matchMachines[1].indexOf(diskette.name) >= 0 && argv['rebuild']) {
sFrontMatter = sFrontMatter.replace(matchMachines[0], matchMachines[2]);
sIndexNew = sIndexNew.replace(/\n\{% include machine.html .*?%\}\n/, "");
matchMachines = null;
}
}
if (!matchMachines) {
/*
* To add a compatible machine, we look at a few aspects of the diskette itself:
*
* if the diskette format > 360K or any file dates are >= 1986, then a PC AT ("5170") is preferred;
* otherwise, if any file dates are >= 1984, a PC XT ("5160") is preferred;
* otherwise, a PC ("5150") should suffice.
*
* However, a diskette's "version" definition can also include a "@hardware" configuration with "options"
* that supplement or override those initial preferences:
*
* manufacturer, such as "ibm" or "compaq"
* model, such as "5150" or "5160"
* video preference, such as "mda" or "cga"
* memory preference, such "256kb" or "640kb"
* hardware preference, such as "com1" or "mouse"
* operating system (aka boot disk) preference, such as "PC DOS 2.00 (Disk 1)"
*
* Browse diskettes.json for more examples (look for "@hardware" properties).
*
* TODO: Finish support for all of the above preferences (eg, mouse support, serial and parallel ports, etc).
*
* TODO: Consider using the @hardware 'machine' property to allow a specific machine to be used; when that property
* is named 'url' instead, the /_includes/explorer/software.html template uses it to create a hardware_url link for the
* software, but we REALLY prefer having dedicated pages for each piece of software.
*/
let diskSize = di.getSize() / 1024;
let dateNewest = di.getNewestDate(true);
let yearNewest = dateNewest && dateNewest.getFullYear() || 1981;
let hardware = diskette.hardware || {}, options = "";
if (hardware) options = hardware.options || "";
let aOptions = options.split(",");
let findOption = function(aPossibleOptions) {
for (let i = 0; i < aPossibleOptions.length; i++) {
if (!aPossibleOptions[i]) continue;
for (let j = 0; j < aOptions.length; j++) {
if (aOptions[j].indexOf(aPossibleOptions[i]) >= 0) return aOptions[j];
}
}
return aPossibleOptions[0];
};
let findConfig = function(configPath) {
configPath = getFullPath(configPath);
let configPossible;
let aPossibleConfigs = glob.sync(configPath);
let optionMemory = findOption(["kb"]);
for (let i = 0; i < aPossibleConfigs.length; i++) {
let configFile = aPossibleConfigs[i];
if (configFile.indexOf("debugger") > 0 || configFile.indexOf("array") > 0) continue;
configPossible = configFile.substr(rootDir.length);
if (configFile.indexOf(optionMemory) >= 0) break;
}
return configPossible;
};
/*
* Now that we have all the raw inputs ("ingredients"), let's toss some defaults together.
*/
let sAutoGen = " autoGen: true\n";
let sAutoType = hardware.autoType;
if (sAutoType == undefined) sAutoType = diskette.autoType;
let manufacturer = findOption(["ibm","compaq"]);
let sDefaultIBMModel = diskSize > 360 || yearNewest >= 1986? "5170" : (yearNewest >= 1984? "5160" : "5150");
let sDefaultCOMPAQModel = diskSize > 360 || yearNewest >= 1986? "deskpro386" : "portable";
let model = findOption({
"ibm": [sDefaultIBMModel, "5150","5160","5170"],
"compaq": [sDefaultCOMPAQModel, "portable","deskpro386"]
}[manufacturer]);
let video = findOption(["*","mda","cga","ega","vga","vdu"]);
let configFile = hardware.config || findConfig("/machines/pcx86/" + manufacturer + '/' + model + '/' + video + "/**/machine.xml");
if (configFile == "none") configFile = "";
if (configFile) {
let bootDisk = findOption(["", "DOS"]);
let demoDisk = diskette.name;
let sDiskettes = "";
let diskMatch = diskFile.match(/\/pcsig\/([0-9])[0-9]+-/);
if (diskMatch) {
sDiskettes = " diskettes: /machines/pcx86/diskettes.json,/disks/pcsigdisks/pcx86/diskettes.json\n";
}
if (diskette.bootable) {
bootDisk = demoDisk;
demoDisk = "";
} else {
if (sAutoType == undefined) sAutoType = "$date\\r$time\\rB:\\rDIR\\r";
}
let sMachineID = (model.length <= 4? manufacturer : "") + model;
let sMachine = " - id: " + sMachineID + "\n type: pcx86\n config: " + configFile + "\n";
for (let prop in hardware) {
if (prop == "autoType" || prop == "config" || prop == "machine" || prop == "options" || prop == "url" || prop[0] == '@') continue;
let chQuote = "";
if (prop == "drives" || prop == "floppyDrives") {
chQuote = "'";
if (prop == "drives") bootDisk = "None";
sAutoType = "";
}
sMachine += " " + prop + ": " + chQuote + hardware[prop] + chQuote + "\n";
}
if (bootDisk) bootDisk = " A: \"" + bootDisk + "\"\n";
if (demoDisk) demoDisk = " B: \"" + demoDisk + "\"\n";
let sAutoMount = " autoMount:\n" + bootDisk + demoDisk;
if (sAutoType) sAutoType = " autoType: " + sAutoType + "\n";
sFrontMatter += "machines:\n" + sMachine + sDiskettes + sAutoGen + sAutoMount + (sAutoType || "");
sIndexNew = sIndexNew.replace(matchFrontMatter[1], sFrontMatter);
sMachineEmbed = "\n{% include machine.html id=\"" + sMachineID + "\" %}\n";
}
}