pax_global_header00006660000000000000000000000064141223360430014510gustar00rootroot0000000000000052 comment=457e5a7b6c15f75a2110ba221086a61d0744a438 unrar-free-0.0.2/000077500000000000000000000000001412233604300135555ustar00rootroot00000000000000unrar-free-0.0.2/.gitignore000066400000000000000000000004121412233604300155420ustar00rootroot00000000000000# CVS default ignores begin tags TAGS .make.state .nse_depinfo *~ \#* .#* ,* _$* *$ *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb *.o *.obj *.so *.exe *.Z *.elc *.ln core # CVS default ignores end Makefile autom4te.cache config.h config.log config.status stamp-h1 unrar-free-0.0.2/AUTHORS000066400000000000000000000001731412233604300146260ustar00rootroot00000000000000Ben Asselstine Jeroen Dekkers Bastian Germann unrar-free-0.0.2/COPYING000066400000000000000000000431331412233604300146140ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, 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 Library 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 St, 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 Library General Public License instead of this License. unrar-free-0.0.2/ChangeLog000066400000000000000000000044671412233604300153420ustar00rootroot000000000000002021-09-21 Bastian Germann * unrar-free.1: Add man page by Niklas Vainio * src/unrar.c: Remove unar code, which drops RARv3 compatibility * src/opts.c: Add ineffective -y for compatibility * src/unrar.c: Add missing Info-ZIP license * src/unrar.c: Fix CVE-2017-14120 * src/unrarlib.c: Fix CVE-2017-11190, CVE-2017-14121, and CVE-2017-14122 2014-07-07 Ying-Chun Liu * src/unrar.c: Use unar to handle RARv3 format when it is installed 2007-11-27 Ying-Chun Liu * src: Remove RARv3 code from libclamav due to unclear license 2007-05-15 Ying-Chun Liu * src/unrar.c: mkpath if path does not exist when extracting files * misc/tarar.pike: Add new pike program 2007-04-24 Ying-Chun Liu * src/unrarlib.c: Handle unknown header info * src: Merge RARv3 from unrarlib SVN, which comes from libclamav 2006-06-09 Ying-Chun Liu * src/unrarlib.c: Fix warnings: dereferencing type-punned pointer 2006-04-30 Ying-Chun Liu * src/unrar.c: Make parent of directories if it doesn't exist * src/unrarlib.c: Fix the type of the return value of CalcCRC32() 2006-04-12 Ying-Chun Liu * src/opts.c: Avoid extracting with non-free unrar command "t" 2006-03-05 Ying-Chun Liu * src/unrarlib.c: Remove filename length 260 bytes restriction * src/unrarlib.c: Remove archive name length 255 bytes restriction * src/unrarlib.c: Remove password length 255 bytes restriction 2006-02-28 Ying-Chun Liu * src/opts.c: Command line compatibility with non-free unrar 2004-06-14 Ben Asselstine * src/unrarlib.h, src/Makefile.am: Moved the _DEBUG_LOG define into Makefile.am, and commented it out. * src/opts.c (parse_opts): fixed calling of getpass, so it only gets called once even if --password is on the command-line twice. * src/opts.c (parse_opts): now using realloc(n,NULL) to behave like malloc(n), so that memory allocation only happens in one place. * src/Makefile.in: regenerated. * src/unrar.c: added Jeroen's name to the visible copyright notice. 2004-06-05 Jeroen Dekkers * src/opts.c (options): Put string constants directly in the structure. unrar-free-0.0.2/Makefile.am000066400000000000000000000001021412233604300156020ustar00rootroot00000000000000SUBDIRS=src man_MANS=unrar-free.1 EXTRA_DIST=TODO misc/tarar.pike unrar-free-0.0.2/NEWS000066400000000000000000000000001412233604300142420ustar00rootroot00000000000000unrar-free-0.0.2/README000066400000000000000000000042761412233604300144460ustar00rootroot00000000000000UNRAR-FREE ========== Description ----------- unrar-free is a free software version of the non-free unrar utility. It incorporates the GPL'd UniquE RAR Library (https://www.unrarlib.org) by Christian Scheurer and Johannes Winkelmann. This program is a simple command-line front-end to that library, and can list and extract RAR archives. It does not rival the non-free unrar in terms of features, but special care has been taken to ensure it meets most user's needs. User Documentation ------------------ This is an abstract of the unrar-free(1) man page: Usage: unrar [OPTION...] ARCHIVE [FILE...] [DESTINATION] Extract files from rar archives. -x, --extract Extract files from archive (default) -t, --list List files in archive -f, --force Overwrite files when extracting --extract-newer Only extract newer files from the archive --extract-no-paths Don't create directories while extracting -p, --password Decrypt archive using a password -?, --help Give this help list --usage Give a short usage message -V, --version Print program version Development ----------- Please use the issue tracker and merge requests that are part of the git hosting platform to hand in bug reports and patches. All changes have to be compatible with the GPL-2.0-or-later project license. If you do not include any license information with your changes, it is assumed that they are licensed under GPL-2.0-or-later. History ------- unrar-free used to be developed on Gna! which was shut down. It is now maintained at https://gitlab.com/bgermann/unrar-free which holds most of the original CVS history that was exported via cvs-fast-export. There are changes that might be legally problematic and so the git tree is rebased on top of commit 745cb033fa ("add adddir function"), removing the problematic changes, and dropping some hunks from the usable changes. After the original upstream was shut down, most development on the project happened on the Debian package, which fixed several CVEs and added a man page with the changes licensed under GPL-2.0-or-later. These are imported into the tree. unrar-free-0.0.2/TODO000066400000000000000000000001141412233604300142410ustar00rootroot00000000000000rerun autoscan test --extract-newer test --extract-no-paths test --password unrar-free-0.0.2/configure.ac000066400000000000000000000012351412233604300160440ustar00rootroot00000000000000# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) AC_INIT([unrar],[0.0.2]) AM_INIT_AUTOMAKE AM_CONFIG_HEADER(config.h) # Checks for programs. AC_PROG_CC AC_PROG_INSTALL AC_PROG_LN_S AC_PROG_MAKE_SET # Checks for header files. AC_HEADER_STDC AC_CHECK_HEADERS([limits.h stdlib.h string.h unistd.h]) # Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_SIZE_T # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_REALLOC AC_CHECK_FUNCS([atexit realpath setenv strchr]) AC_CONFIG_FILES([Makefile src/Makefile]) AC_OUTPUT unrar-free-0.0.2/misc/000077500000000000000000000000001412233604300145105ustar00rootroot00000000000000unrar-free-0.0.2/misc/tarar.pike000077500000000000000000000140511412233604300164770ustar00rootroot00000000000000#!/usr/bin/pike /* Copyright (C) 2004 Jeroen Dekkers Copyright (C) 2004 Ben Asselstine Copyright (C) 2006 Ying-Chun Liu 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ /* test case generator 1 */ import Stdio; int crc32_file(Stdio.File file1) { int currentpos; int shiftRegister=0; string data; currentpos = file1->tell(); file1->seek(0); while (1) { data = file1->read(1024*8); if (data == 0 || strlen(data)==0) { break; } shiftRegister = Gz.crc32(data,shiftRegister); } file1->seek(currentpos); return shiftRegister; } string int2bin16 (int d) { string ret; ret=sprintf("%c%c", d%256, (d/256)%256); return ret; } string int2bin32 (int d) { string ret; ret=sprintf("%c%c%c%c", d%256, (d/256)%256, (d/256/256)%256, (d/256/256/256)%256); return ret; } int addfile(string filename1,Stdio.File rarfile) { Stdio.File datafile = Stdio.File(); Stdio.Stat datafile_stat; int datafile_crc32,tmp1; mapping(string:int) datafile_mtime; string datafile_header; if (datafile->open(filename1,"r")==0) { return 0; } datafile_stat = datafile->stat(); datafile_mtime = localtime(datafile_stat->mtime); datafile_crc32 = ((crc32_file(datafile)) & 0x0ffffffff); /* header: type, flags */ datafile_header = "\x74\0\x80"; /* header: header size */ tmp1 = 32+strlen(filename1); datafile_header = datafile_header + int2bin16(tmp1); /* header: comp. size, uncomp. size */ tmp1 = datafile_stat->size; datafile_header = datafile_header + int2bin32(tmp1); datafile_header = datafile_header + int2bin32(tmp1); /* header: OS */ datafile_header = datafile_header + "\0"; /* header: File CRC */ tmp1 = datafile_crc32; datafile_header = datafile_header + int2bin32(tmp1); /* header: time */ tmp1 = (datafile_mtime["year"]-80); if (tmp1 < 0) tmp1=0; tmp1 = tmp1 << 25; tmp1 = tmp1 + ((datafile_mtime["mon"]+1)<<21); tmp1 = tmp1 + ((datafile_mtime["mday"])<<16); tmp1 = tmp1 + ((datafile_mtime["hour"])<<11); tmp1 = tmp1 + ((datafile_mtime["min"])<<5); tmp1 = tmp1 + ((datafile_mtime["sec"])>>1); datafile_header = datafile_header + int2bin32(tmp1); /* header: unp. version, method */ datafile_header = datafile_header + "\x14\x30"; /* header: filename size */ tmp1 = strlen(filename1); datafile_header = datafile_header + int2bin16(tmp1); /* header: file attr. */ datafile_header = datafile_header + "\x20\0\0\0"; /* header: filename */ datafile_header = datafile_header + replace(filename1,"/","\\"); /* header: crc32 */ tmp1 = ((Gz.crc32(datafile_header)) & 0x0000ffff); datafile_header = int2bin16(tmp1) + datafile_header; rarfile->write(datafile_header); while (1) { string datatmp; datatmp = datafile->read(1024*8); if (datatmp == 0 || strlen(datatmp)==0) { break; } rarfile->write(datatmp); } datafile->close(); return 1; } int adddir_header(string filename1,Stdio.File rarfile) { int tmp1; string datafile_header=""; Stdio.Stat datafile_stat; mapping(string:int) datafile_mtime; /* header: type, flags */ datafile_header = "\x74\0\xe0"; if (has_suffix(filename1, "\\") || has_suffix(filename1,"/")) { filename1 = filename1[..strlen(filename1)-2]; } tmp1 = 32+strlen(filename1); datafile_header += int2bin16(tmp1); datafile_header += int2bin32(0); datafile_header += int2bin32(0); datafile_header += "\0"; datafile_header += int2bin32(0); datafile_stat = file_stat(filename1); datafile_mtime = localtime(datafile_stat->mtime); tmp1 = (datafile_mtime["year"]-80); if (tmp1 < 0) tmp1=0; tmp1 = tmp1 << 25; tmp1 = tmp1 + ((datafile_mtime["mon"]+1)<<21); tmp1 = tmp1 + ((datafile_mtime["mday"])<<16); tmp1 = tmp1 + ((datafile_mtime["hour"])<<11); tmp1 = tmp1 + ((datafile_mtime["min"])<<5); tmp1 = tmp1 + ((datafile_mtime["sec"])>>1); datafile_header += int2bin32(tmp1); datafile_header += "\x14\x30"; tmp1 = strlen(filename1); datafile_header += int2bin16(tmp1); datafile_header += "\x10\0\0\0"; datafile_header +=replace(filename1,"/","\\"); tmp1 = ((Gz.crc32(datafile_header)) & 0x0000ffff); datafile_header = int2bin16(tmp1) + datafile_header; rarfile->write(datafile_header); } mapping(string:int) adddir_dirs=([]); int adddir(string filename1,Stdio.File rarfile) { Filesystem.Traversion ft; string filename; ft = Filesystem.Traversion(filename1); foreach(ft; string dir; string file) { if (adddir_dirs[dir] != 1) { adddir_header(dir,rarfile); adddir_dirs += ([dir:1]); } filename = dir+file; if (is_file(filename)) { addfile(filename,rarfile); } else if (is_dir(filename)) { adddir_header(filename,rarfile); } } } int main(int argc,array(string) argv) { int i,tmp1; string filename1; Stdio.File rarfile = Stdio.File(); if ( argc < 2 ) { write ( "Usage: " + argv[0] + " ARCHIVE [FILE...]\n" ); return 1; } if (rarfile->open(argv[1],"wtc")==0) { write("Cannot open "+argv[1]+" file\n"); return 0; } rarfile->write("Rar!\x1a\x07\0"); /* Marker block */ rarfile->write("\xcf\x90\x73\0\0\x0d\0\0\0\0\0\0\0"); /* Archive header */ for (i=2 ; iclose(); return 0; } unrar-free-0.0.2/src/000077500000000000000000000000001412233604300143445ustar00rootroot00000000000000unrar-free-0.0.2/src/.gitignore000066400000000000000000000000251412233604300163310ustar00rootroot00000000000000.deps Makefile unrar unrar-free-0.0.2/src/Makefile.am000066400000000000000000000002361412233604300164010ustar00rootroot00000000000000bin_PROGRAMS=unrar unrar_SOURCES=unrar.c opts.c opts.h unrarlib.c unrarlib.h unrar_CFLAGS = -fno-strict-aliasing AM_CFLAGS= #AM_CFLAGS= -Wall -g -D_DEBUG_LOG unrar-free-0.0.2/src/opts.c000066400000000000000000000251621412233604300155030ustar00rootroot00000000000000/* Copyright (C) 2004 Jeroen Dekkers Copyright (C) 2004 Ben Asselstine 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include #include "opts.h" #define FULL_VERSION PACKAGE_NAME " " PACKAGE_VERSION const char *argp_program_version = FULL_VERSION; static char doc[] = "Extract files from rar archives."; static char args_doc[] = "ARCHIVE [FILE...] [DESTINATION]"; struct arguments_t arguments; static struct argp_option options[] = { {"extract", CMD_EXTRACT, 0, 0, "Extract files from archive (default)", 0}, {"list", CMD_LIST, 0, 0, "List files in archive", 1}, {"force", OPT_FORCE, 0, 0, "Overwrite files when extracting", 2}, {"extract-newer", OPT_EXTRACT_NEWER, 0, 0, "Only extract newer files from the archive", 3}, {"extract-no-paths", OPT_JUNK_PATHS, 0, 0, "Don't create directories while extracting", 3}, {"password", OPT_PASSWORD, 0, 0, "Decrypt archive using a password", 3}, {"verbose", OPT_VERBOSE, 0, OPTION_HIDDEN, "Verbosely list files extracted", 3}, {0} }; void free_arguments () { if (arguments.args) free (arguments.args); if (arguments.unrar.destination_dir) free (arguments.unrar.destination_dir); if (arguments.unrar.archive_filename) free (arguments.unrar.archive_filename); if (arguments.unrar.password) free (arguments.unrar.password); return; } static error_t parse_opt (int key, char *arg, struct argp_state *state) { /* Get the INPUT argument from `argp_parse', which we know is a pointer to our arguments structure. */ struct arguments_t *arguments = state->input; char *pass; switch (key) { case CMD_EXTRACT: arguments->unrar.mode = MODE_EXTRACT; break; case CMD_LIST: arguments->unrar.mode = MODE_LIST; break; case OPT_FORCE: arguments->unrar.force = 1; break; case OPT_JUNK_PATHS: arguments->unrar.junk_paths = 1; break; case OPT_EXTRACT_NEWER: arguments->unrar.extract_newer = 1; break; case OPT_PASSWORD: if (arguments->unrar.password == NULL) { if ((pass = getpass ("Password:"))) arguments->unrar.password = strdup (pass); } break; case OPT_VERBOSE: arguments->unrar.verbose = 1; break; case ARGP_KEY_INIT: free_arguments (); arguments->args = NULL; arguments->arraylen = 0; break; case ARGP_KEY_ARG: arguments->arraylen++; arguments->args = (char **) realloc (arguments->args, arguments->arraylen * sizeof (char *)); arguments->args[state->arg_num] = arg; break; case ARGP_KEY_END: if (arguments->arraylen > 0) { char *file; struct stat statbuf; file = realpath (arguments->args[0], NULL); if (lstat (file, &statbuf) == -1) { free (file); error (0, 0, "invalid archive '%s': %m", arguments->args[0]); argp_usage (state); } else { if (!(S_ISDIR (statbuf.st_mode))) arguments->unrar.archive_filename = file; else { free (file); error (0, 0, "invalid archive '%s': is a directory", arguments->args[0]); argp_usage (state); } } } if (arguments->arraylen > 1) { char *dir; struct stat statbuf; dir = realpath (arguments->args[arguments->arraylen - 1], NULL); if (lstat (dir, &statbuf) == -1) free (dir); else { if (S_ISDIR (statbuf.st_mode)) { arguments->unrar.destination_dir = dir; arguments->args[arguments->arraylen - 1] = NULL; arguments->arraylen--; } else free (dir); } } break; default: return ARGP_ERR_UNKNOWN; } return 0; } int set_default_arguments (struct unrar_arguments_t *unrar) { if (unrar->mode == MODE_UNKNOWN) unrar->mode = MODE_EXTRACT; if (unrar->destination_dir == NULL) unrar->destination_dir = realpath ("./", NULL); return 0; } struct argp argp = { options, parse_opt, args_doc, doc }; int parse_opts (int argc, char **argv, struct arguments_t *arguments) { int retval; setenv ("ARGP_HELP_FMT", "no-dup-args-note", 1); atexit (free_arguments); retval = argp_parse (&argp, argc, argv, 0, 0, arguments); if (retval < 0) argp_help (&argp, stdout, ARGP_HELP_EXIT_ERR | ARGP_HELP_SEE, PACKAGE_NAME); set_default_arguments (&arguments->unrar); if (arguments->arraylen == 0) { error (0, 0, "Archive not specified\n"); argp_help (&argp, stdout, ARGP_HELP_EXIT_ERR | ARGP_HELP_SEE, PACKAGE_NAME); return -1; } return 0; } /** * @brief Decide a valid unrar command. * To decide a string is an unrar command or not * @param a the string * @retval true it is an unrar command * @retval false it is not an unrar command */ int compat_iscmd(char *a) { if (strcmp(a,"e")==0 || strcmp(a,"l")==0 || strcmp(a,"lt")==0 || strcmp(a,"lb")==0 || strcmp(a,"p")==0 || strcmp(a,"t")==0 || strcmp(a,"v")==0 || strcmp(a,"vt")==0 || strcmp(a,"vb")==0 || strcmp(a,"x")==0 || strcmp(a,"y")==0 ) { return (1==1); } return (1==0); } /** * @brief To execute an unrar command. * Set arguments to execute an unrar command * @param a the command * @param the arguments structure */ void compat_execcmd(char *a, struct arguments_t *arguments) { if (strcmp(a,"e")==0) { arguments->unrar.mode = MODE_EXTRACT; arguments->unrar.junk_paths = 1; } else if (strcmp(a,"l")==0) { arguments->unrar.mode = MODE_LIST; } else if (strcmp(a,"lt")==0) { arguments->unrar.mode = MODE_LIST; } else if (strcmp(a,"lb")==0) { arguments->unrar.mode = MODE_LIST; } else if (strcmp(a,"p")==0) { } else if (strcmp(a,"t")==0) { arguments->unrar.mode = MODE_LIST; } else if (strcmp(a,"v")==0) { arguments->unrar.mode = MODE_LIST; arguments->unrar.verbose = 1; } else if (strcmp(a,"vt")==0) { arguments->unrar.mode = MODE_LIST; arguments->unrar.verbose = 1; } else if (strcmp(a,"vb")==0) { arguments->unrar.mode = MODE_LIST; arguments->unrar.verbose = 1; } else if (strcmp(a,"x")==0) { arguments->unrar.mode = MODE_EXTRACT; } else { return; } } /** * @brief Execute an unrar switch. * Set arguments to execute an unrar switch * @param a the string * @param arguments the arguments strcture * @retval 0 it is a switch (start with "-") and arguments is changed * @retval 1 it is not a switch and arguments is unchanged * @retval 2 it is a stop switch "--" and arguments is unchanged */ int compat_execswitch(char *a, struct arguments_t *arguments) { char *swtch,*opt,*pass; if (a[0]=='-') { swtch=&(a[1]); } else { /* not a switch */ return 1; } if (strcmp(swtch,"-")==0) { /* stop switch */ return 2; } else if (strcmp(swtch,"ep")==0) { arguments->unrar.junk_paths = 1; } else if (strcmp(swtch,"o+")==0) { arguments->unrar.force = 1; } else if (strcmp(swtch,"o-")==0) { arguments->unrar.force = 0; } else if (strncmp(swtch,"p",1)==0) { opt = &(swtch[1]); if (strcmp(opt,"-")==0) { /* don't ask for password */ } else if (opt[0] != '\0') { /* copy password from cmd line */ pass = opt; arguments->unrar.password = strdup(pass); } else { /* ask password */ if ((pass = getpass ("Password:")) != NULL) { arguments->unrar.password = strdup(pass); } } } else if (strcmp(swtch,"u")==0) { arguments->unrar.extract_newer = 1; } else { } return 0; } /** * @brief Add an string to arguments.args. * Add a string to an arguments structure * @param a the string * @param arguments the arguments strcture */ void compat_addargs(char *a, struct arguments_t *arguments) { int arg_num; arg_num = arguments->arraylen; arguments->arraylen++; arguments->args = (char **) realloc (arguments->args, arguments->arraylen * sizeof (char *)); arguments->args[arg_num] = a; } int compat_parse_opts(int argc, char **argv, struct arguments_t *arguments1) { int retval=0,i; /* iscmd? */ if (argc <=2 || !compat_iscmd(argv[1])) { return -1; } /* init */ free_arguments(); arguments1->args=NULL; arguments1->arraylen=0; /* cmd */ compat_execcmd(argv[1],arguments1); /* switch */ for (i=2 ; iarraylen > 0) { char *file; struct stat statbuf; file = realpath (arguments1->args[0], NULL); if (lstat (file, &statbuf) == -1) { free (file); /* error (0, 0, "invalid archive '%s': %m", arguments1->args[0]); */ retval=-1; } else { if (!(S_ISDIR (statbuf.st_mode))) { arguments1->unrar.archive_filename = file; } else { free (file); /*error (0, 0, "invalid archive '%s': is a directory", arguments1->args[0]);*/ retval=-1; } } } if (retval<0) { free_arguments(); memset(&arguments,0,sizeof(arguments)); return -1; } if (arguments1->arraylen > 1) { char *dir; struct stat statbuf; dir = realpath (arguments1->args[arguments1->arraylen - 1], NULL); if (lstat (dir, &statbuf) == -1) free(dir); else { if (S_ISDIR (statbuf.st_mode)) { arguments1->unrar.destination_dir = dir; arguments1->args[arguments1->arraylen - 1] = NULL; arguments1->arraylen--; } else free (dir); } } set_default_arguments (&arguments1->unrar); if (arguments1->arraylen == 0) { /*error (0, 0, "Archive not specified\n");*/ free_arguments(); memset(&arguments,0,sizeof(arguments)); return -1; } /* argument parsing success, register free_arguments to atexit */ atexit (free_arguments); return 0; } unrar-free-0.0.2/src/opts.h000066400000000000000000000031211412233604300154770ustar00rootroot00000000000000/* Copyright (C) 2004 Jeroen Dekkers Copyright (C) 2004 Ben Asselstine 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef FUNRAR_OPTS_H #define FUNRAR_OPTS_H 1 enum stow_options_enum_t { OPT_NONE, OPT_EXTRACT_NEWER, OPT_JUNK_PATHS, OPT_FORCE = 'f', OPT_PASSWORD = 'p', CMD_LIST = 't', OPT_VERBOSE = 'v', CMD_EXTRACT = 'x', }; enum unrar_mode_enum_t { MODE_UNKNOWN, MODE_EXTRACT, MODE_LIST, }; struct unrar_arguments_t { int mode; //stow_mode_enum_t int force; int junk_paths; int extract_newer; char *destination_dir; char *archive_filename; int verbose; char *password; }; struct arguments_t { char **args; int arraylen; //for argument processing struct unrar_arguments_t unrar; }; int parse_opts (int argc, char **argv, struct arguments_t *arguments); int compat_parse_opts (int argc, char **argv, struct arguments_t *arguments); #endif unrar-free-0.0.2/src/unrar.c000066400000000000000000000377131412233604300156520ustar00rootroot00000000000000/* Copyright (C) 2004 Jeroen Dekkers Copyright (C) 2004 Ben Asselstine 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 St, Fifth Floor, Boston, MA 02110-1301 USA ADDITIONAL LICENSE INFORMATION for dos_to_unix_time: Copyright (c) 1990-2004 Info-ZIP. All rights reserved. For the purposes of this copyright and license, "Info-ZIP" is defined as the following set of individuals: Mark Adler, John Bush, Karl Davis, Harald Denker, Jean-Michel Dubois, Jean-loup Gailly, Hunter Goatley, Ian Gorman, Chris Herborth, Dirk Haase, Greg Hartwig, Robert Heath, Jonathan Hudson, Paul Kienitz, David Kirschbaum, Johnny Lee, Onno van der Linden, Igor Mandrichenko, Steve P. Miller, Sergio Monesi, Keith Owens, George Petrov, Greg Roelofs, Kai Uwe Rommel, Steve Salisbury, Dave Smith, Christian Spieler, Antoine Verheijen, Paul von Behren, Rich Wales, Mike White This software is provided "as is," without warranty of any kind, express or implied. In no event shall Info-ZIP or its contributors be held liable for any direct, indirect, incidental, special or consequential damages arising out of the use of or inability to use this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. Redistributions of source code must retain the above copyright notice, definition, disclaimer, and this list of conditions. 2. Redistributions in binary form (compiled executables) must reproduce the above copyright notice, definition, disclaimer, and this list of conditions in documentation and/or other materials provided with the distribution. The sole exception to this condition is redistribution of a standard UnZipSFX binary (including SFXWiz) as part of a self-extracting archive; that is permitted without inclusion of this license, as long as the normal SFX banner has not been removed from the binary or disabled. 3. Altered versions--including, but not limited to, ports to new operating systems, existing ports with new graphical interfaces, and dynamic, shared, or static library versions--must be plainly marked as such and must not be misrepresented as being the original source. Such altered versions also must not be misrepresented as being Info-ZIP releases--including, but not limited to, labeling of the altered versions with the names "Info-ZIP" (or any variation thereof, including, but not limited to, different capitalizations), "Pocket UnZip," "WiZ" or "MacZip" without the explicit permission of Info-ZIP. Such altered versions are further prohibited from misrepresentative use of the Zip-Bugs or Info-ZIP e-mail addresses or of the Info-ZIP URL(s). 4. Info-ZIP retains the right to use the names "Info-ZIP," "Zip," "UnZip," "UnZipSFX," "WiZ," "Pocket UnZip," "Pocket Zip," and "MacZip" for its own source and binary releases. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include "opts.h" #include "unrarlib.h" /* * * dump_file is based on a simple GPL'd unrar client by Andreas F Borchert. * * */ extern struct arguments_t arguments; void show_copyright () { printf ("\n"); printf ("%s %s Copyright (C) 2004 Ben Asselstine, Jeroen Dekkers\n", PACKAGE, VERSION); printf ("\n"); return; } void show_list_header (struct unrar_arguments_t *unrar) { printf ("\n"); printf ("RAR archive %s\n", unrar->archive_filename); printf ("\n"); printf ("Pathname/Comment\n"); printf (" Size Packed Ratio Date Time Attr CRC Meth Ver\n"); printf ("-------------------------------------------------------------------------------\n"); return; } void show_list_footer (struct unrar_arguments_t *unrar) { printf ("-------------------------------------------------------------------------------\n"); return; } void show_list_stats (unsigned int num_files, unsigned int num_compressed_bytes, unsigned int num_bytes) { float ratio; ratio = ((float) num_compressed_bytes / (float) num_bytes) * 100; printf ("%5u %10u %8u %3.0f%%\n", num_files, num_bytes, num_compressed_bytes, ratio); return; } #define DOSTIME_2038_01_18 ((unsigned long)0x74320000L) #define U_TIME_T_MAX ((time_t)(unsigned long)0xffffffffL) #define S_TIME_T_MAX ((time_t)(unsigned long)0x7fffffffL) #define YRBASE 1900 time_t dos_to_unix_time (unsigned long dosdatetime) { time_t m_time; struct tm *tm; time_t now = time (NULL); tm = localtime (&now); tm->tm_isdst = -1; /* let mktime determine if DST is in effect */ /* dissect date */ tm->tm_year = ((int) (dosdatetime >> 25) & 0x7f) + (1980 - YRBASE); tm->tm_mon = ((int) (dosdatetime >> 21) & 0x0f) - 1; tm->tm_mday = ((int) (dosdatetime >> 16) & 0x1f); /* dissect time */ tm->tm_hour = (int) ((unsigned) dosdatetime >> 11) & 0x1f; tm->tm_min = (int) ((unsigned) dosdatetime >> 5) & 0x3f; tm->tm_sec = (int) ((unsigned) dosdatetime << 1) & 0x3e; m_time = mktime (tm); if ((dosdatetime >= DOSTIME_2038_01_18) && (m_time < (time_t) 0x70000000L)) m_time = U_TIME_T_MAX; /* saturate in case of (unsigned) overflow */ if (m_time < (time_t) 0L) /* a converted DOS time cannot be negative */ m_time = S_TIME_T_MAX; /* -> saturate at max signed time_t value */ return m_time; } void replace_backslash_with_slash (char *s1) { char *ptr; if (!s1) return; while ((ptr = strchr (s1, '\\'))) { ptr[0] = '/'; s1 = &ptr[1]; } return; } void unrar_list_item (struct unrar_arguments_t *unrar, ArchiveList_struct * listptr) { char datetime[20]; char *attr; float ratio; printf (" %s\n", listptr->item.Name); if (listptr->item.UnpSize == 0) ratio = 0; else ratio = ((float) listptr->item.PackSize / (float) listptr->item.UnpSize) * 100; if (ratio > 100.0) ratio = 100.0; if (listptr->item.FileTime) { struct tm filetime; time_t unixtime; unixtime = dos_to_unix_time ((unsigned long) listptr->item.FileTime); localtime_r ((const time_t *) &unixtime, &filetime); strftime (datetime, sizeof (datetime), "%d-%m-%y %H:%M", &filetime); } else snprintf (datetime, sizeof (datetime), "00-00-00 00:00"); if (listptr->item.FileAttr & 0x10) attr = ".D...."; else attr = ".....A"; printf (" %10u %8u %3.0f%% %s %s %08X m%c? %3.1f\n", (unsigned int) listptr->item.UnpSize, (unsigned int) listptr->item.PackSize, ratio, datetime, attr, (unsigned int) listptr->item.FileCRC, listptr->item.Method, (float) (listptr->item.UnpVer / 10.0)); return; } int unrar_list (struct unrar_arguments_t *unrar, int num_files, char **files) { ArchiveList_struct list; ArchiveList_struct *listptr; int i, j, n; unsigned int count_files = 0; unsigned int count_bytes = 0; unsigned int count_compressed_bytes = 0; list.next = NULL; n = urarlib_list (unrar->archive_filename, &list.next); if (n < 0) return n; if (unrar->verbose) printf ("showing %d files...\n", n); if (unrar->verbose) printf ("given a list of %d files.\n", num_files); listptr = list.next; show_list_header (unrar); for (i = 0; i < n; i++, listptr = listptr->next) { replace_backslash_with_slash (listptr->item.Name); if (num_files) { int found = 0; for (j = 0; j < num_files; j++) { if (unrar->verbose) printf ("comparing '%s' vs '%s'\n", files[j], listptr->item.Name); if (strcmp (files[j], listptr->item.Name) == 0) { found = 1; break; } } if (!found) continue; } count_files++; count_compressed_bytes += listptr->item.PackSize; count_bytes += listptr->item.UnpSize; unrar_list_item (unrar, listptr); if (listptr == NULL) //sanity check. break; } urarlib_freelist (list.next); show_list_footer (unrar); show_list_stats (count_files, count_compressed_bytes, count_bytes); return 0; } int unrar_mkpath (char *path) { char *path_tmp; int i,ret=0; if (path == NULL || path[0] == '\0') return (-1); path_tmp = strdup(path); if (path_tmp == NULL) return (-1); for (i=0; path_tmp[i] != '\0'; i++) { if (path_tmp[i]=='/') { path_tmp[i] = '\0'; if (path_tmp[0] != '\0') { ret = mkdir(path_tmp,0777); } path_tmp[i] = '/'; } } free(path_tmp); return ret; } int dump_file (struct unrar_arguments_t *unrar, char *filename, void *data, unsigned long data_size) { int fd; int written; ssize_t nbytes = 0; int fcntl_flags = O_WRONLY | O_CREAT; if (unrar->force) fcntl_flags |= O_TRUNC; else fcntl_flags |= O_EXCL; fd = open (filename, fcntl_flags, 0666); if (fd < 0 && errno == ENOENT) { unrar_mkpath (filename); fd = open (filename, fcntl_flags, 0666); } if (fd < 0) return -1; while (nbytes < data_size) { written = write (fd, data + nbytes, data_size - nbytes); if (written < 0) return -1; nbytes += written; } if (close (fd) < 0) return -1; return 0; } void show_status_line (char *action, char *file, char *status) { printf ("%-11s %-57s %-10s\n", action, file, status); return; } int unrar_extract_directory (struct unrar_arguments_t *unrar, char *dir) { char *destination = NULL; int ret=0; if (unrar->junk_paths) return 0; if (asprintf (&destination, "%s/%s/", unrar->destination_dir, dir) == -1) { error (0, 0, "asprintf failed: %m\n"); return -1; } if (mkdir (destination, 0777) < 0) { switch (errno) { case EEXIST: if (unrar->force) chmod (destination, 0777); break; case ENOENT: ret = unrar_mkpath(destination); if (ret==(-1)) { error(0, 0, "mkpath failed '%s': %m\n", destination); } break; default: error (0, 0, "mkdir failed '%s': %m\n", destination); ret=(-1); break; } } free (destination); return ret; } int unrar_extract_file (struct unrar_arguments_t *unrar, char *filename, char *archive_member, time_t FileTime) { int retval; char *destination = NULL; void *data; unsigned long data_size; if (!urarlib_get (&data, &data_size, archive_member, unrar->archive_filename, unrar->password)) return -1; else { char *file; if (unrar->junk_paths) { file = strrchr (filename, '/'); if (!file) file = filename; } else file = filename; if (asprintf (&destination, "%s/%s", unrar->destination_dir, file) == -1) { error (0, 0, "asprintf failed: %m\n"); return 0; } if (!strncmp ("../", file, strlen("../")) || strstr (file, "/../")) { error (0, 0, "archive contains unsafe filename: '%s'\n", file); return -1; } //where do i put it? in destination. if (unrar->extract_newer) { struct stat statbuf; time_t unixtime; int non_existent_files_are_not_newer = 1; retval = lstat (destination, &statbuf); if (retval < 0) { if (non_existent_files_are_not_newer) { free (destination); return 1; } } else { unixtime = dos_to_unix_time ((unsigned long) FileTime); if (unixtime <= statbuf.st_mtime); { free (destination); return 1; } } } //okay put it in destination. if (dump_file (unrar, destination, data, data_size) < 0) { free (data); free (destination); return -1; } free (data); free (destination); } return 0; } int unrar_extract (struct unrar_arguments_t *unrar, int num_files, char **files) { ArchiveList_struct list; ArchiveList_struct *listptr; int i, j, n; int retval; char *action; char *status; char *orig_name; int num_failed = 0; printf ("\n"); printf ("Extracting from %s\n", unrar->archive_filename); printf ("\n"); list.next = NULL; n = urarlib_list (unrar->archive_filename, &list.next); if (n < 0) return n; if (unrar->verbose) { printf ("showing %d files...\n", n); printf ("given a list of %d files.\n", num_files); } listptr = list.next; for (i = 0; i < n; i++, listptr = listptr->next) { orig_name = strdup (listptr->item.Name); replace_backslash_with_slash (listptr->item.Name); if (num_files) { int found = 0; for (j = 0; j < num_files; j++) { if (unrar->verbose) printf ("comparing '%s' vs '%s'\n", files[j], listptr->item.Name); if (strcmp (files[j], listptr->item.Name) == 0) { found = 1; break; } } if (!found) { free (orig_name); if (listptr->item.FileAttr & 0x10) continue; action = "Skipping"; status = ""; show_status_line (action, listptr->item.Name, status); continue; } } status = "OK"; if (listptr->item.FileAttr & 0x10) //is directory. { action = "Creating"; if ((retval = unrar_extract_directory (unrar, listptr->item.Name)) < 0) { status = "Failed"; } else if (retval == 0) { free (orig_name); continue; } } else //is file. { action = "Extracting"; if ((retval = unrar_extract_file (unrar, listptr->item.Name, orig_name, listptr->item.FileTime)) < 0) { status = "Failed"; } else if (retval == 1) { action = "Skipping"; status = ""; show_status_line (action, listptr->item.Name, status); free (orig_name); continue; } else if (retval == 0) { status = "OK"; show_status_line (action, listptr->item.Name, status); free (orig_name); continue; } } free (orig_name); show_status_line (action, listptr->item.Name, status); if (strcmp (status, "Failed") == 0) num_failed++; if (listptr == NULL) //sanity check. break; } urarlib_freelist (list.next); if (num_failed) { printf ("%d Failed\n", num_failed); return -1; } else printf ("All OK\n"); return 0; } int main (int argc, char **argv) { int retval = 0; char **files = NULL; int num_files = 0; if (compat_parse_opts (argc, argv, &arguments) == 0) { /* compatible mode success */ } else if (parse_opts (argc, argv, &arguments) < 0) exit (1); if (arguments.unrar.verbose) { printf ("archive name is '%s'\n", arguments.unrar.archive_filename); printf ("destination directory is '%s'\n", arguments.unrar.destination_dir); printf ("mode = %d\n", arguments.unrar.mode); printf ("force = %d\n", arguments.unrar.force); printf ("extract_newer = %d\n", arguments.unrar.extract_newer); printf ("junk_paths = %d\n", arguments.unrar.junk_paths); } if (arguments.arraylen > 1) { files = &arguments.args[1]; num_files = arguments.arraylen - 1; } show_copyright (); if (arguments.unrar.mode == MODE_LIST) retval = unrar_list (&arguments.unrar, num_files, files); else if (arguments.unrar.mode == MODE_EXTRACT) retval = unrar_extract (&arguments.unrar, num_files, files); if (retval < 0) exit (1); exit (0); } unrar-free-0.0.2/src/unrarlib.c000066400000000000000000001530531412233604300163350ustar00rootroot00000000000000/* Copyright (C) 2004 Jeroen Dekkers Copyright (C) 2000-2002 Christian Scheurer (www.ChristianScheurer.ch) Copyright (C) 2000-2002 Johannes Winkelmann (jw@tks6.net) RAR decompression code: Copyright (c) 1993-2002 Eugene Roshal 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "unrarlib.h" #include #include #include #include #include #include #define FM_LABEL 0x0000 #define FM_DIREC 0x4000 #define PATHDIVIDER "/" #define CPATHDIVIDER '/' #define MASKALL "*.*" /* emulation of the windows API and data types */ /* 20-08-2000 Johannes Winkelmann, jw@tks6.net */ typedef long DWORD; #ifdef _DEBUG_LOG /* define macros for debugging */ #define debug_log(a) puts (a); #else /* !_DEBUG_LOG */ /* no debug this time */ #define debug_log(a) #endif /* !_DEBUG_LOG */ #define MAXWINSIZE 0x100000 #define MAXWINMASK (MAXWINSIZE-1) #define UNP_MEMORY MAXWINSIZE #define Min(x,y) (((x)<(y)) ? (x):(y)) #define Max(x,y) (((x)>(y)) ? (x):(y)) #define NM 260 #define SIZEOF_MARKHEAD 7 #define SIZEOF_OLDMHD 7 #define SIZEOF_NEWMHD 13 #define SIZEOF_OLDLHD 21 #define SIZEOF_NEWLHD 32 #define SIZEOF_SHORTBLOCKHEAD 7 #define SIZEOF_LONGBLOCKHEAD 11 #define SIZEOF_COMMHEAD 13 #define SIZEOF_PROTECTHEAD 26 #define PACK_VER 20 /* version of decompression code */ #define UNP_VER 20 #define PROTECT_VER 20 enum { M_DENYREAD, M_DENYWRITE, M_DENYNONE, M_DENYALL }; enum { FILE_EMPTY, FILE_ADD, FILE_UPDATE, FILE_COPYOLD, FILE_COPYBLOCK }; enum { SUCCESS, WARNING, FATAL_ERROR, CRC_ERROR, LOCK_ERROR, WRITE_ERROR, OPEN_ERROR, USER_ERROR, MEMORY_ERROR, USER_BREAK = 255, IMM_ABORT = 0x8000 }; enum { EN_LOCK = 1, EN_VOL = 2 }; enum { SD_MEMORY = 1, SD_FILES = 2 }; enum { NAMES_DONTCHANGE }; enum { LOG_ARC = 1, LOG_FILE = 2 }; enum { OLD_DECODE = 0, OLD_ENCODE = 1, NEW_CRYPT = 2 }; enum { OLD_UNPACK, NEW_UNPACK }; #define MHD_COMMENT 2 #define MHD_LOCK 4 #define MHD_PACK_COMMENT 16 #define MHD_AV 32 #define MHD_PROTECT 64 #define LHD_SPLIT_BEFORE 1 #define LHD_SPLIT_AFTER 2 #define LHD_PASSWORD 4 #define LHD_COMMENT 8 #define LHD_SOLID 16 #define LHD_WINDOWMASK 0x00e0 #define LHD_WINDOW64 0 #define LHD_WINDOW128 32 #define LHD_WINDOW256 64 #define LHD_WINDOW512 96 #define LHD_WINDOW1024 128 #define LHD_DIRECTORY 0x00e0 #define LONG_BLOCK 0x8000 #define READSUBBLOCK 0x8000 enum { ALL_HEAD = 0, MARK_HEAD = 0x72, MAIN_HEAD = 0x73, FILE_HEAD = 0x74, COMM_HEAD = 0x75, AV_HEAD = 0x76, SUB_HEAD = 0x77, PROTECT_HEAD = 0x78 }; enum { EA_HEAD = 0x100 }; enum { MS_DOS = 0, OS2 = 1, WIN_32 = 2, UNIX = 3 }; struct mark_header { uint16_t head_crc; uint8_t head_type; uint16_t head_flags; uint16_t head_size; } __attribute__ ((packed)); struct archive_header { uint16_t head_crc; uint8_t head_type; uint16_t head_flags; uint16_t head_size; uint16_t reserved1; uint32_t reserved2; } __attribute__ ((packed)); struct NewFileHeader { UWORD HeadCRC; UBYTE HeadType; UWORD Flags; UWORD HeadSize; UDWORD PackSize; UDWORD UnpSize; UBYTE HostOS; UDWORD FileCRC; UDWORD FileTime; UBYTE UnpVer; UBYTE Method; UWORD NameSize; UDWORD FileAttr; UDWORD HighPackSize; UDWORD HighUnpSize; }; struct BlockHeader { UWORD HeadCRC; UBYTE HeadType; UWORD Flags; UWORD HeadSize; UDWORD DataSize; }; struct Decode { unsigned int MaxNum; unsigned int *DecodeLen; unsigned int *DecodePos; unsigned int *DecodeNum; }; struct mark_header markheader; struct archive_header archiveheader; struct NewFileHeader NewLhd; struct BlockHeader BlockHead; UBYTE *TempMemory; /* temporary unpack-buffer */ char *CommMemory; UBYTE *UnpMemory; char* ArgName=NULL; /* current file in rar archive */ char* ArcFileName; /* file to decompress */ char* ArcName=NULL; /* RAR archive name */ FILE *inputfile; /* input RAR file handler */ char *Password=NULL; /* password to decrypt files */ unsigned char *temp_output_buffer; /* extract files to this pointer */ unsigned long *temp_output_buffer_offset; /* size of temp. extract buffer */ bool FileFound; /* true=use current extracted data, false=throw data away, wrong file */ long CurBlockPos, NextBlockPos; unsigned long CurUnpRead, CurUnpWrite; long UnpPackedSize; long DestUnpSize; UDWORD HeaderCRC; int Encryption; unsigned int UnpWrSize; unsigned char *UnpWrAddr; unsigned int UnpPtr, WrPtr; unsigned char PN1, PN2, PN3; unsigned short OldKey[4]; /* function header definitions */ int ReadHeader (int BlockType); bool ExtrFile (void); bool ListFile (void); bool UnstoreFile (void); int IsArchive (void); int ReadBlock (int BlockType); unsigned int UnpRead (unsigned char *Addr, unsigned int Count); void UnpInitData (void); void Unpack (unsigned char *UnpAddr); UBYTE DecodeAudio (int Delta); static void DecodeNumber (struct Decode *Dec); void UpdKeys (UBYTE * Buf); void SetCryptKeys (char *Password); void SetOldKeys (char *Password); void DecryptBlock (unsigned char *Buf); void InitCRC (void); uint32_t CalcCRC32 (uint32_t StartCRC, UBYTE * Addr, UDWORD Size); void UnpReadBuf (int FirstBuf); void ReadTables (void); static void ReadLastTables (void); static void MakeDecodeTables (unsigned char *LenTab, struct Decode *Dec, int Size); int stricomp (char *Str1, char *Str2); /* ------------------------------------------------------------------------ */ /* -- global functions ---------------------------------------------------- */ int urarlib_get (void **output, unsigned long *size, const char *filename, const char *rarfile, const char *libpassword) /* Get a file from a RAR file to the "output" buffer. The UniquE RAR FileLib * does everything from allocating memory, decrypting and unpacking the file * from the archive. true is returned if the file could be successfully * extracted, else a false indicates a failure. */ { bool retcode; #ifdef _DEBUG_LOG char DebugMsg[500]; /* used to compose debug msg */ #endif InitCRC (); /* init some vars */ /* set file(s) to extract */ if (ArgName) free(ArgName); ArgName = strdup(filename); /* set RAR file name */ if (ArcName) free(ArcName); ArcName = strdup(rarfile); if (Password) free(Password); if (libpassword != NULL) /* init password */ Password = strdup(libpassword); else Password = strdup(""); temp_output_buffer = NULL; temp_output_buffer_offset = size; /* set size of the temp buffer */ retcode = ExtrFile (); /* unpack file now! */ /* clear password */ if (Password) free(Password); Password = strdup(""); if (inputfile != NULL) { fclose (inputfile); inputfile = NULL; } if (UnpMemory) free (UnpMemory); /* free memory */ if (TempMemory) free (TempMemory); if (CommMemory) free (CommMemory); UnpMemory = NULL; TempMemory = NULL; CommMemory = NULL; if (retcode == false) { if (temp_output_buffer) free (temp_output_buffer); /* free memory and return NULL */ temp_output_buffer = NULL; *(DWORD *) output = 0; /* pointer on errors */ *size = 0; #ifdef _DEBUG_LOG sprintf (DebugMsg, "Error - couldn't extract archive and allocated " "%u Bytes of unused memory!", (unsigned int) *size); } else { sprintf (DebugMsg, "Extracted %u Bytes.", (unsigned int) *size); } debug_log (DebugMsg); #else } #endif *(DWORD *) output = (DWORD) temp_output_buffer; /* return pointer for unpacked */ /* data */ return retcode; } int urarlib_list (const char *rarfile, ArchiveList_struct **list) { ArchiveList_struct *tmp_List = NULL; int filecount = 0; /* number of files in archive */ InitCRC (); /* init some vars */ /* open and identify archive */ inputfile = fopen (rarfile, "r"); if (inputfile) { if (!IsArchive ()) { debug_log ("Not a RAR file"); fclose (inputfile); inputfile = NULL; return 0; /* error => exit! */ } } else { debug_log ("Error opening file."); return 0; } UnpMemory = malloc (UNP_MEMORY); if (!UnpMemory) { debug_log ("Can't allocate memory for decompression!"); return 0; } fseek (inputfile, archiveheader.head_size - SIZEOF_NEWMHD, SEEK_CUR); *list = NULL; /* init file list */ /* do while file is not extracted and there's no error */ while (1) { if (ReadBlock (FILE_HEAD | READSUBBLOCK) <= 0) /* read name of the next */ { /* file within the RAR archive */ /* debug_log ("Couldn't read next filename from archive (I/O error).");*/ break; /* error, file not found in archive or I/O error */ } if (BlockHead.HeadType == SUB_HEAD) { debug_log ("Sorry, sub-headers not supported."); break; /* error => exit */ } /* first entry */ if (*list == NULL) { tmp_List = malloc (sizeof (ArchiveList_struct)); tmp_List->next = NULL; *list = tmp_List; } else /* add entry */ { tmp_List->next = malloc (sizeof (ArchiveList_struct)); tmp_List = tmp_List->next; tmp_List->next = NULL; } tmp_List->item.Name = malloc (NewLhd.NameSize + 1); strcpy (tmp_List->item.Name, ArcFileName); tmp_List->item.NameSize = NewLhd.NameSize; tmp_List->item.PackSize = NewLhd.PackSize; tmp_List->item.UnpSize = NewLhd.UnpSize; tmp_List->item.HostOS = NewLhd.HostOS; tmp_List->item.FileCRC = NewLhd.FileCRC; tmp_List->item.FileTime = NewLhd.FileTime; tmp_List->item.UnpVer = NewLhd.UnpVer; tmp_List->item.Method = NewLhd.Method; tmp_List->item.FileAttr = NewLhd.FileAttr; filecount++; /* count files */ if (inputfile != NULL) fseek (inputfile, NextBlockPos, SEEK_SET); } /* free memory, clear password and close archive */ /* clear password */ if (Password) free(Password); Password = strdup(""); if (inputfile != NULL) { fclose (inputfile); inputfile = NULL; } if (UnpMemory) free (UnpMemory); /* free memory */ if (TempMemory) free (TempMemory); if (CommMemory) free (CommMemory); UnpMemory = NULL; TempMemory = NULL; CommMemory = NULL; return filecount; } /* urarlib_freelist: * (after the suggestion and code of Duy Nguyen, Sean O'Blarney * and Johannes Winkelmann who independently wrote a patch) * free the memory of a ArchiveList_struct created by urarlib_list. * * input: *list pointer to an ArchiveList_struct * output: - */ void urarlib_freelist (ArchiveList_struct * list) { ArchiveList_struct *tmp = list; while (list) { tmp = list->next; free (list->item.Name); free (list); list = tmp; } } /* B L O C K I / O */ #define GetHeaderByte(N) Header[N] #define GetHeaderWord(N) (Header[N]+((UWORD)Header[N+1]<<8)) #define GetHeaderDword(N) (Header[N]+((UWORD)Header[N+1]<<8)+\ ((UDWORD)Header[N+2]<<16)+\ ((UDWORD)Header[N+3]<<24)) int ReadBlock (int BlockType) { struct NewFileHeader SaveFileHead; int Size, ReadSubBlock = 0; static int LastBlock; memcpy (&SaveFileHead, &NewLhd, sizeof (SaveFileHead)); if (BlockType & READSUBBLOCK) ReadSubBlock = 1; BlockType &= 0xff; while (1) { CurBlockPos = ftell (inputfile); Size = ReadHeader (FILE_HEAD); if (Size != 0) { if (NewLhd.HeadSize < SIZEOF_SHORTBLOCKHEAD) return 0; NextBlockPos = CurBlockPos + NewLhd.HeadSize; if (NewLhd.Flags & LONG_BLOCK) NextBlockPos += NewLhd.PackSize; if (NextBlockPos <= CurBlockPos) return 0; } if (Size > 0 && BlockType != SUB_HEAD) LastBlock = BlockType; if (Size == 0 || BlockType == ALL_HEAD || NewLhd.HeadType == BlockType || (NewLhd.HeadType == SUB_HEAD && ReadSubBlock && LastBlock == BlockType)) break; fseek (inputfile, NextBlockPos, SEEK_SET); } BlockHead.HeadCRC = NewLhd.HeadCRC; BlockHead.HeadType = NewLhd.HeadType; BlockHead.Flags = NewLhd.Flags; BlockHead.HeadSize = NewLhd.HeadSize; BlockHead.DataSize = NewLhd.PackSize; if (BlockType != NewLhd.HeadType) BlockType = ALL_HEAD; if ((FILE_HEAD == BlockType) && (Size > 0)) { ArcFileName=realloc(ArcFileName,NewLhd.NameSize+1); fread (ArcFileName, 1, NewLhd.NameSize, inputfile); ArcFileName[NewLhd.NameSize] = 0; #ifdef _DEBUG_LOG if (NewLhd.HeadCRC != (UWORD) ~ CalcCRC32 (HeaderCRC, (UBYTE *) & ArcFileName[0], NewLhd.NameSize)) { debug_log ("file header broken"); } #endif Size += NewLhd.NameSize; if ( (NewLhd.Flags & 0x0400) ) { char tmpbuf1[8]; memset(tmpbuf1,0,sizeof(tmpbuf1)); if (Size>(15-4*i)) & 0x0001) == 0) { continue; } if (i!=0) { if (Size>(12-4*i)) & 0x0003) ; j++) { if (Size exit! */ } } else { debug_log ("Error opening file."); return false; } if ((UnpMemory = malloc (UNP_MEMORY)) == NULL) { debug_log ("Can't allocate memory for decompression!"); return false; } fseek (inputfile, archiveheader.head_size - SIZEOF_NEWMHD, SEEK_CUR); /* do while file is not extracted and there's no error */ do { if (ReadBlock (FILE_HEAD | READSUBBLOCK) <= 0) /* read name of the next */ { /* file within the RAR archive */ /* * * 21.11.2000 UnQ There's a problem with some linux distros when a file * can not be found in an archive. * * debug_log("Couldn't read next filename from archive (I/O error)."); * */ ReturnCode = false; break; /* error, file not found in */ } /* archive or I/O error */ if (BlockHead.HeadType == SUB_HEAD) { debug_log ("Sorry, sub-headers not supported."); ReturnCode = false; break; /* error => exit */ } FileFound = (stricomp (ArgName, ArcFileName) == 0); if (FileFound) /* file found! */ { /* Allocate memory for the file. The default offset within the buffer is 0. */ temp_output_buffer = malloc (NewLhd.UnpSize); *temp_output_buffer_offset = 0; if (temp_output_buffer == NULL) { debug_log ("can't allocate memory for the file decompression"); ReturnCode = false; break; /* error, can't extract file! */ } } /* in case of a solid archive, we need to decompress any single file till * we have found the one we are looking for. In case of normal archives * (recommended!!), we skip the files until we are sure that it is the * one we want. */ if ((archiveheader.head_flags & 0x08) || FileFound) { if (NewLhd.UnpVer < 13 || NewLhd.UnpVer > UNP_VER) { char DebugMsg[64]; snprintf(DebugMsg, sizeof DebugMsg, "unknown compression method: %d", NewLhd.UnpVer); debug_log(DebugMsg); ReturnCode = false; break; /* error, can't extract file! */ } CurUnpRead = CurUnpWrite = 0; if ((*Password != 0) && (NewLhd.Flags & LHD_PASSWORD)) Encryption = NewLhd.UnpVer; else Encryption = 0; if (Encryption) SetCryptKeys (Password); UnpPackedSize = NewLhd.PackSize; DestUnpSize = NewLhd.UnpSize; if (NewLhd.Method == 0x30) { UnstoreFile (); } else { Unpack (UnpMemory); } #ifdef _DO_CRC32_CHECK /* calculate CRC32 */ if ((UBYTE *) temp_output_buffer != NULL) { if (NewLhd.FileCRC != ~CalcCRC32 (0xFFFFFFFFL, (UBYTE *) temp_output_buffer, NewLhd.UnpSize)) { debug_log ("CRC32 error - file couldn't be decompressed correctly!"); ReturnCode = false; break; /* error, can't extract file! */ } } #endif } if (inputfile != NULL) fseek (inputfile, NextBlockPos, SEEK_SET); } while (stricomp (ArgName, ArcFileName) != 0); /* exit if file is extracted */ /* free memory, clear password and close archive */ free (UnpMemory); UnpMemory = NULL; if (inputfile != NULL) { fclose (inputfile); inputfile = NULL; } return ReturnCode; /* file extracted successful! */ } /* G L O B A L F U N C T I O N S */ int stricomp (char *Str1, char *Str2) /* compare strings without regard of '\' and '/' */ { char S1[512], S2[512]; char *chptr; strncpy (S1, Str1, sizeof (S1)); strncpy (S2, Str2, sizeof (S2)); while ((chptr = strchr (S1, '\\')) != NULL) /* ignore backslash */ { *chptr = '_'; } while ((chptr = strchr (S2, '\\')) != NULL) /* ignore backslash */ { *chptr = '_'; } while ((chptr = strchr (S1, '/')) != NULL) /* ignore slash */ { *chptr = '_'; } while ((chptr = strchr (S2, '/')) != NULL) /* ignore slash */ { *chptr = '_'; } return strcasecmp (S1, S2); } /* U N P A C K C O D E */ /* ***************************** * ** unpack stored RAR files ** * *****************************/ bool UnstoreFile (void) { if ((long) (*temp_output_buffer_offset = UnpRead (temp_output_buffer, NewLhd.UnpSize)) == -1) { debug_log ("Read error of stored file!"); return false; } return true; } /* **************************************** * ** RAR decompression code starts here ** * ****************************************/ #define NC 298 /* alphabet = {0,1,2, .,NC - 1} */ #define DC 48 #define RC 28 #define BC 19 #define MC 257 enum { CODE_HUFFMAN = 0, CODE_LZ = 1, CODE_LZ2 = 2, CODE_REPEATLZ = 3, CODE_CACHELZ = 4, CODE_STARTFILE = 5, CODE_ENDFILE = 6, CODE_ENDMM = 7, CODE_STARTMM = 8, CODE_MMDELTA = 9 }; struct AudioVariables { int K1, K2, K3, K4, K5; int D1, D2, D3, D4; int LastDelta; unsigned int Dif[11]; unsigned int ByteCount; int LastChar; }; struct AudioVariables AudV[4]; #define GetBits() \ BitField = ( ( ( (UDWORD)InBuf[InAddr] << 16 ) | \ ( (UWORD) InBuf[InAddr+1] << 8 ) | \ ( InBuf[InAddr+2] ) ) \ >> (8-InBit) ) & 0xffff; #define AddBits(Bits) \ InAddr += ( InBit + (Bits) ) >> 3; \ InBit = ( InBit + (Bits) ) & 7; static unsigned char *UnpBuf; static unsigned int BitField; static unsigned int Number; unsigned char InBuf[8192]; /* input read buffer */ unsigned char UnpOldTable[MC * 4]; unsigned int InAddr, InBit, ReadTop; unsigned int LastDist, LastLength; static unsigned int Length, Distance; unsigned int OldDist[4], OldDistPtr; struct LitDecode { unsigned int MaxNum; unsigned int DecodeLen[16]; unsigned int DecodePos[16]; unsigned int DecodeNum[NC]; } LD; struct DistDecode { unsigned int MaxNum; unsigned int DecodeLen[16]; unsigned int DecodePos[16]; unsigned int DecodeNum[DC]; } DD; struct RepDecode { unsigned int MaxNum; unsigned int DecodeLen[16]; unsigned int DecodePos[16]; unsigned int DecodeNum[RC]; } RD; struct MultDecode { unsigned int MaxNum; unsigned int DecodeLen[16]; unsigned int DecodePos[16]; unsigned int DecodeNum[MC]; } MD[4]; struct BitDecode { unsigned int MaxNum; unsigned int DecodeLen[16]; unsigned int DecodePos[16]; unsigned int DecodeNum[BC]; } BD; static struct MultDecode *MDPtr[4] = { &MD[0], &MD[1], &MD[2], &MD[3] }; int UnpAudioBlock, UnpChannels, CurChannel, ChannelDelta; struct Decode Decode_tmp; struct Decode * LitDecode2Decode (struct LitDecode *ld) { Decode_tmp.MaxNum = ld->MaxNum; Decode_tmp.DecodeLen = ld->DecodeLen; Decode_tmp.DecodePos = ld->DecodePos; Decode_tmp.DecodeNum = ld->DecodeNum; return &Decode_tmp; } struct Decode * DistDecode2Decode (struct DistDecode *ld) { Decode_tmp.MaxNum = ld->MaxNum; Decode_tmp.DecodeLen = ld->DecodeLen; Decode_tmp.DecodePos = ld->DecodePos; Decode_tmp.DecodeNum = ld->DecodeNum; return &Decode_tmp; } struct Decode * RepDecode2Decode (struct RepDecode *ld) { Decode_tmp.MaxNum = ld->MaxNum; Decode_tmp.DecodeLen = ld->DecodeLen; Decode_tmp.DecodePos = ld->DecodePos; Decode_tmp.DecodeNum = ld->DecodeNum; return &Decode_tmp; } struct Decode * MultDecode2Decode (struct MultDecode *ld) { Decode_tmp.MaxNum = ld->MaxNum; Decode_tmp.DecodeLen = ld->DecodeLen; Decode_tmp.DecodePos = ld->DecodePos; Decode_tmp.DecodeNum = ld->DecodeNum; return &Decode_tmp; } struct Decode * BitDecode2Decode (struct BitDecode *ld) { Decode_tmp.MaxNum = ld->MaxNum; Decode_tmp.DecodeLen = ld->DecodeLen; Decode_tmp.DecodePos = ld->DecodePos; Decode_tmp.DecodeNum = ld->DecodeNum; return &Decode_tmp; } void Decode2LitDecode (struct LitDecode *ld) { ld->MaxNum = Decode_tmp.MaxNum; } void Decode2DistDecode (struct DistDecode *ld) { ld->MaxNum = Decode_tmp.MaxNum; } void Decode2RepDecode (struct RepDecode *ld) { ld->MaxNum = Decode_tmp.MaxNum; } void Decode2MultDecode (struct MultDecode *ld) { ld->MaxNum = Decode_tmp.MaxNum; } void Decode2BitDecode (struct BitDecode *ld) { ld->MaxNum = Decode_tmp.MaxNum; } void Unpack (unsigned char *UnpAddr) /* *** 38.3% of all CPU time is spent within this function!!! */ { static unsigned char LDecode[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224 }; static unsigned char LBits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; static int DDecode[] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768U, 49152U, 65536, 98304, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, 917504, 983040 }; static unsigned char DBits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; static unsigned char SDDecode[] = { 0, 4, 8, 16, 32, 64, 128, 192 }; static unsigned char SDBits[] = { 2, 2, 3, 4, 5, 6, 6, 6 }; unsigned int Bits; /* UnpAddr is a pointer to the unpack buffer */ UnpBuf = UnpAddr; UnpInitData (); UnpReadBuf (1); if (!(NewLhd.Flags & LHD_SOLID)) ReadTables (); DestUnpSize--; while (DestUnpSize >= 0) { UnpPtr &= MAXWINMASK; if (InAddr > sizeof (InBuf) - 30) UnpReadBuf (0); if (((WrPtr - UnpPtr) & MAXWINMASK) < 270 && WrPtr != UnpPtr) { if (FileFound) { if (UnpPtr < WrPtr) { if ((*temp_output_buffer_offset + UnpPtr) > NewLhd.UnpSize) { debug_log ("Fatal! Buffer overrun during decompression!"); DestUnpSize = -1; } else { /* copy extracted data to output buffer */ memcpy (temp_output_buffer + *temp_output_buffer_offset, &UnpBuf[WrPtr], (0 - WrPtr) & MAXWINMASK); /* update offset within buffer */ *temp_output_buffer_offset += (0 - WrPtr) & MAXWINMASK; /* copy extracted data to output buffer */ memcpy (temp_output_buffer + *temp_output_buffer_offset, UnpBuf, UnpPtr); /* update offset within buffer */ *temp_output_buffer_offset += UnpPtr; } } else { if ((*temp_output_buffer_offset + (UnpPtr - WrPtr)) > NewLhd.UnpSize) { debug_log ("Fatal! Buffer overrun during decompression!"); DestUnpSize = -1; } else { /* copy extracted data to output buffer */ memcpy (temp_output_buffer + *temp_output_buffer_offset, &UnpBuf[WrPtr], UnpPtr - WrPtr); *temp_output_buffer_offset += UnpPtr - WrPtr; /* update offset within buffer */ } } } WrPtr = UnpPtr; } if (UnpAudioBlock) { DecodeNumber ((struct Decode *) MDPtr[CurChannel]); if (Number == 256) { ReadTables (); continue; } UnpBuf[UnpPtr++] = DecodeAudio (Number); if (++CurChannel == UnpChannels) CurChannel = 0; DestUnpSize--; continue; } DecodeNumber (LitDecode2Decode(&LD)); if (Number < 256) { UnpBuf[UnpPtr++] = (UBYTE) Number; DestUnpSize--; continue; } if (Number > 269) { Length = LDecode[Number -= 270] + 3; if ((Bits = LBits[Number]) > 0) { GetBits (); Length += BitField >> (16 - Bits); AddBits (Bits); } DecodeNumber (DistDecode2Decode(&DD)); Distance = DDecode[Number] + 1; if ((Bits = DBits[Number]) > 0) { GetBits (); Distance += BitField >> (16 - Bits); AddBits (Bits); } if (Distance >= 0x40000L) Length++; if (Distance >= 0x2000) Length++; LastDist = OldDist[OldDistPtr++ & 3] = Distance; DestUnpSize -= (LastLength = Length); while (Length--) { UnpBuf[UnpPtr] = UnpBuf[(UnpPtr - Distance) & MAXWINMASK]; UnpPtr = (UnpPtr + 1) & MAXWINMASK; } continue; } if (Number == 269) { ReadTables (); continue; } if (Number == 256) { Length = LastLength; Distance = LastDist; LastDist = OldDist[OldDistPtr++ & 3] = Distance; DestUnpSize -= (LastLength = Length); while (Length--) { UnpBuf[UnpPtr] = UnpBuf[(UnpPtr - Distance) & MAXWINMASK]; UnpPtr = (UnpPtr + 1) & MAXWINMASK; } continue; } if (Number < 261) { Distance = OldDist[(OldDistPtr - (Number - 256)) & 3]; DecodeNumber (RepDecode2Decode(&RD)); Length = LDecode[Number] + 2; if ((Bits = LBits[Number]) > 0) { GetBits (); Length += BitField >> (16 - Bits); AddBits (Bits); } if (Distance >= 0x40000) Length++; if (Distance >= 0x2000) Length++; if (Distance >= 0x101) Length++; LastDist = OldDist[OldDistPtr++ & 3] = Distance; DestUnpSize -= (LastLength = Length); while (Length--) { UnpBuf[UnpPtr] = UnpBuf[(UnpPtr - Distance) & MAXWINMASK]; UnpPtr = (UnpPtr + 1) & MAXWINMASK; } continue; } if (Number < 270) { Distance = SDDecode[Number -= 261] + 1; if ((Bits = SDBits[Number]) > 0) { GetBits (); Distance += BitField >> (16 - Bits); AddBits (Bits); } Length = 2; LastDist = OldDist[OldDistPtr++ & 3] = Distance; DestUnpSize -= (LastLength = Length); while (Length--) { UnpBuf[UnpPtr] = UnpBuf[(UnpPtr - Distance) & MAXWINMASK]; UnpPtr = (UnpPtr + 1) & MAXWINMASK; } continue; } } ReadLastTables (); if (FileFound) /* flush buffer */ { if (UnpPtr < WrPtr) { if ((*temp_output_buffer_offset + UnpPtr) > NewLhd.UnpSize) { debug_log ("Fatal! Buffer overrun during decompression!"); DestUnpSize = -1; } else { /* copy extracted data to output buffer */ memcpy (temp_output_buffer + *temp_output_buffer_offset, &UnpBuf[WrPtr], (0 - WrPtr) & MAXWINMASK); /* update offset within buffer */ *temp_output_buffer_offset += (0 - WrPtr) & MAXWINMASK; /* copy extracted data to output buffer */ memcpy (temp_output_buffer + *temp_output_buffer_offset, UnpBuf, UnpPtr); /* update offset within buffer */ *temp_output_buffer_offset += UnpPtr; } } else { if ((*temp_output_buffer_offset + (UnpPtr - WrPtr)) > NewLhd.UnpSize) { debug_log ("Fatal! Buffer overrun during decompression!"); DestUnpSize = -1; } else { /* copy extracted data to output buffer */ memcpy (temp_output_buffer + *temp_output_buffer_offset, &UnpBuf[WrPtr], UnpPtr - WrPtr); /* update offset within buffer */ *temp_output_buffer_offset += UnpPtr - WrPtr; } } } WrPtr = UnpPtr; } unsigned int UnpRead (unsigned char *Addr, unsigned int Count) { int RetCode = 0; unsigned int I, ReadSize, TotalRead = 0; unsigned char *ReadAddr = Addr; if (Count > 0) { ReadSize = (unsigned int) ((Count > (unsigned long) UnpPackedSize) ? (unsigned int)UnpPackedSize : Count); if (inputfile == NULL) return 0; RetCode = fread (ReadAddr, 1, ReadSize, inputfile); CurUnpRead += RetCode; ReadAddr += RetCode; TotalRead += RetCode; Count -= RetCode; UnpPackedSize -= RetCode; } if (RetCode != -1) { RetCode = TotalRead; if (Encryption) { if (Encryption < 20) { debug_log ("Old Crypt() not supported!"); } else { for (I = 0; I < (unsigned int) RetCode; I += 16) DecryptBlock (&Addr[I]); } } } return RetCode; } void UnpReadBuf (int FirstBuf) { int RetCode; if (FirstBuf) { ReadTop = UnpRead (InBuf, sizeof (InBuf)); InAddr = 0; } else { memcpy (InBuf, &InBuf[sizeof (InBuf) - 32], 32); InAddr &= 0x1f; RetCode = UnpRead (&InBuf[32], sizeof (InBuf) - 32); if (RetCode > 0) ReadTop = RetCode + 32; else ReadTop = InAddr; } } void ReadTables (void) { UBYTE BitLength[BC]; unsigned char Table[MC * 4]; int TableSize, N, I; if (InAddr > sizeof (InBuf) - 25) UnpReadBuf (0); GetBits (); UnpAudioBlock = (BitField & 0x8000); if (!(BitField & 0x4000)) memset (UnpOldTable, 0, sizeof (UnpOldTable)); AddBits (2); if (UnpAudioBlock) { UnpChannels = ((BitField >> 12) & 3) + 1; if (CurChannel >= UnpChannels) CurChannel = 0; AddBits (2); TableSize = MC * UnpChannels; } else TableSize = NC + DC + RC; for (I = 0; I < BC; I++) { GetBits (); BitLength[I] = (UBYTE) (BitField >> 12); AddBits (4); } MakeDecodeTables (BitLength, BitDecode2Decode(&BD), BC); Decode2BitDecode(&BD); I = 0; while (I < TableSize) { if (InAddr > sizeof (InBuf) - 5) UnpReadBuf (0); DecodeNumber (BitDecode2Decode(&BD)); if (Number < 16) { Table[I] = (Number + UnpOldTable[I]) & 0xf; I++; } else if (Number == 16) { GetBits (); N = (BitField >> 14) + 3; AddBits (2); while (N-- > 0 && I < TableSize) { Table[I] = Table[I - 1]; I++; } } else { if (Number == 17) { GetBits (); N = (BitField >> 13) + 3; AddBits (3); } else { GetBits (); N = (BitField >> 9) + 11; AddBits (7); } while (N-- > 0 && I < TableSize) Table[I++] = 0; } } if (UnpAudioBlock) for (I = 0; I < UnpChannels; I++) { MakeDecodeTables (&Table[I * MC], MultDecode2Decode(MDPtr[I]), MC); Decode2MultDecode(MDPtr[I]); } else { MakeDecodeTables (&Table[0], LitDecode2Decode(&LD), NC); Decode2LitDecode(&LD); MakeDecodeTables (&Table[NC], DistDecode2Decode(&DD), DC); Decode2DistDecode(&DD); MakeDecodeTables (&Table[NC + DC], RepDecode2Decode(&RD), RC); Decode2RepDecode(&RD); } memcpy (UnpOldTable, Table, sizeof (UnpOldTable)); } static void ReadLastTables (void) { if (ReadTop >= InAddr + 5) { if (UnpAudioBlock) { DecodeNumber (MultDecode2Decode(MDPtr[CurChannel])); if (Number == 256) ReadTables (); } else { DecodeNumber (LitDecode2Decode(&LD)); if (Number == 269) ReadTables (); } } } static void MakeDecodeTables (unsigned char *LenTab, struct Decode *Dec, int Size) { int LenCount[16], TmpPos[16], I; long M, N; memset (LenCount, 0, sizeof (LenCount)); for (I = 0; I < Size; I++) LenCount[LenTab[I] & 0xF]++; LenCount[0] = 0; for (TmpPos[0] = Dec->DecodePos[0] = Dec->DecodeLen[0] = 0, N = 0, I = 1; I < 16; I++) { N = 2 * (N + LenCount[I]); M = N << (15 - I); if (M > 0xFFFF) M = 0xFFFF; Dec->DecodeLen[I] = (unsigned int) M; TmpPos[I] = Dec->DecodePos[I] = Dec->DecodePos[I - 1] + LenCount[I - 1]; } for (I = 0; I < Size; I++) if (LenTab[I] != 0) Dec->DecodeNum[TmpPos[LenTab[I] & 0xF]++] = I; Dec->MaxNum = Size; } static void DecodeNumber (struct Decode *Deco) /* *** 52.6% of all CPU time is spent within this function!!! */ { unsigned int I; register unsigned int N; GetBits (); #ifdef _USE_ASM __asm__ __volatile__ ("andl $0xFFFFFFFE, %%eax\n" " movl %%eax, %1\n" " cmpl 8*4(%%edx), %%eax /* 5379 */\n" " jae else_G\n" "\n" " cmpl 4*4(%%edx), %%eax\n" " jae else_F\n" "\n" " cmpl 2*4(%%edx), %%eax\n" " jae else_C\n" "\n" " cmpl 1*4(%%edx), %%eax\n" "\n" " jae else_1\n" " movl $1, %0\n" " jmp next_1\n" " else_1: \n" " movl $2, %0\n" " next_1:\n" " \n" " jmp next_C\n" " else_C: \n" "\n" " cmpl 3*4(%%edx), %%eax \n" " jae else_2\n" " movl $3, %0\n" " jmp next_2\n" " else_2: \n" " movl $4, %0\n" " next_2:\n" "\n" " next_C: \n" "\n" " jmp next_F\n" " else_F:\n" "\n" " cmpl 6*4(%%edx), %%eax\n" " jae else_E\n" "\n" " cmpl 5*4(%%edx), %%eax\n" " jae else_3\n" " movl $5, %0 \n" " jmp next_3\n" " else_3: \n" " movl $6, %0 \n" " next_3:\n" "\n" " jmp next_E\n" " else_E: \n" "\n" " cmpl 7*4(%%edx), %%eax\n" " jae else_4\n" " movl $7, %0 \n" " jmp next_4\n" " else_4: \n" " movl $8, %0 \n" " next_4:\n" "\n" " next_E:\n" "\n" " next_F:\n" "\n" " jmp next_G\n" " else_G:\n" "\n" " cmpl 12*4(%%edx), %%eax\n" " jae else_D\n" "\n" " cmpl 10*4(%%edx), %%eax\n" " jae else_B\n" "\n" " cmpl 9*4(%%edx), %%eax\n" " jae else_5\n" " movl $9, %0 \n" " jmp next_5\n" " else_5: \n" " movl $10, %0 \n" " next_5:\n" "\n" " jmp next_B\n" " else_B: \n" "\n" " cmpl 11*4(%%edx), %%eax\n" " \n" " jae else_6\n" " movl $11, %0 \n" " jmp next_6\n" " else_6: \n" " movl $12, %0 \n" " next_6:\n" "\n" " next_B:\n" " \n" " \n" " jmp next_D\n" " else_D: \n" "\n" " cmpl 14*4(%%edx), %%eax\n" " jae else_A\n" "\n" " cmpl 13*4(%%edx), %%eax\n" " jae else_7\n" " movl $13, %0\n" " jmp next_7\n" " else_7: \n" " movl $14, %0\n" " next_7:\n" "\n" " jmp next_A\n" " else_A: \n" " movl $15, %0 \n" " next_A:\n" " \n" " next_D: \n" " next_G:\n":"=g" (I), "=r" (N):"eax" ((long) BitField), "edx" ((long) Deco->DecodeLen):"memory"); #else N = BitField & 0xFFFE; if (!Deco->DecodeLen) return; if (N < Deco->DecodeLen[8]) { if (N < Deco->DecodeLen[4]) { if (N < Deco->DecodeLen[2]) { if (N < Deco->DecodeLen[1]) I = 1; else I = 2; } else { if (N < Deco->DecodeLen[3]) I = 3; else I = 4; } } else { if (N < Deco->DecodeLen[6]) { if (N < Deco->DecodeLen[5]) I = 5; else I = 6; } else { if (N < Deco->DecodeLen[7]) I = 7; else I = 8; } } } else { if (N < Deco->DecodeLen[12]) { if (N < Deco->DecodeLen[10]) { if (N < Deco->DecodeLen[9]) I = 9; else I = 10; } else { if (N < Deco->DecodeLen[11]) I = 11; else I = 12; } } else { if (N < Deco->DecodeLen[14]) { if (N < Deco->DecodeLen[13]) I = 13; else I = 14; } else { I = 15; } } } #endif AddBits (I); if ((N = Deco->DecodePos[I] + ((N - Deco->DecodeLen[I - 1]) >> (16 - I))) >= Deco->MaxNum) N = 0; Number = Deco->DecodeNum[N]; } void UnpInitData () { InAddr = InBit = 0; if (!(NewLhd.Flags & LHD_SOLID)) { ChannelDelta = CurChannel = 0; #ifdef _USE_ASM asm volatile (" cld\n" /* increment EDI and ESI */ " movb $0x00, %%al\n" " movl %0, %%ecx\n" " movl %1, %%edi\n" " rep\n" " stosb\n" /* clear memory */ "\n" " movl %2, %%ecx\n" " mov %3, %%edi\n" " rep\n" " stosb\n" /* clear memory */ "\n" " movl %4, %%ecx\n" " movl %5, %%edi\n" " rep\n" " stosb\n" /* clear memory */ "\n" " movl $0, (OldDistPtr)\n" " movl $0, (LastDist)\n" " movl $0, (LastLength)\n" " movl $0, (UnpPtr)\n" " movl $0, (WrPtr)\n" " movl $0, (OldDistPtr)\n" " movl $0, (LastLength)\n" " movl $0, (LastDist)\n" " movl $0, (UnpPtr)\n" " movl $0, (WrPtr)\n" : : "m" ((long) sizeof (AudV)), "m" ((long) AudV), "m" ((long) sizeof (OldDist)), "m" ((long) OldDist), "m" ((long) sizeof (UnpOldTable)), "m" ((long) UnpOldTable) :"memory", "edi", "eax", "ecx"); memset (UnpBuf, 0, MAXWINSIZE); #else /* unix/linux on non-i386 cpu */ memset (AudV, 0, sizeof (AudV)); memset (OldDist, 0, sizeof (OldDist)); OldDistPtr = 0; LastDist = LastLength = 0; memset (UnpBuf, 0, MAXWINSIZE); memset (UnpOldTable, 0, sizeof (UnpOldTable)); UnpPtr = WrPtr = 0; #endif } } UBYTE DecodeAudio (int Delta) { struct AudioVariables *V; unsigned int Ch; unsigned int NumMinDif, MinDif; int PCh, I; V = &AudV[CurChannel]; V->ByteCount++; V->D4 = V->D3; V->D3 = V->D2; V->D2 = V->LastDelta - V->D1; V->D1 = V->LastDelta; PCh = 8 * V->LastChar + V->K1 * V->D1 + V->K2 * V->D2 + V->K3 * V->D3 + V->K4 * V->D4 + V->K5 * ChannelDelta; PCh = (PCh >> 3) & 0xFF; Ch = PCh - Delta; I = ((signed char) Delta) << 3; V->Dif[0] += abs (I); V->Dif[1] += abs (I - V->D1); V->Dif[2] += abs (I + V->D1); V->Dif[3] += abs (I - V->D2); V->Dif[4] += abs (I + V->D2); V->Dif[5] += abs (I - V->D3); V->Dif[6] += abs (I + V->D3); V->Dif[7] += abs (I - V->D4); V->Dif[8] += abs (I + V->D4); V->Dif[9] += abs (I - ChannelDelta); V->Dif[10] += abs (I + ChannelDelta); ChannelDelta = V->LastDelta = (signed char) (Ch - V->LastChar); V->LastChar = Ch; if ((V->ByteCount & 0x1F) == 0) { MinDif = V->Dif[0]; NumMinDif = 0; V->Dif[0] = 0; for (I = 1; (unsigned int) I < sizeof (V->Dif) / sizeof (V->Dif[0]); I++) { if (V->Dif[I] < MinDif) { MinDif = V->Dif[I]; NumMinDif = I; } V->Dif[I] = 0; } switch (NumMinDif) { case 1: if (V->K1 >= -16) V->K1--; break; case 2: if (V->K1 < 16) V->K1++; break; case 3: if (V->K2 >= -16) V->K2--; break; case 4: if (V->K2 < 16) V->K2++; break; case 5: if (V->K3 >= -16) V->K3--; break; case 6: if (V->K3 < 16) V->K3++; break; case 7: if (V->K4 >= -16) V->K4--; break; case 8: if (V->K4 < 16) V->K4++; break; case 9: if (V->K5 >= -16) V->K5--; break; case 10: if (V->K5 < 16) V->K5++; break; } } return (UBYTE) Ch; } /* CRCCrypt Code - decryption engine starts here */ #define NROUNDS 32 #define rol(x,n) (((x)<<(n)) | ((x)>>(8*sizeof(x)-(n)))) #define ror(x,n) (((x)>>(n)) | ((x)<<(8*sizeof(x)-(n)))) #define substLong(t) ( (UDWORD)SubstTable[(int)t&255] | \ ((UDWORD)SubstTable[(int)(t>> 8)&255]<< 8) | \ ((UDWORD)SubstTable[(int)(t>>16)&255]<<16) | \ ((UDWORD)SubstTable[(int)(t>>24)&255]<<24) ) UDWORD CRCTab[256]; UBYTE SubstTable[256]; UBYTE InitSubstTable[256] = { 215, 19, 149, 35, 73, 197, 192, 205, 249, 28, 16, 119, 48, 221, 2, 42, 232, 1, 177, 233, 14, 88, 219, 25, 223, 195, 244, 90, 87, 239, 153, 137, 255, 199, 147, 70, 92, 66, 246, 13, 216, 40, 62, 29, 217, 230, 86, 6, 71, 24, 171, 196, 101, 113, 218, 123, 93, 91, 163, 178, 202, 67, 44, 235, 107, 250, 75, 234, 49, 167, 125, 211, 83, 114, 157, 144, 32, 193, 143, 36, 158, 124, 247, 187, 89, 214, 141, 47, 121, 228, 61, 130, 213, 194, 174, 251, 97, 110, 54, 229, 115, 57, 152, 94, 105, 243, 212, 55, 209, 245, 63, 11, 164, 200, 31, 156, 81, 176, 227, 21, 76, 99, 139, 188, 127, 17, 248, 51, 207, 120, 189, 210, 8, 226, 41, 72, 183, 203, 135, 165, 166, 60, 98, 7, 122, 38, 155, 170, 69, 172, 252, 238, 39, 134, 59, 128, 236, 27, 240, 80, 131, 3, 85, 206, 145, 79, 154, 142, 159, 220, 201, 133, 74, 64, 20, 129, 224, 185, 138, 103, 173, 182, 43, 34, 254, 82, 198, 151, 231, 180, 58, 10, 118, 26, 102, 12, 50, 132, 22, 191, 136, 111, 162, 179, 45, 4, 148, 108, 161, 56, 78, 126, 242, 222, 15, 175, 146, 23, 33, 241, 181, 190, 77, 225, 0, 46, 169, 186, 68, 95, 237, 65, 53, 208, 253, 168, 9, 18, 100, 52, 116, 184, 160, 96, 109, 37, 30, 106, 140, 104, 150, 5, 204, 117, 112, 84 }; UDWORD Key[4]; void EncryptBlock (UBYTE * Buf) { int I; UDWORD A, B, C, D, T, TA, TB; #ifdef NON_INTEL_BYTE_ORDER A = ((UDWORD) Buf[0] | ((UDWORD) Buf[1] << 8) | ((UDWORD) Buf[2] << 16) | ((UDWORD) Buf[3] << 24)) ^ Key[0]; B = ((UDWORD) Buf[4] | ((UDWORD) Buf[5] << 8) | ((UDWORD) Buf[6] << 16) | ((UDWORD) Buf[7] << 24)) ^ Key[1]; C = ((UDWORD) Buf[8] | ((UDWORD) Buf[9] << 8) | ((UDWORD) Buf[10] << 16) | ((UDWORD) Buf[11] << 24)) ^ Key[2]; D = ((UDWORD) Buf[12] | ((UDWORD) Buf[13] << 8) | ((UDWORD) Buf[14] << 16) | ((UDWORD) Buf[15] << 24)) ^ Key[3]; #else UDWORD *BufPtr; BufPtr = (UDWORD *) Buf; A = BufPtr[0] ^ Key[0]; B = BufPtr[1] ^ Key[1]; C = BufPtr[2] ^ Key[2]; D = BufPtr[3] ^ Key[3]; #endif for (I = 0; I < NROUNDS; I++) { T = ((C + rol (D, 11)) ^ Key[I & 3]); TA = A ^ substLong (T); T = ((D ^ rol (C, 17)) + Key[I & 3]); TB = B ^ substLong (T); A = C; B = D; C = TA; D = TB; } #ifdef NON_INTEL_BYTE_ORDER C ^= Key[0]; Buf[0] = (UBYTE) C; Buf[1] = (UBYTE) (C >> 8); Buf[2] = (UBYTE) (C >> 16); Buf[3] = (UBYTE) (C >> 24); D ^= Key[1]; Buf[4] = (UBYTE) D; Buf[5] = (UBYTE) (D >> 8); Buf[6] = (UBYTE) (D >> 16); Buf[7] = (UBYTE) (D >> 24); A ^= Key[2]; Buf[8] = (UBYTE) A; Buf[9] = (UBYTE) (A >> 8); Buf[10] = (UBYTE) (A >> 16); Buf[11] = (UBYTE) (A >> 24); B ^= Key[3]; Buf[12] = (UBYTE) B; Buf[13] = (UBYTE) (B >> 8); Buf[14] = (UBYTE) (B >> 16); Buf[15] = (UBYTE) (B >> 24); #else BufPtr[0] = C ^ Key[0]; BufPtr[1] = D ^ Key[1]; BufPtr[2] = A ^ Key[2]; BufPtr[3] = B ^ Key[3]; #endif UpdKeys (Buf); } void DecryptBlock (UBYTE * Buf) { int I; UBYTE InBuf[16]; UDWORD A, B, C, D, T, TA, TB; #ifdef NON_INTEL_BYTE_ORDER A = ((UDWORD) Buf[0] | ((UDWORD) Buf[1] << 8) | ((UDWORD) Buf[2] << 16) | ((UDWORD) Buf[3] << 24)) ^ Key[0]; B = ((UDWORD) Buf[4] | ((UDWORD) Buf[5] << 8) | ((UDWORD) Buf[6] << 16) | ((UDWORD) Buf[7] << 24)) ^ Key[1]; C = ((UDWORD) Buf[8] | ((UDWORD) Buf[9] << 8) | ((UDWORD) Buf[10] << 16) | ((UDWORD) Buf[11] << 24)) ^ Key[2]; D = ((UDWORD) Buf[12] | ((UDWORD) Buf[13] << 8) | ((UDWORD) Buf[14] << 16) | ((UDWORD) Buf[15] << 24)) ^ Key[3]; #else UDWORD *BufPtr; BufPtr = (UDWORD *) Buf; A = BufPtr[0] ^ Key[0]; /* xxx may be this can be */ B = BufPtr[1] ^ Key[1]; /* optimized in assembler */ C = BufPtr[2] ^ Key[2]; D = BufPtr[3] ^ Key[3]; #endif memcpy (InBuf, Buf, sizeof (InBuf)); for (I = NROUNDS - 1; I >= 0; I--) { T = ((C + rol (D, 11)) ^ Key[I & 3]); TA = A ^ substLong (T); T = ((D ^ rol (C, 17)) + Key[I & 3]); TB = B ^ substLong (T); A = C; B = D; C = TA; D = TB; } #ifdef NON_INTEL_BYTE_ORDER C ^= Key[0]; Buf[0] = (UBYTE) C; Buf[1] = (UBYTE) (C >> 8); Buf[2] = (UBYTE) (C >> 16); Buf[3] = (UBYTE) (C >> 24); D ^= Key[1]; Buf[4] = (UBYTE) D; Buf[5] = (UBYTE) (D >> 8); Buf[6] = (UBYTE) (D >> 16); Buf[7] = (UBYTE) (D >> 24); A ^= Key[2]; Buf[8] = (UBYTE) A; Buf[9] = (UBYTE) (A >> 8); Buf[10] = (UBYTE) (A >> 16); Buf[11] = (UBYTE) (A >> 24); B ^= Key[3]; Buf[12] = (UBYTE) B; Buf[13] = (UBYTE) (B >> 8); Buf[14] = (UBYTE) (B >> 16); Buf[15] = (UBYTE) (B >> 24); #else BufPtr[0] = C ^ Key[0]; BufPtr[1] = D ^ Key[1]; BufPtr[2] = A ^ Key[2]; BufPtr[3] = B ^ Key[3]; #endif UpdKeys (InBuf); } void UpdKeys (UBYTE * Buf) { int I; for (I = 0; I < 16; I += 4) { Key[0] ^= CRCTab[Buf[I]]; /* xxx may be I'll rewrite this */ Key[1] ^= CRCTab[Buf[I + 1]]; /* in asm for speedup */ Key[2] ^= CRCTab[Buf[I + 2]]; Key[3] ^= CRCTab[Buf[I + 3]]; } } void SetCryptKeys (char *Password) { unsigned int I, J, K, PswLength; unsigned char N1, N2; unsigned char Psw[256]; #if !defined _USE_ASM UBYTE Ch; #endif SetOldKeys (Password); Key[0] = 0xD3A3B879L; Key[1] = 0x3F6D12F7L; Key[2] = 0x7515A235L; Key[3] = 0xA4E7F123L; memset (Psw, 0, sizeof (Psw)); strcpy ((char *) Psw, Password); PswLength = strlen (Password); memcpy (SubstTable, InitSubstTable, sizeof (SubstTable)); for (J = 0; J < 256; J++) for (I = 0; I < PswLength; I += 2) { N2 = (unsigned char) CRCTab[(Psw[I + 1] + J) & 0xFF]; for (K = 1, N1 = (unsigned char) CRCTab[(Psw[I] - J) & 0xFF]; (N1 != N2) && (N1 < 256); /* I had to add "&& (N1 < 256)", because the system crashed with encrypted RARs */ N1++, K++) { #ifdef _USE_ASM __asm__ __volatile__ (" xorl %%ecx, %%ecx\n" " movl %2, %%ecx /* ecx = N1 */\n" " mov %%ebx, %%edx\n" " addl %%ecx, %%ebx\n" "\n" " addl %0, %%ecx\n" " addl %1, %%ecx\n" " andl $0x000000FF, %%ecx\n" " addl %%ecx, %%edx\n" " \n" " movb (%%ebx), %%al\n" " movb (%%edx), %%ah\n" "\n" " movb %%ah, (%%ebx) /* and write back */\n" " movb %%al, (%%edx)\n"::"g" ((long) I), "g" ((long) K), "g" ((long) N1), "ebx" ((long) SubstTable):"ecx", "edx"); #else /* Swap(&SubstTable[N1],&SubstTable[(N1+I+K)&0xFF]); */ Ch = SubstTable[N1]; SubstTable[N1] = SubstTable[(N1 + I + K) & 0xFF]; SubstTable[(N1 + I + K) & 0xFF] = Ch; #endif } } for (I = 0; I < PswLength; I += 16) EncryptBlock (&Psw[I]); } void SetOldKeys (char *Password) { UDWORD PswCRC; UBYTE Ch; PswCRC = CalcCRC32 (0xFFFFFFFFL, (UBYTE *) Password, strlen (Password)); OldKey[0] = (UWORD) PswCRC; OldKey[1] = (UWORD) (PswCRC >> 16); OldKey[2] = OldKey[3] = 0; PN1 = PN2 = PN3 = 0; while ((Ch = *Password) != 0) { PN1 += Ch; PN2 ^= Ch; PN3 += Ch; PN3 = (UBYTE) rol (PN3, 1); OldKey[2] ^= ((UWORD) (Ch ^ CRCTab[Ch])); OldKey[3] += ((UWORD) (Ch + (CRCTab[Ch] >> 16))); Password++; } } void InitCRC (void) { int I, J; UDWORD C; for (I = 0; I < 256; I++) { for (C = I, J = 0; J < 8; J++) C = (C & 1) ? (C >> 1) ^ 0xEDB88320L : (C >> 1); CRCTab[I] = C; } } uint32_t CalcCRC32 (uint32_t StartCRC, UBYTE * Addr, UDWORD Size) { unsigned int I; for (I = 0; I < Size; I++) StartCRC = CRCTab[(UBYTE) StartCRC ^ Addr[I]] ^ (StartCRC >> 8); return StartCRC; } unrar-free-0.0.2/src/unrarlib.h000066400000000000000000000100221412233604300163260ustar00rootroot00000000000000/* Copyright (C) 2004 Jeroen Dekkers Copyright (C) 2000-2002 by Christian Scheurer (www.ChristianScheurer.ch) Copyright (C) 2000-2002 by Johannes Winkelmann (jw@tks6.net) 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __URARLIB_H #define __URARLIB_H #ifdef __cplusplus extern "C" { #endif /* Perform cyclical redundancy check (CRC32) - you can disable this for a little speed-up */ #define _DO_CRC32_CHECK /* Disable assembly extensions for x86 cpus. */ #undef _USE_ASM /* -- global type definitions --------------------------------------------- */ typedef unsigned char UBYTE; typedef unsigned short UWORD; typedef unsigned long UDWORD; /* This structure is used for listing archive content */ struct RAR20_archive_entry /* These infos about files are */ { /* stored in RAR v2.0 archives */ char *Name; UWORD NameSize; UDWORD PackSize; UDWORD UnpSize; UBYTE HostOS; /* MSDOS=0,OS2=1,WIN32=2,UNIX=3 */ UDWORD FileCRC; UDWORD FileTime; UBYTE UnpVer; UBYTE Method; UDWORD FileAttr; }; typedef struct archivelist /* used to list archives */ { struct RAR20_archive_entry item; struct archivelist *next; } ArchiveList_struct; /* -- global functions ---------------------------------------------------- */ /* urarlib_get: * decompresses and decrypt data from a RAR file to a buffer in system memory. * * input: *output pointer to an empty char*. This pointer will show * to the extracted data * *size shows where to write the size of the decompressed * file * (**NOTE: URARLib _does_ memory allocation etc.!**) * *filename pointer to string containing the file to decompress * *rarfile pointer to a string with the full name and path of * the RAR file or pointer to a RAR file in memory if * memory-to-memory decompression is active. * *libpassword pointer to a string with the password used to * en-/decrypt the RAR * output: int returns TRUE on success or FALSE on error * (FALSE=0, TRUE=1) */ extern int urarlib_get (void **output, unsigned long *size, const char *filename, const char *rarfile, const char *libpassword); /* urarlib_list: * list the content of a RAR archive. * * input: *rarfile pointer to a string with the full name and path of * the RAR file or pointer to a RAR file in memory if * memory-to-memory decompression is active. * *list pointer to an ArchiveList_struct that can be * filled with details about the archive * to the extracted data * output: int number of files/directories within archive */ extern int urarlib_list (const char *rarfile, ArchiveList_struct **list); /* urarlib_freelist: * (after the suggestion and code of Duy Nguyen, Sean O'Blarney * and Johannes Winkelmann who independently wrote a patch) * free the memory of a ArchiveList_struct created by urarlib_list. * * input: *list pointer to an ArchiveList_struct * output: - */ extern void urarlib_freelist (ArchiveList_struct * list); #ifdef __cplusplus }; #endif #endif unrar-free-0.0.2/unrar-free.1000066400000000000000000000046211412233604300157100ustar00rootroot00000000000000.TH UNRAR-FREE 1 .SH NAME unrar-free \- extract files from rar archives .SH SYNOPSIS .PP \fBunrar-free\fR [\-xtfp?V] [\-\-extract] [\-\-list] [\-\-force] [\-\-extract-newer] [\-\-extract-no-paths] [\-\-password] [\-\-help] [\-\-usage] [\-\-version] ARCHIVE [FILE \&...] [DESTINATION] .SH DESCRIPTION .PP \fBunrar-free\fR is a program for extracting files from rar archives. .SH OPTIONS .PP These programs follow the usual GNU command line syntax, with long options starting with two dashes (`\-'). A summary of options is included below. .TP \fB-x\fP \fB\-\-extract\fP Extract files from archive (default). .TP \fB-t\fP \fB\-\-list\fP List files in archive. .TP \fB-f\fP \fB\-\-force\fP Overwrite files when extracting. .TP \fB\-\-extract-newer\fP Only extract newer files from the archive. .TP \fB\-\-extract-no-paths\fP Don't create directories while extracting. .TP \fB-p\fP \fB\-\-password\fP Decrypt archive using a password. .TP \fB-?\fP \fB\-\-help\fP Show program help. .TP \fB\-\-usage\fP Show short program usage message. .TP \fB-V\fP \fB\-\-version\fP Show version of program. .SH NON-FREE UNRAR COMPATIBLE SYNOPSIS .PP \fBunrar-free\fR [elvx] [\-ep] [\-o+] [\-o-] [\-p\fIPassword\fP] [\-u] [\-\-] ARCHIVE [FILE \&...] [DESTINATION] .PP This syntax should only be used in front-end programs which use the non-free unrar as a back-end. It is recommended to use this program by GNU command line syntax. .SH NON-FREE UNRAR COMPATIBLE OPTIONS .TP \fBe\fP Extract files from archive without full path. .TP \fBl\fP List files in archive. .TP \fBv\fP Verbosely list files in archive. .TP \fBx\fP Extract files from archive with full path. .TP \fB-ep\fP Don't create directories while extracting. .TP \fB-o+\fP Overwrite files when extracting. .TP \fB-o-\fP Don't overwrite files when extracting. .TP \fB-p\fP\fIPassword\fP Decrypt archive using the password \fIPassword\fP. .TP \fB-u\fP Only extract newer files from the archive. .TP \fB\-\-\fP Disable further switch processing. Any switch after the \-\- is treated as filename or destination. .SH BUGS .PP Advanced features of version 3.0 archives are not currently supported. .SH AUTHORS .PP This manual page was written by Niklas Vainio . Permission is granted to copy, distribute and/or modify this document under the terms of the GNU General Public License, Version 2, or any later version published by the Free Software Foundation.