Class: ZipTricks::ZipWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/zip_tricks/zip_writer.rb

Overview

A low-level ZIP file data writer. You can use it to write out various headers and central directory elements separately. The class handles the actual encoding of the data according to the ZIP format APPNOTE document.

The primary reason the writer is a separate object is because it is kept stateless. That is, all the data that is needed for writing a piece of the ZIP (say, the EOCD record, or a data descriptor) can be written without depending on data available elsewhere. This makes the writer very easy to test, since each of it's methods outputs something that only depends on the method's arguments. For example, we use this to test writing Zip64 files which, when tested in a streaming fashion, would need tricky IO stubs to wind IO objects back and forth by large offsets. Instead, we can just write out the EOCD record with given offsets as arguments.

Since some methods need a lot of data about the entity being written, everything is passed via keyword arguments - this way it is much less likely that you can make a mistake writing something.

Another reason for having a separate Writer is that most ZIP libraries attach the methods for writing out the file headers to some sort of Entry object, which represents a file within the ZIP. However, when you are diagnosing issues with the ZIP files you produce, you actually want to have absolute most of the code responsible for writing the actual encoded bytes available to you on one screen. Altering or checking that code then becomes much, much easier. The methods doing the writing are also intentionally left very verbose - so that you can follow what is happening at all times.

All methods of the writer accept anything that responds to << as io argument - you can use that to output to String objects, or to output to Arrays that you can later join together.

Constant Summary collapse

EMPTY_DIRECTORY_EXTERNAL_ATTRS =
begin
  # Applies permissions to an empty directory.
  unix_perms = 0o755
  file_type_dir = 0o04
  (file_type_dir << 12 | (unix_perms & 0o7777)) << 16
end
C_CHAR =

For bit-encoded strings

'C'
C_INT4 =

Encode a 4-byte signed little-endian int

'N'

Instance Method Summary collapse

Instance Method Details

#write_central_directory_file_header(io:, local_file_header_location:, gp_flags:, storage_mode:, compressed_size:, uncompressed_size:, mtime:, crc32:, filename:) ⇒ void

This method returns an undefined value.

Writes the file header for the central directory, for a particular file in the archive. When writing out this data, ensure that the CRC32 and both sizes (compressed/uncompressed) are correct for the entry in question.

Parameters:

  • io (#<<)

    the buffer to write the local file header to

  • filename (String)

    the name of the file in the archive

  • compressed_size (Fixnum)

    The size of the compressed (or stored) data - how much space it uses in the ZIP

  • uncompressed_size (Fixnum)

    The size of the file once extracted

  • crc32 (Fixnum)

    The CRC32 checksum of the file

  • mtime (Time)

    the modification time to be recorded in the ZIP

  • gp_flags (Fixnum)

    bit-packed general purpose flags



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
# File 'lib/zip_tricks/zip_writer.rb', line 140

def write_central_directory_file_header(io:,
                                        local_file_header_location:,
                                        gp_flags:,
                                        storage_mode:,
                                        compressed_size:,
                                        uncompressed_size:,
                                        mtime:,
                                        crc32:,
                                        filename:)
  # At this point if the header begins somewhere beyound 0xFFFFFFFF we _have_ to record the offset
  # of the local file header as a zip64 extra field, so we give up, give in, you loose, love will always win...
  add_zip64 = (local_file_header_location > FOUR_BYTE_MAX_UINT) ||
              (compressed_size > FOUR_BYTE_MAX_UINT) || (uncompressed_size > FOUR_BYTE_MAX_UINT)

  io << [0x02014b50].pack(C_UINT4)                        # central file header signature   4 bytes  (0x02014b50)
  io << MADE_BY_SIGNATURE                             # version made by                 2 bytes
  io << if add_zip64
    [VERSION_NEEDED_TO_EXTRACT_ZIP64].pack(C_UINT2) # version needed to extract       2 bytes
  else
    [VERSION_NEEDED_TO_EXTRACT].pack(C_UINT2)       # version needed to extract       2 bytes
  end

  io << [gp_flags].pack(C_UINT2)                          # general purpose bit flag        2 bytes
  io << [storage_mode].pack(C_UINT2)                      # compression method              2 bytes
  io << [to_binary_dos_time(mtime)].pack(C_UINT2)         # last mod file time              2 bytes
  io << [to_binary_dos_date(mtime)].pack(C_UINT2)         # last mod file date              2 bytes
  io << [crc32].pack(C_UINT4)                             # crc-32                          4 bytes

  if add_zip64
    io << [FOUR_BYTE_MAX_UINT].pack(C_UINT4)              # compressed size              4 bytes
    io << [FOUR_BYTE_MAX_UINT].pack(C_UINT4)              # uncompressed size            4 bytes
  else
    io << [compressed_size].pack(C_UINT4)                 # compressed size              4 bytes
    io << [uncompressed_size].pack(C_UINT4)               # uncompressed size            4 bytes
  end

  # Filename should not be longer than 0xFFFF otherwise this wont fit here
  io << [filename.bytesize].pack(C_UINT2)                 # file name length                2 bytes

  extra_fields = StringIO.new
  if add_zip64
    extra_fields << zip_64_extra_for_central_directory_file_header(local_file_header_location: local_file_header_location,
                                                                   compressed_size: compressed_size,
                                                                   uncompressed_size: uncompressed_size)
  end
  extra_fields << timestamp_extra(mtime)

  io << [extra_fields.size].pack(C_UINT2)                 # extra field length              2 bytes

  io << [0].pack(C_UINT2)                                 # file comment length             2 bytes

  # For The Unarchiver < 3.11.1 this field has to be set to the overflow value if zip64 is used
  # because otherwise it does not properly advance the pointer when reading the Zip64 extra field
  # https://bitbucket.org/WAHa_06x36/theunarchiver/pull-requests/2/bug-fix-for-zip64-extra-field-parser/diff
  io << if add_zip64                                        # disk number start               2 bytes
    [TWO_BYTE_MAX_UINT].pack(C_UINT2)
  else
    [0].pack(C_UINT2)
        end
  io << [0].pack(C_UINT2)                                # internal file attributes        2 bytes

  # Because the add_empty_directory method will create a directory with a trailing "/",
  # this check can be used to assign proper permissions to the created directory.
  io << if filename.end_with?('/')
    [EMPTY_DIRECTORY_EXTERNAL_ATTRS].pack(C_UINT4)
  else
    [DEFAULT_EXTERNAL_ATTRS].pack(C_UINT4)           # external file attributes        4 bytes
  end

  io << if add_zip64                                 # relative offset of local header 4 bytes
    [FOUR_BYTE_MAX_UINT].pack(C_UINT4)
  else
    [local_file_header_location].pack(C_UINT4)
  end

  io << filename                                     # file name (variable size)
  io << extra_fields.string                          # extra field (variable size)
  # (empty)                                          # file comment (variable size)
end

#write_data_descriptor(io:, compressed_size:, uncompressed_size:, crc32:) ⇒ void

This method returns an undefined value.

Writes the data descriptor following the file data for a file whose local file header was written with general-purpose flag bit 3 set. If the one of the sizes exceeds the Zip64 threshold, the data descriptor will have the sizes written out as 8-byte values instead of 4-byte values.

Parameters:

  • io (#<<)

    the buffer to write the local file header to

  • crc32 (Fixnum)

    The CRC32 checksum of the file

  • compressed_size (Fixnum)

    The size of the compressed (or stored) data - how much space it uses in the ZIP

  • uncompressed_size (Fixnum)

    The size of the file once extracted



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/zip_tricks/zip_writer.rb', line 229

def write_data_descriptor(io:, compressed_size:, uncompressed_size:, crc32:)
  io << [0x08074b50].pack(C_UINT4)  # Although not originally assigned a signature, the value
  # 0x08074b50 has commonly been adopted as a signature value
  # for the data descriptor record.
  io << [crc32].pack(C_UINT4)                             # crc-32                          4 bytes

  # If one of the sizes is above 0xFFFFFFF use ZIP64 lengths (8 bytes) instead. A good unarchiver
  # will decide to unpack it as such if it finds the Zip64 extra for the file in the central directory.
  # So also use the opportune moment to switch the entry to Zip64 if needed
  requires_zip64 = (compressed_size > FOUR_BYTE_MAX_UINT || uncompressed_size > FOUR_BYTE_MAX_UINT)
  pack_spec = requires_zip64 ? C_UINT8 : C_UINT4

  io << [compressed_size].pack(pack_spec)       # compressed size                 4 bytes, or 8 bytes for ZIP64
  io << [uncompressed_size].pack(pack_spec)     # uncompressed size               4 bytes, or 8 bytes for ZIP64
end

#write_end_of_central_directory(io:, start_of_central_directory_location:, central_directory_size:, num_files_in_archive:, comment: ZIP_TRICKS_COMMENT) ⇒ void

This method returns an undefined value.

Writes the "end of central directory record" (including the Zip6 salient bits if necessary)

Parameters:

  • io (#<<)

    the buffer to write the central directory to.

  • start_of_central_directory_location (Fixnum)

    byte offset of the start of central directory form the beginning of ZIP file

  • central_directory_size (Fixnum)

    the size of the central directory (only file headers) in bytes

  • num_files_in_archive (Fixnum)

    How many files the archive contains

  • comment (String) (defaults to: ZIP_TRICKS_COMMENT)

    the comment for the archive (defaults to ZIP_TRICKS_COMMENT)



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
# File 'lib/zip_tricks/zip_writer.rb', line 253

def write_end_of_central_directory(io:, start_of_central_directory_location:, central_directory_size:, num_files_in_archive:, comment: ZIP_TRICKS_COMMENT)
  zip64_eocdr_offset = start_of_central_directory_location + central_directory_size

  zip64_required = central_directory_size > FOUR_BYTE_MAX_UINT ||
                   start_of_central_directory_location > FOUR_BYTE_MAX_UINT ||
                   zip64_eocdr_offset > FOUR_BYTE_MAX_UINT ||
                   num_files_in_archive > TWO_BYTE_MAX_UINT

  # Then, if zip64 is used
  if zip64_required
    # [zip64 end of central directory record]
    # zip64 end of central dir
    io << [0x06064b50].pack(C_UINT4)                           # signature                       4 bytes  (0x06064b50)
    io << [44].pack(C_UINT8)                                  # size of zip64 end of central
    # directory record                8 bytes
    # (this is ex. the 12 bytes of the signature and the size value itself).
    # Without the extensible data sector (which we are not using)
    # it is always 44 bytes.
    io << MADE_BY_SIGNATURE                                # version made by                 2 bytes
    io << [VERSION_NEEDED_TO_EXTRACT_ZIP64].pack(C_UINT2)      # version needed to extract       2 bytes
    io << [0].pack(C_UINT4)                                    # number of this disk             4 bytes
    io << [0].pack(C_UINT4)                                    # number of the disk with the
    # start of the central directory  4 bytes
    io << [num_files_in_archive].pack(C_UINT8)                # total number of entries in the
    # central directory on this disk  8 bytes
    io << [num_files_in_archive].pack(C_UINT8)                # total number of entries in the
    # central directory               8 bytes
    io << [central_directory_size].pack(C_UINT8)              # size of the central directory   8 bytes
    # offset of start of central
    # directory with respect to
    io << [start_of_central_directory_location].pack(C_UINT8) # the starting disk number        8 bytes
    # zip64 extensible data sector    (variable size), blank for us

    # [zip64 end of central directory locator]
    io << [0x07064b50].pack(C_UINT4)                           # zip64 end of central dir locator
    # signature                       4 bytes  (0x07064b50)
    io << [0].pack(C_UINT4)                                    # number of the disk with the
    # start of the zip64 end of
    # central directory               4 bytes
    io << [zip64_eocdr_offset].pack(C_UINT8)                  # relative offset of the zip64
    # end of central directory record 8 bytes
    # (note: "relative" is actually "from the start of the file")
    io << [1].pack(C_UINT4)                                    # total number of disks           4 bytes
  end

  # Then the end of central directory record:
  io << [0x06054b50].pack(C_UINT4)                            # end of central dir signature     4 bytes  (0x06054b50)
  io << [0].pack(C_UINT2)                                     # number of this disk              2 bytes
  io << [0].pack(C_UINT2)                                     # number of the disk with the
  # start of the central directory 2 bytes

  if zip64_required # the number of entries will be read from the zip64 part of the central directory
    io << [TWO_BYTE_MAX_UINT].pack(C_UINT2)                   # total number of entries in the
    # central directory on this disk   2 bytes
    io << [TWO_BYTE_MAX_UINT].pack(C_UINT2)                   # total number of entries in
  # the central directory            2 bytes
  else
    io << [num_files_in_archive].pack(C_UINT2)                # total number of entries in the
    # central directory on this disk   2 bytes
    io << [num_files_in_archive].pack(C_UINT2)                # total number of entries in
    # the central directory            2 bytes
  end

  if zip64_required
    io << [FOUR_BYTE_MAX_UINT].pack(C_UINT4)                  # size of the central directory    4 bytes
    io << [FOUR_BYTE_MAX_UINT].pack(C_UINT4)                  # offset of start of central
  # directory with respect to
  # the starting disk number        4 bytes
  else
    io << [central_directory_size].pack(C_UINT4)              # size of the central directory    4 bytes
    io << [start_of_central_directory_location].pack(C_UINT4) # offset of start of central
    # directory with respect to
    # the starting disk number        4 bytes
  end
  io << [comment.bytesize].pack(C_UINT2)                      # .ZIP file comment length        2 bytes
  io << comment                                           # .ZIP file comment       (variable size)
end

#write_local_file_header(io:, filename:, compressed_size:, uncompressed_size:, crc32:, gp_flags:, mtime:, storage_mode:) ⇒ void

This method returns an undefined value.

Writes the local file header, that precedes the actual file data.

Parameters:

  • io (#<<)

    the buffer to write the local file header to

  • filename (String)

    the name of the file in the archive

  • compressed_size (Fixnum)

    The size of the compressed (or stored) data - how much space it uses in the ZIP

  • uncompressed_size (Fixnum)

    The size of the file once extracted

  • crc32 (Fixnum)

    The CRC32 checksum of the file

  • mtime (Time)

    the modification time to be recorded in the ZIP

  • gp_flags (Fixnum)

    bit-packed general purpose flags

  • storage_mode (Fixnum)

    8 for deflated, 0 for stored...



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
# File 'lib/zip_tricks/zip_writer.rb', line 85

def write_local_file_header(io:, filename:, compressed_size:, uncompressed_size:, crc32:, gp_flags:, mtime:, storage_mode:)
  requires_zip64 = (compressed_size > FOUR_BYTE_MAX_UINT || uncompressed_size > FOUR_BYTE_MAX_UINT)

  io << [0x04034b50].pack(C_UINT4)                        # local file header signature     4 bytes  (0x04034b50)
  io << if requires_zip64                                 # version needed to extract       2 bytes
    [VERSION_NEEDED_TO_EXTRACT_ZIP64].pack(C_UINT2)
  else
    [VERSION_NEEDED_TO_EXTRACT].pack(C_UINT2)
  end

  io << [gp_flags].pack(C_UINT2)                          # general purpose bit flag        2 bytes
  io << [storage_mode].pack(C_UINT2)                      # compression method              2 bytes
  io << [to_binary_dos_time(mtime)].pack(C_UINT2)         # last mod file time              2 bytes
  io << [to_binary_dos_date(mtime)].pack(C_UINT2)         # last mod file date              2 bytes
  io << [crc32].pack(C_UINT4)                             # crc-32                          4 bytes

  if requires_zip64
    io << [FOUR_BYTE_MAX_UINT].pack(C_UINT4)              # compressed size              4 bytes
    io << [FOUR_BYTE_MAX_UINT].pack(C_UINT4)              # uncompressed size            4 bytes
  else
    io << [compressed_size].pack(C_UINT4)                 # compressed size              4 bytes
    io << [uncompressed_size].pack(C_UINT4)               # uncompressed size            4 bytes
  end

  # Filename should not be longer than 0xFFFF otherwise this wont fit here
  io << [filename.bytesize].pack(C_UINT2)                 # file name length             2 bytes

  extra_fields = StringIO.new

  # Interesting tidbit:
  # https://social.technet.microsoft.com/Forums/windows/en-US/6a60399f-2879-4859-b7ab-6ddd08a70948
  # TL;DR of it is: Windows 7 Explorer _will_ open Zip64 entries. However, it desires to have the
  # Zip64 extra field as _the first_ extra field.
  if requires_zip64
    extra_fields << zip_64_extra_for_local_file_header(compressed_size: compressed_size, uncompressed_size: uncompressed_size)
  end
  extra_fields << timestamp_extra(mtime)

  io << [extra_fields.size].pack(C_UINT2)                # extra field length              2 bytes

  io << filename                                     # file name (variable size)
  io << extra_fields.string
end