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