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