pax_global_header00006660000000000000000000000064123627431710014520gustar00rootroot0000000000000052 comment=07e5fae5a93a0265ae9cf0d8651aa5fa47bc1e0a apt-transport-tor-0.2.1/000077500000000000000000000000001236274317100151405ustar00rootroot00000000000000apt-transport-tor-0.2.1/COPYING000066400000000000000000000432541236274317100162030ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. apt-transport-tor-0.2.1/Makefile.am000066400000000000000000000004751236274317100172020ustar00rootroot00000000000000# Avoiding $(libdir) because Debian does not put it under /usr/lib methodsdir = $(prefix)/lib/apt/methods methods_PROGRAMS = tor tor_SOURCES = tor.cc tor.h server.cc server.h apti18n.h install-data-hook: cd $(DESTDIR)$(methodsdir) && \ $(LN_S) tor tor+https && \ $(LN_S) tor tor+http EXTRA_DIST = README.md apt-transport-tor-0.2.1/README.md000066400000000000000000000067021236274317100164240ustar00rootroot00000000000000# apt-transport-tor Easily install Debian packages via Tor. This package implements an APT "acquire method" that handles URLs starting with "tor+http://" or "tor+https://" in your sources.list. ## Installation ### Via apt This package will soon be available in Debian: apt-get install apt-transport-tor ### From source If you are working from a git checkout, first run: autoreconf -i Then, or if installing from a tarball: ./configure --prefix=/usr make sudo make install ## Usage Edit your /etc/apt/sources.list like so, adjusting the suite/components appropriately for your system: deb tor+http://http.debian.net/debian unstable main deb-src tor+http://http.debian.net/debian unstable main Note the use of http.debian.net so that a mirror close to your exit node will be automatically chosen. Alternatively, if you have the Tor hidden service address of a Debian mirror, you can use that: deb tor+http://.onion/debian unstable main deb-src tor+http://.onion/debian unstable main ## Configuration Most users should not need to adjust SOCKS settings. By default, apt-transport-tor uses the following SOCKS proxy setting, which matches the default Tor SOCKS port: socks5h://apt:apt@localhost:9050 If you want to use a different port, you can edit the Acquire::tor::proxy apt preference: Acquire::tor::proxy "socks5h://apt:apt@localhost:9050"; Note the use of a username/password to make use of the default IsolateSOCKSAuth Tor setting for stream isolation, which requires bug fixes from Tor 0.2.4.19 to work well. This means your apt traffic will be sent over a different circuit from your regular Tor traffic. Although "sock5h://" is put explicitly in these examples, at the moment its use is hardcoded (to avoid DNS leaks). ## Caveats Downloading your Debian packages over Tor prevents an attacker who is sniffing your network connection from being able to tell which packages you are fetching, or even that your traffic is Debian-related. However, this does not necessarily defend you from, amongst other things: * a global passive adversary (who could potentially correlate the exit node's traffic with your local Tor traffic) * an attacker looking at the size of your downloads, and making an educated guess about the contents * an attacker who has broken into your machine Download speeds will be slower via Tor. ## Copyright & Licensing Copyright (C) 2014 Tim Retout apt-transport-tor was forked from the APT https transport. APT has this copyright notice: Apt is copyright 1997, 1998, 1999 Jason Gunthorpe and others. License: 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. ## Feedback Comments and suggestions to: Tim Retout Bug reports should be sent to the Debian BTS. apt-transport-tor-0.2.1/TODO000066400000000000000000000001711236274317100156270ustar00rootroot00000000000000TODO ==== - Fix i18n properly - Steal some tests from apt - Look at support.cc - can libcurl do more parsing than this? apt-transport-tor-0.2.1/apti18n.h000066400000000000000000000015531236274317100166010ustar00rootroot00000000000000/* include/apti18n.h. Generated from apti18n.h.in by configure. */ // -*- mode: cpp; mode: fold -*- // $Id: apti18n.h.in,v 1.6 2003/01/11 07:18:18 jgg Exp $ /* Internationalization macros for apt. This header should be included last in each C file. */ // Set by autoconf #define USE_NLS 1 #ifdef USE_NLS // apt will use the gettext implementation of the C library #include #include # ifdef APT_DOMAIN # define _(x) dgettext(APT_DOMAIN,x) # define P_(msg,plural,n) dngettext(APT_DOMAIN,msg,plural,n) # else # define _(x) gettext(x) # define P_(msg,plural,n) ngettext(msg,plural,n) # endif # define N_(x) x #else // apt will not use any gettext # define setlocale(a, b) # define textdomain(a) # define bindtextdomain(a, b) # define _(x) x # define P_(msg,plural,n) (n == 1 ? msg : plural) # define N_(x) x # define dgettext(d, m) m #endif apt-transport-tor-0.2.1/configure.ac000066400000000000000000000004131236274317100174240ustar00rootroot00000000000000AC_INIT([apt-transport-tor], [0.2.1], [diocles@debian.org]) AM_INIT_AUTOMAKE([-Wall -Werror foreign]) AC_PROG_CXX AC_PROG_LN_S AC_CONFIG_HEADERS([config.h]) AC_CHECK_LIB([apt-pkg], [main]) AC_CHECK_LIB([curl], [curl_version]) AC_CONFIG_FILES([ Makefile ]) AC_OUTPUT apt-transport-tor-0.2.1/server.cc000066400000000000000000000411531236274317100167610ustar00rootroot00000000000000// -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### HTTP and HTTPS share a lot of common code and these classes are exactly the dumping ground for this common code ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "server.h" #include /*}}}*/ using namespace std; string ServerMethod::FailFile; int ServerMethod::FailFd = -1; time_t ServerMethod::FailTime = 0; // ServerState::RunHeaders - Get the headers before the data /*{{{*/ // --------------------------------------------------------------------- /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header parse error occurred */ ServerState::RunHeadersResult ServerState::RunHeaders(FileFd * const File) { State = Header; Owner->Status(_("Waiting for headers")); Major = 0; Minor = 0; Result = 0; Size = 0; StartPos = 0; Encoding = Closes; HaveContent = false; time(&Date); do { string Data; if (ReadHeaderLines(Data) == false) continue; if (Owner->Debug == true) clog << Data; for (string::const_iterator I = Data.begin(); I < Data.end(); ++I) { string::const_iterator J = I; for (; J != Data.end() && *J != '\n' && *J != '\r'; ++J); if (HeaderLine(string(I,J)) == false) return RUN_HEADERS_PARSE_ERROR; I = J; } // 100 Continue is a Nop... if (Result == 100) continue; // Tidy up the connection persistence state. if (Encoding == Closes && HaveContent == true) Persistent = false; return RUN_HEADERS_OK; } while (LoadNextResponse(false, File) == true); return RUN_HEADERS_IO_ERROR; } /*}}}*/ // ServerState::HeaderLine - Process a header line /*{{{*/ // --------------------------------------------------------------------- /* */ bool ServerState::HeaderLine(string Line) { if (Line.empty() == true) return true; string::size_type Pos = Line.find(' '); if (Pos == string::npos || Pos+1 > Line.length()) { // Blah, some servers use "connection:closes", evil. Pos = Line.find(':'); if (Pos == string::npos || Pos + 2 > Line.length()) return _error->Error(_("Bad header line")); Pos++; } // Parse off any trailing spaces between the : and the next word. string::size_type Pos2 = Pos; while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0) Pos2++; string Tag = string(Line,0,Pos); string Val = string(Line,Pos2); if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0) { // Evil servers return no version if (Line[4] == '/') { int const elements = sscanf(Line.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major,&Minor,&Result,Code); if (elements == 3) { Code[0] = '\0'; if (Owner->Debug == true) clog << "HTTP server doesn't give Reason-Phrase for " << Result << std::endl; } else if (elements != 4) return _error->Error(_("The HTTP server sent an invalid reply header")); } else { Major = 0; Minor = 9; if (sscanf(Line.c_str(),"HTTP %3u%359[^\n]",&Result,Code) != 2) return _error->Error(_("The HTTP server sent an invalid reply header")); } /* Check the HTTP response header to get the default persistence state. */ if (Major < 1) Persistent = false; else { if (Major == 1 && Minor == 0) Persistent = false; else Persistent = true; } return true; } if (stringcasecmp(Tag,"Content-Length:") == 0) { if (Encoding == Closes) Encoding = Stream; HaveContent = true; // The length is already set from the Content-Range header if (StartPos != 0) return true; Size = strtoull(Val.c_str(), NULL, 10); if (Size >= std::numeric_limits::max()) return _error->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header")); else if (Size == 0) HaveContent = false; return true; } if (stringcasecmp(Tag,"Content-Type:") == 0) { HaveContent = true; return true; } if (stringcasecmp(Tag,"Content-Range:") == 0) { HaveContent = true; // ยง14.16 says 'byte-range-resp-spec' should be a '*' in case of 416 if (Result == 416 && sscanf(Val.c_str(), "bytes */%llu",&Size) == 1) { StartPos = 1; // ignore Content-Length, it would override Size HaveContent = false; } else if (sscanf(Val.c_str(),"bytes %llu-%*u/%llu",&StartPos,&Size) != 2) return _error->Error(_("The HTTP server sent an invalid Content-Range header")); if ((unsigned long long)StartPos > Size) return _error->Error(_("This HTTP server has broken range support")); return true; } if (stringcasecmp(Tag,"Transfer-Encoding:") == 0) { HaveContent = true; if (stringcasecmp(Val,"chunked") == 0) Encoding = Chunked; return true; } if (stringcasecmp(Tag,"Connection:") == 0) { if (stringcasecmp(Val,"close") == 0) Persistent = false; if (stringcasecmp(Val,"keep-alive") == 0) Persistent = true; return true; } if (stringcasecmp(Tag,"Last-Modified:") == 0) { if (RFC1123StrToTime(Val.c_str(), Date) == false) return _error->Error(_("Unknown date format")); return true; } if (stringcasecmp(Tag,"Location:") == 0) { Location = Val; return true; } return true; } /*}}}*/ // ServerState::ServerState - Constructor /*{{{*/ ServerState::ServerState(URI Srv, ServerMethod *Owner) : ServerName(Srv), TimeOut(120), Owner(Owner) { Reset(); } /*}}}*/ bool ServerMethod::Configuration(string Message) /*{{{*/ { return pkgAcqMethod::Configuration(Message); } /*}}}*/ // ServerMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/ // --------------------------------------------------------------------- /* We look at the header data we got back from the server and decide what to do. Returns DealWithHeadersResult (see http.h for details). */ ServerMethod::DealWithHeadersResult ServerMethod::DealWithHeaders(FetchResult &Res) { // Not Modified if (Server->Result == 304) { unlink(Queue->DestFile.c_str()); Res.IMSHit = true; Res.LastModified = Queue->LastModified; return IMS_HIT; } /* Redirect * * Note that it is only OK for us to treat all redirection the same * because we *always* use GET, not other HTTP methods. There are * three redirection codes for which it is not appropriate that we * redirect. Pass on those codes so the error handling kicks in. */ if (AllowRedirect && (Server->Result > 300 && Server->Result < 400) && (Server->Result != 300 // Multiple Choices && Server->Result != 304 // Not Modified && Server->Result != 306)) // (Not part of HTTP/1.1, reserved) { if (Server->Location.empty() == true); else if (Server->Location[0] == '/' && Queue->Uri.empty() == false) { URI Uri = Queue->Uri; if (Uri.Host.empty() == false) NextURI = URI::SiteOnly(Uri); else NextURI.clear(); NextURI.append(DeQuoteString(Server->Location)); return TRY_AGAIN_OR_REDIRECT; } else { NextURI = DeQuoteString(Server->Location); URI tmpURI = NextURI; URI Uri = Queue->Uri; // same protocol redirects are okay if (tmpURI.Access == Uri.Access) return TRY_AGAIN_OR_REDIRECT; // as well as http to https else if (Uri.Access == "http" && tmpURI.Access == "https") return TRY_AGAIN_OR_REDIRECT; } /* else pass through for error message */ } // retry after an invalid range response without partial data else if (Server->Result == 416) { struct stat SBuf; if (stat(Queue->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0) { if ((unsigned long long)SBuf.st_size == Server->Size) { // the file is completely downloaded, but was not moved Server->StartPos = Server->Size; Server->Result = 200; Server->HaveContent = false; } else if (unlink(Queue->DestFile.c_str()) == 0) { NextURI = Queue->Uri; return TRY_AGAIN_OR_REDIRECT; } } } /* We have a reply we dont handle. This should indicate a perm server failure */ if (Server->Result < 200 || Server->Result >= 300) { char err[255]; snprintf(err,sizeof(err)-1,"HttpError%i",Server->Result); SetFailReason(err); _error->Error("%u %s",Server->Result,Server->Code); if (Server->HaveContent == true) return ERROR_WITH_CONTENT_PAGE; return ERROR_UNRECOVERABLE; } // This is some sort of 2xx 'data follows' reply Res.LastModified = Server->Date; Res.Size = Server->Size; // Open the file delete File; File = new FileFd(Queue->DestFile,FileFd::WriteAny); if (_error->PendingError() == true) return ERROR_NOT_FROM_SERVER; FailFile = Queue->DestFile; FailFile.c_str(); // Make sure we dont do a malloc in the signal handler FailFd = File->Fd(); FailTime = Server->Date; if (Server->InitHashes(*File) == false) { _error->Errno("read",_("Problem hashing file")); return ERROR_NOT_FROM_SERVER; } if (Server->StartPos > 0) Res.ResumePoint = Server->StartPos; SetNonBlock(File->Fd(),true); return FILE_IS_OPEN; } /*}}}*/ // ServerMethod::SigTerm - Handle a fatal signal /*{{{*/ // --------------------------------------------------------------------- /* This closes and timestamps the open file. This is necessary to get resume behavoir on user abort */ void ServerMethod::SigTerm(int) { if (FailFd == -1) _exit(100); struct timeval times[2]; times[0].tv_sec = FailTime; times[1].tv_sec = FailTime; times[0].tv_usec = times[1].tv_usec = 0; utimes(FailFile.c_str(), times); close(FailFd); _exit(100); } /*}}}*/ // ServerMethod::Fetch - Fetch an item /*{{{*/ // --------------------------------------------------------------------- /* This adds an item to the pipeline. We keep the pipeline at a fixed depth. */ bool ServerMethod::Fetch(FetchItem *) { if (Server == 0) return true; // Queue the requests int Depth = -1; for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth; I = I->Next, Depth++) { // If pipelining is disabled, we only queue 1 request if (Server->Pipeline == false && Depth >= 0) break; // Make sure we stick with the same server if (Server->Comp(I->Uri) == false) break; if (QueueBack == I) { QueueBack = I->Next; SendReq(I); continue; } } return true; } /*}}}*/ // ServerMethod::Loop - Main loop /*{{{*/ int ServerMethod::Loop() { typedef vector StringVector; typedef vector::iterator StringVectorIterator; map Redirected; signal(SIGTERM,SigTerm); signal(SIGINT,SigTerm); Server = 0; int FailCounter = 0; while (1) { // We have no commands, wait for some to arrive if (Queue == 0) { if (WaitFd(STDIN_FILENO) == false) return 0; } /* Run messages, we can accept 0 (no message) if we didn't do a WaitFd above.. Otherwise the FD is closed. */ int Result = Run(true); if (Result != -1 && (Result != 0 || Queue == 0)) { if(FailReason.empty() == false || _config->FindB("Acquire::http::DependOnSTDIN", true) == true) return 100; else return 0; } if (Queue == 0) continue; // Connect to the server if (Server == 0 || Server->Comp(Queue->Uri) == false) { delete Server; Server = CreateServerState(Queue->Uri); } /* If the server has explicitly said this is the last connection then we pre-emptively shut down the pipeline and tear down the connection. This will speed up HTTP/1.0 servers a tad since we don't have to wait for the close sequence to complete */ if (Server->Persistent == false) Server->Close(); // Reset the pipeline if (Server->IsOpen() == false) QueueBack = Queue; // Connnect to the host if (Server->Open() == false) { Fail(true); delete Server; Server = 0; continue; } // Fill the pipeline. Fetch(0); // Fetch the next URL header data from the server. switch (Server->RunHeaders(File)) { case ServerState::RUN_HEADERS_OK: break; // The header data is bad case ServerState::RUN_HEADERS_PARSE_ERROR: { _error->Error(_("Bad header data")); Fail(true); RotateDNS(); continue; } // The server closed a connection during the header get.. default: case ServerState::RUN_HEADERS_IO_ERROR: { FailCounter++; _error->Discard(); Server->Close(); Server->Pipeline = false; if (FailCounter >= 2) { Fail(_("Connection failed"),true); FailCounter = 0; } RotateDNS(); continue; } }; // Decide what to do. FetchResult Res; Res.Filename = Queue->DestFile; switch (DealWithHeaders(Res)) { // Ok, the file is Open case FILE_IS_OPEN: { URIStart(Res); // Run the data bool Result = true; if (Server->HaveContent) Result = Server->RunData(File); /* If the server is sending back sizeless responses then fill in the size now */ if (Res.Size == 0) Res.Size = File->Size(); // Close the file, destroy the FD object and timestamp it FailFd = -1; delete File; File = 0; // Timestamp struct timeval times[2]; times[0].tv_sec = times[1].tv_sec = Server->Date; times[0].tv_usec = times[1].tv_usec = 0; utimes(Queue->DestFile.c_str(), times); // Send status to APT if (Result == true) { Res.TakeHashes(*Server->GetHashes()); URIDone(Res); } else { if (Server->IsOpen() == false) { FailCounter++; _error->Discard(); Server->Close(); if (FailCounter >= 2) { Fail(_("Connection failed"),true); FailCounter = 0; } QueueBack = Queue; } else Fail(true); } break; } // IMS hit case IMS_HIT: { URIDone(Res); break; } // Hard server error, not found or something case ERROR_UNRECOVERABLE: { Fail(); break; } // Hard internal error, kill the connection and fail case ERROR_NOT_FROM_SERVER: { delete File; File = 0; Fail(); RotateDNS(); Server->Close(); break; } // We need to flush the data, the header is like a 404 w/ error text case ERROR_WITH_CONTENT_PAGE: { Fail(); // Send to content to dev/null File = new FileFd("/dev/null",FileFd::WriteExists); Server->RunData(File); delete File; File = 0; break; } // Try again with a new URL case TRY_AGAIN_OR_REDIRECT: { // Clear rest of response if there is content if (Server->HaveContent) { File = new FileFd("/dev/null",FileFd::WriteExists); Server->RunData(File); delete File; File = 0; } /* Detect redirect loops. No more redirects are allowed after the same URI is seen twice in a queue item. */ StringVector &R = Redirected[Queue->DestFile]; bool StopRedirects = false; if (R.empty() == true) R.push_back(Queue->Uri); else if (R[0] == "STOP" || R.size() > 10) StopRedirects = true; else { for (StringVectorIterator I = R.begin(); I != R.end(); ++I) if (Queue->Uri == *I) { R[0] = "STOP"; break; } R.push_back(Queue->Uri); } if (StopRedirects == false) Redirect(NextURI); else Fail(); break; } default: Fail(_("Internal error")); break; } FailCounter = 0; } return 0; } /*}}}*/ apt-transport-tor-0.2.1/server.h000066400000000000000000000102741236274317100166230ustar00rootroot00000000000000// -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### Classes dealing with the abstraction of talking to a end via a text protocol like HTTP (which is used by the http and https methods) ##################################################################### */ /*}}}*/ #ifndef APT_SERVER_H #define APT_SERVER_H #include #include #include #include #include using std::cout; using std::endl; class Hashes; class ServerMethod; class FileFd; struct ServerState { // This is the last parsed Header Line unsigned int Major; unsigned int Minor; unsigned int Result; char Code[360]; // These are some statistics from the last parsed header lines unsigned long long Size; unsigned long long StartPos; time_t Date; bool HaveContent; enum {Chunked,Stream,Closes} Encoding; enum {Header, Data} State; bool Persistent; std::string Location; // This is a Persistent attribute of the server itself. bool Pipeline; URI ServerName; URI Proxy; unsigned long TimeOut; protected: ServerMethod *Owner; virtual bool ReadHeaderLines(std::string &Data) = 0; virtual bool LoadNextResponse(bool const ToFile, FileFd * const File) = 0; public: bool HeaderLine(std::string Line); /** \brief Result of the header acquire */ enum RunHeadersResult { /** \brief Header ok */ RUN_HEADERS_OK, /** \brief IO error while retrieving */ RUN_HEADERS_IO_ERROR, /** \brief Parse error after retrieving */ RUN_HEADERS_PARSE_ERROR }; /** \brief Get the headers before the data */ RunHeadersResult RunHeaders(FileFd * const File); bool Comp(URI Other) const {return Other.Host == ServerName.Host && Other.Port == ServerName.Port;}; virtual void Reset() {Major = 0; Minor = 0; Result = 0; Code[0] = '\0'; Size = 0; StartPos = 0; Encoding = Closes; time(&Date); HaveContent = false; State = Header; Persistent = false; Pipeline = true;}; virtual bool WriteResponse(std::string const &Data) = 0; /** \brief Transfer the data from the socket */ virtual bool RunData(FileFd * const File) = 0; virtual bool Open() = 0; virtual bool IsOpen() = 0; virtual bool Close() = 0; virtual bool InitHashes(FileFd &File) = 0; virtual Hashes * GetHashes() = 0; virtual bool Die(FileFd &File) = 0; virtual bool Flush(FileFd * const File) = 0; virtual bool Go(bool ToFile, FileFd * const File) = 0; ServerState(URI Srv, ServerMethod *Owner); virtual ~ServerState() {}; }; class ServerMethod : public pkgAcqMethod { protected: virtual bool Fetch(FetchItem *); ServerState *Server; std::string NextURI; FileFd *File; unsigned long PipelineDepth; bool AllowRedirect; public: bool Debug; /** \brief Result of the header parsing */ enum DealWithHeadersResult { /** \brief The file is open and ready */ FILE_IS_OPEN, /** \brief We got a IMS hit, the file has not changed */ IMS_HIT, /** \brief The server reported a unrecoverable error */ ERROR_UNRECOVERABLE, /** \brief The server reported a error with a error content page */ ERROR_WITH_CONTENT_PAGE, /** \brief An error on the client side */ ERROR_NOT_FROM_SERVER, /** \brief A redirect or retry request */ TRY_AGAIN_OR_REDIRECT }; /** \brief Handle the retrieved header data */ DealWithHeadersResult DealWithHeaders(FetchResult &Res); // In the event of a fatal signal this file will be closed and timestamped. static std::string FailFile; static int FailFd; static time_t FailTime; static APT_NORETURN void SigTerm(int); virtual bool Configuration(std::string Message); virtual bool Flush() { return Server->Flush(File); }; int Loop(); virtual void SendReq(FetchItem *Itm) = 0; virtual ServerState * CreateServerState(URI uri) = 0; virtual void RotateDNS() = 0; ServerMethod(const char *Ver,unsigned long Flags = 0) : pkgAcqMethod(Ver, Flags), Server(NULL), File(NULL), PipelineDepth(0), AllowRedirect(false), Debug(false) {}; virtual ~ServerMethod() {}; }; #endif apt-transport-tor-0.2.1/tor.cc000066400000000000000000000343521236274317100162620ustar00rootroot00000000000000//-*- mode: cpp; mode: fold -*- // Description /*{{{*/ // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $ /* ###################################################################### Tor Acquire Method - This is the Tor acquire method for APT. It uses libcurl ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ #include "config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "tor.h" #include /*}}}*/ using namespace std; size_t TorMethod::parse_header(void *buffer, size_t size, size_t nmemb, void *userp) { size_t len = size * nmemb; TorMethod *me = (TorMethod *)userp; std::string line((char*) buffer, len); for (--len; len > 0; --len) if (isspace(line[len]) == 0) { ++len; break; } line.erase(len); if (line.empty() == true) { if (me->Server->Result != 416 && me->Server->StartPos != 0) ; else if (me->Server->Result == 416 && me->Server->Size == me->File->FileSize()) { me->Server->Result = 200; me->Server->StartPos = me->Server->Size; } else me->Server->StartPos = 0; me->File->Truncate(me->Server->StartPos); me->File->Seek(me->Server->StartPos); } else if (me->Server->HeaderLine(line) == false) return 0; return size*nmemb; } size_t TorMethod::write_data(void *buffer, size_t size, size_t nmemb, void *userp) { TorMethod *me = (TorMethod *)userp; if (me->Res.Size == 0) me->URIStart(me->Res); if(me->File->Write(buffer, size*nmemb) != true) return false; return size*nmemb; } int TorMethod::progress_callback(void *clientp, double dltotal, double /*dlnow*/, double /*ultotal*/, double /*ulnow*/) { TorMethod *me = (TorMethod *)clientp; if(dltotal > 0 && me->Res.Size == 0) { me->Res.Size = (unsigned long long)dltotal; } return 0; } // TorServerState::TorServerState - Constructor /*{{{*/ TorServerState::TorServerState(URI Srv,TorMethod * /*Owner*/) : ServerState(Srv, NULL) { TimeOut = _config->FindI("Acquire::tor::Timeout",TimeOut); Reset(); } /*}}}*/ void TorMethod::SetupProxy() /*{{{*/ { URI ServerName = Queue->Uri; // Curl should never read proxy settings from the environment, as // we determine which proxy to use. Do this for consistency among // methods and prevent an environment variable overriding a // no-proxy ("DIRECT") setting in apt.conf. curl_easy_setopt(curl, CURLOPT_PROXY, ""); // Determine the proxy setting string UseProxy = _config->Find("Acquire::tor::Proxy", _config->Find("Acquire::tor::Proxy").c_str()); if (UseProxy.empty() == true) { // Default proxy // - socks5h (actually ignored below) - use proxy for DNS resolution // - apt:apt@ - dummy socks authentication (for IsolateSOCKSAuth in Tor) // - localhost:9050 - default Tor SOCKS port UseProxy = "socks5h://apt:apt@localhost:9050"; } // Determine what host and port to use based on the proxy settings Proxy = UseProxy; if (Proxy.Port != 1) curl_easy_setopt(curl, CURLOPT_PROXYPORT, Proxy.Port); curl_easy_setopt(curl, CURLOPT_PROXY, Proxy.Host.c_str()); if (Proxy.User.empty() == false || Proxy.Password.empty() == false) { curl_easy_setopt(curl, CURLOPT_PROXYUSERNAME, Proxy.User.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYPASSWORD, Proxy.Password.c_str()); } // Set proxy type to SOCKS5, and let proxy do DNS resolution curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); } /*}}}*/ // TorMethod::Fetch - Fetch an item /*{{{*/ // --------------------------------------------------------------------- /* This adds an item to the pipeline. We keep the pipeline at a fixed depth. */ bool TorMethod::Fetch(FetchItem *Itm) { struct stat SBuf; struct curl_slist *headers=NULL; char curl_errorstr[CURL_ERROR_SIZE]; URI Uri = Itm->Uri; string remotehost = Uri.Host; // Undo any "tor" or "tor+" at the start string prefix="tor+"; if ("tor" == Uri.Access) { Uri.Access = "http"; } else if (!Uri.Access.compare(0, prefix.size(), prefix)) { Uri.Access = Uri.Access.substr(prefix.size()); } // TODO: // - http::Pipeline-Depth // - error checking/reporting // - more debug options? (CURLOPT_DEBUGFUNCTION?) curl_easy_reset(curl); SetupProxy(); maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc")); // callbacks curl_easy_setopt(curl, CURLOPT_URL, static_cast(Uri).c_str()); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, parse_header); curl_easy_setopt(curl, CURLOPT_WRITEHEADER, this); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this); // options curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); curl_easy_setopt(curl, CURLOPT_FILETIME, true); // Allow curl to handle just the protocols we want curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); // SSL parameters are set by default to the common (non mirror-specific) value // if available (or a default one) and gets overload by mirror-specific ones. // File containing the list of trusted CA. string cainfo = _config->Find("Acquire::https::CaInfo",""); string knob = "Acquire::https::"+remotehost+"::CaInfo"; cainfo = _config->Find(knob.c_str(),cainfo.c_str()); if(cainfo.empty() == false) curl_easy_setopt(curl, CURLOPT_CAINFO,cainfo.c_str()); // Check server certificate against previous CA list ... bool peer_verify = _config->FindB("Acquire::https::Verify-Peer",true); knob = "Acquire::https::" + remotehost + "::Verify-Peer"; peer_verify = _config->FindB(knob.c_str(), peer_verify); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, peer_verify); // ... and hostname against cert CN or subjectAltName bool verify = _config->FindB("Acquire::https::Verify-Host",true); knob = "Acquire::https::"+remotehost+"::Verify-Host"; verify = _config->FindB(knob.c_str(),verify); int const default_verify = (verify == true) ? 2 : 0; curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, default_verify); // Also enforce issuer of server certificate using its cert string issuercert = _config->Find("Acquire::https::IssuerCert",""); knob = "Acquire::https::"+remotehost+"::IssuerCert"; issuercert = _config->Find(knob.c_str(),issuercert.c_str()); if(issuercert.empty() == false) curl_easy_setopt(curl, CURLOPT_ISSUERCERT,issuercert.c_str()); // For client authentication, certificate file ... string pem = _config->Find("Acquire::https::SslCert",""); knob = "Acquire::https::"+remotehost+"::SslCert"; pem = _config->Find(knob.c_str(),pem.c_str()); if(pem.empty() == false) curl_easy_setopt(curl, CURLOPT_SSLCERT, pem.c_str()); // ... and associated key. string key = _config->Find("Acquire::https::SslKey",""); knob = "Acquire::https::"+remotehost+"::SslKey"; key = _config->Find(knob.c_str(),key.c_str()); if(key.empty() == false) curl_easy_setopt(curl, CURLOPT_SSLKEY, key.c_str()); // Allow forcing SSL version to SSLv3 or TLSv1 (SSLv2 is not // supported by GnuTLS). long final_version = CURL_SSLVERSION_DEFAULT; string sslversion = _config->Find("Acquire::https::SslForceVersion",""); knob = "Acquire::https::"+remotehost+"::SslForceVersion"; sslversion = _config->Find(knob.c_str(),sslversion.c_str()); if(sslversion == "TLSv1") final_version = CURL_SSLVERSION_TLSv1; else if(sslversion == "SSLv3") final_version = CURL_SSLVERSION_SSLv3; curl_easy_setopt(curl, CURLOPT_SSLVERSION, final_version); // CRL file string crlfile = _config->Find("Acquire::https::CrlFile",""); knob = "Acquire::https::"+remotehost+"::CrlFile"; crlfile = _config->Find(knob.c_str(),crlfile.c_str()); if(crlfile.empty() == false) curl_easy_setopt(curl, CURLOPT_CRLFILE, crlfile.c_str()); // cache-control if(_config->FindB("Acquire::tor::No-Cache", _config->FindB("Acquire::http::No-Cache",false)) == false) { // cache enabled if (_config->FindB("Acquire::tor::No-Store", _config->FindB("Acquire::http::No-Store",false)) == true) headers = curl_slist_append(headers,"Cache-Control: no-store"); stringstream ss; ioprintf(ss, "Cache-Control: max-age=%u", _config->FindI("Acquire::tor::Max-Age", _config->FindI("Acquire::http::Max-Age",0))); headers = curl_slist_append(headers, ss.str().c_str()); } else { // cache disabled by user headers = curl_slist_append(headers, "Cache-Control: no-cache"); headers = curl_slist_append(headers, "Pragma: no-cache"); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // speed limit int const dlLimit = _config->FindI("Acquire::tor::Dl-Limit", _config->FindI("Acquire::http::Dl-Limit",0))*1024; if (dlLimit > 0) curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, dlLimit); // set header // Hardcoded so that all apt-transport-tor users look the same. curl_easy_setopt(curl, CURLOPT_USERAGENT, "Debian APT-CURL/1.0 (0.1)"); // set timeout int const timeout = _config->FindI("Acquire::tor::Timeout", _config->FindI("Acquire::http::Timeout",120)); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout); //set really low lowspeed timeout (see #497983) curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, DL_MIN_SPEED); curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, timeout); // set redirect options and default to 10 redirects bool const AllowRedirect = _config->FindB("Acquire::tor::AllowRedirect", _config->FindB("Acquire::http::AllowRedirect",true)); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, AllowRedirect); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10); // debug if(_config->FindB("Debug::Acquire::tor", false)) curl_easy_setopt(curl, CURLOPT_VERBOSE, true); // error handling curl_errorstr[0] = '\0'; curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr); // If we ask for uncompressed files servers might respond with content- // negotiation which lets us end up with compressed files we do not support, // see 657029, 657560 and co, so if we have no extension on the request // ask for text only. As a sidenote: If there is nothing to negotate servers // seem to be nice and ignore it. if (_config->FindB("Acquire::tor::SendAccept", _config->FindB("Acquire::http::SendAccept", true)) == true) { size_t const filepos = Itm->Uri.find_last_of('/'); string const file = Itm->Uri.substr(filepos + 1); if (flExtension(file) == file) headers = curl_slist_append(headers, "Accept: text/*"); } // if we have the file send an if-range query with a range header if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0) { char Buf[1000]; sprintf(Buf, "Range: bytes=%li-", (long) SBuf.st_size); headers = curl_slist_append(headers, Buf); sprintf(Buf, "If-Range: %s", TimeRFC1123(SBuf.st_mtime).c_str()); headers = curl_slist_append(headers, Buf); } else if(Itm->LastModified > 0) { curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); curl_easy_setopt(curl, CURLOPT_TIMEVALUE, Itm->LastModified); } // go for it - if the file exists, append on it File = new FileFd(Itm->DestFile, FileFd::WriteAny); Server = new TorServerState(Itm->Uri, this); // keep apt updated Res.Filename = Itm->DestFile; // get it! CURLcode success = curl_easy_perform(curl); // If the server returns 200 OK but the If-Modified-Since condition is not // met, CURLINFO_CONDITION_UNMET will be set to 1 long curl_condition_unmet = 0; curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &curl_condition_unmet); File->Close(); curl_slist_free_all(headers); // cleanup if (success != 0) { _error->Error("%s", curl_errorstr); unlink(File->Name().c_str()); return false; } // server says file not modified if (Server->Result == 304 || curl_condition_unmet == 1) { unlink(File->Name().c_str()); Res.IMSHit = true; Res.LastModified = Itm->LastModified; Res.Size = 0; URIDone(Res); return true; } Res.IMSHit = false; if (Server->Result != 200 && // OK Server->Result != 206 && // Partial Server->Result != 416) // invalid Range { char err[255]; snprintf(err, sizeof(err) - 1, "HttpError%i", Server->Result); SetFailReason(err); _error->Error("%s", err); // unlink, no need keep 401/404 page content in partial/ unlink(File->Name().c_str()); return false; } struct stat resultStat; if (unlikely(stat(File->Name().c_str(), &resultStat) != 0)) { _error->Errno("stat", "Unable to access file %s", File->Name().c_str()); return false; } Res.Size = resultStat.st_size; // invalid range-request if (Server->Result == 416) { unlink(File->Name().c_str()); Res.Size = 0; delete File; Redirect(Itm->Uri); return true; } // Timestamp curl_easy_getinfo(curl, CURLINFO_FILETIME, &Res.LastModified); if (Res.LastModified != -1) { struct timeval times[2]; times[0].tv_sec = Res.LastModified; times[1].tv_sec = Res.LastModified; times[0].tv_usec = times[1].tv_usec = 0; utimes(File->Name().c_str(), times); } else Res.LastModified = resultStat.st_mtime; // take hashes Hashes Hash; FileFd Fd(Res.Filename, FileFd::ReadOnly); Hash.AddFD(Fd); Res.TakeHashes(Hash); // keep apt updated URIDone(Res); // cleanup Res.Size = 0; delete File; return true; } int main() { setlocale(LC_ALL, ""); TorMethod Mth; curl_global_init(CURL_GLOBAL_SSL) ; return Mth.Run(); } apt-transport-tor-0.2.1/tor.h000066400000000000000000000046311236274317100161210ustar00rootroot00000000000000// -*- mode: cpp; mode: fold -*- // Description /*{{{*/// $Id: http.h,v 1.12 2002/04/18 05:09:38 jgg Exp $ // $Id: http.h,v 1.12 2002/04/18 05:09:38 jgg Exp $ /* ###################################################################### HTTP Acquire Method - This is the HTTP acquire method for APT. ##################################################################### */ /*}}}*/ #ifndef APT_TOR_H #define APT_TOR_H #include #include #include #include #include #include "server.h" using std::cout; using std::endl; class Hashes; class TorMethod; class FileFd; class TorServerState : public ServerState { protected: virtual bool ReadHeaderLines(std::string &/*Data*/) { return false; } virtual bool LoadNextResponse(bool const /*ToFile*/, FileFd * const /*File*/) { return false; } public: virtual bool WriteResponse(std::string const &/*Data*/) { return false; } /** \brief Transfer the data from the socket */ virtual bool RunData(FileFd * const /*File*/) { return false; } virtual bool Open() { return false; } virtual bool IsOpen() { return false; } virtual bool Close() { return false; } virtual bool InitHashes(FileFd &/*File*/) { return false; } virtual Hashes * GetHashes() { return NULL; } virtual bool Die(FileFd &/*File*/) { return false; } virtual bool Flush(FileFd * const /*File*/) { return false; } virtual bool Go(bool /*ToFile*/, FileFd * const /*File*/) { return false; } TorServerState(URI Srv, TorMethod *Owner); virtual ~TorServerState() {Close();}; }; class TorMethod : public pkgAcqMethod { // minimum speed in bytes/se that triggers download timeout handling static const int DL_MIN_SPEED = 10; virtual bool Fetch(FetchItem *); static size_t parse_header(void *buffer, size_t size, size_t nmemb, void *userp); static size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp); static int progress_callback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); void SetupProxy(); CURL *curl; FetchResult Res; TorServerState *Server; public: FileFd *File; TorMethod() : pkgAcqMethod("1.2",Pipeline | SendConfig), File(NULL) { File = 0; curl = curl_easy_init(); }; ~TorMethod() { curl_easy_cleanup(curl); }; }; #include URI Proxy; #endif