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