06c88b26ad0dfb07d3fe62d09582ed4136696efb
[platform/upstream/btrfs-progs.git] / cmds-restore.c
1 /*
2  * Copyright (C) 2011 Red Hat.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19
20 #include "kerncompat.h"
21
22 #include <ctype.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <lzo/lzoconf.h>
30 #include <lzo/lzo1x.h>
31 #include <zlib.h>
32 #include <regex.h>
33 #include <getopt.h>
34 #include <sys/types.h>
35 #include <sys/xattr.h>
36
37 #include "ctree.h"
38 #include "disk-io.h"
39 #include "print-tree.h"
40 #include "transaction.h"
41 #include "list.h"
42 #include "volumes.h"
43 #include "utils.h"
44 #include "commands.h"
45 #include "help.h"
46
47 static char fs_name[PATH_MAX];
48 static char path_name[PATH_MAX];
49 static char symlink_target[PATH_MAX];
50 static int get_snaps = 0;
51 static int verbose = 0;
52 static int restore_metadata = 0;
53 static int restore_symlinks = 0;
54 static int ignore_errors = 0;
55 static int overwrite = 0;
56 static int get_xattrs = 0;
57 static int dry_run = 0;
58
59 #define LZO_LEN 4
60 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
61
62 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
63                            u64 decompress_len)
64 {
65         z_stream strm;
66         int ret;
67
68         memset(&strm, 0, sizeof(strm));
69         ret = inflateInit(&strm);
70         if (ret != Z_OK) {
71                 error("zlib init returned %d", ret);
72                 return -1;
73         }
74
75         strm.avail_in = compress_len;
76         strm.next_in = (unsigned char *)inbuf;
77         strm.avail_out = decompress_len;
78         strm.next_out = (unsigned char *)outbuf;
79         ret = inflate(&strm, Z_NO_FLUSH);
80         if (ret != Z_STREAM_END) {
81                 (void)inflateEnd(&strm);
82                 error("zlib inflate failed: %d", ret);
83                 return -1;
84         }
85
86         (void)inflateEnd(&strm);
87         return 0;
88 }
89 static inline size_t read_compress_length(unsigned char *buf)
90 {
91         __le32 dlen;
92         memcpy(&dlen, buf, LZO_LEN);
93         return le32_to_cpu(dlen);
94 }
95
96 static int decompress_lzo(struct btrfs_root *root, unsigned char *inbuf,
97                         char *outbuf, u64 compress_len, u64 *decompress_len)
98 {
99         size_t new_len;
100         size_t in_len;
101         size_t out_len = 0;
102         size_t tot_len;
103         size_t tot_in;
104         int ret;
105
106         ret = lzo_init();
107         if (ret != LZO_E_OK) {
108                 error("lzo init returned %d", ret);
109                 return -1;
110         }
111
112         tot_len = read_compress_length(inbuf);
113         inbuf += LZO_LEN;
114         tot_in = LZO_LEN;
115
116         while (tot_in < tot_len) {
117                 size_t mod_page;
118                 size_t rem_page;
119                 in_len = read_compress_length(inbuf);
120
121                 if ((tot_in + LZO_LEN + in_len) > tot_len) {
122                         error("bad compress length %lu",
123                                 (unsigned long)in_len);
124                         return -1;
125                 }
126
127                 inbuf += LZO_LEN;
128                 tot_in += LZO_LEN;
129                 new_len = lzo1x_worst_compress(root->fs_info->sectorsize);
130                 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
131                                             (unsigned char *)outbuf,
132                                             (void *)&new_len, NULL);
133                 if (ret != LZO_E_OK) {
134                         error("lzo decompress failed: %d", ret);
135                         return -1;
136                 }
137                 out_len += new_len;
138                 outbuf += new_len;
139                 inbuf += in_len;
140                 tot_in += in_len;
141
142                 /*
143                  * If the 4 byte header does not fit to the rest of the page we
144                  * have to move to the next one, unless we read some garbage
145                  */
146                 mod_page = tot_in % root->fs_info->sectorsize;
147                 rem_page = root->fs_info->sectorsize - mod_page;
148                 if (rem_page < LZO_LEN) {
149                         inbuf += rem_page;
150                         tot_in += rem_page;
151                 }
152         }
153
154         *decompress_len = out_len;
155
156         return 0;
157 }
158
159 static int decompress(struct btrfs_root *root, char *inbuf, char *outbuf,
160                         u64 compress_len, u64 *decompress_len, int compress)
161 {
162         switch (compress) {
163         case BTRFS_COMPRESS_ZLIB:
164                 return decompress_zlib(inbuf, outbuf, compress_len,
165                                        *decompress_len);
166         case BTRFS_COMPRESS_LZO:
167                 return decompress_lzo(root, (unsigned char *)inbuf, outbuf,
168                                         compress_len, decompress_len);
169         default:
170                 break;
171         }
172
173         error("invalid compression type: %d", compress);
174         return -1;
175 }
176
177 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
178 {
179         int slot;
180         int level = 1;
181         int offset = 1;
182         struct extent_buffer *c;
183         struct extent_buffer *next = NULL;
184         struct btrfs_fs_info *fs_info = root->fs_info;
185
186 again:
187         for (; level < BTRFS_MAX_LEVEL; level++) {
188                 if (path->nodes[level])
189                         break;
190         }
191
192         if (level >= BTRFS_MAX_LEVEL)
193                 return 1;
194
195         slot = path->slots[level] + 1;
196
197         while(level < BTRFS_MAX_LEVEL) {
198                 if (!path->nodes[level])
199                         return 1;
200
201                 slot = path->slots[level] + offset;
202                 c = path->nodes[level];
203                 if (slot >= btrfs_header_nritems(c)) {
204                         level++;
205                         if (level == BTRFS_MAX_LEVEL)
206                                 return 1;
207                         offset = 1;
208                         continue;
209                 }
210
211                 if (path->reada)
212                         reada_for_search(root, path, level, slot, 0);
213
214                 next = read_node_slot(fs_info, c, slot);
215                 if (extent_buffer_uptodate(next))
216                         break;
217                 offset++;
218         }
219         path->slots[level] = slot;
220         while(1) {
221                 level--;
222                 c = path->nodes[level];
223                 free_extent_buffer(c);
224                 path->nodes[level] = next;
225                 path->slots[level] = 0;
226                 if (!level)
227                         break;
228                 if (path->reada)
229                         reada_for_search(root, path, level, 0, 0);
230                 next = read_node_slot(fs_info, next, 0);
231                 if (!extent_buffer_uptodate(next))
232                         goto again;
233         }
234         return 0;
235 }
236
237 static int copy_one_inline(struct btrfs_root *root, int fd,
238                                 struct btrfs_path *path, u64 pos)
239 {
240         struct extent_buffer *leaf = path->nodes[0];
241         struct btrfs_file_extent_item *fi;
242         char buf[4096];
243         char *outbuf;
244         u64 ram_size;
245         ssize_t done;
246         unsigned long ptr;
247         int ret;
248         int len;
249         int inline_item_len;
250         int compress;
251
252         fi = btrfs_item_ptr(leaf, path->slots[0],
253                             struct btrfs_file_extent_item);
254         ptr = btrfs_file_extent_inline_start(fi);
255         len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
256         inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
257         read_extent_buffer(leaf, buf, ptr, inline_item_len);
258
259         compress = btrfs_file_extent_compression(leaf, fi);
260         if (compress == BTRFS_COMPRESS_NONE) {
261                 done = pwrite(fd, buf, len, pos);
262                 if (done < len) {
263                         fprintf(stderr, "Short inline write, wanted %d, did "
264                                 "%zd: %d\n", len, done, errno);
265                         return -1;
266                 }
267                 return 0;
268         }
269
270         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
271         outbuf = calloc(1, ram_size);
272         if (!outbuf) {
273                 error("not enough memory");
274                 return -ENOMEM;
275         }
276
277         ret = decompress(root, buf, outbuf, len, &ram_size, compress);
278         if (ret) {
279                 free(outbuf);
280                 return ret;
281         }
282
283         done = pwrite(fd, outbuf, ram_size, pos);
284         free(outbuf);
285         if (done < ram_size) {
286                 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
287                         "did %zd: %d\n", ram_size, done, errno);
288                 return -1;
289         }
290
291         return 0;
292 }
293
294 static int copy_one_extent(struct btrfs_root *root, int fd,
295                            struct extent_buffer *leaf,
296                            struct btrfs_file_extent_item *fi, u64 pos)
297 {
298         struct btrfs_multi_bio *multi = NULL;
299         struct btrfs_device *device;
300         char *inbuf, *outbuf = NULL;
301         ssize_t done, total = 0;
302         u64 bytenr;
303         u64 ram_size;
304         u64 disk_size;
305         u64 num_bytes;
306         u64 length;
307         u64 size_left;
308         u64 dev_bytenr;
309         u64 offset;
310         u64 count = 0;
311         int compress;
312         int ret;
313         int dev_fd;
314         int mirror_num = 1;
315         int num_copies;
316
317         compress = btrfs_file_extent_compression(leaf, fi);
318         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
319         disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
320         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
321         offset = btrfs_file_extent_offset(leaf, fi);
322         num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
323         size_left = disk_size;
324         if (compress == BTRFS_COMPRESS_NONE)
325                 bytenr += offset;
326
327         if (verbose && offset)
328                 printf("offset is %Lu\n", offset);
329         /* we found a hole */
330         if (disk_size == 0)
331                 return 0;
332
333         inbuf = malloc(size_left);
334         if (!inbuf) {
335                 error("not enough memory");
336                 return -ENOMEM;
337         }
338
339         if (compress != BTRFS_COMPRESS_NONE) {
340                 outbuf = calloc(1, ram_size);
341                 if (!outbuf) {
342                         error("not enough memory");
343                         free(inbuf);
344                         return -ENOMEM;
345                 }
346         }
347 again:
348         length = size_left;
349         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
350                               bytenr, &length, &multi, mirror_num, NULL);
351         if (ret) {
352                 error("cannot map block logical %llu length %llu: %d",
353                                 (unsigned long long)bytenr,
354                                 (unsigned long long)length, ret);
355                 goto out;
356         }
357         device = multi->stripes[0].dev;
358         dev_fd = device->fd;
359         device->total_ios++;
360         dev_bytenr = multi->stripes[0].physical;
361         free(multi);
362
363         if (size_left < length)
364                 length = size_left;
365
366         done = pread(dev_fd, inbuf+count, length, dev_bytenr);
367         /* Need both checks, or we miss negative values due to u64 conversion */
368         if (done < 0 || done < length) {
369                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
370                                               bytenr, length);
371                 mirror_num++;
372                 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
373                 if (mirror_num > num_copies) {
374                         ret = -1;
375                         error("exhausted mirrors trying to read (%d > %d)",
376                                         mirror_num, num_copies);
377                         goto out;
378                 }
379                 fprintf(stderr, "Trying another mirror\n");
380                 goto again;
381         }
382
383         mirror_num = 1;
384         size_left -= length;
385         count += length;
386         bytenr += length;
387         if (size_left)
388                 goto again;
389
390         if (compress == BTRFS_COMPRESS_NONE) {
391                 while (total < num_bytes) {
392                         done = pwrite(fd, inbuf+total, num_bytes-total,
393                                       pos+total);
394                         if (done < 0) {
395                                 ret = -1;
396                                 error("cannot write data: %d %s", errno, strerror(errno));
397                                 goto out;
398                         }
399                         total += done;
400                 }
401                 ret = 0;
402                 goto out;
403         }
404
405         ret = decompress(root, inbuf, outbuf, disk_size, &ram_size, compress);
406         if (ret) {
407                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
408                                               bytenr, length);
409                 mirror_num++;
410                 if (mirror_num >= num_copies) {
411                         ret = -1;
412                         goto out;
413                 }
414                 fprintf(stderr, "Trying another mirror\n");
415                 goto again;
416         }
417
418         while (total < num_bytes) {
419                 done = pwrite(fd, outbuf + offset + total,
420                               num_bytes - total,
421                               pos + total);
422                 if (done < 0) {
423                         ret = -1;
424                         goto out;
425                 }
426                 total += done;
427         }
428 out:
429         free(inbuf);
430         free(outbuf);
431         return ret;
432 }
433
434 enum loop_response {
435         LOOP_STOP,
436         LOOP_CONTINUE,
437         LOOP_DONTASK
438 };
439
440 static enum loop_response ask_to_continue(const char *file)
441 {
442         char buf[2];
443         char *ret;
444
445         printf("We seem to be looping a lot on %s, do you want to keep going "
446                "on ? (y/N/a): ", file);
447 again:
448         ret = fgets(buf, 2, stdin);
449         if (*ret == '\n' || tolower(*ret) == 'n')
450                 return LOOP_STOP;
451         if (tolower(*ret) == 'a')
452                 return LOOP_DONTASK;
453         if (tolower(*ret) != 'y') {
454                 printf("Please enter one of 'y', 'n', or 'a': ");
455                 goto again;
456         }
457
458         return LOOP_CONTINUE;
459 }
460
461
462 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
463                            int fd, const char *file_name)
464 {
465         struct btrfs_key key;
466         struct btrfs_path path;
467         struct extent_buffer *leaf;
468         struct btrfs_dir_item *di;
469         u32 name_len = 0;
470         u32 data_len = 0;
471         u32 len = 0;
472         u32 cur, total_len;
473         char *name = NULL;
474         char *data = NULL;
475         int ret = 0;
476
477         btrfs_init_path(&path);
478         key.objectid = inode;
479         key.type = BTRFS_XATTR_ITEM_KEY;
480         key.offset = 0;
481         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
482         if (ret < 0)
483                 goto out;
484
485         leaf = path.nodes[0];
486         while (1) {
487                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
488                         do {
489                                 ret = next_leaf(root, &path);
490                                 if (ret < 0) {
491                                         error("searching for extended attributes: %d",
492                                                 ret);
493                                         goto out;
494                                 } else if (ret) {
495                                         /* No more leaves to search */
496                                         ret = 0;
497                                         goto out;
498                                 }
499                                 leaf = path.nodes[0];
500                         } while (!leaf);
501                         continue;
502                 }
503
504                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
505                 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
506                         break;
507                 cur = 0;
508                 total_len = btrfs_item_size_nr(leaf, path.slots[0]);
509                 di = btrfs_item_ptr(leaf, path.slots[0],
510                                     struct btrfs_dir_item);
511
512                 while (cur < total_len) {
513                         len = btrfs_dir_name_len(leaf, di);
514                         if (len > name_len) {
515                                 free(name);
516                                 name = (char *) malloc(len + 1);
517                                 if (!name) {
518                                         ret = -ENOMEM;
519                                         goto out;
520                                 }
521                         }
522                         read_extent_buffer(leaf, name,
523                                            (unsigned long)(di + 1), len);
524                         name[len] = '\0';
525                         name_len = len;
526
527                         len = btrfs_dir_data_len(leaf, di);
528                         if (len > data_len) {
529                                 free(data);
530                                 data = (char *) malloc(len);
531                                 if (!data) {
532                                         ret = -ENOMEM;
533                                         goto out;
534                                 }
535                         }
536                         read_extent_buffer(leaf, data,
537                                            (unsigned long)(di + 1) + name_len,
538                                            len);
539                         data_len = len;
540
541                         if (fsetxattr(fd, name, data, data_len, 0))
542                                 error("setting extended attribute %s on file %s: %s",
543                                         name, file_name, strerror(errno));
544
545                         len = sizeof(*di) + name_len + data_len;
546                         cur += len;
547                         di = (struct btrfs_dir_item *)((char *)di + len);
548                 }
549                 path.slots[0]++;
550         }
551         ret = 0;
552 out:
553         btrfs_release_path(&path);
554         free(name);
555         free(data);
556
557         return ret;
558 }
559
560 static int copy_metadata(struct btrfs_root *root, int fd,
561                 struct btrfs_key *key)
562 {
563         struct btrfs_path path;
564         struct btrfs_inode_item *inode_item;
565         int ret;
566
567         btrfs_init_path(&path);
568         ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
569         if (ret == 0) {
570                 struct btrfs_timespec *bts;
571                 struct timespec times[2];
572
573                 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
574                                 struct btrfs_inode_item);
575
576                 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
577                                 btrfs_inode_gid(path.nodes[0], inode_item));
578                 if (ret) {
579                         error("failed to change owner: %s", strerror(errno));
580                         goto out;
581                 }
582
583                 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
584                 if (ret) {
585                         error("failed to change mode: %s", strerror(errno));
586                         goto out;
587                 }
588
589                 bts = btrfs_inode_atime(inode_item);
590                 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
591                 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
592
593                 bts = btrfs_inode_mtime(inode_item);
594                 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
595                 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
596
597                 ret = futimens(fd, times);
598                 if (ret) {
599                         error("failed to set times: %s", strerror(errno));
600                         goto out;
601                 }
602         }
603 out:
604         btrfs_release_path(&path);
605         return ret;
606 }
607
608 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
609                      const char *file)
610 {
611         struct extent_buffer *leaf;
612         struct btrfs_path path;
613         struct btrfs_file_extent_item *fi;
614         struct btrfs_inode_item *inode_item;
615         struct btrfs_timespec *bts;
616         struct btrfs_key found_key;
617         int ret;
618         int extent_type;
619         int compression;
620         int loops = 0;
621         u64 found_size = 0;
622         struct timespec times[2];
623         int times_ok = 0;
624
625         btrfs_init_path(&path);
626         ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
627         if (ret == 0) {
628                 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
629                                     struct btrfs_inode_item);
630                 found_size = btrfs_inode_size(path.nodes[0], inode_item);
631
632                 if (restore_metadata) {
633                         /*
634                          * Change the ownership and mode now, set times when
635                          * copyout is finished.
636                          */
637
638                         ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
639                                         btrfs_inode_gid(path.nodes[0], inode_item));
640                         if (ret && !ignore_errors)
641                                 goto out;
642
643                         ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
644                         if (ret && !ignore_errors)
645                                 goto out;
646
647                         bts = btrfs_inode_atime(inode_item);
648                         times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
649                         times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
650
651                         bts = btrfs_inode_mtime(inode_item);
652                         times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
653                         times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
654                         times_ok = 1;
655                 }
656         }
657         btrfs_release_path(&path);
658
659         key->offset = 0;
660         key->type = BTRFS_EXTENT_DATA_KEY;
661
662         ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
663         if (ret < 0) {
664                 error("searching extent data returned %d", ret);
665                 goto out;
666         }
667
668         leaf = path.nodes[0];
669         while (!leaf) {
670                 ret = next_leaf(root, &path);
671                 if (ret < 0) {
672                         error("cannot get next leaf: %d", ret);
673                         goto out;
674                 } else if (ret > 0) {
675                         /* No more leaves to search */
676                         ret = 0;
677                         goto out;
678                 }
679                 leaf = path.nodes[0];
680         }
681
682         while (1) {
683                 if (loops >= 0 && loops++ >= 1024) {
684                         enum loop_response resp;
685
686                         resp = ask_to_continue(file);
687                         if (resp == LOOP_STOP)
688                                 break;
689                         else if (resp == LOOP_CONTINUE)
690                                 loops = 0;
691                         else if (resp == LOOP_DONTASK)
692                                 loops = -1;
693                 }
694                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
695                         do {
696                                 ret = next_leaf(root, &path);
697                                 if (ret < 0) {
698                                         fprintf(stderr, "Error searching %d\n", ret);
699                                         goto out;
700                                 } else if (ret) {
701                                         /* No more leaves to search */
702                                         btrfs_release_path(&path);
703                                         goto set_size;
704                                 }
705                                 leaf = path.nodes[0];
706                         } while (!leaf);
707                         continue;
708                 }
709                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
710                 if (found_key.objectid != key->objectid)
711                         break;
712                 if (found_key.type != key->type)
713                         break;
714                 fi = btrfs_item_ptr(leaf, path.slots[0],
715                                     struct btrfs_file_extent_item);
716                 extent_type = btrfs_file_extent_type(leaf, fi);
717                 compression = btrfs_file_extent_compression(leaf, fi);
718                 if (compression >= BTRFS_COMPRESS_LAST) {
719                         warning("compression type %d not supported",
720                                 compression);
721                         ret = -1;
722                         goto out;
723                 }
724
725                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
726                         goto next;
727                 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
728                         ret = copy_one_inline(root, fd, &path, found_key.offset);
729                         if (ret)
730                                 goto out;
731                 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
732                         ret = copy_one_extent(root, fd, leaf, fi,
733                                               found_key.offset);
734                         if (ret)
735                                 goto out;
736                 } else {
737                         warning("weird extent type %d", extent_type);
738                 }
739 next:
740                 path.slots[0]++;
741         }
742
743         btrfs_release_path(&path);
744 set_size:
745         if (found_size) {
746                 ret = ftruncate(fd, (loff_t)found_size);
747                 if (ret)
748                         return ret;
749         }
750         if (get_xattrs) {
751                 ret = set_file_xattrs(root, key->objectid, fd, file);
752                 if (ret)
753                         return ret;
754         }
755         if (restore_metadata && times_ok) {
756                 ret = futimens(fd, times);
757                 if (ret)
758                         return ret;
759         }
760         return 0;
761
762 out:
763         btrfs_release_path(&path);
764         return ret;
765 }
766
767 /*
768  * returns:
769  *  0 if the file exists and should be skipped.
770  *  1 if the file does NOT exist
771  *  2 if the file exists but is OK to overwrite
772  */
773 static int overwrite_ok(const char * path)
774 {
775         static int warn = 0;
776         struct stat st;
777         int ret;
778
779         /* don't be fooled by symlinks */
780         ret = fstatat(-1, path_name, &st, AT_SYMLINK_NOFOLLOW);
781
782         if (!ret) {
783                 if (overwrite)
784                         return 2;
785
786                 if (verbose || !warn)
787                         printf("Skipping existing file"
788                                    " %s\n", path);
789                 if (!warn)
790                         printf("If you wish to overwrite use -o\n");
791                 warn = 1;
792                 return 0;
793         }
794         return 1;
795 }
796
797 static int copy_symlink(struct btrfs_root *root, struct btrfs_key *key,
798                      const char *file)
799 {
800         struct btrfs_path path;
801         struct extent_buffer *leaf;
802         struct btrfs_file_extent_item *extent_item;
803         struct btrfs_inode_item *inode_item;
804         u32 len;
805         u32 name_offset;
806         int ret;
807         struct btrfs_timespec *bts;
808         struct timespec times[2];
809
810         ret = overwrite_ok(path_name);
811         if (ret == 0)
812             return 0; /* skip this file */
813
814         /* symlink() can't overwrite, so unlink first */
815         if (ret == 2) {
816                 ret = unlink(path_name);
817                 if (ret) {
818                         fprintf(stderr, "failed to unlink '%s' for overwrite\n",
819                                         path_name);
820                         return ret;
821                 }
822         }
823
824         btrfs_init_path(&path);
825         key->type = BTRFS_EXTENT_DATA_KEY;
826         key->offset = 0;
827         ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
828         if (ret < 0)
829                 goto out;
830
831         leaf = path.nodes[0];
832         if (!leaf) {
833                 fprintf(stderr, "Error getting leaf for symlink '%s'\n", file);
834                 ret = -1;
835                 goto out;
836         }
837
838         extent_item = btrfs_item_ptr(leaf, path.slots[0],
839                         struct btrfs_file_extent_item);
840
841         len = btrfs_file_extent_inline_item_len(leaf,
842                         btrfs_item_nr(path.slots[0]));
843         if (len >= PATH_MAX) {
844                 fprintf(stderr, "Symlink '%s' target length %d is longer than PATH_MAX\n",
845                                 fs_name, len);
846                 ret = -1;
847                 goto out;
848         }
849
850         name_offset = (unsigned long) extent_item
851                         + offsetof(struct btrfs_file_extent_item, disk_bytenr);
852         read_extent_buffer(leaf, symlink_target, name_offset, len);
853
854         symlink_target[len] = 0;
855
856         if (!dry_run) {
857                 ret = symlink(symlink_target, path_name);
858                 if (ret < 0) {
859                         fprintf(stderr, "Failed to restore symlink '%s': %s\n",
860                                         path_name, strerror(errno));
861                         goto out;
862                 }
863         }
864         printf("SYMLINK: '%s' => '%s'\n", path_name, symlink_target);
865
866         ret = 0;
867         if (!restore_metadata)
868                 goto out;
869
870         /*
871          * Symlink metadata operates differently than files/directories, so do
872          * our own work here.
873          */
874         key->type = BTRFS_INODE_ITEM_KEY;
875         key->offset = 0;
876
877         btrfs_release_path(&path);
878
879         ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
880         if (ret) {
881                 fprintf(stderr, "Failed to lookup inode for '%s'\n", file);
882                 goto out;
883         }
884
885         inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
886                         struct btrfs_inode_item);
887
888         ret = fchownat(-1, file, btrfs_inode_uid(path.nodes[0], inode_item),
889                                    btrfs_inode_gid(path.nodes[0], inode_item),
890                                    AT_SYMLINK_NOFOLLOW);
891         if (ret) {
892                 fprintf(stderr, "Failed to change owner: %s\n",
893                                 strerror(errno));
894                 goto out;
895         }
896
897         bts = btrfs_inode_atime(inode_item);
898         times[0].tv_sec  = btrfs_timespec_sec(path.nodes[0], bts);
899         times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
900
901         bts = btrfs_inode_mtime(inode_item);
902         times[1].tv_sec  = btrfs_timespec_sec(path.nodes[0], bts);
903         times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
904
905         ret = utimensat(-1, file, times, AT_SYMLINK_NOFOLLOW);
906         if (ret)
907                 fprintf(stderr, "Failed to set times: %s\n", strerror(errno));
908 out:
909         btrfs_release_path(&path);
910         return ret;
911 }
912
913 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
914                       const char *output_rootdir, const char *in_dir,
915                       const regex_t *mreg)
916 {
917         struct btrfs_path path;
918         struct extent_buffer *leaf;
919         struct btrfs_dir_item *dir_item;
920         struct btrfs_key found_key, location;
921         char filename[BTRFS_NAME_LEN + 1];
922         unsigned long name_ptr;
923         int name_len;
924         int ret = 0;
925         int fd;
926         int loops = 0;
927         u8 type;
928
929         btrfs_init_path(&path);
930         key->offset = 0;
931         key->type = BTRFS_DIR_INDEX_KEY;
932         ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
933         if (ret < 0) {
934                 fprintf(stderr, "Error searching %d\n", ret);
935                 goto out;
936         }
937
938         ret = 0;
939
940         leaf = path.nodes[0];
941         while (!leaf) {
942                 if (verbose > 1)
943                         printf("No leaf after search, looking for the next "
944                                "leaf\n");
945                 ret = next_leaf(root, &path);
946                 if (ret < 0) {
947                         fprintf(stderr, "Error getting next leaf %d\n",
948                                 ret);
949                         goto out;
950                 } else if (ret > 0) {
951                         /* No more leaves to search */
952                         if (verbose)
953                                 printf("Reached the end of the tree looking "
954                                        "for the directory\n");
955                         ret = 0;
956                         goto out;
957                 }
958                 leaf = path.nodes[0];
959         }
960
961         while (leaf) {
962                 if (loops++ >= 1024) {
963                         printf("We have looped trying to restore files in %s "
964                                "too many times to be making progress, "
965                                "stopping\n", in_dir);
966                         break;
967                 }
968
969                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
970                         do {
971                                 ret = next_leaf(root, &path);
972                                 if (ret < 0) {
973                                         fprintf(stderr, "Error searching %d\n",
974                                                 ret);
975                                         goto out;
976                                 } else if (ret > 0) {
977                                         /* No more leaves to search */
978                                         if (verbose)
979                                                 printf("Reached the end of "
980                                                        "the tree searching the"
981                                                        " directory\n");
982                                         ret = 0;
983                                         goto out;
984                                 }
985                                 leaf = path.nodes[0];
986                         } while (!leaf);
987                         continue;
988                 }
989                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
990                 if (found_key.objectid != key->objectid) {
991                         if (verbose > 1)
992                                 printf("Found objectid=%Lu, key=%Lu\n",
993                                        found_key.objectid, key->objectid);
994                         break;
995                 }
996                 if (found_key.type != key->type) {
997                         if (verbose > 1)
998                                 printf("Found type=%u, want=%u\n",
999                                        found_key.type, key->type);
1000                         break;
1001                 }
1002                 dir_item = btrfs_item_ptr(leaf, path.slots[0],
1003                                           struct btrfs_dir_item);
1004                 name_ptr = (unsigned long)(dir_item + 1);
1005                 name_len = btrfs_dir_name_len(leaf, dir_item);
1006                 read_extent_buffer(leaf, filename, name_ptr, name_len);
1007                 filename[name_len] = '\0';
1008                 type = btrfs_dir_type(leaf, dir_item);
1009                 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
1010
1011                 /* full path from root of btrfs being restored */
1012                 snprintf(fs_name, PATH_MAX, "%s/%s", in_dir, filename);
1013
1014                 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
1015                         goto next;
1016
1017                 /* full path from system root */
1018                 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, fs_name);
1019
1020                 /*
1021                  * Restore directories, files, symlinks and metadata.
1022                  */
1023                 if (type == BTRFS_FT_REG_FILE) {
1024                         if (!overwrite_ok(path_name))
1025                                 goto next;
1026
1027                         if (verbose)
1028                                 printf("Restoring %s\n", path_name);
1029                         if (dry_run)
1030                                 goto next;
1031                         fd = open(path_name, O_CREAT|O_WRONLY, 0644);
1032                         if (fd < 0) {
1033                                 fprintf(stderr, "Error creating %s: %d\n",
1034                                         path_name, errno);
1035                                 if (ignore_errors)
1036                                         goto next;
1037                                 ret = -1;
1038                                 goto out;
1039                         }
1040                         loops = 0;
1041                         ret = copy_file(root, fd, &location, path_name);
1042                         close(fd);
1043                         if (ret) {
1044                                 fprintf(stderr, "Error copying data for %s\n",
1045                                         path_name);
1046                                 if (ignore_errors)
1047                                         goto next;
1048                                 goto out;
1049                         }
1050                 } else if (type == BTRFS_FT_DIR) {
1051                         struct btrfs_root *search_root = root;
1052                         char *dir = strdup(fs_name);
1053
1054                         if (!dir) {
1055                                 fprintf(stderr, "Ran out of memory\n");
1056                                 ret = -ENOMEM;
1057                                 goto out;
1058                         }
1059
1060                         if (location.type == BTRFS_ROOT_ITEM_KEY) {
1061                                 /*
1062                                  * If we are a snapshot and this is the index
1063                                  * object to ourselves just skip it.
1064                                  */
1065                                 if (location.objectid ==
1066                                     root->root_key.objectid) {
1067                                         free(dir);
1068                                         goto next;
1069                                 }
1070
1071                                 location.offset = (u64)-1;
1072                                 search_root = btrfs_read_fs_root(root->fs_info,
1073                                                                  &location);
1074                                 if (IS_ERR(search_root)) {
1075                                         free(dir);
1076                                         fprintf(stderr, "Error reading "
1077                                                 "subvolume %s: %lu\n",
1078                                                 path_name,
1079                                                 PTR_ERR(search_root));
1080                                         if (ignore_errors)
1081                                                 goto next;
1082                                         ret = PTR_ERR(search_root);
1083                                         goto out;
1084                                 }
1085
1086                                 /*
1087                                  * A subvolume will have a key.offset of 0, a
1088                                  * snapshot will have key.offset of a transid.
1089                                  */
1090                                 if (search_root->root_key.offset != 0 &&
1091                                     get_snaps == 0) {
1092                                         free(dir);
1093                                         printf("Skipping snapshot %s\n",
1094                                                filename);
1095                                         goto next;
1096                                 }
1097                                 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
1098                         }
1099
1100                         if (verbose)
1101                                 printf("Restoring %s\n", path_name);
1102
1103                         errno = 0;
1104                         if (dry_run)
1105                                 ret = 0;
1106                         else
1107                                 ret = mkdir(path_name, 0755);
1108                         if (ret && errno != EEXIST) {
1109                                 free(dir);
1110                                 fprintf(stderr, "Error mkdiring %s: %d\n",
1111                                         path_name, errno);
1112                                 if (ignore_errors)
1113                                         goto next;
1114                                 ret = -1;
1115                                 goto out;
1116                         }
1117                         loops = 0;
1118                         ret = search_dir(search_root, &location,
1119                                          output_rootdir, dir, mreg);
1120                         free(dir);
1121                         if (ret) {
1122                                 fprintf(stderr, "Error searching %s\n",
1123                                         path_name);
1124                                 if (ignore_errors)
1125                                         goto next;
1126                                 goto out;
1127                         }
1128                 } else if (type == BTRFS_FT_SYMLINK) {
1129                         if (restore_symlinks)
1130                                 ret = copy_symlink(root, &location, path_name);
1131                         if (ret < 0) {
1132                                 if (ignore_errors)
1133                                         goto next;
1134                                 btrfs_release_path(&path);
1135                                 return ret;
1136                         }
1137                 }
1138 next:
1139                 path.slots[0]++;
1140         }
1141
1142         if (restore_metadata) {
1143                 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, in_dir);
1144                 fd = open(path_name, O_RDONLY);
1145                 if (fd < 0) {
1146                         fprintf(stderr, "ERROR: Failed to access %s to restore metadata\n",
1147                                         path_name);
1148                         if (!ignore_errors) {
1149                                 ret = -1;
1150                                 goto out;
1151                         }
1152                 } else {
1153                         /*
1154                          * Set owner/mode/time on the directory as well
1155                          */
1156                         key->type = BTRFS_INODE_ITEM_KEY;
1157                         ret = copy_metadata(root, fd, key);
1158                         close(fd);
1159                         if (ret && !ignore_errors)
1160                                 goto out;
1161                 }
1162         }
1163
1164         if (verbose)
1165                 printf("Done searching %s\n", in_dir);
1166 out:
1167         btrfs_release_path(&path);
1168         return ret;
1169 }
1170
1171 static int do_list_roots(struct btrfs_root *root)
1172 {
1173         struct btrfs_key key;
1174         struct btrfs_key found_key;
1175         struct btrfs_disk_key disk_key;
1176         struct btrfs_path path;
1177         struct extent_buffer *leaf;
1178         struct btrfs_root_item ri;
1179         unsigned long offset;
1180         int slot;
1181         int ret;
1182
1183         root = root->fs_info->tree_root;
1184
1185         btrfs_init_path(&path);
1186         key.offset = 0;
1187         key.objectid = 0;
1188         key.type = BTRFS_ROOT_ITEM_KEY;
1189         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1190         if (ret < 0) {
1191                 fprintf(stderr, "Failed to do search %d\n", ret);
1192                 btrfs_release_path(&path);
1193                 return -1;
1194         }
1195
1196         leaf = path.nodes[0];
1197
1198         while (1) {
1199                 slot = path.slots[0];
1200                 if (slot >= btrfs_header_nritems(leaf)) {
1201                         ret = btrfs_next_leaf(root, &path);
1202                         if (ret)
1203                                 break;
1204                         leaf = path.nodes[0];
1205                         slot = path.slots[0];
1206                 }
1207                 btrfs_item_key(leaf, &disk_key, slot);
1208                 btrfs_disk_key_to_cpu(&found_key, &disk_key);
1209                 if (found_key.type != BTRFS_ROOT_ITEM_KEY) {
1210                         path.slots[0]++;
1211                         continue;
1212                 }
1213
1214                 offset = btrfs_item_ptr_offset(leaf, slot);
1215                 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
1216                 printf(" tree ");
1217                 btrfs_print_key(&disk_key);
1218                 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
1219                        btrfs_root_level(&ri));
1220                 path.slots[0]++;
1221         }
1222         btrfs_release_path(&path);
1223
1224         return 0;
1225 }
1226
1227 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
1228                                   int super_mirror, int list_roots)
1229 {
1230         struct btrfs_fs_info *fs_info = NULL;
1231         struct btrfs_root *root = NULL;
1232         u64 bytenr;
1233         int i;
1234
1235         for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1236                 bytenr = btrfs_sb_offset(i);
1237                 fs_info = open_ctree_fs_info(dev, bytenr, root_location, 0,
1238                                              OPEN_CTREE_PARTIAL);
1239                 if (fs_info)
1240                         break;
1241                 fprintf(stderr, "Could not open root, trying backup super\n");
1242         }
1243
1244         if (!fs_info)
1245                 return NULL;
1246
1247         /*
1248          * All we really need to succeed is reading the chunk tree, everything
1249          * else we can do by hand, since we only need to read the tree root and
1250          * the fs_root.
1251          */
1252         if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1253                 u64 generation;
1254
1255                 root = fs_info->tree_root;
1256                 if (!root_location)
1257                         root_location = btrfs_super_root(fs_info->super_copy);
1258                 generation = btrfs_super_generation(fs_info->super_copy);
1259                 root->node = read_tree_block(fs_info, root_location,
1260                                              fs_info->nodesize, generation);
1261                 if (!extent_buffer_uptodate(root->node)) {
1262                         fprintf(stderr, "Error opening tree root\n");
1263                         close_ctree(root);
1264                         return NULL;
1265                 }
1266         }
1267
1268         if (!list_roots && !fs_info->fs_root) {
1269                 struct btrfs_key key;
1270
1271                 key.objectid = BTRFS_FS_TREE_OBJECTID;
1272                 key.type = BTRFS_ROOT_ITEM_KEY;
1273                 key.offset = (u64)-1;
1274                 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1275                 if (IS_ERR(fs_info->fs_root)) {
1276                         fprintf(stderr, "Couldn't read fs root: %ld\n",
1277                                 PTR_ERR(fs_info->fs_root));
1278                         close_ctree(fs_info->tree_root);
1279                         return NULL;
1280                 }
1281         }
1282
1283         if (list_roots && do_list_roots(fs_info->tree_root)) {
1284                 close_ctree(fs_info->tree_root);
1285                 return NULL;
1286         }
1287
1288         return fs_info->fs_root;
1289 }
1290
1291 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1292 {
1293         struct btrfs_path path;
1294         struct btrfs_key found_key;
1295         struct btrfs_key key;
1296         int ret = -1;
1297         int i;
1298
1299         btrfs_init_path(&path);
1300         key.objectid = 0;
1301         key.type = BTRFS_DIR_INDEX_KEY;
1302         key.offset = 0;
1303         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1304         if (ret < 0) {
1305                 fprintf(stderr, "Error searching %d\n", ret);
1306                 goto out;
1307         }
1308
1309         if (!path.nodes[0]) {
1310                 fprintf(stderr, "No leaf!\n");
1311                 goto out;
1312         }
1313 again:
1314         for (i = path.slots[0];
1315              i < btrfs_header_nritems(path.nodes[0]); i++) {
1316                 btrfs_item_key_to_cpu(path.nodes[0], &found_key, i);
1317                 if (found_key.type != key.type)
1318                         continue;
1319
1320                 printf("Using objectid %Lu for first dir\n",
1321                        found_key.objectid);
1322                 *objectid = found_key.objectid;
1323                 ret = 0;
1324                 goto out;
1325         }
1326         do {
1327                 ret = next_leaf(root, &path);
1328                 if (ret < 0) {
1329                         fprintf(stderr, "Error getting next leaf %d\n",
1330                                 ret);
1331                         goto out;
1332                 } else if (ret > 0) {
1333                         fprintf(stderr, "No more leaves\n");
1334                         goto out;
1335                 }
1336         } while (!path.nodes[0]);
1337         if (path.nodes[0])
1338                 goto again;
1339         printf("Couldn't find a dir index item\n");
1340 out:
1341         btrfs_release_path(&path);
1342         return ret;
1343 }
1344
1345 const char * const cmd_restore_usage[] = {
1346         "btrfs restore [options] <device> <path> | -l <device>",
1347         "Try to restore files from a damaged filesystem (unmounted)",
1348         "",
1349         "-s|--snapshots       get snapshots",
1350         "-x|--xattr           restore extended attributes",
1351         "-m|--metadata        restore owner, mode and times",
1352         "-S|--symlink         restore symbolic links",
1353         "-v|--verbose         verbose",
1354         "-i|--ignore-errors   ignore errors",
1355         "-o|--overwrite       overwrite",
1356         "-t <bytenr>          tree location",
1357         "-f <bytenr>          filesystem location",
1358         "-u|--super <mirror>  super mirror",
1359         "-r|--root <rootid>   root objectid",
1360         "-d                   find dir",
1361         "-l|--list-roots      list tree roots",
1362         "-D|--dry-run         dry run (only list files that would be recovered)",
1363         "--path-regex <regex>",
1364         "                     restore only filenames matching regex,",
1365         "                     you have to use following syntax (possibly quoted):",
1366         "                     ^/(|home(|/username(|/Desktop(|/.*))))$",
1367         "-c                   ignore case (--path-regex only)",
1368         NULL
1369 };
1370
1371 int cmd_restore(int argc, char **argv)
1372 {
1373         struct btrfs_root *root;
1374         struct btrfs_key key;
1375         char dir_name[PATH_MAX];
1376         u64 tree_location = 0;
1377         u64 fs_location = 0;
1378         u64 root_objectid = 0;
1379         int len;
1380         int ret;
1381         int super_mirror = 0;
1382         int find_dir = 0;
1383         int list_roots = 0;
1384         const char *match_regstr = NULL;
1385         int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1386         regex_t match_reg, *mreg = NULL;
1387         char reg_err[256];
1388
1389         while (1) {
1390                 int opt;
1391                 enum { GETOPT_VAL_PATH_REGEX = 256 };
1392                 static const struct option long_options[] = {
1393                         { "path-regex", required_argument, NULL,
1394                                 GETOPT_VAL_PATH_REGEX },
1395                         { "dry-run", no_argument, NULL, 'D'},
1396                         { "metadata", no_argument, NULL, 'm'},
1397                         { "symlinks", no_argument, NULL, 'S'},
1398                         { "snapshots", no_argument, NULL, 's'},
1399                         { "xattr", no_argument, NULL, 'x'},
1400                         { "verbose", no_argument, NULL, 'v'},
1401                         { "ignore-errors", no_argument, NULL, 'i'},
1402                         { "overwrite", no_argument, NULL, 'o'},
1403                         { "super", required_argument, NULL, 'u'},
1404                         { "root", required_argument, NULL, 'r'},
1405                         { "list-roots", no_argument, NULL, 'l'},
1406                         { NULL, 0, NULL, 0}
1407                 };
1408
1409                 opt = getopt_long(argc, argv, "sSxviot:u:dmf:r:lDc", long_options,
1410                                         NULL);
1411                 if (opt < 0)
1412                         break;
1413
1414                 switch (opt) {
1415                         case 's':
1416                                 get_snaps = 1;
1417                                 break;
1418                         case 'v':
1419                                 verbose++;
1420                                 break;
1421                         case 'i':
1422                                 ignore_errors = 1;
1423                                 break;
1424                         case 'o':
1425                                 overwrite = 1;
1426                                 break;
1427                         case 't':
1428                                 tree_location = arg_strtou64(optarg);
1429                                 break;
1430                         case 'f':
1431                                 fs_location = arg_strtou64(optarg);
1432                                 break;
1433                         case 'u':
1434                                 super_mirror = arg_strtou64(optarg);
1435                                 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1436                                         fprintf(stderr, "Super mirror not "
1437                                                 "valid\n");
1438                                         exit(1);
1439                                 }
1440                                 break;
1441                         case 'd':
1442                                 find_dir = 1;
1443                                 break;
1444                         case 'r':
1445                                 root_objectid = arg_strtou64(optarg);
1446                                 if (!is_fstree(root_objectid)) {
1447                                         fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1448                                                         root_objectid);
1449                                         exit(1);
1450                                 }
1451                                 break;
1452                         case 'l':
1453                                 list_roots = 1;
1454                                 break;
1455                         case 'm':
1456                                 restore_metadata = 1;
1457                                 break;
1458                         case 'S':
1459                                 restore_symlinks = 1;
1460                                 break;
1461                         case 'D':
1462                                 dry_run = 1;
1463                                 break;
1464                         case 'c':
1465                                 match_cflags |= REG_ICASE;
1466                                 break;
1467                         case GETOPT_VAL_PATH_REGEX:
1468                                 match_regstr = optarg;
1469                                 break;
1470                         case 'x':
1471                                 get_xattrs = 1;
1472                                 break;
1473                         default:
1474                                 usage(cmd_restore_usage);
1475                 }
1476         }
1477
1478         if (!list_roots && check_argc_min(argc - optind, 2))
1479                 usage(cmd_restore_usage);
1480         else if (list_roots && check_argc_min(argc - optind, 1))
1481                 usage(cmd_restore_usage);
1482
1483         if (fs_location && root_objectid) {
1484                 fprintf(stderr, "don't use -f and -r at the same time.\n");
1485                 return 1;
1486         }
1487
1488         if ((ret = check_mounted(argv[optind])) < 0) {
1489                 fprintf(stderr, "Could not check mount status: %s\n",
1490                         strerror(-ret));
1491                 return 1;
1492         } else if (ret) {
1493                 fprintf(stderr, "%s is currently mounted.  Aborting.\n", argv[optind]);
1494                 return 1;
1495         }
1496
1497         root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1498         if (root == NULL)
1499                 return 1;
1500
1501         if (list_roots)
1502                 goto out;
1503
1504         if (fs_location != 0) {
1505                 free_extent_buffer(root->node);
1506                 root->node = read_tree_block(root->fs_info, fs_location,
1507                                 root->fs_info->nodesize, 0);
1508                 if (!extent_buffer_uptodate(root->node)) {
1509                         fprintf(stderr, "Failed to read fs location\n");
1510                         ret = 1;
1511                         goto out;
1512                 }
1513         }
1514
1515         memset(path_name, 0, PATH_MAX);
1516
1517         if (strlen(argv[optind + 1]) >= PATH_MAX) {
1518                 fprintf(stderr, "ERROR: path too long\n");
1519                 ret = 1;
1520                 goto out;
1521         }
1522         strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1523         dir_name[sizeof dir_name - 1] = 0;
1524
1525         /* Strip the trailing / on the dir name */
1526         len = strlen(dir_name);
1527         while (len && dir_name[--len] == '/') {
1528                 dir_name[len] = '\0';
1529         }
1530
1531         if (root_objectid != 0) {
1532                 struct btrfs_root *orig_root = root;
1533
1534                 key.objectid = root_objectid;
1535                 key.type = BTRFS_ROOT_ITEM_KEY;
1536                 key.offset = (u64)-1;
1537                 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1538                 if (IS_ERR(root)) {
1539                         fprintf(stderr, "fail to read root %llu: %s\n",
1540                                         root_objectid, strerror(-PTR_ERR(root)));
1541                         root = orig_root;
1542                         ret = 1;
1543                         goto out;
1544                 }
1545                 key.type = 0;
1546                 key.offset = 0;
1547         }
1548
1549         if (find_dir) {
1550                 ret = find_first_dir(root, &key.objectid);
1551                 if (ret)
1552                         goto out;
1553         } else {
1554                 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1555         }
1556
1557         if (match_regstr) {
1558                 ret = regcomp(&match_reg, match_regstr, match_cflags);
1559                 if (ret) {
1560                         regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1561                         fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1562                         goto out;
1563                 }
1564                 mreg = &match_reg;
1565         }
1566
1567         if (dry_run)
1568                 printf("This is a dry-run, no files are going to be restored\n");
1569
1570         ret = search_dir(root, &key, dir_name, "", mreg);
1571
1572 out:
1573         if (mreg)
1574                 regfree(mreg);
1575         close_ctree(root);
1576         return !!ret;
1577 }