btrfs-progs: fix len of read_extent_buffer for inline extent in restore
[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 #define _XOPEN_SOURCE 500
20 #define _GNU_SOURCE 1
21
22 #include "kerncompat.h"
23
24 #include <ctype.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <lzo/lzoconf.h>
32 #include <lzo/lzo1x.h>
33 #include <zlib.h>
34 #include <regex.h>
35 #include <getopt.h>
36 #include <sys/types.h>
37 #include <sys/xattr.h>
38
39 #include "ctree.h"
40 #include "disk-io.h"
41 #include "print-tree.h"
42 #include "transaction.h"
43 #include "list.h"
44 #include "version.h"
45 #include "volumes.h"
46 #include "utils.h"
47 #include "commands.h"
48
49 static char fs_name[4096];
50 static char path_name[4096];
51 static int get_snaps = 0;
52 static int verbose = 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                 fprintf(stderr, "inflate init returnd %d\n", 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                 fprintf(stderr, "failed to inflate: %d\n", 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                 fprintf(stderr, "lzo init returned %d\n", 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                 in_len = read_compress_length(inbuf);
118
119                 if ((tot_in + LZO_LEN + in_len) > tot_len) {
120                         fprintf(stderr, "bad compress length %lu\n",
121                                 (unsigned long)in_len);
122                         return -1;
123                 }
124
125                 inbuf += LZO_LEN;
126                 tot_in += LZO_LEN;
127
128                 new_len = lzo1x_worst_compress(PAGE_CACHE_SIZE);
129                 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
130                                             (unsigned char *)outbuf,
131                                             (void *)&new_len, NULL);
132                 if (ret != LZO_E_OK) {
133                         fprintf(stderr, "failed to inflate: %d\n", ret);
134                         return -1;
135                 }
136                 out_len += new_len;
137                 outbuf += new_len;
138                 inbuf += in_len;
139                 tot_in += in_len;
140         }
141
142         *decompress_len = out_len;
143
144         return 0;
145 }
146
147 static int decompress(char *inbuf, char *outbuf, u64 compress_len,
148                       u64 *decompress_len, int compress)
149 {
150         switch (compress) {
151         case BTRFS_COMPRESS_ZLIB:
152                 return decompress_zlib(inbuf, outbuf, compress_len,
153                                        *decompress_len);
154         case BTRFS_COMPRESS_LZO:
155                 return decompress_lzo((unsigned char *)inbuf, outbuf, compress_len,
156                                       decompress_len);
157         default:
158                 break;
159         }
160
161         fprintf(stderr, "invalid compression type: %d\n", compress);
162         return -1;
163 }
164
165 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
166 {
167         int slot;
168         int level = 1;
169         int offset = 1;
170         struct extent_buffer *c;
171         struct extent_buffer *next = NULL;
172
173 again:
174         for (; level < BTRFS_MAX_LEVEL; level++) {
175                 if (path->nodes[level])
176                         break;
177         }
178
179         if (level == BTRFS_MAX_LEVEL)
180                 return 1;
181
182         slot = path->slots[level] + 1;
183
184         while(level < BTRFS_MAX_LEVEL) {
185                 if (!path->nodes[level])
186                         return 1;
187
188                 slot = path->slots[level] + offset;
189                 c = path->nodes[level];
190                 if (slot >= btrfs_header_nritems(c)) {
191                         level++;
192                         if (level == BTRFS_MAX_LEVEL)
193                                 return 1;
194                         continue;
195                 }
196
197                 if (path->reada)
198                         reada_for_search(root, path, level, slot, 0);
199
200                 next = read_node_slot(root, c, slot);
201                 if (next)
202                         break;
203                 offset++;
204         }
205         path->slots[level] = slot;
206         while(1) {
207                 level--;
208                 c = path->nodes[level];
209                 free_extent_buffer(c);
210                 path->nodes[level] = next;
211                 path->slots[level] = 0;
212                 if (!level)
213                         break;
214                 if (path->reada)
215                         reada_for_search(root, path, level, 0, 0);
216                 next = read_node_slot(root, next, 0);
217                 if (!next)
218                         goto again;
219         }
220         return 0;
221 }
222
223 static int copy_one_inline(int fd, struct btrfs_path *path, u64 pos)
224 {
225         struct extent_buffer *leaf = path->nodes[0];
226         struct btrfs_file_extent_item *fi;
227         char buf[4096];
228         char *outbuf;
229         u64 ram_size;
230         ssize_t done;
231         unsigned long ptr;
232         int ret;
233         int len;
234         int inline_item_len;
235         int compress;
236
237         fi = btrfs_item_ptr(leaf, path->slots[0],
238                             struct btrfs_file_extent_item);
239         ptr = btrfs_file_extent_inline_start(fi);
240         len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
241         inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
242         read_extent_buffer(leaf, buf, ptr, inline_item_len);
243
244         compress = btrfs_file_extent_compression(leaf, fi);
245         if (compress == BTRFS_COMPRESS_NONE) {
246                 done = pwrite(fd, buf, len, pos);
247                 if (done < len) {
248                         fprintf(stderr, "Short inline write, wanted %d, did "
249                                 "%zd: %d\n", len, done, errno);
250                         return -1;
251                 }
252                 return 0;
253         }
254
255         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
256         outbuf = calloc(1, ram_size);
257         if (!outbuf) {
258                 fprintf(stderr, "No memory\n");
259                 return -ENOMEM;
260         }
261
262         ret = decompress(buf, outbuf, len, &ram_size, compress);
263         if (ret) {
264                 free(outbuf);
265                 return ret;
266         }
267
268         done = pwrite(fd, outbuf, ram_size, pos);
269         free(outbuf);
270         if (done < ram_size) {
271                 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
272                         "did %zd: %d\n", ram_size, done, errno);
273                 return -1;
274         }
275
276         return 0;
277 }
278
279 static int copy_one_extent(struct btrfs_root *root, int fd,
280                            struct extent_buffer *leaf,
281                            struct btrfs_file_extent_item *fi, u64 pos)
282 {
283         struct btrfs_multi_bio *multi = NULL;
284         struct btrfs_device *device;
285         char *inbuf, *outbuf = NULL;
286         ssize_t done, total = 0;
287         u64 bytenr;
288         u64 ram_size;
289         u64 disk_size;
290         u64 num_bytes;
291         u64 length;
292         u64 size_left;
293         u64 dev_bytenr;
294         u64 offset;
295         u64 count = 0;
296         int compress;
297         int ret;
298         int dev_fd;
299         int mirror_num = 1;
300         int num_copies;
301
302         compress = btrfs_file_extent_compression(leaf, fi);
303         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
304         disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
305         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
306         offset = btrfs_file_extent_offset(leaf, fi);
307         num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
308         size_left = disk_size;
309         if (compress == BTRFS_COMPRESS_NONE)
310                 bytenr += offset;
311
312         if (verbose && offset)
313                 printf("offset is %Lu\n", offset);
314         /* we found a hole */
315         if (disk_size == 0)
316                 return 0;
317
318         inbuf = malloc(size_left);
319         if (!inbuf) {
320                 fprintf(stderr, "No memory\n");
321                 return -ENOMEM;
322         }
323
324         if (compress != BTRFS_COMPRESS_NONE) {
325                 outbuf = calloc(1, ram_size);
326                 if (!outbuf) {
327                         fprintf(stderr, "No memory\n");
328                         free(inbuf);
329                         return -ENOMEM;
330                 }
331         }
332 again:
333         length = size_left;
334         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
335                               bytenr, &length, &multi, mirror_num, NULL);
336         if (ret) {
337                 fprintf(stderr, "Error mapping block %d\n", ret);
338                 goto out;
339         }
340         device = multi->stripes[0].dev;
341         dev_fd = device->fd;
342         device->total_ios++;
343         dev_bytenr = multi->stripes[0].physical;
344         kfree(multi);
345
346         if (size_left < length)
347                 length = size_left;
348
349         done = pread(dev_fd, inbuf+count, length, dev_bytenr);
350         /* Need both checks, or we miss negative values due to u64 conversion */
351         if (done < 0 || done < length) {
352                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
353                                               bytenr, length);
354                 mirror_num++;
355                 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
356                 if (mirror_num > num_copies) {
357                         ret = -1;
358                         fprintf(stderr, "Exhausted mirrors trying to read\n");
359                         goto out;
360                 }
361                 fprintf(stderr, "Trying another mirror\n");
362                 goto again;
363         }
364
365         mirror_num = 1;
366         size_left -= length;
367         count += length;
368         bytenr += length;
369         if (size_left)
370                 goto again;
371
372         if (compress == BTRFS_COMPRESS_NONE) {
373                 while (total < num_bytes) {
374                         done = pwrite(fd, inbuf+total, num_bytes-total,
375                                       pos+total);
376                         if (done < 0) {
377                                 ret = -1;
378                                 fprintf(stderr, "Error writing: %d %s\n", errno, strerror(errno));
379                                 goto out;
380                         }
381                         total += done;
382                 }
383                 ret = 0;
384                 goto out;
385         }
386
387         ret = decompress(inbuf, outbuf, disk_size, &ram_size, compress);
388         if (ret) {
389                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
390                                               bytenr, length);
391                 mirror_num++;
392                 if (mirror_num >= num_copies) {
393                         ret = -1;
394                         goto out;
395                 }
396                 fprintf(stderr, "Trying another mirror\n");
397                 goto again;
398         }
399
400         while (total < num_bytes) {
401                 done = pwrite(fd, outbuf + offset + total,
402                               num_bytes - total,
403                               pos + total);
404                 if (done < 0) {
405                         ret = -1;
406                         goto out;
407                 }
408                 total += done;
409         }
410 out:
411         free(inbuf);
412         free(outbuf);
413         return ret;
414 }
415
416 enum loop_response {
417         LOOP_STOP,
418         LOOP_CONTINUE,
419         LOOP_DONTASK
420 };
421
422 static enum loop_response ask_to_continue(const char *file)
423 {
424         char buf[2];
425         char *ret;
426
427         printf("We seem to be looping a lot on %s, do you want to keep going "
428                "on ? (y/N/a): ", file);
429 again:
430         ret = fgets(buf, 2, stdin);
431         if (*ret == '\n' || tolower(*ret) == 'n')
432                 return LOOP_STOP;
433         if (tolower(*ret) == 'a')
434                 return LOOP_DONTASK;
435         if (tolower(*ret) != 'y') {
436                 printf("Please enter one of 'y', 'n', or 'a': ");
437                 goto again;
438         }
439
440         return LOOP_CONTINUE;
441 }
442
443
444 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
445                            int fd, const char *file_name)
446 {
447         struct btrfs_key key;
448         struct btrfs_path *path;
449         struct extent_buffer *leaf;
450         struct btrfs_dir_item *di;
451         u32 name_len = 0;
452         u32 data_len = 0;
453         u32 len = 0;
454         u32 cur, total_len;
455         char *name = NULL;
456         char *data = NULL;
457         int ret = 0;
458
459         key.objectid = inode;
460         key.type = BTRFS_XATTR_ITEM_KEY;
461         key.offset = 0;
462
463         path = btrfs_alloc_path();
464         if (!path)
465                 return -ENOMEM;
466
467         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
468         if (ret < 0)
469                 goto out;
470
471         leaf = path->nodes[0];
472         while (1) {
473                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
474                         do {
475                                 ret = next_leaf(root, path);
476                                 if (ret < 0) {
477                                         fprintf(stderr,
478                                                 "Error searching for extended attributes: %d\n",
479                                                 ret);
480                                         goto out;
481                                 } else if (ret) {
482                                         /* No more leaves to search */
483                                         ret = 0;
484                                         goto out;
485                                 }
486                                 leaf = path->nodes[0];
487                         } while (!leaf);
488                         continue;
489                 }
490
491                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
492                 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
493                         break;
494                 cur = 0;
495                 total_len = btrfs_item_size_nr(leaf, path->slots[0]);
496                 di = btrfs_item_ptr(leaf, path->slots[0],
497                                     struct btrfs_dir_item);
498
499                 while (cur < total_len) {
500                         len = btrfs_dir_name_len(leaf, di);
501                         if (len > name_len) {
502                                 free(name);
503                                 name = (char *) malloc(len + 1);
504                                 if (!name) {
505                                         ret = -ENOMEM;
506                                         goto out;
507                                 }
508                         }
509                         read_extent_buffer(leaf, name,
510                                            (unsigned long)(di + 1), len);
511                         name[len] = '\0';
512                         name_len = len;
513
514                         len = btrfs_dir_data_len(leaf, di);
515                         if (len > data_len) {
516                                 free(data);
517                                 data = (char *) malloc(len);
518                                 if (!data) {
519                                         ret = -ENOMEM;
520                                         goto out;
521                                 }
522                         }
523                         read_extent_buffer(leaf, data,
524                                            (unsigned long)(di + 1) + name_len,
525                                            len);
526                         data_len = len;
527
528                         if (fsetxattr(fd, name, data, data_len, 0)) {
529                                 int err = errno;
530
531                                 fprintf(stderr,
532                                         "Error setting extended attribute %s on file %s: %s\n",
533                                         name, file_name, strerror(err));
534                         }
535
536                         len = sizeof(*di) + name_len + data_len;
537                         cur += len;
538                         di = (struct btrfs_dir_item *)((char *)di + len);
539                 }
540                 path->slots[0]++;
541         }
542         ret = 0;
543 out:
544         btrfs_free_path(path);
545         free(name);
546         free(data);
547
548         return ret;
549 }
550
551
552 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
553                      const char *file)
554 {
555         struct extent_buffer *leaf;
556         struct btrfs_path *path;
557         struct btrfs_file_extent_item *fi;
558         struct btrfs_inode_item *inode_item;
559         struct btrfs_key found_key;
560         int ret;
561         int extent_type;
562         int compression;
563         int loops = 0;
564         u64 found_size = 0;
565
566         path = btrfs_alloc_path();
567         if (!path) {
568                 fprintf(stderr, "Ran out of memory\n");
569                 return -ENOMEM;
570         }
571
572         ret = btrfs_lookup_inode(NULL, root, path, key, 0);
573         if (ret == 0) {
574                 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
575                                     struct btrfs_inode_item);
576                 found_size = btrfs_inode_size(path->nodes[0], inode_item);
577         }
578         btrfs_release_path(path);
579
580         key->offset = 0;
581         key->type = BTRFS_EXTENT_DATA_KEY;
582
583         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
584         if (ret < 0) {
585                 fprintf(stderr, "Error searching %d\n", ret);
586                 btrfs_free_path(path);
587                 return ret;
588         }
589
590         leaf = path->nodes[0];
591         while (!leaf) {
592                 ret = next_leaf(root, path);
593                 if (ret < 0) {
594                         fprintf(stderr, "Error getting next leaf %d\n",
595                                 ret);
596                         btrfs_free_path(path);
597                         return ret;
598                 } else if (ret > 0) {
599                         /* No more leaves to search */
600                         btrfs_free_path(path);
601                         return 0;
602                 }
603                 leaf = path->nodes[0];
604         }
605
606         while (1) {
607                 if (loops >= 0 && loops++ >= 1024) {
608                         enum loop_response resp;
609
610                         resp = ask_to_continue(file);
611                         if (resp == LOOP_STOP)
612                                 break;
613                         else if (resp == LOOP_CONTINUE)
614                                 loops = 0;
615                         else if (resp == LOOP_DONTASK)
616                                 loops = -1;
617                 }
618                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
619                         do {
620                                 ret = next_leaf(root, path);
621                                 if (ret < 0) {
622                                         fprintf(stderr, "Error searching %d\n", ret);
623                                         btrfs_free_path(path);
624                                         return ret;
625                                 } else if (ret) {
626                                         /* No more leaves to search */
627                                         btrfs_free_path(path);
628                                         goto set_size;
629                                 }
630                                 leaf = path->nodes[0];
631                         } while (!leaf);
632                         continue;
633                 }
634                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
635                 if (found_key.objectid != key->objectid)
636                         break;
637                 if (found_key.type != key->type)
638                         break;
639                 fi = btrfs_item_ptr(leaf, path->slots[0],
640                                     struct btrfs_file_extent_item);
641                 extent_type = btrfs_file_extent_type(leaf, fi);
642                 compression = btrfs_file_extent_compression(leaf, fi);
643                 if (compression >= BTRFS_COMPRESS_LAST) {
644                         fprintf(stderr, "Don't support compression yet %d\n",
645                                 compression);
646                         btrfs_free_path(path);
647                         return -1;
648                 }
649
650                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
651                         goto next;
652                 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
653                         ret = copy_one_inline(fd, path, found_key.offset);
654                         if (ret) {
655                                 btrfs_free_path(path);
656                                 return -1;
657                         }
658                 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
659                         ret = copy_one_extent(root, fd, leaf, fi,
660                                               found_key.offset);
661                         if (ret) {
662                                 btrfs_free_path(path);
663                                 return ret;
664                         }
665                 } else {
666                         printf("Weird extent type %d\n", extent_type);
667                 }
668 next:
669                 path->slots[0]++;
670         }
671
672         btrfs_free_path(path);
673 set_size:
674         if (found_size) {
675                 ret = ftruncate(fd, (loff_t)found_size);
676                 if (ret)
677                         return ret;
678         }
679         if (get_xattrs) {
680                 ret = set_file_xattrs(root, key->objectid, fd, file);
681                 if (ret)
682                         return ret;
683         }
684         return 0;
685 }
686
687 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
688                       const char *output_rootdir, const char *in_dir,
689                       const regex_t *mreg)
690 {
691         struct btrfs_path *path;
692         struct extent_buffer *leaf;
693         struct btrfs_dir_item *dir_item;
694         struct btrfs_key found_key, location;
695         char filename[BTRFS_NAME_LEN + 1];
696         unsigned long name_ptr;
697         int name_len;
698         int ret;
699         int fd;
700         int loops = 0;
701         u8 type;
702
703         path = btrfs_alloc_path();
704         if (!path) {
705                 fprintf(stderr, "Ran out of memory\n");
706                 return -ENOMEM;
707         }
708
709         key->offset = 0;
710         key->type = BTRFS_DIR_INDEX_KEY;
711
712         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
713         if (ret < 0) {
714                 fprintf(stderr, "Error searching %d\n", ret);
715                 btrfs_free_path(path);
716                 return ret;
717         }
718
719         leaf = path->nodes[0];
720         while (!leaf) {
721                 if (verbose > 1)
722                         printf("No leaf after search, looking for the next "
723                                "leaf\n");
724                 ret = next_leaf(root, path);
725                 if (ret < 0) {
726                         fprintf(stderr, "Error getting next leaf %d\n",
727                                 ret);
728                         btrfs_free_path(path);
729                         return ret;
730                 } else if (ret > 0) {
731                         /* No more leaves to search */
732                         if (verbose)
733                                 printf("Reached the end of the tree looking "
734                                        "for the directory\n");
735                         btrfs_free_path(path);
736                         return 0;
737                 }
738                 leaf = path->nodes[0];
739         }
740
741         while (leaf) {
742                 if (loops++ >= 1024) {
743                         printf("We have looped trying to restore files in %s "
744                                "too many times to be making progress, "
745                                "stopping\n", in_dir);
746                         break;
747                 }
748
749                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
750                         do {
751                                 ret = next_leaf(root, path);
752                                 if (ret < 0) {
753                                         fprintf(stderr, "Error searching %d\n",
754                                                 ret);
755                                         btrfs_free_path(path);
756                                         return ret;
757                                 } else if (ret > 0) {
758                                         /* No more leaves to search */
759                                         if (verbose)
760                                                 printf("Reached the end of "
761                                                        "the tree searching the"
762                                                        " directory\n");
763                                         btrfs_free_path(path);
764                                         return 0;
765                                 }
766                                 leaf = path->nodes[0];
767                         } while (!leaf);
768                         continue;
769                 }
770                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
771                 if (found_key.objectid != key->objectid) {
772                         if (verbose > 1)
773                                 printf("Found objectid=%Lu, key=%Lu\n",
774                                        found_key.objectid, key->objectid);
775                         break;
776                 }
777                 if (found_key.type != key->type) {
778                         if (verbose > 1)
779                                 printf("Found type=%u, want=%u\n",
780                                        found_key.type, key->type);
781                         break;
782                 }
783                 dir_item = btrfs_item_ptr(leaf, path->slots[0],
784                                           struct btrfs_dir_item);
785                 name_ptr = (unsigned long)(dir_item + 1);
786                 name_len = btrfs_dir_name_len(leaf, dir_item);
787                 read_extent_buffer(leaf, filename, name_ptr, name_len);
788                 filename[name_len] = '\0';
789                 type = btrfs_dir_type(leaf, dir_item);
790                 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
791
792                 /* full path from root of btrfs being restored */
793                 snprintf(fs_name, 4096, "%s/%s", in_dir, filename);
794
795                 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
796                         goto next;
797
798                 /* full path from system root */
799                 snprintf(path_name, 4096, "%s%s", output_rootdir, fs_name);
800
801                 /*
802                  * At this point we're only going to restore directories and
803                  * files, no symlinks or anything else.
804                  */
805                 if (type == BTRFS_FT_REG_FILE) {
806                         if (!overwrite) {
807                                 static int warn = 0;
808                                 struct stat st;
809
810                                 ret = stat(path_name, &st);
811                                 if (!ret) {
812                                         loops = 0;
813                                         if (verbose || !warn)
814                                                 printf("Skipping existing file"
815                                                        " %s\n", path_name);
816                                         if (warn)
817                                                 goto next;
818                                         printf("If you wish to overwrite use "
819                                                "the -o option to overwrite\n");
820                                         warn = 1;
821                                         goto next;
822                                 }
823                                 ret = 0;
824                         }
825                         if (verbose)
826                                 printf("Restoring %s\n", path_name);
827                         if (dry_run)
828                                 goto next;
829                         fd = open(path_name, O_CREAT|O_WRONLY, 0644);
830                         if (fd < 0) {
831                                 fprintf(stderr, "Error creating %s: %d\n",
832                                         path_name, errno);
833                                 if (ignore_errors)
834                                         goto next;
835                                 btrfs_free_path(path);
836                                 return -1;
837                         }
838                         loops = 0;
839                         ret = copy_file(root, fd, &location, path_name);
840                         close(fd);
841                         if (ret) {
842                                 if (ignore_errors)
843                                         goto next;
844                                 btrfs_free_path(path);
845                                 return ret;
846                         }
847                 } else if (type == BTRFS_FT_DIR) {
848                         struct btrfs_root *search_root = root;
849                         char *dir = strdup(fs_name);
850
851                         if (!dir) {
852                                 fprintf(stderr, "Ran out of memory\n");
853                                 btrfs_free_path(path);
854                                 return -ENOMEM;
855                         }
856
857                         if (location.type == BTRFS_ROOT_ITEM_KEY) {
858                                 /*
859                                  * If we are a snapshot and this is the index
860                                  * object to ourselves just skip it.
861                                  */
862                                 if (location.objectid ==
863                                     root->root_key.objectid) {
864                                         free(dir);
865                                         goto next;
866                                 }
867
868                                 location.offset = (u64)-1;
869                                 search_root = btrfs_read_fs_root(root->fs_info,
870                                                                  &location);
871                                 if (IS_ERR(search_root)) {
872                                         free(dir);
873                                         fprintf(stderr, "Error reading "
874                                                 "subvolume %s: %lu\n",
875                                                 path_name,
876                                                 PTR_ERR(search_root));
877                                         if (ignore_errors)
878                                                 goto next;
879                                         btrfs_free_path(path);
880                                         return PTR_ERR(search_root);
881                                 }
882
883                                 /*
884                                  * A subvolume will have a key.offset of 0, a
885                                  * snapshot will have key.offset of a transid.
886                                  */
887                                 if (search_root->root_key.offset != 0 &&
888                                     get_snaps == 0) {
889                                         free(dir);
890                                         printf("Skipping snapshot %s\n",
891                                                filename);
892                                         goto next;
893                                 }
894                                 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
895                         }
896
897                         if (verbose)
898                                 printf("Restoring %s\n", path_name);
899
900                         errno = 0;
901                         if (dry_run)
902                                 ret = 0;
903                         else
904                                 ret = mkdir(path_name, 0755);
905                         if (ret && errno != EEXIST) {
906                                 free(dir);
907                                 fprintf(stderr, "Error mkdiring %s: %d\n",
908                                         path_name, errno);
909                                 if (ignore_errors)
910                                         goto next;
911                                 btrfs_free_path(path);
912                                 return -1;
913                         }
914                         loops = 0;
915                         ret = search_dir(search_root, &location,
916                                          output_rootdir, dir, mreg);
917                         free(dir);
918                         if (ret) {
919                                 if (ignore_errors)
920                                         goto next;
921                                 btrfs_free_path(path);
922                                 return ret;
923                         }
924                 }
925 next:
926                 path->slots[0]++;
927         }
928
929         if (verbose)
930                 printf("Done searching %s\n", in_dir);
931         btrfs_free_path(path);
932         return 0;
933 }
934
935 static int do_list_roots(struct btrfs_root *root)
936 {
937         struct btrfs_key key;
938         struct btrfs_key found_key;
939         struct btrfs_disk_key disk_key;
940         struct btrfs_path *path;
941         struct extent_buffer *leaf;
942         struct btrfs_root_item ri;
943         unsigned long offset;
944         int slot;
945         int ret;
946
947         root = root->fs_info->tree_root;
948         path = btrfs_alloc_path();
949         if (!path) {
950                 fprintf(stderr, "Failed to alloc path\n");
951                 return -ENOMEM;
952         }
953
954         key.offset = 0;
955         key.objectid = 0;
956         key.type = BTRFS_ROOT_ITEM_KEY;
957
958         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
959         if (ret < 0) {
960                 fprintf(stderr, "Failed to do search %d\n", ret);
961                 btrfs_free_path(path);
962                 return -1;
963         }
964
965         while (1) {
966                 leaf = path->nodes[0];
967                 slot = path->slots[0];
968                 if (slot >= btrfs_header_nritems(leaf)) {
969                         ret = btrfs_next_leaf(root, path);
970                         if (ret)
971                                 break;
972                         leaf = path->nodes[0];
973                         slot = path->slots[0];
974                 }
975                 btrfs_item_key(leaf, &disk_key, slot);
976                 btrfs_disk_key_to_cpu(&found_key, &disk_key);
977                 if (btrfs_key_type(&found_key) != BTRFS_ROOT_ITEM_KEY) {
978                         path->slots[0]++;
979                         continue;
980                 }
981
982                 offset = btrfs_item_ptr_offset(leaf, slot);
983                 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
984                 printf(" tree ");
985                 btrfs_print_key(&disk_key);
986                 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
987                        btrfs_root_level(&ri));
988                 path->slots[0]++;
989         }
990         btrfs_free_path(path);
991
992         return 0;
993 }
994
995 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
996                                   int super_mirror, int list_roots)
997 {
998         struct btrfs_fs_info *fs_info = NULL;
999         struct btrfs_root *root = NULL;
1000         u64 bytenr;
1001         int i;
1002
1003         for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1004                 bytenr = btrfs_sb_offset(i);
1005                 fs_info = open_ctree_fs_info(dev, bytenr, root_location,
1006                                              OPEN_CTREE_PARTIAL);
1007                 if (fs_info)
1008                         break;
1009                 fprintf(stderr, "Could not open root, trying backup super\n");
1010         }
1011
1012         if (!fs_info)
1013                 return NULL;
1014
1015         /*
1016          * All we really need to succeed is reading the chunk tree, everything
1017          * else we can do by hand, since we only need to read the tree root and
1018          * the fs_root.
1019          */
1020         if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1021                 u64 generation;
1022
1023                 root = fs_info->tree_root;
1024                 if (!root_location)
1025                         root_location = btrfs_super_root(fs_info->super_copy);
1026                 generation = btrfs_super_generation(fs_info->super_copy);
1027                 root->node = read_tree_block(root, root_location,
1028                                              root->leafsize, generation);
1029                 if (!extent_buffer_uptodate(root->node)) {
1030                         fprintf(stderr, "Error opening tree root\n");
1031                         close_ctree(root);
1032                         return NULL;
1033                 }
1034         }
1035
1036         if (!list_roots && !fs_info->fs_root) {
1037                 struct btrfs_key key;
1038
1039                 key.objectid = BTRFS_FS_TREE_OBJECTID;
1040                 key.type = BTRFS_ROOT_ITEM_KEY;
1041                 key.offset = (u64)-1;
1042                 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1043                 if (IS_ERR(fs_info->fs_root)) {
1044                         fprintf(stderr, "Couldn't read fs root: %ld\n",
1045                                 PTR_ERR(fs_info->fs_root));
1046                         close_ctree(fs_info->tree_root);
1047                         return NULL;
1048                 }
1049         }
1050
1051         if (list_roots && do_list_roots(fs_info->tree_root)) {
1052                 close_ctree(fs_info->tree_root);
1053                 return NULL;
1054         }
1055
1056         return fs_info->fs_root;
1057 }
1058
1059 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1060 {
1061         struct btrfs_path *path;
1062         struct btrfs_key found_key;
1063         struct btrfs_key key;
1064         int ret = -1;
1065         int i;
1066
1067         key.objectid = 0;
1068         key.type = BTRFS_DIR_INDEX_KEY;
1069         key.offset = 0;
1070
1071         path = btrfs_alloc_path();
1072         if (!path) {
1073                 fprintf(stderr, "Ran out of memory\n");
1074                 return ret;
1075         }
1076
1077         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1078         if (ret < 0) {
1079                 fprintf(stderr, "Error searching %d\n", ret);
1080                 goto out;
1081         }
1082
1083         if (!path->nodes[0]) {
1084                 fprintf(stderr, "No leaf!\n");
1085                 goto out;
1086         }
1087 again:
1088         for (i = path->slots[0];
1089              i < btrfs_header_nritems(path->nodes[0]); i++) {
1090                 btrfs_item_key_to_cpu(path->nodes[0], &found_key, i);
1091                 if (found_key.type != key.type)
1092                         continue;
1093
1094                 printf("Using objectid %Lu for first dir\n",
1095                        found_key.objectid);
1096                 *objectid = found_key.objectid;
1097                 ret = 0;
1098                 goto out;
1099         }
1100         do {
1101                 ret = next_leaf(root, path);
1102                 if (ret < 0) {
1103                         fprintf(stderr, "Error getting next leaf %d\n",
1104                                 ret);
1105                         goto out;
1106                 } else if (ret > 0) {
1107                         fprintf(stderr, "No more leaves\n");
1108                         goto out;
1109                 }
1110         } while (!path->nodes[0]);
1111         if (path->nodes[0])
1112                 goto again;
1113         printf("Couldn't find a dir index item\n");
1114 out:
1115         btrfs_free_path(path);
1116         return ret;
1117 }
1118
1119 static struct option long_options[] = {
1120         { "path-regex", 1, NULL, 256},
1121         { "dry-run", 0, NULL, 'D'},
1122         { NULL, 0, NULL, 0}
1123 };
1124
1125 const char * const cmd_restore_usage[] = {
1126         "btrfs restore [options] <device> <path> | -l <device>",
1127         "Try to restore files from a damaged filesystem (unmounted)",
1128         "",
1129         "-s              get snapshots",
1130         "-x              get extended attributes",
1131         "-v              verbose",
1132         "-i              ignore errors",
1133         "-o              overwrite",
1134         "-t <bytenr>     tree location",
1135         "-f <bytenr>     filesystem location",
1136         "-u <mirror>     super mirror",
1137         "-r <rootid>     root objectid",
1138         "-d              find dir",
1139         "-l              list tree roots",
1140         "-D|--dry-run    dry run (only list files that would be recovered)",
1141         "--path-regex <regex>",
1142         "                restore only filenames matching regex,",
1143         "                you have to use following syntax (possibly quoted):",
1144         "                ^/(|home(|/username(|/Desktop(|/.*))))$",
1145         "-c              ignore case (--path-regrex only)",
1146         NULL
1147 };
1148
1149 int cmd_restore(int argc, char **argv)
1150 {
1151         struct btrfs_root *root;
1152         struct btrfs_key key;
1153         char dir_name[128];
1154         u64 tree_location = 0;
1155         u64 fs_location = 0;
1156         u64 root_objectid = 0;
1157         int len;
1158         int ret;
1159         int opt;
1160         int option_index = 0;
1161         int super_mirror = 0;
1162         int find_dir = 0;
1163         int list_roots = 0;
1164         const char *match_regstr = NULL;
1165         int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1166         regex_t match_reg, *mreg = NULL;
1167         char reg_err[256];
1168
1169         while ((opt = getopt_long(argc, argv, "sxviot:u:df:r:lDc", long_options,
1170                                         &option_index)) != -1) {
1171
1172                 switch (opt) {
1173                         case 's':
1174                                 get_snaps = 1;
1175                                 break;
1176                         case 'v':
1177                                 verbose++;
1178                                 break;
1179                         case 'i':
1180                                 ignore_errors = 1;
1181                                 break;
1182                         case 'o':
1183                                 overwrite = 1;
1184                                 break;
1185                         case 't':
1186                                 tree_location = arg_strtou64(optarg);
1187                                 break;
1188                         case 'f':
1189                                 fs_location = arg_strtou64(optarg);
1190                                 break;
1191                         case 'u':
1192                                 super_mirror = arg_strtou64(optarg);
1193                                 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1194                                         fprintf(stderr, "Super mirror not "
1195                                                 "valid\n");
1196                                         exit(1);
1197                                 }
1198                                 break;
1199                         case 'd':
1200                                 find_dir = 1;
1201                                 break;
1202                         case 'r':
1203                                 root_objectid = arg_strtou64(optarg);
1204                                 if (!is_fstree(root_objectid)) {
1205                                         fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1206                                                         root_objectid);
1207                                         exit(1);
1208                                 }
1209                                 break;
1210                         case 'l':
1211                                 list_roots = 1;
1212                                 break;
1213                         case 'D':
1214                                 dry_run = 1;
1215                                 break;
1216                         case 'c':
1217                                 match_cflags |= REG_ICASE;
1218                                 break;
1219                         /* long option without single letter alternative */
1220                         case 256:
1221                                 match_regstr = optarg;
1222                                 break;
1223                         case 'x':
1224                                 get_xattrs = 1;
1225                                 break;
1226                         default:
1227                                 usage(cmd_restore_usage);
1228                 }
1229         }
1230
1231         set_argv0(argv);
1232         if (!list_roots && check_argc_min(argc - optind, 2))
1233                 usage(cmd_restore_usage);
1234         else if (list_roots && check_argc_min(argc - optind, 1))
1235                 usage(cmd_restore_usage);
1236
1237         if (fs_location && root_objectid) {
1238                 fprintf(stderr, "don't use -f and -r at the same time.\n");
1239                 return 1;
1240         }
1241
1242         if ((ret = check_mounted(argv[optind])) < 0) {
1243                 fprintf(stderr, "Could not check mount status: %s\n",
1244                         strerror(-ret));
1245                 return 1;
1246         } else if (ret) {
1247                 fprintf(stderr, "%s is currently mounted.  Aborting.\n", argv[optind]);
1248                 return 1;
1249         }
1250
1251         root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1252         if (root == NULL)
1253                 return 1;
1254
1255         if (list_roots)
1256                 goto out;
1257
1258         if (fs_location != 0) {
1259                 free_extent_buffer(root->node);
1260                 root->node = read_tree_block(root, fs_location, root->leafsize, 0);
1261                 if (!root->node) {
1262                         fprintf(stderr, "Failed to read fs location\n");
1263                         ret = 1;
1264                         goto out;
1265                 }
1266         }
1267
1268         memset(path_name, 0, 4096);
1269
1270         strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1271         dir_name[sizeof dir_name - 1] = 0;
1272
1273         /* Strip the trailing / on the dir name */
1274         len = strlen(dir_name);
1275         while (len && dir_name[--len] == '/') {
1276                 dir_name[len] = '\0';
1277         }
1278
1279         if (root_objectid != 0) {
1280                 struct btrfs_root *orig_root = root;
1281
1282                 key.objectid = root_objectid;
1283                 key.type = BTRFS_ROOT_ITEM_KEY;
1284                 key.offset = (u64)-1;
1285                 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1286                 if (IS_ERR(root)) {
1287                         fprintf(stderr, "fail to read root %llu: %s\n",
1288                                         root_objectid, strerror(-PTR_ERR(root)));
1289                         root = orig_root;
1290                         ret = 1;
1291                         goto out;
1292                 }
1293                 key.type = 0;
1294                 key.offset = 0;
1295         }
1296
1297         if (find_dir) {
1298                 ret = find_first_dir(root, &key.objectid);
1299                 if (ret)
1300                         goto out;
1301         } else {
1302                 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1303         }
1304
1305         if (match_regstr) {
1306                 ret = regcomp(&match_reg, match_regstr, match_cflags);
1307                 if (ret) {
1308                         regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1309                         fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1310                         goto out;
1311                 }
1312                 mreg = &match_reg;
1313         }
1314
1315         if (dry_run)
1316                 printf("This is a dry-run, no files are going to be restored\n");
1317
1318         ret = search_dir(root, &key, dir_name, "", mreg);
1319
1320 out:
1321         if (mreg)
1322                 regfree(mreg);
1323         close_ctree(root);
1324         return !!ret;
1325 }