Class: Fat32::DirectoryEntry

Inherits:
Object
  • Object
show all
Defined in:
lib/fs/fat32/directory_entry.rb

Overview

//////////////////////////////////////////////////////////////////////////// // Class.

Constant Summary collapse

LFN_NAME_COMPONENTS =

From the UTF-8 perspective. LFN name components: entry hash name, char offset, length.

[
  ['name',   0, 5],
  ['name2',  5, 6],
  ['name3', 11, 2]
]
LFN_NC_HASHNAME =

Name component second sub access names.

0
LFN_NC_OFFSET =
1
LFN_NC_LENGTH =
2
SFN_NAME_LENGTH =

SFN failure cases.

1
SFN_EXT_LENGTH =
2
SFN_NAME_NULL =
3
SFN_NAME_DEVICE =
4
SFN_ILLEGAL_CHARS =
5
LFN_NAME_LENGTH =

LFN failure cases.

1
LFN_NAME_DEVICE =
2
LFN_ILLEGAL_CHARS =
3
FA_READONLY =

FileAttributes

0x01
FA_HIDDEN =
0x02
FA_SYSTEM =
0x04
FA_LABEL =
0x08
FA_DIRECTORY =
0x10
FA_ARCHIVE =
0x20
FA_LFN =
0x0f
MSK_DAY =

DOS time masks.

0x001f
MSK_MONTH =

Range: 1 - 31

0x01e0
MSK_YEAR =

Right shift 5, Range: 1 - 12

0xfe00
MSK_SEC =

Right shift 9, Range: 127 (add 1980 for year).

0x001f
MSK_MIN =

Range: 0 - 29 WARNING: 2 second granularity on this.

0x07e0
MSK_HOUR =

Right shift 5, Range: 0 - 59

0xf800
AF_NOT_ALLOCATED =

AllocationFlags

0x00
AF_DELETED =
0xe5
AF_LFN_LAST =
0x40

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buf = nil) ⇒ DirectoryEntry

Initialization



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
# File 'lib/fs/fat32/directory_entry.rb', line 106

def initialize(buf = nil)
  # Create for write.
  if buf == nil
    self.create
    return
  end

  # Handle possibly multiple LFN records.
  data = StringIO.new(buf); @lfn_ents = []
  checksum = 0; @name = ""
  loop do
    buf = data.read(DIR_ENT_SIZE)
    if buf == nil
      @unused = ""
      return
    end

    # If attribute contains 0x0f then LFN entry.
    isLfn = buf[ATTRIB_OFFSET] == FA_LFN
    @dir_ent = isLfn ? DIR_ENT_LFN.decode(buf) : DIR_ENT_SFN.decode(buf)
    break if !isLfn

    # Ignore this entry if deleted or not allocated.
    af = @dir_ent['seq_num']
    if af == AF_DELETED || af == AF_NOT_ALLOCATED
      @name = @dir_ent['seq_num']
      @unused = data.read()
      return
    end

    # Set checksum or make sure it's the same
    checksum = @dir_ent['checksum'] if checksum == 0
    raise "Directory entry LFN checksum mismatch." if @dir_ent['checksum'] != checksum

    # Track LFN entry, gather names & prepend to name.
    @lfn_ents << @dir_ent
    @name = getLongNameFromEntry(@dir_ent) + @name
  end #LFN loop

  # Push the rest of the data back.
  @unused = data.read()

  # If this is the last record of an LFN chain, check the checksum.
  if checksum != 0
    csum = calcChecksum
    if csum != checksum
      puts "Directory entry SFN checksum does not match LFN entries:"
      puts "Got 0x#{'%02x' % csum}, should be 0x#{'%02x' % checksum}."
      puts "Non LFN OS corruption?"
      puts dump
      raise "Checksum error"
    end
  end

  # Populate name if not LFN.
  if @name == "" && !@dir_ent['name'].empty?
    @name = @dir_ent['name'][0, 8].strip
    ext = @dir_ent['name'][8, 3].strip
    @name += "." + ext unless ext.empty?
  end
end

Instance Attribute Details

#dirtyObject (readonly)

Members.



100
101
102
# File 'lib/fs/fat32/directory_entry.rb', line 100

def dirty
  @dirty
end

#nameObject

Members.



100
101
102
# File 'lib/fs/fat32/directory_entry.rb', line 100

def name
  @name
end

#parentClusterObject

Returns the value of attribute parentCluster.



101
102
103
# File 'lib/fs/fat32/directory_entry.rb', line 101

def parentCluster
  @parentCluster
end

#parentOffsetObject

Returns the value of attribute parentOffset.



101
102
103
# File 'lib/fs/fat32/directory_entry.rb', line 101

def parentOffset
  @parentOffset
end

#unusedObject (readonly)

Members.



100
101
102
# File 'lib/fs/fat32/directory_entry.rb', line 100

def unused
  @unused
end

Instance Method Details

#aTimeObject



330
331
332
# File 'lib/fs/fat32/directory_entry.rb', line 330

def aTime
  return dosToRubyTime(@dir_ent['atime_day'], 0)
end

#aTime=(tim) ⇒ Object

WRITE: change access time.



253
254
255
256
257
# File 'lib/fs/fat32/directory_entry.rb', line 253

def aTime=(tim)
  @dirty = true
  time, day = rubyToDosTime(tim)
  @dir_ent['atime_day'] = day
end

#attributesObject



309
310
311
# File 'lib/fs/fat32/directory_entry.rb', line 309

def attributes
  return @dir_ent['attributes']
end

#calcChecksumObject



469
470
471
472
473
474
475
# File 'lib/fs/fat32/directory_entry.rb', line 469

def calcChecksum
  name = @dir_ent['name']; csum = 0
  0.upto(10) {|i|
    csum = ((csum & 1 == 1 ? 0x80 : 0) + (csum >> 1) + name[i]) & 0xff
  }
  return csum
end

#checkForDeviceName(fn) ⇒ Object



441
442
443
444
445
446
# File 'lib/fs/fat32/directory_entry.rb', line 441

def checkForDeviceName(fn)
  %w[aux com1 com2 com3 com4 lpt lpt1 lpt2 lpt3 lpt4 mailslot nul pipe prn].each {|bad|
    return true if fn == bad
  }
  return false
end

#close(bs) ⇒ Object



305
306
307
# File 'lib/fs/fat32/directory_entry.rb', line 305

def close(bs)
  writeEntry(bs) if @dirty
end

#createObject



367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/fs/fat32/directory_entry.rb', line 367

def create
  @dirty = true
  @dir_ent = Hash.new
  @dir_ent['name'] = "FILENAMEEXT"
  @name = self.shortName
  @dir_ent['attributes'] = FA_ARCHIVE
  @dir_ent['ctime_tos'] = 0
  @dir_ent['ctime_hms'], @dir_ent['ctime_day'] = rubyToDosTime(Time.now)
  @dir_ent['atime_day'] = @dir_ent['ctime_day']
  @dir_ent['mtime_hms'], @dir_ent['mtime_day'] = @dir_ent['ctime_hms'], @dir_ent['ctime_day']
  # Must fill all members or BinaryStruct.encode fails.
  self.magic = 0x00; self.length = 0; self.firstCluster = 0 #magic used to be 0x18
end

#cTimeObject



334
335
336
# File 'lib/fs/fat32/directory_entry.rb', line 334

def cTime
  return dosToRubyTime(@dir_ent['ctime_day'], @dir_ent['ctime_hms'])
end

#delete(bs) ⇒ Object

WRITE: delete file.



295
296
297
298
299
300
301
302
303
# File 'lib/fs/fat32/directory_entry.rb', line 295

def delete(bs)
  # Deallocate data chain.
  bs.wipeChain(self.firstCluster) if self.firstCluster != 0
  # Deallocate dir entry.
  if @lfn_ents then @lfn_ents.each {|ent| ent['seq_num'] = AF_DELETED} end
  @dir_ent['name'][0] = AF_DELETED
  @dirty = true
  self.writeEntry(bs)
end

#dosToRubyTime(dos_day, dos_time) ⇒ Object



477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/fs/fat32/directory_entry.rb', line 477

def dosToRubyTime(dos_day, dos_time)
  # Extract d,m,y,s,m,h & range check.
  day = dos_day & MSK_DAY; day = 1 if day == 0
  month = (dos_day & MSK_MONTH) >> 5; month = 1 if month == 0
  month = month.modulo(12) if month > 12
  year = ((dos_day & MSK_YEAR) >> 9) + 1980 #DOS year epoc is 1980.
  # Extract seconds, range check & expand granularity.
  sec = (dos_time & MSK_SEC); sec = sec.modulo(29) if sec > 29; sec *= 2
  min = (dos_time & MSK_MIN) >> 5; min = min.modulo(59) if min > 59
  hour = (dos_time & MSK_HOUR) >> 11; hour = hour.modulo(23) if hour > 23
  # Make a Ruby time.
  return Time.mktime(year, month, day, hour, min, sec)
end

#dumpObject

Dump object.



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
# File 'lib/fs/fat32/directory_entry.rb', line 506

def dump
  out = "\#<#{self.class}:0x#{'%08x' % self.object_id}>\n"
  if @lfn_ents
    out += "LFN Entries:\n"
    @lfn_ents.each {|ent|
      out += "Sequence num : 0x#{'%02x' % ent['seq_num']}\n"
      n = ent['name']; n.UnicodeToUtf8! unless n == nil
      out += "Name1        : '#{n}'\n"
      out += "Attributes   : 0x#{'%02x' % ent['attributes']}\n"
      out += "Reserved1    : 0x#{'%02x' % ent['reserved1']}\n"
      out += "Checksum     : 0x#{'%02x' % ent['checksum']}\n"
      n = ent['name2']; n.UnicodeToUtf8! unless n == nil
      out += "Name2        : '#{n}'\n"
      out += "Reserved2    : 0x#{'%04x' % ent['reserved2']}\n"
      n = ent['name3']; n.UnicodeToUtf8! unless n == nil
      out += "Name3        : '#{n}'\n\n"
    }
  end
  out += "SFN Entry:\n"
  out += "Name         : #{@dir_ent['name']}\n"
  out += "Attributes   : 0x#{'%02x' % @dir_ent['attributes']}\n"
  out += "Reserved1    : 0x#{'%02x' % @dir_ent['reserved1']}\n"
  out += "CTime, tenths: 0x#{'%02x' % @dir_ent['ctime_tos']}\n"
  out += "CTime, hms   : 0x#{'%04x' % @dir_ent['ctime_hms']}\n"
  out += "CTime, day   : 0x#{'%04x' % @dir_ent['ctime_day']} (#{cTime})\n"
  out += "ATime, day   : 0x#{'%04x' % @dir_ent['atime_day']} (#{aTime})\n"
  out += "First clus hi: 0x#{'%04x' % @dir_ent['first_clus_hi']}\n"
  out += "MTime, hms   : 0x#{'%04x' % @dir_ent['mtime_hms']}\n"
  out += "MTime, day   : 0x#{'%04x' % @dir_ent['mtime_day']} (#{mTime})\n"
  out += "First clus lo: 0x#{'%04x' % @dir_ent['first_clus_lo']}\n"
  out += "File size    : 0x#{'%08x' % @dir_ent['file_size']}\n"
end

#firstClusterObject



317
318
319
# File 'lib/fs/fat32/directory_entry.rb', line 317

def firstCluster
  return (@dir_ent['first_clus_hi'] << 16) + @dir_ent['first_clus_lo']
end

#firstCluster=(first_clus) ⇒ Object

WRITE: change first cluster.



246
247
248
249
250
# File 'lib/fs/fat32/directory_entry.rb', line 246

def firstCluster=(first_clus)
  @dirty = true
  @dir_ent['first_clus_hi'] = (first_clus >> 16)
  @dir_ent['first_clus_lo'] = (first_clus & 0xffff)
end

#getLongNameFromEntry(ent) ⇒ Object

//////////////////////////////////////////////////////////////////////////// // Utility functions.



341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/fs/fat32/directory_entry.rb', line 341

def getLongNameFromEntry(ent)
  pre_name = ""; hashNames = %w(name name2 name3)
  hashNames.each {|name|
    n = ent["#{name}"]

    # Regexp.new options used below:
    #   nil (default options: not case insensitive, extended, multiline, etc.)
    #   'n' - No encoding on the regexp
    regex = Regexp.new('\377', nil, 'n')
    pre_name += n.gsub(regex, "").UnicodeToUtf8.gsub(/\000/, "")
  }
  return pre_name
end

#incShortNameObject



355
356
357
358
359
360
361
362
363
364
365
# File 'lib/fs/fat32/directory_entry.rb', line 355

def incShortName
  @dirty = true
  num = @dir_ent['name'][7].to_i
  num += 1
  raise "More than 9 files with name: #{@dir_ent['name'][0, 6]}" if num > 57
  @dir_ent['name'][7] = num
  csum = calcChecksum()
  if @lfn_ents
    @lfn_ents.each {|ent| ent['checksum'] = csum}
  end
end

#isDir?Boolean

Returns:

  • (Boolean)


321
322
323
324
# File 'lib/fs/fat32/directory_entry.rb', line 321

def isDir?
  return true if @dir_ent['attributes'] & FA_DIRECTORY == FA_DIRECTORY
  return false
end

#isIllegalLfn(name) ⇒ Object



458
459
460
461
462
# File 'lib/fs/fat32/directory_entry.rb', line 458

def isIllegalLfn(name)
  return LFN_NAME_LENGTH if name.length > LFN_NAME_MAXLEN
  return LFN_ILLEGAL_CHARS if name.index(/\/\\:><?/) != nil
  return false
end

#isIllegalSfn(name) ⇒ Object



428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/fs/fat32/directory_entry.rb', line 428

def isIllegalSfn(name)
  # Check: name length, extension length, NULL file name,
  # device names as file names & illegal chars.
  return SFN_NAME_LENGTH if name.length > 12
  extpos = name.reverse.index(".")
  return SFN_EXT_LENGTH if extpos > 3
  return SFN_NAME_NULL if extpos == 0
  fn = name[0...extpos].downcase
  return SFN_NAME_DEVICE if checkForDeviceNames(fn)
  return SFN_ILLEGAL_CHARS if name.index(/[;+=\[\]',\"*\\<>\/?\:|]/) != nil
  return false
end

#lengthObject



313
314
315
# File 'lib/fs/fat32/directory_entry.rb', line 313

def length
  return @dir_ent['file_size']
end

#length=(len) ⇒ Object

WRITE: change length.



240
241
242
243
# File 'lib/fs/fat32/directory_entry.rb', line 240

def length=(len)
  @dirty = true
  @dir_ent['file_size'] = len
end

#longNameObject

Construct & return long name from lfn entries.



194
195
196
197
198
199
# File 'lib/fs/fat32/directory_entry.rb', line 194

def longName
  return nil if @lfn_ents == nil
  name = ""
  @lfn_ents.reverse.each {|ent| name += getLongNameFromEntry(ent)}
  return name
end

#magicObject



225
226
227
# File 'lib/fs/fat32/directory_entry.rb', line 225

def magic
  return @dir_ent['reserved1']
end

#magic=(magic) ⇒ Object

WRITE: change magic number.



220
221
222
223
# File 'lib/fs/fat32/directory_entry.rb', line 220

def magic=(magic)
  @dirty = true
  @dir_ent['reserved1'] = magic
end

#mkLegalLfn(name) ⇒ Object



464
465
466
467
# File 'lib/fs/fat32/directory_entry.rb', line 464

def mkLegalLfn(name)
  name = name[0...LFN_NAME_MAXLEN] if name.length > LFN_NAME_MAXLEN
  return name.gsub(/\/\\:><?/, "_")
end

#mkLegalSfn(name) ⇒ Object



448
449
450
451
452
453
454
455
456
# File 'lib/fs/fat32/directory_entry.rb', line 448

def mkLegalSfn(name)
  name = name.upcase; name = name.delete(" ")
  name = name + "." if not name.include?(".")
  extpos = name.reverse.index(".")
  if extpos == 0 then ext = "" else ext = name[-extpos, 3] end
  fn = name[0, (name.length - extpos - 1)]
  fn = fn[0, 6] + "~1" if fn.length > 8
  return (fn.ljust(8) + ext.ljust(3)).gsub(/[;+=\[\]',\"*\\<>\/?\:|]/, "_")
end

#mkLfn(name) ⇒ Object



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
# File 'lib/fs/fat32/directory_entry.rb', line 391

def mkLfn(name)
  name = mkLegalLfn(name)
  lfn_ents = []
  # Get number of LFN entries necessary to encode name.
  ents, leftover = name.length.divmod(CHARS_PER_LFN)
  if leftover > 0
    ents += 1
    name += "\000"
  end
  # Split out & convert name components.
  1.upto(ents) {|ent_num|
    ent = {}; ent['attributes'] = FA_LFN; ent['seq_num'] = ent_num
    ent['reserved1'] = 0; ent['reserved2'] = 0;
    LFN_NAME_COMPONENTS.each {|comp|
      chStart = (ent_num - 1) * CHARS_PER_LFN + comp[LFN_NC_OFFSET]
      if chStart > name.length
        ent["#{comp[LFN_NC_HASHNAME]}"] = "\377".b * (comp[LFN_NC_LENGTH] * 2)
      else
        ptName = name[chStart, comp[LFN_NC_LENGTH]]
        ptName.Utf8ToUnicode!
        if ptName.length < comp[LFN_NC_LENGTH] * 2
          ptName += "\377".b * (comp[LFN_NC_LENGTH] * 2 - ptName.length)
        end
        ent["#{comp[LFN_NC_HASHNAME]}"] = ptName
      end
    }
    lfn_ents << ent
  }
  lfn_ents.reverse!
  lfn_ents[0]['seq_num'] |= AF_LFN_LAST
  return lfn_ents
end

#mkLongName(name) ⇒ Object



381
382
383
384
385
386
387
388
389
# File 'lib/fs/fat32/directory_entry.rb', line 381

def mkLongName(name)
  @lfn_ents = mkLfn(name)
  @dir_ent['name'] = mkSfn(name)
  # Change magic number to 0.
  @dir_ent['reserved1'] = 0
  # Do checksums in lfn entries.
  csum = calcChecksum()
  @lfn_ents.each {|ent| ent['checksum'] = csum}
end

#mkSfn(name) ⇒ Object



424
425
426
# File 'lib/fs/fat32/directory_entry.rb', line 424

def mkSfn(name)
  return mkLegalSfn(name)
end

#mTimeObject



326
327
328
# File 'lib/fs/fat32/directory_entry.rb', line 326

def mTime
  return dosToRubyTime(@dir_ent['mtime_day'], @dir_ent['mtime_hms'])
end

#mTime=(tim) ⇒ Object

WRITE: change modified (written) time.



268
269
270
271
# File 'lib/fs/fat32/directory_entry.rb', line 268

def mTime=(tim)
  @dirty = true
  @dir_ent['mtime_hms'], @dir_ent['mtime_day'] = rubyToDosTime(tim)
end

#numEntsObject

Number of dir ent structures (both sfn and lfn).



179
180
181
182
183
# File 'lib/fs/fat32/directory_entry.rb', line 179

def numEnts
  num = 1
  num += @lfn_ents.size if @lfn_ents
  return num
end

#rawObject

Return this entry as a raw string.



172
173
174
175
176
# File 'lib/fs/fat32/directory_entry.rb', line 172

def raw
  out = ""
  @lfn_ents.each {|ent| out += BinaryStruct.encode(ent, DIR_ENT_LFN)} if @lfn_ents
  out += BinaryStruct.encode(@dir_ent, DIR_ENT_SFN)
end

#rubyToDosTime(tim) ⇒ Object



491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/fs/fat32/directory_entry.rb', line 491

def rubyToDosTime(tim)
  # Time
  sec = tim.sec; sec -= 1 if sec == 60 #correction for possible leap second.
  sec = (sec / 2).to_i #dos granularity is 2sec.
  min = tim.min; hour = tim.hour
  dos_time = (hour << 11) + (min << 5) + sec
  # Day
  day = tim.day; month = tim.month
  # NOTE: This fails after 2107.
  year = tim.year - 1980 #DOS year epoc is 1980.
  dos_day = (year << 9) + (month << 5) + day
  return dos_time, dos_day
end

#setAttribute(attrib, set = true) ⇒ Object

WRITE: change attribs.



230
231
232
233
234
235
236
237
# File 'lib/fs/fat32/directory_entry.rb', line 230

def setAttribute(attrib, set = true)
  @dirty = true
  if set
    @dir_ent['attributes'] |= attrib
  else
    @dir_ent['attributes'] &= (~attrib)
  end
end

#shortNameObject

Return normalized 8.3 name.



186
187
188
189
190
191
# File 'lib/fs/fat32/directory_entry.rb', line 186

def shortName
  name = @dir_ent['name'][0, 8].strip
  ext  = @dir_ent['name'][8, 3].strip
  name += "." + ext if ext != ""
  return name
end

#writeEntry(bs) ⇒ Object

WRITE: write or rewrite directory entry.



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/fs/fat32/directory_entry.rb', line 274

def writeEntry(bs)
  return if not @dirty
  cluster = @parentCluster; offset = @parentOffset
  buf = bs.getCluster(cluster)
  if @lfn_ents
    @lfn_ents.each {|ent|
      buf[offset...(offset + DIR_ENT_SIZE)] = BinaryStruct.encode(ent, DIR_ENT_LFN)
      offset += DIR_ENT_SIZE
      if offset >= bs.bytesPerCluster
        bs.putCluster(cluster, buf)
        cluster, buf = bs.getNextCluster(cluster)
        offset = 0
      end
    }
  end
  buf[offset...(offset + DIR_ENT_SIZE)] = BinaryStruct.encode(@dir_ent, DIR_ENT_SFN)
  bs.putCluster(cluster, buf)
  @dirty = false
end

#zeroTimeObject

To support root dir times (all zero).



260
261
262
263
264
265
# File 'lib/fs/fat32/directory_entry.rb', line 260

def zeroTime
  @dirty = true
  @dir_ent['atime_day'] = 0
  @dir_ent['ctime_tos'] = 0; @dir_ent['ctime_hms'] = 0; @dir_ent['ctime_day'] = 0
  @dir_ent['mtime_hms'] = 0; @dir_ent['mtime_day'] = 0
end