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