Merge branch 'master' of https://source.denx.de/u-boot/custodians/u-boot-sh
[u-boot.git] / fs / squashfs / sqfs.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2020 Bootlin
4  *
5  * Author: Joao Marcos Costa <joaomarcos.costa@bootlin.com>
6  *
7  * sqfs.c: SquashFS filesystem implementation
8  */
9
10 #include <asm/unaligned.h>
11 #include <div64.h>
12 #include <errno.h>
13 #include <fs.h>
14 #include <linux/types.h>
15 #include <asm/byteorder.h>
16 #include <linux/compat.h>
17 #include <memalign.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <squashfs.h>
21 #include <part.h>
22
23 #include "sqfs_decompressor.h"
24 #include "sqfs_filesystem.h"
25 #include "sqfs_utils.h"
26
27 #define MAX_SYMLINK_NEST 8
28
29 static struct squashfs_ctxt ctxt;
30 static int symlinknest;
31
32 static int sqfs_readdir_nest(struct fs_dir_stream *fs_dirs, struct fs_dirent **dentp);
33
34 static int sqfs_disk_read(__u32 block, __u32 nr_blocks, void *buf)
35 {
36         ulong ret;
37
38         if (!ctxt.cur_dev)
39                 return -1;
40
41         ret = blk_dread(ctxt.cur_dev, ctxt.cur_part_info.start + block,
42                         nr_blocks, buf);
43
44         if (ret != nr_blocks)
45                 return -1;
46
47         return ret;
48 }
49
50 static int sqfs_read_sblk(struct squashfs_super_block **sblk)
51 {
52         *sblk = malloc_cache_aligned(ctxt.cur_dev->blksz);
53         if (!*sblk)
54                 return -ENOMEM;
55
56         if (sqfs_disk_read(0, 1, *sblk) != 1) {
57                 free(*sblk);
58                 *sblk = NULL;
59                 return -EINVAL;
60         }
61
62         return 0;
63 }
64
65 static int sqfs_count_tokens(const char *filename)
66 {
67         int token_count = 1, l;
68
69         for (l = 1; l < strlen(filename); l++) {
70                 if (filename[l] == '/')
71                         token_count++;
72         }
73
74         /* Ignore trailing '/' in path */
75         if (filename[strlen(filename) - 1] == '/')
76                 token_count--;
77
78         if (!token_count)
79                 token_count = 1;
80
81         return token_count;
82 }
83
84 /*
85  * Calculates how many blocks are needed for the buffer used in sqfs_disk_read.
86  * The memory section (e.g. inode table) start offset and its end (i.e. the next
87  * table start) must be specified. It also calculates the offset from which to
88  * start reading the buffer.
89  */
90 static int sqfs_calc_n_blks(__le64 start, __le64 end, u64 *offset)
91 {
92         u64 start_, table_size;
93
94         table_size = le64_to_cpu(end) - le64_to_cpu(start);
95         start_ = lldiv(le64_to_cpu(start), ctxt.cur_dev->blksz);
96         *offset = le64_to_cpu(start) - (start_ * ctxt.cur_dev->blksz);
97
98         return DIV_ROUND_UP(table_size + *offset, ctxt.cur_dev->blksz);
99 }
100
101 /*
102  * Retrieves fragment block entry and returns true if the fragment block is
103  * compressed
104  */
105 static int sqfs_frag_lookup(u32 inode_fragment_index,
106                             struct squashfs_fragment_block_entry *e)
107 {
108         u64 start, end, exp_tbl, n_blks, src_len, table_offset, start_block;
109         unsigned char *metadata_buffer, *metadata, *table;
110         struct squashfs_fragment_block_entry *entries;
111         struct squashfs_super_block *sblk = ctxt.sblk;
112         unsigned long dest_len;
113         int block, offset, ret;
114         u16 header;
115
116         metadata_buffer = NULL;
117         entries = NULL;
118         table = NULL;
119
120         if (inode_fragment_index >= get_unaligned_le32(&sblk->fragments))
121                 return -EINVAL;
122
123         start = get_unaligned_le64(&sblk->fragment_table_start);
124         end = get_unaligned_le64(&sblk->id_table_start);
125         exp_tbl = get_unaligned_le64(&sblk->export_table_start);
126
127         if (exp_tbl > start && exp_tbl < end)
128                 end = exp_tbl;
129
130         n_blks = sqfs_calc_n_blks(sblk->fragment_table_start,
131                                   cpu_to_le64(end), &table_offset);
132
133         start /= ctxt.cur_dev->blksz;
134
135         /* Allocate a proper sized buffer to store the fragment index table */
136         table = malloc_cache_aligned(n_blks * ctxt.cur_dev->blksz);
137         if (!table) {
138                 ret = -ENOMEM;
139                 goto out;
140         }
141
142         if (sqfs_disk_read(start, n_blks, table) < 0) {
143                 ret = -EINVAL;
144                 goto out;
145         }
146
147         block = SQFS_FRAGMENT_INDEX(inode_fragment_index);
148         offset = SQFS_FRAGMENT_INDEX_OFFSET(inode_fragment_index);
149
150         /*
151          * Get the start offset of the metadata block that contains the right
152          * fragment block entry
153          */
154         start_block = get_unaligned_le64(table + table_offset + block *
155                                          sizeof(u64));
156
157         start = start_block / ctxt.cur_dev->blksz;
158         n_blks = sqfs_calc_n_blks(cpu_to_le64(start_block),
159                                   sblk->fragment_table_start, &table_offset);
160
161         metadata_buffer = malloc_cache_aligned(n_blks * ctxt.cur_dev->blksz);
162         if (!metadata_buffer) {
163                 ret = -ENOMEM;
164                 goto out;
165         }
166
167         if (sqfs_disk_read(start, n_blks, metadata_buffer) < 0) {
168                 ret = -EINVAL;
169                 goto out;
170         }
171
172         /* Every metadata block starts with a 16-bit header */
173         header = get_unaligned_le16(metadata_buffer + table_offset);
174         metadata = metadata_buffer + table_offset + SQFS_HEADER_SIZE;
175
176         if (!metadata || !header) {
177                 ret = -ENOMEM;
178                 goto out;
179         }
180
181         entries = malloc(SQFS_METADATA_BLOCK_SIZE);
182         if (!entries) {
183                 ret = -ENOMEM;
184                 goto out;
185         }
186
187         if (SQFS_COMPRESSED_METADATA(header)) {
188                 src_len = SQFS_METADATA_SIZE(header);
189                 dest_len = SQFS_METADATA_BLOCK_SIZE;
190                 ret = sqfs_decompress(&ctxt, entries, &dest_len, metadata,
191                                       src_len);
192                 if (ret) {
193                         ret = -EINVAL;
194                         goto out;
195                 }
196         } else {
197                 memcpy(entries, metadata, SQFS_METADATA_SIZE(header));
198         }
199
200         *e = entries[offset];
201         ret = SQFS_COMPRESSED_BLOCK(e->size);
202
203 out:
204         free(entries);
205         free(metadata_buffer);
206         free(table);
207
208         return ret;
209 }
210
211 /*
212  * The entry name is a flexible array member, and we don't know its size before
213  * actually reading the entry. So we need a first copy to retrieve this size so
214  * we can finally copy the whole struct.
215  */
216 static int sqfs_read_entry(struct squashfs_directory_entry **dest, void *src)
217 {
218         struct squashfs_directory_entry *tmp;
219         u16 sz;
220
221         tmp = src;
222         sz = get_unaligned_le16(src + sizeof(*tmp) - sizeof(u16));
223         /*
224          * 'src' points to the begin of a directory entry, and 'sz' gets its
225          * 'name_size' member's value. name_size is actually the string
226          * length - 1, so adding 2 compensates this difference and adds space
227          * for the trailling null byte.
228          */
229         *dest = malloc(sizeof(*tmp) + sz + 2);
230         if (!*dest)
231                 return -ENOMEM;
232
233         memcpy(*dest, src, sizeof(*tmp) + sz + 1);
234         (*dest)->name[sz + 1] = '\0';
235
236         return 0;
237 }
238
239 static int sqfs_get_tokens_length(char **tokens, int count)
240 {
241         int length = 0, i;
242
243         /*
244          * 1 is added to the result of strlen to consider the slash separator
245          * between the tokens.
246          */
247         for (i = 0; i < count; i++)
248                 length += strlen(tokens[i]) + 1;
249
250         return length;
251 }
252
253 /* Takes a token list and returns a single string with '/' as separator. */
254 static char *sqfs_concat_tokens(char **token_list, int token_count)
255 {
256         char *result;
257         int i, length = 0, offset = 0;
258
259         length = sqfs_get_tokens_length(token_list, token_count);
260
261         result = malloc(length + 1);
262         if (!result)
263                 return NULL;
264
265         result[length] = '\0';
266
267         for (i = 0; i < token_count; i++) {
268                 strcpy(result + offset, token_list[i]);
269                 offset += strlen(token_list[i]);
270                 result[offset++] = '/';
271         }
272
273         return result;
274 }
275
276 /*
277  * Differently from sqfs_concat_tokens, sqfs_join writes the result into a
278  * previously allocated string, and returns the number of bytes written.
279  */
280 static int sqfs_join(char **strings, char *dest, int start, int end,
281                      char separator)
282 {
283         int i, offset = 0;
284
285         for (i = start; i < end; i++) {
286                 strcpy(dest + offset, strings[i]);
287                 offset += strlen(strings[i]);
288                 if (i < end - 1)
289                         dest[offset++] = separator;
290         }
291
292         return offset;
293 }
294
295 /*
296  * Fills the given token list using its size (count) and a source string (str)
297  */
298 static int sqfs_tokenize(char **tokens, int count, const char *str)
299 {
300         int i, j, ret = 0;
301         char *aux, *strc;
302
303         strc = strdup(str);
304         if (!strc)
305                 return -ENOMEM;
306
307         if (!strcmp(strc, "/")) {
308                 tokens[0] = strdup(strc);
309                 if (!tokens[0]) {
310                         ret = -ENOMEM;
311                         goto free_strc;
312                 }
313         } else {
314                 for (j = 0; j < count; j++) {
315                         aux = strtok(!j ? strc : NULL, "/");
316                         tokens[j] = strdup(aux);
317                         if (!tokens[j]) {
318                                 for (i = 0; i < j; i++)
319                                         free(tokens[i]);
320                                 ret = -ENOMEM;
321                                 goto free_strc;
322                         }
323                 }
324         }
325
326 free_strc:
327         free(strc);
328
329         return ret;
330 }
331
332 /*
333  * Remove last 'updir + 1' tokens from the base path tokens list. This leaves us
334  * with a token list containing only the tokens needed to form the resolved
335  * path, and returns the decremented size of the token list.
336  */
337 static int sqfs_clean_base_path(char **base, int count, int updir)
338 {
339         int i;
340
341         for (i = count - updir - 1; i < count; i++)
342                 free(base[i]);
343
344         return count - updir - 1;
345 }
346
347 /*
348  * Given the base ("current dir.") path and the relative one, generate the
349  * absolute path.
350  */
351 static char *sqfs_get_abs_path(const char *base, const char *rel)
352 {
353         char **base_tokens, **rel_tokens, *resolved = NULL;
354         int ret, bc, rc, i, updir = 0, resolved_size = 0, offset = 0;
355
356         base_tokens = NULL;
357         rel_tokens = NULL;
358
359         /* Memory allocation for the token lists */
360         bc = sqfs_count_tokens(base);
361         rc = sqfs_count_tokens(rel);
362         if (bc < 1 || rc < 1)
363                 return NULL;
364
365         base_tokens = calloc(bc, sizeof(char *));
366         if (!base_tokens)
367                 return NULL;
368
369         rel_tokens = calloc(rc, sizeof(char *));
370         if (!rel_tokens)
371                 goto out;
372
373         /* Fill token lists */
374         ret = sqfs_tokenize(base_tokens, bc, base);
375         if (ret)
376                 goto out;
377
378         ret = sqfs_tokenize(rel_tokens, rc, rel);
379         if (ret)
380                 goto out;
381
382         /* count '..' occurrences in target path */
383         for (i = 0; i < rc; i++) {
384                 if (!strcmp(rel_tokens[i], ".."))
385                         updir++;
386         }
387
388         /* Remove the last token and the '..' occurrences */
389         bc = sqfs_clean_base_path(base_tokens, bc, updir);
390         if (bc < 0)
391                 goto out;
392
393         /* Calculate resolved path size */
394         if (!bc)
395                 resolved_size++;
396
397         resolved_size += sqfs_get_tokens_length(base_tokens, bc) +
398                 sqfs_get_tokens_length(rel_tokens, rc);
399
400         resolved = malloc(resolved_size + 1);
401         if (!resolved)
402                 goto out;
403
404         /* Set resolved path */
405         memset(resolved, '\0', resolved_size + 1);
406         offset += sqfs_join(base_tokens, resolved + offset, 0, bc, '/');
407         resolved[offset++] = '/';
408         offset += sqfs_join(rel_tokens, resolved + offset, updir, rc, '/');
409
410 out:
411         if (rel_tokens)
412                 for (i = 0; i < rc; i++)
413                         free(rel_tokens[i]);
414         if (base_tokens)
415                 for (i = 0; i < bc; i++)
416                         free(base_tokens[i]);
417
418         free(rel_tokens);
419         free(base_tokens);
420
421         return resolved;
422 }
423
424 static char *sqfs_resolve_symlink(struct squashfs_symlink_inode *sym,
425                                   const char *base_path)
426 {
427         char *resolved, *target;
428         u32 sz;
429
430         if (__builtin_add_overflow(get_unaligned_le32(&sym->symlink_size), 1, &sz))
431                 return NULL;
432
433         target = malloc(sz);
434         if (!target)
435                 return NULL;
436
437         /*
438          * There is no trailling null byte in the symlink's target path, so a
439          * copy is made and a '\0' is added at its end.
440          */
441         target[sz - 1] = '\0';
442         /* Get target name (relative path) */
443         strncpy(target, sym->symlink, sz - 1);
444
445         /* Relative -> absolute path conversion */
446         resolved = sqfs_get_abs_path(base_path, target);
447
448         free(target);
449
450         return resolved;
451 }
452
453 /*
454  * m_list contains each metadata block's position, and m_count is the number of
455  * elements of m_list. Those metadata blocks come from the compressed directory
456  * table.
457  */
458 static int sqfs_search_dir(struct squashfs_dir_stream *dirs, char **token_list,
459                            int token_count, u32 *m_list, int m_count)
460 {
461         struct squashfs_super_block *sblk = ctxt.sblk;
462         char *path, *target, **sym_tokens, *res, *rem;
463         int j, ret = 0, new_inode_number, offset;
464         struct squashfs_symlink_inode *sym;
465         struct squashfs_ldir_inode *ldir;
466         struct squashfs_dir_inode *dir;
467         struct fs_dir_stream *dirsp;
468         struct fs_dirent *dent;
469         unsigned char *table;
470
471         res = NULL;
472         rem = NULL;
473         path = NULL;
474         target = NULL;
475         sym_tokens = NULL;
476
477         dirsp = (struct fs_dir_stream *)dirs;
478
479         /* Start by root inode */
480         table = sqfs_find_inode(dirs->inode_table, le32_to_cpu(sblk->inodes),
481                                 sblk->inodes, sblk->block_size);
482         if (!table)
483                 return -EINVAL;
484
485         dir = (struct squashfs_dir_inode *)table;
486         ldir = (struct squashfs_ldir_inode *)table;
487
488         /* get directory offset in directory table */
489         offset = sqfs_dir_offset(table, m_list, m_count);
490         dirs->table = &dirs->dir_table[offset];
491
492         /* Setup directory header */
493         dirs->dir_header = malloc(SQFS_DIR_HEADER_SIZE);
494         if (!dirs->dir_header)
495                 return -ENOMEM;
496
497         memcpy(dirs->dir_header, dirs->table, SQFS_DIR_HEADER_SIZE);
498
499         /* Initialize squashfs_dir_stream members */
500         dirs->table += SQFS_DIR_HEADER_SIZE;
501         dirs->size = get_unaligned_le16(&dir->file_size) - SQFS_DIR_HEADER_SIZE;
502         dirs->entry_count = dirs->dir_header->count + 1;
503
504         /* No path given -> root directory */
505         if (!strcmp(token_list[0], "/")) {
506                 dirs->table = &dirs->dir_table[offset];
507                 memcpy(&dirs->i_dir, dir, sizeof(*dir));
508                 return 0;
509         }
510
511         for (j = 0; j < token_count; j++) {
512                 if (!sqfs_is_dir(get_unaligned_le16(&dir->inode_type))) {
513                         printf("** Cannot find directory. **\n");
514                         ret = -EINVAL;
515                         goto out;
516                 }
517
518                 while (!sqfs_readdir_nest(dirsp, &dent)) {
519                         ret = strcmp(dent->name, token_list[j]);
520                         if (!ret)
521                                 break;
522                         free(dirs->entry);
523                         dirs->entry = NULL;
524                 }
525
526                 if (ret) {
527                         printf("** Cannot find directory. **\n");
528                         ret = -EINVAL;
529                         goto out;
530                 }
531
532                 /* Redefine inode as the found token */
533                 new_inode_number = dirs->entry->inode_offset +
534                         dirs->dir_header->inode_number;
535
536                 /* Get reference to inode in the inode table */
537                 table = sqfs_find_inode(dirs->inode_table, new_inode_number,
538                                         sblk->inodes, sblk->block_size);
539                 if (!table)
540                         return -EINVAL;
541                 dir = (struct squashfs_dir_inode *)table;
542
543                 /* Check for symbolic link and inode type sanity */
544                 if (get_unaligned_le16(&dir->inode_type) == SQFS_SYMLINK_TYPE) {
545                         if (++symlinknest == MAX_SYMLINK_NEST) {
546                                 ret = -ELOOP;
547                                 goto out;
548                         }
549
550                         sym = (struct squashfs_symlink_inode *)table;
551                         /* Get first j + 1 tokens */
552                         path = sqfs_concat_tokens(token_list, j + 1);
553                         if (!path) {
554                                 ret = -ENOMEM;
555                                 goto out;
556                         }
557                         /* Resolve for these tokens */
558                         target = sqfs_resolve_symlink(sym, path);
559                         if (!target) {
560                                 ret = -ENOMEM;
561                                 goto out;
562                         }
563                         /* Join remaining tokens */
564                         rem = sqfs_concat_tokens(token_list + j + 1, token_count -
565                                                  j - 1);
566                         if (!rem) {
567                                 ret = -ENOMEM;
568                                 goto out;
569                         }
570                         /*
571                          * Concatenate remaining tokens and symlink's target.
572                          * Allocate enough space for rem, target, '/' and '\0'.
573                          */
574                         res = malloc(strlen(rem) + strlen(target) + 2);
575                         if (!res) {
576                                 ret = -ENOMEM;
577                                 goto out;
578                         }
579                         strcpy(res, target);
580                         res[strlen(target)] = '/';
581                         strcpy(res + strlen(target) + 1, rem);
582                         token_count = sqfs_count_tokens(res);
583
584                         if (token_count < 0) {
585                                 ret = -EINVAL;
586                                 goto out;
587                         }
588
589                         sym_tokens = malloc(token_count * sizeof(char *));
590                         if (!sym_tokens) {
591                                 ret = -EINVAL;
592                                 goto out;
593                         }
594
595                         /* Fill tokens list */
596                         ret = sqfs_tokenize(sym_tokens, token_count, res);
597                         if (ret) {
598                                 ret = -EINVAL;
599                                 goto out;
600                         }
601                         free(dirs->entry);
602                         dirs->entry = NULL;
603
604                         ret = sqfs_search_dir(dirs, sym_tokens, token_count,
605                                               m_list, m_count);
606                         goto out;
607                 } else if (!sqfs_is_dir(get_unaligned_le16(&dir->inode_type))) {
608                         printf("** Cannot find directory. **\n");
609                         free(dirs->entry);
610                         dirs->entry = NULL;
611                         ret = -EINVAL;
612                         goto out;
613                 }
614
615                 /* Check if it is an extended dir. */
616                 if (get_unaligned_le16(&dir->inode_type) == SQFS_LDIR_TYPE)
617                         ldir = (struct squashfs_ldir_inode *)table;
618
619                 /* Get dir. offset into the directory table */
620                 offset = sqfs_dir_offset(table, m_list, m_count);
621                 dirs->table = &dirs->dir_table[offset];
622
623                 /* Copy directory header */
624                 memcpy(dirs->dir_header, &dirs->dir_table[offset],
625                        SQFS_DIR_HEADER_SIZE);
626
627                 /* Check for empty directory */
628                 if (sqfs_is_empty_dir(table)) {
629                         printf("Empty directory.\n");
630                         free(dirs->entry);
631                         dirs->entry = NULL;
632                         ret = SQFS_EMPTY_DIR;
633                         goto out;
634                 }
635
636                 dirs->table += SQFS_DIR_HEADER_SIZE;
637                 dirs->size = get_unaligned_le16(&dir->file_size);
638                 dirs->entry_count = dirs->dir_header->count + 1;
639                 dirs->size -= SQFS_DIR_HEADER_SIZE;
640                 free(dirs->entry);
641                 dirs->entry = NULL;
642         }
643
644         offset = sqfs_dir_offset(table, m_list, m_count);
645         dirs->table = &dirs->dir_table[offset];
646
647         if (get_unaligned_le16(&dir->inode_type) == SQFS_DIR_TYPE)
648                 memcpy(&dirs->i_dir, dir, sizeof(*dir));
649         else
650                 memcpy(&dirs->i_ldir, ldir, sizeof(*ldir));
651
652 out:
653         free(res);
654         free(rem);
655         free(path);
656         free(target);
657         free(sym_tokens);
658         return ret;
659 }
660
661 /*
662  * Inode and directory tables are stored as a series of metadata blocks, and
663  * given the compressed size of this table, we can calculate how much metadata
664  * blocks are needed to store the result of the decompression, since a
665  * decompressed metadata block should have a size of 8KiB.
666  */
667 static int sqfs_count_metablks(void *table, u32 offset, int table_size)
668 {
669         int count = 0, cur_size = 0, ret;
670         u32 data_size;
671         bool comp;
672
673         do {
674                 ret = sqfs_read_metablock(table, offset + cur_size, &comp,
675                                           &data_size);
676                 if (ret)
677                         return -EINVAL;
678                 cur_size += data_size + SQFS_HEADER_SIZE;
679                 count++;
680         } while (cur_size < table_size);
681
682         return count;
683 }
684
685 /*
686  * Storing the metadata blocks header's positions will be useful while looking
687  * for an entry in the directory table, using the reference (index and offset)
688  * given by its inode.
689  */
690 static int sqfs_get_metablk_pos(u32 *pos_list, void *table, u32 offset,
691                                 int metablks_count)
692 {
693         u32 data_size, cur_size = 0;
694         int j, ret = 0;
695         bool comp;
696
697         if (!metablks_count)
698                 return -EINVAL;
699
700         for (j = 0; j < metablks_count; j++) {
701                 ret = sqfs_read_metablock(table, offset + cur_size, &comp,
702                                           &data_size);
703                 if (ret)
704                         return -EINVAL;
705
706                 cur_size += data_size + SQFS_HEADER_SIZE;
707                 pos_list[j] = cur_size;
708         }
709
710         return ret;
711 }
712
713 static int sqfs_read_inode_table(unsigned char **inode_table)
714 {
715         struct squashfs_super_block *sblk = ctxt.sblk;
716         u64 start, n_blks, table_offset, table_size;
717         int j, ret = 0, metablks_count;
718         unsigned char *src_table, *itb;
719         u32 src_len, dest_offset = 0;
720         unsigned long dest_len = 0;
721         bool compressed;
722
723         table_size = get_unaligned_le64(&sblk->directory_table_start) -
724                 get_unaligned_le64(&sblk->inode_table_start);
725         start = get_unaligned_le64(&sblk->inode_table_start) /
726                 ctxt.cur_dev->blksz;
727         n_blks = sqfs_calc_n_blks(sblk->inode_table_start,
728                                   sblk->directory_table_start, &table_offset);
729
730         /* Allocate a proper sized buffer (itb) to store the inode table */
731         itb = malloc_cache_aligned(n_blks * ctxt.cur_dev->blksz);
732         if (!itb)
733                 return -ENOMEM;
734
735         if (sqfs_disk_read(start, n_blks, itb) < 0) {
736                 ret = -EINVAL;
737                 goto free_itb;
738         }
739
740         /* Parse inode table (metadata block) header */
741         ret = sqfs_read_metablock(itb, table_offset, &compressed, &src_len);
742         if (ret) {
743                 ret = -EINVAL;
744                 goto free_itb;
745         }
746
747         /* Calculate size to store the whole decompressed table */
748         metablks_count = sqfs_count_metablks(itb, table_offset, table_size);
749         if (metablks_count < 1) {
750                 ret = -EINVAL;
751                 goto free_itb;
752         }
753
754         *inode_table = kcalloc(metablks_count, SQFS_METADATA_BLOCK_SIZE,
755                                GFP_KERNEL);
756         if (!*inode_table) {
757                 ret = -ENOMEM;
758                 printf("Error: failed to allocate squashfs inode_table of size %i, increasing CONFIG_SYS_MALLOC_LEN could help\n",
759                        metablks_count * SQFS_METADATA_BLOCK_SIZE);
760                 goto free_itb;
761         }
762
763         src_table = itb + table_offset + SQFS_HEADER_SIZE;
764
765         /* Extract compressed Inode table */
766         for (j = 0; j < metablks_count; j++) {
767                 sqfs_read_metablock(itb, table_offset, &compressed, &src_len);
768                 if (compressed) {
769                         dest_len = SQFS_METADATA_BLOCK_SIZE;
770                         ret = sqfs_decompress(&ctxt, *inode_table +
771                                               dest_offset, &dest_len,
772                                               src_table, src_len);
773                         if (ret) {
774                                 free(*inode_table);
775                                 *inode_table = NULL;
776                                 goto free_itb;
777                         }
778
779                         dest_offset += dest_len;
780                 } else {
781                         memcpy(*inode_table + (j * SQFS_METADATA_BLOCK_SIZE),
782                                src_table, src_len);
783                 }
784
785                 /*
786                  * Offsets to the decompression destination, to the metadata
787                  * buffer 'itb' and to the decompression source, respectively.
788                  */
789
790                 table_offset += src_len + SQFS_HEADER_SIZE;
791                 src_table += src_len + SQFS_HEADER_SIZE;
792         }
793
794 free_itb:
795         free(itb);
796
797         return ret;
798 }
799
800 static int sqfs_read_directory_table(unsigned char **dir_table, u32 **pos_list)
801 {
802         u64 start, n_blks, table_offset, table_size;
803         struct squashfs_super_block *sblk = ctxt.sblk;
804         int j, ret = 0, metablks_count = -1;
805         unsigned char *src_table, *dtb;
806         u32 src_len, dest_offset = 0;
807         unsigned long dest_len = 0;
808         bool compressed;
809
810         *dir_table = NULL;
811         *pos_list = NULL;
812         /* DIRECTORY TABLE */
813         table_size = get_unaligned_le64(&sblk->fragment_table_start) -
814                 get_unaligned_le64(&sblk->directory_table_start);
815         start = get_unaligned_le64(&sblk->directory_table_start) /
816                 ctxt.cur_dev->blksz;
817         n_blks = sqfs_calc_n_blks(sblk->directory_table_start,
818                                   sblk->fragment_table_start, &table_offset);
819
820         /* Allocate a proper sized buffer (dtb) to store the directory table */
821         dtb = malloc_cache_aligned(n_blks * ctxt.cur_dev->blksz);
822         if (!dtb)
823                 return -ENOMEM;
824
825         if (sqfs_disk_read(start, n_blks, dtb) < 0)
826                 goto out;
827
828         /* Parse directory table (metadata block) header */
829         ret = sqfs_read_metablock(dtb, table_offset, &compressed, &src_len);
830         if (ret)
831                 goto out;
832
833         /* Calculate total size to store the whole decompressed table */
834         metablks_count = sqfs_count_metablks(dtb, table_offset, table_size);
835         if (metablks_count < 1)
836                 goto out;
837
838         *dir_table = malloc(metablks_count * SQFS_METADATA_BLOCK_SIZE);
839         if (!*dir_table)
840                 goto out;
841
842         *pos_list = malloc(metablks_count * sizeof(u32));
843         if (!*pos_list)
844                 goto out;
845
846         ret = sqfs_get_metablk_pos(*pos_list, dtb, table_offset,
847                                    metablks_count);
848         if (ret) {
849                 metablks_count = -1;
850                 goto out;
851         }
852
853         src_table = dtb + table_offset + SQFS_HEADER_SIZE;
854
855         /* Extract compressed Directory table */
856         dest_offset = 0;
857         for (j = 0; j < metablks_count; j++) {
858                 sqfs_read_metablock(dtb, table_offset, &compressed, &src_len);
859                 if (compressed) {
860                         dest_len = SQFS_METADATA_BLOCK_SIZE;
861                         ret = sqfs_decompress(&ctxt, *dir_table +
862                                               (j * SQFS_METADATA_BLOCK_SIZE),
863                                               &dest_len, src_table, src_len);
864                         if (ret) {
865                                 metablks_count = -1;
866                                 goto out;
867                         }
868
869                         if (dest_len < SQFS_METADATA_BLOCK_SIZE) {
870                                 dest_offset += dest_len;
871                                 break;
872                         }
873
874                         dest_offset += dest_len;
875                 } else {
876                         memcpy(*dir_table + (j * SQFS_METADATA_BLOCK_SIZE),
877                                src_table, src_len);
878                 }
879
880                 /*
881                  * Offsets to the decompression destination, to the metadata
882                  * buffer 'dtb' and to the decompression source, respectively.
883                  */
884                 table_offset += src_len + SQFS_HEADER_SIZE;
885                 src_table += src_len + SQFS_HEADER_SIZE;
886         }
887
888 out:
889         if (metablks_count < 1) {
890                 free(*dir_table);
891                 free(*pos_list);
892                 *dir_table = NULL;
893                 *pos_list = NULL;
894         }
895         free(dtb);
896
897         return metablks_count;
898 }
899
900 static int sqfs_opendir_nest(const char *filename, struct fs_dir_stream **dirsp)
901 {
902         unsigned char *inode_table = NULL, *dir_table = NULL;
903         int j, token_count = 0, ret = 0, metablks_count;
904         struct squashfs_dir_stream *dirs;
905         char **token_list = NULL, *path = NULL;
906         u32 *pos_list = NULL;
907
908         dirs = calloc(1, sizeof(*dirs));
909         if (!dirs)
910                 return -EINVAL;
911
912         /* these should be set to NULL to prevent dangling pointers */
913         dirs->dir_header = NULL;
914         dirs->entry = NULL;
915         dirs->table = NULL;
916         dirs->inode_table = NULL;
917         dirs->dir_table = NULL;
918
919         ret = sqfs_read_inode_table(&inode_table);
920         if (ret) {
921                 ret = -EINVAL;
922                 goto out;
923         }
924
925         metablks_count = sqfs_read_directory_table(&dir_table, &pos_list);
926         if (metablks_count < 1) {
927                 ret = -EINVAL;
928                 goto out;
929         }
930
931         /* Tokenize filename */
932         token_count = sqfs_count_tokens(filename);
933         if (token_count < 0) {
934                 ret = -EINVAL;
935                 goto out;
936         }
937
938         path = strdup(filename);
939         if (!path) {
940                 ret = -EINVAL;
941                 goto out;
942         }
943
944         token_list = malloc(token_count * sizeof(char *));
945         if (!token_list) {
946                 ret = -EINVAL;
947                 goto out;
948         }
949
950         /* Fill tokens list */
951         ret = sqfs_tokenize(token_list, token_count, path);
952         if (ret)
953                 goto out;
954         /*
955          * ldir's (extended directory) size is greater than dir, so it works as
956          * a general solution for the malloc size, since 'i' is a union.
957          */
958         dirs->inode_table = inode_table;
959         dirs->dir_table = dir_table;
960         ret = sqfs_search_dir(dirs, token_list, token_count, pos_list,
961                               metablks_count);
962         if (ret)
963                 goto out;
964
965         if (le16_to_cpu(dirs->i_dir.inode_type) == SQFS_DIR_TYPE)
966                 dirs->size = le16_to_cpu(dirs->i_dir.file_size);
967         else
968                 dirs->size = le32_to_cpu(dirs->i_ldir.file_size);
969
970         /* Setup directory header */
971         memcpy(dirs->dir_header, dirs->table, SQFS_DIR_HEADER_SIZE);
972         dirs->entry_count = dirs->dir_header->count + 1;
973         dirs->size -= SQFS_DIR_HEADER_SIZE;
974
975         /* Setup entry */
976         dirs->entry = NULL;
977         dirs->table += SQFS_DIR_HEADER_SIZE;
978
979         *dirsp = (struct fs_dir_stream *)dirs;
980
981 out:
982         for (j = 0; j < token_count; j++)
983                 free(token_list[j]);
984         free(token_list);
985         free(pos_list);
986         free(path);
987         if (ret) {
988                 free(inode_table);
989                 free(dirs);
990         }
991
992         return ret;
993 }
994
995 int sqfs_opendir(const char *filename, struct fs_dir_stream **dirsp)
996 {
997         symlinknest = 0;
998         return sqfs_opendir_nest(filename, dirsp);
999 }
1000
1001 int sqfs_readdir(struct fs_dir_stream *fs_dirs, struct fs_dirent **dentp)
1002 {
1003         symlinknest = 0;
1004         return sqfs_readdir_nest(fs_dirs, dentp);
1005 }
1006
1007 static int sqfs_readdir_nest(struct fs_dir_stream *fs_dirs, struct fs_dirent **dentp)
1008 {
1009         struct squashfs_super_block *sblk = ctxt.sblk;
1010         struct squashfs_dir_stream *dirs;
1011         struct squashfs_lreg_inode *lreg;
1012         struct squashfs_base_inode *base;
1013         struct squashfs_reg_inode *reg;
1014         int i_number, offset = 0, ret;
1015         struct fs_dirent *dent;
1016         unsigned char *ipos;
1017         u16 name_size;
1018
1019         dirs = (struct squashfs_dir_stream *)fs_dirs;
1020         if (!dirs->size) {
1021                 *dentp = NULL;
1022                 return -SQFS_STOP_READDIR;
1023         }
1024
1025         dent = &dirs->dentp;
1026
1027         if (!dirs->entry_count) {
1028                 if (dirs->size > SQFS_DIR_HEADER_SIZE) {
1029                         dirs->size -= SQFS_DIR_HEADER_SIZE;
1030                 } else {
1031                         *dentp = NULL;
1032                         dirs->size = 0;
1033                         return -SQFS_STOP_READDIR;
1034                 }
1035
1036                 if (dirs->size > SQFS_EMPTY_FILE_SIZE) {
1037                         /* Read follow-up (emitted) dir. header */
1038                         memcpy(dirs->dir_header, dirs->table,
1039                                SQFS_DIR_HEADER_SIZE);
1040                         dirs->entry_count = dirs->dir_header->count + 1;
1041                         ret = sqfs_read_entry(&dirs->entry, dirs->table +
1042                                               SQFS_DIR_HEADER_SIZE);
1043                         if (ret)
1044                                 return -SQFS_STOP_READDIR;
1045
1046                         dirs->table += SQFS_DIR_HEADER_SIZE;
1047                 }
1048         } else {
1049                 ret = sqfs_read_entry(&dirs->entry, dirs->table);
1050                 if (ret)
1051                         return -SQFS_STOP_READDIR;
1052         }
1053
1054         i_number = dirs->dir_header->inode_number + dirs->entry->inode_offset;
1055         ipos = sqfs_find_inode(dirs->inode_table, i_number, sblk->inodes,
1056                                sblk->block_size);
1057         if (!ipos)
1058                 return -SQFS_STOP_READDIR;
1059
1060         base = (struct squashfs_base_inode *)ipos;
1061
1062         /* Set entry type and size */
1063         switch (dirs->entry->type) {
1064         case SQFS_DIR_TYPE:
1065         case SQFS_LDIR_TYPE:
1066                 dent->type = FS_DT_DIR;
1067                 break;
1068         case SQFS_REG_TYPE:
1069         case SQFS_LREG_TYPE:
1070                 /*
1071                  * Entries do not differentiate extended from regular types, so
1072                  * it needs to be verified manually.
1073                  */
1074                 if (get_unaligned_le16(&base->inode_type) == SQFS_LREG_TYPE) {
1075                         lreg = (struct squashfs_lreg_inode *)ipos;
1076                         dent->size = get_unaligned_le64(&lreg->file_size);
1077                 } else {
1078                         reg = (struct squashfs_reg_inode *)ipos;
1079                         dent->size = get_unaligned_le32(&reg->file_size);
1080                 }
1081
1082                 dent->type = FS_DT_REG;
1083                 break;
1084         case SQFS_BLKDEV_TYPE:
1085         case SQFS_CHRDEV_TYPE:
1086         case SQFS_LBLKDEV_TYPE:
1087         case SQFS_LCHRDEV_TYPE:
1088         case SQFS_FIFO_TYPE:
1089         case SQFS_SOCKET_TYPE:
1090         case SQFS_LFIFO_TYPE:
1091         case SQFS_LSOCKET_TYPE:
1092                 dent->type = SQFS_MISC_ENTRY_TYPE;
1093                 break;
1094         case SQFS_SYMLINK_TYPE:
1095         case SQFS_LSYMLINK_TYPE:
1096                 dent->type = FS_DT_LNK;
1097                 break;
1098         default:
1099                 return -SQFS_STOP_READDIR;
1100         }
1101
1102         /* Set entry name (capped at FS_DIRENT_NAME_LEN which is a U-Boot limitation) */
1103         name_size = min_t(u16, dirs->entry->name_size + 1, FS_DIRENT_NAME_LEN - 1);
1104         strncpy(dent->name, dirs->entry->name, name_size);
1105         dent->name[name_size] = '\0';
1106
1107         offset = dirs->entry->name_size + 1 + SQFS_ENTRY_BASE_LENGTH;
1108         dirs->entry_count--;
1109
1110         /* Decrement size to be read */
1111         if (dirs->size > offset)
1112                 dirs->size -= offset;
1113         else
1114                 dirs->size = 0;
1115
1116         /* Keep a reference to the current entry before incrementing it */
1117         dirs->table += offset;
1118
1119         *dentp = dent;
1120
1121         return 0;
1122 }
1123
1124 int sqfs_probe(struct blk_desc *fs_dev_desc, struct disk_partition *fs_partition)
1125 {
1126         struct squashfs_super_block *sblk;
1127         int ret;
1128
1129         ctxt.cur_dev = fs_dev_desc;
1130         ctxt.cur_part_info = *fs_partition;
1131
1132         ret = sqfs_read_sblk(&sblk);
1133         if (ret)
1134                 goto error;
1135
1136         /* Make sure it has a valid SquashFS magic number*/
1137         if (get_unaligned_le32(&sblk->s_magic) != SQFS_MAGIC_NUMBER) {
1138                 debug("Bad magic number for SquashFS image.\n");
1139                 ret = -EINVAL;
1140                 goto error;
1141         }
1142
1143         ctxt.sblk = sblk;
1144
1145         ret = sqfs_decompressor_init(&ctxt);
1146         if (ret) {
1147                 goto error;
1148         }
1149
1150         return 0;
1151 error:
1152         ctxt.cur_dev = NULL;
1153         free(ctxt.sblk);
1154         ctxt.sblk = NULL;
1155         return ret;
1156 }
1157
1158 static char *sqfs_basename(char *path)
1159 {
1160         char *fname;
1161
1162         fname = path + strlen(path) - 1;
1163         while (fname >= path) {
1164                 if (*fname == '/') {
1165                         fname++;
1166                         break;
1167                 }
1168
1169                 fname--;
1170         }
1171
1172         return fname;
1173 }
1174
1175 static char *sqfs_dirname(char *path)
1176 {
1177         char *fname;
1178
1179         fname = sqfs_basename(path);
1180         --fname;
1181         *fname = '\0';
1182
1183         return path;
1184 }
1185
1186 /*
1187  * Takes a path to file and splits it in two parts: the filename itself and the
1188  * directory's path, e.g.:
1189  * path: /path/to/file.txt
1190  * file: file.txt
1191  * dir: /path/to
1192  */
1193 static int sqfs_split_path(char **file, char **dir, const char *path)
1194 {
1195         char *dirc, *basec, *bname, *dname, *tmp_path;
1196         int ret = 0;
1197
1198         *file = NULL;
1199         *dir = NULL;
1200         dirc = NULL;
1201         basec = NULL;
1202         bname = NULL;
1203         dname = NULL;
1204         tmp_path = NULL;
1205
1206         /* check for first slash in path*/
1207         if (path[0] == '/') {
1208                 tmp_path = strdup(path);
1209                 if (!tmp_path) {
1210                         ret = -ENOMEM;
1211                         goto out;
1212                 }
1213         } else {
1214                 tmp_path = malloc(strlen(path) + 2);
1215                 if (!tmp_path) {
1216                         ret = -ENOMEM;
1217                         goto out;
1218                 }
1219                 tmp_path[0] = '/';
1220                 strcpy(tmp_path + 1, path);
1221         }
1222
1223         /* String duplicates */
1224         dirc = strdup(tmp_path);
1225         if (!dirc) {
1226                 ret = -ENOMEM;
1227                 goto out;
1228         }
1229
1230         basec = strdup(tmp_path);
1231         if (!basec) {
1232                 ret = -ENOMEM;
1233                 goto out;
1234         }
1235
1236         dname = sqfs_dirname(dirc);
1237         bname = sqfs_basename(basec);
1238
1239         *file = strdup(bname);
1240
1241         if (!*file) {
1242                 ret = -ENOMEM;
1243                 goto out;
1244         }
1245
1246         if (*dname == '\0') {
1247                 *dir = malloc(2);
1248                 if (!*dir) {
1249                         ret = -ENOMEM;
1250                         goto out;
1251                 }
1252
1253                 (*dir)[0] = '/';
1254                 (*dir)[1] = '\0';
1255         } else {
1256                 *dir = strdup(dname);
1257                 if (!*dir) {
1258                         ret = -ENOMEM;
1259                         goto out;
1260                 }
1261         }
1262
1263 out:
1264         if (ret) {
1265                 free(*file);
1266                 free(*dir);
1267                 *dir = NULL;
1268                 *file = NULL;
1269         }
1270         free(basec);
1271         free(dirc);
1272         free(tmp_path);
1273
1274         return ret;
1275 }
1276
1277 static int sqfs_get_regfile_info(struct squashfs_reg_inode *reg,
1278                                  struct squashfs_file_info *finfo,
1279                                  struct squashfs_fragment_block_entry *fentry,
1280                                  __le32 blksz)
1281 {
1282         int datablk_count = 0, ret;
1283
1284         finfo->size = get_unaligned_le32(&reg->file_size);
1285         finfo->offset = get_unaligned_le32(&reg->offset);
1286         finfo->start = get_unaligned_le32(&reg->start_block);
1287         finfo->frag = SQFS_IS_FRAGMENTED(get_unaligned_le32(&reg->fragment));
1288
1289         if (finfo->frag && finfo->offset == 0xFFFFFFFF)
1290                 return -EINVAL;
1291
1292         if (finfo->size < 1 || finfo->start == 0xFFFFFFFF)
1293                 return -EINVAL;
1294
1295         if (finfo->frag) {
1296                 datablk_count = finfo->size / le32_to_cpu(blksz);
1297                 ret = sqfs_frag_lookup(get_unaligned_le32(&reg->fragment),
1298                                        fentry);
1299                 if (ret < 0)
1300                         return -EINVAL;
1301                 finfo->comp = ret;
1302                 if (fentry->size < 1 || fentry->start == 0x7FFFFFFF)
1303                         return -EINVAL;
1304         } else {
1305                 datablk_count = DIV_ROUND_UP(finfo->size, le32_to_cpu(blksz));
1306         }
1307
1308         finfo->blk_sizes = malloc(datablk_count * sizeof(u32));
1309         if (!finfo->blk_sizes)
1310                 return -ENOMEM;
1311
1312         return datablk_count;
1313 }
1314
1315 static int sqfs_get_lregfile_info(struct squashfs_lreg_inode *lreg,
1316                                   struct squashfs_file_info *finfo,
1317                                   struct squashfs_fragment_block_entry *fentry,
1318                                  __le32 blksz)
1319 {
1320         int datablk_count = 0, ret;
1321
1322         finfo->size = get_unaligned_le64(&lreg->file_size);
1323         finfo->offset = get_unaligned_le32(&lreg->offset);
1324         finfo->start = get_unaligned_le64(&lreg->start_block);
1325         finfo->frag = SQFS_IS_FRAGMENTED(get_unaligned_le32(&lreg->fragment));
1326
1327         if (finfo->frag && finfo->offset == 0xFFFFFFFF)
1328                 return -EINVAL;
1329
1330         if (finfo->size < 1 || finfo->start == 0x7FFFFFFF)
1331                 return -EINVAL;
1332
1333         if (finfo->frag) {
1334                 datablk_count = finfo->size / le32_to_cpu(blksz);
1335                 ret = sqfs_frag_lookup(get_unaligned_le32(&lreg->fragment),
1336                                        fentry);
1337                 if (ret < 0)
1338                         return -EINVAL;
1339                 finfo->comp = ret;
1340                 if (fentry->size < 1 || fentry->start == 0x7FFFFFFF)
1341                         return -EINVAL;
1342         } else {
1343                 datablk_count = DIV_ROUND_UP(finfo->size, le32_to_cpu(blksz));
1344         }
1345
1346         finfo->blk_sizes = malloc(datablk_count * sizeof(u32));
1347         if (!finfo->blk_sizes)
1348                 return -ENOMEM;
1349
1350         return datablk_count;
1351 }
1352
1353 static int sqfs_read_nest(const char *filename, void *buf, loff_t offset,
1354                           loff_t len, loff_t *actread)
1355 {
1356         char *dir = NULL, *fragment_block, *datablock = NULL;
1357         char *fragment = NULL, *file = NULL, *resolved, *data;
1358         u64 start, n_blks, table_size, data_offset, table_offset, sparse_size;
1359         int ret, j, i_number, datablk_count = 0;
1360         struct squashfs_super_block *sblk = ctxt.sblk;
1361         struct squashfs_fragment_block_entry frag_entry;
1362         struct squashfs_file_info finfo = {0};
1363         struct squashfs_symlink_inode *symlink;
1364         struct fs_dir_stream *dirsp = NULL;
1365         struct squashfs_dir_stream *dirs;
1366         struct squashfs_lreg_inode *lreg;
1367         struct squashfs_base_inode *base;
1368         struct squashfs_reg_inode *reg;
1369         unsigned long dest_len;
1370         struct fs_dirent *dent;
1371         unsigned char *ipos;
1372
1373         *actread = 0;
1374
1375         if (offset) {
1376                 /*
1377                  * TODO: implement reading at an offset in file
1378                  */
1379                 printf("Error: reading at a specific offset in a squashfs file is not supported yet.\n");
1380                 return -EINVAL;
1381         }
1382
1383         /*
1384          * sqfs_opendir_nest will uncompress inode and directory tables, and will
1385          * return a pointer to the directory that contains the requested file.
1386          */
1387         sqfs_split_path(&file, &dir, filename);
1388         ret = sqfs_opendir_nest(dir, &dirsp);
1389         if (ret) {
1390                 goto out;
1391         }
1392
1393         dirs = (struct squashfs_dir_stream *)dirsp;
1394
1395         /* For now, only regular files are able to be loaded */
1396         while (!sqfs_readdir_nest(dirsp, &dent)) {
1397                 ret = strcmp(dent->name, file);
1398                 if (!ret)
1399                         break;
1400
1401                 free(dirs->entry);
1402                 dirs->entry = NULL;
1403         }
1404
1405         if (ret) {
1406                 printf("File not found.\n");
1407                 *actread = 0;
1408                 ret = -ENOENT;
1409                 goto out;
1410         }
1411
1412         i_number = dirs->dir_header->inode_number + dirs->entry->inode_offset;
1413         ipos = sqfs_find_inode(dirs->inode_table, i_number, sblk->inodes,
1414                                sblk->block_size);
1415         if (!ipos) {
1416                 ret = -EINVAL;
1417                 goto out;
1418         }
1419
1420         base = (struct squashfs_base_inode *)ipos;
1421         switch (get_unaligned_le16(&base->inode_type)) {
1422         case SQFS_REG_TYPE:
1423                 reg = (struct squashfs_reg_inode *)ipos;
1424                 datablk_count = sqfs_get_regfile_info(reg, &finfo, &frag_entry,
1425                                                       sblk->block_size);
1426                 if (datablk_count < 0) {
1427                         ret = -EINVAL;
1428                         goto out;
1429                 }
1430
1431                 memcpy(finfo.blk_sizes, ipos + sizeof(*reg),
1432                        datablk_count * sizeof(u32));
1433                 break;
1434         case SQFS_LREG_TYPE:
1435                 lreg = (struct squashfs_lreg_inode *)ipos;
1436                 datablk_count = sqfs_get_lregfile_info(lreg, &finfo,
1437                                                        &frag_entry,
1438                                                        sblk->block_size);
1439                 if (datablk_count < 0) {
1440                         ret = -EINVAL;
1441                         goto out;
1442                 }
1443
1444                 memcpy(finfo.blk_sizes, ipos + sizeof(*lreg),
1445                        datablk_count * sizeof(u32));
1446                 break;
1447         case SQFS_SYMLINK_TYPE:
1448         case SQFS_LSYMLINK_TYPE:
1449                 if (++symlinknest == MAX_SYMLINK_NEST) {
1450                         ret = -ELOOP;
1451                         goto out;
1452                 }
1453
1454                 symlink = (struct squashfs_symlink_inode *)ipos;
1455                 resolved = sqfs_resolve_symlink(symlink, filename);
1456                 ret = sqfs_read_nest(resolved, buf, offset, len, actread);
1457                 free(resolved);
1458                 goto out;
1459         case SQFS_BLKDEV_TYPE:
1460         case SQFS_CHRDEV_TYPE:
1461         case SQFS_LBLKDEV_TYPE:
1462         case SQFS_LCHRDEV_TYPE:
1463         case SQFS_FIFO_TYPE:
1464         case SQFS_SOCKET_TYPE:
1465         case SQFS_LFIFO_TYPE:
1466         case SQFS_LSOCKET_TYPE:
1467         default:
1468                 printf("Unsupported entry type\n");
1469                 ret = -EINVAL;
1470                 goto out;
1471         }
1472
1473         /* If the user specifies a length, check its sanity */
1474         if (len) {
1475                 if (len > finfo.size) {
1476                         ret = -EINVAL;
1477                         goto out;
1478                 }
1479
1480                 finfo.size = len;
1481         } else {
1482                 len = finfo.size;
1483         }
1484
1485         if (datablk_count) {
1486                 data_offset = finfo.start;
1487                 datablock = malloc(get_unaligned_le32(&sblk->block_size));
1488                 if (!datablock) {
1489                         ret = -ENOMEM;
1490                         goto out;
1491                 }
1492         }
1493
1494         for (j = 0; j < datablk_count; j++) {
1495                 char *data_buffer;
1496
1497                 start = lldiv(data_offset, ctxt.cur_dev->blksz);
1498                 table_size = SQFS_BLOCK_SIZE(finfo.blk_sizes[j]);
1499                 table_offset = data_offset - (start * ctxt.cur_dev->blksz);
1500                 n_blks = DIV_ROUND_UP(table_size + table_offset,
1501                                       ctxt.cur_dev->blksz);
1502
1503                 /* Don't load any data for sparse blocks */
1504                 if (finfo.blk_sizes[j] == 0) {
1505                         n_blks = 0;
1506                         table_offset = 0;
1507                         data_buffer = NULL;
1508                         data = NULL;
1509                 } else {
1510                         data_buffer = malloc_cache_aligned(n_blks * ctxt.cur_dev->blksz);
1511
1512                         if (!data_buffer) {
1513                                 ret = -ENOMEM;
1514                                 goto out;
1515                         }
1516
1517                         ret = sqfs_disk_read(start, n_blks, data_buffer);
1518                         if (ret < 0) {
1519                                 /*
1520                                  * Possible causes: too many data blocks or too large
1521                                  * SquashFS block size. Tip: re-compile the SquashFS
1522                                  * image with mksquashfs's -b <block_size> option.
1523                                  */
1524                                 printf("Error: too many data blocks to be read.\n");
1525                                 goto out;
1526                         }
1527
1528                         data = data_buffer + table_offset;
1529                 }
1530
1531                 /* Load the data */
1532                 if (finfo.blk_sizes[j] == 0) {
1533                         /* This is a sparse block */
1534                         sparse_size = get_unaligned_le32(&sblk->block_size);
1535                         if ((*actread + sparse_size) > len)
1536                                 sparse_size = len - *actread;
1537                         memset(buf + *actread, 0, sparse_size);
1538                         *actread += sparse_size;
1539                 } else if (SQFS_COMPRESSED_BLOCK(finfo.blk_sizes[j])) {
1540                         dest_len = get_unaligned_le32(&sblk->block_size);
1541                         ret = sqfs_decompress(&ctxt, datablock, &dest_len,
1542                                               data, table_size);
1543                         if (ret)
1544                                 goto out;
1545
1546                         if ((*actread + dest_len) > len)
1547                                 dest_len = len - *actread;
1548                         memcpy(buf + *actread, datablock, dest_len);
1549                         *actread += dest_len;
1550                 } else {
1551                         if ((*actread + table_size) > len)
1552                                 table_size = len - *actread;
1553                         memcpy(buf + *actread, data, table_size);
1554                         *actread += table_size;
1555                 }
1556
1557                 data_offset += table_size;
1558                 free(data_buffer);
1559                 if (*actread >= len)
1560                         break;
1561         }
1562
1563         /*
1564          * There is no need to continue if the file is not fragmented.
1565          */
1566         if (!finfo.frag) {
1567                 ret = 0;
1568                 goto out;
1569         }
1570
1571         start = lldiv(frag_entry.start, ctxt.cur_dev->blksz);
1572         table_size = SQFS_BLOCK_SIZE(frag_entry.size);
1573         table_offset = frag_entry.start - (start * ctxt.cur_dev->blksz);
1574         n_blks = DIV_ROUND_UP(table_size + table_offset, ctxt.cur_dev->blksz);
1575
1576         fragment = malloc_cache_aligned(n_blks * ctxt.cur_dev->blksz);
1577
1578         if (!fragment) {
1579                 ret = -ENOMEM;
1580                 goto out;
1581         }
1582
1583         ret = sqfs_disk_read(start, n_blks, fragment);
1584         if (ret < 0)
1585                 goto out;
1586
1587         /* File compressed and fragmented */
1588         if (finfo.frag && finfo.comp) {
1589                 dest_len = get_unaligned_le32(&sblk->block_size);
1590                 fragment_block = malloc(dest_len);
1591                 if (!fragment_block) {
1592                         ret = -ENOMEM;
1593                         goto out;
1594                 }
1595
1596                 ret = sqfs_decompress(&ctxt, fragment_block, &dest_len,
1597                                       (void *)fragment  + table_offset,
1598                                       frag_entry.size);
1599                 if (ret) {
1600                         free(fragment_block);
1601                         goto out;
1602                 }
1603
1604                 memcpy(buf + *actread, &fragment_block[finfo.offset], finfo.size - *actread);
1605                 *actread = finfo.size;
1606
1607                 free(fragment_block);
1608
1609         } else if (finfo.frag && !finfo.comp) {
1610                 fragment_block = (void *)fragment + table_offset;
1611
1612                 memcpy(buf + *actread, &fragment_block[finfo.offset], finfo.size - *actread);
1613                 *actread = finfo.size;
1614         }
1615
1616 out:
1617         free(fragment);
1618         free(datablock);
1619         free(file);
1620         free(dir);
1621         free(finfo.blk_sizes);
1622         sqfs_closedir(dirsp);
1623
1624         return ret;
1625 }
1626
1627 int sqfs_read(const char *filename, void *buf, loff_t offset, loff_t len,
1628               loff_t *actread)
1629 {
1630         symlinknest = 0;
1631         return sqfs_read_nest(filename, buf, offset, len, actread);
1632 }
1633
1634 static int sqfs_size_nest(const char *filename, loff_t *size)
1635 {
1636         struct squashfs_super_block *sblk = ctxt.sblk;
1637         struct squashfs_symlink_inode *symlink;
1638         struct fs_dir_stream *dirsp = NULL;
1639         struct squashfs_base_inode *base;
1640         struct squashfs_dir_stream *dirs;
1641         struct squashfs_lreg_inode *lreg;
1642         struct squashfs_reg_inode *reg;
1643         char *dir, *file, *resolved;
1644         struct fs_dirent *dent;
1645         unsigned char *ipos;
1646         int ret, i_number;
1647
1648         sqfs_split_path(&file, &dir, filename);
1649         /*
1650          * sqfs_opendir_nest will uncompress inode and directory tables, and will
1651          * return a pointer to the directory that contains the requested file.
1652          */
1653         ret = sqfs_opendir_nest(dir, &dirsp);
1654         if (ret) {
1655                 ret = -EINVAL;
1656                 goto free_strings;
1657         }
1658
1659         dirs = (struct squashfs_dir_stream *)dirsp;
1660
1661         while (!sqfs_readdir_nest(dirsp, &dent)) {
1662                 ret = strcmp(dent->name, file);
1663                 if (!ret)
1664                         break;
1665                 free(dirs->entry);
1666                 dirs->entry = NULL;
1667         }
1668
1669         if (ret) {
1670                 printf("File not found.\n");
1671                 *size = 0;
1672                 ret = -EINVAL;
1673                 goto free_strings;
1674         }
1675
1676         i_number = dirs->dir_header->inode_number + dirs->entry->inode_offset;
1677         ipos = sqfs_find_inode(dirs->inode_table, i_number, sblk->inodes,
1678                                sblk->block_size);
1679
1680         if (!ipos) {
1681                 *size = 0;
1682                 ret = -EINVAL;
1683                 goto free_strings;
1684         }
1685
1686         free(dirs->entry);
1687         dirs->entry = NULL;
1688
1689         base = (struct squashfs_base_inode *)ipos;
1690         switch (get_unaligned_le16(&base->inode_type)) {
1691         case SQFS_REG_TYPE:
1692                 reg = (struct squashfs_reg_inode *)ipos;
1693                 *size = get_unaligned_le32(&reg->file_size);
1694                 break;
1695         case SQFS_LREG_TYPE:
1696                 lreg = (struct squashfs_lreg_inode *)ipos;
1697                 *size = get_unaligned_le64(&lreg->file_size);
1698                 break;
1699         case SQFS_SYMLINK_TYPE:
1700         case SQFS_LSYMLINK_TYPE:
1701                 if (++symlinknest == MAX_SYMLINK_NEST) {
1702                         *size = 0;
1703                         return -ELOOP;
1704                 }
1705
1706                 symlink = (struct squashfs_symlink_inode *)ipos;
1707                 resolved = sqfs_resolve_symlink(symlink, filename);
1708                 ret = sqfs_size(resolved, size);
1709                 free(resolved);
1710                 break;
1711         case SQFS_BLKDEV_TYPE:
1712         case SQFS_CHRDEV_TYPE:
1713         case SQFS_LBLKDEV_TYPE:
1714         case SQFS_LCHRDEV_TYPE:
1715         case SQFS_FIFO_TYPE:
1716         case SQFS_SOCKET_TYPE:
1717         case SQFS_LFIFO_TYPE:
1718         case SQFS_LSOCKET_TYPE:
1719         default:
1720                 printf("Unable to recover entry's size.\n");
1721                 *size = 0;
1722                 ret = -EINVAL;
1723                 break;
1724         }
1725
1726 free_strings:
1727         free(dir);
1728         free(file);
1729
1730         sqfs_closedir(dirsp);
1731
1732         return ret;
1733 }
1734
1735 int sqfs_exists(const char *filename)
1736 {
1737         struct fs_dir_stream *dirsp = NULL;
1738         struct squashfs_dir_stream *dirs;
1739         char *dir, *file;
1740         struct fs_dirent *dent;
1741         int ret;
1742
1743         sqfs_split_path(&file, &dir, filename);
1744         /*
1745          * sqfs_opendir_nest will uncompress inode and directory tables, and will
1746          * return a pointer to the directory that contains the requested file.
1747          */
1748         symlinknest = 0;
1749         ret = sqfs_opendir_nest(dir, &dirsp);
1750         if (ret) {
1751                 ret = -EINVAL;
1752                 goto free_strings;
1753         }
1754
1755         dirs = (struct squashfs_dir_stream *)dirsp;
1756
1757         while (!sqfs_readdir_nest(dirsp, &dent)) {
1758                 ret = strcmp(dent->name, file);
1759                 if (!ret)
1760                         break;
1761                 free(dirs->entry);
1762                 dirs->entry = NULL;
1763         }
1764
1765         sqfs_closedir(dirsp);
1766
1767 free_strings:
1768         free(dir);
1769         free(file);
1770
1771         return ret == 0;
1772 }
1773
1774 int sqfs_size(const char *filename, loff_t *size)
1775 {
1776         symlinknest = 0;
1777         return sqfs_size_nest(filename, size);
1778 }
1779
1780 void sqfs_close(void)
1781 {
1782         sqfs_decompressor_cleanup(&ctxt);
1783         free(ctxt.sblk);
1784         ctxt.sblk = NULL;
1785         ctxt.cur_dev = NULL;
1786 }
1787
1788 void sqfs_closedir(struct fs_dir_stream *dirs)
1789 {
1790         struct squashfs_dir_stream *sqfs_dirs;
1791
1792         if (!dirs)
1793                 return;
1794
1795         sqfs_dirs = (struct squashfs_dir_stream *)dirs;
1796         free(sqfs_dirs->inode_table);
1797         free(sqfs_dirs->dir_table);
1798         free(sqfs_dirs->dir_header);
1799         free(sqfs_dirs);
1800 }
This page took 0.127969 seconds and 4 git commands to generate.