]> wimlib.net Git - wimlib/blob - src/resource.c
4b71cb3f6d60990db4a3e819cf09bd72804aa095
[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
38
39 /* 
40  * Reads all or part of a compressed resource into an in-memory buffer.
41  *
42  * @fp:                 The FILE* for the WIM file.
43  * @resource_compressed_size:    The compressed size of the resource.  
44  * @resource_uncompressed_size:  The uncompressed size of the resource.
45  * @resource_offset:             The offset of the start of the resource from
46  *                                      the start of the stream @fp.
47  * @resource_ctype:     The compression type of the resource. 
48  * @len:                The number of bytes of uncompressed data to read from
49  *                              the resource.
50  * @offset:             The offset of the bytes to read within the uncompressed
51  *                              resource.
52  * @contents_len:       An array into which the uncompressed data is written.
53  *                              It must be at least @len bytes long.
54  *
55  * Returns zero on success, nonzero on failure.
56  */
57 static int read_compressed_resource(FILE *fp, u64 resource_compressed_size, 
58                                     u64 resource_uncompressed_size, 
59                                     u64 resource_offset, int resource_ctype, 
60                                     u64 len, u64 offset, u8  contents_ret[])
61 {
62
63         DEBUG2("comp size = %"PRIu64", uncomp size = %"PRIu64", "
64                "res offset = %"PRIu64"",
65                resource_compressed_size,
66                resource_uncompressed_size,
67                resource_offset);
68         DEBUG2("resource_ctype = %s, len = %"PRIu64", offset = %"PRIu64"",
69                wimlib_get_compression_type_string(resource_ctype), len, offset);
70         /* Trivial case */
71         if (len == 0)
72                 return 0;
73
74         int (*decompress)(const void *, uint, void *, uint);
75         /* Set the appropriate decompress function. */
76         if (resource_ctype == WIM_COMPRESSION_TYPE_LZX)
77                 decompress = lzx_decompress;
78         else
79                 decompress = xpress_decompress;
80
81         /* The structure of a compressed resource consists of a table of chunk
82          * offsets followed by the chunks themselves.  Each chunk consists of
83          * compressed data, and there is one chunk for each WIM_CHUNK_SIZE =
84          * 32768 bytes of the uncompressed file, with the last chunk having any
85          * remaining bytes.
86          *
87          * The chunk offsets are measured relative to the end of the chunk
88          * table.  The first chunk is omitted from the table in the WIM file
89          * because its offset is implicitly given by the fact that it directly
90          * follows the chunk table and therefore must have an offset of 0. 
91          */
92
93         /* Calculate how many chunks the resource conists of in its entirety. */
94         u64 num_chunks = (resource_uncompressed_size + WIM_CHUNK_SIZE - 1) /
95                                                                 WIM_CHUNK_SIZE;
96         /* As mentioned, the first chunk has no entry in the chunk table. */
97         u64 num_chunk_entries = num_chunks - 1;
98
99
100         /* The index of the chunk that the read starts at. */
101         u64 start_chunk = offset / WIM_CHUNK_SIZE;
102         /* The byte offset at which the read starts, within the start chunk. */
103         u64 start_chunk_offset = offset % WIM_CHUNK_SIZE;
104
105         /* The index of the chunk that contains the last byte of the read. */
106         u64 end_chunk   = (offset + len - 1) / WIM_CHUNK_SIZE;
107         /* The byte offset of the last byte of the read, within the end chunk */
108         u64 end_chunk_offset = (offset + len - 1) % WIM_CHUNK_SIZE;
109
110         /* Number of chunks that are actually needed to read the requested part
111          * of the file. */
112         u64 num_needed_chunks = end_chunk - start_chunk + 1;
113
114         /* If the end chunk is not the last chunk, an extra chunk entry is
115          * needed because we need to know the offset of the chunk after the last
116          * chunk read to figure out the size of the last read chunk. */
117         if (end_chunk != num_chunks - 1)
118                 num_needed_chunks++;
119
120         /* Declare the chunk table.  It will only contain offsets for the chunks
121          * that are actually needed for this read. */
122         u64 chunk_offsets[num_needed_chunks];
123
124         /* Set the implicit offset of the first chunk if it is included in the
125          * needed chunks.
126          *
127          * Note: M$'s documentation includes a picture that shows the first
128          * chunk starting right after the chunk entry table, labeled as offset
129          * 0x10.  However, in the actual file format, the offset is measured
130          * from the end of the chunk entry table, so the first chunk has an
131          * offset of 0. */
132         if (start_chunk == 0)
133                 chunk_offsets[0] = 0;
134
135         /* According to M$'s documentation, if the uncompressed size of
136          * the file is greater than 4 GB, the chunk entries are 8-byte
137          * integers.  Otherwise, they are 4-byte integers. */
138         u64 chunk_entry_size = (resource_uncompressed_size >= (u64)1 << 32) ? 
139                                                                         8 : 4;
140
141         /* Size of the full chunk table in the WIM file. */
142         u64 chunk_table_size = chunk_entry_size * num_chunk_entries;
143
144         /* Read the needed chunk offsets from the table in the WIM file. */
145
146         /* Index, in the WIM file, of the first needed entry in the
147          * chunk table. */
148         u64 start_table_idx = (start_chunk == 0) ? 0 : start_chunk - 1;
149
150         /* Number of entries we need to actually read from the chunk
151          * table (excludes the implicit first chunk). */
152         u64 num_needed_chunk_entries = (start_chunk == 0) ? 
153                                 num_needed_chunks - 1 : num_needed_chunks;
154
155         /* Skip over unneeded chunk table entries. */
156         u64 file_offset_of_needed_chunk_entries = resource_offset + 
157                                 start_table_idx * chunk_entry_size;
158         if (fseeko(fp, file_offset_of_needed_chunk_entries, SEEK_SET) != 0) {
159                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
160                                  "chunk table of compressed resource",
161                                  file_offset_of_needed_chunk_entries);
162                 return WIMLIB_ERR_READ;
163         }
164
165         /* Number of bytes we need to read from the chunk table. */
166         size_t size = num_needed_chunk_entries * chunk_entry_size;
167
168         u8 chunk_tab_buf[size];
169
170         if (fread(chunk_tab_buf, 1, size, fp) != size)
171                 goto err;
172
173         /* Now fill in chunk_offsets from the entries we have read in
174          * chunk_tab_buf. */
175
176         u64 *chunk_tab_p = chunk_offsets;
177         if (start_chunk == 0)
178                 chunk_tab_p++;
179
180         if (chunk_entry_size == 4) {
181                 u32 *entries = (u32*)chunk_tab_buf;
182                 while (num_needed_chunk_entries--)
183                         *chunk_tab_p++ = to_le32(*entries++);
184         } else {
185                 u64 *entries = (u64*)chunk_tab_buf;
186                 while (num_needed_chunk_entries--)
187                         *chunk_tab_p++ = to_le64(*entries++);
188         }
189
190         /* Done with the chunk table now.  We must now seek to the first chunk
191          * that is needed for the read. */
192
193         u64 file_offset_of_first_needed_chunk = resource_offset + 
194                                 chunk_table_size + chunk_offsets[0];
195         if (fseeko(fp, file_offset_of_first_needed_chunk, SEEK_SET) != 0) {
196                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
197                                  "first chunk of compressed resource",
198                                  file_offset_of_first_needed_chunk);
199                 return WIMLIB_ERR_READ;
200         }
201
202         /* Pointer to current position in the output buffer for uncompressed
203          * data. */
204         u8 *out_p = (u8*)contents_ret;
205
206         /* Buffer for compressed data.  While most compressed chunks will have a
207          * size much less than WIM_CHUNK_SIZE, WIM_CHUNK_SIZE - 1 is the maximum
208          * size in the worst-case.  This assumption is valid only if chunks that
209          * happen to compress to more than the uncompressed size (i.e. a
210          * sequence of random bytes) are always stored uncompressed. But this seems
211          * to be the case in M$'s WIM files, even though it is undocumented. */
212         u8 compressed_buf[WIM_CHUNK_SIZE - 1];
213
214
215         /* Decompress all the chunks. */
216         for (u64 i = start_chunk; i <= end_chunk; i++) {
217
218                 DEBUG2("Chunk %"PRIu64" (start %"PRIu64", end %"PRIu64").",
219                        i, start_chunk, end_chunk);
220
221                 /* Calculate the sizes of the compressed chunk and of the
222                  * uncompressed chunk. */
223                 uint compressed_chunk_size, uncompressed_chunk_size;
224                 if (i != num_chunks - 1) {
225                         /* All the chunks except the last one in the resource
226                          * expand to WIM_CHUNK_SIZE uncompressed, and the amount
227                          * of compressed data for the chunk is given by the
228                          * difference of offsets in the chunk offset table. */
229                         compressed_chunk_size = chunk_offsets[i + 1 - start_chunk] - 
230                                                 chunk_offsets[i - start_chunk];
231                         uncompressed_chunk_size = WIM_CHUNK_SIZE;
232                 } else {
233                         /* The last compressed chunk consists of the remaining
234                          * bytes in the file resource, and the last uncompressed
235                          * chunk has size equal to however many bytes are left-
236                          * that is, the remainder of the uncompressed size when
237                          * divided by WIM_CHUNK_SIZE. 
238                          *
239                          * Note that the resource_compressed_size includes the
240                          * chunk table, so the size of it must be subtracted. */
241                         compressed_chunk_size = resource_compressed_size - 
242                                                 chunk_table_size -
243                                                 chunk_offsets[i - start_chunk];
244
245                         uncompressed_chunk_size = resource_uncompressed_size % 
246                                                                 WIM_CHUNK_SIZE;
247
248                         /* If the remainder is 0, the last chunk actually
249                          * uncompresses to a full WIM_CHUNK_SIZE bytes. */
250                         if (uncompressed_chunk_size == 0)
251                                 uncompressed_chunk_size = WIM_CHUNK_SIZE;
252                 }
253
254                 DEBUG2("compressed_chunk_size = %u, "
255                        "uncompressed_chunk_size = %u",
256                        compressed_chunk_size, uncompressed_chunk_size);
257
258
259                 /* Figure out how much of this chunk we actually need to read */
260                 u64 start_offset;
261                 if (i == start_chunk)
262                         start_offset = start_chunk_offset;
263                 else
264                         start_offset = 0;
265                 u64 end_offset;
266                 if (i == end_chunk)
267                         end_offset = end_chunk_offset;
268                 else
269                         end_offset = WIM_CHUNK_SIZE - 1;
270
271                 u64 partial_chunk_size = end_offset + 1 - start_offset;
272                 bool is_partial_chunk = (partial_chunk_size != 
273                                                 uncompressed_chunk_size);
274
275                 DEBUG2("start_offset = %u, end_offset = %u", start_offset,
276                                         end_offset);
277                 DEBUG2("partial_chunk_size = %u", partial_chunk_size);
278
279                 /* This is undocumented, but chunks can be uncompressed.  This
280                  * appears to always be the case when the compressed chunk size
281                  * is equal to the uncompressed chunk size. */
282                 if (compressed_chunk_size == uncompressed_chunk_size) {
283                         /* Probably an uncompressed chunk */
284
285                         if (start_offset != 0) {
286                                 if (fseeko(fp, start_offset, SEEK_CUR) != 0) {
287                                         ERROR_WITH_ERRNO("Uncompressed partial "
288                                                          "chunk fseek() error");
289                                         return WIMLIB_ERR_READ;
290                                 }
291                         }
292                         if (fread(out_p, 1, partial_chunk_size, fp) != 
293                                         partial_chunk_size)
294                                 goto err;
295                 } else {
296                         /* Compressed chunk */
297                         int ret;
298
299                         /* Read the compressed data into compressed_buf. */
300                         if (fread(compressed_buf, 1, compressed_chunk_size, 
301                                                 fp) != compressed_chunk_size)
302                                 goto err;
303
304                         /* For partial chunks we must buffer the uncompressed
305                          * data because we don't need all of it. */
306                         if (is_partial_chunk) {
307                                 u8 uncompressed_buf[uncompressed_chunk_size];
308
309                                 ret = decompress(compressed_buf,
310                                                 compressed_chunk_size,
311                                                 uncompressed_buf, 
312                                                 uncompressed_chunk_size);
313                                 if (ret != 0)
314                                         return WIMLIB_ERR_DECOMPRESSION;
315                                 memcpy(out_p, uncompressed_buf + start_offset,
316                                                 partial_chunk_size);
317                         } else {
318                                 ret = decompress(compressed_buf,
319                                                 compressed_chunk_size,
320                                                 out_p,
321                                                 uncompressed_chunk_size);
322                                 if (ret != 0)
323                                         return WIMLIB_ERR_DECOMPRESSION;
324                         }
325                 }
326
327                 /* Advance the pointer into the uncompressed output data by the
328                  * number of uncompressed bytes that were written.  */
329                 out_p += partial_chunk_size;
330         }
331
332         return 0;
333
334 err:
335         if (feof(fp))
336                 ERROR("Unexpected EOF in compressed file resource");
337         else
338                 ERROR_WITH_ERRNO("Error reading compressed file resource");
339         return WIMLIB_ERR_READ;
340 }
341
342 /* 
343  * Reads uncompressed data from an open file stream.
344  */
345 int read_uncompressed_resource(FILE *fp, u64 offset, u64 len, 
346                                         u8 contents_ret[])
347 {
348         if (fseeko(fp, offset, SEEK_SET) != 0) {
349                 ERROR("Failed to seek to byte %"PRIu64" of input file "
350                       "to read uncompressed resource (len = %"PRIu64")",
351                       offset, len);
352                 return WIMLIB_ERR_READ;
353         }
354         if (fread(contents_ret, 1, len, fp) != len) {
355                 if (feof(fp)) {
356                         ERROR("Unexpected EOF in uncompressed file resource");
357                 } else {
358                         ERROR("Failed to read %"PRIu64" bytes from "
359                               "uncompressed resource at offset %"PRIu64,
360                               len, offset);
361                 }
362                 return WIMLIB_ERR_READ;
363         }
364         return 0;
365 }
366
367
368 /* 
369  * Reads a WIM resource.
370  *
371  * @fp:                 The FILE* for the WIM file.
372  * @resource_size:              The compressed size of the resource.
373  * @resource_original_size:     The uncompressed size of the resource.
374  * @resource_offset:            The offset of the resource in the stream @fp.
375  * @resource_ctype:             The compression type of the resource.
376  *                              (WIM_COMPRESSION_TYPE_*)
377  * @len:                How many bytes of the resource should be read.
378  * @offset:             The offset within the resource at which the read
379  *                              will occur.
380  *
381  *                      To read the whole file resource, specify offset =
382  *                      0 and len = resource_original_size, or call
383  *                      read_full_resource().
384  *
385  * @contents_ret:       An array, that must have length at least @len,
386  *                              into which the uncompressed contents of
387  *                              the file resource starting at @offset and 
388  *                              continuing for @len bytes will be written.
389  *
390  * @return:             Zero on success, nonzero on failure. Failure may be due to
391  *                      being unable to read the data from the WIM file at the
392  *                      specified length and offset, or it may be due to the
393  *                      compressed data (if the data is compressed) being
394  *                      invalid.
395  */
396 int read_resource(FILE *fp, u64 resource_size, u64 resource_original_size,
397                   u64 resource_offset, int resource_ctype, u64 len, 
398                   u64 offset, void *contents_ret)
399 {
400         if (resource_ctype == WIM_COMPRESSION_TYPE_NONE) {
401                 if (resource_size != resource_original_size) {
402                         ERROR("Resource with original size %"PRIu64" bytes is "
403                               "marked as uncompressed, but its actual size is "
404                               "%"PRIu64" bytes", 
405                               resource_original_size, resource_size);
406                         return WIMLIB_ERR_INVALID_RESOURCE_SIZE;
407                 }
408                 return read_uncompressed_resource(fp, 
409                                 resource_offset + offset, 
410                                 len, contents_ret);
411         } else {
412                 return read_compressed_resource(fp, resource_size,
413                                 resource_original_size, resource_offset,
414                                 resource_ctype, len, offset, contents_ret);
415         }
416 }
417
418
419 /* 
420  * Extracts the first @size bytes file resource specified by @entry to the open
421  * file @fd.  Returns nonzero on error.
422  *
423  * XXX
424  * This function is somewhat redundant with uncompress_resource(). The
425  * main difference is that this function writes to a file descriptor using
426  * low-level calls to write() rather than to a FILE* with fwrite(); also this
427  * function allows only up to @size bytes to be extracted.
428  */
429 int extract_resource_to_fd(WIMStruct *w, const struct resource_entry *entry, 
430                            int fd, u64 size)
431 {
432         u64 num_chunks;
433         u64 n;
434         u8 buf[min(size, WIM_CHUNK_SIZE)];
435         int res_ctype;
436         u64 offset;
437         u64 i;
438         int ret;
439
440         errno = 0;
441
442         num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
443         n = WIM_CHUNK_SIZE;
444         res_ctype = wim_resource_compression_type(w, entry);
445         offset = 0;
446         for (i = 0; i < num_chunks; i++) {
447                 if (i == num_chunks - 1) {
448                         n = size % WIM_CHUNK_SIZE;
449                         if (n == 0) {
450                                 n = WIM_CHUNK_SIZE;
451                         }
452                 }
453
454                 ret = read_resource(w->fp, entry->size, entry->original_size,
455                                     entry->offset, res_ctype, n, offset, buf);
456                 if (ret != 0)
457                         return ret;
458
459                 if (full_write(fd, buf, n) != n)
460                         return WIMLIB_ERR_WRITE;
461                 offset += n;
462         }
463         return ret;
464 }
465
466 /* 
467  * Copies the file resource specified by the lookup table entry @lte from the
468  * input WIM, pointed to by the fp field of the WIMStruct, to the output WIM,
469  * pointed to by the out_fp field of the WIMStruct.
470  *
471  * The output_resource_entry, out_refcnt, and part_number fields of @lte are
472  * updated.
473  *
474  * Metadata resources are not copied (they are handled elsewhere for joining and
475  * splitting).
476  */
477 int copy_resource(struct lookup_table_entry *lte, void *w)
478 {
479         if ((lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) &&
480             !((WIMStruct*)w)->write_metadata) {
481                 return 0;
482         }
483
484         FILE *in_fp = ((WIMStruct*)w)->fp;
485         FILE *out_fp = ((WIMStruct*)w)->out_fp;
486         int ret;
487         u64 size = lte->resource_entry.size;
488         u64 offset = lte->resource_entry.offset;
489         off_t new_offset = ftello(out_fp);
490
491         if (new_offset == -1)
492                 return WIMLIB_ERR_WRITE;
493
494         ret = copy_between_files(in_fp, offset, out_fp, size);
495         if (ret != 0)
496                 return ret;
497
498         memcpy(&lte->output_resource_entry, &lte->resource_entry, 
499                         sizeof(struct resource_entry));
500
501         lte->output_resource_entry.offset = new_offset;
502         lte->out_refcnt = lte->refcnt;
503         lte->part_number = ((WIMStruct*)w)->hdr.part_number;
504         return 0;
505 }
506
507 /* Reads the contents of a struct resource_entry, as represented in the on-disk
508  * format, from the memory pointed to by @p, and fills in the fields of @entry.
509  * A pointer to the byte after the memory read at @p is returned. */
510 const u8 *get_resource_entry(const u8 *p, struct resource_entry *entry)
511 {
512         u64 size;
513         u8 flags;
514
515         p = get_u56(p, &size);
516         p = get_u8(p, &flags);
517         entry->size = size;
518         entry->flags = flags;
519         p = get_u64(p, &entry->offset);
520         p = get_u64(p, &entry->original_size);
521         return p;
522 }
523
524 /* Copies the struct resource_entry @entry to the memory pointed to by @p in the
525  * on-disk format.  A pointer to the byte after the memory written at @p is
526  * returned. */
527 u8 *put_resource_entry(u8 *p, const struct resource_entry *entry)
528 {
529         p = put_u56(p, entry->size);
530         p = put_u8(p, entry->flags);
531         p = put_u64(p, entry->offset);
532         p = put_u64(p, entry->original_size);
533         return p;
534 }
535
536 /* Given the compression type for the WIM file as a whole as the flags field of
537  * a resource entry, returns the compression type for that resource entry. */
538 int resource_compression_type(int wim_ctype, int reshdr_flags)
539 {
540         if (wim_ctype != WIM_COMPRESSION_TYPE_NONE &&
541              (reshdr_flags & WIM_RESHDR_FLAG_COMPRESSED))
542                 return wim_ctype;
543         else
544                 return WIM_COMPRESSION_TYPE_NONE;
545 }
546
547
548
549 /*
550  * Copies bytes between two file streams.
551  *
552  * Copies @len bytes from @in_fp to @out_fp, at the current position in @out_fp,
553  * and at an offset of @in_offset in @in_fp.
554  */
555 int copy_between_files(FILE *in_fp, off_t in_offset, FILE *out_fp, size_t len)
556 {
557         u8 buf[BUFFER_SIZE];
558         size_t n;
559
560         if (fseeko(in_fp, in_offset, SEEK_SET) != 0) {
561                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of "
562                                  "input file", in_offset);
563                 return WIMLIB_ERR_READ;
564         }
565         /* To reduce memory usage and improve speed, read and write BUFFER_SIZE
566          * bytes at a time. */
567         while (len != 0) {
568                 n = min(len, BUFFER_SIZE);
569                 if (fread(buf, 1, n, in_fp) != n) {
570                         if (feof(in_fp)) {
571                                 ERROR("Unexpected EOF when copying data "
572                                       "between files");
573                         } else {
574                                 ERROR_WITH_ERRNO("Error copying data between "
575                                                  "files");
576                         }
577                         return WIMLIB_ERR_READ;
578                 }
579
580                 if (fwrite(buf, 1, n, out_fp) != n) {
581                         ERROR_WITH_ERRNO("Error copying data between files");
582                         return WIMLIB_ERR_WRITE;
583                 }
584                 len -= n;
585         }
586         return 0;
587 }
588
589
590 /* 
591  * Uncompresses a WIM file resource and writes it uncompressed to a file stream.
592  *
593  * @in_fp:          The file stream that contains the file resource.
594  * @size:           The size of the resource in the input file.
595  * @original_size:  The original (uncompressed) size of the resource. 
596  * @offset:         The offset of the start of the resource in @in.
597  * @input_ctype:    The compression type of the resource in @in.
598  * @out_fp:         The file stream to write the file resource to.
599  */
600 static int uncompress_resource(FILE *in_fp, u64 size, u64 original_size,
601                                off_t offset, int input_ctype, FILE *out_fp)
602 {
603         int ret;
604         u8 buf[WIM_CHUNK_SIZE];
605         /* Determine how many compressed chunks the file is divided into. */
606         u64 num_chunks;
607         u64 i;
608         u64 uncompressed_offset;
609         u64 uncompressed_chunk_size;
610         
611         num_chunks = (original_size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
612
613         for (i = 0; i < num_chunks; i++) {
614
615                 uncompressed_offset = i * WIM_CHUNK_SIZE;
616                 uncompressed_chunk_size = min(WIM_CHUNK_SIZE, original_size -
617                                               uncompressed_offset);
618
619                 ret = read_resource(in_fp, size, original_size, offset,
620                                     input_ctype, uncompressed_chunk_size, 
621                                     uncompressed_offset, buf);
622                 if (ret != 0)
623                         return ret;
624
625                 if (fwrite(buf, 1, uncompressed_chunk_size, out_fp) != 
626                       uncompressed_chunk_size) 
627                 {
628                         ERROR_WITH_ERRNO("Failed to write file resource");
629                         return WIMLIB_ERR_WRITE;
630                 }
631         }
632         return 0;
633 }
634
635 /* 
636  * Transfers a file resource between two files, writing it compressed.  The file
637  * resource in the input file may be either compressed or uncompressed.
638  * Alternatively, the input resource may be in-memory, but it must be
639  * uncompressed.
640  *
641  * @in_fp:                  The file stream that contains the file resource.  Ignored
642  *                      if uncompressed_resource != NULL.
643  * @uncompressed_resource:      If this pointer is not NULL, it points to an
644  *                                      array of @original_size bytes that are
645  *                                      the uncompressed input resource.
646  * @size:           The size of the resource in the input file.
647  * @original_size:  The original (uncompressed) size of the resource. 
648  * @offset:         The offset of the start of the resource in @in.  Ignored
649  *                      if uncompressed_resource != NULL.
650  * @input_ctype:    The compression type of the resource in @in.  Ignored if
651  *                      uncompressed_resource != NULL.
652  * @out_fp:         The file stream to write the file resource to.
653  * @output_type:    The compression type to use when writing the resource to
654  *                      @out.
655  * @new_size_ret:   A location into which the new compressed size of the file
656  *                      resource in returned.
657  */
658 static int recompress_resource(FILE *in_fp, const u8 *uncompressed_resource, 
659                                u64 size, u64 original_size,
660                                off_t offset, int input_ctype, FILE *out_fp,
661                                int output_ctype, u64 *new_size_ret)
662 {
663         int ret;
664         int (*compress)(const void *, uint, void *, uint *);
665         if (output_ctype == WIM_COMPRESSION_TYPE_LZX)
666                 compress = lzx_compress;
667         else
668                 compress = xpress_compress;
669
670         u8 uncompressed_buf[WIM_CHUNK_SIZE];
671         u8 compressed_buf[WIM_CHUNK_SIZE - 1];
672
673         /* Determine how many compressed chunks the file needs to be divided
674          * into. */
675         u64 num_chunks = (original_size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
676
677         u64 num_chunk_entries = num_chunks - 1;
678
679         /* Size of the chunk entries--- 8 bytes for files over 4GB, otherwise 4
680          * bytes */
681         uint chunk_entry_size = (original_size >= (u64)1 << 32) ? 8 : 4;
682
683         /* Array in which to construct the chunk offset table. */
684         u64 chunk_offsets[num_chunk_entries];
685
686         /* Offset of the start of the chunk table in the output file. */
687         off_t chunk_tab_offset = ftello(out_fp);
688
689         if (chunk_tab_offset == -1) {
690                 ERROR_WITH_ERRNO("Failed to get offset of output file");
691                 return WIMLIB_ERR_WRITE;
692         }
693
694         /* Total size of the chunk table (as written to the file) */
695         u64 chunk_tab_size = chunk_entry_size * num_chunk_entries;
696
697         /* Reserve space for the chunk table. */
698         if (fwrite(chunk_offsets, 1, chunk_tab_size, out_fp) !=
699               chunk_tab_size)
700         {
701                 ERROR_WITH_ERRNO("Failed to write chunk offset table");
702                 return WIMLIB_ERR_WRITE;
703         }
704
705         /* Read each chunk of the file, compress it, write it to the output
706          * file, and update th chunk offset table. */
707         u64 cur_chunk_offset = 0;
708         for (u64 i = 0; i < num_chunks; i++) {
709
710                 u64 uncompressed_offset = i * WIM_CHUNK_SIZE;
711                 u64 uncompressed_chunk_size = min(WIM_CHUNK_SIZE, 
712                                         original_size - uncompressed_offset);
713
714                 const u8 *uncompressed_p;
715                 if (uncompressed_resource != NULL) {
716                         uncompressed_p = uncompressed_resource + 
717                                          uncompressed_offset;
718
719                 } else {
720                         /* Read chunk i of the file into uncompressed_buf. */
721                         ret = read_resource(in_fp, size, original_size, offset,
722                                             input_ctype,
723                                             uncompressed_chunk_size, 
724                                             uncompressed_offset, 
725                                             uncompressed_buf);
726                         if (ret != 0)
727                                 return ret;
728                         uncompressed_p = uncompressed_buf;
729                 }
730
731                 if (i != 0)
732                         chunk_offsets[i - 1] = cur_chunk_offset;
733
734                 uint compressed_len;
735
736                 ret = compress(uncompressed_p, uncompressed_chunk_size, 
737                                compressed_buf, &compressed_len);
738
739                 /* if compress() returned nonzero, the compressed chunk would
740                  * have been at least as large as the uncompressed chunk.  In
741                  * this situation, the WIM format requires that the uncompressed
742                  * chunk be written instead. */
743                 const u8 *buf_to_write;
744                 uint len_to_write;
745                 if (ret == 0) {
746                         buf_to_write = compressed_buf;
747                         len_to_write = compressed_len;
748                 } else {
749                         buf_to_write = uncompressed_p;
750                         len_to_write = uncompressed_chunk_size;
751                 }
752
753                 if (fwrite(buf_to_write, 1, len_to_write, out_fp) !=
754                       len_to_write)
755                 {
756                         ERROR_WITH_ERRNO("Failed to write compressed "
757                                          "file resource");
758                         return WIMLIB_ERR_WRITE;
759                 }
760                 cur_chunk_offset += len_to_write;
761         }
762
763         /* The chunk offset after the last chunk, plus the size of the chunk
764          * table, gives the total compressed size of the resource. */
765         *new_size_ret = cur_chunk_offset + chunk_tab_size;
766
767         /* Now that all entries of the chunk table are determined, rewind the
768          * stream to where the chunk table was, and write it back out. */
769
770         if (fseeko(out_fp, chunk_tab_offset, SEEK_SET) != 0) {
771                 ERROR_WITH_ERRNO("Failed to seek to beginning of chunk table");
772                 return WIMLIB_ERR_READ;
773         }
774
775         if (chunk_entry_size == 8) {
776                 array_to_le64(chunk_offsets, num_chunk_entries);
777         } else {
778                 for (u64 i = 0; i < num_chunk_entries; i++)
779                         ((u32*)chunk_offsets)[i] = to_le32(chunk_offsets[i]);
780         }
781         if (fwrite(chunk_offsets, 1, chunk_tab_size, out_fp) != chunk_tab_size)
782         {
783                 ERROR_WITH_ERRNO("Failed to write chunk table");
784                 return WIMLIB_ERR_WRITE;
785         }
786
787         if (fseeko(out_fp, 0, SEEK_END) != 0) {
788                 ERROR_WITH_ERRNO("Failed to seek to end of output file");
789                 return WIMLIB_ERR_WRITE;
790         }
791
792         return 0;
793 }
794
795 int write_resource_from_memory(const u8 resource[], int out_ctype,
796                                u64 resource_original_size, FILE *out_fp,
797                                u64 *resource_size_ret)
798 {
799         if (out_ctype == WIM_COMPRESSION_TYPE_NONE) {
800                 if (fwrite(resource, 1, resource_original_size, out_fp) != 
801                       resource_original_size)
802                 {
803                         ERROR_WITH_ERRNO("Failed to write resource of length "
804                                          "%"PRIu64, resource_original_size);
805                         return WIMLIB_ERR_WRITE;
806                 }
807                 *resource_size_ret = resource_original_size;
808                 return 0;
809         } else {
810                 return recompress_resource(NULL, resource,
811                                            resource_original_size,
812                                            resource_original_size, 0, 0, out_fp,
813                                            out_ctype, resource_size_ret);
814         }
815 }
816
817
818 /* 
819  * Transfers a file resource from a FILE* opened for reading to a FILE* opened
820  * for writing, possibly changing the compression type. 
821  *
822  * @in_fp:              The FILE* that contains the file resource.
823  * @size:               The (compressed) size of the file resource.
824  * @original_size:      The uncompressed size of the file resource.
825  * @offset:             The offset of the file resource in the input file.
826  * @input_ctype:        The compression type of the file resource in the input
827  *                              file.
828  * @out_fp:             The FILE* for the output file.  The file resource is 
829  *                              written at the current position of @out.
830  * @output_ctype:       The compression type to which the file resource will be
831  *                              converted.
832  * @output_res_entry:   A pointer to a resource entry that, upon successful
833  *                              return of this function,  will have the size,
834  *                              original size, offset, and flags fields filled
835  *                              in for the file resource written to the output
836  *                              file.
837  */
838 static int transfer_file_resource(FILE *in_fp, u64 size, u64 original_size,
839                                   off_t offset, int input_ctype, FILE *out_fp,
840                                   int output_ctype,
841                                   struct resource_entry *output_res_entry)
842 {
843         int ret;
844
845         /* Handle zero-length files */
846         if (original_size == 0) {
847                 memset(output_res_entry, 0, sizeof(*output_res_entry));
848                 return 0;
849         }
850
851         /* Get current offset in the output file. */
852         off_t out_offset = ftello(out_fp);
853         if (out_offset == -1) {
854                 ERROR_WITH_ERRNO("Failed to get output position");
855                 return WIMLIB_ERR_WRITE;
856         }
857         output_res_entry->offset = (u64)out_offset;
858
859         if (output_ctype == input_ctype) {
860                 /* The same compression types; simply copy the resource. */
861
862                 ret = copy_between_files(in_fp, offset, out_fp, size);
863                 if (ret != 0)
864                         return ret;
865                 output_res_entry->size = size;
866         } else {
867                 /* Different compression types. */
868
869                 if (output_ctype == WIM_COMPRESSION_TYPE_NONE) {
870                         /* Uncompress a compressed file resource */
871                         ret = uncompress_resource(in_fp, size,
872                                                   original_size, offset, 
873                                                   input_ctype, out_fp);
874                         if (ret != 0)
875                                 return ret;
876                         output_res_entry->size = original_size;
877                 } else {
878                         u64 new_size;
879                         /* Compress an uncompressed file resource, or compress a
880                          * compressed file resource using a different
881                          * compression type */
882                         ret = recompress_resource(in_fp, NULL, size,
883                                                   original_size,
884                                                   offset, input_ctype, out_fp,
885                                                   output_ctype, &new_size);
886                         if (ret != 0)
887                                 return ret;
888                         output_res_entry->size = new_size;
889                 }
890
891         }
892
893         output_res_entry->original_size = original_size;
894         if (output_ctype == WIM_COMPRESSION_TYPE_NONE)
895                 output_res_entry->flags = 0;
896         else
897                 output_res_entry->flags = WIM_RESHDR_FLAG_COMPRESSED;
898         return 0;
899 }
900
901 /* 
902  * Reads the metadata metadata resource from the WIM file.  The metadata
903  * resource consists of the security data, followed by the directory entry for
904  * the root directory, followed by all the other directory entries in the
905  * filesystem.  The subdir_offset field of each directory entry gives the start
906  * of its child entries from the beginning of the metadata resource.  An
907  * end-of-directory is signaled by a directory entry of length '0', really of
908  * length 8, because that's how long the 'length' field is.
909  *
910  * @fp:         The FILE* for the input WIM file.
911  * @wim_ctype:  The compression type of the WIM file.
912  * @imd:        Pointer to the image metadata structure.  Its
913  *              `lookup_table_entry' member specifies the lookup table entry for
914  *              the metadata resource.  The rest of the image metadata entry
915  *              will be filled in by this function.
916  *
917  * @return:     Zero on success, nonzero on failure.
918  */
919 int read_metadata_resource(FILE *fp, int wim_ctype, struct image_metadata *imd)
920 {
921         u8 *buf;
922         int ctype;
923         u32 dentry_offset;
924         int ret;
925         const struct resource_entry *res_entry;
926         struct dentry *dentry;
927         struct wim_security_data *sd;
928         struct link_group_table *lgt;
929
930         res_entry = &imd->metadata_lte->resource_entry;
931
932         DEBUG("Reading metadata resource: length = %"PRIu64", "
933               "offset = %"PRIu64"",
934               res_entry->original_size, res_entry->offset);
935
936         if (res_entry->original_size < 8) {
937                 ERROR("Expected at least 8 bytes for the metadata resource");
938                 return WIMLIB_ERR_INVALID_RESOURCE_SIZE;
939         }
940
941         /* Allocate memory for the uncompressed metadata resource. */
942         buf = MALLOC(res_entry->original_size);
943
944         if (!buf) {
945                 ERROR("Failed to allocate %"PRIu64" bytes for uncompressed "
946                       "metadata resource", res_entry->original_size);
947                 return WIMLIB_ERR_NOMEM;
948         }
949
950         /* Determine the compression type of the metadata resource. */
951         ctype = resource_compression_type(wim_ctype, res_entry->flags);
952
953         /* Read the metadata resource into memory.  (It may be compressed.) */
954         ret = read_full_resource(fp, res_entry->size, 
955                                  res_entry->original_size, res_entry->offset, 
956                                  ctype, buf);
957         if (ret != 0)
958                 goto out_free_buf;
959
960         DEBUG("Finished reading metadata resource into memory.");
961
962         /* The root directory entry starts after security data, on an 8-byte
963          * aligned address. 
964          *
965          * The security data starts with a 4-byte integer giving its total
966          * length. */
967
968         /* Read the security data into a wim_security_data structure. */
969         ret = read_security_data(buf, res_entry->original_size, &sd);
970         if (ret != 0)
971                 goto out_free_buf;
972
973         dentry = MALLOC(sizeof(struct dentry));
974         if (!dentry) {
975                 ERROR("Failed to allocate %zu bytes for root dentry",
976                       sizeof(struct dentry));
977                 ret = WIMLIB_ERR_NOMEM;
978                 goto out_free_security_data;
979         }
980
981         get_u32(buf, &dentry_offset);
982         if (dentry_offset == 0)
983                 dentry_offset = 8;
984         dentry_offset = (dentry_offset + 7) & ~7;
985                 
986         ret = read_dentry(buf, res_entry->original_size, dentry_offset, dentry);
987         /* This is the root dentry, so set its pointers correctly. */
988         dentry->parent = dentry;
989         dentry->next   = dentry;
990         dentry->prev   = dentry;
991         if (ret != 0)
992                 goto out_free_dentry_tree;
993
994         /* Now read the entire directory entry tree. */
995         ret = read_dentry_tree(buf, res_entry->original_size, dentry);
996         if (ret != 0)
997                 goto out_free_dentry_tree;
998
999         /* Calculate the full paths in the dentry tree. */
1000         ret = for_dentry_in_tree(dentry, calculate_dentry_full_path, NULL);
1001         if (ret != 0)
1002                 goto out_free_dentry_tree;
1003
1004         lgt = new_link_group_table(9001);
1005         if (!lgt)
1006                 goto out_free_dentry_tree;
1007         ret = for_dentry_in_tree(dentry, link_group_table_insert, lgt);
1008         if (ret != 0)
1009                 goto out_free_lgt;
1010
1011         ret = link_groups_free_duplicate_data(lgt);
1012         if (ret != 0)
1013                 goto out_free_lgt;
1014
1015         imd->lgt           = lgt;
1016         imd->security_data = sd;
1017         imd->root_dentry   = dentry;
1018         goto out_free_buf;
1019 out_free_lgt:
1020         free_link_group_table(lgt);
1021 out_free_dentry_tree:
1022         free_dentry_tree(dentry, NULL, false);
1023 out_free_security_data:
1024         free_security_data(sd);
1025 out_free_buf:
1026         FREE(buf);
1027         return ret;
1028 }
1029
1030 /* Write the metadata resource for the current image. */
1031 int write_metadata_resource(WIMStruct *w)
1032 {
1033         FILE *out;
1034         u8 *buf;
1035         u8 *p;
1036         int ret;
1037         u64 subdir_offset;
1038         struct dentry *root;
1039         struct lookup_table_entry *lte;
1040         struct resource_entry *res_entry;
1041         off_t metadata_offset;
1042         u64 metadata_original_size;
1043         u64 metadata_compressed_size;
1044         int metadata_ctype;
1045         u8  hash[WIM_HASH_SIZE];
1046
1047         DEBUG("Writing metadata resource for image %d", w->current_image);
1048
1049         out = w->out_fp;
1050         root = wim_root_dentry(w);
1051         metadata_ctype = wimlib_get_compression_type(w);
1052         metadata_offset = ftello(out);
1053         if (metadata_offset == -1)
1054                 return WIMLIB_ERR_WRITE;
1055
1056         struct wim_security_data *sd = wim_security_data(w);
1057         if (sd)
1058                 subdir_offset = sd->total_length + root->length + 8;
1059         else
1060                 subdir_offset = 8 + root->length + 8;
1061         calculate_subdir_offsets(root, &subdir_offset);
1062         metadata_original_size = subdir_offset;
1063         buf = MALLOC(metadata_original_size);
1064         if (!buf) {
1065                 ERROR("Failed to allocate %"PRIu64" bytes for "
1066                       "metadata resource", metadata_original_size);
1067                 return WIMLIB_ERR_NOMEM;
1068         }
1069
1070         p = write_security_data(sd, buf);
1071
1072         DEBUG("Writing dentry tree.");
1073         p = write_dentry_tree(root, p);
1074
1075         /* Like file resources, the lookup table entry for a metadata resource
1076          * uses for the hash code a SHA1 message digest of its uncompressed
1077          * contents. */
1078         sha1_buffer(buf, metadata_original_size, hash);
1079
1080         ret = write_resource_from_memory(buf, 
1081                                          metadata_ctype,
1082                                          metadata_original_size, 
1083                                          out,
1084                                          &metadata_compressed_size);
1085         FREE(buf);
1086         if (ret != 0)
1087                 return ret;
1088
1089         /* Update the lookup table entry, including the hash and output resource
1090          * entry fields, for this image's metadata resource.  */
1091         lte = wim_metadata_lookup_table_entry(w);
1092         res_entry = &lte->output_resource_entry;
1093         lte->out_refcnt++;
1094         if (memcmp(hash, lte->hash, WIM_HASH_SIZE) != 0) {
1095                 lookup_table_unlink(w->lookup_table, lte);
1096                 memcpy(lte->hash, hash, WIM_HASH_SIZE);
1097                 lookup_table_insert(w->lookup_table, lte);
1098         }
1099         res_entry->original_size = metadata_original_size;
1100         res_entry->offset        = metadata_offset;
1101         res_entry->size          = metadata_compressed_size;
1102         res_entry->flags         = WIM_RESHDR_FLAG_METADATA;
1103         if (metadata_ctype != WIM_COMPRESSION_TYPE_NONE)
1104                 res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
1105         return 0;
1106 }
1107
1108 static int write_file_resource(WIMStruct *w, const u8 hash[])
1109 {
1110         /* Get the lookup entry for the file resource. */
1111         struct lookup_table_entry *lte;
1112         
1113         lte = __lookup_resource(w->lookup_table, hash);
1114         if (!lte)
1115                 return 0;
1116
1117         /* No need to write file resources twice. */
1118         if (++lte->out_refcnt != 1)
1119                 return 0;
1120
1121         /* do not write empty resources */
1122         if (lte->resource_entry.original_size == 0)
1123                 return 0;
1124
1125         int out_wim_ctype = wimlib_get_compression_type(w);
1126         struct resource_entry *output_res_entry = &lte->output_resource_entry;
1127         u64 len;
1128         FILE *in_fp;
1129         FILE *out_fp = w->out_fp;
1130         int ret = 0;
1131
1132         /* Figure out if we can read the resource from the WIM file, or
1133          * if we have to read it from the filesystem outside, or if it's a
1134          * symbolic link with the data already in memory pointed to by a field
1135          * of the lookup table entry. */
1136         if (lte->is_symlink) {
1137                 off_t offset = ftello(w->out_fp);
1138                 u64 new_size;
1139
1140                 if (offset == -1) {
1141                         ERROR_WITH_ERRNO("Could not get position in output "
1142                                          "file");
1143                         return WIMLIB_ERR_WRITE;
1144                 }
1145
1146                 wimlib_assert(lte->symlink_buf);
1147
1148                 len = lte->resource_entry.original_size;
1149
1150                 ret = recompress_resource(NULL, lte->symlink_buf, len, len, 0,
1151                                           0, out_fp, out_wim_ctype, &new_size);
1152                 output_res_entry->size = new_size;
1153                 output_res_entry->original_size = len;
1154                 output_res_entry->offset = offset;
1155                 output_res_entry->flags = (out_wim_ctype == WIM_COMPRESSION_TYPE_NONE)
1156                                                 ? 0 : WIM_RESHDR_FLAG_COMPRESSED;
1157         } else if (lte->file_on_disk) {
1158
1159                 /* Read from disk (uncompressed) */
1160
1161                 len = lte->resource_entry.original_size;
1162
1163                 in_fp = fopen(lte->file_on_disk, "rb");
1164                 if (!in_fp) {
1165                         ERROR_WITH_ERRNO("Failed to open the file `%s'",
1166                                          lte->file_on_disk);
1167                         return WIMLIB_ERR_OPEN;
1168                 }
1169
1170                 ret = transfer_file_resource(in_fp, len, len, 0,
1171                                              WIM_COMPRESSION_TYPE_NONE, out_fp,
1172                                              out_wim_ctype, output_res_entry);
1173                 fclose(in_fp);
1174         } else {
1175                 int in_wim_ctype;
1176
1177                 /* Read from input WIM (possibly compressed) */
1178
1179                 /* It may be a different WIM file, in the case of
1180                  * exporting images from one WIM file to another */
1181                 if (lte->other_wim_fp) {
1182                         /* Different WIM file. */
1183                         in_fp = lte->other_wim_fp;
1184                         in_wim_ctype = lte->other_wim_ctype;
1185                 } else {
1186                         /* Same WIM file. */
1187                         in_fp = w->fp;
1188                         in_wim_ctype = out_wim_ctype;
1189                 }
1190                 int input_res_ctype = resource_compression_type(
1191                                                 in_wim_ctype, 
1192                                                 lte->resource_entry.flags);
1193
1194                 ret = transfer_file_resource(in_fp,
1195                                              lte->resource_entry.size,
1196                                              lte->resource_entry.original_size, 
1197                                              lte->resource_entry.offset,
1198                                              input_res_ctype, 
1199                                              out_fp,
1200                                              out_wim_ctype,
1201                                              output_res_entry);
1202         }
1203         return ret;
1204 }
1205
1206 /* 
1207  * Writes a dentry's resources to the output file. 
1208  *
1209  * @dentry:  The dentry for the file resource.
1210  * @wim_p:   A pointer to the WIMStruct.  The fields of interest to this
1211  *           function are the input and output file streams and the lookup
1212  *           table, and the alternate data streams.
1213  *
1214  * @return zero on success, nonzero on failure. 
1215  */
1216 int write_dentry_resources(struct dentry *dentry, void *wim_p)
1217 {
1218         WIMStruct *w = wim_p;
1219         int ret;
1220
1221         /* Directories don't need file resources. */
1222         if (dentry_is_directory(dentry))
1223                 return 0;
1224
1225         ret = write_file_resource(w, dentry->hash);
1226         if (ret != 0)
1227                 return ret;
1228         for (u16 i = 0; i < dentry->num_ads; i++) {
1229                 ret = write_file_resource(w, dentry->ads_entries[i].hash);
1230                 if (ret != 0)
1231                         return ret;
1232         }
1233         return 0;
1234 }
1235