Debian Codegraph @

tools/pycdlib-genisoimage

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright (C) 2017-2021 Chris Lalancette <[email protected]>
4
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation;
8 # version 2.1 of the License.
9
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 """
20 A drop-in replacement program for the 'genisoimage' executable that uses
21 PyCdlib under the hood.
22 """
23
24 from __future__ import print_function
25
26 import argparse
27 import collections
28 import fileinput
29 import fnmatch
30 import os
31 import sys
32 import time
33 try:
34 from cStringIO import StringIO as BytesIO
35 except ImportError:
36 from io import BytesIO
37
38 import pycdlib
39
40 ################################ MURMER3 HASH FUNCTIONS ##############################
41
42 if sys.version_info >= (3, 0):
43 def xrange(a, b, c):
44 """An xrange that works for Python 3."""
45 return range(a, b, c)
46
47 def xencode(x):
48 """A version of encode that works for bytes, bytearrays, or strings."""
49 if isinstance(x, (bytearray, bytes)):
50 return x
51 return x.encode()
52 else:
53 def xencode(x):
54 """The identity version of xencode for Python 2."""
55 return x
56
57
58 def mm3hash(key, seed=0x0):
59 """Implements 32bit murmur3 hash."""
60
61 key = bytearray(xencode(key))
62
63 def fmix(h):
64 """A function to mix h."""
65 h ^= h >> 16
66 h = (h * 0x85ebca6b) & 0xFFFFFFFF
67 h ^= h >> 13
68 h = (h * 0xc2b2ae35) & 0xFFFFFFFF
69 h ^= h >> 16
70 return h
71
72 length = len(key)
73 nblocks = int(length / 4)
74
75 h1 = seed
76
77 c1 = 0xcc9e2d51
78 c2 = 0x1b873593
79
80 # body
81 for block_start in xrange(0, nblocks * 4, 4):
82 # ??? big endian?
83 k1 = key[block_start + 3] << 24 | key[block_start + 2] << 16 | key[block_start + 1] << 8 | key[block_start + 0]
84
85 k1 = (c1 * k1) & 0xFFFFFFFF
86 k1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF # inlined ROTL32
87 k1 = (c2 * k1) & 0xFFFFFFFF
88
89 h1 ^= k1
90 h1 = (h1 << 13 | h1 >> 19) & 0xFFFFFFFF # inlined ROTL32
91 h1 = (h1 * 5 + 0xe6546b64) & 0xFFFFFFFF
92
93 # tail
94 tail_index = nblocks * 4
95 k1 = 0
96 tail_size = length & 3
97
98 if tail_size >= 3:
99 k1 ^= key[tail_index + 2] << 16
100 if tail_size >= 2:
101 k1 ^= key[tail_index + 1] << 8
102 if tail_size >= 1:
103 k1 ^= key[tail_index + 0]
104
105 if tail_size > 0:
106 k1 = (k1 * c1) & 0xFFFFFFFF
107 k1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF # inlined ROTL32
108 k1 = (k1 * c2) & 0xFFFFFFFF
109 h1 ^= k1
110
111 # finalization
112 unsigned_val = fmix(h1 ^ length)
113 if unsigned_val & 0x80000000 == 0:
114 return unsigned_val
115
116 return -((unsigned_val ^ 0xFFFFFFFF) + 1)
117
118
119 def mm3hashfromfile(filename):
120 """A function to generate a Murmur3 hash given a filename."""
121 with open(filename, 'rb') as infp:
122 done = False
123 seed = 0
124 while not done:
125 data = infp.read(32 * 1024)
126 if len(data) < 32 * 1024:
127 # EOF
128 done = True
129 seed = mm3hash(data, seed)
130
131 return seed
132
133
134 ################################ HELPER FUNCTIONS ##############################
135
136
137 def match_entry_to_list(pattern_list, entry):
138 """
139 A function to match a string to a list of filename patterns. If any of them
140 match, returns True, otherwise, returns False.
141
142 Parameters:
143 pattern_list - The list of filename patterns to check against
144 entry - The string to check
145 Returns:
146 True if the string matches any of the filename patterns, False otherwise.
147 """
148 for pattern in pattern_list:
149 if fnmatch.fnmatch(entry, pattern):
150 return True
151
152 return False
153
154
155 def parse_file_list(thelist):
156 """
157 A function to take a list of filenames, open each one for reading, and
158 yield each of the lines in the file.
159
160 Parameters:
161 thelist - The list of files to open
162 Returns:
163 Nothing.
164 """
165 for f in thelist:
166 with open(f, 'r') as infp:
167 for line in infp.xreadlines():
168 yield line.rstrip()
169
170
171 def build_joliet_path(root, name):
172 """
173 A function to build a complete, valid Joliet path based on a root directory
174 and a name.
175
176 Parameters:
177 root - The root directory name
178 name - The name for the Joliet entry
179 Returns:
180 A valid, absolute Joliet filename.
181 """
182 if root and root[0] == '/':
183 root = root[1:]
184 intermediate = ''
185 for intdir in root.split('/'):
186 if not intdir:
187 continue
188
189 intermediate += '/' + intdir[:64]
190
191 return intermediate + '/' + name[:64]
192
193
194 def build_udf_path(root, name):
195 """
196 A function to build a complete, valid UDF path based on a root directory
197 and a name.
198
199 Parameters:
200 root - The root directory name.
201 name - The name for the UDF entry.
202 Returns:
203 A valid, absolute UDF filename.
204 """
205 if root and root[0] == '/':
206 root = root[1:]
207 intermediate = ''
208 for intdir in root.split('/'):
209 if not intdir:
210 continue
211
212 intermediate += '/' + intdir
213
214 return intermediate + '/' + name
215
216
217 class EltoritoEntry(object):
218 """
219 A class that represents a single El Torito entry on the ISO. There may be
220 more than one of these per-ISO, so each one is tracked separately.
221 """
222
223 __slots__ = ('bootfile_orig', 'bootfile_parts', 'mediatype', 'boot',
224 'load_size', 'load_seg', 'boot_info_table',
225 'bootfile_iso_path', 'dirlevel')
226
227 def __init__(self):
228 self.bootfile_orig = ''
229 self.bootfile_parts = []
230 self.mediatype = 'floppy'
231 self.boot = True
232 self.load_size = 0
233 self.load_seg = 0
234 self.boot_info_table = False
235 self.bootfile_iso_path = ''
236 self.dirlevel = None
237
238 def set_bootfile(self, bootfile):
239 """
240 Set the bootfile for this El Torito entry.
241
242 Parameters:
243 bootfile - The bootfile to set for this El Torito entry
244 Returns:
245 Nothing.
246 """
247 self.bootfile_orig = bootfile
248 self.bootfile_parts = bootfile.split('/')
249
250
251 def parse_arguments():
252 """
253 A function to parse all of the arguments passed to the executable. Note
254 that the set of arguments accepted is intentionally compatible with
255 genisoimage. Also note that this executable does not support all flags
256 below, and will silently ignore ones it doesn't understand. This is to
257 keep maximum compatibility with genisoimage.
258
259 Parameters:
260 None.
261 Returns:
262 An ArgumentParser object with the parsed command-line arguments.
263 """
264 parser = argparse.ArgumentParser(add_help=False)
265 parser.add_argument('-nobak', '-no-bak', help='Do not include backup files', action='store_true')
266 parser.add_argument('-abstract', help='Set Abstract filename', action='store', default='')
267 parser.add_argument('-appid', '-A', help='Set Application ID', action='store', default='')
268 parser.add_argument('-biblio', help='Set Bibliographic filename', action='store', default='')
269 parser.add_argument('-cache-inodes', help='Cache inodes (needed to detect hard links)', action='store_true')
270 parser.add_argument('-no-cache-inodes', help='Do not cache inodes (if filesystem has no unique unides)', action='store_true')
271 parser.add_argument('-check-oldnames', help='Check all imported ISO9660 names from old session', action='store_true')
272 parser.add_argument('-check-session', help='Check all ISO9660 names from previous session', action='store')
273 parser.add_argument('-copyright', help='Set Copyright filename', action='store', default='')
274 parser.add_argument('-debug', help='Set debug flag', action='store_true')
275 parser.add_argument('-eltorito-boot', '-b', help='Set El Torito boot image name', action='store')
276 parser.add_argument('-efi-boot', '-e', help='Set EFI boot image name', action='append')
277 parser.add_argument('-eltorito-alt-boot', help='Start specifying alternative El Torito boot parameters', action='append_const', const=True)
278 parser.add_argument('-sparc-boot', '-B', help='Set sparc boot image names', action='store')
279 parser.add_argument('-sunx86-boot', help='Set sunx86 boot image names', action='store')
280 parser.add_argument('-generic-boot', '-G', help='Set generic boot image name', action='store')
281 parser.add_argument('-sparc-label', help='Set sparc boot disk label', action='store', nargs=2)
282 parser.add_argument('-sunx86-label', help='Set sunx86 boot disk label', action='store', nargs=2)
283 parser.add_argument('-eltorito-catalog', '-c', help='Set El Torito boot catalog name', action='store', default=None)
284 parser.add_argument('-cdrecord-params', '-C', help='Magic parameters from cdrecord', action='store')
285 parser.add_argument('-omit-period', '-d', help='Omit trailing periods from filenames (violates ISO9660)', action='store_true')
286 parser.add_argument('-dir-mode', help='Make the mode of all directories this mode', action='store')
287 parser.add_argument('-disable-deep-relocation', '-D', help='Disable deep directory relocation (violates ISO9660)', action='store_true')
288 parser.add_argument('-file-mode', help='Make the mode of all plain files this mode', action='store')
289 parser.add_argument('-follow-links', '-f', help='Follow symbolic links', action='store_true')
290 parser.add_argument('-gid', help='Make the group owner of all files this gid', action='store')
291 parser.add_argument('-graft-points', help='Allow to use graft points for filenames', action='store_true')
292 parser.add_argument('-root', help='Set root directory for all new files and directories', action='store')
293 parser.add_argument('-old-root', help='Set root directory in previous session this is searched for files', action='store')
294 parser.add_argument('-help', help='Print option help', action='help')
295 parser.add_argument('-hide', help='Hide ISO9660/RR file', action='append', default=[])
296 parser.add_argument('-hide-list', help='File with list of ISO9660/RR files to hide', action='append', default=[])
297 parser.add_argument('-hidden', help='Set hidden attribute on ISO9660 file', action='append', default=[])
298 parser.add_argument('-hidden-list', help='File with list of ISO9660 files with hidden attribute', action='append', default=[])
299 parser.add_argument('-hide-joliet', help='Hide Joliet file', action='append', default=[])
300 parser.add_argument('-hide-joliet-list', help='File with list of Joliet files to hide', action='append', default=[])
301 parser.add_argument('-hide-joliet-trans-tbl', help='Hide TRANS.TBL from Joliet tree', action='store_true')
302 parser.add_argument('-hide-rr-moved', help='Rename RR_MOVED to .rr_moved in Rock Ridge tree', action='store_true')
303 parser.add_argument('-gui', help='Switch behavior for GUI', action='store_true')
304 parser.add_argument('-i', help='No longer supported', action='store')
305 parser.add_argument('-input-charset', help='Local input charset for file name conversion', action='store')
306 parser.add_argument('-output-charset', help='Output charset for file name conversion', action='store')
307 parser.add_argument('-iso-level', help='Set ISO9660 conformance level (1..3) or 4 for ISO9660 version 2', action='store', default=1, type=int, choices=range(1, 5))
308 parser.add_argument('-joliet', '-J', help='Generate Joliet directory information', action='store_true', default=False)
309 parser.add_argument('-joliet-long', help='Allow Joliet file names to be 103 Unicode characters', action='store_true')
310 parser.add_argument('-jcharset', help='Local charset for Joliet directory information', action='store')
311 parser.add_argument('-full-iso9660-filenames', '-l', help='Allow full 31 character filenames for ISO9660 names', action='store_true')
312 parser.add_argument('-max-iso9660-filenames', help='Allow 37 character filenames for ISO9660 names (violates ISO9660)', action='store_true')
313 parser.add_argument('-allow-limited-size', help='Allow different file sizes in ISO9660/UDF on large files', action='store_true')
314 parser.add_argument('-allow-leading-dots', '-ldots', '-L', help="Allow ISO9660 filenames to start with '.' (violates ISO9660)", action='store_true')
315 parser.add_argument('-log-file', help='Re-direct messages to LOG_FILE', action='store')
316 parser.add_argument('-exclude', '-m', help='Exclude file name', action='append', default=[])
317 parser.add_argument('-exclude-list', help='File with list of file names to exclude', action='append', default=[])
318 parser.add_argument('-pad', help='Pad output to a multiple of 32k (default)', action='store_true')
319 parser.add_argument('-no-pad', help='Do not pad output to a multiple of 32k', action='store_true')
320 parser.add_argument('-prev-session', '-M', help='Set path to previous session to merge', action='store')
321 parser.add_argument('-dev', help='Device', action='store')
322 parser.add_argument('-omit-version-number', '-N', help='Omit version number from ISO9660 filename (violates ISO9660)', action='store_true')
323 parser.add_argument('-new-dir-mode', help='Mode used when creating new directories', action='store')
324 parser.add_argument('-force-rr', help='Inhibit automatic Rock Ridge detection for previous session', action='store_true')
325 parser.add_argument('-no-rr', help='Inhibit reading of Rock Ridge attributes from previous session', action='store_true')
326 parser.add_argument('-no-split-symlink-components', help='Inhibit splitting symlink components', action='store_true')
327 parser.add_argument('-no-split-symlink-fields', help='Inhibit splitting symlink fields', action='store_true')
328 parser.add_argument('-output', '-o', help='Set output file name', action='store')
329 parser.add_argument('-path-list', help='File with list of pathnames to process', action='store')
330 parser.add_argument('-preparer', '-p', help='Set Volume preparer', action='store', default='')
331 parser.add_argument('-print-size', help='Print estimated filesystem size and exit', action='store_true')
332 parser.add_argument('-publisher', '-P', help='Set Volume publisher', action='store', default='')
333 parser.add_argument('-quiet', help='Run quietly', action='store_true')
334 parser.add_argument('-rational-rock', '-r', help='Generate rationalized Rock Ridge directory information', action='store_true', default=False)
335 parser.add_argument('-rock', '-R', help='Generate Rock Ridge directory information', action='store_true', default=False)
336 parser.add_argument('-sectype', '-s', help='Set output sector type to e.g. data/xa1/raw', action='store')
337 parser.add_argument('-alpha-boot', help='Set alpha boot image name (relative to image root)', action='store')
338 parser.add_argument('-hppa-cmdline', help='Set hppa boot command line (relative to image root)', action='store')
339 parser.add_argument('-hppa-kernel-32', help='Set hppa 32-bit image name (relative to image root)', action='store')
340 parser.add_argument('-hppa-kernel-64', help='Set hppa 64-bit image name (relative to image root)', action='store')
341 parser.add_argument('-hppa-bootloader', help='Set hppa boot loader file name (relative to image root)', action='store')
342 parser.add_argument('-hppa-ramdisk', help='Set hppa ramdisk file name (relative to image root)', action='store')
343 parser.add_argument('-mips-boot', help='Set mips boot image name (relative to image root)', action='store')
344 parser.add_argument('-mipsel-boot', help='Set mipsel boot image name (relative to image root)', action='store')
345 parser.add_argument('-jigdo-jigdo', help='Produce a jigdo .jigdo file as well as the .iso', action='store')
346 parser.add_argument('-jigdo-template', help='Produce a jigdo .template file as well as the .iso', action='store')
347 parser.add_argument('-jigdo-min-file-size', help='Minimum size for a file to be listed in the jigdo file', action='store')
348 parser.add_argument('-jigdo-force-md5', help='Pattern(s) where files MUST match an externally-supplied MD5Sum', action='store')
349 parser.add_argument('-jigdo-exclude', help='Pattern(s) to exclude from the jigdo file', action='store')
350 parser.add_argument('-jigdo-map', help='Pattern(s) to map paths (e.g. Debian=/mirror/debian)', action='store')
351 parser.add_argument('-md5-list', help='File containing MD5 sums of the files that should be checked', action='store')
352 parser.add_argument('-jigdo-template-compress', help='Choose to use gzip or bzip2 compression for template data; default is gzip', action='store')
353 parser.add_argument('-checksum_algorithm_iso', help='Specify the checksum types desired for the output image', action='store')
354 parser.add_argument('-checksum_algorithm_template', help='Specify the checksum types desired for the output jigdo template', action='store')
355 parser.add_argument('-sort', help='Sort file content locations according to rules in FILE', action='store')
356 parser.add_argument('-split-output', help='Split output into files of approx. 1GB size', action='store_true')
357 parser.add_argument('-stream-file-name', help='Set the stream file ISO9660 name (incl. version)', action='store')
358 parser.add_argument('-stream-media-size', help='Set the size of your CD media in sectors', action='store')
359 parser.add_argument('-sysid', help='Set System ID', action='store', default='')
360 parser.add_argument('-translation-table', '-T', help="Generate translation tables for systems that don't understand long filenames", action='store_true')
361 parser.add_argument('-table-name', help='Translation table file name', action='store')
362 parser.add_argument('-ucs-level', help='Set Joliet UCS level (1..3)', action='store')
363 parser.add_argument('-udf', help='Generate UDF file system', action='store_true')
364 parser.add_argument('-dvd-video', help='Generate DVD-Video compliant UDF file system', action='store_true')
365 parser.add_argument('-uid', help='Make the owner of all files this uid', action='store')
366 parser.add_argument('-untranslated-filenames', '-U',
367 help='Allow Untranslated filenames (for HPUX & AIX - violates ISO9660). Forces -l, -d, -N, -allow-leading-dots, -relaxed-filenames, -allow-lowercase, -allow-multidot',
368 action='store_true')
369 parser.add_argument('-relaxed-filenames', help='Allow 7 bit ASCII except lower case characters (violates ISO9660)', action='store_true')
370 parser.add_argument('-no-iso-translate', help="Do not translate illegal ISO characters '~', '-', and '#' (violates ISO9660)", action='store_true')
371 parser.add_argument('-allow-lowercase', help='Allow lower case characters in addition to the current character set (violates ISO9660)', action='store_true')
372 parser.add_argument('-allow-multidot', help='Allow more than one dot in filenames (e.g. .tar.gz) (violates ISO9660)', action='store_true')
373 parser.add_argument('-use-fileversion', help='Use fileversion # from filesystem', action='store')
374 parser.add_argument('-verbose', '-v', help='Verbose', action='store_true')
375 parser.add_argument('-version', help='Print the current version', action='store_true')
376 parser.add_argument('-volid', '-V', help='Set Volume ID', action='store', default='')
377 parser.add_argument('-volset', help='Set Volume set ID', action='store', default='')
378 parser.add_argument('-volset-size', help='Set Volume set size', action='store', default=1)
379 parser.add_argument('-volset-seqno', help='Set Volume set sequence number', action='store', default=1)
380 parser.add_argument('-old-exclude', '-x', help='Exclude file name (deprecated)', action='append', default=[])
381 parser.add_argument('-hard-disk-boot', help='Boot image is a hard disk image', action='append_const', const=True)
382 parser.add_argument('-no-emul-boot', help="Boot image is a 'no emulation' image", action='append_const', const=True)
383 parser.add_argument('-no-boot', help='Boot image is not bootable', action='append_const', const=True)
384 parser.add_argument('-boot-load-seg', help='Set load segment for boot image', action='append')
385 parser.add_argument('-boot-load-size', help='Set number of load sectors', action='append')
386 parser.add_argument('-boot-info-table', help='Patch boot image with info table', action='append_const', const=True)
387 parser.add_argument('-XA', help='Generate XA directory attributes', action='store_true')
388 parser.add_argument('-xa', help='Generate rationalized XA directory attributes', action='store_true')
389 parser.add_argument('-transparent-compression', '-z', help='Enable transparent compression of files', action='store_true')
390 parser.add_argument('-hfs-type', help='Set HFS default TYPE', action='store')
391 parser.add_argument('-hfs-creator', help='Set HFS default CREATOR', action='store')
392 parser.add_argument('-apple', '-g', help='Add Apple ISO9660 extensions', action='store_true')
393 parser.add_argument('-hfs', '-h', help='Create ISO9660/HFS hybrid', action='store_true')
394 parser.add_argument('-map', '-H', help='Map file extensions to HFS TYPE/CREATOR', action='store')
395 parser.add_argument('-magic', help='Magic file for HFS TYPE/CREATOR', action='store')
396 parser.add_argument('-probe', help='Probe all files for Apple/Unix file types', action='store_true')
397 parser.add_argument('-mac-name', help='Use Macintosh name for ISO9660/Joliet/RockRidge file name', action='store_true')
398 parser.add_argument('-no-mac-files', help='Do not look for Unix/Mac files (deprecated)', action='store_true')
399 parser.add_argument('-boot-hfs-file', help='Set HFS boot image name', action='store')
400 parser.add_argument('-part', help='Generate HFS partition table', action='store_true')
401 parser.add_argument('-cluster-size', help='Cluster size for PC Exchange Macintosh files', action='store')
402 parser.add_argument('-auto', help='Set HFS AutoStart file name', action='store')
403 parser.add_argument('-no-desktop', help='Do not create the HFS (empty) Desktop files', action='store_true')
404 parser.add_argument('-hide-hfs', help='Hide HFS file', action='append', default=[])
405 parser.add_argument('-hide-hfs-list', help='List of HFS files to hide', action='append', default=[])
406 parser.add_argument('-hfs-volid', help='Volume name for the HFS partition', action='store')
407 parser.add_argument('-icon-position', help='Keep HFS icon position', action='store_true')
408 parser.add_argument('-root-info', help='finderinfo for root folder', action='store')
409 parser.add_argument('-input-hfs-charset', help='Local input charset for HFS file name conversion', action='store')
410 parser.add_argument('-output-hfs-charset', help='Output charset for HFS file name conversion', action='store')
411 parser.add_argument('-hfs-unlock', help='Leave HFS volume unlocked', action='store_true')
412 parser.add_argument('-hfs-bless', help='Name of Folder to be blessed', action='store')
413 parser.add_argument('-hfs-parms', help='Comma separated list of HFS parameters', action='store')
414 parser.add_argument('-prep-boot', help='PReP boot image file -- up to 4 are allowed', action='store') # FIXME: we need to allow between 1 and 4 arguments
415 parser.add_argument('-chrp-boot', help='Add CHRP boot header', action='store_true')
416 parser.add_argument('--cap', help='Look for AUFS CAP Macintosh files', action='store_true')
417 parser.add_argument('--netatalk', help='Look for NETATALK Macintosh files', action='store_true')
418 parser.add_argument('--double', help='Look for AppleDouble Macintosh files', action='store_true')
419 parser.add_argument('--ethershare', help='Look for Helios EtherShare Macintosh files', action='store_true')
420 parser.add_argument('--exchange', help='Look for PC Exchange Macintosh files', action='store_true')
421 parser.add_argument('--sgi', help='Look for SGI Macintosh files', action='store_true')
422 parser.add_argument('--macbin', help='Look for MacBinary Macintosh files', action='store_true')
423 parser.add_argument('--single', help='Look for AppleSingle Macintosh files', action='store_true')
424 parser.add_argument('--ushare', help='Look for IPT UShare Macintosh files', action='store_true')
425 parser.add_argument('--xinet', help='Look for XINET Macintosh files', action='store_true')
426 parser.add_argument('--dave', help='Look for DAVE Macintosh files', action='store_true')
427 parser.add_argument('--sfm', help='Look for SFM Macintosh files', action='store_true')
428 parser.add_argument('--osx-double', help='Look for MacOS X AppleDouble Macintosh files', action='store_true')
429 parser.add_argument('--osx-hfs', help='Look for MacOS X HFS Macintosh files', action='store_true')
430 parser.add_argument('-find', help='Option separator: Use find command line to the right', action='store')
431 parser.add_argument('-posix-H', help='Follow symbolic links encountered on command line', action='store_true')
432 parser.add_argument('-posix-L', help='Follow all symbolic links', action='store_true')
433 parser.add_argument('-posix-P', help='Do not follow symbolic links (default)', action='store_true')
434 parser.add_argument('-rrip110', help='Create old Rock Ridge V 1.10', action='store_true')
435 parser.add_argument('-rrip112', help='Create new Rock Ridge V 1.12 (default)', action='store_true')
436 parser.add_argument('-ignore-error', help='Ignore errors', action='store_true')
437 parser.add_argument('-eltorito-platform', help='Set El Torito platform id for the next boot entry', action='store')
438 parser.add_argument('-data-change-warn', help='Treat data/size changes as warning only', action='store_true')
439 parser.add_argument('-errctl', help='Read error control defs from file or inline.', action='store')
440 parser.add_argument('-hide-udf', help='Hide UDF file', action='append', default=[])
441 parser.add_argument('-hide-udf-list', help='File with list of UDF files to hide', action='append', default=[])
442 parser.add_argument('-long-rr-time', help='Use long Rock Ridge time format', action='store_true')
443 parser.add_argument('-modification-date', help='Set the modification date field of the PVD', action='store')
444 parser.add_argument('-no-limit-pathtables', help='Allow more than 65535 parent directories (violates ISO9660)', action='store_true')
445 parser.add_argument('-no-long-rr-time', '-short-rr-time', help='Use short Rock Ridge time format', action='store_true')
446 parser.add_argument('-UDF', help='Generate UDF file system', action='store_true')
447 parser.add_argument('-udf-symlinks', help='Create symbolic links on UDF image (default)', action='store_true')
448 parser.add_argument('-no-udf-symlinks', help='Do not create symbolic links on UDF image', action='store_true')
449 parser.add_argument('-no-hfs', help='Do not create ISO9660/HFS hybrid', action='store_true')
450 parser.add_argument('-scan-for-duplicates', help='Aggressively try to find duplicate files to reduce size (very slow!)', action='store_true')
451 parser.add_argument('paths', help='Paths to get data from', action='store', nargs=argparse.REMAINDER)
452 return parser.parse_args()
453
454
455 def determine_eltorito_entries(args):
456 """
457 A function to build up the list of EltoritoEntry objects for this ISO.
458
459 Parameters:
460 args - The ArgumentParser object returned from parse_arguments()
461 Returns:
462 A list of EltoritoEntry objects for this ISO (which may be empty).
463 """
464 eltorito_entries = []
465 efi_boot_index = 0
466 load_seg_index = 0
467 load_size_index = 0
468
469 for arg in sys.argv[1:]:
470 if arg == '-eltorito-alt-boot':
471 eltorito_entries.append(EltoritoEntry())
472 continue
473
474 if arg not in ('-b', '-eltorito-boot', '-e', '-efi-boot',
475 '-no-emul-boot', '-hard-disk-boot', '-no-boot',
476 '-boot-load-seg', '-boot-load-size', '-boot-info-table'):
477 continue
478
479 if not eltorito_entries:
480 entry = EltoritoEntry()
481 eltorito_entries.append(entry)
482 else:
483 entry = eltorito_entries[-1]
484
485 if arg in ('-b', '-eltorito-boot'):
486 entry.set_bootfile(args.eltorito_boot)
487 elif arg in ('-e', '-efi-boot'):
488 entry.set_bootfile(args.efi_boot[efi_boot_index])
489 efi_boot_index += 1
490 elif arg == '-no-emul-boot':
491 entry.mediatype = 'noemul'
492 elif arg == '-hard-disk-boot':
493 entry.mediatype = 'hdemul'
494 elif arg == '-no-boot':
495 entry.boot = False
496 elif arg == '-boot-load-seg':
497 entry.load_seg = int(args.boot_load_seg[load_seg_index])
498 load_seg_index += 1
499 elif arg == '-boot-load-size':
500 entry.load_size = int(args.boot_load_size[load_size_index])
501 load_size_index += 1
502 elif arg == '-boot-info-table':
503 entry.boot_info_table = True
504
505 return eltorito_entries
506
507
508 class DirLevel(object):
509 """
510 A class to hold information about one directory level of the directory
511 hierarchy. Each level has an iso_path, a joliet_path, and a set of
512 mangled maps for mangling filenames as appropriate.
513 """
514
515 __slots__ = ('iso_path', 'joliet_path', 'udf_path', 'mangled_children')
516
517 def __init__(self, iso_path, joliet_path, udf_path):
518 self.iso_path = iso_path
519 self.joliet_path = joliet_path
520 self.udf_path = udf_path
521 self.mangled_children = {}
522
523
524 def build_iso_path(parent_dirlevel, nameonly, iso_level, is_dir):
525 """
526 A function to build an absolute ISO path from a DirLevel object, a name,
527 an ISO interchange level, and whether this is a directory or not.
528
529 Parameters:
530 parent_dirlevel - The DirLevel object representing the parent.
531 nameonly - The basename of the ISO path.
532 iso_level - The ISO interchange level to use.
533 is_dir - Whether this is a directory or not.
534 Returns:
535 A string representing the ISO absolute path.
536 """
537
538 # Mangling the name and keeping track is a complicated affair. First off,
539 # we mangle the incoming dirname so it conforms to ISO9660 rules (see
540 # mangle_dir_for_iso9660() for more info on that). Once we have the
541 # mangled name, we see if that name has been used at this directory level
542 # yet. If it has not been used, we mark it as now used, and return it
543 # unmolested (beyond the ISO9660 mangle). If it has been used, then we
544 # need to strip it down to its prefix (the first 4 characters), add a
545 # 3-digit number starting at zero, then iterate until we find a free one.
546 # Once we have found a free one, we mark it as now used, and return what
547 # we figured out.
548
549 if is_dir:
550 filemangle = pycdlib.utils.mangle_dir_for_iso9660(nameonly, iso_level)
551 else:
552 filename, ext = pycdlib.utils.mangle_file_for_iso9660(nameonly, iso_level)
553 if ext == '':
554 filemangle = filename
555 else:
556 filemangle = '.'.join([filename, ext])
557
558 if filemangle in parent_dirlevel.mangled_children:
559 currnum = 0
560 prefix = filemangle[:5]
561 while True:
562 if is_dir:
563 tmp = '%s%.03d' % (prefix, currnum)
564 else:
565 tmp = '%s%.03d.%s' % (prefix, currnum, ext)
566 if tmp not in parent_dirlevel.mangled_children:
567 filemangle = tmp
568 break
569 currnum += 1
570 if currnum == 1000:
571 return None
572
573 parent_dirlevel.mangled_children[filemangle] = True
574
575 parent_iso_path = parent_dirlevel.iso_path
576 if parent_dirlevel.iso_path == '/':
577 parent_iso_path = parent_dirlevel.iso_path[1:]
578 return parent_iso_path + '/' + filemangle
579
580
581 ################################### MAIN #######################################
582
583 def main():
584 """
585 The main function for this executable that does the main work of generating
586 an ISO given the parameters specified by the user.
587 """
588 args = parse_arguments()
589
590 eltorito_entries = determine_eltorito_entries(args)
591
592 if args.quiet:
593 logfp = open(os.devnull, 'w') # pylint: disable=consider-using-with
594 else:
595 if args.log_file is not None:
596 print('re-directing all messages to %s' % (args.log_file))
597 logfp = open(args.log_file, 'w') # pylint: disable=consider-using-with
598 else:
599 logfp = sys.stdout
600
601 print('pycdlib-genisoimage 1.0.0', file=logfp)
602
603 # Check out all of the arguments we can here.
604 if args.version:
605 sys.exit(0)
606
607 rock_version = None
608 if args.rational_rock or args.rock:
609 rock_version = '1.09'
610 if args.rrip110:
611 rock_version = '1.10'
612 if args.rrip112:
613 rock_version = '1.12'
614
615 udf_version = None
616 if args.udf or args.UDF:
617 udf_version = '2.60'
618
619 if args.joliet and rock_version is None:
620 print('Warning: creating filesystem with Joliet extensions but without Rock Ridge', file=logfp)
621 print(' extensions. It is highly recommended to add Rock Ridge.', file=logfp)
622
623 if args.eltorito_catalog is not None and not eltorito_entries:
624 print('genisoimage: No boot image specified.', file=logfp)
625 sys.exit(255)
626
627 if args.i is not None:
628 print('genisoimage: -i option no longer supported.', file=logfp)
629 sys.exit(255)
630
631 hidden_patterns = args.hidden
632 for pattern in parse_file_list(args.hidden_list):
633 hidden_patterns.append(pattern)
634
635 exclude_patterns = args.exclude + args.old_exclude
636 for pattern in parse_file_list(args.exclude_list):
637 exclude_patterns.append(pattern)
638
639 hide_patterns = args.hide
640 for pattern in parse_file_list(args.hide_list):
641 hide_patterns.append(pattern)
642
643 hide_joliet_patterns = args.hide_joliet
644 for pattern in parse_file_list(args.hide_joliet_list):
645 hide_joliet_patterns.append(pattern)
646
647 hide_udf_patterns = args.hide_udf
648 for pattern in parse_file_list(args.hide_udf_list):
649 hide_udf_patterns.append(pattern)
650
651 ignore_patterns = []
652 if args.nobak:
653 ignore_patterns.extend(('*~*', '*#*', '*.bak'))
654
655 if args.print_size:
656 fp = BytesIO()
657 else:
658 if args.output is None:
659 print('Output file must be specified (use -o)', file=logfp)
660 sys.exit(1)
661
662 fp = open(args.output, 'wb') # pylint: disable=consider-using-with
663
664 # Figure out Joliet flag, which is the combination of args.joliet
665 # and args.ucs_level.
666 joliet_level = None
667 if args.joliet:
668 joliet_level = 3
669 if args.ucs_level is not None:
670 joliet_level = int(args.ucs_level)
671
672 eltorito_catalog_path = ''
673 eltorito_catalog_parts = []
674 if args.eltorito_catalog is not None:
675 eltorito_catalog_parts = args.eltorito_catalog.split('/')
676
677 # Create a new PyCdlib object.
678 iso = pycdlib.PyCdlib()
679
680 if args.hide_rr_moved:
681 iso.set_relocated_name('_RR_MOVE', '.rr_moved')
682
683 # Create a new ISO.
684 iso.new(interchange_level=args.iso_level,
685 sys_ident=args.sysid,
686 vol_ident=args.volid,
687 set_size=args.volset_size,
688 seqnum=args.volset_seqno,
689 vol_set_ident=args.volset,
690 pub_ident_str=args.publisher,
691 preparer_ident_str=args.preparer,
692 app_ident_str=args.appid,
693 copyright_file=args.copyright,
694 abstract_file=args.abstract,
695 bibli_file=args.biblio,
696 joliet=joliet_level,
697 rock_ridge=rock_version,
698 xa=(args.XA or args.xa),
699 udf=udf_version)
700
701 path_list = args.paths
702
703 if args.path_list is not None:
704 for line in fileinput.input(args.path_list):
705 path_list.append(line.strip())
706
707 size_to_name_and_hashes = {}
708 for path in path_list:
709 check_eltorito_catalog = len(eltorito_catalog_parts) > 0
710 root_level = DirLevel('/', '/', '/')
711 for eltorito_entry in eltorito_entries:
712 eltorito_entry.dirlevel = root_level
713 entries = collections.deque([(os.path.normpath(path), root_level, False,
714 check_eltorito_catalog)])
715 while entries:
716 localpath, parent_level, add_dir, check_eltorito_catalog = entries.popleft()
717 basename = os.path.basename(localpath)
718
719 if check_eltorito_catalog and len(eltorito_catalog_parts) == 1:
720 filename, ext = pycdlib.utils.mangle_file_for_iso9660(eltorito_catalog_parts.pop(),
721 args.iso_level)
722 eltorito_catalog_path += '/' + filename + '.' + ext
723
724 for eltorito_entry in eltorito_entries:
725 if eltorito_entry.dirlevel == parent_level and len(eltorito_entry.bootfile_parts) == 1:
726 filename, ext = pycdlib.utils.mangle_file_for_iso9660(eltorito_entry.bootfile_parts.pop(),
727 args.iso_level)
728 tail = '.' + ext
729 if ext == '':
730 tail = ''
731 eltorito_entry.bootfile_iso_path += '/' + filename + tail
732
733 rr_name = None
734 if args.rational_rock or args.rock:
735 rr_name = basename
736
737 joliet_path = None
738 if args.joliet:
739 joliet_path = build_joliet_path(parent_level.joliet_path,
740 basename)
741
742 udf_path = None
743 if args.udf or args.UDF:
744 udf_path = build_udf_path(parent_level.udf_path, basename)
745
746 if os.path.islink(localpath):
747 if (not args.rational_rock or args.rock) and (not args.udf or args.UDF):
748 print('Symlink %s ignored - continuing.' % (localpath),
749 file=logfp)
750 else:
751 iso_path = build_iso_path(parent_level, basename,
752 args.iso_level, False)
753 if iso_path is None:
754 print('Could not find free ISO9660 name for path %s; skipping' % (localpath),
755 file=logfp)
756 continue
757
758 rr_target = None
759 if args.rational_rock or args.rock:
760 rr_target = os.readlink(localpath)
761
762 udf_target = None
763 if args.udf or args.UDF:
764 udf_target = os.readlink(localpath)
765
766 iso.add_symlink(iso_path, rr_symlink_name=rr_name, rr_path=rr_target,
767 udf_symlink_path=udf_path, udf_target=udf_target,
768 joliet_path=joliet_path)
769
770 elif os.path.isdir(localpath):
771 if add_dir:
772 iso_path = build_iso_path(parent_level, basename,
773 args.iso_level, True)
774 if iso_path is None:
775 print('Could not find free ISO9660 name for path %s; skipping' % (localpath),
776 file=logfp)
777 continue
778
779 depth = iso_path.count('/')
780 if rr_name is None and depth > 7:
781 print("Directories too deep for '%s' (%d) max is 7; ignored - continuing." % (localpath, depth),
782 file=logfp)
783 continue
784 iso.add_directory(iso_path, rr_name=rr_name,
785 joliet_path=joliet_path,
786 udf_path=udf_path)
787 else:
788 iso_path = parent_level.iso_path
789 joliet_path = parent_level.joliet_path
790 udf_path = parent_level.udf_path
791
792 on_eltorito_catalog_path = False
793 eltorito_duplicate_check = ''
794 if check_eltorito_catalog and len(eltorito_catalog_parts) > 1 and eltorito_catalog_parts[0] == basename:
795 eltorito_catalog_path += '/' + pycdlib.utils.mangle_dir_for_iso9660(basename, args.iso_level)
796 eltorito_catalog_parts.pop(0)
797 on_eltorito_catalog_path = True
798 if len(eltorito_catalog_parts) == 1:
799 eltorito_duplicate_check = eltorito_catalog_parts[0]
800
801 parent = DirLevel(iso_path, joliet_path, udf_path)
802 for eltorito_entry in eltorito_entries:
803 if parent_level == eltorito_entry.dirlevel and len(eltorito_entry.bootfile_parts) > 1 and eltorito_entry.bootfile_parts[0] == basename:
804 eltorito_entry.bootfile_iso_path += '/' + pycdlib.utils.mangle_dir_for_iso9660(basename, args.iso_level)
805 eltorito_entry.bootfile_parts.pop(0)
806 eltorito_entry.dirlevel = parent
807
808 for f in os.listdir(localpath):
809 fullpath = os.path.join(localpath, f)
810
811 if match_entry_to_list(exclude_patterns, f) or eltorito_duplicate_check == f:
812 print('Excluded by match: %s' % (fullpath), file=logfp)
813 continue
814
815 if match_entry_to_list(ignore_patterns, f):
816 print('Ignoring file %s' % (fullpath), file=logfp)
817 continue
818
819 if args.verbose:
820 print('Scanning %s' % (fullpath), file=logfp)
821
822 entries.append((fullpath, parent, True, on_eltorito_catalog_path))
823 else:
824 iso_path = build_iso_path(parent_level, basename,
825 args.iso_level, False)
826 if iso_path is None:
827 print('Could not find free ISO9660 name for path %s; skipping' % (localpath),
828 file=logfp)
829
830 duplicate_name = None
831 if args.scan_for_duplicates:
832 size = os.stat(localpath).st_size
833 if size in size_to_name_and_hashes:
834 thishash = mm3hashfromfile(localpath)
835 for index, name_and_hashes in enumerate(size_to_name_and_hashes[size]):
836 oldlocal, oldiso, oldhash = name_and_hashes
837 if oldhash is None:
838 # The old hash was None, make it, set it, and
839 # test against it
840 oldhash = mm3hashfromfile(oldlocal)
841 size_to_name_and_hashes[size][index][2] = oldhash
842
843 if thishash == oldhash:
844 duplicate_name = oldiso
845 break
846 else:
847 # Something with the same size and same hash was not
848 # in the list. Add this one.
849 size_to_name_and_hashes[size].append([localpath, iso_path, thishash])
850 else:
851 # Nothing with the same size was in the list. Put it in
852 # the size list, but defer calculating the hash until
853 # something else tries to match against it.
854 size_to_name_and_hashes[size] = [[localpath, iso_path, None]]
855
856 if duplicate_name is not None:
857 iso.add_hard_link(iso_old_path=duplicate_name, iso_new_path=iso_path, rr_name=rr_name)
858 if joliet_path is not None:
859 iso.add_hard_link(iso_old_path=duplicate_name, joliet_new_path=joliet_path)
860 if udf_path is not None:
861 iso.add_hard_link(iso_old_path=duplicate_name, udf_new_path=udf_path)
862 else:
863 iso.add_file(localpath, iso_path, rr_name=rr_name,
864 joliet_path=joliet_path, udf_path=udf_path)
865 if match_entry_to_list(hide_patterns, basename):
866 iso.rm_hard_link(iso_path=iso_path)
867
868 if args.joliet and match_entry_to_list(hide_joliet_patterns,
869 basename):
870 iso.rm_hard_link(joliet_path=joliet_path)
871
872 if args.udf and match_entry_to_list(hide_udf_patterns,
873 basename):
874 iso.rm_hard_link(udf_path=udf_path)
875
876 if match_entry_to_list(hidden_patterns, basename):
877 iso.set_hidden(iso_path)
878 print('Hidden ISO9660 attribute: %s' % (localpath), file=logfp)
879
880 # Add in El Torito if it was requested
881 for entry in eltorito_entries:
882 try:
883 iso.add_eltorito(entry.bootfile_iso_path,
884 bootcatfile=eltorito_catalog_path,
885 bootable=entry.boot,
886 boot_load_size=entry.load_size,
887 boot_info_table=entry.boot_info_table,
888 media_name=entry.mediatype,
889 boot_load_seg=entry.load_seg)
890 except pycdlib.pycdlibexception.PyCdlibInvalidInput as e:
891 if 'Could not find path' in str(e):
892 print("Uh oh, I cant find the boot image '%s' !" % (entry.bootfile_orig),
893 file=logfp)
894 sys.exit(255)
895 else:
896 raise
897
898 class ProgressData(object):
899 """
900 A private class to hold onto the data from the last progress call.
901 """
902
903 __slots__ = ('last_percent', 'logfp', 'begun')
904
905 def __init__(self, logfp):
906 self.last_percent = ''
907 self.logfp = logfp
908 self.begun = time.time()
909
910 def progress_cb(done, total, progress_data):
911 """
912 A private function that will be passed into the write_fp method of the
913 PyCdlib object, and prints out the current progress of the mastering.
914
915 Parameters (as prescribed by PyCdlib):
916 done - The amount of data written so far
917 total - The total amount of data to write
918 progress_data - An object of type ProgressData to track progress
919 Returns:
920 Nothing.
921 """
922 frac = float(done) / float(total)
923 percent = '%.2f%%' % (frac * 100)
924 if percent != progress_data.last_percent:
925 the_end = time.time()
926 if frac > 0:
927 the_end = progress_data.begun + (the_end - progress_data.begun) / frac
928 print('%7s done, estimate finish %s' % (percent, time.ctime(the_end)),
929 file=progress_data.logfp)
930 progress_data.last_percent = percent
931
932 iso.write_fp(fp, progress_cb=progress_cb, progress_opaque=ProgressData(logfp))
933
934 if args.print_size:
935 print('Total extents scheduled to be written = %d' % (len(fp.getvalue()) / 2048), file=logfp)
936
937 iso.close()
938
939
940 if __name__ == '__main__':
941 main()