-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathTarHeader.cs
More file actions
1320 lines (1139 loc) · 36.3 KB
/
TarHeader.cs
File metadata and controls
1320 lines (1139 loc) · 36.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Buffers;
using System.Text;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// This class encapsulates the Tar Entry Header used in Tar Archives.
/// The class also holds a number of tar constants, used mostly in headers.
/// </summary>
/// <remarks>
/// The tar format and its POSIX successor PAX have a long history which makes for compatability
/// issues when creating and reading files.
///
/// This is further complicated by a large number of programs with variations on formats
/// One common issue is the handling of names longer than 100 characters.
/// GNU style long names are currently supported.
///
/// This is the ustar (Posix 1003.1) header.
///
/// struct header
/// {
/// char t_name[100]; // 0 Filename
/// char t_mode[8]; // 100 Permissions
/// char t_uid[8]; // 108 Numerical User ID
/// char t_gid[8]; // 116 Numerical Group ID
/// char t_size[12]; // 124 Filesize
/// char t_mtime[12]; // 136 st_mtime
/// char t_chksum[8]; // 148 Checksum
/// char t_typeflag; // 156 Type of File
/// char t_linkname[100]; // 157 Target of Links
/// char t_magic[6]; // 257 "ustar" or other...
/// char t_version[2]; // 263 Version fixed to 00
/// char t_uname[32]; // 265 User Name
/// char t_gname[32]; // 297 Group Name
/// char t_devmajor[8]; // 329 Major for devices
/// char t_devminor[8]; // 337 Minor for devices
/// char t_prefix[155]; // 345 Prefix for t_name
/// char t_mfill[12]; // 500 Filler up to 512
/// };
/// </remarks>
public class TarHeader
{
#region Constants
/// <summary>
/// The length of the name field in a header buffer.
/// </summary>
public const int NAMELEN = 100;
/// <summary>
/// The length of the mode field in a header buffer.
/// </summary>
public const int MODELEN = 8;
/// <summary>
/// The length of the user id field in a header buffer.
/// </summary>
public const int UIDLEN = 8;
/// <summary>
/// The length of the group id field in a header buffer.
/// </summary>
public const int GIDLEN = 8;
/// <summary>
/// The length of the checksum field in a header buffer.
/// </summary>
public const int CHKSUMLEN = 8;
/// <summary>
/// Offset of checksum in a header buffer.
/// </summary>
public const int CHKSUMOFS = 148;
/// <summary>
/// The length of the size field in a header buffer.
/// </summary>
public const int SIZELEN = 12;
/// <summary>
/// The length of the magic field in a header buffer.
/// </summary>
public const int MAGICLEN = 6;
/// <summary>
/// The length of the version field in a header buffer.
/// </summary>
public const int VERSIONLEN = 2;
/// <summary>
/// The length of the modification time field in a header buffer.
/// </summary>
public const int MODTIMELEN = 12;
/// <summary>
/// The length of the user name field in a header buffer.
/// </summary>
public const int UNAMELEN = 32;
/// <summary>
/// The length of the group name field in a header buffer.
/// </summary>
public const int GNAMELEN = 32;
/// <summary>
/// The length of the devices field in a header buffer.
/// </summary>
public const int DEVLEN = 8;
/// <summary>
/// The length of the name prefix field in a header buffer.
/// </summary>
public const int PREFIXLEN = 155;
//
// LF_ constants represent the "type" of an entry
//
/// <summary>
/// The "old way" of indicating a normal file.
/// </summary>
public const byte LF_OLDNORM = 0;
/// <summary>
/// Normal file type.
/// </summary>
public const byte LF_NORMAL = (byte) '0';
/// <summary>
/// Link file type.
/// </summary>
public const byte LF_LINK = (byte) '1';
/// <summary>
/// Symbolic link file type.
/// </summary>
public const byte LF_SYMLINK = (byte) '2';
/// <summary>
/// Character device file type.
/// </summary>
public const byte LF_CHR = (byte) '3';
/// <summary>
/// Block device file type.
/// </summary>
public const byte LF_BLK = (byte) '4';
/// <summary>
/// Directory file type.
/// </summary>
public const byte LF_DIR = (byte) '5';
/// <summary>
/// FIFO (pipe) file type.
/// </summary>
public const byte LF_FIFO = (byte) '6';
/// <summary>
/// Contiguous file type.
/// </summary>
public const byte LF_CONTIG = (byte) '7';
/// <summary>
/// Posix.1 2001 global extended header
/// </summary>
public const byte LF_GHDR = (byte) 'g';
/// <summary>
/// Posix.1 2001 extended header
/// </summary>
public const byte LF_XHDR = (byte) 'x';
// POSIX allows for upper case ascii type as extensions
/// <summary>
/// Solaris access control list file type
/// </summary>
public const byte LF_ACL = (byte) 'A';
/// <summary>
/// GNU dir dump file type
/// This is a dir entry that contains the names of files that were in the
/// dir at the time the dump was made
/// </summary>
public const byte LF_GNU_DUMPDIR = (byte) 'D';
/// <summary>
/// Solaris Extended Attribute File
/// </summary>
public const byte LF_EXTATTR = (byte) 'E';
/// <summary>
/// Inode (metadata only) no file content
/// </summary>
public const byte LF_META = (byte) 'I';
/// <summary>
/// Identifies the next file on the tape as having a long link name
/// </summary>
public const byte LF_GNU_LONGLINK = (byte) 'K';
/// <summary>
/// Identifies the next file on the tape as having a long name
/// </summary>
public const byte LF_GNU_LONGNAME = (byte) 'L';
/// <summary>
/// Continuation of a file that began on another volume
/// </summary>
public const byte LF_GNU_MULTIVOL = (byte) 'M';
/// <summary>
/// For storing filenames that dont fit in the main header (old GNU)
/// </summary>
public const byte LF_GNU_NAMES = (byte) 'N';
/// <summary>
/// GNU Sparse file
/// </summary>
public const byte LF_GNU_SPARSE = (byte) 'S';
/// <summary>
/// GNU Tape/volume header ignore on extraction
/// </summary>
public const byte LF_GNU_VOLHDR = (byte) 'V';
/// <summary>
/// The magic tag representing a POSIX tar archive. (would be written with a trailing NULL)
/// </summary>
public const string TMAGIC = "ustar";
/// <summary>
/// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it
/// </summary>
public const string GNU_TMAGIC = "ustar ";
private const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds
private static readonly DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
#endregion Constants
#region Constructors
/// <summary>
/// Initialise a default TarHeader instance
/// </summary>
public TarHeader()
{
Magic = TMAGIC;
Version = " ";
Name = "";
LinkName = "";
UserId = defaultUserId;
GroupId = defaultGroupId;
UserName = defaultUser;
GroupName = defaultGroupName;
Size = 0;
}
#endregion Constructors
#region Properties
/// <summary>
/// Get/set the name for this tar entry.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set the property to null.</exception>
public string Name
{
get { return name; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
name = value;
}
}
/// <summary>
/// Get the name of this entry.
/// </summary>
/// <returns>The entry's name.</returns>
[Obsolete("Use the Name property instead", true)]
public string GetName()
{
return name;
}
/// <summary>
/// Get/set the entry's Unix style permission mode.
/// </summary>
public int Mode
{
get { return mode; }
set { mode = value; }
}
/// <summary>
/// The entry's user id.
/// </summary>
/// <remarks>
/// This is only directly relevant to unix systems.
/// The default is zero.
/// </remarks>
public int UserId
{
get { return userId; }
set { userId = value; }
}
/// <summary>
/// Get/set the entry's group id.
/// </summary>
/// <remarks>
/// This is only directly relevant to linux/unix systems.
/// The default value is zero.
/// </remarks>
public int GroupId
{
get { return groupId; }
set { groupId = value; }
}
/// <summary>
/// Get/set the entry's size.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown when setting the size to less than zero.</exception>
public long Size
{
get { return size; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "Cannot be less than zero");
}
size = value;
}
}
/// <summary>
/// Get/set the entry's modification time.
/// </summary>
/// <remarks>
/// The modification time is only accurate to within a second.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown when setting the date time to less than 1/1/1970.</exception>
public DateTime ModTime
{
get { return modTime; }
set
{
if (value < dateTime1970)
{
throw new ArgumentOutOfRangeException(nameof(value), "ModTime cannot be before Jan 1st 1970");
}
modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second);
}
}
/// <summary>
/// Get the entry's checksum. This is only valid/updated after writing or reading an entry.
/// </summary>
public int Checksum
{
get { return checksum; }
}
/// <summary>
/// Get value of true if the header checksum is valid, false otherwise.
/// </summary>
public bool IsChecksumValid
{
get { return isChecksumValid; }
}
/// <summary>
/// Get/set the entry's type flag.
/// </summary>
public byte TypeFlag
{
get { return typeFlag; }
set { typeFlag = value; }
}
/// <summary>
/// The entry's link name.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set LinkName to null.</exception>
public string LinkName
{
get { return linkName; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
linkName = value;
}
}
/// <summary>
/// Get/set the entry's magic tag.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set Magic to null.</exception>
public string Magic
{
get { return magic; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
magic = value;
}
}
/// <summary>
/// The entry's version.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set Version to null.</exception>
public string Version
{
get { return version; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
version = value;
}
}
/// <summary>
/// The entry's user name.
/// </summary>
public string UserName
{
get { return userName; }
set
{
if (value != null)
{
userName = value.Substring(0, Math.Min(UNAMELEN, value.Length));
}
else
{
string currentUser = "user";
if (currentUser.Length > UNAMELEN)
{
currentUser = currentUser.Substring(0, UNAMELEN);
}
userName = currentUser;
}
}
}
/// <summary>
/// Get/set the entry's group name.
/// </summary>
/// <remarks>
/// This is only directly relevant to unix systems.
/// </remarks>
public string GroupName
{
get { return groupName; }
set
{
if (value == null)
{
groupName = "None";
}
else
{
groupName = value;
}
}
}
/// <summary>
/// Get/set the entry's major device number.
/// </summary>
public int DevMajor
{
get { return devMajor; }
set { devMajor = value; }
}
/// <summary>
/// Get/set the entry's minor device number.
/// </summary>
public int DevMinor
{
get { return devMinor; }
set { devMinor = value; }
}
#endregion Properties
#region ICloneable Members
/// <summary>
/// Create a new <see cref="TarHeader"/> that is a copy of the current instance.
/// </summary>
/// <returns>A new <see cref="Object"/> that is a copy of the current instance.</returns>
public object Clone()
{
return this.MemberwiseClone();
}
#endregion ICloneable Members
/// <summary>
/// Parse TarHeader information from a header buffer.
/// </summary>
/// <param name = "header">
/// The tar entry header buffer to get information from.
/// </param>
/// <param name = "nameEncoding">
/// The <see cref="Encoding"/> used for the Name field, or null for ASCII only
/// </param>
public void ParseBuffer(byte[] header, Encoding nameEncoding)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
int offset = 0;
var headerSpan = header.AsSpan();
name = ParseName(headerSpan.Slice(offset, NAMELEN), nameEncoding);
offset += NAMELEN;
mode = (int) ParseOctal(header, offset, MODELEN);
offset += MODELEN;
UserId = (int) ParseOctal(header, offset, UIDLEN);
offset += UIDLEN;
GroupId = (int) ParseOctal(header, offset, GIDLEN);
offset += GIDLEN;
Size = ParseBinaryOrOctal(header, offset, SIZELEN);
offset += SIZELEN;
ModTime = GetDateTimeFromCTime(ParseOctal(header, offset, MODTIMELEN));
offset += MODTIMELEN;
checksum = (int) ParseOctal(header, offset, CHKSUMLEN);
offset += CHKSUMLEN;
TypeFlag = header[offset++];
LinkName = ParseName(headerSpan.Slice(offset, NAMELEN), nameEncoding);
offset += NAMELEN;
Magic = ParseName(headerSpan.Slice(offset, MAGICLEN), nameEncoding);
offset += MAGICLEN;
if (Magic == "ustar")
{
Version = ParseName(headerSpan.Slice(offset, VERSIONLEN), nameEncoding);
offset += VERSIONLEN;
UserName = ParseName(headerSpan.Slice(offset, UNAMELEN), nameEncoding);
offset += UNAMELEN;
GroupName = ParseName(headerSpan.Slice(offset, GNAMELEN), nameEncoding);
offset += GNAMELEN;
DevMajor = (int) ParseOctal(header, offset, DEVLEN);
offset += DEVLEN;
DevMinor = (int) ParseOctal(header, offset, DEVLEN);
offset += DEVLEN;
string prefix = ParseName(headerSpan.Slice(offset, PREFIXLEN), nameEncoding);
if (!string.IsNullOrEmpty(prefix)) Name = prefix + '/' + Name;
}
isChecksumValid = Checksum == TarHeader.MakeCheckSum(header);
}
/// <summary>
/// Parse TarHeader information from a header buffer.
/// </summary>
/// <param name = "header">
/// The tar entry header buffer to get information from.
/// </param>
[Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")]
public void ParseBuffer(byte[] header)
{
ParseBuffer(header, null);
}
/// <summary>
/// 'Write' header information to buffer provided, updating the <see cref="Checksum">check sum</see>.
/// </summary>
/// <param name="outBuffer">output buffer for header information</param>
[Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")]
public void WriteHeader(byte[] outBuffer)
{
WriteHeader(outBuffer, null);
}
/// <summary>
/// 'Write' header information to buffer provided, updating the <see cref="Checksum">check sum</see>.
/// </summary>
/// <param name="outBuffer">output buffer for header information</param>
/// <param name="nameEncoding">The <see cref="Encoding"/> used for the Name field, or null for ASCII only</param>
public void WriteHeader(byte[] outBuffer, Encoding nameEncoding)
{
if (outBuffer == null)
{
throw new ArgumentNullException(nameof(outBuffer));
}
int offset = 0;
offset = GetNameBytes(Name, outBuffer, offset, NAMELEN, nameEncoding);
offset = GetOctalBytes(mode, outBuffer, offset, MODELEN);
offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN);
offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN);
offset = GetBinaryOrOctalBytes(Size, outBuffer, offset, SIZELEN);
offset = GetOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN);
int csOffset = offset;
for (int c = 0; c < CHKSUMLEN; ++c)
{
outBuffer[offset++] = (byte) ' ';
}
outBuffer[offset++] = TypeFlag;
offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN, nameEncoding);
offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN, nameEncoding);
offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN, nameEncoding);
offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN, nameEncoding);
offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN, nameEncoding);
if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK))
{
offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN);
offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN);
}
for (; offset < outBuffer.Length;)
{
outBuffer[offset++] = 0;
}
checksum = ComputeCheckSum(outBuffer);
GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN);
isChecksumValid = true;
}
/// <summary>
/// Get a hash code for the current object.
/// </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>
/// Determines if this instance is equal to the specified object.
/// </summary>
/// <param name="obj">The object to compare with.</param>
/// <returns>true if the objects are equal, false otherwise.</returns>
public override bool Equals(object obj)
{
var localHeader = obj as TarHeader;
bool result;
if (localHeader != null)
{
result = (name == localHeader.name)
&& (mode == localHeader.mode)
&& (UserId == localHeader.UserId)
&& (GroupId == localHeader.GroupId)
&& (Size == localHeader.Size)
&& (ModTime == localHeader.ModTime)
&& (Checksum == localHeader.Checksum)
&& (TypeFlag == localHeader.TypeFlag)
&& (LinkName == localHeader.LinkName)
&& (Magic == localHeader.Magic)
&& (Version == localHeader.Version)
&& (UserName == localHeader.UserName)
&& (GroupName == localHeader.GroupName)
&& (DevMajor == localHeader.DevMajor)
&& (DevMinor == localHeader.DevMinor);
}
else
{
result = false;
}
return result;
}
/// <summary>
/// Set defaults for values used when constructing a TarHeader instance.
/// </summary>
/// <param name="userId">Value to apply as a default for userId.</param>
/// <param name="userName">Value to apply as a default for userName.</param>
/// <param name="groupId">Value to apply as a default for groupId.</param>
/// <param name="groupName">Value to apply as a default for groupName.</param>
internal static void SetValueDefaults(int userId, string userName, int groupId, string groupName)
{
defaultUserId = userIdAsSet = userId;
defaultUser = userNameAsSet = userName;
defaultGroupId = groupIdAsSet = groupId;
defaultGroupName = groupNameAsSet = groupName;
}
internal static void RestoreSetValues()
{
defaultUserId = userIdAsSet;
defaultUser = userNameAsSet;
defaultGroupId = groupIdAsSet;
defaultGroupName = groupNameAsSet;
}
// Return value that may be stored in octal or binary. Length must exceed 8.
//
private static long ParseBinaryOrOctal(byte[] header, int offset, int length)
{
if (header[offset] >= 0x80)
{
// File sizes over 8GB are stored in 8 right-justified bytes of binary indicated by setting the high-order bit of the leftmost byte of a numeric field.
long result = 0;
for (int pos = length - 8; pos < length; pos++)
{
result = result << 8 | header[offset + pos];
}
return result;
}
return ParseOctal(header, offset, length);
}
/// <summary>
/// Parse an octal string from a header buffer.
/// </summary>
/// <param name = "header">The header buffer from which to parse.</param>
/// <param name = "offset">The offset into the buffer from which to parse.</param>
/// <param name = "length">The number of header bytes to parse.</param>
/// <returns>The long equivalent of the octal string.</returns>
public static long ParseOctal(byte[] header, int offset, int length)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
long result = 0;
bool stillPadding = true;
int end = offset + length;
for (int i = offset; i < end; ++i)
{
if (header[i] == 0)
{
break;
}
if (header[i] == (byte) ' ' || header[i] == '0')
{
if (stillPadding)
{
continue;
}
if (header[i] == (byte) ' ')
{
break;
}
}
stillPadding = false;
result = (result << 3) + (header[i] - '0');
}
return result;
}
/// <summary>
/// Parse a name from a header buffer.
/// </summary>
/// <param name="header">
/// The header buffer from which to parse.
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to parse.
/// </param>
/// <param name="length">
/// The number of header bytes to parse.
/// </param>
/// <returns>
/// The name parsed.
/// </returns>
[Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")]
public static string ParseName(byte[] header, int offset, int length)
{
return ParseName(header.AsSpan().Slice(offset, length), null);
}
/// <summary>
/// Parse a name from a header buffer.
/// </summary>
/// <param name="header">
/// The header buffer from which to parse.
/// </param>
/// <param name="encoding">
/// name encoding, or null for ASCII only
/// </param>
/// <returns>
/// The name parsed.
/// </returns>
public static string ParseName(ReadOnlySpan<byte> header, Encoding encoding)
{
var builder = StringBuilderPool.Instance.Rent();
int count = 0;
if (encoding == null)
{
for (int i = 0; i < header.Length; ++i)
{
var b = header[i];
if (b == 0)
{
break;
}
builder.Append((char) b);
}
}
else
{
for (int i = 0; i < header.Length; ++i, ++count)
{
if (header[i] == 0)
{
break;
}
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
var value = encoding.GetString(header.Slice(0, count));
#else
var value = encoding.GetString(header.ToArray(), 0, count);
#endif
builder.Append(value);
}
var result = builder.ToString();
StringBuilderPool.Instance.Return(builder);
return result;
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="nameOffset">The offset of the first character</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="bufferOffset">The index of the first byte to add</param>
/// <param name="length">The number of characters/bytes to add</param>
/// <returns>The next free index in the <paramref name="buffer"/></returns>
public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length)
{
return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length, null);
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="nameOffset">The offset of the first character</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="bufferOffset">The index of the first byte to add</param>
/// <param name="length">The number of characters/bytes to add</param>
/// <returns>The next free index in the <paramref name="buffer"/></returns>
public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length)
{
return GetNameBytes(name, nameOffset, buffer, bufferOffset, length, null);
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="nameOffset">The offset of the first character</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="bufferOffset">The index of the first byte to add</param>
/// <param name="length">The number of characters/bytes to add</param>
/// <param name="encoding">name encoding, or null for ASCII only</param>
/// <returns>The next free index in the <paramref name="buffer"/></returns>
public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length,
Encoding encoding)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
int i;
if (encoding != null)
{
// it can be more sufficient if using Span or unsafe
ReadOnlySpan<char> nameArray =
name.AsSpan().Slice(nameOffset, Math.Min(name.Length - nameOffset, length));
var charArray = ArrayPool<char>.Shared.Rent(nameArray.Length);
nameArray.CopyTo(charArray);
// it can be more sufficient if using Span(or unsafe?) and ArrayPool for temporary buffer
var bytesLength = encoding.GetBytes(charArray, 0, nameArray.Length, buffer, bufferOffset);
ArrayPool<char>.Shared.Return(charArray);
i = Math.Min(bytesLength, length);
}
else
{
for (i = 0; i < length && nameOffset + i < name.Length; ++i)
{
buffer[bufferOffset + i] = (byte) name[nameOffset + i];
}
}
for (; i < length; ++i)
{
buffer[bufferOffset + i] = 0;
}
return bufferOffset + length;
}
/// <summary>
/// Add an entry name to the buffer
/// </summary>
/// <param name="name">
/// The name to add
/// </param>
/// <param name="buffer">
/// The buffer to add to
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to start adding
/// </param>
/// <param name="length">
/// The number of header bytes to add
/// </param>
/// <returns>
/// The index of the next free byte in the buffer
/// </returns>
/// TODO: what should be default behavior?(omit upper byte or UTF8?)
[Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")]
public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length)
{
return GetNameBytes(name, buffer, offset, length, null);
}
/// <summary>
/// Add an entry name to the buffer
/// </summary>
/// <param name="name">
/// The name to add
/// </param>
/// <param name="buffer">
/// The buffer to add to
/// </param>
/// <param name="offset">