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