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