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