]> wimlib.net Git - wimlib/blob - src/resource.c
4f093622f9e64d356484015f8b45db1cc33635b9
[wimlib] / src / resource.c
1 /*
2  * resource.c
3  *
4  * Read uncompressed and compressed metadata and file resources.
5  */
6
7 /*
8  * Copyright (C) 2010 Carl Thijssen
9  * Copyright (C) 2012 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU Lesser General Public License as published by the Free
15  * Software Foundation; either version 2.1 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #include "wimlib_internal.h"
28 #include "lookup_table.h"
29 #include "io.h"
30 #include "lzx.h"
31 #include "xpress.h"
32 #include "sha1.h"
33 #include "dentry.h"
34 #include "config.h"
35 #include <unistd.h>
36 #include <errno.h>
37 #include <alloca.h>
38
39
40 /* 
41  * Reads all or part of a compressed resource into an in-memory buffer.
42  *
43  * @fp:                 The FILE* for the WIM file.
44  * @resource_compressed_size:    The compressed size of the resource.  
45  * @resource_uncompressed_size:  The uncompressed size of the resource.
46  * @resource_offset:             The offset of the start of the resource from
47  *                                      the start of the stream @fp.
48  * @resource_ctype:     The compression type of the resource. 
49  * @len:                The number of bytes of uncompressed data to read from
50  *                              the resource.
51  * @offset:             The offset of the bytes to read within the uncompressed
52  *                              resource.
53  * @contents_len:       An array into which the uncompressed data is written.
54  *                              It must be at least @len bytes long.
55  *
56  * Returns zero on success, nonzero on failure.
57  */
58 static int read_compressed_resource(FILE *fp, u64 resource_compressed_size, 
59                                     u64 resource_uncompressed_size, 
60                                     u64 resource_offset, int resource_ctype, 
61                                     u64 len, u64 offset, u8  contents_ret[])
62 {
63
64         DEBUG2("comp size = %"PRIu64", uncomp size = %"PRIu64", "
65                "res offset = %"PRIu64"",
66                resource_compressed_size,
67                resource_uncompressed_size,
68                resource_offset);
69         DEBUG2("resource_ctype = %s, len = %"PRIu64", offset = %"PRIu64"",
70                wimlib_get_compression_type_string(resource_ctype), len, offset);
71         /* Trivial case */
72         if (len == 0)
73                 return 0;
74
75         int (*decompress)(const void *, uint, void *, uint);
76         /* Set the appropriate decompress function. */
77         if (resource_ctype == WIM_COMPRESSION_TYPE_LZX)
78                 decompress = lzx_decompress;
79         else
80                 decompress = xpress_decompress;
81
82         /* The structure of a compressed resource consists of a table of chunk
83          * offsets followed by the chunks themselves.  Each chunk consists of
84          * compressed data, and there is one chunk for each WIM_CHUNK_SIZE =
85          * 32768 bytes of the uncompressed file, with the last chunk having any
86          * remaining bytes.
87          *
88          * The chunk offsets are measured relative to the end of the chunk
89          * table.  The first chunk is omitted from the table in the WIM file
90          * because its offset is implicitly given by the fact that it directly
91          * follows the chunk table and therefore must have an offset of 0. 
92          */
93
94         /* Calculate how many chunks the resource conists of in its entirety. */
95         u64 num_chunks = (resource_uncompressed_size + WIM_CHUNK_SIZE - 1) /
96                                                                 WIM_CHUNK_SIZE;
97         /* As mentioned, the first chunk has no entry in the chunk table. */
98         u64 num_chunk_entries = num_chunks - 1;
99
100
101         /* The index of the chunk that the read starts at. */
102         u64 start_chunk = offset / WIM_CHUNK_SIZE;
103         /* The byte offset at which the read starts, within the start chunk. */
104         u64 start_chunk_offset = offset % WIM_CHUNK_SIZE;
105
106         /* The index of the chunk that contains the last byte of the read. */
107         u64 end_chunk   = (offset + len - 1) / WIM_CHUNK_SIZE;
108         /* The byte offset of the last byte of the read, within the end chunk */
109         u64 end_chunk_offset = (offset + len - 1) % WIM_CHUNK_SIZE;
110
111         /* Number of chunks that are actually needed to read the requested part
112          * of the file. */
113         u64 num_needed_chunks = end_chunk - start_chunk + 1;
114
115         /* If the end chunk is not the last chunk, an extra chunk entry is
116          * needed because we need to know the offset of the chunk after the last
117          * chunk read to figure out the size of the last read chunk. */
118         if (end_chunk != num_chunks - 1)
119                 num_needed_chunks++;
120
121         /* Declare the chunk table.  It will only contain offsets for the chunks
122          * that are actually needed for this read. */
123         u64 chunk_offsets[num_needed_chunks];
124
125         /* Set the implicit offset of the first chunk if it is included in the
126          * needed chunks.
127          *
128          * Note: M$'s documentation includes a picture that shows the first
129          * chunk starting right after the chunk entry table, labeled as offset
130          * 0x10.  However, in the actual file format, the offset is measured
131          * from the end of the chunk entry table, so the first chunk has an
132          * offset of 0. */
133         if (start_chunk == 0)
134                 chunk_offsets[0] = 0;
135
136         /* According to M$'s documentation, if the uncompressed size of
137          * the file is greater than 4 GB, the chunk entries are 8-byte
138          * integers.  Otherwise, they are 4-byte integers. */
139         u64 chunk_entry_size = (resource_uncompressed_size >= (u64)1 << 32) ? 
140                                                                         8 : 4;
141
142         /* Size of the full chunk table in the WIM file. */
143         u64 chunk_table_size = chunk_entry_size * num_chunk_entries;
144
145         /* Read the needed chunk offsets from the table in the WIM file. */
146
147         /* Index, in the WIM file, of the first needed entry in the
148          * chunk table. */
149         u64 start_table_idx = (start_chunk == 0) ? 0 : start_chunk - 1;
150
151         /* Number of entries we need to actually read from the chunk
152          * table (excludes the implicit first chunk). */
153         u64 num_needed_chunk_entries = (start_chunk == 0) ? 
154                                 num_needed_chunks - 1 : num_needed_chunks;
155
156         /* Skip over unneeded chunk table entries. */
157         u64 file_offset_of_needed_chunk_entries = resource_offset + 
158                                 start_table_idx * chunk_entry_size;
159         if (fseeko(fp, file_offset_of_needed_chunk_entries, SEEK_SET) != 0) {
160                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
161                                  "chunk table of compressed resource",
162                                  file_offset_of_needed_chunk_entries);
163                 return WIMLIB_ERR_READ;
164         }
165
166         /* Number of bytes we need to read from the chunk table. */
167         size_t size = num_needed_chunk_entries * chunk_entry_size;
168
169         u8 chunk_tab_buf[size];
170
171         if (fread(chunk_tab_buf, 1, size, fp) != size)
172                 goto err;
173
174         /* Now fill in chunk_offsets from the entries we have read in
175          * chunk_tab_buf. */
176
177         u64 *chunk_tab_p = chunk_offsets;
178         if (start_chunk == 0)
179                 chunk_tab_p++;
180
181         if (chunk_entry_size == 4) {
182                 u32 *entries = (u32*)chunk_tab_buf;
183                 while (num_needed_chunk_entries--)
184                         *chunk_tab_p++ = to_le32(*entries++);
185         } else {
186                 u64 *entries = (u64*)chunk_tab_buf;
187                 while (num_needed_chunk_entries--)
188                         *chunk_tab_p++ = to_le64(*entries++);
189         }
190
191         /* Done with the chunk table now.  We must now seek to the first chunk
192          * that is needed for the read. */
193
194         u64 file_offset_of_first_needed_chunk = resource_offset + 
195                                 chunk_table_size + chunk_offsets[0];
196         if (fseeko(fp, file_offset_of_first_needed_chunk, SEEK_SET) != 0) {
197                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
198                                  "first chunk of compressed resource",
199                                  file_offset_of_first_needed_chunk);
200                 return WIMLIB_ERR_READ;
201         }
202
203         /* Pointer to current position in the output buffer for uncompressed
204          * data. */
205         u8 *out_p = (u8*)contents_ret;
206
207         /* Buffer for compressed data.  While most compressed chunks will have a
208          * size much less than WIM_CHUNK_SIZE, WIM_CHUNK_SIZE - 1 is the maximum
209          * size in the worst-case.  This assumption is valid only if chunks that
210          * happen to compress to more than the uncompressed size (i.e. a
211          * sequence of random bytes) are always stored uncompressed. But this seems
212          * to be the case in M$'s WIM files, even though it is undocumented. */
213         u8 compressed_buf[WIM_CHUNK_SIZE - 1];
214
215
216         /* Decompress all the chunks. */
217         for (u64 i = start_chunk; i <= end_chunk; i++) {
218
219                 DEBUG2("Chunk %"PRIu64" (start %"PRIu64", end %"PRIu64").",
220                        i, start_chunk, end_chunk);
221
222                 /* Calculate the sizes of the compressed chunk and of the
223                  * uncompressed chunk. */
224                 uint compressed_chunk_size, uncompressed_chunk_size;
225                 if (i != num_chunks - 1) {
226                         /* All the chunks except the last one in the resource
227                          * expand to WIM_CHUNK_SIZE uncompressed, and the amount
228                          * of compressed data for the chunk is given by the
229                          * difference of offsets in the chunk offset table. */
230                         compressed_chunk_size = chunk_offsets[i + 1 - start_chunk] - 
231                                                 chunk_offsets[i - start_chunk];
232                         uncompressed_chunk_size = WIM_CHUNK_SIZE;
233                 } else {
234                         /* The last compressed chunk consists of the remaining
235                          * bytes in the file resource, and the last uncompressed
236                          * chunk has size equal to however many bytes are left-
237                          * that is, the remainder of the uncompressed size when
238                          * divided by WIM_CHUNK_SIZE. 
239                          *
240                          * Note that the resource_compressed_size includes the
241                          * chunk table, so the size of it must be subtracted. */
242                         compressed_chunk_size = resource_compressed_size - 
243                                                 chunk_table_size -
244                                                 chunk_offsets[i - start_chunk];
245
246                         uncompressed_chunk_size = resource_uncompressed_size % 
247                                                                 WIM_CHUNK_SIZE;
248
249                         /* If the remainder is 0, the last chunk actually
250                          * uncompresses to a full WIM_CHUNK_SIZE bytes. */
251                         if (uncompressed_chunk_size == 0)
252                                 uncompressed_chunk_size = WIM_CHUNK_SIZE;
253                 }
254
255                 DEBUG2("compressed_chunk_size = %u, "
256                        "uncompressed_chunk_size = %u",
257                        compressed_chunk_size, uncompressed_chunk_size);
258
259
260                 /* Figure out how much of this chunk we actually need to read */
261                 u64 start_offset;
262                 if (i == start_chunk)
263                         start_offset = start_chunk_offset;
264                 else
265                         start_offset = 0;
266                 u64 end_offset;
267                 if (i == end_chunk)
268                         end_offset = end_chunk_offset;
269                 else
270                         end_offset = WIM_CHUNK_SIZE - 1;
271
272                 u64 partial_chunk_size = end_offset + 1 - start_offset;
273                 bool is_partial_chunk = (partial_chunk_size != 
274                                                 uncompressed_chunk_size);
275
276                 DEBUG2("start_offset = %u, end_offset = %u", start_offset,
277                                         end_offset);
278                 DEBUG2("partial_chunk_size = %u", partial_chunk_size);
279
280                 /* This is undocumented, but chunks can be uncompressed.  This
281                  * appears to always be the case when the compressed chunk size
282                  * is equal to the uncompressed chunk size. */
283                 if (compressed_chunk_size == uncompressed_chunk_size) {
284                         /* Probably an uncompressed chunk */
285
286                         if (start_offset != 0) {
287                                 if (fseeko(fp, start_offset, SEEK_CUR) != 0) {
288                                         ERROR_WITH_ERRNO("Uncompressed partial "
289                                                          "chunk fseek() error");
290                                         return WIMLIB_ERR_READ;
291                                 }
292                         }
293                         if (fread(out_p, 1, partial_chunk_size, fp) != 
294                                         partial_chunk_size)
295                                 goto err;
296                 } else {
297                         /* Compressed chunk */
298                         int ret;
299
300                         /* Read the compressed data into compressed_buf. */
301                         if (fread(compressed_buf, 1, compressed_chunk_size, 
302                                                 fp) != compressed_chunk_size)
303                                 goto err;
304
305                         /* For partial chunks we must buffer the uncompressed
306                          * data because we don't need all of it. */
307                         if (is_partial_chunk) {
308                                 u8 uncompressed_buf[uncompressed_chunk_size];
309
310                                 ret = decompress(compressed_buf,
311                                                 compressed_chunk_size,
312                                                 uncompressed_buf, 
313                                                 uncompressed_chunk_size);
314                                 if (ret != 0)
315                                         return WIMLIB_ERR_DECOMPRESSION;
316                                 memcpy(out_p, uncompressed_buf + start_offset,
317                                                 partial_chunk_size);
318                         } else {
319                                 ret = decompress(compressed_buf,
320                                                 compressed_chunk_size,
321                                                 out_p,
322                                                 uncompressed_chunk_size);
323                                 if (ret != 0)
324                                         return WIMLIB_ERR_DECOMPRESSION;
325                         }
326                 }
327
328                 /* Advance the pointer into the uncompressed output data by the
329                  * number of uncompressed bytes that were written.  */
330                 out_p += partial_chunk_size;
331         }
332
333         return 0;
334
335 err:
336         if (feof(fp))
337                 ERROR("Unexpected EOF in compressed file resource");
338         else
339                 ERROR_WITH_ERRNO("Error reading compressed file resource");
340         return WIMLIB_ERR_READ;
341 }
342
343 /* 
344  * Reads uncompressed data from an open file stream.
345  */
346 int read_uncompressed_resource(FILE *fp, u64 offset, u64 len,
347                                u8 contents_ret[])
348 {
349         if (fseeko(fp, offset, SEEK_SET) != 0) {
350                 ERROR("Failed to seek to byte %"PRIu64" of input file "
351                       "to read uncompressed resource (len = %"PRIu64")",
352                       offset, len);
353                 return WIMLIB_ERR_READ;
354         }
355         if (fread(contents_ret, 1, len, fp) != len) {
356                 if (feof(fp)) {
357                         ERROR("Unexpected EOF in uncompressed file resource");
358                 } else {
359                         ERROR("Failed to read %"PRIu64" bytes from "
360                               "uncompressed resource at offset %"PRIu64,
361                               len, offset);
362                 }
363                 return WIMLIB_ERR_READ;
364         }
365         return 0;
366 }
367
368
369
370
371 /* Reads the contents of a struct resource_entry, as represented in the on-disk
372  * format, from the memory pointed to by @p, and fills in the fields of @entry.
373  * A pointer to the byte after the memory read at @p is returned. */
374 const u8 *get_resource_entry(const u8 *p, struct resource_entry *entry)
375 {
376         u64 size;
377         u8 flags;
378
379         p = get_u56(p, &size);
380         p = get_u8(p, &flags);
381         entry->size = size;
382         entry->flags = flags;
383         p = get_u64(p, &entry->offset);
384         p = get_u64(p, &entry->original_size);
385         return p;
386 }
387
388 /* Copies the struct resource_entry @entry to the memory pointed to by @p in the
389  * on-disk format.  A pointer to the byte after the memory written at @p is
390  * returned. */
391 u8 *put_resource_entry(u8 *p, const struct resource_entry *entry)
392 {
393         p = put_u56(p, entry->size);
394         p = put_u8(p, entry->flags);
395         p = put_u64(p, entry->offset);
396         p = put_u64(p, entry->original_size);
397         return p;
398 }
399
400 /*
401  * Reads some data from the resource corresponding to a WIM lookup table entry.
402  *
403  * @lte:        The WIM lookup table entry for the resource.
404  * @buf:        Buffer into which to write the data.
405  * @size:       Number of bytes to read.
406  * @offset:     Offset at which to start reading the resource.
407  * @raw:        If %true, compressed data is read literally rather than being
408  *                      decompressed first.
409  *
410  * Returns zero on success, nonzero on failure.
411  */
412 int read_wim_resource(const struct lookup_table_entry *lte, u8 buf[],
413                       size_t size, u64 offset, bool raw)
414 {
415         /* We shouldn't be allowing read over-runs in any part of the library.
416          * */
417         if (raw)
418                 wimlib_assert(offset + size <= lte->resource_entry.size);
419         else
420                 wimlib_assert(offset + size <= lte->resource_entry.original_size);
421
422         int ctype;
423         int ret;
424         FILE *fp;
425         switch (lte->resource_location) {
426         case RESOURCE_IN_WIM:
427                 /* The resource is in a WIM file, and its WIMStruct is given by
428                  * the lte->wim member.  The resource may be either compressed
429                  * or uncompressed. */
430                 wimlib_assert(lte->wim);
431                 wimlib_assert(lte->wim->fp);
432                 ctype = wim_resource_compression_type(lte);
433
434                 /* XXX This check should be moved elsewhere */
435                 if (ctype == WIM_COMPRESSION_TYPE_NONE &&
436                      lte->resource_entry.original_size !=
437                       lte->resource_entry.size) {
438                         ERROR("WIM resource at offset %"PRIu64", size %"PRIu64
439                               "has an original size of %"PRIu64", but is "
440                               "uncompressed",
441                               lte->resource_entry.offset,
442                               lte->resource_entry.size,
443                               lte->resource_entry.original_size);
444                         return WIMLIB_ERR_INVALID_RESOURCE_SIZE;
445                 }
446
447                 if (raw || ctype == WIM_COMPRESSION_TYPE_NONE)
448                         return read_uncompressed_resource(lte->wim->fp,
449                                                           lte->resource_entry.offset + offset,
450                                                           size, buf);
451                 else
452                         return read_compressed_resource(lte->wim->fp,
453                                                         lte->resource_entry.size,
454                                                         lte->resource_entry.original_size,
455                                                         lte->resource_entry.offset,
456                                                         ctype, size, offset, buf);
457                 break;
458         case RESOURCE_IN_STAGING_FILE:
459                 /* The WIM FUSE implementation needs to handle multiple open
460                  * file descriptors per lookup table entry so it does not
461                  * currently work with this function. */
462                 wimlib_assert(lte->staging_file_name);
463                 wimlib_assert(0);
464                 break;
465         case RESOURCE_IN_FILE_ON_DISK:
466                 /* The resource is in some file on the external filesystem and
467                  * needs to be read uncompressed */
468                 wimlib_assert(lte->file_on_disk);
469                 /* Use existing file pointer if available; otherwise open one
470                  * temporarily */
471                 if (lte->file_on_disk_fp) {
472                         fp = lte->file_on_disk_fp;
473                 } else {
474                         fp = fopen(lte->file_on_disk, "rb");
475                         if (!fp) {
476                                 ERROR_WITH_ERRNO("Failed to open the file "
477                                                  "`%s'", lte->file_on_disk);
478                         }
479                 }
480                 ret = read_uncompressed_resource(fp, offset, size, buf);
481                 if (fp != lte->file_on_disk_fp)
482                         fclose(fp);
483                 return ret;
484                 break;
485         case RESOURCE_IN_ATTACHED_BUFFER:
486                 /* The resource is directly attached uncompressed in an
487                  * in-memory buffer. */
488                 wimlib_assert(lte->attached_buffer);
489                 memcpy(buf, lte->attached_buffer + offset, size);
490                 return 0;
491                 break;
492         default:
493                 assert(0);
494         }
495 }
496
497 /* 
498  * Reads all the data from the resource corresponding to a WIM lookup table
499  * entry.
500  *
501  * @lte:        The WIM lookup table entry for the resource.
502  * @buf:        Buffer into which to write the data.  It must be at least
503  *              wim_resource_size(lte) bytes long.
504  *
505  * Returns 0 on success; nonzero on failure.
506  */
507 int read_full_wim_resource(const struct lookup_table_entry *lte, u8 buf[])
508 {
509         return read_wim_resource(lte, buf, wim_resource_size(lte), 0, false);
510 }
511
512 /* Chunk table that's located at the beginning of each compressed resource in
513  * the WIM.  (This is not the on-disk format; the on-disk format just has an
514  * array of offsets.) */
515 struct chunk_table {
516         off_t file_offset;
517         u64 num_chunks;
518         u64 original_resource_size;
519         u64 bytes_per_chunk_entry;
520         u64 table_disk_size;
521         u64 cur_offset;
522         u64 *cur_offset_p;
523         u64 offsets[0];
524 };
525
526 /* 
527  * Allocates and initializes a chunk table, and reserves space for it in the
528  * output file.
529  */
530 static int
531 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
532                              FILE *out_fp,
533                              off_t file_offset,
534                              struct chunk_table **chunk_tab_ret)
535 {
536         u64 size = wim_resource_size(lte);
537         u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
538         struct chunk_table *chunk_tab = MALLOC(sizeof(struct chunk_table) +
539                                                num_chunks * sizeof(u64));
540         int ret = 0;
541
542         wimlib_assert(size != 0);
543
544         if (!chunk_tab) {
545                 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
546                       "resource", size);
547                 ret = WIMLIB_ERR_NOMEM;
548                 goto out;
549         }
550         chunk_tab->file_offset = file_offset;
551         chunk_tab->num_chunks = num_chunks;
552         chunk_tab->original_resource_size = size;
553         chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
554         chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
555                                      (num_chunks - 1);
556         chunk_tab->cur_offset = 0;
557         chunk_tab->cur_offset_p = chunk_tab->offsets;
558
559         if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
560                    chunk_tab->table_disk_size) {
561                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
562                                  "file resource");
563                 ret = WIMLIB_ERR_WRITE;
564                 goto out;
565         }
566
567         *chunk_tab_ret = chunk_tab;
568 out:
569         return ret;
570 }
571
572 /* 
573  * Compresses a chunk of a WIM resource.
574  *
575  * @chunk:              Uncompressed data of the chunk.
576  * @chunk_size:         Size of the uncompressed chunk in bytes.
577  * @compressed_chunk:   Pointer to output buffer of size at least
578  *                              (@chunk_size - 1) bytes.
579  * @compressed_chunk_len_ret:   Pointer to an unsigned int into which the size
580  *                                      of the compressed chunk will be
581  *                                      returned.
582  * @ctype:      Type of compression to use.  Must be WIM_COMPRESSION_TYPE_LZX
583  *              or WIM_COMPRESSION_TYPE_XPRESS.
584  *
585  * Returns zero if compressed succeeded, and nonzero if the chunk could not be
586  * compressed to any smaller than @chunk_size.  This function cannot fail for
587  * any other reasons.
588  */
589 static int compress_chunk(const u8 chunk[], unsigned chunk_size,
590                           u8 compressed_chunk[],
591                           unsigned *compressed_chunk_len_ret,
592                           int ctype)
593 {
594         unsigned compressed_chunk_sz;
595         int (*compress)(const void *, unsigned, void *, unsigned *);
596         switch (ctype) {
597         case WIM_COMPRESSION_TYPE_LZX:
598                 compress = lzx_compress;
599                 break;
600         case WIM_COMPRESSION_TYPE_XPRESS:
601                 compress = xpress_compress;
602                 break;
603         default:
604                 wimlib_assert(0);
605                 break;
606         }
607         return (*compress)(chunk, chunk_size, compressed_chunk,
608                            compressed_chunk_len_ret);
609 }
610
611 /*
612  * Writes a chunk of a WIM resource to an output file.
613  *
614  * @chunk:        Uncompressed data of the chunk.
615  * @chunk_size:   Size of the chunk (<= WIM_CHUNK_SIZE)
616  * @out_fp:       FILE * to write tho chunk to.
617  * @out_ctype:    Compression type to use when writing the chunk (ignored if no 
618  *                      chunk table provided)
619  * @chunk_tab:    Pointer to chunk table being created.  It is updated with the
620  *                      offset of the chunk we write.
621  *
622  * Returns 0 on success; nonzero on failure.
623  */
624 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
625                                     FILE *out_fp, int out_ctype,
626                                     struct chunk_table *chunk_tab)
627 {
628         const u8 *out_chunk;
629         unsigned out_chunk_size;
630
631         wimlib_assert(chunk_size <= WIM_CHUNK_SIZE);
632
633         if (!chunk_tab) {
634                 out_chunk = chunk;
635                 out_chunk_size = chunk_size;
636         } else {
637                 u8 *compressed_chunk = alloca(chunk_size);
638                 int ret;
639                 unsigned compressed_chunk_len;
640
641                 ret = compress_chunk(chunk, chunk_size, compressed_chunk,
642                                      &out_chunk_size, out_ctype);
643                 if (ret == 0) {
644                         out_chunk = compressed_chunk;
645                 } else {
646                         out_chunk = chunk;
647                         out_chunk_size = chunk_size;
648                 }
649                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
650                 chunk_tab->cur_offset += out_chunk_size;
651         }
652         
653         if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
654                 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
655                 return WIMLIB_ERR_WRITE;
656         }
657         return 0;
658 }
659
660 /* 
661  * Finishes a WIM chunk tale and writes it to the output file at the correct
662  * offset.
663  *
664  * The final size of the full compressed resource is returned in the
665  * @compressed_size_p.
666  */
667 static int
668 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
669                               FILE *out_fp, u64 *compressed_size_p)
670 {
671         size_t bytes_written;
672         if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
673                 ERROR_WITH_ERRNO("Failed to seek to byte "PRIu64" of output "
674                                  "WIM file", chunk_tab->file_offset);
675                 return WIMLIB_ERR_WRITE;
676         }
677
678         if (chunk_tab->bytes_per_chunk_entry == 8) {
679                 array_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
680         } else {
681                 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
682                         ((u32*)chunk_tab->offsets)[i] =
683                                 to_le32(chunk_tab->offsets[i]);
684         }
685         bytes_written = fwrite((u8*)chunk_tab->offsets +
686                                         chunk_tab->bytes_per_chunk_entry,
687                                1, chunk_tab->table_disk_size, out_fp);
688         if (bytes_written != chunk_tab->table_disk_size) {
689                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
690                                  "file resource");
691                 return WIMLIB_ERR_WRITE;
692         }
693         if (fseeko(out_fp, 0, SEEK_END) != 0) {
694                 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
695                 return WIMLIB_ERR_WRITE;
696         }
697         *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
698         return 0;
699 }
700
701 /*
702  * Writes a WIM resource to a FILE * opened for writing.  The resource may be
703  * written uncompressed or compressed depending on the @out_ctype parameter.
704  *
705  * If by chance the resource compresses to more than the original size (this may
706  * happen with random data or files than are pre-compressed), the resource is
707  * instead written uncompressed (and this is reflected in the @out_res_entry by
708  * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
709  *
710  * @lte:        The lookup table entry for the WIM resource.
711  * @out_fp:     The FILE * to write the resource to.
712  * @out_ctype:  The compression type of the resource to write.  Note: if this is
713  *                      the same as the compression type of the WIM resource we
714  *                      need to read, we simply copy the data (i.e. we do not
715  *                      uncompress it, then compress it again).
716  * @out_res_entry:  If non-NULL, a resource entry that is filled in with the 
717  *                  offset, original size, compressed size, and compression flag
718  *                  of the output resource.
719  *
720  * Returns 0 on success; nonzero on failure.
721  */
722 static int write_wim_resource(struct lookup_table_entry *lte,
723                               FILE *out_fp, int out_ctype,
724                               struct resource_entry *out_res_entry)
725 {
726         u64 bytes_remaining;
727         u64 original_size;
728         u64 old_compressed_size;
729         u64 new_compressed_size;
730         u64 offset = 0;
731         int ret = 0;
732         struct chunk_table *chunk_tab = NULL;
733         bool raw;
734         off_t file_offset;
735
736         /* Original size of the resource */
737         original_size = wim_resource_size(lte);
738
739         /* Compressed size of the resource (as it exists now) */
740         old_compressed_size = wim_resource_compressed_size(lte);
741
742         /* Current offset in output file */
743         file_offset = ftello(out_fp);
744         if (file_offset == -1) {
745                 ERROR_WITH_ERRNO("Failed to get offset in output "
746                                  "stream");
747                 return WIMLIB_ERR_WRITE;
748         }
749         
750         /* Are the compression types the same?  If so, do a raw copy (copy
751          * without decompressing and recompressing the data). */
752         raw = (wim_resource_compression_type(lte) == out_ctype
753                && out_ctype != WIM_COMPRESSION_TYPE_NONE);
754         if (raw)
755                 bytes_remaining = old_compressed_size;
756         else
757                 bytes_remaining = original_size;
758
759         /* Empty resource; nothing needs to be done, so just return success. */
760         if (bytes_remaining == 0)
761                 return 0;
762
763         /* Buffer for reading chunks for the resource */
764         char buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
765
766         /* If we are writing a compressed resource and not doing a raw copy, we
767          * need to initialize the chunk table */
768         if (out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw) {
769                 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
770                                                    &chunk_tab);
771                 if (ret != 0)
772                         goto out;
773         }
774
775         /* If the WIM resource is in an external file, open a FILE * to it so we
776          * don't have to open a temporary one in read_wim_resource() for each
777          * chunk. */
778         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
779              && !lte->file_on_disk_fp)
780         {
781                 wimlib_assert(lte->file_on_disk);
782                 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
783                 if (!lte->file_on_disk_fp) {
784                         ERROR_WITH_ERRNO("Failed to open the file `%s' for "
785                                          "reading", lte->file_on_disk);
786                         ret = WIMLIB_ERR_OPEN;
787                         goto out;
788                 }
789         }
790
791         /* If we aren't doing a raw copy, we will compute the SHA1 message
792          * digest of the resource as we read it, and verify it's the same as the
793          * hash given in the lookup table entry once we've finished reading the
794          * resource. */
795         SHA_CTX ctx;
796         if (!raw)
797                 sha1_init(&ctx);
798
799         /* While there are still bytes remaining in the WIM resource, read a
800          * chunk of the resource, update SHA1, then write that chunk using the
801          * desired compression type. */
802         do {
803                 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
804                 ret = read_wim_resource(lte, buf, to_read, offset, raw);
805                 if (ret != 0)
806                         goto out_fclose;
807                 if (!raw)
808                         sha1_update(&ctx, buf, to_read);
809                 ret = write_wim_resource_chunk(buf, to_read, out_fp,
810                                                out_ctype, chunk_tab);
811                 if (ret != 0)
812                         goto out_fclose;
813                 bytes_remaining -= to_read;
814                 offset += to_read;
815         } while (bytes_remaining);
816
817         /* If writing a compressed resource and not doing a raw copy, write the
818          * chunk table, and finish_wim_resource_chunk_tab() will provide the
819          * compressed size of the resource we wrote.  Otherwise, the compressed
820          * size of the written resource is the same as the compressed size of
821          * the existing resource. */
822         if (out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw) {
823                 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
824                                                     &new_compressed_size);
825                 if (ret != 0)
826                         goto out_fclose;
827         } else {
828                 new_compressed_size = old_compressed_size;
829         }
830
831         /* Verify SHA1 message digest of the resource, unless we are doing a raw
832          * write (in which case we never even saw the uncompressed data).  Or,
833          * if the hash we had before is all 0's, just re-set it to be the new
834          * hash. */
835         if (!raw) {
836                 u8 md[SHA1_HASH_SIZE];
837                 sha1_final(md, &ctx);
838                 if (is_zero_hash(lte->hash)) {
839                         copy_hash(lte->hash, md);
840                 } else if (!hashes_equal(md, lte->hash)) {
841                         ERROR("WIM resource has incorrect hash!");
842                         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
843                                 ERROR("We were reading it from `%s'; maybe it changed "
844                                       "while we were reading it.",
845                                       lte->file_on_disk);
846                         }
847                         ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
848                         goto out_fclose;
849                 }
850         }
851
852         if (new_compressed_size > original_size) {
853                 /* Oops!  We compressed the resource to larger than the original
854                  * size.  Write the resource uncompressed instead. */
855                 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
856                         ERROR_WITH_ERRNO("Failed to seek to byte "PRIu64" "
857                                          "of output WIM file", file_offset);
858                         ret = WIMLIB_ERR_WRITE;
859                         goto out_fclose;
860                 }
861                 ret = write_wim_resource(lte, out_fp, WIM_COMPRESSION_TYPE_NONE,
862                                          out_res_entry);
863                 if (ret != 0)
864                         goto out_fclose;
865                 if (fflush(out_fp) != 0) {
866                         ERROR_WITH_ERRNO("Failed to flush output WIM file");
867                         ret = WIMLIB_ERR_WRITE;
868                         goto out_fclose;
869                 }
870                 if (ftruncate(fileno(out_fp), file_offset + out_res_entry->size) != 0) {
871                         ERROR_WITH_ERRNO("Failed to truncate output WIM file");
872                         ret = WIMLIB_ERR_WRITE;
873                 }
874                 goto out_fclose;
875         }
876         wimlib_assert(new_compressed_size <= original_size);
877         if (out_res_entry) {
878                 out_res_entry->size          = new_compressed_size;
879                 out_res_entry->original_size = original_size;
880                 out_res_entry->offset        = file_offset;
881                 out_res_entry->flags         = lte->resource_entry.flags
882                                                 & ~WIM_RESHDR_FLAG_COMPRESSED;
883                 if (out_ctype != WIM_COMPRESSION_TYPE_NONE)
884                         out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
885         }
886 out_fclose:
887         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
888              && lte->file_on_disk_fp) {
889                 fclose(lte->file_on_disk_fp);
890                 lte->file_on_disk_fp = NULL;
891         }
892 out:
893         FREE(chunk_tab);
894         return ret;
895 }
896
897 /* Like write_wim_resource(), but the resource is specified by a buffer of
898  * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
899  * the buffer to @hash.  */
900 static int write_wim_resource_from_buffer(const u8 *buf, u64 buf_size,
901                                           FILE *out_fp, int out_ctype,
902                                           struct resource_entry *out_res_entry,
903                                           u8 hash[SHA1_HASH_SIZE])
904 {
905         /* Set up a temporary lookup table entry that we provide to
906          * write_wim_resource(). */
907         struct lookup_table_entry lte;
908         int ret;
909         lte.resource_entry.flags         = 0;
910         lte.resource_entry.original_size = buf_size;
911         lte.resource_entry.size          = buf_size;
912         lte.resource_entry.offset        = 0;
913         lte.resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
914         lte.attached_buffer              = (u8*)buf;
915
916         zero_hash(lte.hash);
917         ret = write_wim_resource(&lte, out_fp, out_ctype, out_res_entry);
918         if (ret != 0)
919                 return ret;
920         copy_hash(hash, lte.hash);
921         return 0;
922 }
923
924 /* 
925  * Extracts the first @size bytes of the WIM resource specified by @lte to the
926  * open file descriptor @fd.
927  * 
928  * Returns 0 on success; nonzero on failure.
929  */
930 int extract_wim_resource_to_fd(const struct lookup_table_entry *lte, int fd,
931                                u64 size)
932 {
933         u64 bytes_remaining = size;
934         char buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
935         u64 offset = 0;
936         int ret = 0;
937         u8 hash[SHA1_HASH_SIZE];
938
939         SHA_CTX ctx;
940         sha1_init(&ctx);
941
942         while (bytes_remaining) {
943                 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
944                 ret = read_wim_resource(lte, buf, to_read, offset, false);
945                 if (ret != 0)
946                         break;
947                 sha1_update(&ctx, buf, to_read);
948                 if (full_write(fd, buf, to_read) < 0) {
949                         ERROR_WITH_ERRNO("Error extracting WIM resource");
950                         return WIMLIB_ERR_WRITE;
951                 }
952                 bytes_remaining -= to_read;
953                 offset += to_read;
954         }
955         sha1_final(hash, &ctx);
956         if (!hashes_equal(hash, lte->hash)) {
957                 ERROR("Invalid checksum on a WIM resource "
958                       "(detected when extracting to external file)");
959                 ERROR("The following WIM resource is invalid:");
960                 print_lookup_table_entry(lte);
961                 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
962         }
963         return 0;
964 }
965
966 /* 
967  * Extracts the WIM resource specified by @lte to the open file descriptor @fd.
968  * 
969  * Returns 0 on success; nonzero on failure.
970  */
971 int extract_full_wim_resource_to_fd(const struct lookup_table_entry *lte, int fd)
972 {
973         return extract_wim_resource_to_fd(lte, fd, wim_resource_size(lte));
974 }
975
976 /* 
977  * Copies the file resource specified by the lookup table entry @lte from the
978  * input WIM to the output WIM that has its FILE * given by
979  * ((WIMStruct*)wim)->out_fp.
980  *
981  * The output_resource_entry, out_refcnt, and part_number fields of @lte are
982  * updated.
983  *
984  * Metadata resources are not copied (they are handled elsewhere for joining and
985  * splitting).
986  */
987 int copy_resource(struct lookup_table_entry *lte, void *wim)
988 {
989         WIMStruct *w = wim;
990         int ret;
991
992         if ((lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) &&
993             !w->write_metadata)
994                 return 0;
995
996         ret = write_wim_resource(lte, w->out_fp,
997                                  wim_resource_compression_type(lte), 
998                                  &lte->output_resource_entry);
999         if (ret != 0)
1000                 return ret;
1001         lte->out_refcnt = lte->refcnt;
1002         lte->part_number = w->hdr.part_number;
1003         return 0;
1004 }
1005
1006 /* 
1007  * Writes a dentry's resources, including the main file resource as well as all
1008  * alternate data streams, to the output file. 
1009  *
1010  * @dentry:  The dentry for the file.
1011  * @wim_p:   A pointer to the WIMStruct containing @dentry.
1012  *
1013  * @return zero on success, nonzero on failure. 
1014  */
1015 int write_dentry_resources(struct dentry *dentry, void *wim_p)
1016 {
1017         WIMStruct *w = wim_p;
1018         int ret = 0;
1019         struct lookup_table_entry *lte;
1020         int ctype = wimlib_get_compression_type(w);
1021
1022         if (w->write_flags & WIMLIB_WRITE_FLAG_VERBOSE) {
1023                 wimlib_assert(dentry->full_path_utf8);
1024                 printf("Writing streams for `%s'\n", dentry->full_path_utf8);
1025         }
1026
1027         for (unsigned i = 0; i <= dentry->num_ads; i++) {
1028                 lte = dentry_stream_lte(dentry, i, w->lookup_table);
1029                 if (lte && ++lte->out_refcnt == 1) {
1030                         ret = write_wim_resource(lte, w->out_fp, ctype,
1031                                                  &lte->output_resource_entry);
1032                         if (ret != 0)
1033                                 break;
1034                 }
1035         }
1036         return ret;
1037 }
1038
1039 /* 
1040  * Reads the metadata metadata resource from the WIM file.  The metadata
1041  * resource consists of the security data, followed by the directory entry for
1042  * the root directory, followed by all the other directory entries in the
1043  * filesystem.  The subdir_offset field of each directory entry gives the start
1044  * of its child entries from the beginning of the metadata resource.  An
1045  * end-of-directory is signaled by a directory entry of length '0', really of
1046  * length 8, because that's how long the 'length' field is.
1047  *
1048  * @fp:         The FILE* for the input WIM file.
1049  * @wim_ctype:  The compression type of the WIM file.
1050  * @imd:        Pointer to the image metadata structure.  Its `metadata_lte'
1051  *              member specifies the lookup table entry for the metadata
1052  *              resource.  The rest of the image metadata entry will be filled
1053  *              in by this function.
1054  *
1055  * @return:     Zero on success, nonzero on failure.
1056  */
1057 int read_metadata_resource(FILE *fp, int wim_ctype, struct image_metadata *imd)
1058 {
1059         u8 *buf;
1060         int ctype;
1061         u32 dentry_offset;
1062         int ret;
1063         struct dentry *dentry;
1064         struct wim_security_data *sd;
1065         struct link_group_table *lgt;
1066         const struct lookup_table_entry *metadata_lte;
1067         const struct resource_entry *res_entry;
1068
1069         metadata_lte = imd->metadata_lte;
1070         res_entry = &metadata_lte->resource_entry;
1071
1072         DEBUG("Reading metadata resource: length = %"PRIu64", "
1073               "offset = %"PRIu64"",
1074               res_entry->original_size, res_entry->offset);
1075
1076         if (res_entry->original_size < 8) {
1077                 ERROR("Expected at least 8 bytes for the metadata resource");
1078                 return WIMLIB_ERR_INVALID_RESOURCE_SIZE;
1079         }
1080
1081         /* Allocate memory for the uncompressed metadata resource. */
1082         buf = MALLOC(res_entry->original_size);
1083
1084         if (!buf) {
1085                 ERROR("Failed to allocate %"PRIu64" bytes for uncompressed "
1086                       "metadata resource", res_entry->original_size);
1087                 return WIMLIB_ERR_NOMEM;
1088         }
1089
1090         /* Determine the compression type of the metadata resource. */
1091
1092         /* Read the metadata resource into memory.  (It may be compressed.) */
1093         ret = read_full_wim_resource(metadata_lte, buf);
1094         if (ret != 0)
1095                 goto out_free_buf;
1096
1097         DEBUG("Finished reading metadata resource into memory.");
1098
1099         /* The root directory entry starts after security data, on an 8-byte
1100          * aligned address. 
1101          *
1102          * The security data starts with a 4-byte integer giving its total
1103          * length. */
1104
1105         /* Read the security data into a wim_security_data structure. */
1106         ret = read_security_data(buf, res_entry->original_size, &sd);
1107         if (ret != 0)
1108                 goto out_free_buf;
1109
1110         dentry = MALLOC(sizeof(struct dentry));
1111         if (!dentry) {
1112                 ERROR("Failed to allocate %zu bytes for root dentry",
1113                       sizeof(struct dentry));
1114                 ret = WIMLIB_ERR_NOMEM;
1115                 goto out_free_security_data;
1116         }
1117
1118         get_u32(buf, &dentry_offset);
1119         if (dentry_offset == 0)
1120                 dentry_offset = 8;
1121         dentry_offset = (dentry_offset + 7) & ~7;
1122                 
1123         ret = read_dentry(buf, res_entry->original_size, dentry_offset, dentry);
1124         /* This is the root dentry, so set its pointers correctly. */
1125         dentry->parent = dentry;
1126         dentry->next   = dentry;
1127         dentry->prev   = dentry;
1128         if (ret != 0)
1129                 goto out_free_dentry_tree;
1130
1131         DEBUG("Reading dentry tree");
1132         /* Now read the entire directory entry tree. */
1133         ret = read_dentry_tree(buf, res_entry->original_size, dentry);
1134         if (ret != 0)
1135                 goto out_free_dentry_tree;
1136
1137         DEBUG("Calculating dentry full paths");
1138         /* Calculate the full paths in the dentry tree. */
1139         ret = for_dentry_in_tree(dentry, calculate_dentry_full_path, NULL);
1140         if (ret != 0)
1141                 goto out_free_dentry_tree;
1142
1143         DEBUG("Building link group table");
1144         /* Build hash table that maps hard link group IDs to dentry sets */
1145         lgt = new_link_group_table(9001);
1146         if (!lgt)
1147                 goto out_free_dentry_tree;
1148         ret = for_dentry_in_tree(dentry, link_group_table_insert, lgt);
1149         if (ret != 0)
1150                 goto out_free_lgt;
1151
1152         DEBUG("Freeing duplicate ADS entries in link group table");
1153         ret = link_groups_free_duplicate_data(lgt);
1154         if (ret != 0)
1155                 goto out_free_lgt;
1156         DEBUG("Done reading image metadata");
1157
1158         imd->lgt           = lgt;
1159         imd->security_data = sd;
1160         imd->root_dentry   = dentry;
1161         goto out_free_buf;
1162 out_free_lgt:
1163         free_link_group_table(lgt);
1164 out_free_dentry_tree:
1165         free_dentry_tree(dentry, NULL);
1166 out_free_security_data:
1167         free_security_data(sd);
1168 out_free_buf:
1169         FREE(buf);
1170         return ret;
1171 }
1172
1173 /* Write the metadata resource for the current WIM image. */
1174 int write_metadata_resource(WIMStruct *w)
1175 {
1176         u8 *buf;
1177         u8 *p;
1178         int ret;
1179         u64 subdir_offset;
1180         struct dentry *root;
1181         struct lookup_table_entry *lte;
1182         u64 metadata_original_size;
1183
1184         DEBUG("Writing metadata resource for image %d", w->current_image);
1185
1186         root = wim_root_dentry(w);
1187
1188         struct wim_security_data *sd = wim_security_data(w);
1189         if (sd)
1190                 subdir_offset = sd->total_length + root->length + 8;
1191         else
1192                 subdir_offset = 8 + root->length + 8;
1193         calculate_subdir_offsets(root, &subdir_offset);
1194         metadata_original_size = subdir_offset;
1195         buf = MALLOC(metadata_original_size);
1196         if (!buf) {
1197                 ERROR("Failed to allocate %"PRIu64" bytes for "
1198                       "metadata resource", metadata_original_size);
1199                 return WIMLIB_ERR_NOMEM;
1200         }
1201
1202         p = write_security_data(sd, buf);
1203
1204         DEBUG("Writing dentry tree.");
1205         p = write_dentry_tree(root, p);
1206         wimlib_assert(p - buf == metadata_original_size);
1207
1208         lte = wim_metadata_lookup_table_entry(w);
1209
1210         ret = write_wim_resource_from_buffer(buf, metadata_original_size,
1211                                              w->out_fp,
1212                                              wimlib_get_compression_type(w),
1213                                              &lte->output_resource_entry,
1214                                              lte->hash);
1215
1216         lookup_table_unlink(w->lookup_table, lte);
1217         lookup_table_insert(w->lookup_table, lte);
1218         lte->out_refcnt++;
1219         lte->output_resource_entry.flags |= WIM_RESHDR_FLAG_METADATA;
1220         FREE(buf);
1221         return ret;
1222 }