This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathdiskdump.js
3885 lines (3670 loc) · 164 KB
/
diskdump.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 Converts disk images to/from JSON
* @author <a href="mailto:[email protected]">Jeff Parsons</a> (@jeffpar)
* @copyright © 2012-2020 Jeff Parsons
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* PCjs is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* PCjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCjs. If not,
* see <http://www.gnu.org/licenses/gpl.html>.
*
* You are required to include the above copyright notice in every modified copy of this work
* and to display that copyright notice when the software starts running; see COPYRIGHT in
* <https://www.pcjs.org/modules/shared/lib/defines.js>.
*
* Some PCjs files also attempt to load external resource files, such as character-image files,
* ROM files, and disk image files. Those external resource files are not considered part of PCjs
* for purposes of the GNU General Public License, and the author does not claim any copyright
* as to their contents.
*/
/*
* See http://en.wikipedia.org/wiki/Design_of_the_FAT_file_system for more information.
*/
"use strict";
if (typeof module != "undefined") { // we can't simply test for NODE, since defines.js hasn't been loaded yet
var NODE = true;
var fs = require("fs");
var path = require("path");
var glob = require("glob");
var http = require("http");
var mkdirp = require("mkdirp");
var crypto = require("crypto");
var defines = require("../../shared/lib/defines");
var net = require("../../shared/lib/netlib");
var proc = require("../../shared/lib/proclib");
var str = require("../../shared/lib/strlib");
var usr = require("../../shared/lib/usrlib");
var web = require("../../shared/lib/weblib");
var DiskAPI = require("../../shared/lib/diskapi");
var DumpAPI = require("../../shared/lib/dumpapi");
var X86 = require("../../pcx86/lib/x86");
/**
* @class exports
* @property {string} name
* @property {string} version
*/
var pkg = require("../../../package.json");
}
/*
* fConsole controls console messages; it is false by default but is enable by the CLI interface.
*/
var fConsole = false;
/*
* fDebug controls debug console messages; it is false by default but can be enabled from the command-line
* using "--debug".
*/
var fDebug = false;
/*
* logFile is passed from the web server through HTMLOut to us, allowing us to "mingle" our logConsole()
* output with the server's log (typically "./logs/node.log").
*/
var logFile = null;
/*
* fNormalize attempts to enforce consistency across multiple dump requests, including the order of files within every
* directory, the use of hard-coded volume label timestamps, replacement of line-endings in text files, etc. It can be
* turned on here or with the experimental "--normalize" command-line option.
*/
var fNormalize = false;
/**
* BufferPF(init, start, end)
*
* BufferPF is our browser polyfill (hence the PF) for Node's Buffer class. It's basically a wrapper object
* containing a real Buffer in Node and a simulated buffer in the browser.
*
* This is NOT a general-purpose polyfill. It supports only those Buffer constructor calls and methods that the
* DiskDump module actually requires.
*
* The constructor supports initialization with: 1) a number specifying the buffer length in bytes, 2) a string,
* 3) an array of byte-sized numbers (aka octets), or 4) another BufferPF, but only when ALSO specifying start and end
* parameters; this final variation is used to support the slice() method.
*
* Finally, under Node, if an API gives us a real Buffer, we need a way to create a BufferPF from it, so that's handled
* as a special NODE case.
*
* @constructor
* @param {number|string|Array|BufferPF|Buffer} [init]
* @param {number} [start]
* @param {number} [end]
*/
function BufferPF(init, start, end)
{
if (NODE) {
if (start === undefined) {
if (typeof init == "object" && init instanceof Buffer) {
this.buf = init;
}
else {
/*
* The following code replaces the now-deprecated code:
*
* this.buf = new Buffer(init);
*/
if (typeof init == "number") {
this.buf = Buffer.alloc(init);
}
else {
this.buf = Buffer.from(init);
}
}
} else {
this.buf = init.buf.slice(start, end);
}
this.length = this.buf.length;
}
else if (typeof init == "number") {
this.ab = new ArrayBuffer(init);
this.dv = new DataView(this.ab, 0, init);
this.length = init;
}
else if (start === undefined) {
let off;
this.ab = new ArrayBuffer(init.length);
this.dv = new DataView(this.ab, 0, init.length);
if (typeof init != "string") {
for (off = 0; off < init.length; off++) {
this.dv.setUint8(off, init[off]);
}
} else {
for (off = 0; off < init.length; off++) {
this.dv.setUint8(off, init.charCodeAt(off));
}
}
this.length = init.length;
} else {
this.ab = init.ab;
if (end === undefined) end = this.ab.length;
this.dv = new DataView(this.ab, start, this.length = end - start);
}
}
/**
* fill(b)
*
* @this {BufferPF}
* @param {number} b
*/
BufferPF.prototype.fill = function(b)
{
if (NODE) {
this.buf.fill(b);
} else {
for (let off = 0; off < this.length; off++) {
this.dv.setUint8(off, b);
}
}
};
/**
* write(s, off, len)
*
* @this {BufferPF}
* @param {string} s
* @param {number} off
* @param {number} len
*/
BufferPF.prototype.write = function(s, off, len)
{
if (NODE) {
this.buf.write(s, off, len);
} else {
let i = 0;
while (off < this.length) {
this.dv.setUint8(off, s.charCodeAt(i++));
off++;
}
}
};
/**
* readUInt8(b)
*
* @this {BufferPF}
* @param {number} off
* @return {number}
*/
BufferPF.prototype.readUInt8 = function(off)
{
return (NODE? this.buf.readUInt8(off) : this.dv.getUint8(off));
};
/**
* writeUInt8(b, off)
*
* @this {BufferPF}
* @param {number} b
* @param {number} off
*/
BufferPF.prototype.writeUInt8 = function(b, off)
{
if (NODE) {
this.buf.writeUInt8(b, off);
} else {
this.dv.setUint8(off, b);
}
};
/**
* readUInt16BE(off)
*
* @this {BufferPF}
* @param {number} off
* @return {number}
*/
BufferPF.prototype.readUInt16BE = function(off)
{
return (NODE? this.buf.readUInt16BE(off) : this.dv.getUint16(off));
};
/**
* readUInt16LE(off)
*
* @this {BufferPF}
* @param {number} off
* @return {number}
*/
BufferPF.prototype.readUInt16LE = function(off)
{
return (NODE? this.buf.readUInt16LE(off) : this.dv.getUint16(off, true));
};
/**
* readUInt32BE(off)
*
* @this {BufferPF}
* @param {number} off
* @return {number}
*/
BufferPF.prototype.readUInt32BE = function(off)
{
return (NODE? this.buf.readUInt32BE(off) : this.dv.getUint32(off));
};
/**
* readUInt32LE(off)
*
* @this {BufferPF}
* @param {number} off
* @return {number}
*/
BufferPF.prototype.readUInt32LE = function(off)
{
return (NODE? this.buf.readUInt32LE(off) : this.dv.getUint32(off, true));
};
/**
* readInt32BE(off)
*
* @this {BufferPF}
* @param {number} off
* @return {number}
*/
BufferPF.prototype.readInt32BE = function(off)
{
return (NODE? this.buf.readInt32BE(off) : this.dv.getInt32(off));
};
/**
* readInt32LE(off)
*
* @this {BufferPF}
* @param {number} off
* @return {number}
*/
BufferPF.prototype.readInt32LE = function(off)
{
return (NODE? this.buf.readInt32LE(off) : this.dv.getInt32(off, true));
};
/**
* writeInt32LE(dw, off)
*
* @this {BufferPF}
* @param {number} dw
* @param {number} off
*/
BufferPF.prototype.writeInt32LE = function(dw, off)
{
if (NODE) {
this.buf.writeInt32LE(dw, off);
} else {
this.dv.setInt32(off, dw, true);
}
};
/**
* copy(bufTarget, offTarget)
*
* @this {BufferPF}
* @param {BufferPF} bufTarget
* @param {number} offTarget
*/
BufferPF.prototype.copy = function(bufTarget, offTarget)
{
if (NODE) {
this.buf.copy(bufTarget.buf, offTarget);
} else {
let offMax = this.length;
let cbMax = bufTarget.length - offTarget;
if (offMax > cbMax) offMax = cbMax;
for (let off = 0; off < offMax; off++) {
bufTarget.writeUInt8(this.readUInt8(off), offTarget + off);
}
}
};
/**
* slice(start, end)
*
* @this {BufferPF}
* @param {number} [start]
* @param {number} [end]
* @return {BufferPF}
*/
BufferPF.prototype.slice = function(start, end)
{
return new BufferPF(this, start || 0, end);
};
/**
* toString(format)
*
* @this {BufferPF}
* @param {string} [format]
* @return {string}
*/
BufferPF.prototype.toString = function(format)
{
if (NODE) {
return this.buf.toString(format);
} else {
return ""; // TODO: Implement; see also: encodeAsBase64()
}
};
/**
* DiskDump()
*
* TODO: If sServerRoot is set, make sure sDiskPath refers to something in either /apps/ or /disks-demo/,
* to prevent random enumeration of other server resources.
*
* @constructor
* @param {string|Array} sDiskPath
* @param {Array|null} [asExclude] contains filename exclusions, if any
* @param {string} [sFormat] is the output format, one of "json"|"data"|"hex"|"bytes"|"img"
* @param {boolean|string} [fComments] enables comments and other readability enhancements in the JSON output
* @param {string} [sSize] specifies a target disk size, in kilobytes, when building a new image
* @param {string|null} [sServerRoot]
* @param {string} [sManifestFile]
* @param {Object} [argv] optional (experimental) arguments, if any
*/
function DiskDump(sDiskPath, asExclude, sFormat, fComments, sSize, sServerRoot, sManifestFile, argv)
{
this.argv = argv || {};
this.sDiskPath = sDiskPath;
this.sServerRoot = sServerRoot || "";
if (this.sServerRoot && !net.isRemote(sDiskPath) && sDiskPath[0] == '/' && sDiskPath.indexOf(';') < 0) {
this.sDiskPath = path.join(this.sServerRoot, sDiskPath);
}
this.asExclude = asExclude || DiskDump.asExclusions;
this.kbTarget = sSize|0; // convert the numeric string to a 32-bit number (or 0 if invalid)
this.sFormat = (sFormat || DumpAPI.FORMAT.JSON);
this.fJSONNative = (this.sFormat == DumpAPI.FORMAT.JSON && !fComments);
this.nJSONIndent = 0;
this.fJSONComments = fComments;
this.sJSONWhitespace = (this.fJSONComments? " " : "");
this.fXDFSupport = this.argv['xdf'];
/*
* Specifying a label of "none" will suppress volume LABEL generation as well as ARCHIVE
* file attributes for normal files; this is useful when generating PC DOS 1.x-compatible
* disk images (ie, 160K disks for PC DOS 1.00 or 320K disks for PC DOS 1.10), because PC
* DOS 1.x understands neither the LABEL nor the ARCHIVE attribute bits (in fact, PC DOS 1.x
* CHKDSK misinterprets the ARCHIVE bit, treating it as if the HIDDEN bit was set instead).
*/
this.sLabel = this.argv['label'];
this.forceBPB = this.argv['forceBPB'];
this.fNormalize = fNormalize || this.argv['normalize'];
/*
* The dump operation itself doesn't care about sManifestFile, but we DO need some indication
* of whether MD5 checksums need to be computed for the individual files, so we use the filename
* as that indication.
*/
this.sManifestFile = sManifestFile;
/*
* If we have to enumerate one or more files during the buildImage() process, this array
* will save them, in case the caller wants to query that information later, in updateManifest().
*
* Originally, I thought each saved entry would be a subset of what the FileInfo objects contain,
* but it turns out I pretty much need everything. This, in turn, means that some of the original
* buildImage() functions could simply use this.aManifestInfo, instead of their own aFiles array,
* but sometimes they're using aFiles of subdirectories, so it's not quite that simple.
*/
this.aManifestInfo = [];
/*
* bufDisk is set by buildImage() (or by loadFile() if the file is NOT a ".json" file; otherwise
* loadFile() loads the file as string data and stores it in jsonDisk).
*
* In those cases where bufDisk is set, the caller must call convertToJSON() to obtain JSON, which
* will simply return jsonDisk if it was already set by loadFile() OR if it was already created by
* a previous convertToJSON() call.
*
* In those cases where jsonDisk is set, the caller must call convertToIMG() to obtain an IMG file.
* Since that function relies on dataDisk, it first calls JSON.parse() to convert jsonDisk to dataDisk,
* and then it builds bufDisk from dataDisk; if a previous call already created dataDisk and/or bufDisk,
* the previous values are used/returned.
*
* dataDisk is a native data object built by convertToJSON() and convertToIMG() as needed. In the
* first case, it's used to create JSON using JSON.stringify(), but only if fJSONNative is set (ie,
* the caller explicitly specifies FORMAT_JSON); that probably should be the default setting, but it
* wasn't an option in the original PHP code, so I added it as an option here in order to compare the
* output of both methods. fJSONNative still isn't an option for converting OSI disk images to JSON
* (and it may never be, as those images aren't very common).
*/
this.bufDisk = null;
this.jsonDisk = "";
this.dataDisk = undefined;
}
/**
* setLogFile(file)
*
* @param {Object} file
*/
DiskDump.setLogFile = function(file) {
logFile = file;
};
/*
* Class constants
*/
DiskDump.sAPIURL = "http://www.pcjs.org" + DumpAPI.ENDPOINT;
DiskDump.sCopyright = COPYRIGHT;
DiskDump.sNotice = DiskDump.sAPIURL + " " + DiskDump.sCopyright;
DiskDump.sUsage = "Usage: " + DiskDump.sAPIURL + "?" + DumpAPI.QUERY.PATH + "={url}&" + DumpAPI.QUERY.FORMAT + "=json|data|hex|bytes|img";
/*
* PCJS_LABEL is our default label, used whenever a more suitable label (eg, the disk image's folder name)
* is not available or not supplied, and PCJS_OEM is inserted into any DiskDump-generated diskette images.
*/
DiskDump.PCJS_LABEL = "PCJS";
DiskDump.PCJS_OEM = "PCJS.ORG";
/**
* The BPBs that buildImage() currently supports; these BPBs should be in order of smallest to largest capacity,
* to help ensure we don't select a disk format larger than necessary.
*/
DiskDump.aDefaultBPBs = [
[ // define BPB for 160Kb diskette
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x20, 0x31, 0x2E, 0x30, // "IBM 1.0" (this is a fake OEM signature)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x01, // 0x0D: sectors per cluster (1)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0x40, 0x00, // 0x11: root directory entries (0x40 or 64) 0x40 * 0x20 = 0x800 (1 sector is 0x200 bytes, total of 4 sectors)
0x40, 0x01, // 0x13: number of sectors (0x140 or 320)
0xFE, // 0x15: media ID (eg, 0xFF: 320Kb, 0xFE: 160Kb, 0xFD: 360Kb, 0xFC: 180Kb)
0x01, 0x00, // 0x16: sectors per FAT (1)
0x08, 0x00, // 0x18: sectors per track (8)
0x01, 0x00, // 0x1A: number of heads (1)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
[ // define BPB for 320Kb diskette
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x20, 0x31, 0x2E, 0x30, // "IBM 1.0" (this is a real OEM signature)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x02, // 0x0D: sectors per cluster (2)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0x70, 0x00, // 0x11: root directory entries (0x70 or 112) 0x70 * 0x20 = 0xE00 (1 sector is 0x200 bytes, total of 7 sectors)
0x80, 0x02, // 0x13: number of sectors (0x280 or 640)
0xFF, // 0x15: media ID (eg, 0xFF: 320Kb, 0xFE: 160Kb, 0xFD: 360Kb, 0xFC: 180Kb)
0x01, 0x00, // 0x16: sectors per FAT (1)
0x08, 0x00, // 0x18: sectors per track (8)
0x02, 0x00, // 0x1A: number of heads (2)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
[ // define BPB for 180Kb diskette
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x20, 0x32, 0x2E, 0x30, // "IBM 2.0" (this is a fake OEM signature)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x01, // 0x0D: sectors per cluster (1)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0x40, 0x00, // 0x11: root directory entries (0x40 or 64) 0x40 * 0x20 = 0x800 (1 sector is 0x200 bytes, total of 4 sectors)
0x68, 0x01, // 0x13: number of sectors (0x168 or 360)
0xFC, // 0x15: media ID (eg, 0xFF: 320Kb, 0xFE: 160Kb, 0xFD: 360Kb, 0xFC: 180Kb)
0x02, 0x00, // 0x16: sectors per FAT (2)
0x09, 0x00, // 0x18: sectors per track (9)
0x01, 0x00, // 0x1A: number of heads (1)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
[ // define BPB for 360Kb diskette
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x20, 0x32, 0x2E, 0x30, // "IBM 2.0" (this is a real OEM signature)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x02, // 0x0D: sectors per cluster (2)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0x70, 0x00, // 0x11: root directory entries (0x70 or 112) 0x70 * 0x20 = 0xE00 (1 sector is 0x200 bytes, total of 7 sectors)
0xD0, 0x02, // 0x13: number of sectors (0x2D0 or 720)
0xFD, // 0x15: media ID (eg, 0xFF: 320Kb, 0xFE: 160Kb, 0xFD: 360Kb, 0xFC: 180Kb)
0x02, 0x00, // 0x16: sectors per FAT (2)
0x09, 0x00, // 0x18: sectors per track (9)
0x02, 0x00, // 0x1A: number of heads (2)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
[ // define BPB for 1.2Mb diskette
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x31, 0x30, 0x2E, 0x31, // "10.0" (which I believe was used on IBM OS/2 1.0 diskettes)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x01, // 0x0D: sectors per cluster (1)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0xE0, 0x00, // 0x11: root directory entries (0xe0 or 224) 0xe0 * 0x20 = 0x1c00 (1 sector is 0x200 bytes, total of 14 sectors)
0x60, 0x09, // 0x13: number of sectors (0x960 or 2400)
0xF9, // 0x15: media ID (0xF9 was used for 1228800-byte diskettes, and later for 737280-byte diskettes)
0x07, 0x00, // 0x16: sectors per FAT (7)
0x0f, 0x00, // 0x18: sectors per track (15)
0x02, 0x00, // 0x1A: number of heads (2)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
[ // define BPB for 720Kb diskette (2 sector/cluster format more commonly used)
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x20, 0x35, 0x2E, 0x30, // "IBM 5.0" (this is a real OEM signature)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x02, // 0x0D: sectors per cluster (2)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0x70, 0x00, // 0x11: root directory entries (0x70 or 112) 0x70 * 0x20 = 0xE00 (1 sector is 0x200 bytes, total of 7 sectors)
0xA0, 0x05, // 0x13: number of sectors (0x5A0 or 1440)
0xF9, // 0x15: media ID
0x03, 0x00, // 0x16: sectors per FAT (3)
0x09, 0x00, // 0x18: sectors per track (9)
0x02, 0x00, // 0x1A: number of heads (2)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
[ // define BPB for 720Kb diskette (1 sector/cluster format used by PC DOS 4.01)
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x20, 0x34, 0x2E, 0x30, // "IBM 4.0" (this is a real OEM signature)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x01, // 0x0D: sectors per cluster (1)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0x70, 0x00, // 0x11: root directory entries (0x70 or 112) 0x70 * 0x20 = 0xE00 (1 sector is 0x200 bytes, total of 7 sectors)
0xA0, 0x05, // 0x13: number of sectors (0x5A0 or 1440)
0xF9, // 0x15: media ID
0x05, 0x00, // 0x16: sectors per FAT (5)
0x09, 0x00, // 0x18: sectors per track (9)
0x02, 0x00, // 0x1A: number of heads (2)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
[ // define BPB for 1.44Mb diskette
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x4d, 0x53, 0x44, 0x4F, 0x53, 0x35, 0x2E, 0x30, // "MSDOS5.0" (an actual OEM signature, arbitrarily chosen for use here)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x01, // 0x0D: sectors per cluster (1)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0xE0, 0x00, // 0x11: root directory entries (0xe0 or 224) 0xe0 * 0x20 = 0x1c00 (1 sector is 0x200 bytes, total of 14 sectors)
0x40, 0x0B, // 0x13: number of sectors (0xb40 or 2880)
0xF0, // 0x15: media ID (0xF0 was used for 1474560-byte diskettes)
0x09, 0x00, // 0x16: sectors per FAT (9)
0x12, 0x00, // 0x18: sectors per track (18)
0x02, 0x00, // 0x1A: number of heads (2)
0x00, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
],
/*
* Here's some useful background information on a 10Mb PC XT fixed disk, partitioned with a single DOS partition.
*
* The BPB for a 10Mb "type 3" PC XT hard disk specifies 0x5103 or 20739 for TOTAL_SECS, which is the partition
* size in sectors (10,618,368 bytes), whereas total disk size is 20808 sectors (10,653,696 bytes). The partition
* is 69 sectors smaller than the disk because the first sector is reserved for the MBR and 68 sectors (the entire
* last cylinder) are reserved for diagnostics, head parking, etc. This cylinder usage is confirmed by FDISK,
* which reports that 305 cylinders (not 306) are assigned to the DOS partition.
*
* That 69-sector overhead is NOT overhead incurred by the FAT file system. The FAT overhead is the boot sector
* (1), FAT sectors (2 * 8), and root directory sectors (32), for a total of 49 sectors, leaving 20739 - 49 or
* 20690 sectors. Moreover, free space is measured in clusters, not sectors, and the partition uses 8 sectors/cluster,
* leaving room for 2586.25 clusters. Since a fractional cluster is not allowed, another 2 sectors are lost, for
* a total of 51 sectors of FAT overhead. So actual free space is (20739 - 51) * 512, or 10,592,256 bytes -- which
* is exactly what is reported as the available space on a freshly formatted 10Mb PC XT fixed disk.
*
* Some sources on the internet (eg, http://www.wikiwand.com/en/Timeline_of_DOS_operating_systems) claim that the
* file system overhead for the XT's 10Mb disk is "50 sectors". As they explain:
*
* "The fixed disk has 10,618,880 bytes of raw space: 305 cylinders (the equivalent of tracks) × 2 platters
* × 2 sides or heads per platter × 17 sectors per track = 20,740 sectors × 512 bytes per sector = 10,618,880
* bytes...."
*
* and:
*
* "With DOS the only partition, the combined overhead is 50 sectors leaving 10,592,256 bytes for user data:
* DOS's FAT is eight sectors (16 sectors for two copies) + 32 sectors for the root directory, room for 512
* directory entries + 2 sectors (one master and one DOS boot sector) = 50 sectors...."
*
* However, that's incorrect. First, the disk has 306 cylinders, not 305. Second, there are TWO overhead values:
* the overhead OUTSIDE the partition (69 sectors) and the overhead INSIDE the partition (51 sectors). They failed
* to account for the reserved cylinder in the first calculation and the fractional cluster in the second calculation,
* and then they conflated the two values to produce a single (incorrect) result.
*
* Even if one were to assume that the disk had only 305 cylinders, that would only change the partitioning overhead
* to 1 sector; the FAT file system overhead would still be 51 sectors.
*/
[ // define BPB for 10Mb hard drive
0xEB, 0xFE, 0x90, // 0x00: JMP instruction, following by 8-byte OEM signature
0x50, 0x43, 0x4A, 0x53, 0x2E, 0x4F, 0x52, 0x47, // PCJS_OEM
// 0x49, 0x42, 0x4D, 0x20, 0x20, 0x32, 0x2E, 0x30, // "IBM 2.0" (this is a real OEM signature)
0x00, 0x02, // 0x0B: bytes per sector (0x200 or 512)
0x08, // 0x0D: sectors per cluster (8)
0x01, 0x00, // 0x0E: reserved sectors; ie, # sectors preceding the first FAT--usually just the boot sector (1)
0x02, // 0x10: FAT copies (2)
0x00, 0x02, // 0x11: root directory entries (0x200 or 512) 0x200 * 0x20 = 0x4000 (1 sector is 0x200 bytes, total of 0x20 or 32 sectors)
0x03, 0x51, // 0x13: number of sectors (0x5103 or 20739; * 512 bytes/sector = 10,618,368 bytes = 10,369Kb = 10Mb)
0xF8, // 0x15: media ID (eg, 0xF8: hard drive w/FAT12)
0x08, 0x00, // 0x16: sectors per FAT (8)
//
// Wikipedia (http://en.wikipedia.org/wiki/File_Allocation_Table#BIOS_Parameter_Block) implies everything past
// this point was introduced post-DOS 2.0. However, DOS 2.0 merely said they were optional, and in fact, DOS 2.0
// FORMAT always initializes the next 3 words. A 4th word, LARGE_SECS, was added in DOS 3.20 at offset 0x1E,
// and then in DOS 3.31, both HIDDEN_SECS and LARGE_SECS were widened from words to dwords.
//
0x11, 0x00, // 0x18: sectors per track (17)
0x04, 0x00, // 0x1A: number of heads (4)
//
// PC DOS 2.0 actually stored 0x01, 0x00, 0x80, 0x00 here, so you can't rely on more than the first word.
// TODO: Investigate PC DOS 2.0 BPB behavior (ie, what did the 0x80 mean)?
//
0x01, 0x00, 0x00, 0x00 // 0x1C: number of hidden sectors (always 0 for non-partitioned media)
]
];
DiskDump.asExclusions = [".*", ".IMG"];
/*
* 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 isASCII() on all
* these file contents first.
*/
DiskDump.asTextFileExts = [".MD", ".ME", ".BAS", ".BAT", ".ASM", ".LRF", ".MAK", ".TXT", ".XML"];
/*
* Class methods
*/
/**
* CLI()
*
* Provides the command-line interface for the diskdump module.
*
* Usage:
*
* diskdump --dir={directory} [--format=json|data|hex|bytes|img] [--comments] [--output={file}]
* diskdump --disk={disk image} [--format=json|data|hex|bytes|img] [--comments] [--output={file}]
* diskdump --path={file[;file]...} [--format=json|data|hex|bytes|img] [--comments] [--output={file}]
*
* NOTE: --img is permitted as an alias for --disk
*
* Arguments:
*
* The default format is "json", which generates an array of signed 32-bit decimal values; "hex" is an older
* text format that consists entirely of 2-character hex values (deprecated), and "bytes" is a JSON-like format
* that also uses hex values (but with "0x" prefixes) and is normally used only when comments are enabled.
*
* Note that command-line arguments, if any, are not validated. For example, argv['comments'] may be any of
* boolean, string, or undefined, since the user may have typed "--comments" or "--comments=foo" or nothing at all.
*
* Additional command-line arguments include:
*
* --mbhd={number}: requests a hard drive image with the given number of megabytes (DEPRECATED)
* --size={number}: requests a target disk size with the given number of kilobytes (eg, 360, 720, 1200, 1440, 10000)
* --exclude={filename}: specifies a filename that should be excluded from the image; repeat as often as needed
* --overwrite: allows the --output option to overwrite an existing file; default is to NOT overwrite
* --manifest[={filename}]: update the specified manifest.xml file with details about the disk image
* --xdf: enable support for XDF-formatted disk images (experimental)
*
* Examples:
*
* node modules/diskdump/bin/diskdump --disk=../pcjs/disks/pcx86/games/infocom/zork1/zork1.dsk
* node modules/diskdump/bin/diskdump --dir=./apps/pcx86/1981/visicalc/ --format=img --output=./apps/pcx86/1981/visicalc/disk.img
* node modules/diskdump/bin/diskdump --path=./apps/pcx86/1981/visicalc/bin/vc.com;../README.md --format=json --output=./apps/pcx86/1981/visicalc/disk.json
*/
DiskDump.CLI = function()
{
let err = null;
let args = proc.getArgs();
fConsole = true;
if (args.argc) {
let argv = args.argv;
if (argv['debug'] !== undefined) fDebug = argv['debug'];
if (fDebug) {
DiskDump.logConsole("cwd: " + process.cwd());
DiskDump.logConsole("args: " + JSON.stringify(argv));
}
let sDiskPath = null;
let sServerRoot = process.cwd();
let i = sServerRoot.indexOf("/pcjs/");
sServerRoot = i > 0? sServerRoot.substr(0, i+5) : undefined;
let sDir = argv['dir'], sDisk = (argv['disk'] || argv['img']), sPath = argv['path'];
if (typeof sDir == "string") {
sDiskPath = sDir;
}
else if (typeof sDisk == "string") {
sDiskPath = sDisk;
}
else if (typeof sPath == "string") {
sDiskPath = sPath;
}
let asExclude = argv['exclude'];
if (asExclude && typeof asExclude == "string") asExclude = [asExclude];
/*
* Create some sensible defaults for --manifest and --output when no values are specified
*/
let sManifestFile = argv['manifest'];
if (typeof sManifestFile == "boolean") {
sManifestFile = "manifest.xml";
}
if (sManifestFile && sManifestFile.charAt(0) != '/') {
sManifestFile = path.join(process.cwd(), sManifestFile);
}
let sOutput = "";
let sOutputFile = argv['output'];
if (typeof sOutputFile == "string" && sOutputFile.lastIndexOf('.') < 0) {
sOutput = sOutputFile;
sOutputFile = true;
}
if (typeof sOutputFile == "boolean") {
if (sDir || sDisk) {
sOutput = path.join(sOutput, path.basename(sDir || sDisk));
let i = sOutput.lastIndexOf('.');
if (i > 0) sOutput = sOutput.substr(0, i);
} else {
sOutput = "disk";
}
sOutputFile = sOutput + '.' + argv['format'];
}
if (sOutputFile && sOutputFile.charAt(0) != '/') sOutputFile = path.join(process.cwd(), sOutputFile);
let fOverwrite = argv['overwrite'];
let sManifestTitle = argv['title'];
if (sDiskPath) {
let sSize = argv['mbhd'];
if (!sSize) {
sSize = argv['size'];
} else {
sSize = (sSize * 1000).toString();
}
let disk = new DiskDump(sDiskPath, asExclude, argv['format'], argv['comments'], sSize, sServerRoot, sManifestFile, argv);
if (sDir) {
disk.buildImage(true, function(err) {
DiskDump.outputDisk(err, disk, sDiskPath, sOutputFile, fOverwrite, sManifestTitle);
});
}
else if (sDisk) {
disk.loadFile(function(err) {
DiskDump.outputDisk(err, disk, sDiskPath, sOutputFile, fOverwrite, sManifestTitle);
});
}
else if (sPath) {
disk.buildImage(false, function(err) {
DiskDump.outputDisk(err, disk, sDiskPath, sOutputFile, fOverwrite, sManifestTitle);
});
}
} else {
err = new Error("no dir|disk|path specified");
}
}
else {
DiskDump.logConsole("usage: diskdump --dir={dir}|--disk={disk}|--path={file}[;{file}...] [--format=json|data|hex|bytes|img] [--comments] [--output={file}] [--manifest={file}] [--xdf]");
}
if (err) {
DiskDump.logError(err);
process.exit(1);
}
};
/**
* API
*
* Client-side version of the web-based server-side function HTTPAPI.processDumpAPI(req, res).
*
* @param {Object} aParms (analogous to req.query on the server)
*/
DiskDump.API = function(aParms)
{
let sDisk = aParms[DumpAPI.QUERY.DISK];
let sFormat = aParms[DumpAPI.QUERY.FORMAT] || DumpAPI.FORMAT.JSON;
let fComments = (!!aParms[DumpAPI.QUERY.COMMENTS]);
if (sDisk) {
let disk = new DiskDump(sDisk, null, sFormat, fComments);
disk.loadFile(function(err) {
if (!err) {
let sData, sType, fBase64;
if (sFormat == DumpAPI.FORMAT.IMG) {
sType = "octet-stream";
let buf = disk.convertToIMG();
if (buf) {
sData = disk.encodeAsBase64(buf);
fBase64 = true;
}
} else {
sType = "json";
sData = disk.convertToJSON();
}
if (sData) {
let sFileName = str.getBaseName(disk.sDiskPath, true) + '.' + sFormat;
let sAlert = web.downloadFile(sData, sType, fBase64, sFileName);
web.alertUser(sAlert);
} else {
web.alertUser("No data.");
}
} else {
web.alertUser(err.message);
}
});
}
else if (aParms[DumpAPI.QUERY.DIR] || aParms[DumpAPI.QUERY.PATH] || aParms[DumpAPI.QUERY.FILE]) {
/*
* The web-based client-side API currently supports DISK requests only (eg, no DIR, PATH, or FILE requests).
*/
web.alertUser("Unsupported API request.");
}
};
/**
* outputDisk(err, disk, sDiskPath, sOutputFile, fOverwrite, sManifestTitle)
*
* @param {Error} err
* @param {DiskDump} disk
* @param {string} sDiskPath
* @param {string} sOutputFile
* @param {boolean} fOverwrite
* @param {string} [sManifestTitle]
*/
DiskDump.outputDisk = function(err, disk, sDiskPath, sOutputFile, fOverwrite, sManifestTitle)
{
if (!err) {
/*
* The caller may have built an image (or loaded an IMG file), in which case
* bufDisk will be set (otherwise, jsonDisk will be set). We then look for pending
* conversions: if a disk image was built/loaded, but the requested format was not,
* call convertToJSON(). Similarly, if bufDisk is not set and a raw image was
* requested, call convertToIMG().
*/
let data = disk.bufDisk;
if (data) {
if (disk.sFormat != DumpAPI.FORMAT.IMG) {
data = disk.convertToJSON();
}
} else {
if (disk.sFormat == DumpAPI.FORMAT.IMG) {
data = disk.convertToIMG();
}
}
if (data) {
let cbDisk = (disk.bufDisk? disk.bufDisk.length : data.length);
if (sOutputFile) {
let fUnchanged;
let md5Disk = disk.hashDisk, md5JSON = null;
if (disk.sManifestFile) {
if (typeof data == "string") {
md5JSON = crypto.createHash('md5').update(data).digest('hex');
}
if (!md5Disk && disk.bufDisk) {
let buf = disk.bufDisk.buf || disk.bufDisk;
md5Disk = crypto.createHash('md5').update(buf).digest('hex');
}
/*
* Before calling updateManifest(), see if we have any aManifestInfo entries, and if not, see if
* there's a folder that the original files have been "dumped" into, from which we can create those
* entries...
*/
disk.buildManifestInfo(sDiskPath);
fUnchanged = DiskDump.updateManifest(disk, disk.sManifestFile, sDiskPath, sOutputFile, true, sManifestTitle, md5Disk, md5JSON);
}
try {
if (fUnchanged) {
DiskDump.logConsole(sOutputFile + " unchanged");
} else {
if (fs.existsSync(sOutputFile) && !fOverwrite) {
DiskDump.logConsole(sOutputFile + " exists, use --overwrite to rewrite");
} else {
let sDirName = path.dirname(sOutputFile);
if (!fs.existsSync(sDirName)) mkdirp.sync(sDirName);
fs.writeFileSync(sOutputFile, data.buf || data);
DiskDump.logConsole(cbDisk + "-byte disk image saved as " + sOutputFile);
}
}
} catch(e) {
err = e;
}
} else {
/*
* We'll dump JSON to the console, but not a raw disk buffer; we could add an option to
* "stringify" buffers, but if that's what the caller wants, they should use "--format=json".
*/
if (typeof data === "string") {
DiskDump.logConsole(data);
} else {
DiskDump.logConsole("specify --output={file} to save " + cbDisk + "-byte disk image");
}
}
} else {
err = new Error("unable to convert " + disk.sDiskPath);
}
}
if (err) {
DiskDump.logError(err);
process.exit(1);
}
};
/**
* getManifestAttr(sID, sTag)
*
* @param sID
* @param sTag
* @return {string|null}
*/
DiskDump.getManifestAttr = function(sID, sTag)
{
let match = sTag.match(new RegExp(sID + '="([^"]*)"'));
if (match) return match[1];
return null;
};
/**
* updateManifest(disk, sManifestFile, sDiskPath, sOutputFile, fOverwrite, sTitle, md5Disk, md5JSON)
*
* This function reports a change if EITHER the md5Disk value does not match the original
* "md5" value recorded in the manifest OR the manifest itself has changed. If md5JSON is
* also provided, we require that to match as well.
*
* Since this function is for command-line use only, we use *Sync functions, so that we can
* return the results immediately.
*
* @param {DiskDump} disk
* @param {string} sManifestFile
* @param {string} sDiskPath
* @param {string} sOutputFile
* @param {boolean} fOverwrite
* @param {string} [sTitle]
* @param {string} [md5Disk] for the entire disk image
* @param {string} [md5JSON] for the entire JSON-encoded disk image, if any
* @return {boolean|undefined} true if disk has changed, false if not, undefined if unknown
*/
DiskDump.updateManifest = function(disk, sManifestFile, sDiskPath, sOutputFile, fOverwrite, sTitle, md5Disk, md5JSON)