1 /*
2  *  GRUB  --  GRand Unified Bootloader
3  *  Copyright (C) 1999, 2001, 2003  Free Software Foundation, Inc.
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include <xenfsimage_grub.h>
20 
21 #define	mapblock1 (*fsig_int1(ffi))
22 #define	mapblock2 (*fsig_int2(ffi))
23 
24 /* sizes are always in bytes, BLOCK values are always in DEV_BSIZE (sectors) */
25 #define DEV_BSIZE 512
26 
27 /* include/linux/fs.h */
28 #define BLOCK_SIZE 1024		/* initial block size for superblock read */
29 /* made up, defaults to 1 but can be passed via mount_opts */
30 #define WHICH_SUPER 1
31 /* kind of from fs/ext2/super.c */
32 #define SBLOCK (WHICH_SUPER * BLOCK_SIZE / DEV_BSIZE)	/* = 2 */
33 
34 /* include/asm-i386/types.h */
35 typedef __signed__ char __s8;
36 typedef unsigned char __u8;
37 typedef __signed__ short __s16;
38 typedef unsigned short __u16;
39 typedef __signed__ int __s32;
40 typedef unsigned int __u32;
41 
42 /*
43  * Constants relative to the data blocks, from ext2_fs.h
44  */
45 #define EXT2_NDIR_BLOCKS                12
46 #define EXT2_IND_BLOCK                  EXT2_NDIR_BLOCKS
47 #define EXT2_DIND_BLOCK                 (EXT2_IND_BLOCK + 1)
48 #define EXT2_TIND_BLOCK                 (EXT2_DIND_BLOCK + 1)
49 #define EXT2_N_BLOCKS                   (EXT2_TIND_BLOCK + 1)
50 
51 /* Inode flags */
52 #define EXT4_EXTENTS_FL                 0x00080000 /* Inode uses extents */
53 
54 /* include/linux/ext2_fs.h */
55 struct ext2_super_block
56   {
57     __u32 s_inodes_count;	/* Inodes count */
58     __u32 s_blocks_count;	/* Blocks count */
59     __u32 s_r_blocks_count;	/* Reserved blocks count */
60     __u32 s_free_blocks_count;	/* Free blocks count */
61     __u32 s_free_inodes_count;	/* Free inodes count */
62     __u32 s_first_data_block;	/* First Data Block */
63     __u32 s_log_block_size;	/* Block size */
64     __s32 s_log_frag_size;	/* Fragment size */
65     __u32 s_blocks_per_group;	/* # Blocks per group */
66     __u32 s_frags_per_group;	/* # Fragments per group */
67     __u32 s_inodes_per_group;	/* # Inodes per group */
68     __u32 s_mtime;		/* Mount time */
69     __u32 s_wtime;		/* Write time */
70     __u16 s_mnt_count;		/* Mount count */
71     __s16 s_max_mnt_count;	/* Maximal mount count */
72     __u16 s_magic;		/* Magic signature */
73     __u16 s_state;		/* File system state */
74     __u16 s_errors;		/* Behaviour when detecting errors */
75     __u16 s_pad;
76     __u32 s_lastcheck;		/* time of last check */
77     __u32 s_checkinterval;	/* max. time between checks */
78     __u32 s_creator_os;		/* OS */
79     __u32 s_rev_level;		/* Revision level */
80     __u16 s_def_resuid;		/* Default uid for reserved blocks */
81     __u16 s_def_resgid;		/* Default gid for reserved blocks */
82     /*
83      * These fields are for EXT2_DYNAMIC_REV superblocks only.
84      *
85      * Note: the difference between the compatible feature set and
86      * the incompatible feature set is that if there is a bit set
87      * in the incompatible feature set that the kernel doesn't
88      * know about, it should refuse to mount the filesystem.
89      *
90      * e2fsck's requirements are more strict; if it doesn't know
91      * about a feature in either the compatible or incompatible
92      * feature set, it must abort and not try to meddle with
93      * things it doesn't understand...
94      */
95     __u32 s_first_ino;		/* First non-reserved inode */
96     __u16 s_inode_size;		/* size of inode structure */
97     __u16 s_block_group_nr;	/* block group # of this superblock */
98     __u32 s_feature_compat;	/* compatible feature set */
99     __u32 s_feature_incompat;	/* incompatible feature set */
100     __u32 s_feature_ro_compat;	/* readonly-compatible feature set */
101     __u8  s_uuid[16];		/* 128-bit uuid for volume */
102     char  s_volume_name[16];	/* volume name */
103     char  s_last_mounted[64];	/* directory where last mounted */
104     __u32 s_algorithm_usage_bitmap; /* For compression */
105     /*
106      * Performance hints.  Directory preallocation should only
107      * happen if the EXT2_FEATURE_COMPAT_DIR_PREALLOC flag is on.
108      */
109     __u8  s_prealloc_blocks;	/* Nr of blocks to try to preallocate*/
110     __u8  s_prealloc_dir_blocks;	/* Nr to preallocate for dirs */
111     __u16 s_reserved_gdt_blocks;/* Per group table for online growth */
112     /*
113      * Journaling support valid if EXT2_FEATURE_COMPAT_HAS_JOURNAL set.
114      */
115     __u8 s_journal_uuid[16];	/* uuid of journal superblock */
116     __u32 s_journal_inum;	/* inode number of journal file */
117     __u32 s_journal_dev;	/* device number of journal file */
118     __u32 s_last_orphan;	/* start of list of inodes to delete */
119     __u32 s_hash_seed[4];	/* HTREE hash seed */
120     __u8  s_def_hash_version;	/* Default hash version to use */
121     __u8  s_jnl_backup_type; 	/* Default type of journal backup */
122     __u16 s_reserved_word_pad;
123     __u32 s_default_mount_opts;
124     __u32 s_first_meta_bg;	/* First metablock group */
125     __u32 s_mkfs_time;		/* When the filesystem was created */
126     __u32 s_jnl_blocks[17]; 	/* Backup of the journal inode */
127     __u32 s_reserved[172];	/* Padding to the end of the block */
128   };
129 
130 struct ext2_group_desc
131   {
132     __u32 bg_block_bitmap;	/* Blocks bitmap block */
133     __u32 bg_inode_bitmap;	/* Inodes bitmap block */
134     __u32 bg_inode_table;	/* Inodes table block */
135     __u16 bg_free_blocks_count;	/* Free blocks count */
136     __u16 bg_free_inodes_count;	/* Free inodes count */
137     __u16 bg_used_dirs_count;	/* Directories count */
138     __u16 bg_pad;
139     __u32 bg_reserved[3];
140   };
141 
142 struct ext2_inode
143   {
144     __u16 i_mode;		/* File mode */
145     __u16 i_uid;		/* Owner Uid */
146     __u32 i_size;		/* 4: Size in bytes */
147     __u32 i_atime;		/* Access time */
148     __u32 i_ctime;		/* 12: Creation time */
149     __u32 i_mtime;		/* Modification time */
150     __u32 i_dtime;		/* 20: Deletion Time */
151     __u16 i_gid;		/* Group Id */
152     __u16 i_links_count;	/* 24: Links count */
153     __u32 i_blocks;		/* Blocks count */
154     __u32 i_flags;		/* 32: File flags */
155     union
156       {
157 	struct
158 	  {
159 	    __u32 l_i_reserved1;
160 	  }
161 	linux1;
162 	struct
163 	  {
164 	    __u32 h_i_translator;
165 	  }
166 	hurd1;
167 	struct
168 	  {
169 	    __u32 m_i_reserved1;
170 	  }
171 	masix1;
172       }
173     osd1;			/* OS dependent 1 */
174     __u32 i_block[EXT2_N_BLOCKS];	/* 40: Pointers to blocks */
175     __u32 i_version;		/* File version (for NFS) */
176     __u32 i_file_acl;		/* File ACL */
177     __u32 i_dir_acl;		/* Directory ACL */
178     __u32 i_faddr;		/* Fragment address */
179     union
180       {
181 	struct
182 	  {
183 	    __u8 l_i_frag;	/* Fragment number */
184 	    __u8 l_i_fsize;	/* Fragment size */
185 	    __u16 i_pad1;
186 	    __u32 l_i_reserved2[2];
187 	  }
188 	linux2;
189 	struct
190 	  {
191 	    __u8 h_i_frag;	/* Fragment number */
192 	    __u8 h_i_fsize;	/* Fragment size */
193 	    __u16 h_i_mode_high;
194 	    __u16 h_i_uid_high;
195 	    __u16 h_i_gid_high;
196 	    __u32 h_i_author;
197 	  }
198 	hurd2;
199 	struct
200 	  {
201 	    __u8 m_i_frag;	/* Fragment number */
202 	    __u8 m_i_fsize;	/* Fragment size */
203 	    __u16 m_pad1;
204 	    __u32 m_i_reserved2[2];
205 	  }
206 	masix2;
207       }
208     osd2;			/* OS dependent 2 */
209   };
210 
211 /* linux/limits.h */
212 #define NAME_MAX         255	/* # chars in a file name */
213 
214 /* linux/posix_type.h */
215 typedef long linux_off_t;
216 
217 /* linux/ext2fs.h */
218 #define EXT2_NAME_LEN 255
219 struct ext2_dir_entry
220   {
221     __u32 inode;		/* Inode number */
222     __u16 rec_len;		/* Directory entry length */
223     __u8 name_len;		/* Name length */
224     __u8 file_type;
225     char name[EXT2_NAME_LEN];	/* File name */
226   };
227 
228 /* linux/ext2fs.h */
229 /*
230  * EXT2_DIR_PAD defines the directory entries boundaries
231  *
232  * NOTE: It must be a multiple of 4
233  */
234 #define EXT2_DIR_PAD                    4
235 #define EXT2_DIR_ROUND                  (EXT2_DIR_PAD - 1)
236 #define EXT2_DIR_REC_LEN(name_len)      (((name_len) + 8 + EXT2_DIR_ROUND) & \
237                                          ~EXT2_DIR_ROUND)
238 
239 /* linux/ext4_fs_extents.h */
240 /*
241  * This is the extent on-disk structure.
242  * It's used at the bottom of the tree.
243  */
244 struct ext4_extent {
245     __u32 ee_block;       /* first logical block extent covers */
246     __u16 ee_len;         /* number of blocks covered by extent */
247     __u16 ee_start_hi;    /* high 16 bits of physical block */
248     __u32 ee_start;       /* low 32 bits of physical block */
249 };
250 
251 /*
252  * This is index on-disk structure.
253  * It's used at all the levels except the bottom.
254  */
255 struct ext4_extent_idx {
256     __u32 ei_block;       /* index covers logical blocks from 'block' */
257     __u32 ei_leaf;        /* pointer to the physical block of the next *
258                                  * level. leaf or next index could be there */
259     __u16 ei_leaf_hi;     /* high 16 bits of physical block */
260     __u16 ei_unused;
261 };
262 
263 /*
264  * Each block (leaves and indexes), even inode-stored has header.
265  */
266 struct ext4_extent_header {
267     __u16  eh_magic;       /* probably will support different formats */
268     __u16  eh_entries;     /* number of valid entries */
269     __u16  eh_max;         /* capacity of store in entries */
270     __u16  eh_depth;       /* has tree real underlying blocks? */
271     __u32  eh_generation;  /* generation of the tree */
272 };
273 
274 #define EXT4_EXT_MAGIC          0xf30a
275 
276 /* ext2/super.c */
277 #define log2(n) grub_log2(n)
278 
279 #define EXT2_SUPER_MAGIC      0xEF53	/* include/linux/ext2_fs.h */
280 #define EXT2_ROOT_INO              2	/* include/linux/ext2_fs.h */
281 #define PATH_MAX                1024	/* include/linux/limits.h */
282 #define MAX_LINK_COUNT             5	/* number of symbolic links to follow */
283 
284 /* made up, these are pointers into FSYS_BUF */
285 /* read once, always stays there: */
286 #define SUPERBLOCK \
287     ((struct ext2_super_block *)(FSYS_BUF))
288 #define GROUP_DESC \
289     ((struct ext2_group_desc *) \
290      ((char *)SUPERBLOCK + sizeof(struct ext2_super_block)))
291 #define INODE \
292     ((struct ext2_inode *)((caddr_t)GROUP_DESC + EXT2_BLOCK_SIZE(SUPERBLOCK)))
293 #define DATABLOCK1 \
294     ((char *)((caddr_t)INODE + sizeof(struct ext2_inode)))
295 #define DATABLOCK2 \
296     ((char *)((caddr_t)DATABLOCK1 + EXT2_BLOCK_SIZE(SUPERBLOCK)))
297 
298 /* linux/ext2_fs.h */
299 #define EXT2_ADDR_PER_BLOCK(s)          (EXT2_BLOCK_SIZE(s) / sizeof (__u32))
300 #define EXT2_ADDR_PER_BLOCK_BITS(s)		(log2(EXT2_ADDR_PER_BLOCK(s)))
301 
302 #define EXT2_INODE_SIZE(s)		(SUPERBLOCK->s_inode_size)
303 #define EXT2_INODES_PER_BLOCK(s)	(EXT2_BLOCK_SIZE(s)/EXT2_INODE_SIZE(s))
304 
305 /* linux/ext2_fs.h */
306 #define EXT2_BLOCK_SIZE_BITS(s)        ((s)->s_log_block_size + 10)
307 /* kind of from ext2/super.c */
308 #define EXT2_BLOCK_SIZE(s)	(1 << EXT2_BLOCK_SIZE_BITS(s))
309 /* linux/ext2fs.h */
310 #define EXT2_DESC_PER_BLOCK(s) \
311      (EXT2_BLOCK_SIZE(s) / sizeof (struct ext2_group_desc))
312 /* linux/stat.h */
313 #define S_IFMT  00170000
314 #define S_IFLNK  0120000
315 #define S_IFREG  0100000
316 #define S_IFDIR  0040000
317 #define S_ISLNK(m)	(((m) & S_IFMT) == S_IFLNK)
318 #define S_ISREG(m)      (((m) & S_IFMT) == S_IFREG)
319 #define S_ISDIR(m)      (((m) & S_IFMT) == S_IFDIR)
320 
321 /* check filesystem types and read superblock into memory buffer */
322 static int
ext2fs_mount(fsi_file_t * ffi,const char * options)323 ext2fs_mount (fsi_file_t *ffi, const char *options)
324 {
325   int retval = 1;
326 
327   if (/*(((current_drive & 0x80) || (current_slice != 0))
328        && (current_slice != PC_SLICE_TYPE_EXT2FS)
329        && (current_slice != PC_SLICE_TYPE_LINUX_RAID)
330        && (! IS_PC_SLICE_TYPE_BSD_WITH_FS (current_slice, FS_EXT2FS))
331        && (! IS_PC_SLICE_TYPE_BSD_WITH_FS (current_slice, FS_OTHER)))
332       || part_length < (SBLOCK + (sizeof (struct ext2_super_block) / DEV_BSIZE))
333       || */ !devread (ffi, SBLOCK, 0, sizeof (struct ext2_super_block),
334 		   (char *) SUPERBLOCK)
335       || SUPERBLOCK->s_magic != EXT2_SUPER_MAGIC)
336       retval = 0;
337 
338   return retval;
339 }
340 
341 /* Takes a file system block number and reads it into BUFFER. */
342 static int
ext2_rdfsb(fsi_file_t * ffi,int fsblock,char * buffer)343 ext2_rdfsb (fsi_file_t *ffi, int fsblock, char *buffer)
344 {
345 #ifdef E2DEBUG
346   printf ("fsblock %d buffer %d\n", fsblock, buffer);
347 #endif /* E2DEBUG */
348   return devread (ffi, fsblock * (EXT2_BLOCK_SIZE (SUPERBLOCK) / DEV_BSIZE), 0,
349 		  EXT2_BLOCK_SIZE (SUPERBLOCK), (char *) buffer);
350 }
351 
352 /* Walk through extents index tree to find the good leaf */
353 static struct ext4_extent_header *
ext4_recurse_extent_index(fsi_file_t * ffi,struct ext4_extent_header * extent_block,int logical_block)354 ext4_recurse_extent_index(fsi_file_t *ffi, struct ext4_extent_header *extent_block, int logical_block)
355 {
356   int i;
357   struct ext4_extent_idx *index = (struct ext4_extent_idx *) (extent_block + 1);
358   if (extent_block->eh_magic != EXT4_EXT_MAGIC)
359     return NULL;
360   if (extent_block->eh_depth == 0)
361     return extent_block;
362   for (i = 0; i < extent_block->eh_entries; i++)
363     {
364       if (logical_block < index[i].ei_block)
365         break;
366     }
367   if (i == 0 || !ext2_rdfsb(ffi, index[i-1].ei_leaf, DATABLOCK1))
368     return NULL;
369   return (ext4_recurse_extent_index(ffi, (struct ext4_extent_header *) DATABLOCK1, logical_block));
370 }
371 
372 
373 /* from
374   ext2/inode.c:ext2_bmap()
375 */
376 /* Maps LOGICAL_BLOCK (the file offset divided by the blocksize) into
377    a physical block (the location in the file system) via an inode. */
378 static int
ext2fs_block_map(fsi_file_t * ffi,int logical_block)379 ext2fs_block_map (fsi_file_t *ffi, int logical_block)
380 {
381 #ifdef E2DEBUG
382   unsigned char *i;
383   for (i = (unsigned char *) INODE;
384        i < ((unsigned char *) INODE + sizeof (struct ext2_inode));
385        i++)
386     {
387       printf ("%c", "0123456789abcdef"[*i >> 4]);
388       printf ("%c", "0123456789abcdef"[*i % 16]);
389       if (!((i + 1 - (unsigned char *) INODE) % 16))
390 	{
391 	  printf ("\n");
392 	}
393       else
394 	{
395 	  printf (" ");
396 	}
397     }
398   printf ("logical block %d\n", logical_block);
399 #endif /* E2DEBUG */
400 
401   if (!(INODE->i_flags & EXT4_EXTENTS_FL))
402       {
403       /* if it is directly pointed to by the inode, return that physical addr */
404       if (logical_block < EXT2_NDIR_BLOCKS)
405         {
406 #ifdef E2DEBUG
407           printf ("returning %d\n", (unsigned char *) (INODE->i_block[logical_block]));
408           printf ("returning %d\n", INODE->i_block[logical_block]);
409 #endif /* E2DEBUG */
410           return INODE->i_block[logical_block];
411         }
412       /* else */
413       logical_block -= EXT2_NDIR_BLOCKS;
414       /* try the indirect block */
415       if (logical_block < EXT2_ADDR_PER_BLOCK (SUPERBLOCK))
416         {
417           if (mapblock1 != 1 && !ext2_rdfsb (ffi, INODE->i_block[EXT2_IND_BLOCK], DATABLOCK1))
418             {
419               errnum = ERR_FSYS_CORRUPT;
420               return -1;
421             }
422           mapblock1 = 1;
423           return ((__u32 *) DATABLOCK1)[logical_block];
424         }
425       /* else */
426       logical_block -= EXT2_ADDR_PER_BLOCK (SUPERBLOCK);
427       /* now try the double indirect block */
428       if (logical_block < (1 << (EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK) * 2)))
429         {
430           int bnum;
431           if (mapblock1 != 2 && !ext2_rdfsb (ffi, INODE->i_block[EXT2_DIND_BLOCK], DATABLOCK1))
432             {
433               errnum = ERR_FSYS_CORRUPT;
434               return -1;
435             }
436           mapblock1 = 2;
437           if ((bnum = (((__u32 *) DATABLOCK1)
438                   [logical_block >> EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK)]))
439          != mapblock2
440          && !ext2_rdfsb (ffi, bnum, DATABLOCK2))
441            {
442              errnum = ERR_FSYS_CORRUPT;
443              return -1;
444            }
445           mapblock2 = bnum;
446           return ((__u32 *) DATABLOCK2)
447             [logical_block & (EXT2_ADDR_PER_BLOCK (SUPERBLOCK) - 1)];
448         }
449       /* else */
450       mapblock2 = -1;
451       logical_block -= (1 << (EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK) * 2));
452       if (mapblock1 != 3
453           && !ext2_rdfsb (ffi, INODE->i_block[EXT2_TIND_BLOCK], DATABLOCK1))
454         {
455           errnum = ERR_FSYS_CORRUPT;
456           return -1;
457         }
458       mapblock1 = 3;
459       if (!ext2_rdfsb (ffi, ((__u32 *) DATABLOCK1)
460                   [logical_block >> (EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK)
461                                      * 2)],
462                   DATABLOCK2))
463         {
464           errnum = ERR_FSYS_CORRUPT;
465           return -1;
466         }
467       if (!ext2_rdfsb (ffi, ((__u32 *) DATABLOCK2)
468                   [(logical_block >> EXT2_ADDR_PER_BLOCK_BITS (SUPERBLOCK))
469                    & (EXT2_ADDR_PER_BLOCK (SUPERBLOCK) - 1)],
470                   DATABLOCK2))
471         {
472           errnum = ERR_FSYS_CORRUPT;
473           return -1;
474         }
475 
476       return ((__u32 *) DATABLOCK2)
477        [logical_block & (EXT2_ADDR_PER_BLOCK (SUPERBLOCK) - 1)];
478     }
479     /* inode is in extents format */
480     else
481     {
482       int i;
483       struct ext4_extent_header *extent_hdr =
484          ext4_recurse_extent_index(ffi, (struct ext4_extent_header *) INODE->i_block, logical_block);
485       struct ext4_extent *extent = (struct ext4_extent *) (extent_hdr + 1);
486       if ( extent_hdr == NULL || extent_hdr->eh_magic != EXT4_EXT_MAGIC)
487         {
488           errnum = ERR_FSYS_CORRUPT;
489           return -1;
490         }
491       for (i = 0; i<extent_hdr->eh_entries; i++)
492         {
493           if (extent[i].ee_block <= logical_block && logical_block < extent[i].ee_block + extent[i].ee_len && !(extent[i].ee_len>>15))
494             return (logical_block - extent[i].ee_block + extent[i].ee_start);
495         }
496       /* We should not arrive here */
497 
498       errnum = ERR_FSYS_CORRUPT;
499       return -1;
500     }
501 }
502 
503 /* preconditions: all preconds of ext2fs_block_map */
504 static int
ext2fs_read(fsi_file_t * ffi,char * buf,int len)505 ext2fs_read (fsi_file_t *ffi, char *buf, int len)
506 {
507   int logical_block;
508   int offset;
509   int map;
510   int ret = 0;
511   int size = 0;
512 
513 #ifdef E2DEBUG
514   static char hexdigit[] = "0123456789abcdef";
515   unsigned char *i;
516   for (i = (unsigned char *) INODE;
517        i < ((unsigned char *) INODE + sizeof (struct ext2_inode));
518        i++)
519     {
520       printf ("%c", hexdigit[*i >> 4]);
521       printf ("%c", hexdigit[*i % 16]);
522       if (!((i + 1 - (unsigned char *) INODE) % 16))
523 	{
524 	  printf ("\n");
525 	}
526       else
527 	{
528 	  printf (" ");
529 	}
530     }
531 #endif /* E2DEBUG */
532   while (len > 0)
533     {
534       /* find the (logical) block component of our location */
535       logical_block = filepos >> EXT2_BLOCK_SIZE_BITS (SUPERBLOCK);
536       offset = filepos & (EXT2_BLOCK_SIZE (SUPERBLOCK) - 1);
537       map = ext2fs_block_map (ffi, logical_block);
538 #ifdef E2DEBUG
539       printf ("map=%d\n", map);
540 #endif /* E2DEBUG */
541       if (map < 0)
542 	break;
543 
544       size = EXT2_BLOCK_SIZE (SUPERBLOCK);
545       size -= offset;
546       if (size > len)
547 	size = len;
548 
549       if (map == 0) {
550         memset ((char *) buf, 0, size);
551       } else {
552         disk_read_func = disk_read_hook;
553 
554         devread (ffi, map * (EXT2_BLOCK_SIZE (SUPERBLOCK) / DEV_BSIZE),
555 	         offset, size, buf);
556 
557         disk_read_func = NULL;
558       }
559 
560       buf += size;
561       len -= size;
562       filepos += size;
563       ret += size;
564     }
565 
566   if (errnum)
567     ret = 0;
568 
569   return ret;
570 }
571 
572 
573 /* Based on:
574    def_blk_fops points to
575    blkdev_open, which calls (I think):
576    sys_open()
577    do_open()
578    open_namei()
579    dir_namei() which accesses current->fs->root
580      fs->root was set during original mount:
581      (something)... which calls (I think):
582      ext2_read_super()
583      iget()
584      __iget()
585      read_inode()
586      ext2_read_inode()
587        uses desc_per_block_bits, which is set in ext2_read_super()
588        also uses group descriptors loaded during ext2_read_super()
589    lookup()
590    ext2_lookup()
591    ext2_find_entry()
592    ext2_getblk()
593 
594 */
595 
596 static inline
ext2_is_fast_symlink(fsi_file_t * ffi)597 int ext2_is_fast_symlink (fsi_file_t *ffi)
598 {
599   int ea_blocks;
600   ea_blocks = INODE->i_file_acl ? EXT2_BLOCK_SIZE (SUPERBLOCK) / DEV_BSIZE : 0;
601   return INODE->i_blocks == ea_blocks;
602 }
603 
604 /* preconditions: ext2fs_mount already executed, therefore supblk in buffer
605  *   known as SUPERBLOCK
606  * returns: 0 if error, nonzero iff we were able to find the file successfully
607  * postconditions: on a nonzero return, buffer known as INODE contains the
608  *   inode of the file we were trying to look up
609  * side effects: messes up GROUP_DESC buffer area
610  */
611 static int
ext2fs_dir(fsi_file_t * ffi,char * dirname)612 ext2fs_dir (fsi_file_t *ffi, char *dirname)
613 {
614   int current_ino = EXT2_ROOT_INO;	/* start at the root */
615   int updir_ino = current_ino;	/* the parent of the current directory */
616   int group_id;			/* which group the inode is in */
617   int group_desc;		/* fs pointer to that group */
618   int desc;			/* index within that group */
619   int ino_blk;			/* fs pointer of the inode's information */
620   int str_chk = 0;		/* used to hold the results of a string compare */
621   struct ext2_group_desc *gdp;
622   struct ext2_inode *raw_inode;	/* inode info corresponding to current_ino */
623 
624   char linkbuf[PATH_MAX];	/* buffer for following symbolic links */
625   int link_count = 0;
626 
627   char *rest;
628   char ch;			/* temp char holder */
629 
630   int off;			/* offset within block of directory entry (off mod blocksize) */
631   int loc;			/* location within a directory */
632   int blk;			/* which data blk within dir entry (off div blocksize) */
633   int inodes_per_block;		/* number of inodes in each block */
634   int inode_offset;		/* inode offset in block */
635   long map;			/* fs pointer of a particular block from dir entry */
636   struct ext2_dir_entry *dp;	/* pointer to directory entry */
637 #ifdef E2DEBUG
638   unsigned char *i;
639 #endif	/* E2DEBUG */
640 
641   /* loop invariants:
642      current_ino = inode to lookup
643      dirname = pointer to filename component we are cur looking up within
644      the directory known pointed to by current_ino (if any)
645    */
646 
647   while (1)
648     {
649 #ifdef E2DEBUG
650       printf ("inode %d\n", current_ino);
651       printf ("dirname=%s\n", dirname);
652 #endif /* E2DEBUG */
653 
654       /* look up an inode */
655       group_id = (current_ino - 1) / (SUPERBLOCK->s_inodes_per_group);
656       group_desc = group_id >> log2 (EXT2_DESC_PER_BLOCK (SUPERBLOCK));
657       desc = group_id & (EXT2_DESC_PER_BLOCK (SUPERBLOCK) - 1);
658 #ifdef E2DEBUG
659       printf ("ipg=%d, dpb=%d\n", SUPERBLOCK->s_inodes_per_group,
660 	      EXT2_DESC_PER_BLOCK (SUPERBLOCK));
661       printf ("group_id=%d group_desc=%d desc=%d\n", group_id, group_desc, desc);
662 #endif /* E2DEBUG */
663       if (!ext2_rdfsb (ffi,
664 			(WHICH_SUPER + group_desc + SUPERBLOCK->s_first_data_block),
665 			(char *)GROUP_DESC))
666 	{
667 	  return 0;
668 	}
669       gdp = GROUP_DESC;
670       inodes_per_block =  EXT2_BLOCK_SIZE (SUPERBLOCK) / EXT2_INODE_SIZE(SUPERBLOCK);
671       inode_offset = ((current_ino - 1) % (SUPERBLOCK->s_inodes_per_group));
672       ino_blk = gdp[desc].bg_inode_table + (inode_offset / inodes_per_block);
673 #ifdef E2DEBUG
674       printf ("inode table fsblock=%d\n", ino_blk);
675 #endif /* E2DEBUG */
676       if (!ext2_rdfsb (ffi, ino_blk, (char *)INODE))
677 	{
678 	  return 0;
679 	}
680 
681       /* reset indirect blocks! */
682       mapblock2 = mapblock1 = -1;
683 
684       raw_inode = (struct ext2_inode *)((char *)INODE +
685 	((current_ino - 1) & (EXT2_INODES_PER_BLOCK (SUPERBLOCK) - 1)) *
686 	EXT2_INODE_SIZE (SUPERBLOCK));
687 #ifdef E2DEBUG
688       printf ("ipb=%d, sizeof(inode)=%d\n",
689 	      EXT2_INODES_PER_BLOCK (SUPERBLOCK), EXT2_INODE_SIZE (SUPERBLOCK));
690       printf ("inode=%x, raw_inode=%x\n", INODE, raw_inode);
691       printf ("offset into inode table block=%d\n", (int) raw_inode - (int) INODE);
692       for (i = (unsigned char *) INODE; i <= (unsigned char *) raw_inode;
693 	   i++)
694 	{
695 	  printf ("%c", "0123456789abcdef"[*i >> 4]);
696 	  printf ("%c", "0123456789abcdef"[*i % 16]);
697 	  if (!((i + 1 - (unsigned char *) INODE) % 16))
698 	    {
699 	      printf ("\n");
700 	    }
701 	  else
702 	    {
703 	      printf (" ");
704 	    }
705 	}
706       printf ("first word=%x\n", *((int *) raw_inode));
707 #endif /* E2DEBUG */
708 
709       /* copy inode to fixed location */
710       memmove ((void *) INODE, (void *) raw_inode, sizeof (struct ext2_inode));
711 
712 #ifdef E2DEBUG
713       printf ("first word=%x\n", *((int *) INODE));
714 #endif /* E2DEBUG */
715 
716       /* If we've got a symbolic link, then chase it. */
717       if (S_ISLNK (INODE->i_mode))
718 	{
719 	  int len;
720 	  if (++link_count > MAX_LINK_COUNT)
721 	    {
722 	      errnum = ERR_SYMLINK_LOOP;
723 	      return 0;
724 	    }
725 
726 	  /* Find out how long our remaining name is. */
727 	  len = 0;
728 	  while (dirname[len] && !isspace ((uint8_t)dirname[len]))
729 	    len++;
730 
731 	  /* Get the symlink size. */
732 	  filemax = (INODE->i_size);
733 	  if (filemax + len > sizeof (linkbuf) - 2)
734 	    {
735 	      errnum = ERR_FILELENGTH;
736 	      return 0;
737 	    }
738 
739 	  if (len)
740 	    {
741 	      /* Copy the remaining name to the end of the symlink data.
742 	         Note that DIRNAME and LINKBUF may overlap! */
743 	      memmove (linkbuf + filemax, dirname, len);
744 	    }
745 	  linkbuf[filemax + len] = '\0';
746 
747 	  /* Read the symlink data. */
748 	  if (! ext2_is_fast_symlink (ffi))
749 	    {
750 	      /* Read the necessary blocks, and reset the file pointer. */
751 	      len = ext2fs_read (ffi, linkbuf, filemax);
752 	      filepos = 0;
753 	      if (!len)
754 		return 0;
755 	    }
756 	  else
757 	    {
758 	      /* Copy the data directly from the inode. */
759 	      len = filemax;
760 	      memmove (linkbuf, (char *) INODE->i_block, len);
761 	    }
762 
763 #ifdef E2DEBUG
764 	  printf ("symlink=%s\n", linkbuf);
765 #endif
766 
767 	  dirname = linkbuf;
768 	  if (*dirname == '/')
769 	    {
770 	      /* It's an absolute link, so look it up in root. */
771 	      current_ino = EXT2_ROOT_INO;
772 	      updir_ino = current_ino;
773 	    }
774 	  else
775 	    {
776 	      /* Relative, so look it up in our parent directory. */
777 	      current_ino = updir_ino;
778 	    }
779 
780 	  /* Try again using the new name. */
781 	  continue;
782 	}
783 
784       /* if end of filename, INODE points to the file's inode */
785       if (!*dirname || isspace ((uint8_t)*dirname))
786 	{
787 	  if (!S_ISREG (INODE->i_mode))
788 	    {
789 	      errnum = ERR_BAD_FILETYPE;
790 	      return 0;
791 	    }
792 
793 	  filemax = (INODE->i_size);
794 	  return 1;
795 	}
796 
797       /* else we have to traverse a directory */
798       updir_ino = current_ino;
799 
800       /* skip over slashes */
801       while (*dirname == '/')
802 	dirname++;
803 
804       /* if this isn't a directory of sufficient size to hold our file, abort */
805       if (!(INODE->i_size) || !S_ISDIR (INODE->i_mode))
806 	{
807 	  errnum = ERR_BAD_FILETYPE;
808 	  return 0;
809 	}
810 
811       /* skip to next slash or end of filename (space) */
812       for (rest = dirname; (ch = *rest) && !isspace ((uint8_t)ch) && ch != '/';
813 	   rest++);
814 
815       /* look through this directory and find the next filename component */
816       /* invariant: rest points to slash after the next filename component */
817       *rest = 0;
818       loc = 0;
819 
820       do
821 	{
822 
823 #ifdef E2DEBUG
824 	  printf ("dirname=%s, rest=%s, loc=%d\n", dirname, rest, loc);
825 #endif /* E2DEBUG */
826 
827 	  /* if our location/byte offset into the directory exceeds the size,
828 	     give up */
829 	  if (loc >= INODE->i_size)
830 	    {
831 	      if (print_possibilities < 0)
832 		{
833 # if 0
834 		  putchar ('\n');
835 # endif
836 		}
837 	      else
838 		{
839 		  errnum = ERR_FILE_NOT_FOUND;
840 		  *rest = ch;
841 		}
842 	      return (print_possibilities < 0);
843 	    }
844 
845 	  /* else, find the (logical) block component of our location */
846 	  blk = loc >> EXT2_BLOCK_SIZE_BITS (SUPERBLOCK);
847 
848 	  /* we know which logical block of the directory entry we are looking
849 	     for, now we have to translate that to the physical (fs) block on
850 	     the disk */
851 	  map = ext2fs_block_map (ffi, blk);
852 #ifdef E2DEBUG
853 	  printf ("fs block=%d\n", map);
854 #endif /* E2DEBUG */
855 	  mapblock2 = -1;
856 	  if ((map < 0) || !ext2_rdfsb (ffi, map, DATABLOCK2))
857 	    {
858 	      errnum = ERR_FSYS_CORRUPT;
859 	      *rest = ch;
860 	      return 0;
861 	    }
862 	  off = loc & (EXT2_BLOCK_SIZE (SUPERBLOCK) - 1);
863 	  dp = (struct ext2_dir_entry *) (DATABLOCK2 + off);
864 	  /* advance loc prematurely to next on-disk directory entry  */
865 	  loc += dp->rec_len;
866 
867 	  /* NOTE: ext2fs filenames are NOT null-terminated */
868 
869 #ifdef E2DEBUG
870 	  printf ("directory entry ino=%d\n", dp->inode);
871 	  if (dp->inode)
872 	    printf ("entry=%s\n", dp->name);
873 #endif /* E2DEBUG */
874 
875 	  if (dp->inode)
876 	    {
877 	      int saved_c = dp->name[dp->name_len];
878 
879 	      dp->name[dp->name_len] = 0;
880 	      str_chk = substring (dirname, dp->name);
881 
882 # ifndef STAGE1_5
883 	      if (print_possibilities && ch != '/'
884 		  && (!*dirname || str_chk <= 0))
885 		{
886 		  if (print_possibilities > 0)
887 		    print_possibilities = -print_possibilities;
888 		  print_a_completion (dp->name);
889 		}
890 # endif
891 
892 	      dp->name[dp->name_len] = saved_c;
893 	    }
894 
895 	}
896       while (!dp->inode || (str_chk || (print_possibilities && ch != '/')));
897 
898       current_ino = dp->inode;
899       *(dirname = rest) = ch;
900     }
901   /* never get here */
902 }
903 
904 fsi_plugin_ops_t *
fsi_init_plugin(int version,fsi_plugin_t * fp,const char ** name)905 fsi_init_plugin(int version, fsi_plugin_t *fp, const char **name)
906 {
907 	static fsig_plugin_ops_t ops = {
908 		FSIMAGE_PLUGIN_VERSION,
909 		.fpo_mount = ext2fs_mount,
910 		.fpo_dir = ext2fs_dir,
911 		.fpo_read = ext2fs_read
912 	};
913 
914 	*name = "ext2fs";
915 	return (fsig_init(fp, &ops));
916 }
917