-
Notifications
You must be signed in to change notification settings - Fork 0
/
VMSBackupProcess.py
executable file
·1490 lines (984 loc) · 52.5 KB
/
VMSBackupProcess.py
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
import VMSBackupRAMCache
import VMSBackupTypes
import VMSBackupHelper
import BBHeader
import BRHeader
import BSFileHeader
import os
import sys
import fnmatch
import datetime
import math
import struct
# Calculate these once globally rather than recomputing each time when needed.
__LINESEP = bytes([ord(k) for k in os.linesep])
__LINESEP_WINDOWS = bytes([ord(k) for k in "\r\n"])
__CR = ord('\r')
__LF = ord('\n')
def FileNameWildCardCompare(kString : str, kWildCard : str) :
# [] are frequently used in OpenVMS filenames, but to fnmatch, indicate ranges.
# Since we're only dealing with filenames, and the rest basically works, we can
# mitigate the issue somewhat.
kString = kString.replace ("[", "<").replace("]", ">")
kWildCard = kWildCard.replace("[", "<").replace("]", ">")
return fnmatch.fnmatch(name=kString, pat=kWildCard)
#end
def VMSWriteEOL(kFileMetaData : VMSBackupTypes.VMSFileParameters, bForceEOL : bool = False) :
if VMSBackupTypes.ExtractMode.ASCII == kFileMetaData.kMode :
if (kFileMetaData.nFilePointer >= kFileMetaData.nFileSize) and kFileMetaData.bLFDetected :
kFileMetaData.kFileHandle.write(__LINESEP)
kFileMetaData.bLFDetected = False
elif bForceEOL :
kFileMetaData.kFileHandle.write(__LINESEP)
#end
#end
#end
def VMSWriteFile(kBlock : bytes, kFileMetaData : VMSBackupTypes.VMSFileParameters, nDataLength : int) :
bLastElementWasLFCR = False
bContainsLFCR = False
# TODO: This is covering up a bug elsewhere where 0 byte writes are somehow being passed onwards...
if 0 == nDataLength :
return
#end
if VMSBackupTypes.ExtractMode.ASCII == kFileMetaData.kMode :
# Note: To improve throughput, ASCII Mode doesn't iterate one character at a time, and
# instead finds all indices which contain the line seperators. This allows burst
# writing of everything in between. This does improve average write time at the
# expense of some additional complexity.
kIndicesOfInterest = [i for i,k in enumerate(kBlock[:nDataLength]) if k in __LINESEP_WINDOWS]
if 0 == len(kIndicesOfInterest) :
# This would fall into functionality associated with:
# (__LF != kBlock[nCRLFIndex]) and kFileMetaData.bLFDetected :
if kFileMetaData.bLFDetected :
# This is not seen as a valid EOL, so normalise it
kFileMetaData.kFileHandle.write(__LINESEP)
#end
kFileMetaData.bLFDetected = False
kFileMetaData.bLastElementWasLFCR = False
kFileMetaData.kFileHandle.write(kBlock[:nDataLength])
return
#end
# File I/O Typically likes being performed in large bursts, therefore we buffer the data
# into RAM first.
kBytes = bytearray()
nLastIndex = 0
for nCRLFIndex in kIndicesOfInterest :
if nCRLFIndex > nLastIndex :
# This would fall into functionality associated with:
# (__LF != kBlock[nCRLFIndex]) and kFileMetaData.bLFDetected :
if kFileMetaData.bLFDetected :
# This is not seen as a valid EOL, so normalise it
kBytes.extend(__LINESEP)
#end
kFileMetaData.bLFDetected = False
kFileMetaData.bLastElementWasLFCR = False
kBytes.extend(kBlock[nLastIndex:nCRLFIndex])
#end
if __CR == kBlock[nCRLFIndex] and not kFileMetaData.bLFDetected :
# Do nothing whilst the EOL is assessed
kFileMetaData.bLFDetected = True
# Indicate this data package contains an LF/CR entry
bContainsLFCR = True
bLastElementWasLFCR = (nCRLFIndex+1) == nDataLength
elif (__LF == kBlock[nCRLFIndex]) and kFileMetaData.bLFDetected :
# This file already contains standard EOL conventions
kBytes += __LINESEP
kFileMetaData.bLFDetected = False
# Indicate this data package contains an LF/CR entry
bContainsLFCR = True
bLastElementWasLFCR = (nCRLFIndex+1) == nDataLength
elif (__LF == kBlock[nCRLFIndex]) and not kFileMetaData.bLFDetected :
# This is not seen as a valid EOL, so normalise it
kBytes += __LINESEP
kFileMetaData.bLFDetected = False
# Indicate this data package contains an LF/CR entry
bContainsLFCR = True
bLastElementWasLFCR = (nCRLFIndex+1) == nDataLength
elif (__LF != kBlock[nCRLFIndex]) and kFileMetaData.bLFDetected :
# This is not seen as a valid EOL, so normalise it
kBytes += __LINESEP
kFileMetaData.bLFDetected = False
# Indicate this data package contains an LF/CR entry
bContainsLFCR = True
# Note: This indicates the *previous* byte was an LF/CR therefore the current
# element isn't, hence no check to see if the Last Element is an LF/CR
# Output the current byte since it contained non-EOL data
kBytes.append(kBlock[nCRLFIndex])
else :
# Shouldn't Occur
assert(False)
#end
nLastIndex = nCRLFIndex + 1
#end
# Handle the Last Few Elements
if nLastIndex < nDataLength :
# This would fall into functionality associated with:
# (__LF != kBlock[nCRLFIndex]) and kFileMetaData.bLFDetected :
if kFileMetaData.bLFDetected :
# This is not seen as a valid EOL, so normalise it
kBytes.extend(__LINESEP)
#end
kFileMetaData.bLFDetected = False
kFileMetaData.bLastElementWasLFCR = False
kBytes.extend(kBlock[nLastIndex:nDataLength])
#end
# Output the Buffered Data for Writing
if len(kBytes) > 0 :
kFileMetaData.kFileHandle.write(kBytes)
#end
else :
kFileMetaData.kFileHandle.write(kBlock[:nDataLength])
#end
kFileMetaData.bContainsLFCR = bContainsLFCR
kFileMetaData.bLastElementWasLFCR = bLastElementWasLFCR
#end
def CloseOpenFiles(kExtractStatus : dict) :
kFileMetaData = kExtractStatus["Current"]
if None != kFileMetaData :
if None != kFileMetaData.kFileHandle :
if kFileMetaData.nFilePointer != kFileMetaData.nFileSize :
print(f"Warning: {kFileMetaData.kFileName} extracted {kFileMetaData.nFilePointer}/{kFileMetaData.nFileSize} bytes.")
#end
# assert(kFileMetaData.nFilePointer == kFileMetaData.nFileSize)
kFileMetaData.closeFile()
#end
kExtractStatus["Current"] = None
#end
#end
# TODO: This works for the 1st Jan 1970 Epoch, however, I really need to determine the time functions
# don't actually mandate this, for example, the national instruments time functions actually used
# a different epoch last time I used them, as such, this needs to calculate the true offset between
# the VMS Time Epoch and the used Unix Epoch, however, 1st Jan 1970 is ubiquitous enough that this
# should be correct for most people.
def TimeVMSToUnix(nVMSTime : int) -> int :
return (nVMSTime - 0x07c95674beb4000) // 10000000
#end
def DecodeTimeAndDate (nVMSTime : int, nSubSecondResolution : int) -> str :
##########################################################
# Constants
MONTH = ["JAN", "FEB", "MAR", "APR",
"MAY", "JUN", "JUL", "AUG",
"SEP", "OCT", "NOV", "DEC"]
##########################################################
# Variables
# Open VMS Time is a 64 Bit value representing 100ns tics since 00:00 November 17, 1858
# (Modified Julian Day Zero)
# http://h71000.www7.hp.com/wizard/wiz_2315.html
# C Time Stamp is a 32 Bit value representing seconds since January 1 1970
if 0 == nVMSTime :
return "<None Specified>"
else :
# Convert time to GM Time
nUnixTime = TimeVMSToUnix(nVMSTime)
kGMTTime = datetime.datetime.fromtimestamp(nUnixTime, tz=datetime.timezone.utc)
# Configure the Common Part of the Date String
kDateString = f"{kGMTTime.day}-{MONTH[kGMTTime.month-1]}-{kGMTTime.year} {kGMTTime.hour:02}:{kGMTTime.minute:02}:{kGMTTime.second:02}"
if 0 == nSubSecondResolution :
# Output the Date/Time to match the Open VMS directory listing
return kDateString
else :
# The above algorithm will only have a resolution of seconds, therefore
# extra processing is required in order to get milliseconds
# VMS Time has an LSB of 100ns
# Convert to Hundredths of a Second
nTimeSubSeconds = int((nVMSTime % 10000000) // math.pow(10, 7 - nSubSecondResolution))
return kDateString + f".{nTimeSubSeconds:02}"
#end
#end
#end
def DecodeFileProtection(nValue : int) -> str :
kReturnString = ""
if 0 == (nValue & 0x1) : kReturnString += "R"
if 0 == (nValue & 0x2) : kReturnString += "W"
if 0 == (nValue & 0x4) : kReturnString += "E"
if 0 == (nValue & 0x8) : kReturnString += "D"
return kReturnString
#end
def DecodeRecordFormat(nValue : int, nSize : int) -> str :
nValue = nValue & 0xF
if BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_UDF == nValue :
return ""
elif BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_FIX == nValue :
return "Fixed length 512 byte records"
elif BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_VAR == nValue :
return "Variable length" + (f", maximum {nSize} bytes" if (0 != nSize) else "")
elif BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_VFC == nValue :
return "VFC, 2 byte header" + (f", maximum {nSize} bytes" if (0 != nSize) else "")
elif BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_STM == nValue :
return "Stream" + (f", maximum {nSize} bytes" if (0 != nSize) else "")
elif BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_STMLF == nValue :
return "Stream_LF" + (f", maximum {nSize} bytes" if (0 != nSize) else "")
elif BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_STMCR == nValue :
return "Stream_CR" + (f", maximum {nSize} bytes" if (0 != nSize) else "")
#end
return ""
#end
def DecodeRecordAttributes(nValue : int, bFirstPass : bool) -> str :
if BSFileHeader.BSFileHeader.RecordAttributeType.RECORD_ATTRIBUTE_FTN == nValue :
return "None"
elif BSFileHeader.BSFileHeader.RecordAttributeType.RECORD_ATTRIBUTE_CR == nValue :
return ""
elif BSFileHeader.BSFileHeader.RecordAttributeType.RECORD_ATTRIBUTE_CRN == nValue :
return "Carriage return carriage control"
elif BSFileHeader.BSFileHeader.RecordAttributeType.RECORD_ATTRIBUTE_BLK == nValue :
return ""
elif BSFileHeader.BSFileHeader.RecordAttributeType.RECORD_ATTRIBUTE_PRN == nValue :
return "Print file carriage control"
elif not bFirstPass :
return f"WARNING : Unknown attribute {nValue}"
#end
return ""
#end
def DumpHeader(kHeader : BBHeader.BBHeader, kOptions : VMSBackupTypes.VMSBackupParameters) :
print(f"Save set: {kHeader.T_SSNAME()}")
print(f"Block size: {kHeader.L_BLOCKSIZE()}")
print("")
#end
def DumpBriefFileHeader(kFileHeader : BSFileHeader.BSFileHeader, nSubSecondResolution : int) :
# Output the File Name
print(f"{kFileHeader.FILENAME()}")
# Output the File Size
kRECATTR = kFileHeader.RECATTR(kSizeOf=VMSBackupHelper.sizeof.uint16_t)
if kRECATTR[6] == 0 :
print(f" Size: {kRECATTR[5] - 1:7}/{kFileHeader.FILESIZE():<7}", end="")
else :
print(f" Size: {kRECATTR[5]:7}/{kFileHeader.FILESIZE():<7}", end="")
#end
# Output the Creation Date
print(f" Created: {DecodeTimeAndDate(nVMSTime=kFileHeader.CREDATE(), nSubSecondResolution=nSubSecondResolution)}")
#end
def DumpFullFileHeader(kFileHeader : BSFileHeader.BSFileHeader, kHeader : BRHeader.BRHeader, bFirstPass : bool) :
# TO BE CLEANED
# Change False to True to have the output format match a directory /full syntax, otherwise it will
# match a backup set view.
if True :
##########################################################
# Dump the Full File Header (Directory Format)
# Output the File Name
print(f"{kFileHeader.FILENAME()}", end="")
# Output the File Id
print(f" File ID: ({kFileHeader.FID()[0]},{kFileHeader.FID()[1]},{kFileHeader.FID()[2] - 1})")
# Output the File Size
kRECATTR = kFileHeader.RECATTR(kSizeOf=VMSBackupHelper.sizeof.uint16_t)
if kRECATTR[6] == 0 :
print(f"Size: {(kRECATTR[5] - 1):12}/{kFileHeader.FILESIZE():<12}", end="")
else :
print(f"Size: {kRECATTR[5]:12}/{kFileHeader.FILESIZE():<12}", end="")
#end
# Output the Owner
print(f"Owner: [{kFileHeader.UIC()[1]:06o},{kFileHeader.UIC()[0]:06o}]")
# Output the Creation Date
print(f"Created: {DecodeTimeAndDate(nVMSTime=kFileHeader.CREDATE(), nSubSecondResolution=2)}")
# Output the Revised Date
print(f"Revised: {DecodeTimeAndDate(nVMSTime=kFileHeader.REVDATE(), nSubSecondResolution=2)} ({kFileHeader.REVISION()})")
# Output the Expiry Date
print(f"Expires: {DecodeTimeAndDate(nVMSTime=kFileHeader.EXPDATE(), nSubSecondResolution=2)}")
# Output the Backup Date
print(f"Backup: {DecodeTimeAndDate(nVMSTime=kFileHeader.BAKDATE(), nSubSecondResolution=2)}")
# Output File Organisation
# TODO: Not enough data collated to determine other enumerations
print("File organization: ", end="")
if not kHeader.V_NONSEQUENTIAL() :
print("Sequential")
else :
print("????")
#end
# File Attributes
print("File attributes: ", end="")
# File Attributes - Allocation
print(f"Allocation: {kFileHeader.FILESIZE()}", end="")
# File Attributes - Extend
# TODO: No Idea, always 0
print(", Extend: 0", end="")
# File Attributes - Global Buffer Count
# TODO: No Idea, always 0
print(", Global Buffer Count: 0", end="")
# File Attributes - , Version Limit
print(f", Version limit: {kFileHeader.VERLIMIT()}", end="")
# File Attributes - ????
# TODO: No Idea, sometimes ", Contiguous-best-try", the check below seems to
# work for test data
if 32 == kFileHeader.UCHAR()[0] :
print(", Contiguous best try")
else :
print("")
#end
# Record Format
print(f" Record format: {DecodeRecordFormat(nValue=kFileHeader.RECATTR()[0], nSize=kFileHeader.RECSIZE())}")
# Record Attributes
print(f" Record attributes: {DecodeRecordAttributes(nValue=kFileHeader.RECATTR()[1], bFirstPass=bFirstPass)}")
# Output File Protection
print(" File protection: ", end="")
print(f"System:{DecodeFileProtection(nValue=kFileHeader.FPRO()[0])}", end="")
print(f", Owner:{DecodeFileProtection(nValue=kFileHeader.FPRO()[0] >> 4)}", end="")
print(f", Group:{DecodeFileProtection(nValue=kFileHeader.FPRO()[1])}", end="")
print(f", World:{DecodeFileProtection(nValue=kFileHeader.FPRO()[1] >> 4)}", end="")
print("")
else :
DumpBriefFileHeader(kFileHeader=kFileHeader, nSubSecondResolution=0)
# Output the Owner
print(f" Owner: [{kFileHeader.UIC()[1]:06o},{kFileHeader.UIC()[0]:06o}] ", end="")
# Output the Revised Date
print(f"Revised: {DecodeTimeAndDate(nVMSTime=kFileHeader.REVDATE(), nSubSecondResolution=0)} ({kFileHeader.REVISION()})")
# Output the File Id
# Note : As a quirk, we actually cut the string if it's too wide
print(" File ID: " + f"({kFileHeader.FID()[0]},{kFileHeader.FID()[1]},{kFileHeader.FID()[2] - 1}) "[:14], end="")
# Output the Expiry Date
print(f" Expires: {DecodeTimeAndDate(nVMSTime=kFileHeader.EXPDATE(), nSubSecondResolution=0)}")
# Output the Backup Date
print(f" Backup: {DecodeTimeAndDate(nVMSTime=kFileHeader.BAKDATE(), nSubSecondResolution=0)}")
# Output File Protection
print(" File protection: ", end="")
print(f"System:{DecodeFileProtection(nValue=kFileHeader.FPRO()[0])}", end="")
print(f", Owner:{DecodeFileProtection(nValue=kFileHeader.FPRO()[0] >> 4)}", end="")
print(f", Group:{DecodeFileProtection(nValue=kFileHeader.FPRO()[1])}", end="")
print(f", World:{DecodeFileProtection(nValue=kFileHeader.FPRO()[1] >> 4)}", end="")
print("")
# Output File Organisation
# TODO: Not enough data collated to determine other enumerations
print(" File organization: ", end="")
if not kHeader.V_NONSEQUENTIAL() :
print("Sequential")
else :
print("????")
#end
# File Attributes
print(" File attributes: ", end="")
# File Attributes - Allocation
print(f"Allocation = {kFileHeader.FILESIZE()}", end="")
# File Attributes - Extend
# TODO: No Idea, always 0
print(", Extend = 0")
# File Attributes - Global Buffer Count
# TODO: No Idea, always 0
print(" Global Buffer Count = 0", end="")
# File Attributes - ????
# TODO: No Idea, sometimes ", Contiguous-best-try", the check below seems to
# work for test data
if 32 == kFileHeader.UCHAR()[0] :
print(", Contiguous best try")
else :
print("")
#end
# Record Format
print(f" Record format: {DecodeRecordFormat(nValue=kFileHeader.RECATTR()[0], nSize=kFileHeader.RECSIZE())}")
# Record Attributes
print(f" Record attributes: {DecodeRecordAttributes(nValue=kFileHeader.RECATTR()[1], bFirstPass=bFirstPass)}")
#end
#end
def DumpCSVFileHeader(kFileHeader : BSFileHeader.BSFileHeader, kHeader : BRHeader.BRHeader, bFirstPass : bool) :
# Output the File Name
print(f"\"{kFileHeader.FILENAME()}\",", end="")
# Output the File Size
kRECATTR = kFileHeader.RECATTR(kSizeOf=VMSBackupHelper.sizeof.uint16_t)
if kRECATTR[6] == 0 :
print(f"{(kRECATTR[5] - 1)},{kFileHeader.FILESIZE()},", end="")
else :
print(f"{(kRECATTR[5] - 0)},{kFileHeader.FILESIZE()},", end="")
#end
# Output the Creation Date
print(f"\"{DecodeTimeAndDate(nVMSTime=kFileHeader.CREDATE(), nSubSecondResolution=7)}\",", end="")
# Output the Owner
print(f"{kFileHeader.UIC()[1]:06o},{kFileHeader.UIC()[0]:06o},", end="")
# Output the Revised Date
print(f"\"{DecodeTimeAndDate(nVMSTime=kFileHeader.REVDATE(), nSubSecondResolution=7)}\",{kFileHeader.REVISION()},", end="")
# Output the File Id
print(f"{kFileHeader.FID()[0]},{kFileHeader.FID()[1]},{kFileHeader.FID()[2]},", end="")
# Output the Expiry Date
print(f"\"{DecodeTimeAndDate(nVMSTime=kFileHeader.EXPDATE(), nSubSecondResolution=7)}\",", end="")
# Output the Backup Date
print(f"\"{DecodeTimeAndDate(nVMSTime=kFileHeader.BAKDATE(), nSubSecondResolution=7)}\",", end="")
# Output File Protection
print(f"\"{DecodeFileProtection(nValue=kFileHeader.FPRO()[0] )}\",", end="")
print(f"\"{DecodeFileProtection(nValue=kFileHeader.FPRO()[0] >> 4)}\",", end="")
print(f"\"{DecodeFileProtection(nValue=kFileHeader.FPRO()[1] )}\",", end="")
print(f"\"{DecodeFileProtection(nValue=kFileHeader.FPRO()[1] >> 4)}\",", end="")
# Output File Organisation
# TODO: Not enough data collated to determine other enumerations
if not kHeader.V_NONSEQUENTIAL() :
print("Sequential,", end="")
else :
print("????,", end="")
#end
# File Attributes
# File Attributes - Allocation
print(f"{kFileHeader.FILESIZE()},", end="")
# File Attributes - Extend
# TODO: No Idea, always 0
print("0,", end="")
# File Attributes - Global Buffer Count
# TODO: No Idea, always 0
print("0,", end="")
# File Attributes - ????
# TODO: No Idea, sometimes ", Contiguous-best-try", the check below seems to
# work for test data
if 32 == kFileHeader.UCHAR()[0] :
print("Contiguous best try,", end="")
else :
print(",", end="")
#end
# Record Format
print(f"\"{DecodeRecordFormat(nValue=kFileHeader.RECATTR()[0], nSize=kFileHeader.RECSIZE())}\",", end="")
# Record Attributes
print(f"\"{DecodeRecordAttributes(nValue=kFileHeader.RECATTR()[1], bFirstPass=bFirstPass)}\"", end="")
print("")
#end
def SetNewerFile(kFileName : str, nFileVersion : int, kFileList : dict) :
if kFileName not in kFileList :
# By Default this must be the latest version
kFileList[kFileName] = {"Version" : nFileVersion}
else :
# Determine if this is a later version
if nFileVersion >= kFileList[kFileName]["Version"] :
kFileList[kFileName]["Version"] = nFileVersion
#end
#end
#end
def IsTargetFile(kFileName : str, nFileVersion : int, nTargetExtractVersion : int, kFileList : dict) -> bool :
assert(kFileName in kFileList)
# None represents "*"
if None == nTargetExtractVersion :
return True
else :
# Determine if this version is correct
if nTargetExtractVersion > 0 :
# Version must be exact
return nTargetExtractVersion == nFileVersion
else :
# This is a relative version
# So ;0 means it must be the latest version
# ;-1 means it must be the version prior to the latest
# etc.
return (kFileList[kFileName]["Version"] + nTargetExtractVersion) == nFileVersion
#end
#end
#end
def VMSBackupProcessFile(kBlock : bytes, kHeader : BRHeader.BRHeader, kOptions : VMSBackupTypes.VMSBackupParameters, kFileList : dict, kExtractStatus : dict, bFirstPass : bool) :
##########################################################
# Convert the File Record into a series of streams
kFileHeader = BSFileHeader.BSFileHeader()
kFileHeader.LoadHeaderFromBuffer(kBlock=kBlock, nRSize=kHeader.W_RSIZE())
# Copy the File Name
kFileNameNoMask = kFileHeader.FILENAME()
# Strip the Version Delimiter if required
nFileVersion = 0
if ";" in kFileNameNoMask :
nSemiPos = kFileNameNoMask.find(";")
nFileVersion = int(kFileNameNoMask[nSemiPos+1:])
kFileNameNoMask = kFileNameNoMask[:nSemiPos]
#end
# See if this is a file that needs processing
bWildCardMatch = FileNameWildCardCompare(kString=kFileNameNoMask, kWildCard=kOptions.kExtractMask)
##########################################################
# Handle Older Versions
if bWildCardMatch :
SetNewerFile(kFileName=kFileNameNoMask, nFileVersion=nFileVersion, kFileList=kFileList)
bTargetFile = IsTargetFile(kFileName=kFileNameNoMask, nFileVersion=nFileVersion, nTargetExtractVersion=kOptions.nExtractVersion, kFileList=kFileList)
else :
bTargetFile = False
#end
# Add the Filename to the List to Process
if kFileHeader.FILENAME() not in kFileList :
# Add the Raw File Parameters to the List
# TODO: RECATTR[0] occasionally has a value outside the range defined by RecordFormatType. I've mitigated it for now by masking
# the lower nibble, but I've no way of knowing if this is accurate for the time being.
kFileList[kFileHeader.FILENAME()] = VMSBackupTypes.VMSFileParameters(bIsTargetFile=bTargetFile, kMode=kOptions.eExtractMode)
kFileList[kFileHeader.FILENAME()].setFileMetaData(nFileSize=kFileHeader.FILESIZEBYTES(), kFormat=kFileHeader.RECATTR()[0] & 0x0F)
#end
##########################################################
# Handle Data Extraction if required
if kOptions.bExtract :
if bTargetFile :
# Initialise the File Type
if (VMSBackupTypes.ExtractMode.SMART == kOptions.eExtractMode) and bFirstPass and bTargetFile :
##########################################################
# DEBUG (ENHANCED)
if VMSBackupTypes.ExtractDebug.ENHANCED == kOptions.eExtractDebug :
print("*** DEBUG *** ", end="")
print(f"Beginning smart parse for {kFileHeader.FILENAME()}")
#end
# DEBUG (ENHANCED)
##########################################################
elif bTargetFile :
##########################################################
# DEBUG (ENHANCED)
if VMSBackupTypes.ExtractDebug.ENHANCED == kOptions.eExtractDebug :
print("*** DEBUG *** ", end="")
print(f"Beginning parse/extract for {kFileHeader.FILENAME()}")
#end
# DEBUG (ENHANCED)
##########################################################
#end
# Close any open files
CloseOpenFiles(kExtractStatus=kExtractStatus)
# Set the Current Item of Interest
kExtractStatus["Current"] = kFileList[kFileHeader.FILENAME()]
# If this is not the first pass (or we're in single pass mode)
if not bFirstPass and bTargetFile :
# DEBUG (ENHANCED)
##########################################################
# Open the File for Writing
kExtractStatus["Current"].openFile(kFileName=kFileHeader.FILENAME(), kOptions=kOptions, nCreationDate=TimeVMSToUnix(nVMSTime=kFileHeader.CREDATE()), nModificationDate=TimeVMSToUnix(nVMSTime=kFileHeader.REVDATE()))
##########################################################
# DEBUG (ENHANCED)
if VMSBackupTypes.ExtractDebug.ENHANCED == kOptions.eExtractDebug :
print("*** DEBUG *** ", end="")
print(f"Using {[None, "ASCII", "BINARY", "RAW"][kExtractStatus["Current"].kMode]} for {kFileHeader.FILENAME()}")
#end
#end
#end
#end
##########################################################
# Dump the contents of the File Record
if not bFirstPass and bWildCardMatch and bTargetFile :
if VMSBackupTypes.OutputType.BRIEF == kOptions.eOutputType :
DumpBriefFileHeader(kFileHeader=kFileHeader, nSubSecondResolution=2)
elif VMSBackupTypes.OutputType.FULL == kOptions.eOutputType :
DumpFullFileHeader(kFileHeader=kFileHeader, kHeader=kHeader, bFirstPass=bFirstPass)
elif VMSBackupTypes.OutputType.CSV == kOptions.eOutputType :
DumpCSVFileHeader(kFileHeader=kFileHeader, kHeader=kHeader, bFirstPass=bFirstPass)
#end
#end
#end
def ProcessVBNRaw(kBlock : bytes, kHeader : BRHeader.BRHeader, kFileMetaData : VMSBackupTypes.VMSFileParameters, kOptions : VMSBackupTypes.VMSBackupParameters, bFirstPass : bool) :
if (kFileMetaData.nFilePointer + kHeader.W_RSIZE()) < kFileMetaData.nFileSize :
VMSWriteFile(kBlock=kBlock, kFileMetaData=kFileMetaData, nDataLength=kHeader.W_RSIZE())
kFileMetaData.nFilePointer += kHeader.W_RSIZE()
else :
VMSWriteFile(kBlock=kBlock, kFileMetaData=kFileMetaData, nDataLength=kFileMetaData.nFileSize - kFileMetaData.nFilePointer)
kFileMetaData.nFilePointer += kFileMetaData.nFileSize - kFileMetaData.nFilePointer
#end
#end
def ProcessVBNNonVar(kBlock : bytes, kHeader : BRHeader.BRHeader, kFileMetaData : VMSBackupTypes.VMSFileParameters, kOptions : VMSBackupTypes.VMSBackupParameters, bFirstPass : bool) :
if (kFileMetaData.nFilePointer + kHeader.W_RSIZE()) < kFileMetaData.nFileSize :
if None == kFileMetaData.kFileHandle :
if VMSBackupTypes.ExtractMode.SMART == kFileMetaData.kMode :
for nRecordPointer in range(kHeader.W_RSIZE()) :
if kBlock[nRecordPointer] > 0x7F :
kFileMetaData.kMode = VMSBackupTypes.ExtractMode.BINARY
kFileMetaData.bIgnoreVBN = True
break
#end
#end
#end
else :
VMSWriteFile(kBlock=kBlock, kFileMetaData=kFileMetaData, nDataLength=kHeader.W_RSIZE())
#end
kFileMetaData.nFilePointer += kHeader.W_RSIZE()
else :
if None == kFileMetaData.kFileHandle :
if VMSBackupTypes.ExtractMode.SMART == kFileMetaData.kMode :
for nRecordPointer in range(kFileMetaData.nFileSize - kFileMetaData.nFilePointer) :
if kBlock[nRecordPointer] > 0x7F :
kFileMetaData.kMode = VMSBackupTypes.ExtractMode.BINARY
kFileMetaData.bIgnoreVBN = True
break
#end
#end
#end
else :
VMSWriteFile(kBlock=kBlock, kFileMetaData=kFileMetaData, nDataLength=kFileMetaData.nFileSize - kFileMetaData.nFilePointer)
kFileMetaData.nFilePointer += (kFileMetaData.nFileSize - kFileMetaData.nFilePointer)
VMSWriteEOL(kFileMetaData=kFileMetaData)
#end
#end
#end
def ProcessVBNVar(kBlock : bytes, kHeader : BRHeader.BRHeader, kFileMetaData : VMSBackupTypes.VMSFileParameters, kOptions : VMSBackupTypes.VMSBackupParameters, bFirstPass : bool) :
kFileMetaData.bLastElementWasLFCR = False
kFileMetaData.bContainsLFCR = False
bSkipHeader = BSFileHeader.BSFileHeader.RecordFormatType.RECORD_FORMAT_VFC == kFileMetaData.kFormat
if bSkipHeader :
nRecordLengthModifier = 2
else :
nRecordLengthModifier = 0
#end
# Set the Starting Position of the Record and shift the file pointer
# (this handles the scenario whereby a header might span a record
# but not actually contain any length data)
nRecordPointer = kFileMetaData.nRemainingStartPos
kFileMetaData.nFilePointer += kFileMetaData.nRemainingStartPos
# First Pass requires the file to be scanned as long as it's deemed an ASCII file
if kFileMetaData.nRemainingRecordLength > 0 :
if bFirstPass :
for nLocalRecordPointer in range(kFileMetaData.nRemainingStartPos, kFileMetaData.nRemainingRecordLength) :
if nLocalRecordPointer >= kHeader.W_RSIZE() :
kFileMetaData.nRemainingStartPos = 0
kFileMetaData.nRemainingRecordLength -= nLocalRecordPointer
return
#end
if VMSBackupTypes.ExtractMode.SMART == kFileMetaData.kMode :
if kBlock[nLocalRecordPointer] > 0x7F :
kFileMetaData.kMode = VMSBackupTypes.ExtractMode.BINARY
break
#end
#end
#end
nRecordPointer += kFileMetaData.nRemainingRecordLength
else :
# TODO: Probably a bug elsewhere, but sanity check an overflow of the record
if (nRecordPointer + kFileMetaData.nRemainingRecordLength) >= kHeader.W_RSIZE() :
VMSWriteFile(kBlock=kBlock[nRecordPointer:], kFileMetaData=kFileMetaData, nDataLength=kHeader.W_RSIZE() - nRecordPointer)
kFileMetaData.nRemainingStartPos = 0
kFileMetaData.nRemainingRecordLength -= kHeader.W_RSIZE() - nRecordPointer
kFileMetaData.nFilePointer += kHeader.W_RSIZE() - nRecordPointer
nRecordPointer += kHeader.W_RSIZE() - nRecordPointer
# Record Pointers aren't allowed to finish on an odd byte
if 0 != (nRecordPointer % 2) :
kFileMetaData.nFilePointer += 1
#end
return
#end
# Write File
VMSWriteFile(kBlock=kBlock[nRecordPointer:], kFileMetaData=kFileMetaData, nDataLength=kFileMetaData.nRemainingRecordLength)
nRecordPointer += kFileMetaData.nRemainingRecordLength
#end
kFileMetaData.nFilePointer += kFileMetaData.nRemainingRecordLength
kFileMetaData.nRemainingStartPos = 0
kFileMetaData.nRemainingRecordLength = 0
# Record Pointers aren't allowed to finish on an odd byte
if 0 != (nRecordPointer % 2) :
nRecordPointer += 1
kFileMetaData.nFilePointer += 1
#end
if None != kFileMetaData.kFileHandle :
VMSWriteEOL(kFileMetaData=kFileMetaData, bForceEOL=not kFileMetaData.bLastElementWasLFCR)
#end
#end
# Reset the Remaining Start Position
kFileMetaData.nRemainingStartPos = 0
while (nRecordPointer < kHeader.W_RSIZE()) and (kFileMetaData.nFilePointer < kFileMetaData.nFileSize) :
nRecordLength = struct.unpack_from(VMSBackupHelper.kUnpackType[VMSBackupHelper.sizeof.uint16_t.name], kBlock, nRecordPointer)[0] - nRecordLengthModifier
nRecordPointer += 2 + nRecordLengthModifier
# TODO: .DIR 'files' always seem to have 0xFFFF followed by a whole lot of nothing. I've mitigated this for now by writing this as
# data , but I've no test data to verify this.
if 0xFFFF == nRecordLength :
kFileMetaData.nFilePointer += 2
continue
#end
if nRecordPointer <= kHeader.W_RSIZE() :
if (nRecordPointer + nRecordLength) >= kHeader.W_RSIZE() :
kFileMetaData.nRemainingStartPos = 0
kFileMetaData.nRemainingRecordLength = nRecordLength
nRecordLength = kHeader.W_RSIZE() - nRecordPointer
kFileMetaData.nRemainingRecordLength = kFileMetaData.nRemainingRecordLength - nRecordLength
#end
if None == kFileMetaData.kFileHandle :
# First Pass requires the file to be scanned as long as it's deemed an ASCII file
for nLocalRecordPointer in range(nRecordPointer, nRecordPointer + nRecordLength) :
if VMSBackupTypes.ExtractMode.SMART == kFileMetaData.kMode :
if kBlock[nLocalRecordPointer] > 0x7F :
kFileMetaData.kMode = VMSBackupTypes.ExtractMode.BINARY
kFileMetaData.bIgnoreVBN = True
break
#end
#end
#end
nRecordPointer += nRecordLength
else :
# Write File
VMSWriteFile(kBlock=kBlock[nRecordPointer:], kFileMetaData=kFileMetaData, nDataLength=nRecordLength)
nRecordPointer += nRecordLength
#end