]> wimlib.net Git - wimlib/blob - src/ntfs-capture.c
Misc fixes
[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 /* Frees a security descriptor index tree. */
67 static void free_sd_set(struct sd_node *root)
68 {
69         if (root) {
70                 free_sd_set(root->left);
71                 free_sd_set(root->right);
72                 FREE(root);
73         }
74 }
75
76 /* Inserts a a new node into the security descriptor index tree. */
77 static void insert_sd_node(struct sd_node *new, struct sd_node *root)
78 {
79         int cmp = hashes_cmp(new->hash, root->hash);
80         if (cmp < 0) {
81                 if (root->left)
82                         insert_sd_node(new, root->left);
83                 else 
84                         root->left = new;
85         } else if (cmp > 0) {
86                 if (root->right)
87                         insert_sd_node(new, root->right);
88                 else 
89                         root->right = new;
90         } else {
91                 wimlib_assert(0);
92         }
93 }
94
95 /* Returns the security ID of the security data having a SHA1 message digest of
96  * @hash in the security descriptor index tree rooted at @root. 
97  *
98  * If not found, return -1. */
99 static int lookup_sd(const u8 hash[SHA1_HASH_SIZE], struct sd_node *root)
100 {
101         int cmp;
102         if (!root)
103                 return -1;
104         cmp = hashes_cmp(hash, root->hash);
105         if (cmp < 0)
106                 return lookup_sd(hash, root->left);
107         else if (cmp > 0)
108                 return lookup_sd(hash, root->right);
109         else
110                 return root->security_id;
111 }
112
113 /*
114  * Adds a security descriptor to the indexed security descriptor set as well as
115  * the corresponding `struct wim_security_data', and returns the new security
116  * ID; or, if there is an existing security descriptor that is the same, return
117  * the security ID for it.  If a new security descriptor cannot be allocated,
118  * return -1.
119  */
120 static int sd_set_add_sd(struct sd_set *sd_set, const u8 *descriptor,
121                          size_t size)
122 {
123         u8 hash[SHA1_HASH_SIZE];
124         int security_id;
125         struct sd_node *new;
126         u8 **descriptors;
127         u64 *sizes;
128         u8 *descr_copy;
129         struct wim_security_data *sd;
130
131         sha1_buffer(descriptor, size, hash);
132         security_id = lookup_sd(hash, sd_set->root);
133         if (security_id >= 0)
134                 return security_id;
135
136         new = MALLOC(sizeof(*new));
137         if (!new)
138                 goto out;
139         descr_copy = MALLOC(size);
140         if (!descr_copy)
141                 goto out_free_node;
142
143         sd = sd_set->sd;
144
145         memcpy(descr_copy, descriptor, size);
146         new->security_id = sd->num_entries;
147         new->left = NULL;
148         new->right = NULL;
149         copy_hash(new->hash, hash);
150
151
152         descriptors = REALLOC(sd->descriptors,
153                               (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
154         if (!descriptors)
155                 goto out_free_descr;
156         sd->descriptors = descriptors;
157         sizes = REALLOC(sd->sizes,
158                         (sd->num_entries + 1) * sizeof(sd->sizes[0]));
159         if (!sizes)
160                 goto out_free_descr;
161         sd->sizes = sizes;
162         sd->descriptors[sd->num_entries] = descr_copy;
163         sd->sizes[sd->num_entries] = size;
164         sd->num_entries++;
165         sd->total_length += size + sizeof(sd->sizes[0]);
166
167         if (sd_set->root)
168                 insert_sd_node(sd_set->root, new);
169         else
170                 sd_set->root = new;
171         return new->security_id;
172 out_free_descr:
173         FREE(descr_copy);
174 out_free_node:
175         FREE(new);
176 out:
177         return -1;
178 }
179
180 static inline ntfschar *attr_record_name(ATTR_RECORD *ar)
181 {
182         return (ntfschar*)((u8*)ar + le16_to_cpu(ar->name_offset));
183 }
184
185 /* Calculates the SHA1 message digest of a NTFS attribute. 
186  *
187  * @ni:  The NTFS inode containing the attribute.
188  * @ar:  The ATTR_RECORD describing the attribute.
189  * @md:  If successful, the returned SHA1 message digest.
190  *
191  * Return 0 on success or nonzero on error.
192  */
193 static int ntfs_attr_sha1sum(ntfs_inode *ni, ATTR_RECORD *ar,
194                              u8 md[SHA1_HASH_SIZE])
195 {
196         s64 pos = 0;
197         s64 bytes_remaining;
198         char buf[4096];
199         ntfs_attr *na;
200         SHA_CTX ctx;
201
202         na = ntfs_attr_open(ni, ar->type, attr_record_name(ar),
203                             ar->name_length);
204         if (!na) {
205                 ERROR_WITH_ERRNO("Failed to open NTFS attribute");
206                 return WIMLIB_ERR_NTFS_3G;
207         }
208
209         bytes_remaining = na->data_size;
210         sha1_init(&ctx);
211
212         while (bytes_remaining) {
213                 s64 to_read = min(bytes_remaining, sizeof(buf));
214                 if (ntfs_attr_pread(na, pos, to_read, buf) != to_read) {
215                         ERROR_WITH_ERRNO("Error reading NTFS attribute");
216                         return WIMLIB_ERR_NTFS_3G;
217                 }
218                 sha1_update(&ctx, buf, to_read);
219                 pos += to_read;
220                 bytes_remaining -= to_read;
221         }
222         sha1_final(md, &ctx);
223         ntfs_attr_close(na);
224         return 0;
225 }
226
227 /* Load the streams from a WIM file or reparse point in the NTFS volume into the
228  * WIM lookup table */
229 static int capture_ntfs_streams(struct dentry *dentry, ntfs_inode *ni,
230                                 char path[], size_t path_len,
231                                 struct lookup_table *lookup_table,
232                                 ntfs_volume **ntfs_vol_p,
233                                 ATTR_TYPES type)
234 {
235
236         ntfs_attr_search_ctx *actx;
237         u8 attr_hash[SHA1_HASH_SIZE];
238         struct ntfs_location *ntfs_loc;
239         struct lookup_table_entry *lte;
240         int ret = 0;
241
242         /* Get context to search the streams of the NTFS file. */
243         actx = ntfs_attr_get_search_ctx(ni, NULL);
244         if (!actx) {
245                 ERROR_WITH_ERRNO("Cannot get attribute search "
246                                  "context");
247                 return WIMLIB_ERR_NTFS_3G;
248         }
249
250         /* Capture each data stream or reparse data stream. */
251         while (!ntfs_attr_lookup(type, NULL, 0,
252                                  CASE_SENSITIVE, 0, NULL, 0, actx))
253         {
254                 char *stream_name_utf8;
255                 size_t stream_name_utf16_len;
256
257                 /* Checksum the stream. */
258                 ret = ntfs_attr_sha1sum(ni, actx->attr, attr_hash);
259                 if (ret != 0)
260                         goto out_put_actx;
261
262                 /* Make a lookup table entry for the stream, or use an existing
263                  * one if there's already an identical stream. */
264                 lte = __lookup_resource(lookup_table, attr_hash);
265                 ret = WIMLIB_ERR_NOMEM;
266                 if (lte) {
267                         lte->refcnt++;
268                 } else {
269                         struct ntfs_location *ntfs_loc;
270
271                         ntfs_loc = CALLOC(1, sizeof(*ntfs_loc));
272                         if (!ntfs_loc)
273                                 goto out_put_actx;
274                         ntfs_loc->ntfs_vol_p = ntfs_vol_p;
275                         ntfs_loc->path_utf8 = MALLOC(path_len + 1);
276                         if (!ntfs_loc->path_utf8)
277                                 goto out_free_ntfs_loc;
278                         memcpy(ntfs_loc->path_utf8, path, path_len + 1);
279                         ntfs_loc->stream_name_utf16 = MALLOC(actx->attr->name_length * 2);
280                         if (!ntfs_loc->stream_name_utf16)
281                                 goto out_free_ntfs_loc;
282                         memcpy(ntfs_loc->stream_name_utf16,
283                                attr_record_name(actx->attr),
284                                actx->attr->name_length * 2);
285
286                         ntfs_loc->stream_name_utf16_num_chars = actx->attr->name_length;
287                         ntfs_loc->is_reparse_point = (type == AT_REPARSE_POINT);
288                         lte = new_lookup_table_entry();
289                         if (!lte)
290                                 goto out_free_ntfs_loc;
291                         lte->ntfs_loc = ntfs_loc;
292                         lte->resource_location = RESOURCE_IN_NTFS_VOLUME;
293                         lte->resource_entry.original_size = actx->attr->data_size;
294                         lte->resource_entry.size = actx->attr->data_size;
295                         copy_hash(lte->hash, attr_hash);
296                         lookup_table_insert(lookup_table, lte);
297                 }
298                 if (actx->attr->name_length == 0) {
299                         if (dentry->lte) {
300                                 ERROR("Found two un-named data streams for "
301                                       "`%s'", path);
302                                 ret = WIMLIB_ERR_NTFS_3G;
303                                 goto out_free_lte;
304                         }
305                         dentry->lte = lte;
306                 } else {
307                         struct ads_entry *new_ads_entry;
308                         stream_name_utf8 = utf16_to_utf8((const u8*)attr_record_name(actx->attr),
309                                                          actx->attr->name_length,
310                                                          &stream_name_utf16_len);
311                         if (!stream_name_utf8)
312                                 goto out_free_lte;
313                         new_ads_entry = dentry_add_ads(dentry, stream_name_utf8);
314                         FREE(stream_name_utf8);
315                         if (!new_ads_entry)
316                                 goto out_free_lte;
317                                 
318                         new_ads_entry->lte = lte;
319                 }
320         }
321         ret = 0;
322         goto out_put_actx;
323 out_free_lte:
324         free_lookup_table_entry(lte);
325 out_free_ntfs_loc:
326         if (ntfs_loc) {
327                 FREE(ntfs_loc->path_utf8);
328                 FREE(ntfs_loc->stream_name_utf16);
329                 FREE(ntfs_loc);
330         }
331 out_put_actx:
332         ntfs_attr_put_search_ctx(actx);
333         return ret;
334 }
335
336 struct readdir_ctx {
337         struct dentry       *dentry;
338         ntfs_inode          *dir_ni;
339         char                *path;
340         size_t               path_len;
341         struct lookup_table *lookup_table;
342         struct sd_set       *sd_set;
343         ntfs_volume        **ntfs_vol_p;
344 };
345
346 static int __build_dentry_tree_ntfs(struct dentry *dentry, ntfs_inode *ni,
347                                     char path[], size_t path_len,
348                                     struct lookup_table *lookup_table,
349                                     struct sd_set *sd_set,
350                                     ntfs_volume **ntfs_vol_p);
351
352
353 static int filldir(void *dirent, const ntfschar *name,
354                    const int name_len, const int name_type, const s64 pos,
355                    const MFT_REF mref, const unsigned dt_type)
356 {
357         struct readdir_ctx *ctx;
358         size_t utf8_name_len;
359         char *utf8_name;
360         struct dentry *child;
361         int ret;
362         size_t path_len;
363
364         ret = -1;
365
366         utf8_name = utf16_to_utf8((const u8*)name, name_len * 2,
367                                   &utf8_name_len);
368         if (!utf8_name)
369                 goto out;
370
371         ctx = dirent;
372
373         ntfs_inode *ni = ntfs_inode_open(ctx->dir_ni->vol, mref);
374         if (!ni) {
375                 ERROR_WITH_ERRNO("Failed to open NTFS inode");
376                 ret = 1;
377         }
378         child = new_dentry(utf8_name);
379         if (!child)
380                 goto out_close_ni;
381
382         memcpy(ctx->path + ctx->path_len, utf8_name, utf8_name_len + 1);
383         path_len = ctx->path_len + utf8_name_len;
384         ret = __build_dentry_tree_ntfs(child, ni, ctx->path, path_len,
385                                        ctx->lookup_table, ctx->sd_set,
386                                        ctx->ntfs_vol_p);
387         link_dentry(child, ctx->dentry);
388 out_close_ni:
389         ntfs_inode_close(ni);
390 out_free_utf8_name:
391         FREE(utf8_name);
392 out:
393         return ret;
394 }
395
396 /* Recursively build a WIM dentry tree corresponding to a NTFS volume.
397  * At the same time, update the WIM lookup table with lookup table entries for
398  * the NTFS streams, and build an array of security descriptors.
399  */
400 static int __build_dentry_tree_ntfs(struct dentry *dentry, ntfs_inode *ni,
401                                     char path[], size_t path_len,
402                                     struct lookup_table *lookup_table,
403                                     struct sd_set *sd_set,
404                                     ntfs_volume **ntfs_vol_p)
405 {
406         u32 attributes = ntfs_inode_get_attributes(ni);
407         int mrec_flags = ni->mrec->flags;
408         u32 sd_size;
409         int ret = 0;
410
411         dentry->creation_time    = le64_to_cpu(ni->creation_time);
412         dentry->last_write_time  = le64_to_cpu(ni->last_data_change_time);
413         dentry->last_access_time = le64_to_cpu(ni->last_access_time);
414         dentry->security_id      = le32_to_cpu(ni->security_id);
415         dentry->attributes       = le32_to_cpu(attributes);
416         dentry->hard_link        = ni->mft_no;
417         dentry->resolved = true;
418
419         if (attributes & FILE_ATTR_REPARSE_POINT) {
420                 /* Junction point, symbolic link, or other reparse point */
421                 ret = capture_ntfs_streams(dentry, ni, path, path_len,
422                                            lookup_table, ntfs_vol_p,
423                                            AT_REPARSE_POINT);
424         } else if (mrec_flags & MFT_RECORD_IS_DIRECTORY) {
425                 /* Normal directory */
426                 s64 pos = 0;
427                 struct readdir_ctx ctx = {
428                         .dentry       = dentry,
429                         .dir_ni       = ni,
430                         .path         = path,
431                         .path_len     = path_len,
432                         .lookup_table = lookup_table,
433                         .sd_set       = sd_set,
434                         .ntfs_vol_p   = ntfs_vol_p,
435                 };
436                 ret = ntfs_readdir(ni, &pos, &ctx, filldir);
437                 if (ret != 0)
438                         ret = WIMLIB_ERR_NTFS_3G;
439         } else {
440                 /* Normal file */
441                 ret = capture_ntfs_streams(dentry, ni, path, path_len,
442                                            lookup_table, ntfs_vol_p,
443                                            AT_DATA);
444         }
445         if (ret != 0)
446                 return ret;
447         ret = ntfs_inode_get_security(ni,
448                                       OWNER_SECURITY_INFORMATION |
449                                       GROUP_SECURITY_INFORMATION |
450                                       DACL_SECURITY_INFORMATION  |
451                                       SACL_SECURITY_INFORMATION,
452                                       NULL, 0, &sd_size);
453         u8 sd[sd_size];
454         ret = ntfs_inode_get_security(ni,
455                                       OWNER_SECURITY_INFORMATION |
456                                       GROUP_SECURITY_INFORMATION |
457                                       DACL_SECURITY_INFORMATION  |
458                                       SACL_SECURITY_INFORMATION,
459                                       sd, sd_size, &sd_size);
460         dentry->security_id = sd_set_add_sd(sd_set, sd, sd_size);
461         if (dentry->security_id == -1) {
462                 ERROR("Could not allocate security ID");
463                 ret = WIMLIB_ERR_NOMEM;
464         }
465         return ret;
466 }
467
468 static int build_dentry_tree_ntfs(struct dentry *root_dentry,
469                                   const char *device,
470                                   struct lookup_table *lookup_table,
471                                   struct wim_security_data *sd,
472                                   int flags,
473                                   void *extra_arg)
474 {
475         ntfs_volume *vol;
476         ntfs_inode *root_ni;
477         int ret = 0;
478         struct sd_set tree;
479         tree.sd = sd;
480         tree.root = NULL;
481         ntfs_volume **ntfs_vol_p = extra_arg;
482         
483         vol = ntfs_mount(device, MS_RDONLY);
484         if (!vol) {
485                 ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s' read-only",
486                                  device);
487                 return WIMLIB_ERR_NTFS_3G;
488         }
489         root_ni = ntfs_inode_open(vol, FILE_root);
490         if (!root_ni) {
491                 ERROR_WITH_ERRNO("Failed to open root inode of NTFS volume "
492                                  "`%s'", device);
493                 ret = WIMLIB_ERR_NTFS_3G;
494                 goto out;
495         }
496         char path[4096];
497         path[0] = '/';
498         path[1] = '\0';
499         ret = __build_dentry_tree_ntfs(root_dentry, root_ni, path, 1,
500                                        lookup_table, &tree, ntfs_vol_p);
501         ntfs_inode_close(root_ni);
502
503 out:
504         if (ntfs_umount(vol, FALSE) != 0) {
505                 ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'", device);
506                 if (ret == 0)
507                         ret = WIMLIB_ERR_NTFS_3G;
508         }
509         return ret;
510 }
511
512 WIMLIBAPI int wimlib_add_image_from_ntfs_volume(WIMStruct *w,
513                                                 const char *device,
514                                                 const char *name,
515                                                 const char *description,
516                                                 const char *flags_element,
517                                                 int flags)
518 {
519         if (flags & (WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)) {
520                 ERROR("Cannot dereference files when capturing directly from NTFS");
521                 return WIMLIB_ERR_INVALID_PARAM;
522         }
523         return do_add_image(w, device, name, description, flags_element, flags,
524                             build_dentry_tree_ntfs,
525                             &w->ntfs_vol);
526 }
527
528 #else /* WITH_NTFS_3G */
529 WIMLIBAPI int wimlib_add_image_from_ntfs_volume(WIMStruct *w,
530                                                 const char *device,
531                                                 const char *name,
532                                                 const char *description,
533                                                 const char *flags_element,
534                                                 int flags)
535 {
536         ERROR("wimlib was compiled without support for NTFS-3g, so");
537         ERROR("we cannot capture a WIM image directly from a NTFS volume");
538         return WIMLIB_ERR_UNSUPPORTED;
539 }
540 #endif /* WITH_NTFS_3G */