9dc0b9d49c683f6bf238c4d69dffa02a5ad92ca5
[wimlib] / src / ntfs-capture.c
1 /*
2  * ntfs-capture.c
3  *
4  * Capture a WIM image from a NTFS volume.  We capture everything we can,
5  * including security data and alternate data streams.  There should be no loss
6  * of information.
7  */
8
9 /*
10  * Copyright (C) 2012 Eric Biggers
11  *
12  * This file is part of wimlib, a library for working with WIM files.
13  *
14  * wimlib is free software; you can redistribute it and/or modify it under the
15  * terms of the GNU Lesser General Public License as published by the Free
16  * Software Foundation; either version 2.1 of the License, or (at your option)
17  * any later version.
18  *
19  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21  * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU Lesser General Public License
25  * along with wimlib; if not, see http://www.gnu.org/licenses/.
26  */
27
28 #include "config.h"
29 #include "wimlib_internal.h"
30
31
32 #ifdef WITH_NTFS_3G
33 #include "dentry.h"
34 #include "lookup_table.h"
35 #include "io.h"
36 #include <ntfs-3g/layout.h>
37 #include <ntfs-3g/acls.h>
38 #include <ntfs-3g/attrib.h>
39 #include <ntfs-3g/misc.h>
40 #include <ntfs-3g/reparse.h>
41 #include <ntfs-3g/security.h>
42 #include <ntfs-3g/volume.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45
46 extern int ntfs_inode_get_security(ntfs_inode *ni, u32 selection, char *buf,
47                                    u32 buflen, u32 *psize);
48
49 extern int ntfs_inode_get_attributes(ntfs_inode *ni);
50
51 /* Structure that allows searching the security descriptors by SHA1 message
52  * digest. */
53 struct sd_set {
54         struct wim_security_data *sd;
55         struct sd_node *root;
56 };
57
58 /* Binary tree node of security descriptors, indexed by the @hash field. */
59 struct sd_node {
60         int security_id;
61         u8 hash[SHA1_HASH_SIZE];
62         struct sd_node *left;
63         struct sd_node *right;
64 };
65
66 static void free_sd_tree(struct sd_node *root)
67 {
68         if (root) {
69                 free_sd_tree(root->left);
70                 free_sd_tree(root->right);
71                 FREE(root);
72         }
73 }
74 /* Frees a security descriptor index set. */
75 static void destroy_sd_set(struct sd_set *sd_set)
76 {
77         free_sd_tree(sd_set->root);
78 }
79
80 /* Inserts a a new node into the security descriptor index tree. */
81 static void insert_sd_node(struct sd_node *new, struct sd_node *root)
82 {
83         int cmp = hashes_cmp(new->hash, root->hash);
84         if (cmp < 0) {
85                 if (root->left)
86                         insert_sd_node(new, root->left);
87                 else 
88                         root->left = new;
89         } else if (cmp > 0) {
90                 if (root->right)
91                         insert_sd_node(new, root->right);
92                 else 
93                         root->right = new;
94         } else {
95                 wimlib_assert(0);
96         }
97 }
98
99 /* Returns the security ID of the security data having a SHA1 message digest of
100  * @hash in the security descriptor index tree rooted at @root. 
101  *
102  * If not found, return -1. */
103 static int lookup_sd(const u8 hash[SHA1_HASH_SIZE], struct sd_node *root)
104 {
105         int cmp;
106         if (!root)
107                 return -1;
108         cmp = hashes_cmp(hash, root->hash);
109         if (cmp < 0)
110                 return lookup_sd(hash, root->left);
111         else if (cmp > 0)
112                 return lookup_sd(hash, root->right);
113         else
114                 return root->security_id;
115 }
116
117 /*
118  * Adds a security descriptor to the indexed security descriptor set as well as
119  * the corresponding `struct wim_security_data', and returns the new security
120  * ID; or, if there is an existing security descriptor that is the same, return
121  * the security ID for it.  If a new security descriptor cannot be allocated,
122  * return -1.
123  */
124 static int sd_set_add_sd(struct sd_set *sd_set, const u8 *descriptor,
125                          size_t size)
126 {
127         u8 hash[SHA1_HASH_SIZE];
128         int security_id;
129         struct sd_node *new;
130         u8 **descriptors;
131         u64 *sizes;
132         u8 *descr_copy;
133         struct wim_security_data *sd;
134
135         sha1_buffer(descriptor, size, hash);
136         security_id = lookup_sd(hash, sd_set->root);
137         if (security_id >= 0)
138                 return security_id;
139
140         new = MALLOC(sizeof(*new));
141         if (!new)
142                 goto out;
143         descr_copy = MALLOC(size);
144         if (!descr_copy)
145                 goto out_free_node;
146
147         sd = sd_set->sd;
148
149         memcpy(descr_copy, descriptor, size);
150         new->security_id = sd->num_entries;
151         new->left = NULL;
152         new->right = NULL;
153         copy_hash(new->hash, hash);
154
155
156         descriptors = REALLOC(sd->descriptors,
157                               (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
158         if (!descriptors)
159                 goto out_free_descr;
160         sd->descriptors = descriptors;
161         sizes = REALLOC(sd->sizes,
162                         (sd->num_entries + 1) * sizeof(sd->sizes[0]));
163         if (!sizes)
164                 goto out_free_descr;
165         sd->sizes = sizes;
166         sd->descriptors[sd->num_entries] = descr_copy;
167         sd->sizes[sd->num_entries] = size;
168         sd->num_entries++;
169         sd->total_length += size + sizeof(sd->sizes[0]);
170
171         if (sd_set->root)
172                 insert_sd_node(sd_set->root, new);
173         else
174                 sd_set->root = new;
175         return new->security_id;
176 out_free_descr:
177         FREE(descr_copy);
178 out_free_node:
179         FREE(new);
180 out:
181         return -1;
182 }
183
184 static inline ntfschar *attr_record_name(ATTR_RECORD *ar)
185 {
186         return (ntfschar*)((u8*)ar + le16_to_cpu(ar->name_offset));
187 }
188
189 /* Calculates the SHA1 message digest of a NTFS attribute. 
190  *
191  * @ni:  The NTFS inode containing the attribute.
192  * @ar:  The ATTR_RECORD describing the attribute.
193  * @md:  If successful, the returned SHA1 message digest.
194  *
195  * Return 0 on success or nonzero on error.
196  */
197 static int ntfs_attr_sha1sum(ntfs_inode *ni, ATTR_RECORD *ar,
198                              u8 md[SHA1_HASH_SIZE])
199 {
200         s64 pos = 0;
201         s64 bytes_remaining;
202         char buf[4096];
203         ntfs_attr *na;
204         SHA_CTX ctx;
205
206         na = ntfs_attr_open(ni, ar->type, attr_record_name(ar),
207                             ar->name_length);
208         if (!na) {
209                 ERROR_WITH_ERRNO("Failed to open NTFS attribute");
210                 return WIMLIB_ERR_NTFS_3G;
211         }
212
213         bytes_remaining = na->data_size;
214         sha1_init(&ctx);
215
216         DEBUG("Calculating SHA1 message digest (%"PRIu64" bytes)",
217                         bytes_remaining);
218
219         while (bytes_remaining) {
220                 s64 to_read = min(bytes_remaining, sizeof(buf));
221                 if (ntfs_attr_pread(na, pos, to_read, buf) != to_read) {
222                         ERROR_WITH_ERRNO("Error reading NTFS attribute");
223                         return WIMLIB_ERR_NTFS_3G;
224                 }
225                 sha1_update(&ctx, buf, to_read);
226                 pos += to_read;
227                 bytes_remaining -= to_read;
228         }
229         sha1_final(md, &ctx);
230         ntfs_attr_close(na);
231         return 0;
232 }
233
234 /* Load the streams from a WIM file or reparse point in the NTFS volume into the
235  * WIM lookup table */
236 static int capture_ntfs_streams(struct dentry *dentry, ntfs_inode *ni,
237                                 char path[], size_t path_len,
238                                 struct lookup_table *lookup_table,
239                                 ntfs_volume **ntfs_vol_p,
240                                 ATTR_TYPES type)
241 {
242
243         ntfs_attr_search_ctx *actx;
244         u8 attr_hash[SHA1_HASH_SIZE];
245         struct ntfs_location *ntfs_loc;
246         struct lookup_table_entry *lte;
247         int ret = 0;
248
249         DEBUG("Capturing NTFS data streams from `%s'", path);
250
251         /* Get context to search the streams of the NTFS file. */
252         actx = ntfs_attr_get_search_ctx(ni, NULL);
253         if (!actx) {
254                 ERROR_WITH_ERRNO("Cannot get attribute search "
255                                  "context");
256                 return WIMLIB_ERR_NTFS_3G;
257         }
258
259         /* Capture each data stream or reparse data stream. */
260         while (!ntfs_attr_lookup(type, NULL, 0,
261                                  CASE_SENSITIVE, 0, NULL, 0, actx))
262         {
263                 char *stream_name_utf8;
264                 size_t stream_name_utf16_len;
265
266                 /* Checksum the stream. */
267                 ret = ntfs_attr_sha1sum(ni, actx->attr, attr_hash);
268                 if (ret != 0)
269                         goto out_put_actx;
270
271                 /* Make a lookup table entry for the stream, or use an existing
272                  * one if there's already an identical stream. */
273                 lte = __lookup_resource(lookup_table, attr_hash);
274                 ret = WIMLIB_ERR_NOMEM;
275                 if (lte) {
276                         lte->refcnt++;
277                 } else {
278                         struct ntfs_location *ntfs_loc;
279
280                         ntfs_loc = CALLOC(1, sizeof(*ntfs_loc));
281                         if (!ntfs_loc)
282                                 goto out_put_actx;
283                         ntfs_loc->ntfs_vol_p = ntfs_vol_p;
284                         ntfs_loc->path_utf8 = MALLOC(path_len + 1);
285                         if (!ntfs_loc->path_utf8)
286                                 goto out_free_ntfs_loc;
287                         memcpy(ntfs_loc->path_utf8, path, path_len + 1);
288                         ntfs_loc->stream_name_utf16 = MALLOC(actx->attr->name_length * 2);
289                         if (!ntfs_loc->stream_name_utf16)
290                                 goto out_free_ntfs_loc;
291                         memcpy(ntfs_loc->stream_name_utf16,
292                                attr_record_name(actx->attr),
293                                actx->attr->name_length * 2);
294
295                         ntfs_loc->stream_name_utf16_num_chars = actx->attr->name_length;
296                         ntfs_loc->is_reparse_point = (type == AT_REPARSE_POINT);
297                         lte = new_lookup_table_entry();
298                         if (!lte)
299                                 goto out_free_ntfs_loc;
300                         lte->ntfs_loc = ntfs_loc;
301                         lte->resource_location = RESOURCE_IN_NTFS_VOLUME;
302                         lte->resource_entry.original_size = actx->attr->data_size;
303                         lte->resource_entry.size = actx->attr->data_size;
304                         DEBUG("Add resource for `%s' (size = %zu)",
305                                 dentry->file_name_utf8,
306                                 lte->resource_entry.original_size);
307                         copy_hash(lte->hash, attr_hash);
308                         lookup_table_insert(lookup_table, lte);
309                 }
310                 if (actx->attr->name_length == 0) {
311                         if (dentry->lte) {
312                                 ERROR("Found two un-named data streams for "
313                                       "`%s'", path);
314                                 ret = WIMLIB_ERR_NTFS_3G;
315                                 goto out_free_lte;
316                         }
317                         dentry->lte = lte;
318                 } else {
319                         struct ads_entry *new_ads_entry;
320                         stream_name_utf8 = utf16_to_utf8((const u8*)attr_record_name(actx->attr),
321                                                          actx->attr->name_length,
322                                                          &stream_name_utf16_len);
323                         if (!stream_name_utf8)
324                                 goto out_free_lte;
325                         new_ads_entry = dentry_add_ads(dentry, stream_name_utf8);
326                         FREE(stream_name_utf8);
327                         if (!new_ads_entry)
328                                 goto out_free_lte;
329                                 
330                         new_ads_entry->lte = lte;
331                 }
332         }
333         ret = 0;
334         goto out_put_actx;
335 out_free_lte:
336         free_lookup_table_entry(lte);
337 out_free_ntfs_loc:
338         if (ntfs_loc) {
339                 FREE(ntfs_loc->path_utf8);
340                 FREE(ntfs_loc->stream_name_utf16);
341                 FREE(ntfs_loc);
342         }
343 out_put_actx:
344         ntfs_attr_put_search_ctx(actx);
345         if (ret == 0)
346                 DEBUG("Successfully captured NTFS streams from `%s'", path);
347         else
348                 DEBUG("Failed to capture NTFS streams from `%s", path);
349         return ret;
350 }
351
352 struct readdir_ctx {
353         struct dentry       *parent;
354         ntfs_inode          *dir_ni;
355         char                *path;
356         size_t               path_len;
357         struct lookup_table *lookup_table;
358         struct sd_set       *sd_set;
359         const struct capture_config *config;
360         ntfs_volume        **ntfs_vol_p;
361 };
362
363 static int
364 build_dentry_tree_ntfs_recursive(struct dentry **root_p, ntfs_inode *ni,
365                                  char path[], size_t path_len,
366                                  struct lookup_table *lookup_table,
367                                  struct sd_set *sd_set,
368                                  const struct capture_config *config,
369                                  ntfs_volume **ntfs_vol_p);
370
371 static int wim_ntfs_capture_filldir(void *dirent, const ntfschar *name,
372                                     const int name_len, const int name_type,
373                                     const s64 pos, const MFT_REF mref,
374                                     const unsigned dt_type)
375 {
376         struct readdir_ctx *ctx;
377         size_t utf8_name_len;
378         char *utf8_name;
379         struct dentry *child = NULL;
380         int ret;
381         size_t path_len;
382
383         if (name_type == FILE_NAME_DOS)
384                 return 0;
385
386         ret = -1;
387
388         utf8_name = utf16_to_utf8((const u8*)name, name_len * 2,
389                                   &utf8_name_len);
390         if (!utf8_name)
391                 goto out;
392
393         if (utf8_name[0] == '.' &&
394              (utf8_name[1] == '\0' ||
395               (utf8_name[1] == '.' && utf8_name[2] == '\0'))) {
396                 DEBUG("Skipping dentry `%s'", utf8_name);
397                 ret = 0;
398                 goto out_free_utf8_name;
399         }
400
401         DEBUG("Opening inode for `%s'", utf8_name);
402
403         ctx = dirent;
404
405         ntfs_inode *ni = ntfs_inode_open(ctx->dir_ni->vol, mref);
406         if (!ni) {
407                 ERROR_WITH_ERRNO("Failed to open NTFS inode");
408                 ret = 1;
409         }
410         path_len = ctx->path_len;
411         if (path_len != 1)
412                 ctx->path[path_len++] = '/';
413         memcpy(ctx->path + path_len, utf8_name, utf8_name_len + 1);
414         path_len += utf8_name_len;
415         ret = build_dentry_tree_ntfs_recursive(&child, ni, ctx->path, path_len,
416                                                ctx->lookup_table, ctx->sd_set,
417                                                ctx->config, ctx->ntfs_vol_p);
418
419         if (child) {
420                 DEBUG("Linking dentry `%s' with parent `%s'",
421                       child->file_name_utf8, ctx->parent->file_name_utf8);
422                 link_dentry(child, ctx->parent);
423         }
424 out_close_ni:
425         ntfs_inode_close(ni);
426 out_free_utf8_name:
427         FREE(utf8_name);
428 out:
429         return ret;
430 }
431
432 /* Recursively build a WIM dentry tree corresponding to a NTFS volume.
433  * At the same time, update the WIM lookup table with lookup table entries for
434  * the NTFS streams, and build an array of security descriptors.
435  */
436 static int build_dentry_tree_ntfs_recursive(struct dentry **root_p,
437                                             ntfs_inode *ni,
438                                             char path[], size_t path_len,
439                                             struct lookup_table *lookup_table,
440                                             struct sd_set *sd_set,
441                                             const struct capture_config *config,
442                                             ntfs_volume **ntfs_vol_p)
443 {
444         u32 attributes;
445         int mrec_flags;
446         u32 sd_size;
447         int ret = 0;
448         struct dentry *root;
449
450         if (exclude_path(path, config, false)) {
451                 DEBUG("Excluding `%s' from capture", path);
452                 return 0;
453         }
454
455         DEBUG("Starting recursive capture at path = `%s'", path);
456         mrec_flags = ni->mrec->flags;
457         attributes = ntfs_inode_get_attributes(ni);
458
459         root = new_dentry(path_basename(path));
460         if (!root)
461                 return WIMLIB_ERR_NOMEM;
462
463         *root_p = root;
464         root->creation_time    = le64_to_cpu(ni->creation_time);
465         root->last_write_time  = le64_to_cpu(ni->last_data_change_time);
466         root->last_access_time = le64_to_cpu(ni->last_access_time);
467         root->security_id      = le32_to_cpu(ni->security_id);
468         root->attributes       = le32_to_cpu(attributes);
469         root->link_group_id    = ni->mft_no;
470         root->resolved         = true;
471
472         if (attributes & FILE_ATTR_REPARSE_POINT) {
473                 DEBUG("Reparse point `%s'", path);
474                 /* Junction point, symbolic link, or other reparse point */
475                 ret = capture_ntfs_streams(root, ni, path, path_len,
476                                            lookup_table, ntfs_vol_p,
477                                            AT_REPARSE_POINT);
478         } else if (mrec_flags & MFT_RECORD_IS_DIRECTORY) {
479                 DEBUG("Directory `%s'", path);
480
481                 /* Normal directory */
482                 s64 pos = 0;
483                 struct readdir_ctx ctx = {
484                         .parent       = root,
485                         .dir_ni       = ni,
486                         .path         = path,
487                         .path_len     = path_len,
488                         .lookup_table = lookup_table,
489                         .sd_set       = sd_set,
490                         .config       = config,
491                         .ntfs_vol_p   = ntfs_vol_p,
492                 };
493                 ret = ntfs_readdir(ni, &pos, &ctx, wim_ntfs_capture_filldir);
494                 if (ret != 0) {
495                         ERROR_WITH_ERRNO("ntfs_readdir()");
496                         ret = WIMLIB_ERR_NTFS_3G;
497                 }
498         } else {
499                 DEBUG("Normal file `%s'", path);
500                 /* Normal file */
501                 ret = capture_ntfs_streams(root, ni, path, path_len,
502                                            lookup_table, ntfs_vol_p,
503                                            AT_DATA);
504         }
505         if (ret != 0)
506                 return ret;
507
508         ret = ntfs_inode_get_security(ni,
509                                       OWNER_SECURITY_INFORMATION |
510                                       GROUP_SECURITY_INFORMATION |
511                                       DACL_SECURITY_INFORMATION  |
512                                       SACL_SECURITY_INFORMATION,
513                                       NULL, 0, &sd_size);
514         u8 sd[sd_size];
515         ret = ntfs_inode_get_security(ni,
516                                       OWNER_SECURITY_INFORMATION |
517                                       GROUP_SECURITY_INFORMATION |
518                                       DACL_SECURITY_INFORMATION  |
519                                       SACL_SECURITY_INFORMATION,
520                                       sd, sd_size, &sd_size);
521         if (ret == 0) {
522                 ERROR_WITH_ERRNO("Failed to get security information from "
523                                  "`%s'", path);
524                 ret = WIMLIB_ERR_NTFS_3G;
525         } else {
526                 if (ret > 0) {
527                         /*print_security_descriptor(sd, sd_size);*/
528                         root->security_id = sd_set_add_sd(sd_set, sd, sd_size);
529                         DEBUG("Added security ID = %u for `%s'",
530                               root->security_id, path);
531                 } else { 
532                         root->security_id = -1;
533                         DEBUG("No security ID for `%s'", path);
534                 }
535                 ret = 0;
536         }
537         return ret;
538 }
539
540 static int build_dentry_tree_ntfs(struct dentry **root_p,
541                                   const char *device,
542                                   struct lookup_table *lookup_table,
543                                   struct wim_security_data *sd,
544                                   const struct capture_config *config,
545                                   int flags,
546                                   void *extra_arg)
547 {
548         ntfs_volume *vol;
549         ntfs_inode *root_ni;
550         int ret = 0;
551         struct sd_set sd_set;
552         sd_set.sd = sd;
553         sd_set.root = NULL;
554         ntfs_volume **ntfs_vol_p = extra_arg;
555
556         DEBUG("Mounting NTFS volume `%s' read-only", device);
557         
558         vol = ntfs_mount(device, MS_RDONLY);
559         if (!vol) {
560                 ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s' read-only",
561                                  device);
562                 return WIMLIB_ERR_NTFS_3G;
563         }
564
565         NVolClearShowSysFiles(vol);
566
567         DEBUG("Opening root NTFS dentry");
568         root_ni = ntfs_inode_open(vol, FILE_root);
569         if (!root_ni) {
570                 ERROR_WITH_ERRNO("Failed to open root inode of NTFS volume "
571                                  "`%s'", device);
572                 ret = WIMLIB_ERR_NTFS_3G;
573                 goto out;
574         }
575         char *path = MALLOC(32769);
576         if (!path) {
577                 ERROR("Could not allocate memory for NTFS pathname");
578                 goto out_cleanup;
579         }
580         path[0] = '/';
581         path[1] = '\0';
582         ret = build_dentry_tree_ntfs_recursive(root_p, root_ni, path, 1,
583                                                lookup_table, &sd_set,
584                                                config, ntfs_vol_p);
585 out_cleanup:
586         FREE(path);
587         ntfs_inode_close(root_ni);
588         destroy_sd_set(&sd_set);
589
590 out:
591         if (ret) {
592                 if (ntfs_umount(vol, FALSE) != 0) {
593                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'",
594                                          device);
595                         if (ret == 0)
596                                 ret = WIMLIB_ERR_NTFS_3G;
597                 }
598         } else {
599                 *ntfs_vol_p = vol;
600         }
601         return ret;
602 }
603
604
605
606 WIMLIBAPI int wimlib_add_image_from_ntfs_volume(WIMStruct *w,
607                                                 const char *device,
608                                                 const char *name,
609                                                 const char *config_str,
610                                                 size_t config_len,
611                                                 int flags)
612 {
613         if (flags & (WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)) {
614                 ERROR("Cannot dereference files when capturing directly from NTFS");
615                 return WIMLIB_ERR_INVALID_PARAM;
616         }
617         return do_add_image(w, device, name, config_str, config_len, flags,
618                             build_dentry_tree_ntfs, &w->ntfs_vol);
619 }
620
621 #else /* WITH_NTFS_3G */
622 WIMLIBAPI int wimlib_add_image_from_ntfs_volume(WIMStruct *w,
623                                                 const char *device,
624                                                 const char *name,
625                                                 const char *description,
626                                                 const char *flags_element,
627                                                 int flags,
628                                                 const char *config_str,
629                                                 size_t config_len)
630 {
631         ERROR("wimlib was compiled without support for NTFS-3g, so");
632         ERROR("we cannot capture a WIM image directly from a NTFS volume");
633         return WIMLIB_ERR_UNSUPPORTED;
634 }
635 #endif /* WITH_NTFS_3G */