pax_global_header00006660000000000000000000000064130355177540014524gustar00rootroot0000000000000052 comment=b20ef699b4ee5ded2f078ead776c7deac969e19a mktorrent-1.1/000077500000000000000000000000001303551775400134125ustar00rootroot00000000000000mktorrent-1.1/.gitignore000066400000000000000000000004071303551775400154030ustar00rootroot00000000000000# git-ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): *.[oa] *~ mktorrent prefix *.torrent mktorrent-1.1/BSDmakefile000066400000000000000000000031011303551775400154360ustar00rootroot00000000000000# This file is part of mktorrent # Copyright (C) 2007, 2009 Emil Renner Berthing # # mktorrent 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. # # mktorrent is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA .include "Makefile" CC ?= cc CFLAGS ?= -O2 -Wall INSTALL ?= install PREFIX ?= /usr/local .ifdef USE_PTHREADS DEFINES += -DUSE_PTHREADS SRCS := $(SRCS:hash.c=hash_pthreads.c) LIBS += -lpthread .endif .ifdef USE_OPENSSL DEFINES += -DUSE_OPENSSL SRCS := $(SRCS:sha1.c=) LIBS += -lcrypto .endif .ifdef USE_LONG_OPTIONS DEFINES += -DUSE_LONG_OPTIONS .endif .ifdef USE_LARGE_FILES DEFINES += -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 .endif .ifdef NO_HASH_CHECK DEFINES += -DNO_HASH_CHECK .endif .ifdef MAX_OPENFD DEFINES += -DMAX_OPENFD="$(MAX_OPENFD)" .endif .ifdef DEBUG DEFINES += -DDEBUG .endif OBJS = $(SRCS:.c=.o) all: $(program) .SUFFIXES: .o .c .c.o: $(CC) $(CFLAGS) $(DEFINES) -DPRIoff="\"`./prefix`d\"" -DVERSION="\"$(version)\"" -c $(.IMPSRC) $(OBJS): $(HEADERS) prefix .include "rules.mk" mktorrent-1.1/COPYING000066400000000000000000000437511303551775400144570ustar00rootroot00000000000000Copyright (C) 2007, 2009 Emil Renner Berthing mktorrent is licensed under the terms of the GNU GPL version 2, or (at your option) any later version with one special exception: Permission is granted to link the code in this release with the OpenSSL project's 'OpenSSL' library and to distribute the linked executables. Works derived from mktorrent may, at their authors' discretion, keep or delete this exception. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU 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 Street, Fifth Floor, Boston, MA 02110-1301, USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. mktorrent-1.1/GNUmakefile000066400000000000000000000030521303551775400154640ustar00rootroot00000000000000# This file is part of mktorrent # Copyright (C) 2007, 2009 Emil Renner Berthing # # mktorrent 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. # # mktorrent is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA include Makefile CC ?= cc CFLAGS ?= -O2 -Wall INSTALL ?= install PREFIX ?= /usr/local ifdef USE_PTHREADS DEFINES += -DUSE_PTHREADS SRCS := $(SRCS:hash.c=hash_pthreads.c) LIBS += -lpthread endif ifdef USE_OPENSSL DEFINES += -DUSE_OPENSSL SRCS := $(SRCS:sha1.c=) LIBS += -lcrypto endif ifdef USE_LONG_OPTIONS DEFINES += -DUSE_LONG_OPTIONS endif ifdef USE_LARGE_FILES DEFINES += -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 endif ifdef NO_HASH_CHECK DEFINES += -DNO_HASH_CHECK endif ifdef MAX_OPENFD DEFINES += -DMAX_OPENFD="$(MAX_OPENFD)" endif ifdef DEBUG DEFINES += -DDEBUG endif OFFPRFX = $(shell ./prefix) OBJS = $(SRCS:.c=.o) all: $(program) %.o: %.c $(HEADERS) prefix $(CC) $(CFLAGS) $(DEFINES) -DPRIoff="\"$(OFFPRFX)d\"" -DVERSION="\"$(version)\"" -c $< include rules.mk mktorrent-1.1/Makefile000066400000000000000000000046311303551775400150560ustar00rootroot00000000000000# This file is part of mktorrent # Copyright (C) 2007, 2009 Emil Renner Berthing # # mktorrent 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. # # mktorrent is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA #-------------Interesting variables for you to override :)-------------------- # Default settings shown #CC = cc #CFLAGS = -O2 -Wall #LDFLAGS = #INSTALL = install #PREFIX = /usr/local #DESTDIR = # Use multiple POSIX threads for calculating hashes. This should be slightly # faster. Much faster on systems with multiple CPUs and fast harddrives. #USE_PTHREADS = 1 # Use the SHA1 implementation in the OpenSSL library instead of compiling our # own. #USE_OPENSSL = 1 # Enable long options, started with two dashes. #USE_LONG_OPTIONS = 1 # This is needed on certain 32bit OSes (notably 32bit Linux) to support # files and torrents > 2Gb. #USE_LARGE_FILES = 1 # Disable a redundant check to see if the amount of bytes read from files while # hashing matches the sum of reported file sizes. I've never seen this fail. It # will fail if you change files yet to be hashed while mktorrent is running, # but who'd want to do that? #NO_HASH_CHECK = 1 # Set the number of microseconds mktorrent will wait between every progress # report when hashing multithreaded. Default is 200000, that is 0.2 seconds # between every update. #PROGRESS_PERIOD = 200000 # Maximum number of file descriptors mktorrent will open when scanning the # directory. Default is 100, but I have no idea what a sane default for this # value is, so your number is probably better. #MAX_OPENFD = 100 # Enable leftover debugging code. Usually just spams you with lots of useless # information. #DEBUG = 1 #-------------Nothing interesting below this line----------------------------- program = mktorrent version = 1.1 HEADERS = mktorrent.h SRCS = ftw.c init.c sha1.c hash.c output.c main.c mktorrent-1.1/README000066400000000000000000000004101303551775400142650ustar00rootroot00000000000000Type 'make' to build the program. Do 'make install' to install the program to /usr/local/bin. For more options look in the Makefile. If you use an old version of BSD's make, you might need make -f BSDmakefile See http://mktorrent.sourceforge.net/ for more info. mktorrent-1.1/ftw.c000066400000000000000000000126551303551775400143670ustar00rootroot00000000000000/* This file is part of mktorrent Copyright (C) 2009 Emil Renner Berthing mktorrent 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. mktorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef ALLINONE #include #include #include #include #include #include #include #include #ifdef _WIN32 #define DIRSEP_CHAR '\\' #else #define DIRSEP_CHAR '/' #endif /* _WIN32 */ #define EXPORT #endif /* ALLINONE */ #include "ftw.h" struct dir_state { struct dir_state *next; struct dir_state *prev; size_t length; DIR *dir; off_t offset; }; static struct dir_state *dir_state_new(struct dir_state *prev, struct dir_state *next) { struct dir_state *ds = malloc(sizeof(struct dir_state)); if (ds == NULL) { fprintf(stderr, "Out of memory.\n"); return NULL; } ds->prev = prev; ds->next = next; return ds; } static unsigned int dir_state_open(struct dir_state *ds, const char *name, size_t length) { ds->dir = opendir(name); if (ds->dir == NULL) { fprintf(stderr, "Error opening '%s': %s\n", name, strerror(errno)); return 1; } ds->length = length; return 0; } static unsigned int dir_state_reopen(struct dir_state *ds, char *name) { name[ds->length] = '\0'; ds->dir = opendir(name); if (ds->dir == NULL) { fprintf(stderr, "Error opening '%s': %s\n", name, strerror(errno)); return 1; } name[ds->length] = DIRSEP_CHAR; seekdir(ds->dir, ds->offset); return 0; } static unsigned int dir_state_close(struct dir_state *ds) { ds->offset = telldir(ds->dir); if (ds->offset < 0) { fprintf(stderr, "Error getting dir offset: %s\n", strerror(errno)); return 1; } if (closedir(ds->dir)) { fprintf(stderr, "Error closing directory: %s\n", strerror(errno)); return 1; } ds->dir = NULL; return 0; } static unsigned int cleanup(struct dir_state *ds, char *path, int ret) { while (ds->prev) ds = ds->prev; do { struct dir_state *next = ds->next; free(ds); ds = next; } while (ds); if (path) free(path); return ret; } EXPORT int file_tree_walk(const char *dirname, unsigned int nfds, file_tree_walk_cb callback, void *data) { size_t path_size = 256; char *path; char *path_max; char *end; struct dir_state *ds = dir_state_new(NULL, NULL); struct dir_state *first_open; unsigned int nopen; if (ds == NULL) return -1; path = malloc(path_size); if (path == NULL) { fprintf(stderr, "Out of memory.\n"); return cleanup(ds, NULL, -1); } path_max = path + path_size; /* copy dirname to path */ end = path; while ((*end = *dirname)) { dirname++; end++; if (end == path_max) { char *new_path; new_path = realloc(path, 2*path_size); if (new_path == NULL) { fprintf(stderr, "Out of memory.\n"); return cleanup(ds, path, -1); } end = new_path + path_size; path_size *= 2; path = new_path; path_max = path + path_size; } } /* strip ending directory separators */ while (end > path && *(end-1) == DIRSEP_CHAR) { end--; *end = '\0'; } if (dir_state_open(ds, path, end - path)) return cleanup(ds, path, -1); first_open = ds; nopen = 1; *end = DIRSEP_CHAR; while (1) { struct dirent *de = readdir(ds->dir); if (de) { struct stat sbuf; const char *p; int r; if (de->d_name[0] == '.' && (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0'))) { continue; } end = path + ds->length + 1; p = de->d_name; while ((*end = *p)) { p++; end++; if (end == path_max) { char *new_path; new_path = realloc(path, 2*path_size); if (new_path == NULL) { fprintf(stderr, "Out of memory.\n"); return cleanup(ds, path, -1); } end = new_path + path_size; path_size *= 2; path = new_path; path_max = path + path_size; } } if (stat(path, &sbuf)) { fprintf(stderr, "Error stat'ing '%s': %s\n", path, strerror(errno)); return cleanup(ds, path, -1); } r = callback(path, &sbuf, data); if (r) return cleanup(ds, path, r); if (S_ISDIR(sbuf.st_mode)) { if (ds->next == NULL && (ds->next = dir_state_new(ds, NULL)) == NULL) return cleanup(ds, path, -1); ds = ds->next; if (nopen == nfds) { if (dir_state_close(first_open)) return cleanup(ds, path, -1); first_open = first_open->next; nopen--; } if (dir_state_open(ds, path, end - path)) return cleanup(ds, path, -1); nopen++; *end = DIRSEP_CHAR; } } else { if (closedir(ds->dir)) { path[ds->length] = '\0'; fprintf(stderr, "Error closing '%s': %s\n", path, strerror(errno)); return cleanup(ds, path, -1); } if (ds->prev == NULL) break; ds = ds->prev; nopen--; if (ds->dir == NULL) { if (dir_state_reopen(ds, path)) return cleanup(ds, path, -1); first_open = ds; nopen++; } } } return cleanup(ds, path, 0); } mktorrent-1.1/ftw.h000066400000000000000000000004361303551775400143660ustar00rootroot00000000000000#ifndef _FTW_H #define _FTW_H typedef int (*file_tree_walk_cb)(const char *name, const struct stat *sbuf, void *data); #ifndef ALLINONE int file_tree_walk(const char *dirname, unsigned int nfds, file_tree_walk_cb callback, void *data); #endif /* ALLINONE */ #endif /* _FTW_H */ mktorrent-1.1/hash.c000066400000000000000000000110741303551775400145040ustar00rootroot00000000000000/* This file is part of mktorrent Copyright (C) 2007, 2009 Emil Renner Berthing mktorrent 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. mktorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef ALLINONE #include /* exit() */ #include /* off_t */ #include /* errno */ #include /* strerror() */ #include /* printf() etc. */ #include /* open() */ #include /* read(), close() */ #ifdef USE_OPENSSL #include /* SHA1() */ #else #include #include "sha1.h" #endif #include "mktorrent.h" #define EXPORT #endif /* ALLINONE */ #ifndef O_BINARY #define O_BINARY 0 #endif #if defined _LARGEFILE_SOURCE && defined O_LARGEFILE #define OPENFLAGS (O_RDONLY | O_BINARY | O_LARGEFILE) #else #define OPENFLAGS (O_RDONLY | O_BINARY) #endif /* * go through the files in file_list, split their contents into pieces * of size piece_length and create the hash string, which is the * concatenation of the (20 byte) SHA1 hash of every piece * last piece may be shorter */ EXPORT unsigned char *make_hash(metafile_t *m) { flist_t *f; /* pointer to a place in the file list */ unsigned char *hash_string; /* the hash string */ unsigned char *pos; /* position in the hash string */ unsigned char *read_buf; /* read buffer */ int fd; /* file descriptor */ ssize_t r; /* number of bytes read from file(s) into the read buffer */ SHA_CTX c; /* SHA1 hashing context */ #ifndef NO_HASH_CHECK off_t counter = 0; /* number of bytes hashed should match size when done */ #endif /* allocate memory for the hash string every SHA1 hash is SHA_DIGEST_LENGTH (20) bytes long */ hash_string = malloc(m->pieces * SHA_DIGEST_LENGTH); /* allocate memory for the read buffer to store 1 piece */ read_buf = malloc(m->piece_length); /* check if we've run out of memory */ if (hash_string == NULL || read_buf == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } /* initiate pos to point to the beginning of hash_string */ pos = hash_string; /* and initiate r to 0 since we haven't read anything yet */ r = 0; /* go through all the files in the file list */ for (f = m->file_list; f; f = f->next) { /* open the current file for reading */ if ((fd = open(f->path, OPENFLAGS)) == -1) { fprintf(stderr, "Error opening '%s' for reading: %s\n", f->path, strerror(errno)); exit(EXIT_FAILURE); } printf("Hashing %s.\n", f->path); fflush(stdout); /* fill the read buffer with the contents of the file and append the SHA1 hash of it to the hash string when the buffer is full. repeat until we can't fill the read buffer and we've thus come to the end of the file */ while (1) { ssize_t d = read(fd, read_buf + r, m->piece_length - r); if (d < 0) { fprintf(stderr, "Error reading from '%s': %s\n", f->path, strerror(errno)); exit(EXIT_FAILURE); } if (d == 0) /* end of file */ break; r += d; if (r == m->piece_length) { SHA1_Init(&c); SHA1_Update(&c, read_buf, m->piece_length); SHA1_Final(pos, &c); pos += SHA_DIGEST_LENGTH; #ifndef NO_HASH_CHECK counter += r; /* r == piece_length */ #endif r = 0; } } /* now close the file */ if (close(fd)) { fprintf(stderr, "Error closing '%s': %s\n", f->path, strerror(errno)); exit(EXIT_FAILURE); } } /* finally append the hash of the last irregular piece to the hash string */ if (r) { SHA1_Init(&c); SHA1_Update(&c, read_buf, r); SHA1_Final(pos, &c); } #ifndef NO_HASH_CHECK counter += r; if (counter != m->size) { fprintf(stderr, "Counted %" PRIoff " bytes, " "but hashed %" PRIoff " bytes. " "Something is wrong...\n", m->size, counter); exit(EXIT_FAILURE); } #endif /* free the read buffer before we return */ free(read_buf); return hash_string; } mktorrent-1.1/hash_pthreads.c000066400000000000000000000206271303551775400164020ustar00rootroot00000000000000/* This file is part of mktorrent Copyright (C) 2007, 2009 Emil Renner Berthing mktorrent 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. mktorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef ALLINONE #include /* exit(), malloc() */ #include /* off_t */ #include /* errno */ #include /* strerror() */ #include /* printf() etc. */ #include /* open() */ #include /* access(), read(), close() */ #ifdef USE_OPENSSL #include /* SHA1() */ #else #include #include "sha1.h" #endif #include /* pthread functions and data structures */ #include "mktorrent.h" #define EXPORT #endif /* ALLINONE */ #ifndef PROGRESS_PERIOD #define PROGRESS_PERIOD 200000 #endif #ifndef O_BINARY #define O_BINARY 0 #endif #if defined _LARGEFILE_SOURCE && defined O_LARGEFILE #define OPENFLAGS (O_RDONLY | O_BINARY | O_LARGEFILE) #else #define OPENFLAGS (O_RDONLY | O_BINARY) #endif struct piece_s; typedef struct piece_s piece_t; struct piece_s { piece_t *next; unsigned char *dest; unsigned long len; unsigned char data[1]; }; struct queue_s; typedef struct queue_s queue_t; struct queue_s { piece_t *free; piece_t *full; unsigned int buffers_max; unsigned int buffers; pthread_mutex_t mutex_free; pthread_mutex_t mutex_full; pthread_cond_t cond_empty; pthread_cond_t cond_full; unsigned int done; unsigned int pieces; unsigned int pieces_hashed; }; static piece_t *get_free(queue_t *q, size_t piece_length) { piece_t *r; pthread_mutex_lock(&q->mutex_free); if (q->free) { r = q->free; q->free = r->next; } else if (q->buffers < q->buffers_max) { r = malloc(sizeof(piece_t) - 1 + piece_length); if (r == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } q->buffers++; } else { while (q->free == NULL) { pthread_cond_wait(&q->cond_full, &q->mutex_free); } r = q->free; q->free = r->next; } pthread_mutex_unlock(&q->mutex_free); return r; } static piece_t *get_full(queue_t *q) { piece_t *r; pthread_mutex_lock(&q->mutex_full); again: if (q->full) { r = q->full; q->full = r->next; } else if (q->done) { r = NULL; } else { pthread_cond_wait(&q->cond_empty, &q->mutex_full); goto again; } pthread_mutex_unlock(&q->mutex_full); return r; } static void put_free(queue_t *q, piece_t *p, unsigned int hashed) { pthread_mutex_lock(&q->mutex_free); p->next = q->free; q->free = p; q->pieces_hashed += hashed; pthread_mutex_unlock(&q->mutex_free); pthread_cond_signal(&q->cond_full); } static void put_full(queue_t *q, piece_t *p) { pthread_mutex_lock(&q->mutex_full); p->next = q->full; q->full = p; pthread_mutex_unlock(&q->mutex_full); pthread_cond_signal(&q->cond_empty); } static void set_done(queue_t *q) { pthread_mutex_lock(&q->mutex_full); q->done = 1; pthread_mutex_unlock(&q->mutex_full); pthread_cond_broadcast(&q->cond_empty); } static void free_buffers(queue_t *q) { piece_t *first = q->free; while (first) { piece_t *p = first; first = p->next; free(p); } q->free = NULL; } /* * print the progress in a thread of its own */ static void *print_progress(void *data) { queue_t *q = data; int err; err = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); if (err) { fprintf(stderr, "Error setting thread cancel type: %s\n", strerror(err)); exit(EXIT_FAILURE); } while (1) { /* print progress and flush the buffer immediately */ printf("\rHashed %u of %u pieces.", q->pieces_hashed, q->pieces); fflush(stdout); /* now sleep for PROGRESS_PERIOD microseconds */ usleep(PROGRESS_PERIOD); } return NULL; } static void *worker(void *data) { queue_t *q = data; piece_t *p; SHA_CTX c; while ((p = get_full(q))) { SHA1_Init(&c); SHA1_Update(&c, p->data, p->len); SHA1_Final(p->dest, &c); put_free(q, p, 1); } return NULL; } static void read_files(metafile_t *m, queue_t *q, unsigned char *pos) { int fd; /* file descriptor */ flist_t *f; /* pointer to a place in the file list */ ssize_t r = 0; /* number of bytes read from file(s) into the read buffer */ #ifndef NO_HASH_CHECK off_t counter = 0; /* number of bytes hashed should match size when done */ #endif piece_t *p = get_free(q, m->piece_length); /* go through all the files in the file list */ for (f = m->file_list; f; f = f->next) { /* open the current file for reading */ if ((fd = open(f->path, OPENFLAGS)) == -1) { fprintf(stderr, "Error opening '%s' for reading: %s\n", f->path, strerror(errno)); exit(EXIT_FAILURE); } while (1) { ssize_t d = read(fd, p->data + r, m->piece_length - r); if (d < 0) { fprintf(stderr, "Error reading from '%s': %s\n", f->path, strerror(errno)); exit(EXIT_FAILURE); } if (d == 0) /* end of file */ break; r += d; if (r == m->piece_length) { p->dest = pos; p->len = m->piece_length; put_full(q, p); pos += SHA_DIGEST_LENGTH; #ifndef NO_HASH_CHECK counter += r; #endif r = 0; p = get_free(q, m->piece_length); } } /* now close the file */ if (close(fd)) { fprintf(stderr, "Error closing '%s': %s\n", f->path, strerror(errno)); exit(EXIT_FAILURE); } } /* finally append the hash of the last irregular piece to the hash string */ if (r) { p->dest = pos; p->len = r; put_full(q, p); } else put_free(q, p, 0); #ifndef NO_HASH_CHECK counter += r; if (counter != m->size) { fprintf(stderr, "Counted %" PRIoff " bytes, " "but hashed %" PRIoff " bytes. " "Something is wrong...\n", m->size, counter); exit(EXIT_FAILURE); } #endif } EXPORT unsigned char *make_hash(metafile_t *m) { queue_t q = { NULL, NULL, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0, 0 }; pthread_t print_progress_thread; /* progress printer thread */ pthread_t *workers; unsigned char *hash_string; /* the hash string */ unsigned int i; int err; workers = malloc(m->threads * sizeof(pthread_t)); hash_string = malloc(m->pieces * SHA_DIGEST_LENGTH); if (workers == NULL || hash_string == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } q.pieces = m->pieces; q.buffers_max = 3*m->threads; /* create worker threads */ for (i = 0; i < m->threads; i++) { err = pthread_create(&workers[i], NULL, worker, &q); if (err) { fprintf(stderr, "Error creating thread: %s\n", strerror(err)); exit(EXIT_FAILURE); } } /* now set off the progress printer */ err = pthread_create(&print_progress_thread, NULL, print_progress, &q); if (err) { fprintf(stderr, "Error creating thread: %s\n", strerror(err)); exit(EXIT_FAILURE); } /* read files and feed pieces to the workers */ read_files(m, &q, hash_string); /* we're done so stop printing our progress. */ err = pthread_cancel(print_progress_thread); if (err) { fprintf(stderr, "Error cancelling thread: %s\n", strerror(err)); exit(EXIT_FAILURE); } /* inform workers we're done */ set_done(&q); /* wait for workers to finish */ for (i = 0; i < m->threads; i++) { err = pthread_join(workers[i], NULL); if (err) { fprintf(stderr, "Error joining thread: %s\n", strerror(err)); exit(EXIT_FAILURE); } } free(workers); /* the progress printer should be done by now too */ err = pthread_join(print_progress_thread, NULL); if (err) { fprintf(stderr, "Error joining thread: %s\n", strerror(err)); exit(EXIT_FAILURE); } /* destroy mutexes and condition variables */ pthread_mutex_destroy(&q.mutex_full); pthread_mutex_destroy(&q.mutex_free); pthread_cond_destroy(&q.cond_empty); pthread_cond_destroy(&q.cond_full); /* free buffers */ free_buffers(&q); /* ok, let the user know we're done too */ printf("\rHashed %u of %u pieces.\n", q.pieces_hashed, q.pieces); return hash_string; } mktorrent-1.1/init.c000066400000000000000000000366621303551775400145360ustar00rootroot00000000000000/* This file is part of mktorrent Copyright (C) 2007, 2009 Emil Renner Berthing mktorrent 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. mktorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef ALLINONE #include /* exit() */ #include /* off_t */ #include /* errno */ #include /* strerror() */ #include /* printf() etc. */ #include /* the stat structure */ #include /* getopt(), getcwd(), sysconf() */ #include /* strcmp(), strlen(), strncpy() */ #ifdef USE_LONG_OPTIONS #include /* getopt_long() */ #endif #include "mktorrent.h" #include "ftw.h" #define EXPORT #endif /* ALLINONE */ #ifndef MAX_OPENFD #define MAX_OPENFD 100 /* Maximum number of file descriptors file_tree_walk() will open */ #endif static void strip_ending_dirseps(char *s) { char *end = s; while (*end) end++; while (end > s && *(--end) == DIRSEP_CHAR) *end = '\0'; } static const char *basename(const char *s) { const char *r = s; while (*s != '\0') { if (*s == DIRSEP_CHAR) r = ++s; else ++s; } return r; } static void set_absolute_file_path(metafile_t *m) { char *string; /* string to return */ size_t length = 32; /* length of the string */ /* if the file_path is already an absolute path just return that */ if (m->metainfo_file_path && *m->metainfo_file_path == DIRSEP_CHAR) return; /* first get the current working directory using getcwd is a bit of a PITA */ /* allocate initial string */ string = malloc(length); if (string == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } /* while our allocated memory for the working dir isn't big enough */ while (getcwd(string, length) == NULL) { /* double the buffer size */ length *= 2; /* free our current buffer */ free(string); /* and allocate a new one twice as big muahaha */ string = malloc(length); if (string == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } } /* now set length to the proper length of the working dir */ length = strlen(string); /* if the metainfo file path isn't set */ if (m->metainfo_file_path == NULL) { /* append .torrent to the working dir */ string = realloc(string, length + strlen(m->torrent_name) + 10); if (string == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } sprintf(string + length, DIRSEP "%s.torrent", m->torrent_name); } else { /* otherwise append the torrent path to the working dir */ string = realloc(string, length + strlen(m->metainfo_file_path) + 2); if (string == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } sprintf(string + length, DIRSEP "%s", m->metainfo_file_path); } m->metainfo_file_path = string; } /* * parse a comma separated list of strings [,]* and * return a string list containing the substrings */ static slist_t *get_slist(char *s) { slist_t *list, *last; char *e; /* allocate memory for the first node in the list */ list = last = malloc(sizeof(slist_t)); if (list == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } /* add URLs to the list while there are commas in the string */ while ((e = strchr(s, ','))) { /* set the commas to \0 so the URLs appear as * separate strings */ *e = '\0'; last->s = s; /* move s to point to the next URL */ s = e + 1; /* append another node to the list */ last->next = malloc(sizeof(slist_t)); last = last->next; if (last == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } } /* set the last string in the list */ last->s = s; last->next = NULL; /* return the list */ return list; } /* * checks if target is a directory * sets the file_list and size if it isn't */ static int is_dir(metafile_t *m, char *target) { struct stat s; /* stat structure for stat() to fill */ /* stat the target */ if (stat(target, &s)) { fprintf(stderr, "Error stat'ing '%s': %s\n", target, strerror(errno)); exit(EXIT_FAILURE); } /* if it is a directory, just return 1 */ if (S_ISDIR(s.st_mode)) return 1; /* if it isn't a regular file either, something is wrong.. */ if (!S_ISREG(s.st_mode)) { fprintf(stderr, "'%s' is neither a directory nor regular file.\n", target); exit(EXIT_FAILURE); } /* since we know the torrent is just a single file and we've already stat'ed it, we might as well set the file list */ m->file_list = malloc(sizeof(flist_t)); if (m->file_list == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } m->file_list->path = target; m->file_list->size = s.st_size; m->file_list->next = NULL; /* ..and size variable */ m->size = s.st_size; /* now return 0 since it isn't a directory */ return 0; } /* * called by file_tree_walk() on every file and directory in the subtree * counts the number of (readable) files, their commulative size and adds * their names and individual sizes to the file list */ static int process_node(const char *path, const struct stat *sb, void *data) { flist_t **p; /* pointer to a node in the file list */ flist_t *new_node; /* place to store a newly created node */ metafile_t *m = data; /* skip non-regular files */ if (!S_ISREG(sb->st_mode)) return 0; /* ignore the leading "./" */ path += 2; /* now path should be readable otherwise * display a warning and skip it */ if (access(path, R_OK)) { fprintf(stderr, "Warning: Cannot read '%s', skipping.\n", path); return 0; } if (m->verbose) printf("Adding %s\n", path); /* count the total size of the files */ m->size += sb->st_size; /* find where to insert the new node so that the file list remains ordered by the path */ p = &m->file_list; while (*p && strcmp(path, (*p)->path) > 0) p = &((*p)->next); /* create a new file list node for the file */ new_node = malloc(sizeof(flist_t)); if (new_node == NULL || (new_node->path = strdup(path)) == NULL) { fprintf(stderr, "Out of memory.\n"); return -1; } new_node->size = sb->st_size; /* now insert the node there */ new_node->next = *p; *p = new_node; /* insertion sort is a really stupid way of sorting a list, but usually a torrent doesn't contain too many files, so we'll probably be alright ;) */ return 0; } /* * 'elp! */ static void print_help() { printf( "Usage: mktorrent [OPTIONS] \n\n" "Options:\n" #ifdef USE_LONG_OPTIONS "-a, --announce=[,]* : specify the full announce URLs\n" " at least one is required\n" " additional -a adds backup trackers\n" "-c, --comment= : add a comment to the metainfo\n" "-d, --no-date : don't write the creation date\n" "-h, --help : show this help screen\n" "-l, --piece-length= : set the piece length to 2^n bytes,\n" " default is 18, that is 2^18 = 256kb\n" "-n, --name= : set the name of the torrent\n" " default is the basename of the target\n" "-o, --output= : set the path and filename of the created file\n" " default is .torrent\n" "-p, --private : set the private flag\n" "-s, --source= : add source string embedded in infohash\n" #ifdef USE_PTHREADS "-t, --threads= : use threads for calculating hashes\n" " default is the number of CPU cores\n" #endif "-v, --verbose : be verbose\n" "-w, --web-seed=[,]* : add web seed URLs\n" " additional -w adds more URLs\n" #else "-a [,]* : specify the full announce URLs\n" " at least one is required\n" " additional -a adds backup trackers\n" "-c : add a comment to the metainfo\n" "-d : don't write the creation date\n" "-h : show this help screen\n" "-l : set the piece length to 2^n bytes,\n" " default is 18, that is 2^18 = 256kb\n" "-n : set the name of the torrent,\n" " default is the basename of the target\n" "-o : set the path and filename of the created file\n" " default is .torrent\n" "-p : set the private flag\n" "-s : add source string embedded in infohash\n" #ifdef USE_PTHREADS "-t : use threads for calculating hashes\n" " default is the number of CPU cores\n" #endif "-v : be verbose\n" "-w [,]* : add web seed URLs\n" " additional -w adds more URLs\n" #endif "\nPlease send bug reports, patches, feature requests, praise and\n" "general gossip about the program to: mktorrent@rudde.org\n"); } /* * print the full announce list */ static void print_announce_list(llist_t *list) { unsigned int n; for (n = 1; list; list = list->next, n++) { slist_t *l = list->l; printf(" %u : %s\n", n, l->s); for (l = l->next; l; l = l->next) printf(" %s\n", l->s); } } /* * print the list of web seed URLs */ static void print_web_seed_list(slist_t *list) { printf(" Web Seed URL: "); if (list == NULL) { printf("none\n"); return; } printf("%s\n", list->s); for (list = list->next; list; list = list->next) printf(" %s\n", list->s); } /* * print out all the options */ static void dump_options(metafile_t *m) { printf("Options:\n" " Announce URLs:\n"); print_announce_list(m->announce_list); printf(" Torrent name: %s\n" " Metafile: %s\n" " Piece length: %u\n" #ifdef USE_PTHREADS " Threads: %u\n" #endif " Be verbose: yes\n", m->torrent_name, m->metainfo_file_path, m->piece_length #ifdef USE_PTHREADS ,m->threads #endif ); printf(" Write date: "); if (m->no_creation_date) printf("no\n"); else printf("yes\n"); print_web_seed_list(m->web_seed_list); /* Print source string only if set */ if (m->source) printf("\n Source: %s\n\n", m->source); printf(" Comment: "); if (m->comment == NULL) printf("none\n\n"); else printf("\"%s\"\n\n", m->comment); } /* * parse and check the command line options given * and fill out the appropriate fields of the * metafile structure */ EXPORT void init(metafile_t *m, int argc, char *argv[]) { int c; /* return value of getopt() */ llist_t *announce_last = NULL; slist_t *web_seed_last = NULL; #ifdef USE_LONG_OPTIONS /* the option structure to pass to getopt_long() */ static struct option long_options[] = { {"announce", 1, NULL, 'a'}, {"comment", 1, NULL, 'c'}, {"no-date", 0, NULL, 'd'}, {"help", 0, NULL, 'h'}, {"piece-length", 1, NULL, 'l'}, {"name", 1, NULL, 'n'}, {"output", 1, NULL, 'o'}, {"private", 0, NULL, 'p'}, {"source", 1, NULL, 's'}, #ifdef USE_PTHREADS {"threads", 1, NULL, 't'}, #endif {"verbose", 0, NULL, 'v'}, {"web-seed", 1, NULL, 'w'}, {NULL, 0, NULL, 0} }; #endif /* now parse the command line options given */ #ifdef USE_PTHREADS #define OPT_STRING "a:c:dhl:n:o:ps:t:vw:" #else #define OPT_STRING "a:c:dhl:n:o:ps:vw:" #endif #ifdef USE_LONG_OPTIONS while ((c = getopt_long(argc, argv, OPT_STRING, long_options, NULL)) != -1) { #else while ((c = getopt(argc, argv, OPT_STRING)) != -1) { #endif #undef OPT_STRING switch (c) { case 'a': if (announce_last == NULL) { m->announce_list = announce_last = malloc(sizeof(llist_t)); } else { announce_last->next = malloc(sizeof(llist_t)); announce_last = announce_last->next; } if (announce_last == NULL) { fprintf(stderr, "Out of memory.\n"); exit(EXIT_FAILURE); } announce_last->l = get_slist(optarg); break; case 'c': m->comment = optarg; break; case 'd': m->no_creation_date = 1; break; case 'h': print_help(); exit(EXIT_SUCCESS); case 'l': m->piece_length = atoi(optarg); break; case 'n': m->torrent_name = optarg; break; case 'o': m->metainfo_file_path = optarg; break; case 'p': m->private = 1; break; case 's': m->source = optarg; break; #ifdef USE_PTHREADS case 't': m->threads = atoi(optarg); break; #endif case 'v': m->verbose = 1; break; case 'w': if (web_seed_last == NULL) { m->web_seed_list = web_seed_last = get_slist(optarg); } else { web_seed_last->next = get_slist(optarg); web_seed_last = web_seed_last->next; } while (web_seed_last->next) web_seed_last = web_seed_last->next; break; case '?': fprintf(stderr, "Use -h for help.\n"); exit(EXIT_FAILURE); } } /* set the correct piece length. default is 2^18 = 256kb. */ if (m->piece_length < 15 || m->piece_length > 28) { fprintf(stderr, "The piece length must be a number between " "15 and 28.\n"); exit(EXIT_FAILURE); } m->piece_length = 1 << m->piece_length; if (announce_last != NULL) announce_last->next = NULL; /* ..and a file or directory from which to create the torrent */ if (optind >= argc) { fprintf(stderr, "Must specify the contents, " "use -h for help\n"); exit(EXIT_FAILURE); } #ifdef USE_PTHREADS /* check the number of threads */ if (m->threads) { if (m->threads > 20) { fprintf(stderr, "The number of threads is limited to " "at most 20\n"); exit(EXIT_FAILURE); } } else { #ifdef _SC_NPROCESSORS_ONLN m->threads = sysconf(_SC_NPROCESSORS_ONLN); if (m->threads == -1) #endif m->threads = 2; /* some sane default */ } #endif /* strip ending DIRSEP's from target */ strip_ending_dirseps(argv[optind]); /* if the torrent name isn't set use the basename of the target */ if (m->torrent_name == NULL) m->torrent_name = basename(argv[optind]); /* make sure m->metainfo_file_path is the absolute path to the file */ set_absolute_file_path(m); /* if we should be verbose print out all the options as we have set them */ if (m->verbose) dump_options(m); /* check if target is a directory or just a single file */ m->target_is_directory = is_dir(m, argv[optind]); if (m->target_is_directory) { /* change to the specified directory */ if (chdir(argv[optind])) { fprintf(stderr, "Error changing directory to '%s': %s\n", argv[optind], strerror(errno)); exit(EXIT_FAILURE); } if (file_tree_walk("." DIRSEP, MAX_OPENFD, process_node, m)) exit(EXIT_FAILURE); } /* calculate the number of pieces pieces = ceil( size / piece_length ) */ m->pieces = (m->size + m->piece_length - 1) / m->piece_length; /* now print the size and piece count if we should be verbose */ if (m->verbose) printf("\n%" PRIoff " bytes in all.\n" "That's %u pieces of %u bytes each.\n\n", m->size, m->pieces, m->piece_length); } mktorrent-1.1/main.c000066400000000000000000000105341303551775400145050ustar00rootroot00000000000000/* This file is part of mktorrent Copyright (C) 2007, 2009 Emil Renner Berthing mktorrent 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. mktorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include /* exit() */ #include /* off_t */ #include /* errno */ #include /* strerror() */ #include /* printf() etc. */ #include /* S_IRUSR, S_IWUSR, S_IRGRP, S_IROTH */ #include /* open() */ #ifdef ALLINONE #include #include /* access(), read(), close(), getcwd(), sysconf() */ #ifdef USE_LONG_OPTIONS #include /* getopt_long() */ #endif #include /* time() */ #include /* opendir(), closedir(), readdir() etc. */ #ifdef USE_OPENSSL #include /* SHA1(), SHA_DIGEST_LENGTH */ #else #include #endif #ifdef USE_PTHREADS #include /* pthread functions and data structures */ #endif #define EXPORT static #else /* ALLINONE */ #define EXPORT #endif /* ALLINONE */ #include "mktorrent.h" #ifdef ALLINONE #include "ftw.c" #include "init.c" #ifndef USE_OPENSSL #include "sha1.c" #endif #ifdef USE_PTHREADS #include "hash_pthreads.c" #else #include "hash.c" #endif #include "output.c" #else /* ALLINONE */ /* init.c */ extern void init(metafile_t *m, int argc, char *argv[]); /* hash.c */ extern unsigned char *make_hash(metafile_t *m); /* output.c */ extern void write_metainfo(FILE *f, metafile_t *m, unsigned char *hash_string); #endif /* ALLINONE */ #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef S_IRGRP #define S_IRGRP 0 #endif #ifndef S_IROTH #define S_IROTH 0 #endif /* * create and open the metainfo file for writing and create a stream for it * we don't want to overwrite anything, so abort if the file is already there */ static FILE *open_file(const char *path) { int fd; /* file descriptor */ FILE *f; /* file stream */ /* open and create the file if it doesn't exist already */ fd = open(path, O_WRONLY | O_BINARY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd < 0) { fprintf(stderr, "Error creating '%s': %s\n", path, strerror(errno)); exit(EXIT_FAILURE); } /* create the stream from this filedescriptor */ f = fdopen(fd, "wb"); if (f == NULL) { fprintf(stderr, "Error creating stream for '%s': %s\n", path, strerror(errno)); exit(EXIT_FAILURE); } return f; } /* * close the metainfo file */ static void close_file(FILE *f) { /* close the metainfo file */ if (fclose(f)) { fprintf(stderr, "Error closing stream: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } /* * main().. it starts */ int main(int argc, char *argv[]) { FILE *file; /* stream for writing to the metainfo file */ metafile_t m = { /* options */ 18, /* piece_length, 2^18 = 256kb by default */ NULL, /* announce_list */ NULL, /* torrent_name */ NULL, /* metainfo_file_path */ NULL, /* web_seed_url */ NULL, /* comment */ 0, /* target_is_directory */ 0, /* no_creation_date */ 0, /* private */ NULL, /* source string */ 0, /* verbose */ #ifdef USE_PTHREADS 0, /* threads, initialised by init() */ #endif /* information calculated by read_dir() */ 0, /* size */ NULL, /* file_list */ 0 /* pieces */ }; /* print who we are */ printf("mktorrent " VERSION " (c) 2007, 2009 Emil Renner Berthing\n\n"); /* process options */ init(&m, argc, argv); /* open the file stream now, so we don't have to abort _after_ we did all the hashing in case we fail */ file = open_file(m.metainfo_file_path); /* calculate hash string and write the metainfo to file */ write_metainfo(file, &m, make_hash(&m)); /* close the file stream */ close_file(file); /* yeih! everything seemed to go as planned */ return EXIT_SUCCESS; } mktorrent-1.1/mktorrent.h000066400000000000000000000030071303551775400156100ustar00rootroot00000000000000#ifndef _MKTORRENT_H #define _MKTORRENT_H #ifdef _WIN32 #define DIRSEP "\\" #define DIRSEP_CHAR '\\' #else #define DIRSEP "/" #define DIRSEP_CHAR '/' #endif /* string list */ struct slist_s; typedef struct slist_s slist_t; struct slist_s { char *s; slist_t *next; }; /* list of string lists */ struct llist_s; typedef struct llist_s llist_t; struct llist_s { slist_t *l; llist_t *next; }; /* file list */ struct flist_s; typedef struct flist_s flist_t; struct flist_s { char *path; off_t size; flist_t *next; }; typedef struct { /* options */ unsigned int piece_length; /* piece length */ llist_t *announce_list; /* announce URLs */ char *comment; /* optional comment */ const char *torrent_name; /* name of torrent (name of directory) */ char *metainfo_file_path; /* absolute path to the metainfo file */ slist_t *web_seed_list; /* web seed URLs */ int target_is_directory; /* target is a directory */ int no_creation_date; /* don't write the creation date */ int private; /* set the private flag */ char *source; /* set source for private trackers */ int verbose; /* be verbose */ #ifdef USE_PTHREADS unsigned int threads; /* number of threads used for hashing */ #endif /* information calculated by read_dir() */ off_t size; /* combined size of all files */ flist_t *file_list; /* list of files and their sizes */ unsigned int pieces; /* number of pieces */ } metafile_t; #endif /* _MKTORRENT_H */ mktorrent-1.1/output.c000066400000000000000000000127001303551775400151160ustar00rootroot00000000000000/* This file is part of mktorrent Copyright (C) 2007, 2009 Emil Renner Berthing mktorrent 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. mktorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef ALLINONE #include /* off_t */ #include /* printf() etc. */ #include /* strlen() etc. */ #include /* time() */ #ifdef USE_OPENSSL #include /* SHA_DIGEST_LENGTH */ #else #include #include "sha1.h" #endif #include "mktorrent.h" #define EXPORT #endif /* ALLINONE */ /* * write announce list */ static void write_announce_list(FILE *f, llist_t *list) { /* the announce list is a list of lists of urls */ fprintf(f, "13:announce-listl"); /* go through them all.. */ for (; list; list = list->next) { slist_t *l; /* .. and print the lists */ fprintf(f, "l"); for (l = list->l; l; l = l->next) fprintf(f, "%lu:%s", (unsigned long)strlen(l->s), l->s); fprintf(f, "e"); } fprintf(f, "e"); } /* * write file list */ static void write_file_list(FILE *f, flist_t *list) { char *a, *b; fprintf(f, "5:filesl"); /* go through all the files */ for (; list; list = list->next) { /* the file list contains a dictionary for every file with entries for the length and path write the length first */ fprintf(f, "d6:lengthi%" PRIoff "e4:pathl", list->size); /* the file path is written as a list of subdirectories and the last entry is the filename sorry this code is even uglier than the rest */ a = list->path; /* while there are subdirectories before the filename.. */ while ((b = strchr(a, DIRSEP_CHAR)) != NULL) { /* set the next DIRSEP_CHAR to '\0' so fprintf will only write the first subdirectory name */ *b = '\0'; /* print it bencoded */ fprintf(f, "%lu:%s", (unsigned long)strlen(a), a); /* undo our alteration to the string */ *b = DIRSEP_CHAR; /* and move a to the beginning of the next subdir or filename */ a = b + 1; } /* now print the filename bencoded and end the path name list and file dictionary */ fprintf(f, "%lu:%see", (unsigned long)strlen(a), a); } /* whew, now end the file list */ fprintf(f, "e"); } /* * write web seed list */ static void write_web_seed_list(FILE *f, slist_t *list) { /* print the entry and start the list */ fprintf(f, "8:url-listl"); /* go through the list and write each URL */ for (; list; list = list->next) fprintf(f, "%lu:%s", (unsigned long)strlen(list->s), list->s); /* end the list */ fprintf(f, "e"); } /* * write metainfo to the file stream using all the information * we've gathered so far and the hash string calculated */ EXPORT void write_metainfo(FILE *f, metafile_t *m, unsigned char *hash_string) { /* let the user know we've started writing the metainfo file */ printf("Writing metainfo file... "); fflush(stdout); /* every metainfo file is one big dictonary */ fprintf(f, "d"); if (m->announce_list != NULL) { /* write the announce URL */ fprintf(f, "8:announce%lu:%s", (unsigned long)strlen(m->announce_list->l->s), m->announce_list->l->s); /* write the announce-list entry if we have more than one announce URL */ if (m->announce_list->next || m->announce_list->l->next) write_announce_list(f, m->announce_list); } /* add the comment if one is specified */ if (m->comment != NULL) fprintf(f, "7:comment%lu:%s", (unsigned long)strlen(m->comment), m->comment); /* I made this! */ fprintf(f, "10:created by13:mktorrent " VERSION); /* add the creation date */ if (!m->no_creation_date) fprintf(f, "13:creation datei%lde", (long)time(NULL)); /* now here comes the info section it is yet another dictionary */ fprintf(f, "4:infod"); /* first entry is either 'length', which specifies the length of a single file torrent, or a list of files and their respective sizes */ if (!m->target_is_directory) fprintf(f, "6:lengthi%" PRIoff "e", m->file_list->size); else write_file_list(f, m->file_list); /* the info section also contains the name of the torrent, the piece length and the hash string */ fprintf(f, "4:name%lu:%s12:piece lengthi%ue6:pieces%u:", (unsigned long)strlen(m->torrent_name), m->torrent_name, m->piece_length, m->pieces * SHA_DIGEST_LENGTH); fwrite(hash_string, 1, m->pieces * SHA_DIGEST_LENGTH, f); /* set the private flag */ if (m->private) fprintf(f, "7:privatei1e"); if (m->source) fprintf(f, "6:source%lu:%s", (unsigned long)strlen(m->source), m->source); /* end the info section */ fprintf(f, "e"); /* add url-list if one is specified */ if (m->web_seed_list != NULL) { if (m->web_seed_list->next == NULL) fprintf(f, "8:url-list%lu:%s", (unsigned long)strlen(m->web_seed_list->s), m->web_seed_list->s); else write_web_seed_list(f, m->web_seed_list); } /* end the root dictionary */ fprintf(f, "e"); /* let the user know we're done already */ printf("done.\n"); fflush(stdout); } mktorrent-1.1/prefix.c000066400000000000000000000027071303551775400150610ustar00rootroot00000000000000/* This file is part of mktorrent Copyright (C) 2009 Emil Renner Berthing mktorrent 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. mktorrent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include #include #include #ifndef TYPE #define TYPE off_t #endif int main(int argc, char *argv[]) { unsigned int i; char *prefix[9]; for (i = 0; i < 9; i++) prefix[i] = NULL; prefix[1] = "hh"; prefix[2] = "h"; prefix[8] = "ll"; prefix[sizeof(int)] = ""; prefix[sizeof(long int)] = "l"; #ifdef DEBUG #define xstr(s) str(s) #define str(s) #s #ifdef _LARGEFILE_SOURCE printf("_LARGEFILE_SOURCE is set\n"); #endif #ifdef _FILE_OFFSET_BITS printf("_FILE_OFFSET_BITS = %lu\n", _FILE_OFFSET_BITS); #endif printf("sizeof(" xstr(TYPE) ") = %lu, %lu bits\n", sizeof(TYPE), 8*sizeof(TYPE)); #endif /* DEBUG */ printf("%s\n", prefix[sizeof(TYPE)]); return EXIT_SUCCESS; } mktorrent-1.1/rules.mk000066400000000000000000000026231303551775400151000ustar00rootroot00000000000000# This file is part of mktorrent # Copyright (C) 2007, 2009 Emil Renner Berthing # # mktorrent 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. # # mktorrent is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA .PHONY: strip indent clean install uninstall prefix: prefix.c $(CC) $(CFLAGS) $(DEFINES) $(LDFLAGS) $< -o $@ $(program): $(OBJS) $(CC) $(CFLAGS) $(OBJS) -o $(program) $(LDFLAGS) $(LIBS) allinone: $(SRCS) $(HEADERS) prefix $(CC) $(CFLAGS) $(DEFINES) -DPRIoff="\"`./prefix`d\"" -DVERSION="\"$(version)\"" -DALLINONE main.c -o $(program) $(LDFLAGS) $(LIBS) strip: strip $(program) indent: indent -kr -i8 *.c *.h clean: rm -f $(program) prefix *.o *.c~ *.h~ install: $(program) $(INSTALL) -d $(DESTDIR)$(PREFIX)/bin $(INSTALL) -m755 $(program) $(DESTDIR)$(PREFIX)/bin/$(program) uninstall: rm -f $(DESTDIR)$(PREFIX)/bin/$(program) mktorrent-1.1/sha1.c000066400000000000000000000202531303551775400144140ustar00rootroot00000000000000/* * SHA-1 in C * By Steve Reid * 100% Public Domain * * Modifications by * James H. Brown * Saul Kravitz * Ralph Giles * Emil Renner Berthing * Still 100% Public Domain */ /* #define SHA1_TEST */ /* #define SHA1_HANDSOFF */ /* #define SHA1_WIPE_VARS */ /* #define SHA1_VERBOSE */ #ifndef ALLINONE #ifdef SHA1_TEST #include #endif #include #include #define EXPORT #endif /* ALLINONE */ #include "sha1.h" #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* blk0() and blk() perform the initial expand. */ /* I got the idea of expanding during the round function from SSLeay */ /* FIXME: can we do this in an endian-proof way? */ #ifdef WORDS_BIGENDIAN #define blk0(i) block->l[i] #else #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ |(rol(block->l[i],8)&0x00FF00FF)) #endif #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ ^block->l[(i+2)&15]^block->l[i&15],1)) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); #ifdef SHA1_VERBOSE static void SHAPrintContext(SHA_CTX *context, char *msg){ printf("%s (%d,%d) %x %x %x %x %x\n", msg, context->count[0], context->count[1], context->state[0], context->state[1], context->state[2], context->state[3], context->state[4]); } #endif /* SHA1_VERBOSE */ /* Hash a single 512-bit block. This is the core of the algorithm. */ static void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64]) { uint32_t a, b, c, d, e; typedef union { uint8_t c[64]; uint32_t l[16]; } CHAR64LONG16; CHAR64LONG16 *block; #ifdef SHA1_HANDSOFF static uint8_t workspace[64]; block = (CHAR64LONG16 *)workspace; memcpy(block, buffer, 64); #else block = (CHAR64LONG16 *)buffer; #endif /* Copy context->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; #ifdef SHA1_WIPE_VARS a = b = c = d = e = 0; #endif } /* SHA1Init - Initialize new context */ EXPORT void SHA1_Init(SHA_CTX *context) { /* SHA1 initialization constants */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } /* Run your data through this. */ EXPORT void SHA1_Update(SHA_CTX *context, const uint8_t *data, unsigned long len) { size_t i, j; #ifdef SHA1_VERBOSE SHAPrintContext(context, "before"); #endif j = (context->count[0] >> 3) & 63; if ((context->count[0] += len << 3) < (len << 3)) context->count[1]++; context->count[1] += (len >> 29); if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64-j)); SHA1_Transform(context->state, context->buffer); for ( ; i + 63 < len; i += 64) { SHA1_Transform(context->state, data + i); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); #ifdef SHA1_VERBOSE SHAPrintContext(context, "after "); #endif } /* Add padding and return the message digest. */ EXPORT void SHA1_Final(uint8_t *digest, SHA_CTX *context) { uint32_t i; uint8_t finalcount[8]; for (i = 0; i < 8; i++) { /* Endian independent */ finalcount[i] = (uint8_t) ((context->count[(i >= 4 ? 0 : 1)] >> ((3-(i & 3)) * 8)) & 255); } SHA1_Update(context, (uint8_t *)"\200", 1); while ((context->count[0] & 504) != 448) { SHA1_Update(context, (uint8_t *)"\0", 1); } SHA1_Update(context, finalcount, 8); /* Should cause a SHA1_Transform() */ for (i = 0; i < SHA_DIGEST_LENGTH; i++) { digest[i] = (uint8_t) ((context->state[i>>2] >> ((3-(i & 3)) * 8)) & 255); } #ifdef SHA1_WIPE_VARS i = 0; memset(context->buffer, 0, 64); memset(context->state, 0, 20); memset(context->count, 0, 8); memset(finalcount, 0, 8); #endif #ifdef SHA1_HANDSOFF /* make SHA1Transform overwrite its own static vars */ SHA1_Transform(context->state, context->buffer); #endif } /*************************************************************\ * Self Test * \*************************************************************/ #ifdef SHA1_TEST /* Test Vectors (from FIPS PUB 180-1) "abc" A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 A million repetitions of "a" 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F */ static char *test_data[] = { "abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "A million repetitions of 'a'"}; static char *test_results[] = { "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D", "84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1", "34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F"}; void digest_to_hex(const uint8_t *digest, char *output) { int i,j; char *c = output; for (i = 0; i < SHA_DIGEST_LENGTH/4; i++) { for (j = 0; j < 4; j++) { sprintf(c,"%02X", digest[i*4+j]); c += 2; } sprintf(c, " "); c += 1; } *(c - 1) = '\0'; } int main(int argc, char *argv[]) { int k; SHA_CTX context; uint8_t digest[SHA_DIGEST_LENGTH]; char output[80]; fprintf(stdout, "Verifying SHA-1 implementation... "); fflush(stdout); for (k = 0; k < 2; k++){ SHA1_Init(&context); SHA1_Update(&context, (uint8_t *)test_data[k], strlen(test_data[k])); SHA1_Final(digest, &context); digest_to_hex(digest, output); if (strcmp(output, test_results[k])) { fprintf(stdout, "FAIL\n"); fprintf(stderr,"* hash of \"%s\" incorrect:\n", test_data[k]); fprintf(stderr,"\t%s returned\n", output); fprintf(stderr,"\t%s is correct\n", test_results[k]); return 1; } } /* The million 'a' vector we feed separately */ SHA1_Init(&context); for (k = 0; k < 1000000; k++) SHA1_Update(&context, (uint8_t *)"a", 1); SHA1_Final(digest, &context); digest_to_hex(digest, output); if (strcmp(output, test_results[2])) { fprintf(stdout, "FAIL\n"); fprintf(stderr,"* hash of \"%s\" incorrect:\n", test_data[2]); fprintf(stderr,"\t%s returned\n", output); fprintf(stderr,"\t%s is correct\n", test_results[2]); return 1; } /* success */ fprintf(stdout, "OK\n"); fflush(stdout); return 0; } #endif /* SHA1_TEST */ mktorrent-1.1/sha1.h000066400000000000000000000007441303551775400144240ustar00rootroot00000000000000/* Public API for Steve Reid's public domain SHA-1 implementation */ /* This file is in the public domain */ #ifndef __SHA1_H #define __SHA1_H typedef struct { uint32_t state[5]; uint32_t count[2]; uint8_t buffer[64]; } SHA_CTX; #define SHA_DIGEST_LENGTH 20 #ifndef ALLINONE void SHA1_Init(SHA_CTX *context); void SHA1_Update(SHA_CTX *context, const uint8_t *data, unsigned long len); void SHA1_Final(uint8_t *digest, SHA_CTX *context); #endif #endif /* __SHA1_H */