]> wimlib.net Git - wimlib/blob - src/reparse.c
446b6f9f3765fc74f1c89c5eca495338be9cc53f
[wimlib] / src / reparse.c
1 /*
2  * reparse.c - Handle reparse data.
3  */
4
5 /*
6  * Copyright (C) 2012, 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include "wimlib/assert.h"
29 #include "wimlib/compiler.h"
30 #include "wimlib/endianness.h"
31 #include "wimlib/dentry.h"
32 #include "wimlib/encoding.h"
33 #include "wimlib/error.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/reparse.h"
36 #include "wimlib/resource.h"
37
38 #ifdef __WIN32__
39 #  include "wimlib/win32.h" /* for win32_get_file_and_vol_ids() */
40 #endif
41
42 #ifdef HAVE_ALLOCA_H
43 #  include <alloca.h>
44 #endif
45 #include <errno.h>
46 #include <stdlib.h>
47
48 struct reparse_buffer_disk {
49         le32 rptag;
50         le16 rpdatalen;
51         le16 rpreserved;
52         le16 substitute_name_offset;
53         le16 substitute_name_nbytes;
54         le16 print_name_offset;
55         le16 print_name_nbytes;
56         union {
57                 struct {
58                         le32 rpflags;
59                         u8 data[REPARSE_POINT_MAX_SIZE - 20];
60                 } _packed_attribute symlink;
61                 struct {
62                         u8 data[REPARSE_POINT_MAX_SIZE - 16];
63                 } _packed_attribute junction;
64         };
65 } _packed_attribute;
66
67 static const utf16lechar volume_junction_prefix[11] = {
68         cpu_to_le16('\\'),
69         cpu_to_le16('\\'),
70         cpu_to_le16('?'),
71         cpu_to_le16('\\'),
72         cpu_to_le16('V'),
73         cpu_to_le16('o'),
74         cpu_to_le16('l'),
75         cpu_to_le16('u'),
76         cpu_to_le16('m'),
77         cpu_to_le16('e'),
78         cpu_to_le16('{'),
79 };
80
81 /* Parse the "substitute name" (link target) from a symbolic link or junction
82  * reparse point.
83  *
84  * Return value is:
85  *
86  * Non-negative integer:
87  *      The name is an absolute symbolic link in one of several formats,
88  *      and the return value is the number of UTF-16LE characters that need to
89  *      be advanced to reach a simple "absolute" path starting with a backslash
90  *      (i.e. skip over \??\ and/or drive letter)
91  * Negative integer:
92  *      SUBST_NAME_IS_VOLUME_JUNCTION:
93  *              The name is a volume junction.
94  *      SUBST_NAME_IS_RELATIVE_LINK:
95  *              The name is a relative symbolic link.
96  *      SUBST_NAME_IS_UNKNOWN:
97  *              The name does not appear to be a valid symbolic link, junction,
98  *              or mount point.
99  */
100 int
101 parse_substitute_name(const utf16lechar *substitute_name,
102                       u16 substitute_name_nbytes, u32 rptag)
103 {
104         u16 substitute_name_nchars = substitute_name_nbytes / 2;
105
106         if (substitute_name_nchars >= 7 &&
107             substitute_name[0] == cpu_to_le16('\\') &&
108             substitute_name[1] == cpu_to_le16('?') &&
109             substitute_name[2] == cpu_to_le16('?') &&
110             substitute_name[3] == cpu_to_le16('\\') &&
111             substitute_name[4] != cpu_to_le16('\0') &&
112             substitute_name[5] == cpu_to_le16(':') &&
113             substitute_name[6] == cpu_to_le16('\\'))
114         {
115                 /* "Full" symlink or junction (\??\x:\ prefixed path) */
116                 return 6;
117         } else if (rptag == WIM_IO_REPARSE_TAG_MOUNT_POINT &&
118                    substitute_name_nchars >= 12 &&
119                    memcmp(substitute_name, volume_junction_prefix,
120                           sizeof(volume_junction_prefix)) == 0 &&
121                    substitute_name[substitute_name_nchars - 1] == cpu_to_le16('\\'))
122         {
123                 /* Volume junction.  Can't really do anything with it. */
124                 return SUBST_NAME_IS_VOLUME_JUNCTION;
125         } else if (rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
126                    substitute_name_nchars >= 3 &&
127                    substitute_name[0] != cpu_to_le16('\0') &&
128                    substitute_name[1] == cpu_to_le16(':') &&
129                    substitute_name[2] == cpu_to_le16('\\'))
130         {
131                 /* "Absolute" symlink, with drive letter */
132                 return 2;
133         } else if (rptag == WIM_IO_REPARSE_TAG_SYMLINK &&
134                    substitute_name_nchars >= 1)
135         {
136                 if (substitute_name[0] == cpu_to_le16('\\'))
137                         /* "Absolute" symlink, without drive letter */
138                         return 0;
139                 else
140                         /* "Relative" symlink, without drive letter */
141                         return SUBST_NAME_IS_RELATIVE_LINK;
142         } else {
143                 return SUBST_NAME_IS_UNKNOWN;
144         }
145 }
146
147 /*
148  * Read the data from a symbolic link, junction, or mount point reparse point
149  * buffer into a `struct reparse_data'.
150  *
151  * See http://msdn.microsoft.com/en-us/library/cc232006(v=prot.10).aspx for a
152  * description of the format of the reparse point buffers.
153  */
154 int
155 parse_reparse_data(const u8 * restrict rpbuf, u16 rpbuflen,
156                    struct reparse_data * restrict rpdata)
157 {
158         u16 substitute_name_offset;
159         u16 print_name_offset;
160         const struct reparse_buffer_disk *rpbuf_disk =
161                 (const struct reparse_buffer_disk*)rpbuf;
162         const u8 *data;
163
164         memset(rpdata, 0, sizeof(*rpdata));
165         if (rpbuflen < 16)
166                 goto out_invalid;
167         rpdata->rptag = le32_to_cpu(rpbuf_disk->rptag);
168         wimlib_assert(rpdata->rptag == WIM_IO_REPARSE_TAG_SYMLINK ||
169                       rpdata->rptag == WIM_IO_REPARSE_TAG_MOUNT_POINT);
170         rpdata->rpdatalen = le16_to_cpu(rpbuf_disk->rpdatalen);
171         rpdata->rpreserved = le16_to_cpu(rpbuf_disk->rpreserved);
172         substitute_name_offset = le16_to_cpu(rpbuf_disk->substitute_name_offset);
173         rpdata->substitute_name_nbytes = le16_to_cpu(rpbuf_disk->substitute_name_nbytes);
174         print_name_offset = le16_to_cpu(rpbuf_disk->print_name_offset);
175         rpdata->print_name_nbytes = le16_to_cpu(rpbuf_disk->print_name_nbytes);
176
177         if ((substitute_name_offset & 1) | (print_name_offset & 1) |
178             (rpdata->substitute_name_nbytes & 1) | (rpdata->print_name_nbytes & 1))
179         {
180                 /* Names would be unaligned... */
181                 goto out_invalid;
182         }
183
184         if (rpdata->rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
185                 if (rpbuflen < 20)
186                         goto out_invalid;
187                 rpdata->rpflags = le16_to_cpu(rpbuf_disk->symlink.rpflags);
188                 data = rpbuf_disk->symlink.data;
189         } else {
190                 data = rpbuf_disk->junction.data;
191         }
192         if ((size_t)substitute_name_offset + rpdata->substitute_name_nbytes +
193             (data - rpbuf) > rpbuflen)
194                 goto out_invalid;
195         if ((size_t)print_name_offset + rpdata->print_name_nbytes +
196             (data - rpbuf) > rpbuflen)
197                 goto out_invalid;
198         rpdata->substitute_name = (utf16lechar*)&data[substitute_name_offset];
199         rpdata->print_name = (utf16lechar*)&data[print_name_offset];
200         return 0;
201 out_invalid:
202         ERROR("Invalid reparse data");
203         return WIMLIB_ERR_INVALID_REPARSE_DATA;
204 }
205
206 /*
207  * Create a reparse point data buffer.
208  *
209  * @rpdata:  Structure that contains the data we need.
210  *
211  * @rpbuf:     Buffer into which to write the reparse point data buffer.  Must be
212  *              at least REPARSE_POINT_MAX_SIZE bytes long.
213  */
214 int
215 make_reparse_buffer(const struct reparse_data * restrict rpdata,
216                     u8 * restrict rpbuf)
217 {
218         struct reparse_buffer_disk *rpbuf_disk =
219                 (struct reparse_buffer_disk*)rpbuf;
220         u8 *data;
221
222         rpbuf_disk->rptag = cpu_to_le32(rpdata->rptag);
223         rpbuf_disk->rpreserved = cpu_to_le16(rpdata->rpreserved);
224         rpbuf_disk->substitute_name_offset = cpu_to_le16(0);
225         rpbuf_disk->substitute_name_nbytes = cpu_to_le16(rpdata->substitute_name_nbytes);
226         rpbuf_disk->print_name_offset = cpu_to_le16(rpdata->substitute_name_nbytes + 2);
227         rpbuf_disk->print_name_nbytes = cpu_to_le16(rpdata->print_name_nbytes);
228
229         if (rpdata->rptag == WIM_IO_REPARSE_TAG_SYMLINK) {
230                 rpbuf_disk->symlink.rpflags = cpu_to_le32(rpdata->rpflags);
231                 data = rpbuf_disk->symlink.data;
232         } else {
233                 data = rpbuf_disk->junction.data;
234         }
235
236         /* We null-terminate the substitute and print names, although this may
237          * not be strictly necessary.  Note that the byte counts should not
238          * include the null terminators. */
239         if (data + rpdata->substitute_name_nbytes +
240             rpdata->print_name_nbytes +
241             2 * sizeof(utf16lechar) - rpbuf > REPARSE_POINT_MAX_SIZE)
242         {
243                 ERROR("Reparse data is too long!");
244                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
245         }
246         data = mempcpy(data, rpdata->substitute_name, rpdata->substitute_name_nbytes);
247         *(utf16lechar*)data = cpu_to_le16(0);
248         data += 2;
249         data = mempcpy(data, rpdata->print_name, rpdata->print_name_nbytes);
250         *(utf16lechar*)data = cpu_to_le16(0);
251         data += 2;
252         rpbuf_disk->rpdatalen = cpu_to_le16(data - rpbuf - 8);
253         return 0;
254 }
255
256 /*
257  * Read the reparse data from a WIM inode that is a reparse point.
258  *
259  * @rpbuf points to a buffer at least REPARSE_POINT_MAX_SIZE bytes into which
260  * the reparse point data buffer will be reconstructed.
261  *
262  * Note: in the WIM format, the first 8 bytes of the reparse point data buffer
263  * are omitted, presumably because we already know the reparse tag from the
264  * dentry, and we already know the reparse tag length from the lookup table
265  * entry resource length.  However, we reconstruct the first 8 bytes in the
266  * buffer returned by this function.
267  */
268 int
269 wim_inode_get_reparse_data(const struct wim_inode * restrict inode,
270                            u8 * restrict rpbuf,
271                            u16 * restrict rpbuflen_ret)
272 {
273         struct wim_lookup_table_entry *lte;
274         int ret;
275         struct reparse_buffer_disk *rpbuf_disk;
276         u16 rpdatalen;
277
278         wimlib_assert(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT);
279
280         lte = inode_unnamed_lte_resolved(inode);
281         if (!lte) {
282                 ERROR("Reparse point has no reparse data!");
283                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
284         }
285
286         if (wim_resource_size(lte) > REPARSE_POINT_MAX_SIZE - 8) {
287                 ERROR("Reparse data is too long!");
288                 return WIMLIB_ERR_INVALID_REPARSE_DATA;
289         }
290         rpdatalen = wim_resource_size(lte);
291
292         /* Read the data from the WIM file */
293         ret = read_full_resource_into_buf(lte, rpbuf + 8);
294         if (ret)
295                 return ret;
296
297         /* Reconstruct the first 8 bytes of the reparse point buffer */
298         rpbuf_disk = (struct reparse_buffer_disk*)rpbuf;
299
300         /* ReparseTag */
301         rpbuf_disk->rptag = cpu_to_le32(inode->i_reparse_tag);
302
303         /* ReparseDataLength */
304         rpbuf_disk->rpdatalen = cpu_to_le16(rpdatalen);
305
306         /* ReparseReserved
307          * XXX this could be one of the unknown fields in the WIM dentry. */
308         rpbuf_disk->rpreserved = cpu_to_le16(0);
309
310         *rpbuflen_ret = rpdatalen + 8;
311         return 0;
312 }
313
314 /* UNIX version of getting and setting the data in reparse points */
315 #if !defined(__WIN32__)
316
317 /* Get the UNIX symlink target from a WIM inode.  The inode may be either a
318  * "real" symlink (reparse tag WIM_IO_REPARSE_TAG_SYMLINK), or it may be a
319  * junction point (reparse tag WIM_IO_REPARSE_TAG_MOUNT_POINT).
320  *
321  * This has similar semantics to the UNIX readlink() function, except the path
322  * argument is swapped out with the `struct wim_inode' for a reparse point, and
323  * on failure a negated error code is returned rather than -1 with errno set.  */
324 ssize_t
325 wim_inode_readlink(const struct wim_inode * restrict inode,
326                    char * restrict buf, size_t bufsize)
327 {
328         int ret;
329         struct reparse_buffer_disk rpbuf_disk _aligned_attribute(8);
330         struct reparse_data rpdata;
331         char *link_target;
332         char *translated_target;
333         size_t link_target_len;
334         u16 rpbuflen;
335
336         wimlib_assert(inode_is_symlink(inode));
337
338         if (wim_inode_get_reparse_data(inode, (u8*)&rpbuf_disk, &rpbuflen))
339                 return -EIO;
340
341         if (parse_reparse_data((const u8*)&rpbuf_disk, rpbuflen, &rpdata))
342                 return -EIO;
343
344         ret = utf16le_to_tstr(rpdata.substitute_name,
345                               rpdata.substitute_name_nbytes,
346                               &link_target, &link_target_len);
347         if (ret)
348                 return -errno;
349
350         translated_target = link_target;
351         ret = parse_substitute_name(rpdata.substitute_name,
352                                     rpdata.substitute_name_nbytes,
353                                     rpdata.rptag);
354         switch (ret) {
355         case SUBST_NAME_IS_RELATIVE_LINK:
356                 goto out_translate_slashes;
357         case SUBST_NAME_IS_VOLUME_JUNCTION:
358                 goto out_have_link;
359         case SUBST_NAME_IS_UNKNOWN:
360                 ERROR("Can't understand reparse point "
361                       "substitute name \"%s\"", link_target);
362                 ret = -EIO;
363                 goto out_free_link_target;
364         default:
365                 translated_target += ret;
366                 link_target_len -= ret;
367                 break;
368         }
369
370 out_translate_slashes:
371         for (size_t i = 0; i < link_target_len; i++)
372                 if (translated_target[i] == '\\')
373                         translated_target[i] = '/';
374 out_have_link:
375         if (link_target_len > bufsize) {
376                 link_target_len = bufsize;
377                 ret = -ENAMETOOLONG;
378         } else {
379                 ret = link_target_len;
380         }
381         memcpy(buf, translated_target, link_target_len);
382 out_free_link_target:
383         FREE(link_target);
384         return ret;
385 }
386
387 int
388 wim_inode_set_symlink(struct wim_inode *inode,
389                       const char *target,
390                       struct wim_lookup_table *lookup_table)
391
392 {
393         struct reparse_buffer_disk rpbuf_disk _aligned_attribute(8);
394         struct reparse_data rpdata;
395         static const char abs_subst_name_prefix[12] = "\\\0?\0?\0\\\0C\0:\0";
396         static const char abs_print_name_prefix[4] = "C\0:\0";
397         utf16lechar *name_utf16le;
398         size_t name_utf16le_nbytes;
399         int ret;
400
401         DEBUG("Creating reparse point data buffer for UNIX "
402               "symlink target \"%s\"", target);
403         memset(&rpdata, 0, sizeof(rpdata));
404         ret = tstr_to_utf16le(target, strlen(target),
405                               &name_utf16le, &name_utf16le_nbytes);
406         if (ret)
407                 return ret;
408
409         for (size_t i = 0; i < name_utf16le_nbytes / 2; i++)
410                 if (name_utf16le[i] == cpu_to_le16('/'))
411                         name_utf16le[i] = cpu_to_le16('\\');
412
413         /* Compatability notes:
414          *
415          * On UNIX, an absolute symbolic link begins with '/'; everything else
416          * is a relative symbolic link.  (Quite simple compared to the various
417          * ways to provide Windows paths.)
418          *
419          * To change a UNIX relative symbolic link to Windows format, we only
420          * need to translate it to UTF-16LE and replace backslashes with forward
421          * slashes.  We do not make any attempt to handle filename character
422          * problems, such as a link target that itself contains backslashes on
423          * UNIX.  Then, for these relative links, we set the reparse header
424          * @flags field to SYMBOLIC_LINK_RELATIVE.
425          *
426          * For UNIX absolute symbolic links, we must set the @flags field to 0.
427          * Then, there are multiple options as to actually represent the
428          * absolute link targets:
429          *
430          * (1) An absolute path beginning with one backslash character. similar
431          * to UNIX-style, just with a different path separator.  Print name same
432          * as substitute name.
433          *
434          * (2) Absolute path beginning with drive letter followed by a
435          * backslash.  Print name same as substitute name.
436          *
437          * (3) Absolute path beginning with drive letter followed by a
438          * backslash; substitute name prefixed with \??\, otherwise same as
439          * print name.
440          *
441          * We choose option (3) here, and we just assume C: for the drive
442          * letter.  The reasoning for this is:
443          *
444          * (1) Microsoft imagex.exe has a bug where it does not attempt to do
445          * reparse point fixups for these links, even though they are valid
446          * absolute links.  (Note: in this case prefixing the substitute name
447          * with \??\ does not work; it just makes the data unable to be restored
448          * at all.)
449          * (2) Microsoft imagex.exe will fail when doing reparse point fixups
450          * for these.  It apparently contains a bug that causes it to create an
451          * invalid reparse point, which then cannot be restored.
452          * (3) This is the only option I tested for which reparse point fixups
453          * worked properly in Microsoft imagex.exe.
454          *
455          * So option (3) it is.
456          */
457
458         rpdata.rptag = inode->i_reparse_tag;
459         if (target[0] == '/') {
460                 rpdata.substitute_name_nbytes = name_utf16le_nbytes +
461                                                 sizeof(abs_subst_name_prefix);
462                 rpdata.print_name_nbytes = name_utf16le_nbytes +
463                                            sizeof(abs_print_name_prefix);
464                 rpdata.substitute_name = alloca(rpdata.substitute_name_nbytes);
465                 rpdata.print_name = alloca(rpdata.print_name_nbytes);
466                 memcpy(rpdata.substitute_name, abs_subst_name_prefix,
467                        sizeof(abs_subst_name_prefix));
468                 memcpy(rpdata.print_name, abs_print_name_prefix,
469                        sizeof(abs_print_name_prefix));
470                 memcpy((void*)rpdata.substitute_name + sizeof(abs_subst_name_prefix),
471                        name_utf16le, name_utf16le_nbytes);
472                 memcpy((void*)rpdata.print_name + sizeof(abs_print_name_prefix),
473                        name_utf16le, name_utf16le_nbytes);
474         } else {
475                 rpdata.substitute_name_nbytes = name_utf16le_nbytes;
476                 rpdata.print_name_nbytes = name_utf16le_nbytes;
477                 rpdata.substitute_name = name_utf16le;
478                 rpdata.print_name = name_utf16le;
479                 rpdata.rpflags = SYMBOLIC_LINK_RELATIVE;
480         }
481
482         ret = make_reparse_buffer(&rpdata, (u8*)&rpbuf_disk);
483         if (ret == 0) {
484                 ret = inode_set_unnamed_stream(inode,
485                                                (u8*)&rpbuf_disk + 8,
486                                                le16_to_cpu(rpbuf_disk.rpdatalen),
487                                                lookup_table);
488         }
489         FREE(name_utf16le);
490         return ret;
491 }
492
493 #include <sys/stat.h>
494
495 static int
496 unix_get_ino_and_dev(const char *path, u64 *ino_ret, u64 *dev_ret)
497 {
498         struct stat stbuf;
499         if (stat(path, &stbuf)) {
500                 if (errno != ENOENT)
501                         WARNING_WITH_ERRNO("Failed to stat \"%s\"", path);
502                 /* Treat as a link pointing outside the capture root (it
503                  * most likely is). */
504                 return WIMLIB_ERR_STAT;
505         } else {
506                 *ino_ret = stbuf.st_ino;
507                 *dev_ret = stbuf.st_dev;
508                 return 0;
509         }
510 }
511
512 #endif /* !defined(__WIN32__) */
513
514 #ifdef __WIN32__
515 #  define RP_PATH_SEPARATOR L'\\'
516 #  define is_rp_path_separator(c) ((c) == L'\\' || (c) == L'/')
517 #  define os_get_ino_and_dev win32_get_file_and_vol_ids
518 #else
519 #  define RP_PATH_SEPARATOR '/'
520 #  define is_rp_path_separator(c) ((c) == '/')
521 #  define os_get_ino_and_dev unix_get_ino_and_dev
522 #endif
523
524 /* Fix up absolute symbolic link targets--- mostly shared between UNIX and
525  * Windows */
526 tchar *
527 capture_fixup_absolute_symlink(tchar *dest,
528                                u64 capture_root_ino, u64 capture_root_dev)
529 {
530         tchar *p = dest;
531
532 #ifdef __WIN32__
533         /* Skip drive letter */
534         if (!is_rp_path_separator(*dest))
535                 p += 2;
536 #endif
537
538         DEBUG("Fixing symlink or junction \"%"TS"\"", dest);
539         for (;;) {
540                 tchar save;
541                 int ret;
542                 u64 ino;
543                 u64 dev;
544
545                 while (is_rp_path_separator(*p))
546                         p++;
547
548                 save = *p;
549                 *p = T('\0');
550                 ret = os_get_ino_and_dev(dest, &ino, &dev);
551                 *p = save;
552
553                 if (ret) /* stat() failed before we got to the capture root---
554                             assume the link points outside it. */
555                         return NULL;
556
557                 if (ino == capture_root_ino && dev == capture_root_dev) {
558                         /* Link points inside capture root.  Return abbreviated
559                          * path. */
560                         if (*p == T('\0'))
561                                 *(p - 1) = RP_PATH_SEPARATOR;
562                         while (p - 1 >= dest && is_rp_path_separator(*(p - 1)))
563                                 p--;
564                 #ifdef __WIN32__
565                         if (!is_rp_path_separator(dest[0])) {
566                                 *--p = dest[1];
567                                 *--p = dest[0];
568                         }
569                 #endif
570                         wimlib_assert(p >= dest);
571                         return p;
572                 }
573
574                 if (*p == T('\0')) {
575                         /* Link points outside capture root. */
576                         return NULL;
577                 }
578
579                 do {
580                         p++;
581                 } while (!is_rp_path_separator(*p) && *p != T('\0'));
582         }
583 }