pax_global_header00006660000000000000000000000064132572033400014511gustar00rootroot0000000000000052 comment=39bd7d48d95ce572061905450ffbf924d15d47f9 unyaffs-0.9.7/000077500000000000000000000000001325720334000132015ustar00rootroot00000000000000unyaffs-0.9.7/.gitignore000066400000000000000000000000101325720334000151600ustar00rootroot00000000000000unyaffs unyaffs-0.9.7/Makefile000066400000000000000000000002111325720334000146330ustar00rootroot00000000000000CFLAGS += -O2 -Wall unyaffs: unyaffs.c unyaffs.h $(CC) $(CFLAGS) $(LDFLAGS) unyaffs.c -o unyaffs .PHONY: clean clean: rm -f unyaffs unyaffs-0.9.7/README000066400000000000000000000076711325720334000140740ustar00rootroot00000000000000unyaffs ======= Overview -------- Unyaffs is a program to extract files from a YAFFS2 file system image. Currently it can only extract images created by mkyaffs2image. Unyaffs is based on work of the YAFFS project, see http://www.yaffs.net/ The original implementation was done by Kai Wei , it is available at http://code.google.com/p/unyaffs/ As the project was inactive, Bernhard Ehlers started a fork at https://github.com/ehlers/unyaffs License ------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. The full license text is available in the file gpl-2.0.txt. Requirements ------------ Unyaffs should run on most unix-like operating systems. A C compiler environment and make is necessary to compile it. Compiling --------- type "make" Usage ----- unyaffs - extract files from a YAFFS2 file system image. Usage: unyaffs [options] [] Options: -d detection of flash layout, no extraction -b spare contains bad block information -c set chunk size in KByte (default: autodetect, max: 16) -s set spare size in Byte (default: autodetect, max: 512) -t list image contents -v verbose output -V print version In most cases the flash memory layout is detected automatically. If the detection doesn't work properly, the layout can be set with options -c and -s. If spare contains bad block info, set option -b. Option -t lists all the file names in the image without extracting them. Option -v generates a 'ls -l' like listing of the extracted files. When combined with -t it generates an extended file listing, nothing is extracted. The image file can be - for standard input. If the extraction directory is not given, the files are stored into the current directory. If the extraction dir doesn't exist, it will be created. unyaffs extracts all file types (regular files, directories, soft links, hard links and special files). The permissions and modification dates are restored. When run as root, the ownership is restored as well. Please be careful extracting images as root. It might be possible, that important system files get overwritten. The use of chroot or fakeroot can guard against these problems. Limitations ----------- Block and character devices can only be restored as root. In some operating systems (e.g. Mac OS X) sockets can't be restored. The use of special files (block devices, character devices, pipes, sockets) is not portable across different unix flavors. E.g. device files created on linux will get a strange major and minor device id, when restored under BSD. When it's necessary to deal with special files, please use the same OS as used in the system the image is build for. In most cases that's linux. Windows ------- The differences between the unix and windows file system are big enough to make a windows port of unyaffs a complicated task. But with cygwin (http://www.cygwin.com/) a unix compatibility layer for windows is available. The unmodified source compiles and runs nicely within cygwin. The main differences to a pure unix environment: - Unix functionality only within cygwin environment, native windows programs won't see the more advanced features. - Permissions and file dates/time are correctly restored - Owner/group are not fully restored, only user/groups available in windows - Hard and soft links are correctly restored - Device files have different ids as in linux - Sockets are not restored For analysis of a firmware image, unyaffs within cygwin is a nice tool, but because of the restricted user/group functionality rebuilding a modified image can't be recommended. unyaffs-0.9.7/gpl-2.0.txt000066400000000000000000000432541325720334000150310ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. unyaffs-0.9.7/unyaffs.1000066400000000000000000000013331325720334000147360ustar00rootroot00000000000000.\" (C) Copyright 2013 Matthew Fischer , .TH UNYAFFS 1 "March 23, 2013" .SH NAME unyaffs \- extract files from a YAFFS2 file system image .SH SYNOPSIS .B unyaffs .RI [ options ] [] .SH DESCRIPTION .B unyaffs extracts files from a YAFFS2 file system image that was created with mkyaffs2image. .PP .SH OPTIONS .TP .B \-d detect of flash layout, no extraction .TP .B \-b spare contains bad block information .TP .B \-c get chunk size in KByte (default: autodetect, max: 16) .TP .B \-s set spare size in Byte (default: autodetect, max: 512) .TP .B \-t list image contents .TP .B \-v verbose output .TP .B \-V print version information .sp .LP unyaffs-0.9.7/unyaffs.c000066400000000000000000000520511325720334000150230ustar00rootroot00000000000000/* * unyaffs: extract files from yaffs2 file system image to current directory * * Created by Kai Wei * Modified by Bernhard Ehlers * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /* * History: * V0.1 2008-12-29 * Initial version uploaded to http://code.google.com/p/unyaffs/ * V0.8 2011-08-25 * Fork created at https://github.com/ehlers/unyaffs * Support of chunksizes from 2k to 16k * Restore special files (device nodes) * Restore file date and time * Restore file ownership, when run as root * File listing * Much more error checking * V0.9 2011-09-03 * Allow - as filename for stdin * Optional base dir for file extraction * V0.9.1 2012-04-12 * Additional flash layout: 8k chunk size, 448 byte spare * V0.9.2 2012-04-18 * Additional flash layout: 8k chunk size, 368 byte spare * New options -c and -s to set chunk and spare size, obsoletes option -l * Add support for bad block information in spare header. * Allow first data chunk to be stored in image before file header. * V0.9.3 2012-04-30 * check result of lchown system call * Code cleanup * V0.9.4 2012-05-01 * No predefined flash layouts, detect all possible layouts * Option -d shows detected flash layout, no extraction * V0.9.5 2012-12-02 * Bug in verifying the -s (spare) parameter * V0.9.6 2013-04-09 * Added man page * V0.9.7 2018-03-29 * Directory creation doesn't fail, if it already exists * Fix compiler warnings for newer GCC */ #define VERSION "0.9.7" /* check if lutimes is available */ #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || (defined(__APPLE__) && defined(__MACH__)) #define HAS_LUTIMES 1 #endif #include #include #include #include #include #include #include #include #include #include #include #if defined(__linux__) || defined(__GLIBC__) #include #endif #ifdef HAS_LUTIMES #include #else #include #endif #include "unyaffs.h" #define MIN_CHUNK_SIZE 2048 #define MAX_CHUNK_SIZE 16384 #define MIN_SPARE_SIZE 64 #define MAX_SPARE_SIZE 512 #define HASH_SIZE 7001 #define MAX_WARN 20 #define YAFFS_OBJECTID_ROOT 1 #define STD_PERMS (S_IRWXU|S_IRWXG|S_IRWXO) #define EXTRA_PERMS (S_ISUID|S_ISGID|S_ISVTX) unsigned char data[MAX_CHUNK_SIZE + MAX_SPARE_SIZE]; unsigned char buffer[4*(MAX_CHUNK_SIZE + MAX_SPARE_SIZE)]; unsigned char *chunk_data = data; unsigned char *spare_data = NULL; int chunk_size = MIN_CHUNK_SIZE; int spare_size = MIN_SPARE_SIZE; int spare_off = 0; int buf_len = 0; int buf_idx = 0; int chunk_no = 0; int warn_count = 0; int warn_chown = 0; int img_file; int opt_list; int opt_verbose; typedef struct _object { unsigned id; struct _object *next; yaffs_ObjectType type; unsigned prev_dir_id; __u32 atime; __u32 mtime; char path_name[1]; /* variable length, must be last */ } object; object *obj_list[HASH_SIZE]; unsigned last_dir_id; int set_utime(const char *filename, __u32 yst_atime, __u32 yst_mtime) { #ifdef HAS_LUTIMES struct timeval ftime[2]; ftime[0].tv_sec = yst_atime; ftime[0].tv_usec = 0; ftime[1].tv_sec = yst_mtime; ftime[1].tv_usec = 0; return lutimes(filename, ftime); #else struct utimbuf ftime; ftime.actime = yst_atime; ftime.modtime = yst_mtime; return utime(filename, &ftime); #endif } /* error reporting function, similar to GNU error() */ static void prt_err(int status, int errnum, const char *format, ...) { va_list varg; va_start(varg, format); fflush(stdout); vfprintf(stderr, format, varg); if (errnum != 0) fprintf(stderr, ": %s", strerror(errnum)); fprintf(stderr, "\n"); va_end(varg); if (status != 0) exit(status); } /* read function, which handles partial and interrupted reads */ ssize_t safe_read(int fd, void *buf, size_t len) { char *ptr = buf; ssize_t offset, ret; offset = 0; while (offset < len) { ret = read(fd, ptr+offset, len-offset); if (ret < 0) { if (errno != EAGAIN && errno != EINTR) return -1; } else if (ret == 0) break; else offset += ret; } return offset; } /* write function, which handles partial and interrupted writes */ ssize_t safe_write(int fd, void *buf, size_t len) { char *ptr = buf; ssize_t offset, ret; offset = 0; while (offset < len) { ret = write(fd, ptr+offset, len-offset); if (ret < 0) { if (errno != EAGAIN && errno != EINTR) return -1; } else if (ret == 0) break; else offset += ret; } return offset; } /* * mkdirpath - creates directories including intermediate dirs */ static int mkdirpath(const char *name, mode_t mode) { struct stat st; char *cp; char *buf; if ((buf = malloc(strlen(name)+1)) == NULL) { errno = ENOMEM; return -1; } strcpy(buf, name); cp = buf; while ((cp = strchr(cp, '/')) != NULL) { *cp = '\0'; mkdir(buf, 0755); *cp++ = '/'; } free(buf); if (mkdir(name, mode) < 0) { if (stat(name, &st) < 0 || !S_ISDIR(st.st_mode)) return -1; chmod(name, mode); } return 0; } /* * save_lchown - call lchown and check result */ static void safe_lchown(const char *path, uid_t owner, gid_t group) { if (lchown(path, owner, group) < 0) { if (errno == EPERM || errno == EINVAL) warn_chown = 1; else prt_err(1, errno, "Can't chown %s", path); } } static void init_obj_list(void) { object *obj; unsigned idx; for (idx = 0; idx < HASH_SIZE; idx++) obj_list[idx] = NULL; last_dir_id = 0; obj = malloc(offsetof(object, path_name) + 2); if (obj == NULL) prt_err(1, 0, "Malloc struct object failed."); obj->id = YAFFS_OBJECTID_ROOT; obj->type = YAFFS_OBJECT_TYPE_DIRECTORY; obj->prev_dir_id = 0; obj->atime = obj->mtime = 0; strcpy(obj->path_name, "."); idx = obj->id % HASH_SIZE; obj->next = obj_list[idx]; obj_list[idx] = obj; } static object *get_object(unsigned id) { object *obj; obj = obj_list[id % HASH_SIZE]; while (obj != NULL && obj->id != id) obj = obj->next; return obj; } static object *add_object(yaffs_ObjectHeader *oh, yaffs_PackedTags2 *pt) { object *obj, *parent; unsigned idx; obj = get_object(pt->t.objectId); if (pt->t.objectId == YAFFS_OBJECTID_ROOT) { if (obj == NULL) prt_err(1, 0, "Missing root object"); if (oh->type != YAFFS_OBJECT_TYPE_DIRECTORY) prt_err(1, 0, "Root object must be directory"); if (last_dir_id == 0) last_dir_id = YAFFS_OBJECTID_ROOT; } else { if (oh->type != YAFFS_OBJECT_TYPE_FILE && oh->type != YAFFS_OBJECT_TYPE_DIRECTORY && oh->type != YAFFS_OBJECT_TYPE_SYMLINK && oh->type != YAFFS_OBJECT_TYPE_HARDLINK && oh->type != YAFFS_OBJECT_TYPE_SPECIAL && oh->type != YAFFS_OBJECT_TYPE_UNKNOWN) prt_err(1, 0, "Illegal type %d in object %u (%s)", oh->type, pt->t.objectId, oh->name); if (oh->name[0] == '\0' || strchr(oh->name, '/') != NULL || strcmp(oh->name, ".") == 0 || strcmp(oh->name, "..") == 0) prt_err(1, 0, "Illegal file name %s in object %u", oh->name, pt->t.objectId); if (obj != NULL) prt_err(1, 0, "Duplicate objectId %u", pt->t.objectId); parent = get_object(oh->parentObjectId); if (parent == NULL) prt_err(1, 0, "Invalid parentObjectId %u in object %u (%s)", oh->parentObjectId, pt->t.objectId, oh->name); if (parent->type != YAFFS_OBJECT_TYPE_DIRECTORY) prt_err(1, ENOTDIR, "File %s can't be created in %s", oh->name, parent->path_name); obj = malloc(offsetof(object, path_name) + strlen(parent->path_name) + strlen(oh->name) + 2); if (obj == NULL) prt_err(1, 0, "Malloc struct object failed."); obj->id = pt->t.objectId; obj->type = oh->type; if (obj->type == YAFFS_OBJECT_TYPE_DIRECTORY) { obj->prev_dir_id = last_dir_id; last_dir_id = obj->id; } else obj->prev_dir_id = 0; if (strcmp(parent->path_name, ".") == 0) { strcpy(obj->path_name, oh->name); } else { strcpy(obj->path_name, parent->path_name); strcat(obj->path_name, "/"); strcat(obj->path_name, oh->name); } idx = obj->id % HASH_SIZE; obj->next = obj_list[idx]; obj_list[idx] = obj; } obj->atime = oh->yst_atime; obj->mtime = oh->yst_mtime; return obj; } void set_dirs_utime(void) { unsigned id; object *obj; id = last_dir_id; while (id != 0 && (obj = get_object(id)) != NULL) { set_utime(obj->path_name, obj->atime, obj->mtime); id = obj->prev_dir_id; } } static void prt_node(char *name, yaffs_ObjectHeader *oh) { object *eq_obj; struct tm tm; time_t mtime; mode_t mode; char type; char fsize[16]; char perm[10]; /* get file type, size, mtine and mode */ eq_obj = NULL; strcpy(fsize, "0"); mtime = oh->yst_mtime; mode = oh->yst_mode; switch(oh->type) { case YAFFS_OBJECT_TYPE_FILE: type = '-'; snprintf(fsize, sizeof(fsize), "%d", oh->fileSize); break; case YAFFS_OBJECT_TYPE_DIRECTORY: type = 'd'; break; case YAFFS_OBJECT_TYPE_SYMLINK: type = 'l'; break; case YAFFS_OBJECT_TYPE_HARDLINK: type = 'h'; eq_obj = get_object(oh->equivalentObjectId); mtime = eq_obj != NULL ? eq_obj->mtime : 0; mode = STD_PERMS; break; case YAFFS_OBJECT_TYPE_SPECIAL: switch (oh->yst_mode & S_IFMT) { case S_IFBLK: type = 'b'; snprintf(fsize, sizeof(fsize), "%d,%4d", major(oh->yst_rdev), minor(oh->yst_rdev)); break; case S_IFCHR: type = 'c'; snprintf(fsize, sizeof(fsize), "%d,%4d", major(oh->yst_rdev), minor(oh->yst_rdev)); break; case S_IFIFO: type = 'p'; break; case S_IFSOCK: type = 's'; break; default: type = '?'; break; } break; default: type = '?'; break; } /* get file permissions */ perm[0] = mode & S_IRUSR ? 'r' : '-'; perm[1] = mode & S_IWUSR ? 'w' : '-'; perm[2] = mode & S_IXUSR ? 'x' : '-'; perm[3] = mode & S_IRGRP ? 'r' : '-'; perm[4] = mode & S_IWGRP ? 'w' : '-'; perm[5] = mode & S_IXGRP ? 'x' : '-'; perm[6] = mode & S_IROTH ? 'r' : '-'; perm[7] = mode & S_IWOTH ? 'w' : '-'; perm[8] = mode & S_IXOTH ? 'x' : '-'; if (mode & S_ISUID) perm[2] = perm[2] == '-' ? 'S' : 's'; if (mode & S_ISGID) perm[5] = perm[5] == '-' ? 'S' : 's'; if (mode & S_ISVTX) perm[8] = perm[8] == '-' ? 'T' : 't'; perm[9] = '\0'; /* print file infos */ localtime_r(&mtime, &tm); printf("%c%s %8s %4d-%02d-%02d %02d:%02d %s", type, perm, fsize, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, name); /* link destination */ if (oh->type == YAFFS_OBJECT_TYPE_HARDLINK) { if (eq_obj == NULL) printf(" -> !!! Invalid !!!"); else printf(" -> /%s", eq_obj->path_name); } else if (oh->type == YAFFS_OBJECT_TYPE_SYMLINK) { printf(" -> %s", oh->alias); } printf("\n"); } int read_chunk(void); static struct { unsigned objectId; int chunk_no; unsigned char data[MAX_CHUNK_SIZE + MAX_SPARE_SIZE]; } saved_chunk; int next_data_chunk(void) { yaffs_PackedTags2 *pt; unsigned next_objectId; unsigned next_chunkId; int ret = 0; pt = (yaffs_PackedTags2 *)spare_data; next_objectId = pt->t.objectId; next_chunkId = pt->t.chunkId + 1; if (saved_chunk.objectId == next_objectId && /* use saved chunk ? */ next_chunkId == 1) { memcpy(chunk_data, saved_chunk.data, chunk_size); memcpy(spare_data, saved_chunk.data+chunk_size, spare_size); saved_chunk.objectId = 0; ret = 1; } else { if (read_chunk() && /* valid next chunk ? */ pt->t.objectId == next_objectId && pt->t.chunkId == next_chunkId) { ret = 1; } } return ret; } void process_chunk(void) { yaffs_ObjectHeader oh; yaffs_PackedTags2 *pt; object *obj, *eq_obj; int out_file, remain, s; oh = *(yaffs_ObjectHeader *)chunk_data; pt = (yaffs_PackedTags2 *)spare_data; if (pt->t.sequenceNumber == 0xffffffff) /* empty object */ return; if (saved_chunk.objectId != 0 && /* saved chunk is not part of object */ saved_chunk.objectId != pt->t.objectId) { prt_err(0, 0, "Warning: Invalid header at chunk #%d, skipping...", saved_chunk.chunk_no); if (++warn_count >= MAX_WARN) prt_err(1, 0, "Giving up"); saved_chunk.objectId = 0; } if (pt->t.chunkId == 1) { /* save chunk #1 */ saved_chunk.objectId = pt->t.objectId; saved_chunk.chunk_no = chunk_no; memcpy(saved_chunk.data, chunk_data, chunk_size); memcpy(saved_chunk.data+chunk_size, spare_data, spare_size); return; } else if (pt->t.chunkId != 0) { /* not a new object */ prt_err(0, 0, "Warning: Invalid header at chunk #%d, skipping...", chunk_no); if (++warn_count >= MAX_WARN) prt_err(1, 0, "Giving up"); return; } obj = add_object(&oh, pt); /* listing */ if (opt_verbose) prt_node(obj->path_name, &oh); else if (opt_list) printf("%s\n", obj->path_name); if (opt_list) { if (oh.type == YAFFS_OBJECT_TYPE_FILE) { remain = oh.fileSize; /* skip over data chunks */ while(remain > 0) { if (!next_data_chunk()) prt_err(1, 0, "Broken image file"); remain -= pt->t.byteCount; } } return; } switch(oh.type) { case YAFFS_OBJECT_TYPE_FILE: remain = oh.fileSize; out_file = creat(obj->path_name, oh.yst_mode & STD_PERMS); if (out_file < 0) prt_err(1, errno, "Can't create file %s", obj->path_name); while(remain > 0) { if (!next_data_chunk()) prt_err(1, 0, "Broken image file"); s = (remain < pt->t.byteCount) ? remain : pt->t.byteCount; if (safe_write(out_file, chunk_data, s) < 0) prt_err(1, errno, "Can't write to %s", obj->path_name); remain -= s; } close(out_file); safe_lchown(obj->path_name, oh.yst_uid, oh.yst_gid); if ((oh.yst_mode & EXTRA_PERMS) != 0 && chmod(obj->path_name, oh.yst_mode) < 0) prt_err(0, errno, "Warning: Can't chmod %s", obj->path_name); break; case YAFFS_OBJECT_TYPE_SYMLINK: if (symlink(oh.alias, obj->path_name) < 0) prt_err(1, errno, "Can't create symlink %s", obj->path_name); safe_lchown(obj->path_name, oh.yst_uid, oh.yst_gid); break; case YAFFS_OBJECT_TYPE_DIRECTORY: if (pt->t.objectId != YAFFS_OBJECTID_ROOT && mkdirpath(obj->path_name, oh.yst_mode & STD_PERMS) < 0) prt_err(1, errno, "Can't create directory %s", obj->path_name); safe_lchown(obj->path_name, oh.yst_uid, oh.yst_gid); if ((pt->t.objectId == YAFFS_OBJECTID_ROOT || (oh.yst_mode & EXTRA_PERMS) != 0) && chmod(obj->path_name, oh.yst_mode) < 0) prt_err(0, errno, "Warning: Can't chmod %s", obj->path_name); break; case YAFFS_OBJECT_TYPE_HARDLINK: eq_obj = get_object(oh.equivalentObjectId); if (eq_obj == NULL) prt_err(1, 0, "Invalid equivalentObjectId %u in object %u (%s)", oh.equivalentObjectId, pt->t.objectId, oh.name); if (link(eq_obj->path_name, obj->path_name) < 0) prt_err(1, errno, "Can't create hardlink %s", obj->path_name); break; case YAFFS_OBJECT_TYPE_SPECIAL: if (mknod(obj->path_name, oh.yst_mode, oh.yst_rdev) < 0) { if (errno == EPERM || errno == EINVAL) prt_err(0, errno, "Warning: Can't create device %s", obj->path_name); else prt_err(1, errno, "Can't create device %s", obj->path_name); } else safe_lchown(obj->path_name, oh.yst_uid, oh.yst_gid); break; case YAFFS_OBJECT_TYPE_UNKNOWN: break; } /* set file date and time */ switch(oh.type) { case YAFFS_OBJECT_TYPE_FILE: case YAFFS_OBJECT_TYPE_SPECIAL: #ifdef HAS_LUTIMES case YAFFS_OBJECT_TYPE_SYMLINK: #endif set_utime(obj->path_name, oh.yst_atime, oh.yst_mtime); break; case YAFFS_OBJECT_TYPE_DIRECTORY: default: break; } } int read_chunk(void) { ssize_t s, len, offset; chunk_no++; len = chunk_size + spare_size; offset = 0; memset(data, 0xff, len); if (buf_len > buf_idx) { /* copy from buffer */ s = buf_len - buf_idx; if (s > len) s = len; memcpy(data, buffer+buf_idx, s); buf_idx += s; offset += s; } if (offset < len) { /* read from file */ s = safe_read(img_file, data+offset, len-offset); if (s < 0) prt_err(1, errno, "Read image file"); offset += s; } if (offset != 0 && offset != len) /* partial chunk */ prt_err(1, 0, "Broken image file"); if (offset == len && spare_off != 0) { /* bad block info */ memmove(data+chunk_size, data+chunk_size+spare_off, spare_size-spare_off); memset(data+len-spare_off, 0xff, spare_off); } return offset != 0; } int check_layout(int chunk, int spare, int off) { yaffs_ObjectHeader oh; yaffs_PackedTags2 pt; int i, detect; for (i = 0, detect = 1; i < 4 && detect; i++) { memcpy(&oh, buffer + i * (chunk+spare), sizeof(oh)); memcpy(&pt, buffer + i * (chunk+spare) + chunk+off, sizeof(pt)); detect = (pt.t.chunkId > 0 && pt.t.chunkId <= 10 && pt.t.objectId >= 0x100 && pt.t.objectId <= (0x100+10) && pt.t.byteCount <= chunk) || (pt.t.chunkId == 0 && (pt.t.objectId == YAFFS_OBJECTID_ROOT || (pt.t.objectId >= 0x100 && pt.t.objectId <= (0x100+10))) && pt.t.byteCount == 0xffff && (oh.type == YAFFS_OBJECT_TYPE_FILE || oh.type == YAFFS_OBJECT_TYPE_DIRECTORY || oh.type == YAFFS_OBJECT_TYPE_SYMLINK || oh.type == YAFFS_OBJECT_TYPE_HARDLINK || oh.type == YAFFS_OBJECT_TYPE_SPECIAL)); } return detect; } void detect_flash_layout(int show, int first) { int cnt; int chunk, spare, off; memset(buffer, 0xff, sizeof(buffer)); buf_len = safe_read(img_file, buffer, sizeof(buffer)); if (buf_len < 0) prt_err(1, errno, "Read image file"); if (show) printf("Detected flash layout(s):\n"); cnt = 0; for (chunk = MIN_CHUNK_SIZE; chunk <= MAX_CHUNK_SIZE; chunk *= 2) { for (spare = MIN_SPARE_SIZE; spare <= MAX_SPARE_SIZE; spare += 16) { for (off = 0; off <= 2; off += 2) { if (check_layout(chunk, spare, off)) { cnt++; if (show) { printf("%2s -c %-2d -s %-3d : chunk size = %2dK, spare size = %3d, %sbad block info\n", off ? "-b" : "", chunk / 1024, spare, chunk / 1024, spare, off ? "" : "no "); } if (first) { chunk_size = chunk; spare_size = spare; spare_off = off; return; } } } } } if (cnt == 0) { if (show) { printf("-- none --\n"); exit(1); } else { prt_err(1, 0, "Can't determine flash layout, perhaps not a yaffs2 image"); } } } void usage(void) { fprintf(stderr, "\ unyaffs V%s - extract files from a YAFFS2 file system image.\n\ \n\ Usage: unyaffs [options] []\n\ \n\ Options:\n\ -d detection of flash layout, no extraction\n\ -b spare contains bad block information\n\ -c set chunk size in KByte (default: autodetect, max: %d)\n\ -s set spare size in Byte (default: autodetect, max: %d)\n\ -t list image contents\n\ -v verbose output\n\ -V print version\n\ ", VERSION, MAX_CHUNK_SIZE / 1024, MAX_SPARE_SIZE); exit(1); } int main(int argc, char **argv) { int ch; char *ep; int opt_detect; int opt_bad; int opt_chunk; int opt_spare; /* handle command line options */ opt_detect = 0; opt_bad = 0; opt_chunk = 0; opt_spare = 0; opt_list = 0; opt_verbose = 0; while ((ch = getopt(argc, argv, "dbc:s:tvVh?")) > 0) { switch (ch) { case 'd': opt_detect = 1; break; case 'b': opt_bad = 1; break; case 'c': opt_chunk = strtol(optarg, &ep, 0); if (*ep != '\0' || opt_chunk < 0 || opt_chunk > (MAX_CHUNK_SIZE / 1024) ) usage(); break; case 's': opt_spare = strtol(optarg, &ep, 0); if (*ep != '\0' || opt_spare < 0 || opt_spare > MAX_SPARE_SIZE) usage(); break; case 't': opt_list = 1; break; case 'v': opt_verbose = 1; break; case 'V': printf("V%s\n", VERSION); exit(0); break; case 'h': case '?': default: usage(); break; } } /* extract rest of command line parameters */ if ((argc - optind) < 1 || (argc - optind) > 2) usage(); if (strcmp(argv[optind], "-") == 0) { /* image file from stdin ? */ img_file = 0; } else { img_file = open(argv[optind], O_RDONLY); if (img_file < 0) prt_err(1, errno, "Open image file failed"); } if (opt_detect) { detect_flash_layout(1, 0); return 0; } if (opt_chunk == 0 || opt_spare == 0) { detect_flash_layout(0, 1); if (opt_verbose) prt_err(0, 0, "Header check OK, chunk size = %dK, spare size = %d, %sbad block info.", chunk_size/1024, spare_size, spare_off ? "" : "no "); } else { chunk_size = opt_chunk * 1024; spare_size = opt_spare; spare_off = opt_bad ? 2 : 0; } spare_data = data + chunk_size; if ((argc - optind) == 2 && !opt_list) { if (mkdirpath(argv[optind+1], 0755) < 0) prt_err(1, errno, "Can't mkdir %s", argv[optind+1]); if (chdir(argv[optind+1]) < 0) prt_err(1, errno, "Can't chdir to %s", argv[optind+1]); } umask(0); init_obj_list(); saved_chunk.objectId = 0; while (read_chunk()) { process_chunk(); } set_dirs_utime(); close(img_file); if (warn_chown) #ifdef __CYGWIN__ prt_err(0, 0, "Warning: Can't restore owner/group attribute (limitation of Cygwin/Windows)"); #else prt_err(0, 0, "Warning: Can't restore owner/group attribute, run unyaffs as root"); #endif return 0; } unyaffs-0.9.7/unyaffs.h000066400000000000000000000041001325720334000150200ustar00rootroot00000000000000/* * definition copied from yaffs project */ #ifndef __UNYAFFS_H__ #define __UNYAFFS_H__ #define YAFFS_MAX_NAME_LENGTH 255 #define YAFFS_MAX_ALIAS_LENGTH 159 /* Definition of types */ typedef unsigned char __u8; typedef unsigned short __u16; typedef unsigned __u32; typedef struct { unsigned sequenceNumber; unsigned objectId; unsigned chunkId; unsigned byteCount; } yaffs_PackedTags2TagsPart; typedef struct { unsigned char colParity; unsigned lineParity; unsigned lineParityPrime; } yaffs_ECCOther; typedef struct { yaffs_PackedTags2TagsPart t; yaffs_ECCOther ecc; } yaffs_PackedTags2; typedef enum { YAFFS_OBJECT_TYPE_UNKNOWN, YAFFS_OBJECT_TYPE_FILE, YAFFS_OBJECT_TYPE_SYMLINK, YAFFS_OBJECT_TYPE_DIRECTORY, YAFFS_OBJECT_TYPE_HARDLINK, YAFFS_OBJECT_TYPE_SPECIAL } yaffs_ObjectType; /* -------------------------- Object structure -------------------------------*/ /* This is the object structure as stored on NAND */ typedef struct { yaffs_ObjectType type; /* Apply to everything */ int parentObjectId; __u16 sum__NoLongerUsed; /* checksum of name. No longer used */ char name[YAFFS_MAX_NAME_LENGTH + 1]; /* The following apply to directories, files, symlinks - not hard links */ __u32 yst_mode; /* protection */ #ifdef CONFIG_YAFFS_WINCE __u32 notForWinCE[5]; #else __u32 yst_uid; __u32 yst_gid; __u32 yst_atime; __u32 yst_mtime; __u32 yst_ctime; #endif /* File size applies to files only */ int fileSize; /* Equivalent object id applies to hard links only. */ int equivalentObjectId; /* Alias is for symlinks only. */ char alias[YAFFS_MAX_ALIAS_LENGTH + 1]; __u32 yst_rdev; /* device stuff for block and char devices (major/min) */ #ifdef CONFIG_YAFFS_WINCE __u32 win_ctime[2]; __u32 win_atime[2]; __u32 win_mtime[2]; #else __u32 roomToGrow[6]; #endif __u32 inbandShadowsObject; __u32 inbandIsShrink; __u32 reservedSpace[2]; int shadowsObject; /* This object header shadows the specified object if > 0 */ /* isShrink applies to object headers written when we shrink the file (ie resize) */ __u32 isShrink; } yaffs_ObjectHeader; #endif