1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "ext4_utils/ext4_utils.h"
18 
19 #include <fcntl.h>
20 #include <inttypes.h>
21 #include <stddef.h>
22 #include <string.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 
26 #ifdef _WIN32
27 #include <winsock2.h>
28 #else
29 #include <arpa/inet.h>
30 #include <sys/ioctl.h>
31 #endif
32 
33 #if defined(__linux__)
34 #include <linux/fs.h>
35 #elif defined(__APPLE__) && defined(__MACH__)
36 #include <sys/disk.h>
37 #endif
38 
39 #include "helpers.h"
40 
41 int force = 0;
42 struct fs_info info;
43 struct fs_aux_info aux_info;
44 
45 jmp_buf setjmp_env;
46 
47 /* returns 1 if a is a power of b */
is_power_of(int a,int b)48 static int is_power_of(int a, int b) {
49     while (a > b) {
50         if (a % b) return 0;
51         a /= b;
52     }
53 
54     return (a == b) ? 1 : 0;
55 }
56 
bitmap_get_bit(u8 * bitmap,u32 bit)57 int bitmap_get_bit(u8* bitmap, u32 bit) {
58     if (bitmap[bit / 8] & (1 << (bit % 8))) return 1;
59 
60     return 0;
61 }
62 
bitmap_clear_bit(u8 * bitmap,u32 bit)63 void bitmap_clear_bit(u8* bitmap, u32 bit) {
64     bitmap[bit / 8] &= ~(1 << (bit % 8));
65 
66     return;
67 }
68 
69 /* Returns 1 if the bg contains a backup superblock.  On filesystems with
70    the sparse_super feature, only block groups 0, 1, and powers of 3, 5,
71    and 7 have backup superblocks.  Otherwise, all block groups have backup
72    superblocks */
ext4_bg_has_super_block(int bg)73 int ext4_bg_has_super_block(int bg) {
74     /* Without sparse_super, every block group has a superblock */
75     if (!(info.feat_ro_compat & EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER)) return 1;
76 
77     if (bg == 0 || bg == 1) return 1;
78 
79     if (is_power_of(bg, 3) || is_power_of(bg, 5) || is_power_of(bg, 7)) return 1;
80 
81     return 0;
82 }
83 
84 /* Function to read the primary superblock */
read_sb(int fd,struct ext4_super_block * sb)85 void read_sb(int fd, struct ext4_super_block* sb) {
86     off64_t ret;
87 
88     ret = lseek64(fd, 1024, SEEK_SET);
89     if (ret < 0) critical_error_errno("failed to seek to superblock");
90 
91     ret = read(fd, sb, sizeof(*sb));
92     if (ret < 0) critical_error_errno("failed to read superblock");
93     if (ret != sizeof(*sb)) critical_error("failed to read all of superblock");
94 }
95 
96 /* Compute the rest of the parameters of the filesystem from the basic info */
ext4_create_fs_aux_info()97 void ext4_create_fs_aux_info() {
98     aux_info.first_data_block = (info.block_size > 1024) ? 0 : 1;
99     aux_info.len_blocks = info.len / info.block_size;
100     aux_info.inode_table_blocks =
101             DIV_ROUND_UP(info.inodes_per_group * info.inode_size, info.block_size);
102     aux_info.groups =
103             DIV_ROUND_UP(aux_info.len_blocks - aux_info.first_data_block, info.blocks_per_group);
104     aux_info.blocks_per_ind = info.block_size / sizeof(u32);
105     aux_info.blocks_per_dind = aux_info.blocks_per_ind * aux_info.blocks_per_ind;
106     aux_info.blocks_per_tind = aux_info.blocks_per_dind * aux_info.blocks_per_dind;
107 
108     aux_info.bg_desc_blocks =
109             DIV_ROUND_UP(aux_info.groups * (size_t)info.bg_desc_size, info.block_size);
110 
111     aux_info.default_i_flags = EXT4_NOATIME_FL;
112 
113     u32 last_group_size = aux_info.len_blocks == info.blocks_per_group
114                                   ? aux_info.len_blocks
115                                   : aux_info.len_blocks % info.blocks_per_group;
116     u32 last_header_size = 2 + aux_info.inode_table_blocks;
117     if (ext4_bg_has_super_block((int)aux_info.groups - 1))
118         last_header_size += 1 + aux_info.bg_desc_blocks + info.bg_desc_reserve_blocks;
119     if (aux_info.groups <= 1 && last_group_size < last_header_size) {
120         critical_error("filesystem size too small");
121     }
122     if (last_group_size > 0 && last_group_size < last_header_size) {
123         aux_info.groups--;
124         aux_info.len_blocks -= last_group_size;
125     }
126 
127     /* A zero-filled superblock to be written firstly to the block
128      * device to mark the file-system as invalid
129      */
130     aux_info.sb_zero = (struct ext4_super_block*)calloc(1, info.block_size);
131     if (!aux_info.sb_zero) critical_error_errno("calloc");
132 
133     /* The write_data* functions expect only block aligned calls.
134      * This is not an issue, except when we write out the super
135      * block on a system with a block size > 1K.  So, we need to
136      * deal with that here.
137      */
138     aux_info.sb_block = (struct ext4_super_block*)calloc(1, info.block_size);
139     if (!aux_info.sb_block) critical_error_errno("calloc");
140 
141     if (info.block_size > 1024)
142         aux_info.sb = (struct ext4_super_block*)((char*)aux_info.sb_block + 1024);
143     else
144         aux_info.sb = aux_info.sb_block;
145 
146     /* Alloc an array to hold the pointers to the backup superblocks */
147     aux_info.backup_sb = (struct ext4_super_block**)calloc(aux_info.groups, sizeof(char*));
148 
149     if (!aux_info.sb) critical_error_errno("calloc");
150 
151     aux_info.bg_desc =
152             (struct ext2_group_desc*)calloc(aux_info.groups, sizeof(struct ext2_group_desc));
153     if (!aux_info.bg_desc) critical_error_errno("calloc");
154     aux_info.xattrs = NULL;
155 }
156 
ext4_free_fs_aux_info()157 void ext4_free_fs_aux_info() {
158     unsigned int i;
159 
160     for (i = 0; i < aux_info.groups; i++) {
161         if (aux_info.backup_sb[i]) free(aux_info.backup_sb[i]);
162     }
163     free(aux_info.sb_block);
164     free(aux_info.sb_zero);
165     free(aux_info.bg_desc);
166 }
167 
ext4_parse_sb_info(struct ext4_super_block * sb)168 void ext4_parse_sb_info(struct ext4_super_block* sb) {
169     if (sb->s_magic != EXT4_SUPER_MAGIC) error("superblock magic incorrect");
170 
171     if ((sb->s_state & EXT4_VALID_FS) != EXT4_VALID_FS) error("filesystem state not valid");
172 
173     ext4_parse_sb(sb, &info);
174 
175     ext4_create_fs_aux_info();
176 
177     memcpy(aux_info.sb, sb, sizeof(*sb));
178 
179     if (aux_info.first_data_block != sb->s_first_data_block)
180         critical_error("first data block does not match");
181 }
182 
get_block_device_size(int fd)183 u64 get_block_device_size(int fd) {
184     u64 size = 0;
185     int ret;
186 
187 #if defined(__linux__)
188     ret = ioctl(fd, BLKGETSIZE64, &size);
189 #elif defined(__APPLE__) && defined(__MACH__)
190     ret = ioctl(fd, DKIOCGETBLOCKCOUNT, &size);
191 #else
192     close(fd);
193     return 0;
194 #endif
195 
196     if (ret) return 0;
197 
198     return size;
199 }
200 
is_block_device_fd(int fd)201 int is_block_device_fd(int fd __attribute__((unused))) {
202 #ifdef _WIN32
203     return 0;
204 #else
205     struct stat st;
206     int ret = fstat(fd, &st);
207     if (ret < 0) return 0;
208 
209     return S_ISBLK(st.st_mode);
210 #endif
211 }
212 
get_file_size(int fd)213 u64 get_file_size(int fd) {
214     struct stat buf;
215     int ret;
216     u64 reserve_len = 0;
217     s64 computed_size;
218 
219     ret = fstat(fd, &buf);
220     if (ret) return 0;
221 
222     if (info.len < 0) reserve_len = -info.len;
223 
224     if (S_ISREG(buf.st_mode))
225         computed_size = buf.st_size - reserve_len;
226     else if (S_ISBLK(buf.st_mode))
227         computed_size = get_block_device_size(fd) - reserve_len;
228     else
229         computed_size = 0;
230 
231     if (computed_size < 0) {
232         warn("Computed filesystem size less than 0");
233         computed_size = 0;
234     }
235 
236     return computed_size;
237 }
238 
read_block_group_descriptors(int fd)239 static void read_block_group_descriptors(int fd) {
240     size_t size = info.block_size * (size_t)aux_info.bg_desc_blocks;
241     void* buf = malloc(size);
242     ssize_t ret;
243 
244     if (!buf) critical_error("failed to alloc buffer");
245 
246     ret = read(fd, buf, size);
247     if (ret < 0) {
248         free(buf);
249         critical_error_errno("failed to read block group descriptors");
250     }
251     if (ret != size) {
252         free(buf);
253         critical_error("failed to read all the block group descriptors");
254     }
255     const struct ext4_group_desc* gdp = (const struct ext4_group_desc*)buf;
256     bool extended = (info.bg_desc_size >= EXT4_MIN_DESC_SIZE_64BIT);
257     for (size_t i = 0; i < aux_info.groups; i++) {
258         aux_info.bg_desc[i].bg_block_bitmap =
259                 (extended ? (u64)gdp->bg_block_bitmap_hi << 32 : 0) | gdp->bg_block_bitmap_lo;
260         aux_info.bg_desc[i].bg_inode_bitmap =
261                 (extended ? (u64)gdp->bg_inode_bitmap_hi << 32 : 0) | gdp->bg_inode_bitmap_lo;
262         aux_info.bg_desc[i].bg_inode_table =
263                 (extended ? (u64)gdp->bg_inode_table_hi << 32 : 0) | gdp->bg_inode_table_lo;
264         aux_info.bg_desc[i].bg_free_blocks_count =
265                 (extended ? (u32)gdp->bg_free_blocks_count_hi << 16 : 0) |
266                 gdp->bg_free_blocks_count_lo;
267         aux_info.bg_desc[i].bg_free_inodes_count =
268                 (extended ? (u32)gdp->bg_free_inodes_count_hi << 16 : 0) |
269                 gdp->bg_free_inodes_count_lo;
270         aux_info.bg_desc[i].bg_used_dirs_count =
271                 (extended ? (u32)gdp->bg_used_dirs_count_hi << 16 : 0) | gdp->bg_used_dirs_count_lo;
272         aux_info.bg_desc[i].bg_flags = gdp->bg_flags;
273         gdp = (const struct ext4_group_desc*)((u8*)gdp + info.bg_desc_size);
274     }
275     free(buf);
276 }
277 
read_ext(int fd,int verbose)278 int read_ext(int fd, int verbose) {
279     off64_t ret;
280     struct ext4_super_block sb;
281 
282     read_sb(fd, &sb);
283 
284     ext4_parse_sb_info(&sb);
285 
286     ret = lseek64(fd, info.len, SEEK_SET);
287     if (ret < 0) critical_error_errno("failed to seek to end of input image");
288 
289     ret = lseek64(fd, info.block_size * (aux_info.first_data_block + 1), SEEK_SET);
290     if (ret < 0) critical_error_errno("failed to seek to block group descriptors");
291 
292     read_block_group_descriptors(fd);
293 
294     if (verbose) {
295         printf("Found filesystem with parameters:\n");
296         printf("    Size: %" PRIu64 "\n", info.len);
297         printf("    Block size: %d\n", info.block_size);
298         printf("    Blocks per group: %d\n", info.blocks_per_group);
299         printf("    Inodes per group: %d\n", info.inodes_per_group);
300         printf("    Inode size: %d\n", info.inode_size);
301         printf("    Label: %s\n", info.label);
302         printf("    Blocks: %" PRIext4u64 "\n", aux_info.len_blocks);
303         printf("    Block groups: %d\n", aux_info.groups);
304         printf("    Reserved block group size: %d\n", info.bg_desc_reserve_blocks);
305         printf("    Block group descriptor size: %d\n", info.bg_desc_size);
306         printf("    Used %d/%d inodes and %d/%d blocks\n",
307                aux_info.sb->s_inodes_count - aux_info.sb->s_free_inodes_count,
308                aux_info.sb->s_inodes_count,
309                aux_info.sb->s_blocks_count_lo - aux_info.sb->s_free_blocks_count_lo,
310                aux_info.sb->s_blocks_count_lo);
311     }
312 
313     return 0;
314 }
315