[
  {
    "path": ".gitignore",
    "content": "proxychains4\nproxychains4-daemon\n*.bz2\n*.xz\n*.o\n*.so\n*.la\n*.lo\n.deps/\n.libs/\n*.rcb\n*.out\n*~\n*.patch\nversion.h\n\n# Autoconf stuff \nlibtool\nconfig.*\nstamp-h\n"
  },
  {
    "path": "AUTHORS",
    "content": "original code up to version 3.1\nN3E7CR34TUR3.\nhttp://proxychains.sourceforge.net\nnetcreature@users.sourceforge.net\n\nmain.c, remote-dns, thread safety, bugfixes, build system, \ncleanups, mac support\nrofl0r.\nhttps://github.com/rofl0r/proxychains-ng\n\nlocalnet, bugfixes\njianing yang.\nhttps://github.com/jianingy/proxychains\nhttps://sourceforge.net/projects/proxychains/forums/forum/644747/topic/3498696\n\nround-robin\ncrass.\nhttps://github.com/crass/proxychains-ng\n\npoll_retry (fixes for signal handling)\ncolin cross.\nhttps://sourceforge.net/projects/proxychains/forums/forum/644747/topic/2367923\n\ncollecting patches from px forum and putting it into a repo\nadam hamsik.\nhttps://github.com/haad/proxychains\n\n"
  },
  {
    "path": "COPYING",
    "content": "\t\t    GNU GENERAL PUBLIC LICENSE\n\t\t       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n\t\t\t    Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Library General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\f\n\t\t    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\f\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\f\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\f\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n\t\t\t    NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n\t\t     END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "Makefile",
    "content": "#\n# Makefile for proxychains (requires GNU make), stolen from musl\n#\n# Use config.mak to override any of the following variables.\n# Do not make changes here.\n#\n\nexec_prefix = /usr/local\nbindir = $(exec_prefix)/bin\n\nprefix = /usr/local/\nincludedir = $(prefix)/include\nlibdir = $(prefix)/lib\nsysconfdir = $(prefix)/etc\nzshcompletiondir = $(prefix)/share/zsh/site-functions\n\nOBJS = src/common.o src/main.o\n\nDOBJS = src/daemon/hsearch.o \\\n        src/daemon/sblist.o src/daemon/sblist_delete.o \\\n        src/daemon/daemon.o src/daemon/udpserver.o\n\nLOBJS = src/version.o \\\n        src/core.o src/common.o src/libproxychains.o \\\n        src/allocator_thread.o src/rdns.o \\\n        src/hostsreader.o src/hash.o src/debug.o\n\n\nGENH = src/version.h\n\nCFLAGS  += -Wall -O0 -g -std=c99 -D_GNU_SOURCE -pipe\nNO_AS_NEEDED = -Wl,--no-as-needed\nLDFLAGS = -fPIC $(NO_AS_NEEDED) $(LIBDL) $(PTHREAD)\nINC     = \nPIC     = -fPIC\nAR      = $(CROSS_COMPILE)ar\nRANLIB  = $(CROSS_COMPILE)ranlib\nSOCKET_LIBS =\n\nLDSO_SUFFIX = so\nLD_SET_SONAME = -Wl,-soname=\nINSTALL = ./tools/install.sh\n\nLDSO_PATHNAME = libproxychains4.$(LDSO_SUFFIX)\n\nSHARED_LIBS = $(LDSO_PATHNAME)\nALL_LIBS = $(SHARED_LIBS)\nPXCHAINS = proxychains4\nPXCHAINS_D = proxychains4-daemon\nALL_TOOLS = $(PXCHAINS) $(PXCHAINS_D)\nALL_CONFIGS = src/proxychains.conf\nZSH_COMPLETION = completions/zsh/_proxychains4\n\n-include config.mak\n\nCFLAGS+=$(USER_CFLAGS) $(MAC_CFLAGS)\nCFLAGS_MAIN=-DLIB_DIR=\\\"$(libdir)\\\" -DSYSCONFDIR=\\\"$(sysconfdir)\\\" -DDLL_NAME=\\\"$(LDSO_PATHNAME)\\\"\n\n\nall: $(ALL_LIBS) $(ALL_TOOLS)\n\ninstall: install-libs install-tools\n\n$(DESTDIR)$(bindir)/%: %\n\t$(INSTALL) -D -m 755 $< $@\n\n$(DESTDIR)$(libdir)/%: %\n\t$(INSTALL) -D -m 644 $< $@\n\n$(DESTDIR)$(sysconfdir)/%: src/%\n\t$(INSTALL) -D -m 644 $< $@\n\n$(DESTDIR)$(zshcompletiondir)/%: completions/zsh/%\n\t$(INSTALL) -D -m 644 $< $@\n\ninstall-libs: $(ALL_LIBS:%=$(DESTDIR)$(libdir)/%)\ninstall-tools: $(ALL_TOOLS:%=$(DESTDIR)$(bindir)/%)\ninstall-config: $(ALL_CONFIGS:src/%=$(DESTDIR)$(sysconfdir)/%)\ninstall-zsh-completion: $(ZSH_COMPLETION:completions/zsh/%=$(DESTDIR)$(zshcompletiondir)/%)\n\nclean:\n\trm -f $(ALL_LIBS)\n\trm -f $(ALL_TOOLS)\n\trm -f $(OBJS) $(LOBJS) $(DOBJS)\n\trm -f $(GENH)\n\nsrc/version.h: $(wildcard VERSION .git)\n\tprintf '#define VERSION \"%s\"\\n' \"$$(sh tools/version.sh)\" > $@\n\nsrc/version.o: src/version.h\n\n%.o: %.c\n\t$(CC) $(CPPFLAGS) $(CFLAGS) $(CFLAGS_MAIN) $(INC) $(PIC) -c -o $@ $<\n\n$(LDSO_PATHNAME): $(LOBJS)\n\t$(CC) $(LDFLAGS) $(FAT_LDFLAGS) $(LD_SET_SONAME)$(LDSO_PATHNAME) \\\n\t\t$(USER_LDFLAGS) -shared -o $@ $^ $(SOCKET_LIBS)\n\n$(PXCHAINS): $(OBJS)\n\t$(CC) $^ $(FAT_BIN_LDFLAGS) $(USER_LDFLAGS) $(LIBDL) -o $@\n\n$(PXCHAINS_D): $(DOBJS)\n\t$(CC) $^ $(FAT_BIN_LDFLAGS) $(USER_LDFLAGS) -o $@\n\n\n.PHONY: all clean install install-config install-libs install-tools install-zsh-completion\n"
  },
  {
    "path": "README",
    "content": "ProxyChains-NG ver 4.17 README\n=============================\n\n  ProxyChains is a UNIX program, that hooks network-related libc functions\n  in DYNAMICALLY LINKED programs via a preloaded DLL (dlsym(), LD_PRELOAD)\n  and redirects the connections through SOCKS4a/5 or HTTP proxies.\n  It supports TCP only (no UDP/ICMP etc).\n\n  The way it works is basically a HACK; so it is possible that it doesn't\n  work with your program, especially when it's a script, or starts\n  numerous processes like background daemons or uses dlopen() to load\n  \"modules\" (bug in glibc dynlinker).\n  It should work with simple compiled (C/C++) dynamically linked programs\n  though.\n\n  If your program doesn't work with proxychains, consider using an\n  iptables based solution instead; this is much more robust.\n\n  Supported Platforms: Linux, BSD, Mac, Haiku.\n\n\n*********** ATTENTION ***********\n\n  this program can be used to circumvent censorship.\n  doing so can be VERY DANGEROUS in certain countries.\n\n  ALWAYS MAKE SURE THAT PROXYCHAINS WORKS AS EXPECTED\n  BEFORE USING IT FOR ANYTHING SERIOUS.\n\n  this involves both the program and the proxy that you're going to\n  use.\n\n  for example, you can connect to some \"what is my ip\" service\n  like ifconfig.me to make sure that it's not using your real ip.\n\n  ONLY USE PROXYCHAINS IF YOU KNOW WHAT YOU'RE DOING.\n\n  THE AUTHORS AND MAINTAINERS OF PROXYCHAINS DO NOT TAKE ANY\n  RESPONSIBILITY FOR ANY ABUSE OR MISUSE OF THIS SOFTWARE AND\n  THE RESULTING CONSEQUENCES.\n\n*** Installation ***\n\n  # needs a working C compiler, preferably gcc\n  ./configure --prefix=/usr --sysconfdir=/etc\n  make\n  [optional] sudo make install\n  [optional] sudo make install-config (installs proxychains.conf)\n\n  if you dont install, you can use proxychains from the build directory\n  like this: ./proxychains4 -f src/proxychains.conf telnet google.com 80\n\nChangelog:\n----------\nVersion 4.17\n- add hook for close_range function, fixing newer versions of openssh\n- fat-binary-m1 option for mac\n- fix DNS error handling in proxy_dns_old\n- simplify init code\n- fix openbsd preloading\n- fix double-close in multithreaded apps\n- various improvements to configure script\n\nVersion 4.16\n- fix regression in configure script linker flag detection\n- remove 10 year old workaround for wrong glibc getnameinfo signature\n- support for new DYLD hooking method for OSX Monterey\n- netbsd compilation fix\n- support IPv6 localnets\n- more user-friendly error message when execvp fails\n- proxy_getaddrinfo(): fill in ai_socktype if requested\n\nVersion 4.15\n- fix configure script for buggy binutils version\n- initialize rand_seed with nano-second granularity\n- add support for numeric ipv6 in getaddrinfo\n- fix bug in getaddrinfo when node is null and !passive\n- add dnat feature\n- add raw proxy type\n- add haiku support\n- add proxy_dns_old to emulate proxychains 3.1 behaviour\n- add new proxy_dns_daemon feature (experimental)\n- various other fixes\n\nVersion 4.14\n- allow alternative proto://user:pass@ip:port syntax for proxylist\n- fix endless loop in round robin mode when all proxies are down (#147)\n- fix compilation on android (#265)\n- fix fd leak in forked processes (#273)\n- skip connection attempt to nullrouted ips\n- allow hostnames for proxylist under specific circumstances\n\nVersion 4.13\n- fix robustness of DNS lookup thread and a segfault\n- fix socks5 user/pass auth on non-conforming servers\n- fix memory leak\n- add support for Solaris\n\nVersion 4.12\n- fix several build issues\n  - for MAC\n  - with -pie\n  - with custom CC\n- compatibility fix for some GUI apps (8870140)\n- compatibility fix for some HTTP proxies (cf9a16d)\n- fix several warnings for cleaner build on debian\n- fix random_chain on OSX (0f6b226)\n\nVersion 4.11\n- preliminary IPv6 support\n- fixed bug in hostsreader\n- preliminary support for usage on OpenBSD (caveat emptor)\n\nVersion 4.10\n- fix regression in linking order with custom LDFLAGS\n- fix segfault in DNS mapping code in programs with > ~400 different lookups\n\nVersion 4.9\n- fix a security issue CVE-2015-3887\n- add sendto hook to handle MSG_FASTOPEN flag\n- replace problematic hostentdb with hostsreader\n- fix compilation on OpenBSD (although doesn't work there)\n\nVersion 4.8.1:\n- fix regression in 4.8 install-config Makefile target\n\nVersion 4.8:\n- fix for odd cornercase where getaddrinfo was used with AI_NUMERICHOST\n  to test for a numeric ip instead of resolving it (fixes nmap).\n- allow usage with programs that rely on LD_PRELOAD themselves\n- reject wrong entries in config file\n- print version number on startup\n\nVersion 4.7:\n- new round_robin chaintype by crass.\n- fix bug with lazy allocation when GCC constructor was not used.\n- new configure flag --fat-binary to create a \"fat\" binary/library on OS X\n- return EBADF rather than EINTR in close hook.\n  it's legal for a program to retry close() calls when they receive\n  EINTR, which could cause an infinite loop, as seen in chromium.\n\nVersion 4.6:\n- some cosmetic fixes to Makefile, fix a bug when non-numeric ip was\n  used as proxy server address.\n\nVersion 4.5:\n- hook close() to prevent OpenSSH from messing with internal infrastructure.\n  this caused ssh client to segfault when proxified.\n\nVersion 4.4:\n- FreeBSD port\n- fixes some installation issues on Debian and Mac.\n\nVersion 4.3:\n- fixes programs that do dns-lookups in child processes (fork()ed),\n  like irssi. to achieve this, support for compilation without pthreads\n  was sacrified.\n- fixes thread safety for gethostent() calls.\n- improved DNS handling speed, since hostent db is cached.\n\nVersion 4.2:\n- fixes compilation issues with ubuntu 12.04 toolchain\n- fixes segfault in rare codepath\n\nVersion 4.1\n- support for mac os x (all archs)\n- all internal functions are threadsafe when compiled with -DTHREAD_SAFE\n  (default).\n\nVersion 4.0\n- replaced dnsresolver script (which required a dynamically linked \"dig\"\n  binary to be present) with remote DNS lookup.\n  this speeds up any operation involving DNS, as the old script had to use TCP.\n  additionally it allows to use .onion urls when used with TOR.\n- removed broken autoconf build system with a simple Makefile.\n  there's a ./configure script though for convenience.\n  it also adds support for a config file passed via command line switches/\n  environment variables.\n\nVersion 3.0\n- support for DNS resolving through proxy\n  supports SOCKS4, SOCKS5 and HTTP CONNECT proxy servers.\n  Auth-types: socks - \"user/pass\" , http - \"basic\".\n\nWhen to use it ?\n1) When the only way to get \"outside\" from your LAN is through proxy server.\n2) To get out from behind restrictive firewall which filters outgoing ports.\n3) To use two (or more) proxies in chain:\n\tlike: your_host <--> proxy1 <--> proxy2 <--> target_host\n4) To \"proxify\" some program with no proxy support built-in (like telnet)\n5) Access intranet from outside via proxy.\n6) To use DNS behind proxy.\n7) To access hidden tor onion services.\n\nSome cool features:\n\n* This program can mix different proxy types in the same chain\n\tlike: your_host <-->socks5 <--> http <--> socks4 <--> target_host\n* Different chaining options supported\n\trandom order from the list ( user defined length of chain ).\n\texact order  (as they appear in the list )\n\tdynamic order (smart exclude dead proxies from chain)\n* You can use it with most TCP client applications, possibly even network\n\tscanners, as long as they use standard libc functionality.\n\tpcap based scanning does not work.\n* You can use it with servers, like squid, sendmail, or whatever.\n* DNS resolving through proxy.\n\n\nConfiguration:\n--------------\n\nproxychains looks for config file in following order:\n1)\tfile listed in environment variable PROXYCHAINS_CONF_FILE or\n\tprovided as a -f argument to proxychains script or binary.\n2)\t./proxychains.conf\n3)\t$(HOME)/.proxychains/proxychains.conf\n4)\t$(sysconfdir)/proxychains.conf  **\n\n** usually /etc/proxychains.conf\n\nUsage Example:\n\n\t$ proxychains telnet targethost.com\n\nin this example it will run telnet through proxy(or chained proxies)\nspecified by proxychains.conf\n\nUsage Example:\n\n\t$ proxychains -f /etc/proxychains-other.conf telnet targethost2.com\n\nin this example it will use different configuration file then proxychains.conf\nto connect to targethost2.com host.\n\nUsage Example:\n\n\t$ proxyresolv targethost.com\n\nin this example it will resolve targethost.com through proxy(or chained proxies)\nspecified by proxychains.conf\n\nKnown Problems:\n---------------\n- newer versions of nmap try to determine the network interface to use\n  even if it's not needed (like when doing simple syn scans which use the\n  standard POSIX socket API. this results in errors when proxychains hands\n  out an ip address to a reserved address space.\n  possible workarounds: disable proxy_dns, use a numeric ip, or use nmap's\n  native support for SOCKS proxies.\n\n- Mac OS X 10.11 (El Capitan) ships with a new security feature called SIP\n  that prevents hooking of system apps.\n  workarounds are to partially disable SIP by issuing\n  csrutil enable --without debug in recovery mode,\n  or to copy the system binary into the home directory and run it from there.\n  see github issue #78 for details.\n\n- the glibc dynlinker has a bug or security feature that inhibits dlopen()ed\n  modules from being subject to the same dlsym hooks as installed for the main\n  program. this mainly affects scripting languages such as perl or python\n  that heavily rely on dlopen() for modules written in C to work.\n  there are unconfirmed reports that it works as root though.\n  musl libc is unaffected from the bug.\n\n\nCommunity:\n----------\n#proxychains on irc.libera.chat\n\nDonations:\n----------\nbitcoins donations are welcome - please send to this address:\n1C9LBpuy56veBqw5N33sZMoZW8mwCw3tPh\n\n"
  },
  {
    "path": "TODO",
    "content": "ProxyChains ver 4.0 TODO\n===================\n\n\t\n   hooks for reentrant dns functions, i.e. gethostbyaddr_r\n\n\n"
  },
  {
    "path": "VERSION",
    "content": "4.17\n"
  },
  {
    "path": "completions/zsh/_proxychains4",
    "content": "#compdef proxychains4\n\n_arguments \\\n  '(- : *)--help[More help in README file]' \\\n  '-q[makes proxychains quiet - this overrides the config setting]' \\\n  '-f[allows one to manually specify a configfile to use]: :_files' \\\n  '(-)1: :{_command_names -e}' \\\n  '*:: :_normal'\n"
  },
  {
    "path": "configure",
    "content": "#!/bin/sh\n\nprefix=/usr/local\nOUR_CPPFLAGS=\n\n# Get a temporary filename\nfail() { printf \"%s\\n\" \"$1\" >&2 ; exit 1 ; }\ni=0\nset -C\nwhile : ; do i=$(($i+1))\ntmpc=\"./conf$$-$PPID-$i.c\"\n2>|/dev/null > \"$tmpc\" && break\ntest \"$i\" -gt 50 && fail \"$0: cannot create temporary file $tmpc\"\ndone\nset +C\ntrap 'rm \"$tmpc\"' EXIT INT QUIT TERM HUP\n\ncheck_compile() {\n\tprintf \"checking %s ... \" \"$1\"\n\tprintf \"$3\" > \"$tmpc\"\n\tlocal res=0\n\t$CC $OUR_CPPFLAGS $CPPFLAGS $2 $CFLAGS \"$tmpc\" -o \"$tmpc\".out >/dev/null 2>&1 \\\n\t|| res=1\n\ttest x$res = x0 && \\\n\t{ printf \"yes\\n\" ; test x\"$2\" = x || OUR_CPPFLAGS=\"$OUR_CPPFLAGS $2\" ; } \\\n\t|| printf \"no\\n\"\n\trm -f \"$tmpc\".out\n\treturn $res\n}\n\nget_define() {\n\t$CC $OUR_CPPFLAGS $CPPFLAGS $CFLAGS -dM -E - </dev/null | grep \"$1\"\n}\n\nget_define_stripped() {\n\tlocal output=$(get_define \"$1\")\n\ttest \"$?\" = 0 || return 1\n\tprintf \"%s\\n\" \"$output\" | sed 's/^.* .* //'\n}\n\ncheck_define() {\n\tprintf \"checking whether \\$CC defines %s ... \" \"$1\"\n\tlocal res=1\n\tget_define \"$1\" >/dev/null && res=0\n\ttest x$res = x0 && printf \"yes\\n\" || printf \"no\\n\"\n\treturn $res\n}\n\ncheck_compile_run() {\n\tprintf \"checking %s ... \" \"$1\"\n\tprintf \"$2\" > \"$tmpc\"\n\tlocal res=0\n\t$CC $OUR_CPPFLAGS $CPPFLAGS $CFLAGS \"$tmpc\" -o \"$tmpc\".out >/dev/null 2>&1 \\\n\t|| res=1\n\ttest x$res = x0 && { \"$tmpc\".out || res=1 ; }\n\trm -f \"$tmpc\".out\n\ttest x$res = x0 && printf \"yes\\n\" || printf \"no\\n\"\n\treturn $res\n}\n\ncheck_link_silent() {\n\tprintf \"$2\" > \"$tmpc\"\n\tlocal res=0\n\t$CC $OUR_CPPFLAGS $CPPFLAGS $1 $CFLAGS \"$tmpc\" -o \"$tmpc\".out  >/dev/null 2>&1 || res=1\n\trm -f \"$tmpc\".out\n\treturn $res\n}\n\ncheck_link() {\n\tprintf \"checking %s ... \" \"$1\"\n\tlocal res=0\n\tcheck_link_silent \"$2\" \"$3\" || res=1\n\ttest x$res = x0 && printf \"yes\\n\" || printf \"no\\n\"\n\treturn $res\n}\n\nusage() {\n\techo \"supported arguments\"\n\techo \"--prefix=/path            default: $prefix\"\n\techo \"--exec_prefix=/path       default: $prefix/bin\"\n\techo \"--bindir=/path            default: $prefix/bin\"\n\techo \"--libdir=/path            default: $prefix/lib\"\n\techo \"--includedir=/path        default: $prefix/include\"\n\techo \"--sysconfdir=/path        default: $prefix/etc\"\n\techo \"--ignore-cve              default: no\"\n\techo \"\tif set to yes ignores CVE-2015-3887 and makes it possible\"\n\techo \"\tto preload from current dir (possibly insecure, but handy)\"\n\techo \"--fat-binary : build for both i386 and x86_64 architectures on 64-bit Macs\"\n\techo \"--fat-binary-m1 : build for both arm64e and x86_64 architectures on M1 Macs\"\n\techo \"--fat-binary-m2 : build for arm64, arm64e and x86_64 architectures on M2+ Macs\"\n\techo \"--hookmethod=dlsym|dyld   hook method for osx. default: auto\"\n\techo \"  if OSX >= 12 is detected, dyld method will be used if auto.\"\n\techo \"--help : show this text\"\n\texit 1\n}\n\nspliteq() {\n\targ=$1\n\techo \"${arg#*=}\"\n\t#alternatives echo \"$arg\" | cut -d= -f2-\n\t# or echo \"$arg\" | sed 's/[^=]*=//'\n}\n\nfat_binary=\nfat_binary_m1=\nfat_binary_m2=\nignore_cve=no\nhookmethod=auto\n\nparsearg() {\n\tcase \"$1\" in\n\t--prefix=*) prefix=`spliteq $1`;;\n\t--exec_prefix=*) exec_prefix=`spliteq $1`;;\n\t--bindir=*) bindir=`spliteq $1`;;\n\t--libdir=*) libdir=`spliteq $1`;;\n\t--includedir=*) includedir=`spliteq $1`;;\n\t--sysconfdir=*) sysconfdir=`spliteq $1`;;\n\t--ignore-cve) ignore_cve=1;;\n\t--ignore-cve=*) ignore_cve=`spliteq $1`;;\n\t--hookmethod=*) hookmethod=`spliteq $1`;;\n\t--fat-binary) fat_binary=1;;\n\t--fat-binary-m1) fat_binary_m1=1;;\n\t--fat-binary-m2) fat_binary_m2=1;;\n\t--help) usage;;\n\tesac\n}\n\nwhile true ; do\n\tcase $1 in\n\t-*) parsearg \"$1\"; shift;;\n\t*) break ;;\n\tesac\ndone\n\nif [ -z \"$exec_prefix\" ] ; then\n\texec_prefix=$prefix\nfi\n\nif [ -z \"$libdir\" ] ; then\n\tlibdir=$prefix/lib\nfi\n\nif [ -z \"$includedir\" ] ; then\n\tincludedir=$prefix/include\nfi\n\nif [ -z \"$sysconfdir\" ] ; then\n\tsysconfdir=$prefix/etc\nfi\n\nif [ -z \"$bindir\" ] ; then\n\tbindir=$exec_prefix/bin\nfi\n\nif [ -z \"$CC\" ] ; then\n\tCC=cc\nfi\n\necho > config.mak\n\nbsd_detected=false\nisbsd() {\n\t$bsd_detected\n}\nmac_detected=false\nismac() {\n\t$mac_detected\n}\nmac_64=false\nismac64() {\n\t$mac_64\n}\nsolaris_detected=false\nissolaris() {\n\t$solaris_detected\n}\nhaiku_detected=false\nishaiku() {\n\t$haiku_detected\n}\n\ncheck_compile 'whether C compiler works' '' 'int main() {return 0;}' || fail 'error: install a C compiler and library'\ncheck_compile 'whether libc headers are complete' '' '#include <netdb.h>\\nint main() {return 0;}' || fail 'error: necessary libc headers are not installed'\ncheck_compile 'whether C compiler understands -Wno-unknown-pragmas' '-Wno-unknown-pragmas' 'int main() {return 0;}'\ncheck_compile 'whether C compiler understands -Werror=implicit-function-declaration' '-Werror=implicit-function-declaration' 'int main() {return 0;}'\n\nif ! check_compile 'whether getnameinfo() servlen argument is POSIX compliant (socklen_t)' \"-DGN_NODELEN_T=socklen_t -DGN_SERVLEN_T=socklen_t -DGN_FLAGS_T=int\" \\\n'#define _GNU_SOURCE\\n#include <netdb.h>\\nint getnameinfo(const struct sockaddr *, socklen_t, char *, socklen_t, char *, socklen_t, int);int main() {\\nreturn 0;}' ; then\n # GLIBC < 2.14\n if ! check_compile 'whether getnameinfo() flags argument is unsigned' \"-DGN_NODELEN_T=socklen_t -DGN_SERVLEN_T=socklen_t -DGN_FLAGS_T=unsigned\" \\\n  '#define _GNU_SOURCE\\n#include <netdb.h>\\nint getnameinfo(const struct sockaddr *, socklen_t, char *, socklen_t, char *, socklen_t, unsigned);int main() {\\nreturn 0;}' ; then\n  if ! check_compile 'whether getnameinfo() servlen argument is size_t' \"-DGN_NODELEN_T=socklen_t -DGN_SERVLEN_T=size_t -DGN_FLAGS_T=int\" \\\n   '#define _GNU_SOURCE\\n#include <netdb.h>\\nint getnameinfo(const struct sockaddr *, socklen_t, char *, socklen_t, char *, size_t, int);int main() {\\nreturn 0;}' ; then\n   # OpenBSD & FreeBSD\n   if ! check_compile 'whether getnameinfo() servlen and nodelen argument is size_t' \"-DGN_NODELEN_T=size_t -DGN_SERVLEN_T=size_t -DGN_FLAGS_T=int\" \\\n    '#define _GNU_SOURCE\\n#include <netdb.h>\\nint getnameinfo(const struct sockaddr *, socklen_t, char *, size_t, char *, size_t, int);int main() {\\nreturn 0;}' ; then\n     fail \"failed to detect getnameinfo signature\"\n   fi\n  fi\n fi\nfi\n\ncheck_compile 'whether we have GNU-style getservbyname_r()' \"-DHAVE_GNU_GETSERVBYNAME_R\" \\\n'#define _GNU_SOURCE\\n#include <netdb.h>\\nint main() {\\nstruct servent *se = 0;struct servent se_buf;char buf[1024];\\ngetservbyname_r(\"foo\", (void*) 0, &se_buf, buf, sizeof(buf), &se);\\nreturn 0;}'\n\ncheck_compile 'whether we have pipe2() and O_CLOEXEC' \"-DHAVE_PIPE2\" \\\n'#define _GNU_SOURCE\\n#include <fcntl.h>\\n#include <unistd.h>\\nint main() {\\nint pipefd[2];\\npipe2(pipefd, O_CLOEXEC);\\nreturn 0;}'\n\ncheck_compile 'whether we have SOCK_CLOEXEC' \"-DHAVE_SOCK_CLOEXEC\" \\\n'#define _GNU_SOURCE\\n#include <sys/socket.h>\\nint main() {\\nreturn socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);}'\n\ncheck_compile 'whether we have clock_gettime' \"-DHAVE_CLOCK_GETTIME\" \\\n'#define _GNU_SOURCE\\n#include <time.h>\\nint main() {\\nstruct timespec now;clock_gettime(CLOCK_REALTIME, &now);\\nreturn now.tv_sec ^ now.tv_nsec;}'\n\ncheck_define __APPLE__ && {\n\tmac_detected=true\n\tcheck_define __x86_64__ && mac_64=true\n\tif test \"$hookmethod\" = auto ; then\n\t\tosver=$(get_define_stripped __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 2>/dev/null)\n\t\ttest \"$osver\" -gt $((120000 - 1)) && hookmethod=dyld\n\tfi\n}\ncheck_define __FreeBSD__ && bsd_detected=true\ncheck_define __NetBSD__ && bsd_detected=true\ncheck_define __OpenBSD__ && {\nbsd_detected=true\necho \"CFLAGS+=-DIS_OPENBSD\">>config.mak\ncheck_compile_run 'whether OpenBSDs fclose() (illegally) calls close()' \\\n'#include <stdio.h>\\n#include<stdlib.h>\\nint close(int x){exit(0);}int main(){fclose(stdin);return 1;}' && \\\nOUR_CPPFLAGS=\"$OUR_CPPFLAGS -DBROKEN_FCLOSE\"\n}\ncheck_define __sun && check_define __SVR4 && solaris_detected=true\ncheck_define __HAIKU__ && haiku_detected=true\n\necho \"CC=$CC\">>config.mak\n[ -z \"$CPPFLAGS\" ] || echo \"CPPFLAGS=$CPPFLAGS\">>config.mak\n[ -z \"$CFLAGS\" ] || echo \"USER_CFLAGS=$CFLAGS\">>config.mak\n[ -z \"$LDFLAGS\" ] || echo \"USER_LDFLAGS=$LDFLAGS\">>config.mak\necho prefix=$prefix>>config.mak\necho exec_prefix=$exec_prefix>>config.mak\necho bindir=$bindir>>config.mak\necho libdir=$libdir>>config.mak\necho includedir=$includedir>>config.mak\necho sysconfdir=$sysconfdir>>config.mak\n[ \"$ignore_cve\" = \"no\" ] && echo \"CPPFLAGS+= -DSUPER_SECURE\">>config.mak\n[ -z \"$OUR_CPPFLAGS\" ] || echo \"CPPFLAGS+= $OUR_CPPFLAGS\" >>config.mak\n\ncheck_link \"whether we can use -Wl,--no-as-needed\" \"-Wl,--no-as-needed\" \\\n\"int main() { return 0; }\" || echo NO_AS_NEEDED= >> config.mak\n\nLD_SONAME_FLAG=\nprintf \"checking what's the option to use in linker to set library name ... \"\nfor o in --soname -h -soname -install_name; do\n\tcheck_link_silent \"-shared -Wl,$o,libconftest.so\" \"void test_func(void) {}\" && LD_SONAME_FLAG=$o && break\ndone\nif [ -z \"$LD_SONAME_FLAG\" ]; then\n\tprintf '\\ncannot find an option to set library name\\n'\n\texit 1\nfi\necho \"$LD_SONAME_FLAG\"\necho \"LD_SET_SONAME = -Wl,$LD_SONAME_FLAG,\" >> config.mak\n\nif check_link \"checking whether we can use -ldl\" \"-ldl\" \\\n\"int main(){return 0;}\" ; then\necho \"LIBDL = -ldl\" >> config.mak\nfi\n\nif check_link \"checking whether we can use -lpthread\" \"-lpthread\" \\\n\"int main(){return 0;}\" ; then\necho \"PTHREAD = -lpthread\" >> config.mak\nelse\ncheck_link \"checking whether we can use -pthread\" \"-pthread\" \\\n\"int main(){return 0;}\" || fail \"no pthread support detected\"\necho \"PTHREAD = -pthread\" >> config.mak\nfi\n\nmake_cmd=make\nif ismac ; then\n\techo LDSO_SUFFIX=dylib>>config.mak\n\techo MAC_CFLAGS+=-DIS_MAC=1>>config.mak\n\tif test \"$hookmethod\" = dyld ; then\n\t\techo \"using Monterey style DYLD hooking\"\n\t\techo \"CFLAGS+=-DMONTEREY_HOOKING\">>config.mak\n\tfi\n\tif ismac64 && [ \"$fat_binary\" = 1 ] ; then\n\t\techo \"Configuring a fat binary for i386 and x86_64\"\n\t\techo \"MAC_CFLAGS+=-arch i386 -arch x86_64\">>config.mak\n\t\techo \"FAT_LDFLAGS=-arch i386 -arch x86_64\">>config.mak\n\t\techo \"FAT_BIN_LDFLAGS=-arch i386 -arch x86_64\">>config.mak\n\tfi\n\tif [ \"$fat_binary_m1\" = 1 ] ; then\n\t\techo \"Configuring a fat binary for arm64[e] and x86_64\"\n\t\techo \"MAC_CFLAGS+=-arch arm64 -arch arm64e -arch x86_64\">>config.mak\n\t\techo \"FAT_LDFLAGS=-arch arm64 -arch arm64e -arch x86_64\">>config.mak\n\t\techo \"FAT_BIN_LDFLAGS=-arch arm64 -arch x86_64\">>config.mak\n\tfi\n\tif [ \"$fat_binary_m2\" = 1 ] ; then\n\t\techo \"Configuring a fat binary for arm64[e] and x86_64\"\n\t\techo \"MAC_CFLAGS+=-arch arm64 -arch arm64e -arch x86_64\">>config.mak\n\t\techo \"FAT_LDFLAGS=-arch arm64 -arch arm64e -arch x86_64\">>config.mak\n\t\techo \"FAT_BIN_LDFLAGS=-arch arm64 -arch arm64e -arch x86_64\">>config.mak\n\tfi\nelif isbsd ; then\n\techo LIBDL=>>config.mak\n\techo \"CFLAGS+=-DIS_BSD\">>config.mak\n\tmake_cmd=gmake\nelif issolaris; then\n\techo \"CFLAGS+=-DIS_SOLARIS -D__EXTENSIONS__\" >> config.mak\n\techo \"SOCKET_LIBS=-lsocket -lnsl\" >> config.mak\nelif ishaiku ; then\n\techo LIBDL=>>config.mak\n\techo \"CFLAGS+=-DIS_HAIKU\" >> config.mak\nfi\n\necho \"Done, now run $make_cmd && $make_cmd install\"\nif [ \"$fat_binary_m2\" = 1 ] ; then\necho \"Don't forget to run csrutil disable and sudo nvram boot-args=-arm64e_preview_abi\"\nfi\n"
  },
  {
    "path": "src/allocator_thread.c",
    "content": "#undef _GNU_SOURCE\n#define _GNU_SOURCE\n#undef _POSIX_C_SOURCE\n#define _DARWIN_C_SOURCE\n#include <limits.h>\n#include <pthread.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/select.h>\n#include <assert.h>\n#include <string.h>\n#include <stdint.h>\n#include <stddef.h>\n#include <errno.h>\n#include <sys/mman.h>\n#include \"allocator_thread.h\"\n#include \"debug.h\"\n#include \"ip_type.h\"\n#include \"mutex.h\"\n#include \"hash.h\"\n#include \"remotedns.h\"\n\n/* stuff for our internal translation table */\n\ntypedef struct {\n\tuint32_t hash;\n\tchar* string;\n} string_hash_tuple;\n\ntypedef struct {\n\tuint32_t counter;\n\tuint32_t capa;\n\tstring_hash_tuple** list;\n} internal_ip_lookup_table;\n\nstatic void *dumpstring(char* s, size_t len) {\n\tchar* p = malloc(len);\n\tif(p) memcpy(p, s, len);\n\treturn p;\n}\n\nstatic pthread_mutex_t *internal_ips_lock;\nstatic internal_ip_lookup_table *internal_ips;\n\nuint32_t index_from_internal_ip(ip_type4 internalip) {\n\tPFUNC();\n\tip_type4 tmp = internalip;\n\tuint32_t ret;\n\tret = tmp.octet[3] + (tmp.octet[2] << 8) + (tmp.octet[1] << 16);\n\tret -= 1;\n\treturn ret;\n}\n\nchar *string_from_internal_ip(ip_type4 internalip) {\n\tPFUNC();\n\tchar *res = NULL;\n\tuint32_t index = index_from_internal_ip(internalip);\n\tif(index < internal_ips->counter)\n\t\tres = internal_ips->list[index]->string;\n\treturn res;\n}\n\nextern unsigned int remote_dns_subnet;\nip_type4 make_internal_ip(uint32_t index) {\n\tip_type4 ret;\n\tindex++; // so we can start at .0.0.1\n\tif(index > 0xFFFFFF)\n\t\treturn IPT4_INVALID;\n\tret.octet[0] = remote_dns_subnet & 0xFF;\n\tret.octet[1] = (index & 0xFF0000) >> 16;\n\tret.octet[2] = (index & 0xFF00) >> 8;\n\tret.octet[3] = index & 0xFF;\n\treturn ret;\n}\n\nstatic ip_type4 ip_from_internal_list(char* name, size_t len) {\n\tuint32_t hash = dalias_hash((char *) name);\n\tsize_t i;\n\tip_type4 res;\n\tvoid* new_mem;\n\t// see if we already have this dns entry saved.\n\tif(internal_ips->counter) {\n\t\tfor(i = 0; i < internal_ips->counter; i++) {\n\t\t\tif(internal_ips->list[i]->hash == hash && !strcmp(name, internal_ips->list[i]->string)) {\n\t\t\t\tres = make_internal_ip(i);\n\t\t\t\tPDEBUG(\"got cached ip for %s\\n\", name);\n\t\t\t\tgoto have_ip;\n\t\t\t}\n\t\t}\n\t}\n\t// grow list if needed.\n\tif(internal_ips->capa < internal_ips->counter + 1) {\n\t\tPDEBUG(\"realloc\\n\");\n\t\tnew_mem = realloc(internal_ips->list, (internal_ips->capa + 16) * sizeof(void *));\n\t\tif(new_mem) {\n\t\t\tinternal_ips->capa += 16;\n\t\t\tinternal_ips->list = new_mem;\n\t\t} else {\n\toom:\n\t\t\tPDEBUG(\"out of mem\\n\");\n\t\t\tgoto err_plus_unlock;\n\t\t}\n\t}\n\n\tres = make_internal_ip(internal_ips->counter);\n\tif(res.as_int == IPT4_INVALID.as_int)\n\t\tgoto err_plus_unlock;\n\n\tstring_hash_tuple tmp = { 0 };\n\tnew_mem = dumpstring((char*) &tmp, sizeof(string_hash_tuple));\n\tif(!new_mem)\n\t\tgoto oom;\n\n\tPDEBUG(\"creating new entry %d for ip of %s\\n\", (int) internal_ips->counter, name);\n\n\tinternal_ips->list[internal_ips->counter] = new_mem;\n\tinternal_ips->list[internal_ips->counter]->hash = hash;\n\n\tnew_mem = dumpstring((char*) name, len);\n\n\tif(!new_mem) {\n\t\tinternal_ips->list[internal_ips->counter] = 0;\n\t\tgoto oom;\n\t}\n\tinternal_ips->list[internal_ips->counter]->string = new_mem;\n\n\tinternal_ips->counter += 1;\n\n\thave_ip:\n\n\treturn res;\n\terr_plus_unlock:\n\n\tPDEBUG(\"return err\\n\");\n\treturn IPT4_INVALID;\n}\n\n/* stuff for communication with the allocator thread */\n\nenum at_direction {\n\tATD_SERVER = 0,\n\tATD_CLIENT,\n\tATD_MAX,\n};\n\nstatic pthread_t allocator_thread;\nint req_pipefd[2];\nint resp_pipefd[2];\n\nstatic int wait_data(int readfd) {\n\tPFUNC();\n\tfd_set fds;\n\tFD_ZERO(&fds);\n\tFD_SET(readfd, &fds);\n\tint ret;\n\twhile((ret = select(readfd+1, &fds, NULL, NULL, NULL)) <= 0) {\n\t\tif(ret < 0) {\n\t\t\tint e = errno;\n\t\t\tif(e == EINTR) continue;\n#ifdef __GLIBC__\n\t\t\tchar emsg[1024];\n\t\t\tchar* x = strerror_r(errno, emsg, sizeof emsg);\n\t\t\tdprintf(2, \"select2: %s\\n\", x);\n#endif\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n}\n\nstatic int trywrite(int fd, void* buf, size_t bytes) {\n\tssize_t ret;\n\tunsigned char *out = buf;\nagain:\n\tret = write(fd, out, bytes);\n\tswitch(ret) {\n\t\tcase -1:\n\t\t\tif(errno == EINTR) goto again;\n\t\tcase  0:\n\t\t\treturn 0;\n\t\tdefault:\n\t\t\tif(ret == bytes || !bytes) return 1;\n\t\t\tout += ret;\n\t\t\tbytes -= ret;\n\t\t\tgoto again;\n\t}\n}\n\nstatic int sendmessage(enum at_direction dir, struct at_msg *msg) {\n\tstatic int* destfd[ATD_MAX] = { [ATD_SERVER] = &req_pipefd[1], [ATD_CLIENT] = &resp_pipefd[1] };\n\tassert(msg->h.datalen <= MSG_LEN_MAX);\n\tint ret = trywrite(*destfd[dir], msg, sizeof (msg->h)+msg->h.datalen);\n\tassert(msg->h.datalen <= MSG_LEN_MAX);\n\treturn ret;\n}\n\nstatic int tryread(int fd, void* buf, size_t bytes) {\n\tssize_t ret;\n\tunsigned char *out = buf;\nagain:\n\tret = read(fd, out, bytes);\n\tswitch(ret) {\n\t\tcase -1:\n\t\t\tif(errno == EINTR) goto again;\n\t\tcase  0:\n\t\t\treturn 0;\n\t\tdefault:\n\t\t\tif(ret == bytes || !bytes) return 1;\n\t\t\tout += ret;\n\t\t\tbytes -= ret;\n\t\t\tgoto again;\n\t}\n}\nstatic int readmsg(int fd, struct at_msg *msg) {\n\tint ret = tryread(fd, msg, sizeof(msg->h));\n\tif(ret != 1) return ret;\n\treturn tryread(fd, &msg->m, msg->h.datalen);\n}\n\nstatic int getmessage(enum at_direction dir, struct at_msg *msg) {\n\tstatic int* readfd[ATD_MAX] = { [ATD_SERVER] = &req_pipefd[0], [ATD_CLIENT] = &resp_pipefd[0] };\n\tssize_t ret;\n\tif((ret = wait_data(*readfd[dir]))) {\n\t\tif(!readmsg(*readfd[dir], msg))\n\t\t\treturn 0;\n\t\tassert(msg->h.datalen <= MSG_LEN_MAX);\n\t}\n\treturn ret;\n}\n\nstatic void* threadfunc(void* x) {\n\t(void) x;\n\tint ret;\n\tstruct at_msg msg;\n\twhile((ret = getmessage(ATD_SERVER, &msg))) {\n\t\tswitch(msg.h.msgtype) {\n\t\t\tcase ATM_GETIP:\n\t\t\t\t/* client wants an ip for a DNS name. iterate our list and check if we have an existing entry.\n\t\t\t\t\t* if not, create a new one. */\n\t\t\t\tmsg.m.ip = ip_from_internal_list(msg.m.host, msg.h.datalen);\n\t\t\t\tmsg.h.datalen = sizeof(ip_type4);\n\t\t\t\tbreak;\n\t\t\tcase ATM_GETNAME: {\n\t\t\t\tchar *host = string_from_internal_ip(msg.m.ip);\n\t\t\t\tif(host) {\n\t\t\t\t\tsize_t l = strlen(host);\n\t\t\t\t\tassert(l+1 < MSG_LEN_MAX);\n\t\t\t\t\tmemcpy(msg.m.host, host, l + 1);\n\t\t\t\t\tmsg.h.datalen = l + 1;\n\t\t\t\t} else {\n\t\t\t\t\tmsg.h.datalen = 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase ATM_EXIT:\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\tabort();\n\t\t}\n\t\tret = sendmessage(ATD_CLIENT, &msg);\n\t}\n\treturn 0;\n}\n\n/* API to access the internal ip mapping */\n\nip_type4 at_get_ip_for_host(char* host, size_t len) {\n\tip_type4 readbuf;\n\tMUTEX_LOCK(internal_ips_lock);\n\tif(len > MSG_LEN_MAX) goto inv;\n\tstruct at_msg msg = {.h.msgtype = ATM_GETIP, .h.datalen = len + 1 };\n\tmemcpy(msg.m.host, host, len+1);\n\tif(sendmessage(ATD_SERVER, &msg) &&\n\t   getmessage(ATD_CLIENT, &msg)) readbuf = msg.m.ip;\n\telse {\n\t\tinv:\n\t\treadbuf = IPT4_INVALID;\n\t}\n\tassert(msg.h.msgtype == ATM_GETIP);\n\tMUTEX_UNLOCK(internal_ips_lock);\n\treturn readbuf;\n}\n\nsize_t at_get_host_for_ip(ip_type4 ip, char* readbuf) {\n\tstruct at_msg msg = {.h.msgtype = ATM_GETNAME, .h.datalen = sizeof(ip_type4), .m.ip = ip };\n\tsize_t res = 0;\n\tMUTEX_LOCK(internal_ips_lock);\n\tif(sendmessage(ATD_SERVER, &msg) && getmessage(ATD_CLIENT, &msg)) {\n\t\tif((int16_t) msg.h.datalen <= 0) res = 0;\n\t\telse {\n\t\t\tmemcpy(readbuf, msg.m.host, msg.h.datalen);\n\t\t\tres = msg.h.datalen - 1;\n\t\t}\n\t}\n\tassert(msg.h.msgtype == ATM_GETNAME);\n\tMUTEX_UNLOCK(internal_ips_lock);\n\treturn res;\n}\n\n\nstatic void initpipe(int* fds) {\n\tint retval;\n\n#ifdef HAVE_PIPE2\n\tretval = pipe2(fds, O_CLOEXEC);\n#else\n\tretval = pipe(fds);\n\tif(retval == 0) {\n\t\tfcntl(fds[0], F_SETFD, FD_CLOEXEC);\n\t\tfcntl(fds[1], F_SETFD, FD_CLOEXEC);\n\t}\n#endif\n\tif(retval == -1) {\n\t\tperror(\"pipe\");\n\t\texit(1);\n\t}\n}\n\n#ifndef MAX\n#define MAX(x, y) ((x) > (y) ? (x) : (y))\n#endif\n\n#if !defined(PTHREAD_STACK_MIN) || defined(__APPLE__)\n/* MAC says its min is 8KB, but then crashes in our face. thx hunkOLard */\n#define PTHREAD_STACK_MIN 64*1024\n#endif\n\n/* initialize with pointers to shared memory. these will\n * be used to place responses and arguments */\nvoid at_init(void) {\n\tPFUNC();\n\tvoid *shm = mmap(0, 4096, PROT_WRITE|PROT_READ, MAP_ANON|MAP_SHARED, -1, 0);\n\tassert(shm);\n\tinternal_ips_lock = shm;\n\tinternal_ips = (void*)((char*)shm + 2048);\n\n\tMUTEX_INIT(internal_ips_lock);\n\tmemset(internal_ips, 0, sizeof *internal_ips);\n\tinitpipe(req_pipefd);\n\tinitpipe(resp_pipefd);\n\tpthread_attr_t allocator_thread_attr;\n\tpthread_attr_init(&allocator_thread_attr);\n\tpthread_attr_setstacksize(&allocator_thread_attr, MAX(16 * 1024, PTHREAD_STACK_MIN));\n\tpthread_create(&allocator_thread, &allocator_thread_attr, threadfunc, 0);\n\tpthread_attr_destroy(&allocator_thread_attr);\n}\n\nvoid at_close(void) {\n\tPFUNC();\n\tconst int msg = ATM_EXIT;\n\twrite(req_pipefd[1], &msg, sizeof(int));\n\tpthread_join(allocator_thread, NULL);\n\tclose(req_pipefd[0]);\n\tclose(req_pipefd[1]);\n\tclose(resp_pipefd[0]);\n\tclose(resp_pipefd[1]);\n\tMUTEX_DESTROY(internal_ips_lock);\n}\n"
  },
  {
    "path": "src/allocator_thread.h",
    "content": "#ifndef ALLOCATOR_THREAD_H\n#define ALLOCATOR_THREAD_H\n\n#include <unistd.h>\n#include \"ip_type.h\"\n\nextern int req_pipefd[2];\nextern int resp_pipefd[2];\n\nvoid at_init(void);\nvoid at_close(void);\nsize_t at_get_host_for_ip(ip_type4 ip, char* readbuf);\nip_type4 at_get_ip_for_host(char* host, size_t len);\n\n//RcB: DEP \"allocator_thread.c\"\n#endif\n\n"
  },
  {
    "path": "src/common.c",
    "content": "#include \"common.h\"\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n\nconst char *proxy_type_strmap[] = {\n    \"http\",\n    \"socks4\",\n    \"socks5\",\n};\n\nconst char *chain_type_strmap[] = {\n    \"dynamic_chain\",\n    \"strict_chain\",\n    \"random_chain\",\n    \"round_robin_chain\",\n};\n\nconst char *proxy_state_strmap[] = {\n    \"play\",\n    \"down\",\n    \"blocked\",\n    \"busy\",\n};\n\n/* isnumericipv4() taken from libulz */\nint pc_isnumericipv4(const char* ipstring) {\n\tsize_t x = 0, n = 0, d = 0;\n\tint wasdot = 0;\n\twhile(1) {\n\t\tswitch(ipstring[x]) {\n\t\t\tcase 0: goto done;\n\t\t\tcase '.':\n\t\t\t\tif(!n || wasdot) return 0;\n\t\t\t\td++;\n\t\t\t\twasdot = 1;\n\t\t\t\tbreak;\n\t\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\t\t\tn++;\n\t\t\t\twasdot = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn 0;\n\t\t}\n\t\tx++;\n\t}\n\tdone:\n\tif(d == 3 && n >= 4 && n <= 12) return 1;\n\treturn 0;\n}\n\n// stolen from libulz (C) rofl0r\nvoid pc_stringfromipv4(unsigned char *ip_buf_4_bytes, char *outbuf_16_bytes) {\n\tunsigned char *p;\n\tchar *o = outbuf_16_bytes;\n\tunsigned char n;\n\tfor(p = ip_buf_4_bytes; p < ip_buf_4_bytes + 4; p++) {\n\t\tn = *p;\n\t\tif(*p >= 100) {\n\t\t\tif(*p >= 200)\n\t\t\t\t*(o++) = '2';\n\t\t\telse\n\t\t\t\t*(o++) = '1';\n\t\t\tn %= 100;\n\t\t}\n\t\tif(*p >= 10) {\n\t\t\t*(o++) = (n / 10) + '0';\n\t\t\tn %= 10;\n\t\t}\n\t\t*(o++) = n + '0';\n\t\t*(o++) = '.';\n\t}\n\to[-1] = 0;\n}\n\nstatic int check_path(char *path) {\n\tif(!path)\n\t\treturn 0;\n\treturn access(path, R_OK) != -1;\n}\n\nchar *get_config_path(char* default_path, char* pbuf, size_t bufsize) {\n\tchar buf[512];\n\t// top priority: user defined path\n\tchar *path = default_path;\n\tif(check_path(path))\n\t\tgoto have;\n\n\t// priority 1: env var PROXYCHAINS_CONF_FILE\n\tpath = getenv(PROXYCHAINS_CONF_FILE_ENV_VAR);\n\tif(check_path(path))\n\t\tgoto have;\n\n\t// priority 2; proxychains conf in actual dir\n\tpath = getcwd(buf, sizeof(buf));\n\tsnprintf(pbuf, bufsize, \"%s/%s\", path, PROXYCHAINS_CONF_FILE);\n\tpath = pbuf;\n\tif(check_path(path))\n\t\tgoto have;\n\n\t// priority 3; $HOME/.proxychains/proxychains.conf\n\tpath = getenv(\"HOME\");\n\tsnprintf(pbuf, bufsize, \"%s/.proxychains/%s\", path, PROXYCHAINS_CONF_FILE);\n\tpath = pbuf;\n\tif(check_path(path))\n\t\tgoto have;\n    \n    // priority 3b: ~/config/settings/proxychains.conf (for haiku)\n\tpath = getenv(\"HOME\");\n\tsnprintf(pbuf, bufsize, \"%s/config/settings/%s\", path, PROXYCHAINS_CONF_FILE);\n\tpath = pbuf;\n\tif(check_path(path))\n\t\tgoto have;\n\n\t// priority 4: $SYSCONFDIR/proxychains.conf\n\tpath = SYSCONFDIR \"/\" PROXYCHAINS_CONF_FILE;\n\tif(check_path(path))\n\t\tgoto have;\n\n\t// priority 5: /etc/proxychains.conf\n\tpath = \"/etc/\" PROXYCHAINS_CONF_FILE;\n\tif(check_path(path))\n\t\tgoto have;\n\n\tperror(\"couldnt find configuration file\");\n\texit(1);\n\n\treturn NULL;\n\thave:\n\treturn path;\n}\n"
  },
  {
    "path": "src/common.h",
    "content": "#ifndef COMMON_H\n#define COMMON_H\n\n#define PROXYCHAINS_CONF_FILE_ENV_VAR \"PROXYCHAINS_CONF_FILE\"\n#define PROXYCHAINS_QUIET_MODE_ENV_VAR \"PROXYCHAINS_QUIET_MODE\"\n#define PROXYCHAINS_CONF_FILE \"proxychains.conf\"\n#define LOG_PREFIX \"[proxychains] \"\n#ifndef SYSCONFDIR\n#define SYSCONFDIR \"/etc\"\n#endif\n\n#include <stddef.h>\n\nextern const char *proxy_type_strmap[];\nextern const char *chain_type_strmap[];\nextern const char *proxy_state_strmap[];\n\nchar *get_config_path(char* default_path, char* pbuf, size_t bufsize);\nvoid pc_stringfromipv4(unsigned char *ip_buf_4_bytes, char *outbuf_16_bytes);\nint pc_isnumericipv4(const char* ipstring);\n\n//RcB: DEP \"common.c\"\n#endif\n"
  },
  {
    "path": "src/core.c",
    "content": "/***************************************************************************\n                          core.c  -  description\n                             -------------------\n    begin                : Tue May 14 2002\n    copyright            :  netcreature (C) 2002\n    email                : netcreature@users.sourceforge.net\n ***************************************************************************\n *     GPL *\n ***************************************************************************\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n ***************************************************************************/\n\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <netdb.h>\n\n#include <sys/utsname.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <poll.h>\n#include <sys/wait.h>\n#include <fcntl.h>\n#include <time.h>\n#include <sys/time.h>\n#include <stdarg.h>\n#include <assert.h>\n\n#include \"core.h\"\n#include \"common.h\"\n#include \"rdns.h\"\n#include \"mutex.h\"\n\nextern int tcp_read_time_out;\nextern int tcp_connect_time_out;\nextern int proxychains_quiet_mode;\nextern unsigned int proxychains_proxy_offset;\nextern unsigned int remote_dns_subnet;\n\nstatic int poll_retry(struct pollfd *fds, nfds_t nfsd, int timeout) {\n\tint ret;\n\tint time_remain = timeout;\n\tint time_elapsed = 0;\n\n\tstruct timeval start_time;\n\tstruct timeval tv;\n\n\tgettimeofday(&start_time, NULL);\n\n\tdo {\n\t\t//printf(\"Retry %d\\n\", time_remain);\n\t\tret = poll(fds, nfsd, time_remain);\n\t\tgettimeofday(&tv, NULL);\n\t\ttime_elapsed = ((tv.tv_sec - start_time.tv_sec) * 1000 + (tv.tv_usec - start_time.tv_usec) / 1000);\n\t\t//printf(\"Time elapsed %d\\n\", time_elapsed);\n\t\ttime_remain = timeout - time_elapsed;\n\t} while(ret == -1 && errno == EINTR && time_remain > 0);\n\n\t//if (ret == -1)\n\t//printf(\"Return %d %d %s\\n\", ret, errno, strerror(errno));\n\treturn ret;\n}\n\nstatic void encode_base_64(char *src, char *dest, int max_len) {\n\tstatic const char base64[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\tint n, l, i;\n\tl = strlen(src);\n\tmax_len = (max_len - 1) / 4;\n\tfor(i = 0; i < max_len; i++, src += 3, l -= 3) {\n\t\tswitch (l) {\n\t\t\tcase 0:\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tn = src[0] << 16;\n\t\t\t\t*dest++ = base64[(n >> 18) & 077];\n\t\t\t\t*dest++ = base64[(n >> 12) & 077];\n\t\t\t\t*dest++ = '=';\n\t\t\t\t*dest++ = '=';\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tn = src[0] << 16 | src[1] << 8;\n\t\t\t\t*dest++ = base64[(n >> 18) & 077];\n\t\t\t\t*dest++ = base64[(n >> 12) & 077];\n\t\t\t\t*dest++ = base64[(n >> 6) & 077];\n\t\t\t\t*dest++ = '=';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tn = src[0] << 16 | src[1] << 8 | src[2];\n\t\t\t\t*dest++ = base64[(n >> 18) & 077];\n\t\t\t\t*dest++ = base64[(n >> 12) & 077];\n\t\t\t\t*dest++ = base64[(n >> 6) & 077];\n\t\t\t\t*dest++ = base64[n & 077];\n\t\t}\n\t\tif(l < 3)\n\t\t\tbreak;\n\t}\n\t*dest++ = 0;\n}\n\nvoid proxychains_write_log(char *str, ...) {\n\tchar buff[1024*4];\n\tva_list arglist;\n\tif(!proxychains_quiet_mode) {\n\t\tva_start(arglist, str);\n\t\tvsnprintf(buff, sizeof(buff), str, arglist);\n\t\tva_end(arglist);\n\t\tfprintf(stderr, \"%s\", buff);\n\t\tfflush(stderr);\n\t}\n}\n\nstatic int write_n_bytes(int fd, char *buff, size_t size) {\n\tint i = 0;\n\tsize_t wrote = 0;\n\tfor(;;) {\n\t\ti = write(fd, &buff[wrote], size - wrote);\n\t\tif(i <= 0)\n\t\t\treturn i;\n\t\twrote += i;\n\t\tif(wrote == size)\n\t\t\treturn wrote;\n\t}\n}\n\nstatic int read_n_bytes(int fd, char *buff, size_t size) {\n\tint ready;\n\tsize_t i;\n\tstruct pollfd pfd[1];\n\n\tpfd[0].fd = fd;\n\tpfd[0].events = POLLIN;\n\tfor(i = 0; i < size; i++) {\n\t\tpfd[0].revents = 0;\n\t\tready = poll_retry(pfd, 1, tcp_read_time_out);\n\t\tif(ready != 1 || !(pfd[0].revents & POLLIN) || 1 != read(fd, &buff[i], 1))\n\t\t\treturn -1;\n\t}\n\treturn (int) size;\n}\n\nstatic int timed_connect(int sock, const struct sockaddr *addr, socklen_t len) {\n\tint ret, value;\n\tsocklen_t value_len;\n\tstruct pollfd pfd[1];\n\tPFUNC();\n\n\tpfd[0].fd = sock;\n\tpfd[0].events = POLLOUT;\n\tfcntl(sock, F_SETFL, O_NONBLOCK);\n\tret = true_connect(sock, addr, len);\n\tPDEBUG(\"\\nconnect ret=%d\\n\", ret);\n\t\n\tif(ret == -1 && errno == EINPROGRESS) {\n\t\tret = poll_retry(pfd, 1, tcp_connect_time_out);\n\t\tPDEBUG(\"\\npoll ret=%d\\n\", ret);\n\t\tif(ret == 1) {\n\t\t\tvalue_len = sizeof(socklen_t);\n\t\t\tgetsockopt(sock, SOL_SOCKET, SO_ERROR, &value, &value_len);\n\t\t\tPDEBUG(\"\\nvalue=%d\\n\", value);\n\t\t\tif(!value)\n\t\t\t\tret = 0;\n\t\t\telse\n\t\t\t\tret = -1;\n\t\t} else {\n\t\t\tret = -1;\n\t\t}\n\t} else {\n#ifdef DEBUG\n\t\tif(ret == -1)\n\t\t\tperror(\"true_connect\");\n#endif\n\t\tif(ret != 0)\n\t\t\tret = -1;\n\t}\n\n\tfcntl(sock, F_SETFL, !O_NONBLOCK);\n\treturn ret;\n}\n\n\n#define INVALID_INDEX 0xFFFFFFFFU\n#define BUFF_SIZE 1024  // used to read responses from proxies.\nstatic int tunnel_to(int sock, ip_type ip, unsigned short port, proxy_type pt, char *user, char *pass) {\n\tchar *dns_name = NULL;\n\tchar hostnamebuf[MSG_LEN_MAX];\n\tsize_t dns_len = 0;\n\n\tPFUNC();\n\n\t// we use ip addresses with 224.* to lookup their dns name in our table, to allow remote DNS resolution\n\t// the range 224-255.* is reserved, and it won't go outside (unless the app does some other stuff with\n\t// the results returned from gethostbyname et al.)\n\t// the hardcoded number 224 can now be changed using the config option remote_dns_subnet to i.e. 127\n\tif(!ip.is_v6 && proxychains_resolver >= DNSLF_RDNS_START && ip.addr.v4.octet[0] == remote_dns_subnet) {\n\t\tdns_len = rdns_get_host_for_ip(ip.addr.v4, hostnamebuf);\n\t\tif(!dns_len) goto err;\n\t\telse dns_name = hostnamebuf;\n\t}\n\t\n\tPDEBUG(\"host dns %s\\n\", dns_name ? dns_name : \"<NULL>\");\n\n\tsize_t ulen = strlen(user);\n\tsize_t passlen = strlen(pass);\n\n\tif(ulen > 0xFF || passlen > 0xFF || dns_len > 0xFF) {\n\t\tproxychains_write_log(LOG_PREFIX \"error: maximum size of 255 for user/pass or domain name!\\n\");\n\t\tgoto err;\n\t}\n\n\tint len;\n\tunsigned char buff[BUFF_SIZE];\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tint v6 = ip.is_v6;\n\t\n\tswitch (pt) {\n\t\tcase RAW_TYPE: {\n\t\t\treturn SUCCESS;\n\t\t}\n\t\tbreak;\n\t\tcase HTTP_TYPE:{\n\t\t\tif(!dns_len) {\n\t\t\t\tif(!inet_ntop(v6?AF_INET6:AF_INET,ip.addr.v6,ip_buf,sizeof ip_buf)) {\n\t\t\t\t\tproxychains_write_log(LOG_PREFIX \"error: ip address conversion failed\\n\");\n\t\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t\tdns_name = ip_buf;\n\t\t\t}\n\t\t\t#define HTTP_AUTH_MAX ((0xFF * 2) + 1 + 1) /* 2 * 0xff: username and pass, plus 1 for ':' and 1 for zero terminator. */\n\t\t\tchar src[HTTP_AUTH_MAX];\n\t\t\tchar dst[(4 * HTTP_AUTH_MAX)];\n\t\t\tif(ulen) {\n\t\t\t\tsnprintf(src, sizeof(src), \"%s:%s\", user, pass);\n\t\t\t\tencode_base_64(src, dst, sizeof(dst));\n\t\t\t} else dst[0] = 0;\n\n\t\t\tuint16_t hs_port = ntohs(port);\n\t\t\tlen = snprintf((char *) buff, sizeof(buff),\n\t\t\t               \"CONNECT %s:%d HTTP/1.0\\r\\nHost: %s:%d\\r\\n%s%s%s\\r\\n\",\n\t\t\t                dns_name, hs_port,\n\t\t\t                dns_name, hs_port,\n\t\t\t                ulen ? \"Proxy-Authorization: Basic \" : dst,\n\t\t\t                dst, ulen ? \"\\r\\n\" : dst);\n\n\t\t\tif(len < 0 || len != send(sock, buff, len, 0))\n\t\t\t\tgoto err;\n\n\t\t\tlen = 0;\n\t\t\t// read header byte by byte.\n\t\t\twhile(len < BUFF_SIZE) {\n\t\t\t\tif(1 == read_n_bytes(sock, (char *) (buff + len), 1))\n\t\t\t\t\tlen++;\n\t\t\t\telse\n\t\t\t\t\tgoto err;\n\t\t\t\tif(len > 4 &&\n\t\t\t\t   buff[len - 1] == '\\n' &&\n\t\t\t\t   buff[len - 2] == '\\r' && buff[len - 3] == '\\n' && buff[len - 4] == '\\r')\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// if not ok (200) or response greather than BUFF_SIZE return BLOCKED;\n\t\t\tif(len == BUFF_SIZE || !(buff[9] == '2' && buff[10] == '0' && buff[11] == '0')) {\n\t\t\t\tPDEBUG(\"HTTP proxy blocked: buff=\\\"%s\\\"\\n\", buff);\n\t\t\t\treturn BLOCKED;\n\t\t\t}\n\n\t\t\treturn SUCCESS;\n\t\t}\n\t\tbreak;\n\t\tcase SOCKS4_TYPE:{\n\t\t\tif(v6) {\n\t\t\t\tproxychains_write_log(LOG_PREFIX \"error: SOCKS4 doesn't support ipv6 addresses\\n\");\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\tbuff[0] = 4;\t// socks version\n\t\t\tbuff[1] = 1;\t// connect command\n\t\t\tmemcpy(&buff[2], &port, 2);\t// dest port\n\t\t\tif(dns_len) {\n\t\t\t\tip.addr.v4.octet[0] = 0;\n\t\t\t\tip.addr.v4.octet[1] = 0;\n\t\t\t\tip.addr.v4.octet[2] = 0;\n\t\t\t\tip.addr.v4.octet[3] = 1;\n\t\t\t}\n\t\t\tmemcpy(&buff[4], &ip.addr.v4, 4);\t// dest host\n\t\t\tlen = ulen + 1;\t// username\n\t\t\tif(len > 1)\n\t\t\t\tmemcpy(&buff[8], user, len);\n\t\t\telse {\n\t\t\t\tbuff[8] = 0;\n\t\t\t}\n\n\t\t\t// do socksv4a dns resolution on the server\n\t\t\tif(dns_len) {\n\t\t\t\tmemcpy(&buff[8 + len], dns_name, dns_len + 1);\n\t\t\t\tlen += dns_len + 1;\n\t\t\t}\n\n\t\t\tif((len + 8) != write_n_bytes(sock, (char *) buff, (8 + len)))\n\t\t\t\tgoto err;\n\n\t\t\tif(8 != read_n_bytes(sock, (char *) buff, 8))\n\t\t\t\tgoto err;\n\n\t\t\tif(buff[0] != 0 || buff[1] != 90)\n\t\t\t\treturn BLOCKED;\n\n\t\t\treturn SUCCESS;\n\t\t}\n\t\tbreak;\n\t\tcase SOCKS5_TYPE:{\n\t\t\tint n_methods = ulen ? 2 : 1;\n\t\t\tbuff[0] = 5;\t// version\n\t\t\tbuff[1] = n_methods ;\t// number of methods\n\t\t\tbuff[2] = 0;\t// no auth method\n\t\t\tif(ulen) buff[3] = 2;    /// auth method -> username / password\n\t\t\tif(2+n_methods != write_n_bytes(sock, (char *) buff, 2+n_methods))\n\t\t\t\tgoto err;\n\n\t\t\tif(2 != read_n_bytes(sock, (char *) buff, 2))\n\t\t\t\tgoto err;\n\n\t\t\tif(buff[0] != 5 || (buff[1] != 0 && buff[1] != 2)) {\n\t\t\t\tif(buff[0] == 5 && buff[1] == 0xFF)\n\t\t\t\t\treturn BLOCKED;\n\t\t\t\telse\n\t\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\tif(buff[1] == 2) {\n\t\t\t\t// authentication\n\t\t\t\tchar in[2];\n\t\t\t\tchar out[515];\n\t\t\t\tchar *cur = out;\n\t\t\t\tsize_t c;\n\t\t\t\t*cur++ = 1;\t// version\n\t\t\t\tc = ulen & 0xFF;\n\t\t\t\t*cur++ = c;\n\t\t\t\tmemcpy(cur, user, c);\n\t\t\t\tcur += c;\n\t\t\t\tc = passlen & 0xFF;\n\t\t\t\t*cur++ = c;\n\t\t\t\tmemcpy(cur, pass, c);\n\t\t\t\tcur += c;\n\n\t\t\t\tif((cur - out) != write_n_bytes(sock, out, cur - out))\n\t\t\t\t\tgoto err;\n\n\n\t\t\t\tif(2 != read_n_bytes(sock, in, 2))\n\t\t\t\t\tgoto err;\n\t/* according to RFC 1929 the version field for the user/pass auth sub-\n\t   negotiation should be 1, which is kinda counter-intuitive, so there\n\t   are some socks5 proxies that return 5 instead. other programs like\n\t   curl work fine when the version is 5, so let's do the same and accept\n\t   either of them. */\n\t\t\t\tif(!(in[0] == 5 || in[0] == 1))\n\t\t\t\t\tgoto err;\n\t\t\t\tif(in[1] != 0)\n\t\t\t\t\treturn BLOCKED;\n\t\t\t}\n\t\t\tint buff_iter = 0;\n\t\t\tbuff[buff_iter++] = 5;\t// version\n\t\t\tbuff[buff_iter++] = 1;\t// connect\n\t\t\tbuff[buff_iter++] = 0;\t// reserved\n\n\t\t\tif(!dns_len) {\n\t\t\t\tbuff[buff_iter++] = v6 ? 4 : 1;\t// ip v4/v6\n\t\t\t\tmemcpy(buff + buff_iter, ip.addr.v6, v6?16:4);\t// dest host\n\t\t\t\tbuff_iter += v6?16:4;\n\t\t\t} else {\n\t\t\t\tbuff[buff_iter++] = 3;\t//dns\n\t\t\t\tbuff[buff_iter++] = dns_len & 0xFF;\n\t\t\t\tmemcpy(buff + buff_iter, dns_name, dns_len);\n\t\t\t\tbuff_iter += dns_len;\n\t\t\t}\n\n\t\t\tmemcpy(buff + buff_iter, &port, 2);\t// dest port\n\t\t\tbuff_iter += 2;\n\n\n\t\t\tif(buff_iter != write_n_bytes(sock, (char *) buff, buff_iter))\n\t\t\t\tgoto err;\n\n\t\t\tif(4 != read_n_bytes(sock, (char *) buff, 4))\n\t\t\t\tgoto err;\n\n\t\t\tif(buff[0] != 5 || buff[1] != 0)\n\t\t\t\tgoto err;\n\n\t\t\tswitch (buff[3]) {\n\t\t\t\tcase 1:\n\t\t\t\t\tlen = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tlen = 16;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tlen = 0;\n\t\t\t\t\tif(1 != read_n_bytes(sock, (char *) &len, 1))\n\t\t\t\t\t\tgoto err;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\tif(len + 2 != read_n_bytes(sock, (char *) buff, len + 2))\n\t\t\t\tgoto err;\n\n\t\t\treturn SUCCESS;\n\t\t}\n\t\tbreak;\n\t}\n\n\terr:\n\treturn SOCKET_ERROR;\n}\n\n#define TP \" ... \"\n#define DT \"Dynamic chain\"\n#define ST \"Strict chain\"\n#define RT \"Random chain\"\n#define RRT \"Round Robin chain\"\n\nstatic int start_chain(int *fd, proxy_data * pd, char *begin_mark) {\n\tint v6 = pd->ip.is_v6;\n\n\t*fd = socket(v6?PF_INET6:PF_INET, SOCK_STREAM, 0);\n\tif(*fd == -1)\n\t\tgoto error;\n\t\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tif(!inet_ntop(v6?AF_INET6:AF_INET,pd->ip.addr.v6,ip_buf,sizeof ip_buf))\n\t\tgoto error;\n\n\tproxychains_write_log(LOG_PREFIX \"%s \" TP \" %s:%d \",\n\t\t\t      begin_mark, ip_buf, htons(pd->port));\n\tpd->ps = PLAY_STATE;\n\tstruct sockaddr_in addr = {\n\t\t.sin_family = AF_INET,\n\t\t.sin_port = pd->port,\n\t\t.sin_addr.s_addr = (in_addr_t) pd->ip.addr.v4.as_int\n\t};\n\tstruct sockaddr_in6 addr6 = {\n\t\t.sin6_family = AF_INET6,\n\t\t.sin6_port = pd->port,\n\t};\n\tif(v6) memcpy(&addr6.sin6_addr.s6_addr, pd->ip.addr.v6, 16);\n\tif(timed_connect(*fd, (struct sockaddr *) (v6?(void*)&addr6:(void*)&addr), v6?sizeof(addr6):sizeof(addr))) {\n\t\tpd->ps = DOWN_STATE;\n\t\tgoto error1;\n\t}\n\tpd->ps = BUSY_STATE;\n\treturn SUCCESS;\n\terror1:\n\tproxychains_write_log(TP \" timeout\\n\");\n\terror:\n\tif(*fd != -1) {\n\t\tclose(*fd);\n\t\t*fd = -1;\n\t}\n\treturn SOCKET_ERROR;\n}\n\nstatic proxy_data *select_proxy(select_type how, proxy_data * pd, unsigned int proxy_count, unsigned int *offset) {\n\tunsigned int i = 0, k = 0;\n\tif(*offset >= proxy_count)\n\t\treturn NULL;\n\tswitch (how) {\n\t\tcase RANDOMLY:\n\t\t\tdo {\n\t\t\t\tk++;\n\t\t\t\ti = rand() % proxy_count;\n\t\t\t} while(pd[i].ps != PLAY_STATE && k < proxy_count * 100);\n\t\t\tbreak;\n\t\tcase FIFOLY:\n\t\t\tfor(i = *offset; i < proxy_count; i++) {\n\t\t\t\tif(pd[i].ps == PLAY_STATE) {\n\t\t\t\t\t*offset = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\tif(i >= proxy_count)\n\t\ti = 0;\n\treturn (pd[i].ps == PLAY_STATE) ? &pd[i] : NULL;\n}\n\n\nstatic void release_all(proxy_data * pd, unsigned int proxy_count) {\n\tunsigned int i;\n\tfor(i = 0; i < proxy_count; i++)\n\t\tpd[i].ps = PLAY_STATE;\n\treturn;\n}\n\nstatic void release_busy(proxy_data * pd, unsigned int proxy_count) {\n\tunsigned int i;\n\tfor(i = 0; i < proxy_count; i++)\n\t\tif(pd[i].ps == BUSY_STATE)\n\t\t\tpd[i].ps = PLAY_STATE;\n\treturn;\n}\n\nstatic unsigned int calc_alive(proxy_data * pd, unsigned int proxy_count) {\n\tunsigned int i;\n\tint alive_count = 0;\n\trelease_busy(pd, proxy_count);\n\tfor(i = 0; i < proxy_count; i++)\n\t\tif(pd[i].ps == PLAY_STATE)\n\t\t\talive_count++;\n\treturn alive_count;\n}\n\n\nstatic int chain_step(int *ns, proxy_data * pfrom, proxy_data * pto) {\n\tint retcode = -1;\n\tchar *hostname, *errmsg = 0;\n\tchar hostname_buf[MSG_LEN_MAX];\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tint v6 = pto->ip.is_v6;\n\n\tPFUNC();\n\n\tif(!v6 && proxychains_resolver >= DNSLF_RDNS_START && pto->ip.addr.v4.octet[0] == remote_dns_subnet) {\n\t\tif(!rdns_get_host_for_ip(pto->ip.addr.v4, hostname_buf)) goto usenumericip;\n\t\telse hostname = hostname_buf;\n\t} else {\n\tusenumericip:\n\t\tif(!inet_ntop(v6?AF_INET6:AF_INET,pto->ip.addr.v6,ip_buf,sizeof ip_buf)) {\n\t\t\tpto->ps = DOWN_STATE;\n\t\t\terrmsg = \"<--ip conversion error!\\n\";\n\t\t\tretcode = SOCKET_ERROR;\n\t\t\tgoto err;\n\t\t}\n\t\thostname = ip_buf;\n\t}\n\n\tproxychains_write_log(TP \" %s:%d \", hostname, htons(pto->port));\n\tretcode = tunnel_to(*ns, pto->ip, pto->port, pfrom->pt, pfrom->user, pfrom->pass);\n\tswitch (retcode) {\n\t\tcase SUCCESS:\n\t\t\tpto->ps = BUSY_STATE;\n\t\t\tbreak;\n\t\tcase BLOCKED:\n\t\t\tpto->ps = BLOCKED_STATE;\n\t\t\terrmsg = \"<--denied\\n\";\n\t\t\tgoto err;\n\t\tcase SOCKET_ERROR:\n\t\t\tpto->ps = DOWN_STATE;\n\t\t\terrmsg = \"<--socket error or timeout!\\n\";\n\t\t\tgoto err;\n\t}\n\treturn retcode;\nerr:\n\tif(errmsg) proxychains_write_log(errmsg);\n\tif(*ns != -1) close(*ns);\n\t*ns = -1;\n\treturn retcode;\n}\n\nint connect_proxy_chain(int sock, ip_type target_ip,\n\t\t\tunsigned short target_port, proxy_data * pd,\n\t\t\tunsigned int proxy_count, chain_type ct, unsigned int max_chain) {\n\tproxy_data p4;\n\tproxy_data *p1, *p2, *p3;\n\tint ns = -1;\n\tint rc = -1;\n\tunsigned int offset = 0;\n\tunsigned int alive_count = 0;\n\tunsigned int curr_len = 0;\n\tunsigned int looped = 0; // went back to start of list in RR mode\n\tunsigned int rr_loop_max = 14;\n\n\tp3 = &p4;\n\n\tPFUNC();\n\n\tagain:\n\trc = -1;\n\tDUMP_PROXY_CHAIN(pd, proxy_count);\n\n\tswitch (ct) {\n\t\tcase DYNAMIC_TYPE:\n\t\t\talive_count = calc_alive(pd, proxy_count);\n\t\t\toffset = 0;\n\t\t\tdo {\n\t\t\t\tif(!(p1 = select_proxy(FIFOLY, pd, proxy_count, &offset)))\n\t\t\t\t\tgoto error_more;\n\t\t\t} while(SUCCESS != start_chain(&ns, p1, DT) && offset < proxy_count);\n\t\t\tfor(;;) {\n\t\t\t\tp2 = select_proxy(FIFOLY, pd, proxy_count, &offset);\n\t\t\t\tif(!p2)\n\t\t\t\t\tbreak;\n\t\t\t\tif(SUCCESS != chain_step(&ns, p1, p2)) {\n\t\t\t\t\tPDEBUG(\"GOTO AGAIN 1\\n\");\n\t\t\t\t\tgoto again;\n\t\t\t\t}\n\t\t\t\tp1 = p2;\n\t\t\t}\n\t\t\t//proxychains_write_log(TP);\n\t\t\tp3->ip = target_ip;\n\t\t\tp3->port = target_port;\n\t\t\tif(SUCCESS != chain_step(&ns, p1, p3))\n\t\t\t\tgoto error;\n\t\t\tbreak;\n\n\t\tcase ROUND_ROBIN_TYPE:\n\t\t\talive_count = calc_alive(pd, proxy_count);\n\t\t\toffset = proxychains_proxy_offset;\n\t\t\tif(alive_count < max_chain)\n\t\t\t\tgoto error_more;\n\t\t\tPDEBUG(\"1:rr_offset = %d\\n\", offset);\n\t\t\t/* Check from current RR offset til end */\n\t\t\tfor (;rc != SUCCESS;) {\n\t\t\t\tif (!(p1 = select_proxy(FIFOLY, pd, proxy_count, &offset))) {\n\t\t\t\t\t/* We've reached the end of the list, go to the start */\n \t\t\t\t\toffset = 0;\n\t\t\t\t\tlooped++;\n\t\t\t\t\tif (looped > rr_loop_max) {\n\t\t\t\t\t\tproxychains_proxy_offset = 0;\n\t\t\t\t\t\tgoto error_more;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tPDEBUG(\"rr_type all proxies down, release all\\n\");\n\t\t\t\t\t\trelease_all(pd, proxy_count);\n\t\t\t\t\t\t/* Each loop we wait 10ms more */\n\t\t\t\t\t\tusleep(10000 * looped);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n \t\t\t\tPDEBUG(\"2:rr_offset = %d\\n\", offset);\n \t\t\t\trc=start_chain(&ns, p1, RRT);\n\t\t\t}\n\t\t\t/* Create rest of chain using RR */\n\t\t\tfor(curr_len = 1; curr_len < max_chain;) {\n\t\t\t\tPDEBUG(\"3:rr_offset = %d, curr_len = %d, max_chain = %d\\n\", offset, curr_len, max_chain);\n\t\t\t\tp2 = select_proxy(FIFOLY, pd, proxy_count, &offset);\n\t\t\t\tif(!p2) {\n\t\t\t\t\t/* Try from the beginning to where we started */\n\t\t\t\t\toffset = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if(SUCCESS != chain_step(&ns, p1, p2)) {\n\t\t\t\t\tPDEBUG(\"GOTO AGAIN 1\\n\");\n\t\t\t\t\tgoto again;\n\t\t\t\t} else\n\t\t\t\t\tp1 = p2;\n\t\t\t\tcurr_len++;\n\t\t\t}\n\t\t\t//proxychains_write_log(TP);\n\t\t\tp3->ip = target_ip;\n\t\t\tp3->port = target_port;\n\t\t\tproxychains_proxy_offset = offset+1;\n\t\t\tPDEBUG(\"pd_offset = %d, curr_len = %d\\n\", proxychains_proxy_offset, curr_len);\n\t\t\tif(SUCCESS != chain_step(&ns, p1, p3))\n\t\t\t\tgoto error;\n\t\t\tbreak;\n\n\t\tcase STRICT_TYPE:\n\t\t\talive_count = calc_alive(pd, proxy_count);\n\t\t\toffset = 0;\n\t\t\tif(!(p1 = select_proxy(FIFOLY, pd, proxy_count, &offset))) {\n\t\t\t\tPDEBUG(\"select_proxy failed\\n\");\n\t\t\t\tgoto error_strict;\n\t\t\t}\n\t\t\tif(SUCCESS != start_chain(&ns, p1, ST)) {\n\t\t\t\tPDEBUG(\"start_chain failed\\n\");\n\t\t\t\tgoto error_strict;\n\t\t\t}\n\t\t\twhile(offset < proxy_count) {\n\t\t\t\tif(!(p2 = select_proxy(FIFOLY, pd, proxy_count, &offset)))\n\t\t\t\t\tbreak;\n\t\t\t\tif(SUCCESS != chain_step(&ns, p1, p2)) {\n\t\t\t\t\tPDEBUG(\"chain_step failed\\n\");\n\t\t\t\t\tgoto error_strict;\n\t\t\t\t}\n\t\t\t\tp1 = p2;\n\t\t\t}\n\t\t\t//proxychains_write_log(TP);\n\t\t\tp3->ip = target_ip;\n\t\t\tp3->port = target_port;\n\t\t\tif(SUCCESS != chain_step(&ns, p1, p3))\n\t\t\t\tgoto error;\n\t\t\tbreak;\n\n\t\tcase RANDOM_TYPE:\n\t\t\talive_count = calc_alive(pd, proxy_count);\n\t\t\tif(alive_count < max_chain)\n\t\t\t\tgoto error_more;\n\t\t\tcurr_len = offset = 0;\n\t\t\tdo {\n\t\t\t\tif(!(p1 = select_proxy(RANDOMLY, pd, proxy_count, &offset)))\n\t\t\t\t\tgoto error_more;\n\t\t\t} while(SUCCESS != start_chain(&ns, p1, RT) && offset < max_chain);\n\t\t\twhile(++curr_len < max_chain) {\n\t\t\t\tif(!(p2 = select_proxy(RANDOMLY, pd, proxy_count, &offset)))\n\t\t\t\t\tgoto error_more;\n\t\t\t\tif(SUCCESS != chain_step(&ns, p1, p2)) {\n\t\t\t\t\tPDEBUG(\"GOTO AGAIN 2\\n\");\n\t\t\t\t\tgoto again;\n\t\t\t\t}\n\t\t\t\tp1 = p2;\n\t\t\t}\n\t\t\t//proxychains_write_log(TP);\n\t\t\tp3->ip = target_ip;\n\t\t\tp3->port = target_port;\n\t\t\tif(SUCCESS != chain_step(&ns, p1, p3))\n\t\t\t\tgoto error;\n\n\t}\n\n\tproxychains_write_log(TP \" OK\\n\");\n\tdup2(ns, sock);\n\tclose(ns);\n\treturn 0;\n\terror:\n\tif(ns != -1)\n\t\tclose(ns);\n\terrno = ECONNREFUSED;\t// for nmap ;)\n\treturn -1;\n\n\terror_more:\n\tproxychains_write_log(\"\\n!!!need more proxies!!!\\n\");\n\terror_strict:\n\tPDEBUG(\"error\\n\");\n\t\n\trelease_all(pd, proxy_count);\n\tif(ns != -1)\n\t\tclose(ns);\n\terrno = ETIMEDOUT;\n\treturn -1;\n}\n\nstatic pthread_mutex_t servbyname_lock;\nvoid core_initialize(void) {\n\tMUTEX_INIT(&servbyname_lock);\n}\n\nvoid core_unload(void) {\n\tMUTEX_DESTROY(&servbyname_lock);\n}\n\nstatic void gethostbyname_data_setstring(struct gethostbyname_data* data, char* name) {\n\tsnprintf(data->addr_name, sizeof(data->addr_name), \"%s\", name);\n\tdata->hostent_space.h_name = data->addr_name;\n}\n\nextern ip_type4 hostsreader_get_numeric_ip_for_name(const char* name);\nstruct hostent* proxy_gethostbyname_old(const char *name)\n{\n\tstatic struct hostent hostent_space;\n\tstatic in_addr_t resolved_addr;\n\tstatic char* resolved_addr_p;\n\tstatic char addr_name[256];\n\n\tint pipe_fd[2];\n\tchar buff[256];\n\tin_addr_t addr;\n\tpid_t pid;\n\tint status, ret;\n\tsize_t l;\n\tstruct hostent* hp;\n\n\thostent_space.h_addr_list = &resolved_addr_p;\n\t*hostent_space.h_addr_list = (char*)&resolved_addr;\n\tresolved_addr = 0;\n\n\tif(pc_isnumericipv4(name)) {\n\t\tstrcpy(buff, name);\n\t\tgoto got_buff;\n\t}\n\n\tgethostname(buff,sizeof(buff));\n\tif(!strcmp(buff,name))\n\t\tgoto got_buff;\n\n\tmemset(buff, 0, sizeof(buff));\n\n\t// TODO: this works only once, so cache it  ...\n\t// \t later\n\twhile ((hp=gethostent()))\n\t\tif (!strcmp(hp->h_name,name))\n\t\t\treturn hp;\n#ifdef HAVE_PIPE2\n\tret = pipe2(pipe_fd, O_CLOEXEC);\n#else\n\tret = pipe(pipe_fd);\n\tif(ret == 0) {\n\t\tfcntl(pipe_fd[0], F_SETFD, FD_CLOEXEC);\n\t\tfcntl(pipe_fd[1], F_SETFD, FD_CLOEXEC);\n\t}\n#endif\n\n\tif(ret)\n\t\tgoto err;\n\tpid = fork();\n\tswitch(pid) {\n\n\t\tcase 0: // child\n\t\t\tproxychains_write_log(\"|DNS-request| %s \\n\", name);\n\t\t\tclose(pipe_fd[0]);\n\t\t\tdup2(pipe_fd[1],1);\n\t\t\tclose(pipe_fd[1]);\n\n\t\t//\tputenv(\"LD_PRELOAD=\");\n\t\t\texeclp(\"proxyresolv\",\"proxyresolv\",name,NULL);\n\t\t\tperror(\"can't exec proxyresolv\");\n\t\t\texit(2);\n\n\t\tcase -1: //error\n\t\t\tclose(pipe_fd[0]);\n\t\t\tclose(pipe_fd[1]);\n\t\t\tperror(\"can't fork\");\n\t\t\tgoto err;\n\n\t\tdefault:\n\t\t\tclose(pipe_fd[1]);\n\t\t\twaitpid(pid, &status, 0);\n\t\t\tbuff[0] = 0;\n\t\t\tread(pipe_fd[0],&buff,sizeof(buff));\n\t\t\tclose(pipe_fd[0]);\ngot_buff:\n\t\t\tl = strlen(buff);\n\t\t\tif (!l) goto err_dns;\n\t\t\tif (buff[l-1] == '\\n') buff[l-1] = 0;\n\t\t\taddr = inet_addr(buff);\n\t\t\tif (addr == (in_addr_t) (-1))\n\t\t\t\tgoto err_dns;\n\t\t\tmemcpy(*(hostent_space.h_addr_list),\n\t\t\t\t\t\t&addr ,sizeof(struct in_addr));\n\t\t\thostent_space.h_name = addr_name;\n\t\t\tsnprintf(addr_name, sizeof addr_name, \"%s\", buff);\n\t\t\thostent_space.h_length = sizeof (in_addr_t);\n\t\t\thostent_space.h_addrtype = AF_INET;\n\t}\n\tproxychains_write_log(\"|DNS-response| %s is %s\\n\",\n\t\t\tname, inet_ntoa(*(struct in_addr*)&addr));\n\treturn &hostent_space;\nerr_dns:\n\tproxychains_write_log(\"|DNS-response|: %s lookup error\\n\", name);\nerr:\n\treturn NULL;\n}\n\nstruct hostent *proxy_gethostbyname(const char *name, struct gethostbyname_data* data) {\n\tPFUNC();\n\tchar buff[256];\n\n\tdata->resolved_addr_p[0] = (char *) &data->resolved_addr;\n\tdata->resolved_addr_p[1] = NULL;\n\n\tdata->hostent_space.h_addr_list = data->resolved_addr_p;\n\t// let aliases point to the NULL member, mimicking an empty list.\n\tdata->hostent_space.h_aliases = &data->resolved_addr_p[1];\n\n\tdata->resolved_addr = 0;\n\tdata->hostent_space.h_addrtype = AF_INET;\n\tdata->hostent_space.h_length = sizeof(in_addr_t);\n\n\tif(pc_isnumericipv4(name)) {\n\t\tdata->resolved_addr = inet_addr(name);\n\t\tgoto retname;\n\t}\n\n\tgethostname(buff, sizeof(buff));\n\n\tif(!strcmp(buff, name)) {\n\t\tdata->resolved_addr = inet_addr(buff);\n\t\tif(data->resolved_addr == (in_addr_t) (-1))\n\t\t\tdata->resolved_addr = (in_addr_t) (IPT4_LOCALHOST.as_int);\n\t\tgoto retname;\n\t}\n\n\t// this iterates over the \"known hosts\" db, usually /etc/hosts\n\tip_type4 hdb_res = hostsreader_get_numeric_ip_for_name(name);\n\tif(hdb_res.as_int != IPT4_INVALID.as_int) {\n\t\tdata->resolved_addr = hdb_res.as_int;\n\t\tgoto retname;\n\t}\n\t\n\tdata->resolved_addr = rdns_get_ip_for_host((char*) name, strlen(name)).as_int;\n\tif(data->resolved_addr == (in_addr_t) IPT4_INVALID.as_int) return NULL;\n\n\tretname:\n\n\tgethostbyname_data_setstring(data, (char*) name);\n\t\n\tPDEBUG(\"return hostent space\\n\");\n\t\n\treturn &data->hostent_space;\n}\n\nstruct addrinfo_data {\n\tstruct addrinfo addrinfo_space;\n\tstruct sockaddr_storage sockaddr_space;\n\tchar addr_name[256];\n};\n\nvoid proxy_freeaddrinfo(struct addrinfo *res) {\n\tPFUNC();\n\tfree(res);\n}\n\nstatic int mygetservbyname_r(const char* name, const char* proto, struct servent* result_buf,\n\t\t\t   char* buf, size_t buflen, struct servent** result) {\n\tPFUNC();\n#ifdef HAVE_GNU_GETSERVBYNAME_R\n\tPDEBUG(\"using host getservbyname_r\\n\");\n\treturn getservbyname_r(name, proto, result_buf, buf, buflen, result);\n#endif\n\tstruct servent *res;\n\tint ret;\n\t(void) buf; (void) buflen;\n\tMUTEX_LOCK(&servbyname_lock);\n\tres = getservbyname(name, proto);\n\tif(res) {\n\t\t*result_buf = *res;\n\t\t*result = result_buf;\n\t\tret = 0;\n\t} else {\n\t\t*result = NULL;\n\t\tret = ENOENT;\n\t}\n\tMUTEX_UNLOCK(&servbyname_lock);\n\treturn ret;\n}\n\nstatic int looks_like_numeric_ipv6(const char *node)\n{\n\tif(!strchr(node, ':')) return 0;\n\tconst char* p= node;\n\twhile(1) switch(*(p++)) {\n\t\tcase 0: return 1;\n\t\tcase ':': case '.':\n\t\tcase '0': case '1': case '2': case '3': case '4':\n\t\tcase '5': case '6': case '7': case '8': case '9':\n\t\tcase 'A': case 'B': case 'C': case 'D': case 'E': case 'F':\n\t\tcase 'a': case 'b': case 'c': case 'd': case 'e': case 'f':\n\t\t\tbreak;\n\t\tdefault: return 0;\n\t}\n}\n\nstatic int my_inet_aton(const char *node, struct addrinfo_data* space)\n{\n\tint ret;\n\t((struct sockaddr_in *) &space->sockaddr_space)->sin_family = AF_INET;\n\tret = inet_aton(node, &((struct sockaddr_in *) &space->sockaddr_space)->sin_addr);\n\tif(ret || !looks_like_numeric_ipv6(node)) return ret;\n\tret = inet_pton(AF_INET6, node, &((struct sockaddr_in6 *) &space->sockaddr_space)->sin6_addr);\n\tif(ret) ((struct sockaddr_in6 *) &space->sockaddr_space)->sin6_family = AF_INET6;\n\treturn ret;\n}\n\nint proxy_getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) {\n\tstruct gethostbyname_data ghdata;\n\tstruct addrinfo_data *space;\n\tstruct servent *se = NULL;\n\tstruct hostent *hp = NULL;\n\tstruct servent se_buf;\n\tstruct addrinfo *p;\n\tchar buf[1024];\n\tint port, af = AF_INET;\n\n\tPDEBUG(\"proxy_getaddrinfo node:%s service: %s, flags: %d\\n\",\n\t\tnode?node:\"\",service?service:\"\",hints?(int)hints->ai_flags:0);\n\n\tspace = calloc(1, sizeof(struct addrinfo_data));\n\tif(!space) return EAI_MEMORY;\n\n\tif(node && !my_inet_aton(node, space)) {\n\t\t/* some folks (nmap) use getaddrinfo() with AI_NUMERICHOST to check whether a string\n\t\t   containing a numeric ip was passed. we must return failure in that case. */\n\t\tif(hints && (hints->ai_flags & AI_NUMERICHOST)) {\nerr_nn:\n\t\t\tfree(space);\n\t\t\treturn EAI_NONAME;\n\t\t}\n\t\tif(proxychains_resolver == DNSLF_FORKEXEC)\n\t\t\thp = proxy_gethostbyname_old(node);\n\t\telse\n\t\t\thp = proxy_gethostbyname(node, &ghdata);\n\n\t\tif(hp)\n\t\t\tmemcpy(&((struct sockaddr_in *) &space->sockaddr_space)->sin_addr,\n\t\t\t       *(hp->h_addr_list), sizeof(in_addr_t));\n\t\telse\n\t\t\tgoto err_nn;\n\t} else if(node) {\n\t\taf = ((struct sockaddr_in *) &space->sockaddr_space)->sin_family;\n\t} else if(!node && !(hints->ai_flags & AI_PASSIVE)) {\n\t\taf = ((struct sockaddr_in *) &space->sockaddr_space)->sin_family = AF_INET;\n\t\tmemcpy(&((struct sockaddr_in *) &space->sockaddr_space)->sin_addr,\n\t\t       \"\\177\\0\\0\\1\", 4);\n\t}\n\tif(service) mygetservbyname_r(service, NULL, &se_buf, buf, sizeof(buf), &se);\n\n\tport = se ? se->s_port : htons(atoi(service ? service : \"0\"));\n\tif(af == AF_INET)\n\t\t((struct sockaddr_in *) &space->sockaddr_space)->sin_port = port;\n\telse\n\t\t((struct sockaddr_in6 *) &space->sockaddr_space)->sin6_port = port;\n\n\t*res = p = &space->addrinfo_space;\n\tassert((size_t)p == (size_t) space);\n\n\tp->ai_addr = (void*) &space->sockaddr_space;\n\tif(node)\n\t\tsnprintf(space->addr_name, sizeof(space->addr_name), \"%s\", node);\n\tp->ai_canonname = space->addr_name;\n\tp->ai_next = NULL;\n\tp->ai_family = space->sockaddr_space.ss_family = af;\n\tp->ai_addrlen = af == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);\n\n\tif(hints) {\n\t\tp->ai_socktype = hints->ai_socktype;\n\t\tp->ai_flags = hints->ai_flags;\n\t\tp->ai_protocol = hints->ai_protocol;\n\t\tif(!p->ai_socktype && p->ai_protocol == IPPROTO_TCP)\n\t\t\tp->ai_socktype = SOCK_STREAM;\n\t} else {\n#ifndef AI_V4MAPPED\n#define AI_V4MAPPED 0\n#endif\n\t\tp->ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG);\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "src/core.h",
    "content": "/***************************************************************************\n                          core.h  -  description\n                             -------------------\n    begin                : Tue May 14 2002\n    copyright          :  netcreature (C) 2002\n    email                 : netcreature@users.sourceforge.net\n ***************************************************************************\n ***************************************************************************\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n ***************************************************************************/\n\n#include <unistd.h>\n#include <stdint.h>\n#include <netinet/in.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netdb.h>\n\n#ifndef __CORE_HEADER\n#define __CORE_HEADER\n#define     MAX_LOCALNET 64\n#define     MAX_DNAT 64\n\n#include \"ip_type.h\"\n\n/*error codes*/\ntypedef enum {\n\tSUCCESS=0,\n\tMEMORY_FAIL,        // malloc failed\n\tSOCKET_ERROR,  // look errno for more\n\tCHAIN_DOWN,    // no proxy in chain responds to tcp\n\tCHAIN_EMPTY,   //  if proxy_count = 0\n\tBLOCKED  //  target's port blocked on last proxy in the chain\n} ERR_CODE;\n\ntypedef enum {\n\tHTTP_TYPE,\n\tSOCKS4_TYPE,\n\tSOCKS5_TYPE,\n\tRAW_TYPE\n} proxy_type;\n\ntypedef enum {\n\tDYNAMIC_TYPE,\n\tSTRICT_TYPE,\n\tRANDOM_TYPE,\n\tROUND_ROBIN_TYPE\n} chain_type;\n\ntypedef enum {\n\tPLAY_STATE,\n\tDOWN_STATE,\n\tBLOCKED_STATE,\n\tBUSY_STATE\n} proxy_state;\n\ntypedef enum {\n\tRANDOMLY,\n\tFIFOLY\n} select_type;\n\ntypedef struct {\n\tsa_family_t family;\n\tunsigned short port;\n\tunion {\n\t\tstruct {\n\t\t\tstruct in_addr in_addr;\n\t\t\tstruct in_addr in_mask;\n\t\t};\n\t\tstruct {\n\t\t\tstruct in6_addr in6_addr;\n\t\t\tunsigned char in6_prefix;\n\t\t};\n\t};\n} localaddr_arg;\n\ntypedef struct {\n\tstruct in_addr orig_dst, new_dst;\n\tunsigned short orig_port, new_port;\n} dnat_arg;\n\ntypedef struct {\n\tip_type ip;\n\tunsigned short port;\n\tproxy_type pt;\n\tproxy_state ps;\n\tchar user[256];\n\tchar pass[256];\n} proxy_data;\n\nint connect_proxy_chain (int sock, ip_type target_ip, unsigned short target_port,\n\t\t\t proxy_data * pd, unsigned int proxy_count, chain_type ct,\n\t\t\t unsigned int max_chain );\n\nvoid proxychains_write_log(char *str, ...);\n\ntypedef int (*close_t)(int);\ntypedef int (*close_range_t)(unsigned, unsigned, int);\ntypedef int (*connect_t)(int, const struct sockaddr *, socklen_t);\ntypedef struct hostent* (*gethostbyname_t)(const char *);\ntypedef void (*freeaddrinfo_t)(struct addrinfo *);\ntypedef struct hostent *(*gethostbyaddr_t) (const void *, socklen_t, int);\n\ntypedef int (*getaddrinfo_t)(const char *, const char *, const struct addrinfo *, \n\t\t\t     struct addrinfo **);\n\ntypedef int (*getnameinfo_t) (const struct sockaddr *, socklen_t, char *, \n\t\t\t      GN_NODELEN_T, char *, GN_SERVLEN_T, GN_FLAGS_T);\n\ntypedef ssize_t (*sendto_t) (int sockfd, const void *buf, size_t len, int flags,\n\t\t\t     const struct sockaddr *dest_addr, socklen_t addrlen);\n\n\n\nextern connect_t true_connect;\nextern gethostbyname_t true_gethostbyname;\nextern getaddrinfo_t true_getaddrinfo;\nextern freeaddrinfo_t true_freeaddrinfo;\nextern getnameinfo_t true_getnameinfo;\nextern gethostbyaddr_t true_gethostbyaddr;\n\nstruct gethostbyname_data {\n\tstruct hostent hostent_space;\n\tin_addr_t resolved_addr;\n\tchar *resolved_addr_p[2];\n\tchar addr_name[256];\n};\n\nstruct hostent* proxy_gethostbyname(const char *name, struct gethostbyname_data *data);\nstruct hostent* proxy_gethostbyname_old(const char *name);\n\nint proxy_getaddrinfo(const char *node, const char *service, \n\t\t      const struct addrinfo *hints, struct addrinfo **res);\nvoid proxy_freeaddrinfo(struct addrinfo *res);\n\nvoid core_initialize(void);\nvoid core_unload(void);\n\n#include \"debug.h\"\n\n#endif\n\n//RcB: DEP \"core.c\"\n//RcB: DEP \"libproxychains.c\"\n//RcB: LINK \"-Wl,--no-as-needed -ldl -lpthread\"\n\n"
  },
  {
    "path": "src/daemon/daemon.c",
    "content": "/*\n   proxychains-ng DNS daemon\n\n   Copyright (C) 2020 rofl0r.\n\n*/\n\n#undef _GNU_SOURCE\n#define _GNU_SOURCE\n#include <unistd.h>\n#define _POSIX_C_SOURCE 200809L\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <pthread.h>\n#include <signal.h>\n#include <sys/select.h>\n#include <arpa/inet.h>\n#include <errno.h>\n#include <limits.h>\n#include \"udpserver.h\"\n#include \"sblist.h\"\n#include \"hsearch.h\"\n#include \"../remotedns.h\"\n#include \"../ip_type.h\"\n\n#ifndef MAX\n#define MAX(x, y) ((x) > (y) ? (x) : (y))\n#endif\n\nstatic struct htab *ip_lookup_table;\nstatic sblist *hostnames;\nstatic unsigned remote_subnet;\nstatic const struct server* server;\n\n#ifndef CONFIG_LOG\n#define CONFIG_LOG 1\n#endif\n#if CONFIG_LOG\n/* we log to stderr because it's not using line buffering, i.e. malloc which would need\n   locking when called from different threads. for the same reason we use dprintf,\n   which writes directly to an fd. */\n#define dolog(...) dprintf(2, __VA_ARGS__)\n#else\nstatic void dolog(const char* fmt, ...) { }\n#endif\n\nstatic char* my_inet_ntoa(unsigned char *ip_buf_4_bytes, char *outbuf_16_bytes) {\n\tunsigned char *p;\n\tchar *o = outbuf_16_bytes;\n\tunsigned char n;\n\tfor(p = ip_buf_4_bytes; p < ip_buf_4_bytes + 4; p++) {\n\t\tn = *p;\n\t\tif(*p >= 100) {\n\t\t\tif(*p >= 200)\n\t\t\t\t*(o++) = '2';\n\t\t\telse\n\t\t\t\t*(o++) = '1';\n\t\t\tn %= 100;\n\t\t}\n\t\tif(*p >= 10) {\n\t\t\t*(o++) = (n / 10) + '0';\n\t\t\tn %= 10;\n\t\t}\n\t\t*(o++) = n + '0';\n\t\t*(o++) = '.';\n\t}\n\to[-1] = 0;\n\treturn outbuf_16_bytes;\n}\n\n\n/* buf needs to be long enough for an ipv6 addr, i.e. INET6_ADDRSTRLEN + 1 */\nstatic char* ipstr(union sockaddr_union *su, char* buf) {\n\tint af = SOCKADDR_UNION_AF(su);\n\tvoid *ipdata = SOCKADDR_UNION_ADDRESS(su);\n\tinet_ntop(af, ipdata, buf, INET6_ADDRSTRLEN+1);\n\tchar portbuf[7];\n\tsnprintf(portbuf, sizeof portbuf, \":%u\", (unsigned) ntohs(SOCKADDR_UNION_PORT(su)));\n\tstrcat(buf, portbuf);\n\treturn buf;\n}\n\nstatic int usage(char *a0) {\n\tdprintf(2,\n\t\t\"Proxychains-NG remote dns daemon\\n\"\n\t\t\"--------------------------------\\n\"\n\t\t\"usage: %s -i listenip -p port -r remotesubnet\\n\"\n\t\t\"all arguments are optional.\\n\"\n\t\t\"by default listenip is 127.0.0.1, port 1053 and remotesubnet 224.\\n\\n\", a0\n\t);\n\treturn 1;\n}\n\nunsigned index_from_ip(ip_type4 internalip) {\n\tip_type4 tmp = internalip;\n\tuint32_t ret;\n\tret = tmp.octet[3] + (tmp.octet[2] << 8) + (tmp.octet[1] << 16);\n\tret -= 1;\n\treturn ret;\n}\n\nchar *host_from_ip(ip_type4 internalip) {\n\tchar *res = NULL;\n\tunsigned index = index_from_ip(internalip);\n\tif(index < sblist_getsize(hostnames)) {\n\t\tchar **tmp = sblist_get(hostnames, index);\n\t\tif(tmp && *tmp) res = *tmp;\n\t}\n\treturn res;\n}\n\nip_type4 get_ip_from_index(unsigned index) {\n\tip_type4 ret;\n\tindex++; // so we can start at .0.0.1\n\tif(index > 0xFFFFFF)\n\t\treturn IPT4_INVALID;\n\tret.octet[0] = remote_subnet & 0xFF;\n\tret.octet[1] = (index & 0xFF0000) >> 16;\n\tret.octet[2] = (index & 0xFF00) >> 8;\n\tret.octet[3] = index & 0xFF;\n\treturn ret;\n}\n\nip_type4 get_ip(char* hn) {\n\thtab_value *v = htab_find(ip_lookup_table, hn);\n\tif(v) return get_ip_from_index(v->n);\n\tchar *n = strdup(hn);\n\tif(!n) return IPT4_INVALID;\n\tif(!sblist_add(hostnames, &n)) {\n\to_out:;\n\t\tfree(n);\n\t\treturn IPT4_INVALID;\n\t}\n\tif(!htab_insert(ip_lookup_table, n, HTV_N(sblist_getsize(hostnames)-1))) {\n\t\tsblist_delete(hostnames, sblist_getsize(hostnames)-1);\n\t\tgoto o_out;\n\t}\n\treturn get_ip_from_index(sblist_getsize(hostnames)-1);\n}\n\nint main(int argc, char** argv) {\n\tint ch;\n\tconst char *listenip = \"127.0.0.1\";\n\tunsigned port = 1053;\n\tremote_subnet = 224;\n\twhile((ch = getopt(argc, argv, \":r:i:p:\")) != -1) {\n\t\tswitch(ch) {\n\t\t\tcase 'r':\n\t\t\t\tremote_subnet = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tlistenip = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tport = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase ':':\n\t\t\t\tdprintf(2, \"error: option -%c requires an operand\\n\", optopt);\n\t\t\t\t/* fall through */\n\t\t\tcase '?':\n\t\t\t\treturn usage(argv[0]);\n\t\t}\n\t}\n\tsignal(SIGPIPE, SIG_IGN);\n\tstruct server s;\n\tif(server_setup(&s, listenip, port)) {\n\t\tperror(\"server_setup\");\n\t\treturn 1;\n\t}\n\tserver = &s;\n\n\tip_lookup_table = htab_create(64);\n\thostnames = sblist_new(sizeof(char*), 64);\n\n\twhile(1) {\n\t\tstruct client c;\n\t\tchar ipstr_buf[INET6_ADDRSTRLEN+6+1];\n\t\tchar ip4str_buf[16];\n\t\tstruct at_msg msg, out;\n\t\tsize_t msgl = sizeof(msg);\n\t\tint failed = 0;\n\n#define FAIL() do { failed=1; goto sendresp; } while(0)\n\n\t\tif(server_waitclient(&s, &c, &msg, &msgl)) continue;\n\t\tmsg.h.datalen = ntohs(msg.h.datalen);\n\t\tif(msgl != sizeof(msg.h)+msg.h.datalen) {\n\t\t\tdolog(\"%s: invalid datalen\\n\", ipstr(&c.addr, ipstr_buf));\n\t\t\tFAIL();\n\t\t}\n\n\t\tout.h.msgtype = msg.h.msgtype;\n\t\tif(msg.h.msgtype == ATM_GETIP) {\n\t\t\tif(!memchr(msg.m.host, 0, msg.h.datalen)) {\n\t\t\t\tdolog(\"%s: nul terminator missing\\n\", ipstr(&c.addr, ipstr_buf));\n\t\t\t\tFAIL();\n\t\t\t}\n\t\t\tout.h.datalen = sizeof(ip_type4);\n\t\t\tout.m.ip = get_ip(msg.m.host);\n\t\t\tfailed = !memcmp(&out.m.ip, &IPT4_INVALID, 4);\n\t\t\tdolog(\"%s requested ip for %s (%s)\\n\", ipstr(&c.addr, ipstr_buf),\n\t\t\t      msg.m.host, failed?\"FAIL\":my_inet_ntoa((void*)&out.m.ip, ip4str_buf));\n\t\t\tif(failed) FAIL();\n\t\t} else if (msg.h.msgtype == ATM_GETNAME) {\n\t\t\tif(msg.h.datalen != 4) {\n\t\t\t\tdolog(\"%s: invalid len for getname request\\n\", ipstr(&c.addr, ipstr_buf));\n\t\t\t\tFAIL();\n\t\t\t}\n\t\t\tchar *hn = host_from_ip(msg.m.ip);\n\t\t\tif(hn) {\n\t\t\t\tsize_t l = strlen(hn);\n\t\t\t\tmemcpy(out.m.host, hn, l+1);\n\t\t\t\tout.h.datalen = l+1;\n\t\t\t}\n\t\t\tdolog(\"%s requested name for %s (%s)\\n\", ipstr(&c.addr, ipstr_buf),\n\t\t\t      my_inet_ntoa((void*) &msg.m.ip, ip4str_buf), hn?hn:\"FAIL\");\n\t\t\tif(!hn) FAIL();\n\t\t} else {\n\t\t\tdolog(\"%s: unknown request %u\\n\", ipstr(&c.addr, ipstr_buf),\n\t\t\t      (unsigned) msg.h.msgtype);\n\t\t}\n\tsendresp:;\n\t\tif(failed) {\n\t\t\tout.h.msgtype = ATM_FAIL;\n\t\t\tout.h.datalen = 0;\n\t\t}\n\t\tunsigned short dlen = out.h.datalen;\n\t\tout.h.datalen = htons(dlen);\n\t\tsendto(server->fd, &out, sizeof(out.h)+dlen, 0, (void*) &c.addr, SOCKADDR_UNION_LENGTH(&c.addr));\n\t}\n}\n"
  },
  {
    "path": "src/daemon/hsearch.c",
    "content": "/*\nmusl license, hsearch.c originally written by Szabolcs Nagy\n\nCopyright © 2005-2020 Rich Felker, et al.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#include <stdlib.h>\n#include <string.h>\n#include \"hsearch.h\"\n\n/*\nopen addressing hash table with 2^n table size\nquadratic probing is used in case of hash collision\ntab indices and hash are size_t\nafter resize fails with ENOMEM the state of tab is still usable\n*/\n\ntypedef struct htab_entry {\n\tchar *key;\n\thtab_value data;\n} htab_entry;\n\nstruct elem {\n\thtab_entry item;\n\tsize_t hash;\n};\n\nstruct htab {\n\tstruct elem *elems;\n\tsize_t mask;\n\tsize_t used;\n};\n\n#define MINSIZE 8\n#define MAXSIZE ((size_t)-1/2 + 1)\n\nstatic size_t keyhash(char *k)\n{\n\tunsigned char *p = (void *)k;\n\tsize_t h = 0;\n\n\twhile (*p)\n\t\th = 31*h + *p++;\n\treturn h;\n}\n\nstatic int resize(struct htab *htab, size_t nel)\n{\n\tsize_t newsize;\n\tsize_t i, j;\n\tstruct elem *e, *newe;\n\tstruct elem *oldtab = htab->elems;\n\tstruct elem *oldend = htab->elems + htab->mask + 1;\n\n\tif (nel > MAXSIZE)\n\t\tnel = MAXSIZE;\n\tfor (newsize = MINSIZE; newsize < nel; newsize *= 2);\n\thtab->elems = calloc(newsize, sizeof *htab->elems);\n\tif (!htab->elems) {\n\t\thtab->elems = oldtab;\n\t\treturn 0;\n\t}\n\thtab->mask = newsize - 1;\n\tif (!oldtab)\n\t\treturn 1;\n\tfor (e = oldtab; e < oldend; e++)\n\t\tif (e->item.key) {\n\t\t\tfor (i=e->hash,j=1; ; i+=j++) {\n\t\t\t\tnewe = htab->elems + (i & htab->mask);\n\t\t\t\tif (!newe->item.key)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t*newe = *e;\n\t\t}\n\tfree(oldtab);\n\treturn 1;\n}\n\nstatic struct elem *lookup(struct htab *htab, char *key, size_t hash)\n{\n\tsize_t i, j;\n\tstruct elem *e;\n\n\tfor (i=hash,j=1; ; i+=j++) {\n\t\te = htab->elems + (i & htab->mask);\n\t\tif (!e->item.key ||\n\t\t    (e->hash==hash && strcmp(e->item.key, key)==0))\n\t\t\tbreak;\n\t}\n\treturn e;\n}\n\nstruct htab *htab_create(size_t nel)\n{\n\tstruct htab *r = calloc(1, sizeof *r);\n\tif(r && !resize(r, nel)) {\n\t\tfree(r);\n\t\tr = 0;\n\t}\n\treturn r;\n}\n\nvoid htab_destroy(struct htab *htab)\n{\n\tfree(htab->elems);\n\tfree(htab);\n}\n\nstatic htab_entry *htab_find_item(struct htab *htab, char* key)\n{\n\tsize_t hash = keyhash(key);\n\tstruct elem *e = lookup(htab, key, hash);\n\n\tif (e->item.key) {\n\t\treturn &e->item;\n\t}\n\treturn 0;\n}\n\nhtab_value* htab_find(struct htab *htab, char* key)\n{\n\thtab_entry *i = htab_find_item(htab, key);\n\tif(i) return &i->data;\n\treturn 0;\n}\n\nint htab_delete(struct htab *htab, char* key)\n{\n\thtab_entry *i = htab_find_item(htab, key);\n\tif(!i) return 0;\n\ti->key = 0;\n\treturn 1;\n}\n\nint htab_insert(struct htab *htab, char* key, htab_value value)\n{\n\tsize_t hash = keyhash(key);\n\tstruct elem *e = lookup(htab, key, hash);\n\tif(e->item.key) {\n\t\t/* it's not allowed to overwrite existing data */\n\t\treturn 0;\n\t}\n\n\te->item.key = key;\n\te->item.data = value;\n\te->hash = hash;\n\tif (++htab->used > htab->mask - htab->mask/4) {\n\t\tif (!resize(htab, 2*htab->used)) {\n\t\t\thtab->used--;\n\t\t\te->item.key = 0;\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n}\n\nsize_t htab_next(struct htab *htab, size_t iterator, char** key, htab_value **v)\n{\n\tsize_t i;\n\tfor(i=iterator;i<htab->mask+1;++i) {\n\t\tstruct elem *e = htab->elems + i;\n\t\tif(e->item.key) {\n\t\t\t*key = e->item.key;\n\t\t\t*v = &e->item.data;\n\t\t\treturn i+1;\n\t\t}\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "src/daemon/hsearch.h",
    "content": "#ifndef HSEARCH_H\n#define HSEARCH_H\n\n#include <stdlib.h>\n\ntypedef union htab_value {\n\tvoid *p;\n\tsize_t n;\n} htab_value;\n\n#define HTV_N(N) (htab_value) {.n = N}\n#define HTV_P(P) (htab_value) {.p = P}\n\nstruct htab * htab_create(size_t);\nvoid htab_destroy(struct htab *);\nhtab_value* htab_find(struct htab *, char* key);\nint htab_insert(struct htab *, char*, htab_value);\nint htab_delete(struct htab *htab, char* key);\nsize_t htab_next(struct htab *, size_t iterator, char** key, htab_value **v);\n\n#endif\n"
  },
  {
    "path": "src/daemon/sblist.c",
    "content": "#undef _POSIX_C_SOURCE\n#define _POSIX_C_SOURCE 200809L\n#include \"sblist.h\"\n#include <limits.h>\n#include <stdlib.h>\n#include <string.h>\n#define MY_PAGE_SIZE 4096\n\nsblist* sblist_new(size_t itemsize, size_t blockitems) {\n\tsblist* ret = (sblist*) malloc(sizeof(sblist));\n\tsblist_init(ret, itemsize, blockitems);\n\treturn ret;\n}\n\nstatic void sblist_clear(sblist* l) {\n\tl->items = NULL;\n\tl->capa = 0;\n\tl->count = 0;\n}\n\nvoid sblist_init(sblist* l, size_t itemsize, size_t blockitems) {\n\tif(l) {\n\t\tl->blockitems = blockitems ? blockitems : MY_PAGE_SIZE / itemsize;\n\t\tl->itemsize = itemsize;\n\t\tsblist_clear(l);\n\t}\n}\n\nvoid sblist_free_items(sblist* l) {\n\tif(l) {\n\t\tif(l->items) free(l->items);\n\t\tsblist_clear(l);\n\t}\n}\n\nvoid sblist_free(sblist* l) {\n\tif(l) {\n\t\tsblist_free_items(l);\n\t\tfree(l);\n\t}\n}\n\nchar* sblist_item_from_index(sblist* l, size_t idx) {\n\treturn l->items + (idx * l->itemsize);\n}\n\nvoid* sblist_get(sblist* l, size_t item) {\n\tif(item < l->count) return (void*) sblist_item_from_index(l, item);\n\treturn NULL;\n}\n\nint sblist_set(sblist* l, void* item, size_t pos) {\n\tif(pos >= l->count) return 0;\n\tmemcpy(sblist_item_from_index(l, pos), item, l->itemsize);\n\treturn 1;\n}\n\nint sblist_grow_if_needed(sblist* l) {\n\tchar* temp;\n\tif(l->count == l->capa) {\n\t\ttemp = realloc(l->items, (l->capa + l->blockitems) * l->itemsize);\n\t\tif(!temp) return 0;\n\t\tl->capa += l->blockitems;\n\t\tl->items = temp;\n\t}\n\treturn 1;\n}\n\nint sblist_add(sblist* l, void* item) {\n\tif(!sblist_grow_if_needed(l)) return 0;\n\tl->count++;\n\treturn sblist_set(l, item, l->count - 1);\n}\n"
  },
  {
    "path": "src/daemon/sblist.h",
    "content": "#ifndef SBLIST_H\n#define SBLIST_H\n\n/* this file is part of libulz, as of commit 8ab361a27743aaf025323ee43b8b8876dc054fdd\n   modified for direct inclusion in microsocks. */\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stddef.h>\n/*\n * simple buffer list.\n * \n * this thing here is basically a generic dynamic array\n * will realloc after every blockitems inserts\n * can store items of any size.\n * \n * so think of it as a by-value list, as opposed to a typical by-ref list.\n * you typically use it by having some struct on the stack, and pass a pointer\n * to sblist_add, which will copy the contents into its internal memory.\n * \n */\n\ntypedef struct {\n\tsize_t itemsize;\n\tsize_t blockitems;\n\tsize_t count;\n\tsize_t capa;\n\tchar* items;\n} sblist;\n\n#define sblist_getsize(X) ((X)->count)\n#define sblist_get_count(X) ((X)->count)\n#define sblist_empty(X) ((X)->count == 0)\n\n// for dynamic style\nsblist* sblist_new(size_t itemsize, size_t blockitems);\nvoid sblist_free(sblist* l);\n\n//for static style\nvoid sblist_init(sblist* l, size_t itemsize, size_t blockitems);\nvoid sblist_free_items(sblist* l);\n\n// accessors\nvoid* sblist_get(sblist* l, size_t item);\n// returns 1 on success, 0 on OOM\nint sblist_add(sblist* l, void* item);\nint sblist_set(sblist* l, void* item, size_t pos);\nvoid sblist_delete(sblist* l, size_t item);\nchar* sblist_item_from_index(sblist* l, size_t idx);\nint sblist_grow_if_needed(sblist* l);\nint sblist_insert(sblist* l, void* item, size_t pos);\n/* same as sblist_add, but returns list index of new item, or -1 */\nsize_t sblist_addi(sblist* l, void* item);\nvoid sblist_sort(sblist *l, int (*compar)(const void *, const void *));\n/* insert element into presorted list, returns listindex of new entry or -1*/\nsize_t sblist_insert_sorted(sblist* l, void* o, int (*compar)(const void *, const void *));\n\n#ifndef __COUNTER__\n#define __COUNTER__ __LINE__\n#endif\n\n#define __sblist_concat_impl( x, y ) x##y\n#define __sblist_macro_concat( x, y ) __sblist_concat_impl( x, y )\n#define __sblist_iterator_name __sblist_macro_concat(sblist_iterator, __COUNTER__)\n\n// use with custom iterator variable\n#define sblist_iter_counter(LIST, ITER, PTR) \\\n\tfor(size_t ITER = 0; (PTR = sblist_get(LIST, ITER)), ITER < sblist_getsize(LIST); ITER++)\n\n// use with custom iterator variable, which is predeclared\n#define sblist_iter_counter2(LIST, ITER, PTR) \\\n\tfor(ITER = 0; (PTR = sblist_get(LIST, ITER)), ITER < sblist_getsize(LIST); ITER++)\n\n// use with custom iterator variable, which is predeclared and signed\n// useful for a loop which can delete items from the list, and then decrease the iterator var.\n#define sblist_iter_counter2s(LIST, ITER, PTR) \\\n\tfor(ITER = 0; (PTR = sblist_get(LIST, ITER)), ITER < (ssize_t) sblist_getsize(LIST); ITER++)\n\n\n// uses \"magic\" iterator variable\n#define sblist_iter(LIST, PTR) sblist_iter_counter(LIST, __sblist_iterator_name, PTR)\n\n#ifdef __cplusplus\n}\n#endif\n\n#pragma RcB2 DEP \"sblist.c\" \"sblist_delete.c\"\n\n#endif\n"
  },
  {
    "path": "src/daemon/sblist_delete.c",
    "content": "#include \"sblist.h\"\n#include <string.h>\n\nvoid sblist_delete(sblist* l, size_t item) {\n\tif (l->count && item < l->count) {\n\t\tmemmove(sblist_item_from_index(l, item), sblist_item_from_index(l, item + 1), (sblist_getsize(l) - (item + 1)) * l->itemsize);\n\t\tl->count--;\n\t}\n}\n"
  },
  {
    "path": "src/daemon/udpclient.c",
    "content": "#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include \"../remotedns.h\"\n#include \"../ip_type.h\"\n\nint main() {\n\tint fd;\n\tint port = 1053;\n\tchar srvn[] = \"127.0.0.1\";\n\tstruct sockaddr_in srva = {.sin_family = AF_INET, .sin_port = htons(port)};\n\tinet_pton(AF_INET, srvn, &srva.sin_addr);\n\tfd = socket(AF_INET, SOCK_DGRAM, 0);\n\tchar namebuf[260];\n\twhile(fgets(namebuf, sizeof namebuf, stdin)) {\n\t\tsize_t l = strlen(namebuf);\n\t\tif(namebuf[l-1] == '\\n') {\n\t\t\tl--;\n\t\t\tnamebuf[l] = 0;\n\t\t}\n\t\tstruct at_msg msg = {0};\n\t\tunsigned msglen;\n\t\tif(isdigit(namebuf[0])) {\n\t\t\tmsglen = 4;\n\t\t\tmsg.h.msgtype = ATM_GETNAME;\n\t\t\tinet_aton(namebuf, (void*) &msg.m.ip);\n\t\t} else {\n\t\t\tmsglen = l+1;\n\t\t\tmsg.h.msgtype = ATM_GETIP;\n\t\t\tmemcpy(msg.m.host, namebuf, msglen);\n\t\t}\n\t\tmsg.h.datalen = htons(msglen);\n\t\tsendto(fd, &msg, sizeof(msg.h)+msglen, 0, (void*)&srva, sizeof(srva));\n\t\tchar rcvbuf[512];\n\t\trecvfrom(fd, rcvbuf, sizeof rcvbuf, 0, (void*)0, (void*)0);\n\t}\n}\n"
  },
  {
    "path": "src/daemon/udpserver.c",
    "content": "#include \"udpserver.h\"\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n\nint resolve(const char *host, unsigned short port, struct addrinfo** addr) {\n\tstruct addrinfo hints = {\n\t\t.ai_family = AF_UNSPEC,\n\t\t.ai_socktype = SOCK_STREAM,\n\t\t.ai_flags = AI_PASSIVE,\n\t};\n\tchar port_buf[8];\n\tsnprintf(port_buf, sizeof port_buf, \"%u\", port);\n\treturn getaddrinfo(host, port_buf, &hints, addr);\n}\n\nint resolve_sa(const char *host, unsigned short port, union sockaddr_union *res) {\n\tstruct addrinfo *ainfo = 0;\n\tint ret;\n\tSOCKADDR_UNION_AF(res) = AF_UNSPEC;\n\tif((ret = resolve(host, port, &ainfo))) return ret;\n\tmemcpy(res, ainfo->ai_addr, ainfo->ai_addrlen);\n\tfreeaddrinfo(ainfo);\n\treturn 0;\n}\n\nint bindtoip(int fd, union sockaddr_union *bindaddr) {\n\tsocklen_t sz = SOCKADDR_UNION_LENGTH(bindaddr);\n\tif(sz)\n\t\treturn bind(fd, (struct sockaddr*) bindaddr, sz);\n\treturn 0;\n}\n\nint server_waitclient(struct server *server, struct client* client, void* buf, size_t *buflen) {\n\tsocklen_t clen = sizeof client->addr;\n\tssize_t ret = recvfrom(server->fd, buf, *buflen, 0, (void*)&client->addr, &clen);\n\tif(ret >= 0) {\n\t\t*buflen = ret;\n\t\treturn 0;\n\t}\n\treturn ret;\n}\n\nint server_setup(struct server *server, const char* listenip, unsigned short port) {\n\tstruct addrinfo *ainfo = 0;\n\tif(resolve(listenip, port, &ainfo)) return -1;\n\tstruct addrinfo* p;\n\tint listenfd = -1;\n\tfor(p = ainfo; p; p = p->ai_next) {\n\t\tif((listenfd = socket(p->ai_family, SOCK_DGRAM, 0)) < 0)\n\t\t\tcontinue;\n\t\tint yes = 1;\n\t\tsetsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));\n\t\tif(bind(listenfd, p->ai_addr, p->ai_addrlen) < 0) {\n\t\t\tclose(listenfd);\n\t\t\tlistenfd = -1;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\tfreeaddrinfo(ainfo);\n\tif(listenfd < 0) return -2;\n\tserver->fd = listenfd;\n\treturn 0;\n}\n"
  },
  {
    "path": "src/daemon/udpserver.h",
    "content": "#ifndef SERVER_H\n#define SERVER_H\n\n#undef _POSIX_C_SOURCE\n#define _POSIX_C_SOURCE 200809L\n\n#include <sys/socket.h>\n#include <netdb.h>\n#include <netinet/in.h>\n\n#pragma RcB2 DEP \"udpserver.c\"\n\nunion sockaddr_union {\n\tstruct sockaddr_in  v4;\n\tstruct sockaddr_in6 v6;\n};\n\n#define SOCKADDR_UNION_AF(PTR) (PTR)->v4.sin_family\n\n#define SOCKADDR_UNION_LENGTH(PTR) ( \\\n\t( SOCKADDR_UNION_AF(PTR) == AF_INET  ) ? sizeof((PTR)->v4) : ( \\\n\t( SOCKADDR_UNION_AF(PTR) == AF_INET6 ) ? sizeof((PTR)->v6) : 0 ) )\n\n#define SOCKADDR_UNION_ADDRESS(PTR) ( \\\n\t( SOCKADDR_UNION_AF(PTR) == AF_INET  ) ? (void*) &(PTR)->v4.sin_addr  : ( \\\n\t( SOCKADDR_UNION_AF(PTR) == AF_INET6 ) ? (void*) &(PTR)->v6.sin6_addr : (void*) 0 ) )\n\n#define SOCKADDR_UNION_PORT(PTR) ( \\\n\t( SOCKADDR_UNION_AF(PTR) == AF_INET  ) ? (PTR)->v4.sin_port  : ( \\\n\t( SOCKADDR_UNION_AF(PTR) == AF_INET6 ) ? (PTR)->v6.sin6_port : 0 ) )\n\nstruct client {\n\tunion sockaddr_union addr;\n};\n\nstruct server {\n\tint fd;\n};\n\nint resolve(const char *host, unsigned short port, struct addrinfo** addr);\nint resolve_sa(const char *host, unsigned short port, union sockaddr_union *res);\nint bindtoip(int fd, union sockaddr_union *bindaddr);\n\nint server_waitclient(struct server *server, struct client* client, void* buf, size_t *buflen);\nint server_setup(struct server *server, const char* listenip, unsigned short port);\n\n#endif\n\n"
  },
  {
    "path": "src/debug.c",
    "content": "\n#ifdef DEBUG\n# include \"core.h\"\n# include \"common.h\"\n# include \"debug.h\"\n#include <arpa/inet.h>\n\nvoid dump_proxy_chain(proxy_data *pchain, unsigned int count) {\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tfor (; count; pchain++, count--) {\n\t\tif(!inet_ntop(pchain->ip.is_v6?AF_INET6:AF_INET,pchain->ip.addr.v6,ip_buf,sizeof ip_buf)) {\n\t\t\tproxychains_write_log(LOG_PREFIX \"error: ip address conversion failed\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tPDEBUG(\"[%s] %s %s:%d\", proxy_state_strmap[pchain->ps],\n\t\t       proxy_type_strmap[pchain->pt], \n\t\t       ip_buf, htons(pchain->port));\n\t\tif (*pchain->user || *pchain->pass) {\n\t\t\tPSTDERR(\" [u=%s,p=%s]\", pchain->user, pchain->pass);\n\t\t}\n\t\tPSTDERR(\"\\n\");\n\t}\n}\n\n#else\n\n// Do not allow this translation unit to end up empty\n// for non-DEBUG builds, to satisfy ISO C standards.\ntypedef int __appease_iso_compilers__;\n\n#endif\n"
  },
  {
    "path": "src/debug.h",
    "content": "#ifndef DEBUG_H\n#define DEBUG_H\n\n# include <stdio.h>\n\n#ifdef DEBUG\n# define PSTDERR(fmt, args...) do { dprintf(2,fmt, ## args); } while(0)\n# define PDEBUG(fmt, args...) PSTDERR(\"DEBUG:pid[%d]:\" fmt, getpid(), ## args)\n# define DEBUGDECL(args...) args\n# define DUMP_PROXY_CHAIN(A, B) dump_proxy_chain(A, B)\n#else\n# define PDEBUG(fmt, args...) do {} while (0)\n# define DEBUGDECL(args...)\n# define DUMP_PROXY_CHAIN(args...) do {} while (0)\n#endif\n\n# define PFUNC() do { PDEBUG(\"%s()\\n\", __FUNCTION__); } while(0)\n\n#include \"core.h\"\nvoid dump_proxy_chain(proxy_data *pchain, unsigned int count);\n\n\n#endif\n\n"
  },
  {
    "path": "src/hash.c",
    "content": "#include \"hash.h\"\n\n/* dalias' version of the elf hash */\nuint32_t dalias_hash(char *s0) {\n\tunsigned char *s = (void *) s0;\n\tuint_fast32_t h = 0;\n\twhile(*s) {\n\t\th = 16 * h + *s++;\n\t\th ^= h >> 24 & 0xf0;\n\t}\n\treturn h & 0xfffffff;\n}\n"
  },
  {
    "path": "src/hash.h",
    "content": "#ifndef HASH_H\n#define HASH_H\n\n#include <stdint.h>\n\nuint32_t dalias_hash(char *s0);\n\n//RcB: DEP \"hash.c\"\n\n#endif\n"
  },
  {
    "path": "src/hostsreader.c",
    "content": "#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n#include \"common.h\"\n\n/*\n   simple reader for /etc/hosts\n   it only supports comments, blank lines and lines consisting of an ipv4 hostname pair.\n   this is required so we can return entries from the host db without messing up the\n   non-thread-safe state of libc's gethostent().\n\n*/\n\nstruct hostsreader {\n\tFILE *f;\n\tchar* ip, *name;\n};\n\nint hostsreader_open(struct hostsreader *ctx) {\n\tif(!(ctx->f = fopen(\"/etc/hosts\", \"r\"))) return 0;\n\treturn 1;\n}\n\nvoid hostsreader_close(struct hostsreader *ctx) {\n\tfclose(ctx->f);\n}\n\nint hostsreader_get(struct hostsreader *ctx, char* buf, size_t bufsize) {\n\twhile(1) {\n\t\tif(!fgets(buf, bufsize, ctx->f)) return 0;\n\t\tif(*buf == '#') continue;\n\t\tchar *p = buf;\n\t\tsize_t l = bufsize;\n\t\tctx->ip = p;\n\t\twhile(*p && !isspace(*p) && l) {\n\t\t\tp++;\n\t\t\tl--;\n\t\t}\n\t\tif(!l || !*p || p == ctx->ip) continue;\n\t\t*p = 0;\n\t\tp++;\n\t\twhile(*p && isspace(*p) && l) {\n\t\t\tp++;\n\t\t\tl--;\n\t\t}\n\t\tif(!l || !*p) continue;\n\t\tctx->name = p;\n\t\twhile(*p && !isspace(*p) && l) {\n\t\t\tp++;\n\t\t\tl--;\n\t\t}\n\t\tif(!l || !*p) continue;\n\t\t*p = 0;\n\t\tif(pc_isnumericipv4(ctx->ip)) return 1;\n\t}\n}\n\nchar* hostsreader_get_ip_for_name(const char* name, char* buf, size_t bufsize) {\n\tstruct hostsreader ctx;\n\tchar *res = 0;\n\tif(!hostsreader_open(&ctx)) return 0;\n\twhile(hostsreader_get(&ctx, buf, bufsize)) {\n\t\tif(!strcmp(ctx.name, name)) {\n\t\t\tres = ctx.ip;\n\t\t\tbreak;\n\t\t}\n\t}\n\thostsreader_close(&ctx);\n\treturn res;\n}\n\n#include \"ip_type.h\"\n#include <netinet/in.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\nip_type4 hostsreader_get_numeric_ip_for_name(const char* name) {\n\tchar *hres;\n\tchar buf[320];\n\tif((hres = hostsreader_get_ip_for_name(name, buf, sizeof buf))) {\n\t\tstruct in_addr c;\n\t\tinet_aton(hres, &c);\n\t\tip_type4 res;\n\t\tmemcpy(res.octet, &c.s_addr, 4);\n\t\treturn res;\n\t} else return IPT4_INVALID;\n}\n\n#ifdef HOSTSREADER_TEST\n#include \"ip_type.c\"\nint main(int a, char**b) {\n\tchar buf[256];\n\tif(a != 2) return 1;\n\tchar * ret = hostsreader_get_ip_for_name(b[1], buf, sizeof buf);\n\tprintf(\"%s\\n\", ret ? ret : \"null\");\n}\n#endif\n"
  },
  {
    "path": "src/ip_type.h",
    "content": "#ifndef IP_TYPE_H\n#define IP_TYPE_H\n\n#include <stdint.h>\n\ntypedef union {\n\tunsigned char octet[4];\n\tuint32_t as_int;\n} ip_type4;\n\ntypedef struct {\n\tunion {\n\t\tip_type4 v4;\n\t\tunsigned char v6[16];\n\t} addr;\n\tchar is_v6;\n} ip_type;\n\n#define IPT4_INT(X) (ip_type4){.as_int = (X)}\n#define IPT4_INVALID IPT4_INT(-1)\n\n#define IPT4_BYTES(A,B,C,D) (ip_type4){.octet = {(A), (B), (C), (D)} }\n#define IPT4_LOCALHOST IPT4_BYTES(127,0,0,1)\n\n#endif\n"
  },
  {
    "path": "src/libproxychains.c",
    "content": "/***************************************************************************\n                          libproxychains.c  -  description\n                             -------------------\n    begin                : Tue May 14 2002\n    copyright          :  netcreature (C) 2002\n    email                 : netcreature@users.sourceforge.net\n ***************************************************************************/\n /*     GPL */\n/***************************************************************************\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n ***************************************************************************/\n\n#undef _GNU_SOURCE\n#define _GNU_SOURCE\n\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n#include <ctype.h>\n#include <errno.h>\n#include <assert.h>\n#include <netdb.h>\n\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <fcntl.h>\n#include <dlfcn.h>\n#include <pthread.h>\n\n\n#include \"core.h\"\n#include \"common.h\"\n#include \"rdns.h\"\n\n#undef \t\tsatosin\n#define     satosin(x)      ((struct sockaddr_in *) &(x))\n#define     SOCKADDR(x)     (satosin(x)->sin_addr.s_addr)\n#define     SOCKADDR_2(x)     (satosin(x)->sin_addr)\n#define     SOCKPORT(x)     (satosin(x)->sin_port)\n#define     SOCKFAMILY(x)     (satosin(x)->sin_family)\n#define     MAX_CHAIN 512\n\n#ifdef IS_SOLARIS\n#undef connect\nint __xnet_connect(int sock, const struct sockaddr *addr, unsigned int len);\nconnect_t true___xnet_connect;\n#endif\n\nclose_t true_close;\nclose_range_t true_close_range;\nconnect_t true_connect;\ngethostbyname_t true_gethostbyname;\ngetaddrinfo_t true_getaddrinfo;\nfreeaddrinfo_t true_freeaddrinfo;\ngetnameinfo_t true_getnameinfo;\ngethostbyaddr_t true_gethostbyaddr;\nsendto_t true_sendto;\n\nint tcp_read_time_out;\nint tcp_connect_time_out;\nchain_type proxychains_ct;\nproxy_data proxychains_pd[MAX_CHAIN];\nunsigned int proxychains_proxy_count = 0;\nunsigned int proxychains_proxy_offset = 0;\nint proxychains_got_chain_data = 0;\nunsigned int proxychains_max_chain = 1;\nint proxychains_quiet_mode = 0;\nenum dns_lookup_flavor proxychains_resolver = DNSLF_LIBC;\nlocaladdr_arg localnet_addr[MAX_LOCALNET];\nsize_t num_localnet_addr = 0;\ndnat_arg dnats[MAX_DNAT];\nsize_t num_dnats = 0;\nunsigned int remote_dns_subnet = 224;\n\npthread_once_t init_once = PTHREAD_ONCE_INIT;\n\nstatic int init_l = 0;\n\nstatic void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_type * ct);\n\nstatic void* load_sym(char* symname, void* proxyfunc, int is_mandatory) {\n\tvoid *funcptr = dlsym(RTLD_NEXT, symname);\n\n\tif(is_mandatory && !funcptr) {\n\t\tfprintf(stderr, \"Cannot load symbol '%s' %s\\n\", symname, dlerror());\n\t\texit(1);\n\t} else if (!funcptr) {\n\t\treturn funcptr;\n\t} else {\n\t\tPDEBUG(\"loaded symbol '%s'\" \" real addr %p  wrapped addr %p\\n\", symname, funcptr, proxyfunc);\n\t}\n\tif(funcptr == proxyfunc) {\n\t\tPDEBUG(\"circular reference detected, aborting!\\n\");\n\t\tabort();\n\t}\n\treturn funcptr;\n}\n\n#include \"allocator_thread.h\"\n\nconst char *proxychains_get_version(void);\n\nstatic void setup_hooks(void);\n\ntypedef struct {\n\tunsigned int first, last, flags;\n} close_range_args_t;\n\n/* If there is some `close` or `close_range` system call before do_init, \n   we buffer it, and actually execute them in do_init. */\nstatic int close_fds[16];\nstatic int close_fds_cnt = 0;\nstatic close_range_args_t close_range_buffer[16];\nstatic int close_range_buffer_cnt = 0;\n\nstatic unsigned get_rand_seed(void) {\n#ifdef HAVE_CLOCK_GETTIME\n\tstruct timespec now;\n\tclock_gettime(CLOCK_REALTIME, &now);\n\treturn now.tv_sec ^ now.tv_nsec;\n#else\n\treturn time(NULL);\n#endif\n}\n\nstatic void do_init(void) {\n\tchar *env;\n\n\tsrand(get_rand_seed());\n\tcore_initialize();\n\n\tenv = getenv(PROXYCHAINS_QUIET_MODE_ENV_VAR);\n\tif(env && *env == '1')\n\t\tproxychains_quiet_mode = 1;\n\n\tproxychains_write_log(LOG_PREFIX \"DLL init: proxychains-ng %s\\n\", proxychains_get_version());\n\n\tsetup_hooks();\n\n\t/* read the config file */\n\tget_chain_data(proxychains_pd, &proxychains_proxy_count, &proxychains_ct);\n\tDUMP_PROXY_CHAIN(proxychains_pd, proxychains_proxy_count);\n\n\twhile(close_fds_cnt) true_close(close_fds[--close_fds_cnt]);\n\twhile(close_range_buffer_cnt) {\n\t\tint i = --close_range_buffer_cnt;\n\t\ttrue_close_range(close_range_buffer[i].first, close_range_buffer[i].last, close_range_buffer[i].flags);\n\t}\n\tinit_l = 1;\n\n\trdns_init(proxychains_resolver);\n}\n\nstatic void init_lib_wrapper(const char* caller) {\n#ifndef DEBUG\n\t(void) caller;\n#endif\n\tif(!init_l) PDEBUG(\"%s called from %s\\n\", __FUNCTION__,  caller);\n\tpthread_once(&init_once, do_init);\n}\n\n/* if we use gcc >= 3, we can instruct the dynamic loader\n * to call init_lib at link time. otherwise it gets loaded\n * lazily, which has the disadvantage that there's a potential\n * race condition if 2 threads call it before init_l is set\n * and PTHREAD support was disabled */\n#if __GNUC__+0 > 2\n__attribute__((constructor))\nstatic void gcc_init(void) {\n\tinit_lib_wrapper(__FUNCTION__);\n}\n#define INIT() do {} while(0)\n#else\n#define INIT() init_lib_wrapper(__FUNCTION__)\n#endif\n\n\ntypedef enum {\n\tRS_PT_NONE = 0,\n\tRS_PT_SOCKS4,\n\tRS_PT_SOCKS5,\n\tRS_PT_HTTP\n} rs_proxyType;\n\n/*\n  proxy_from_string() taken from rocksock network I/O library (C) rofl0r\n  valid inputs:\n\tsocks5://user:password@proxy.domain.com:port\n\tsocks5://proxy.domain.com:port\n\tsocks4://proxy.domain.com:port\n\thttp://user:password@proxy.domain.com:port\n\thttp://proxy.domain.com:port\n\n\tsupplying port number is obligatory.\n\tuser:pass@ part is optional for http and socks5.\n\thowever, user:pass authentication is currently not implemented for http proxies.\n  return 1 on success, 0 on error.\n*/\nstatic int proxy_from_string(const char *proxystring,\n\tchar *type_buf,\n\tchar* host_buf,\n\tint *port_n,\n\tchar *user_buf,\n\tchar* pass_buf)\n{\n\tconst char* p;\n\trs_proxyType proxytype;\n\n\tsize_t next_token = 6, ul = 0, pl = 0, hl;\n\tif(!proxystring[0] || !proxystring[1] || !proxystring[2] || !proxystring[3] || !proxystring[4] || !proxystring[5]) goto inv_string;\n\tif(*proxystring == 's') {\n\t\tswitch(proxystring[5]) {\n\t\t\tcase '5': proxytype = RS_PT_SOCKS5; break;\n\t\t\tcase '4': proxytype = RS_PT_SOCKS4; break;\n\t\t\tdefault: goto inv_string;\n\t\t}\n\t} else if(*proxystring == 'h') {\n\t\tproxytype = RS_PT_HTTP;\n\t\tnext_token = 4;\n\t} else goto inv_string;\n\tif(\n\t   proxystring[next_token++] != ':' ||\n\t   proxystring[next_token++] != '/' ||\n\t   proxystring[next_token++] != '/') goto inv_string;\n\tconst char *at = strrchr(proxystring+next_token, '@');\n\tif(at) {\n\t\tif(proxytype == RS_PT_SOCKS4)\n\t\t\treturn 0;\n\t\tp = strchr(proxystring+next_token, ':');\n\t\tif(!p || p >= at) goto inv_string;\n\t\tconst char *u = proxystring+next_token;\n\t\tul = p-u;\n\t\tp++;\n\t\tpl = at-p;\n\t\tif(ul > 255 || pl > 255)\n\t\t\treturn 0;\n\t\tmemcpy(user_buf, u, ul);\n\t\tuser_buf[ul]=0;\n\t\tmemcpy(pass_buf, p, pl);\n\t\tpass_buf[pl]=0;\n\t\tnext_token += 2+ul+pl;\n\t} else {\n\t\tuser_buf[0]=0;\n\t\tpass_buf[0]=0;\n\t}\n\tconst char* h = proxystring+next_token;\n\tp = strchr(h, ':');\n\tif(!p) goto inv_string;\n\thl = p-h;\n\tif(hl > 255)\n\t\treturn 0;\n\tmemcpy(host_buf, h, hl);\n\thost_buf[hl]=0;\n\t*port_n = atoi(p+1);\n\tswitch(proxytype) {\n\t\tcase RS_PT_SOCKS4:\n\t\t\tstrcpy(type_buf, \"socks4\");\n\t\t\tbreak;\n\t\tcase RS_PT_SOCKS5:\n\t\t\tstrcpy(type_buf, \"socks5\");\n\t\t\tbreak;\n\t\tcase RS_PT_HTTP:\n\t\t\tstrcpy(type_buf, \"http\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn 0;\n\t}\n\treturn 1;\ninv_string:\n\treturn 0;\n}\n\nstatic const char* bool_str(int bool_val) {\n\tif(bool_val) return \"true\";\n\treturn \"false\";\n}\n\n#define STR_STARTSWITH(P, LIT) (!strncmp(P, LIT, sizeof(LIT)-1))\n/* get configuration from config file */\nstatic void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_type * ct) {\n\tint count = 0, port_n = 0, list = 0;\n\tchar buf[1024], type[1024], host[1024], user[1024];\n\tchar *buff, *env, *p;\n\tchar local_addr_port[64], local_addr[64], local_netmask[32];\n\tchar dnat_orig_addr_port[32], dnat_new_addr_port[32];\n\tchar dnat_orig_addr[32], dnat_orig_port[32], dnat_new_addr[32], dnat_new_port[32];\n\tchar rdnsd_addr[32], rdnsd_port[8];\n\tFILE *file = NULL;\n\n\tif(proxychains_got_chain_data)\n\t\treturn;\n\n\tPFUNC();\n\n\t//Some defaults\n\ttcp_read_time_out = 4 * 1000;\n\ttcp_connect_time_out = 10 * 1000;\n\t*ct = DYNAMIC_TYPE;\n\n\tenv = get_config_path(getenv(PROXYCHAINS_CONF_FILE_ENV_VAR), buf, sizeof(buf));\n\tif( ( file = fopen(env, \"r\") ) == NULL )\n\t{\n\t        perror(\"couldnt read configuration file\");\n        \texit(1);\n\t}\n\n\twhile(fgets(buf, sizeof(buf), file)) {\n\t\tbuff = buf;\n\t\t/* remove leading whitespace */\n\t\twhile(isspace(*buff)) buff++;\n\t\t/* remove trailing '\\n' */\n\t\tif((p = strrchr(buff, '\\n'))) *p = 0;\n\t\tp = buff + strlen(buff)-1;\n\t\t/* remove trailing whitespace */\n\t\twhile(p >= buff && isspace(*p)) *(p--) = 0;\n\t\tif(!*buff || *buff == '#') continue; /* skip empty lines and comments */\n\t\tif(1) {\n\t\t\t/* proxylist has to come last */\n\t\t\tif(list) {\n\t\t\t\tif(count >= MAX_CHAIN)\n\t\t\t\t\tbreak;\n\n\t\t\t\tmemset(&pd[count], 0, sizeof(proxy_data));\n\n\t\t\t\tpd[count].ps = PLAY_STATE;\n\t\t\t\tport_n = 0;\n\n\t\t\t\tint ret = sscanf(buff, \"%s %s %d %s %s\", type, host, &port_n, pd[count].user, pd[count].pass);\n\t\t\t\tif(ret < 3 || ret == EOF) {\n\t\t\t\t\tif(!proxy_from_string(buff, type, host, &port_n, pd[count].user, pd[count].pass)) {\n\t\t\t\t\t\tinv:\n\t\t\t\t\t\tfprintf(stderr, \"error: invalid item in proxylist section: %s\", buff);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmemset(&pd[count].ip, 0, sizeof(pd[count].ip));\n\t\t\t\tpd[count].ip.is_v6 = !!strchr(host, ':');\n\t\t\t\tpd[count].port = htons((unsigned short) port_n);\n\t\t\t\tip_type* host_ip = &pd[count].ip;\n\t\t\t\tif(1 != inet_pton(host_ip->is_v6 ? AF_INET6 : AF_INET, host, host_ip->addr.v6)) {\n\t\t\t\t\tif(*ct == STRICT_TYPE && proxychains_resolver >= DNSLF_RDNS_START && count > 0) {\n\t\t\t\t\t\t/* we can allow dns hostnames for all but the first proxy in the list if chaintype is strict, as remote lookup can be done */\n\t\t\t\t\t\trdns_init(proxychains_resolver);\n\t\t\t\t\t\tip_type4 internal_ip = rdns_get_ip_for_host(host, strlen(host));\n\t\t\t\t\t\tpd[count].ip.is_v6 = 0;\n\t\t\t\t\t\thost_ip->addr.v4 = internal_ip;\n\t\t\t\t\t\tif(internal_ip.as_int == IPT4_INVALID.as_int)\n\t\t\t\t\t\t\tgoto inv_host;\n\t\t\t\t\t} else {\ninv_host:\n\t\t\t\t\t\tfprintf(stderr, \"proxy %s has invalid value or is not numeric\\n\", host);\n\t\t\t\t\t\tfprintf(stderr, \"non-numeric ips are only allowed under the following circumstances:\\n\");\n\t\t\t\t\t\tfprintf(stderr, \"chaintype == strict (%s), proxy is not first in list (%s), proxy_dns active (%s)\\n\\n\", bool_str(*ct == STRICT_TYPE), bool_str(count > 0), rdns_resolver_string(proxychains_resolver));\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(!strcmp(type, \"http\")) {\n\t\t\t\t\tpd[count].pt = HTTP_TYPE;\n\t\t\t\t} else if(!strcmp(type, \"raw\")) {\n\t\t\t\t\tpd[count].pt = RAW_TYPE;\n\t\t\t\t} else if(!strcmp(type, \"socks4\")) {\n\t\t\t\t\tpd[count].pt = SOCKS4_TYPE;\n\t\t\t\t} else if(!strcmp(type, \"socks5\")) {\n\t\t\t\t\tpd[count].pt = SOCKS5_TYPE;\n\t\t\t\t} else\n\t\t\t\t\tgoto inv;\n\n\t\t\t\tif(port_n)\n\t\t\t\t\tcount++;\n\t\t\t} else {\n\t\t\t\tif(!strcmp(buff, \"[ProxyList]\")) {\n\t\t\t\t\tlist = 1;\n\t\t\t\t} else if(!strcmp(buff, \"random_chain\")) {\n\t\t\t\t\t*ct = RANDOM_TYPE;\n\t\t\t\t} else if(!strcmp(buff, \"strict_chain\")) {\n\t\t\t\t\t*ct = STRICT_TYPE;\n\t\t\t\t} else if(!strcmp(buff, \"dynamic_chain\")) {\n\t\t\t\t\t*ct = DYNAMIC_TYPE;\n\t\t\t\t} else if(!strcmp(buff, \"round_robin_chain\")) {\n\t\t\t\t\t*ct = ROUND_ROBIN_TYPE;\n\t\t\t\t} else if(STR_STARTSWITH(buff, \"tcp_read_time_out\")) {\n\t\t\t\t\tsscanf(buff, \"%s %d\", user, &tcp_read_time_out);\n\t\t\t\t} else if(STR_STARTSWITH(buff, \"tcp_connect_time_out\")) {\n\t\t\t\t\tsscanf(buff, \"%s %d\", user, &tcp_connect_time_out);\n\t\t\t\t} else if(STR_STARTSWITH(buff, \"remote_dns_subnet\")) {\n\t\t\t\t\tsscanf(buff, \"%s %u\", user, &remote_dns_subnet);\n\t\t\t\t\tif(remote_dns_subnet >= 256) {\n\t\t\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\t\"remote_dns_subnet: invalid value. requires a number between 0 and 255.\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t} else if(STR_STARTSWITH(buff, \"localnet\")) {\n\t\t\t\t\tchar colon, extra, right_bracket[2];\n\t\t\t\t\tunsigned short local_port = 0, local_prefix;\n\t\t\t\t\tint local_family, n, valid;\n\t\t\t\t\tif(sscanf(buff, \"%s %53[^/]/%15s%c\", user, local_addr_port, local_netmask, &extra) != 3) {\n\t\t\t\t\t\tfprintf(stderr, \"localnet format error\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\tp = strchr(local_addr_port, ':');\n\t\t\t\t\tif(!p || p == strrchr(local_addr_port, ':')) {\n\t\t\t\t\t\tlocal_family = AF_INET;\n\t\t\t\t\t\tn = sscanf(local_addr_port, \"%15[^:]%c%5hu%c\", local_addr, &colon, &local_port, &extra);\n\t\t\t\t\t\tvalid = n == 1 || (n == 3 && colon == ':');\n\t\t\t\t\t} else if(local_addr_port[0] == '[') {\n\t\t\t\t\t\tlocal_family = AF_INET6;\n\t\t\t\t\t\tn = sscanf(local_addr_port, \"[%45[^][]%1[]]%c%5hu%c\", local_addr, right_bracket, &colon, &local_port, &extra);\n\t\t\t\t\t\tvalid = n == 2 || (n == 4 && colon == ':');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlocal_family = AF_INET6;\n\t\t\t\t\t\tvalid = sscanf(local_addr_port, \"%45[^][]%c\", local_addr, &extra) == 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(!valid) {\n\t\t\t\t\t\tfprintf(stderr, \"localnet address or port error\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\tif(local_port) {\n\t\t\t\t\t\tPDEBUG(\"added localnet: netaddr=%s, port=%u, netmask=%s\\n\",\n\t\t\t\t\t\t       local_addr, local_port, local_netmask);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tPDEBUG(\"added localnet: netaddr=%s, netmask=%s\\n\",\n\t\t\t\t\t\t       local_addr, local_netmask);\n\t\t\t\t\t}\n\t\t\t\t\tif(num_localnet_addr < MAX_LOCALNET) {\n\t\t\t\t\t\tlocalnet_addr[num_localnet_addr].family = local_family;\n\t\t\t\t\t\tlocalnet_addr[num_localnet_addr].port = local_port;\n\t\t\t\t\t\tvalid = 0;\n\t\t\t\t\t\tif (local_family == AF_INET) {\n\t\t\t\t\t\t\tvalid =\n\t\t\t\t\t\t\t    inet_pton(local_family, local_addr,\n\t\t\t\t\t\t\t              &localnet_addr[num_localnet_addr].in_addr) > 0;\n\t\t\t\t\t\t} else if(local_family == AF_INET6) {\n\t\t\t\t\t\t\tvalid =\n\t\t\t\t\t\t\t    inet_pton(local_family, local_addr,\n\t\t\t\t\t\t\t              &localnet_addr[num_localnet_addr].in6_addr) > 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(!valid) {\n\t\t\t\t\t\t\tfprintf(stderr, \"localnet address error\\n\");\n\t\t\t\t\t\t\texit(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(local_family == AF_INET && strchr(local_netmask, '.')) {\n\t\t\t\t\t\t\tvalid =\n\t\t\t\t\t\t\t    inet_pton(local_family, local_netmask,\n\t\t\t\t\t\t\t              &localnet_addr[num_localnet_addr].in_mask) > 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvalid = sscanf(local_netmask, \"%hu%c\", &local_prefix, &extra) == 1;\n\t\t\t\t\t\t\tif (valid) {\n\t\t\t\t\t\t\t\tif(local_family == AF_INET && local_prefix <= 32) {\n\t\t\t\t\t\t\t\t\tlocalnet_addr[num_localnet_addr].in_mask.s_addr =\n\t\t\t\t\t\t\t\t\t\thtonl(0xFFFFFFFFu << (32u - local_prefix));\n\t\t\t\t\t\t\t\t} else if(local_family == AF_INET6 && local_prefix <= 128) {\n\t\t\t\t\t\t\t\t\tlocalnet_addr[num_localnet_addr].in6_prefix =\n\t\t\t\t\t\t\t\t\t\tlocal_prefix;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tvalid = 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(!valid) {\n\t\t\t\t\t\t\tfprintf(stderr, \"localnet netmask error\\n\");\n\t\t\t\t\t\t\texit(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++num_localnet_addr;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfprintf(stderr, \"# of localnet exceed %d.\\n\", MAX_LOCALNET);\n\t\t\t\t\t}\n\t\t\t\t} else if(STR_STARTSWITH(buff, \"chain_len\")) {\n\t\t\t\t\tchar *pc;\n\t\t\t\t\tint len;\n\t\t\t\t\tpc = strchr(buff, '=');\n\t\t\t\t\tif(!pc) {\n\t\t\t\t\t\tfprintf(stderr, \"error: missing equals sign '=' in chain_len directive.\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\tlen = atoi(++pc);\n\t\t\t\t\tproxychains_max_chain = (len ? len : 1);\n\t\t\t\t} else if(!strcmp(buff, \"quiet_mode\")) {\n\t\t\t\t\tproxychains_quiet_mode = 1;\n\t\t\t\t} else if(!strcmp(buff, \"proxy_dns_old\")) {\n\t\t\t\t\tproxychains_resolver = DNSLF_FORKEXEC;\n\t\t\t\t} else if(!strcmp(buff, \"proxy_dns\")) {\n\t\t\t\t\tproxychains_resolver = DNSLF_RDNS_THREAD;\n\t\t\t\t} else if(STR_STARTSWITH(buff, \"proxy_dns_daemon\")) {\n\t\t\t\t\tstruct sockaddr_in rdns_server_buffer;\n\n\t\t\t\t\tif(sscanf(buff, \"%s %15[^:]:%5s\", user, rdnsd_addr, rdnsd_port) < 3) {\n\t\t\t\t\t\tfprintf(stderr, \"proxy_dns_daemon format error\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\trdns_server_buffer.sin_family = AF_INET;\n\t\t\t\t\tint error = inet_pton(AF_INET, rdnsd_addr, &rdns_server_buffer.sin_addr);\n\t\t\t\t\tif(error <= 0) {\n\t\t\t\t\t\tfprintf(stderr, \"bogus proxy_dns_daemon address\\n\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\trdns_server_buffer.sin_port = htons(atoi(rdnsd_port));\n\t\t\t\t\tproxychains_resolver = DNSLF_RDNS_DAEMON;\n\t\t\t\t\trdns_set_daemon(&rdns_server_buffer);\n\t\t\t\t} else if(STR_STARTSWITH(buff, \"dnat\")) {\n\t\t\t\t\tif(sscanf(buff, \"%s %21[^ ] %21s\\n\", user, dnat_orig_addr_port, dnat_new_addr_port) < 3) {\n\t\t\t\t\t\tfprintf(stderr, \"dnat format error\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\t/* clean previously used buffer */\n\t\t\t\t\tmemset(dnat_orig_port, 0, sizeof(dnat_orig_port) / sizeof(dnat_orig_port[0]));\n\t\t\t\t\tmemset(dnat_new_port, 0, sizeof(dnat_new_port) / sizeof(dnat_new_port[0]));\n\n\t\t\t\t\t(void)sscanf(dnat_orig_addr_port, \"%15[^:]:%5s\", dnat_orig_addr, dnat_orig_port);\n\t\t\t\t\t(void)sscanf(dnat_new_addr_port, \"%15[^:]:%5s\", dnat_new_addr, dnat_new_port);\n\n\t\t\t\t\tif(num_dnats < MAX_DNAT) {\n\t\t\t\t\t\tint error;\n\t\t\t\t\t\terror =\n\t\t\t\t\t\t    inet_pton(AF_INET, dnat_orig_addr,\n\t\t\t\t\t\t\t      &dnats[num_dnats].orig_dst);\n\t\t\t\t\t\tif(error <= 0) {\n\t\t\t\t\t\t\tfprintf(stderr, \"dnat original destination address error\\n\");\n\t\t\t\t\t\t\texit(1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\terror =\n\t\t\t\t\t\t    inet_pton(AF_INET, dnat_new_addr,\n\t\t\t\t\t\t\t      &dnats[num_dnats].new_dst);\n\t\t\t\t\t\tif(error <= 0) {\n\t\t\t\t\t\t\tfprintf(stderr, \"dnat effective destination address error\\n\");\n\t\t\t\t\t\t\texit(1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(dnat_orig_port[0]) {\n\t\t\t\t\t\t\tdnats[num_dnats].orig_port =\n\t\t\t\t\t\t\t    (short) atoi(dnat_orig_port);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdnats[num_dnats].orig_port = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(dnat_new_port[0]) {\n\t\t\t\t\t\t\tdnats[num_dnats].new_port =\n\t\t\t\t\t\t\t    (short) atoi(dnat_new_port);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdnats[num_dnats].new_port = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tPDEBUG(\"added dnat: orig-dst=%s orig-port=%d new-dst=%s new-port=%d\\n\", dnat_orig_addr, dnats[num_dnats].orig_port, dnat_new_addr, dnats[num_dnats].new_port);\n\t\t\t\t\t\t++num_dnats;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfprintf(stderr, \"# of dnat exceed %d.\\n\", MAX_DNAT);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n#ifndef BROKEN_FCLOSE\n\tfclose(file);\n#endif\n\tif(!count) {\n\t\tfprintf(stderr, \"error: no valid proxy found in config\\n\");\n\t\texit(1);\n\t}\n\t*proxy_count = count;\n\tproxychains_got_chain_data = 1;\n\tPDEBUG(\"proxy_dns: %s\\n\", rdns_resolver_string(proxychains_resolver));\n}\n\n/*******  HOOK FUNCTIONS  *******/\n\n#define EXPAND( args...) args\n#ifdef MONTEREY_HOOKING\n#define HOOKFUNC(R, N, args...) R pxcng_ ## N ( EXPAND(args) )\n#else\n#define HOOKFUNC(R, N, args...) R N ( EXPAND(args) )\n#endif\n\nHOOKFUNC(int, close, int fd) {\n\tif(!init_l) {\n\t\tif(close_fds_cnt>=(sizeof close_fds/sizeof close_fds[0])) goto err;\n\t\tclose_fds[close_fds_cnt++] = fd;\n\t\terrno = 0;\n\t\treturn 0;\n\t}\n\tif(proxychains_resolver != DNSLF_RDNS_THREAD) return true_close(fd);\n\n\t/* prevent rude programs (like ssh) from closing our pipes */\n\tif(fd != req_pipefd[0]  && fd != req_pipefd[1] &&\n\t   fd != resp_pipefd[0] && fd != resp_pipefd[1]) {\n\t\treturn true_close(fd);\n\t}\n\terr:\n\terrno = EBADF;\n\treturn -1;\n}\nstatic int is_v4inv6(const struct in6_addr *a) {\n\treturn !memcmp(a->s6_addr, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\", 12);\n}\n\nstatic void intsort(int *a, int n) {\n\tint i, j, s;\n\tfor(i=0; i<n; ++i)\n\t\tfor(j=i+1; j<n; ++j)\n\t\t\tif(a[j] < a[i]) {\n\t\t\t\ts = a[i];\n\t\t\t\ta[i] = a[j];\n\t\t\t\ta[j] = s;\n\t\t\t}\n}\n\n/* Warning: Linux manual says the third arg is `unsigned int`, but unistd.h says `int`. */\nHOOKFUNC(int, close_range, unsigned first, unsigned last, int flags) {\n\tif(true_close_range == NULL) {\n\t\tfprintf(stderr, \"Calling close_range, but this platform does not provide this system call. \");\n\t\treturn -1;\n\t}\n\tif(!init_l) {\n\t\t/* push back to cache, and delay the execution. */\n\t\tif(close_range_buffer_cnt >= (sizeof close_range_buffer / sizeof close_range_buffer[0])) {\n\t\t\terrno = ENOMEM;\n\t\t\treturn -1;\n\t\t}\n\t\tint i = close_range_buffer_cnt++;\n\t\tclose_range_buffer[i].first = first;\n\t\tclose_range_buffer[i].last = last;\n\t\tclose_range_buffer[i].flags = flags;\n\t\treturn errno = 0;\n\t}\n\tif(proxychains_resolver != DNSLF_RDNS_THREAD) return true_close_range(first, last, flags);\n\n\t/* prevent rude programs (like ssh) from closing our pipes */\n\tint res = 0, uerrno = 0, i;\n\tint protected_fds[] = {req_pipefd[0], req_pipefd[1], resp_pipefd[0], resp_pipefd[1]};\n\tintsort(protected_fds, 4);\n\t/* We are skipping protected_fds while calling true_close_range()\n\t * If protected_fds cut the range into some sub-ranges, we close sub-ranges BEFORE cut point in the loop. \n\t * [first, cut1-1] , [cut1+1, cut2-1] , [cut2+1, cut3-1]\n\t * Finally, we delete the remaining sub-range, outside the loop. [cut3+1, tail]\n\t */\n\tint next_fd_to_close = first;\n\tfor(i = 0; i < 4; ++i) {\n\t\tif(protected_fds[i] < first || protected_fds[i] > last)\n\t\t\tcontinue;\n\t\tint prev = (i == 0 || protected_fds[i-1] < first) ? first : protected_fds[i-1]+1;\n\t\tif(prev != protected_fds[i]) {\n\t\t\tif(-1 == true_close_range(prev, protected_fds[i]-1, flags)) {\n\t\t\t\tres = -1;\n\t\t\t\tuerrno = errno;\n\t\t\t}\n\t\t}\n\t\tnext_fd_to_close = protected_fds[i]+1;\n\t}\n\tif(next_fd_to_close <= last) {\n\t\tif(-1 == true_close_range(next_fd_to_close, last, flags)) {\n\t\t\tres = -1;\n\t\t\tuerrno = errno;\n\t\t}\n\t}\n\terrno = uerrno;\n\treturn res;\n}\n\nHOOKFUNC(int, connect, int sock, const struct sockaddr *addr, unsigned int len) {\n\tINIT();\n\tPFUNC();\n\n\tint socktype = 0, flags = 0, ret = 0;\n\tsocklen_t optlen = 0;\n\tip_type dest_ip;\n\tDEBUGDECL(char str[256]);\n\n\tstruct in_addr *p_addr_in;\n\tstruct in6_addr *p_addr_in6;\n\tdnat_arg *dnat = NULL;\n\tunsigned short port;\n\tsize_t i;\n\tint remote_dns_connect = 0;\n\toptlen = sizeof(socktype);\n\tsa_family_t fam = SOCKFAMILY(*addr);\n\tgetsockopt(sock, SOL_SOCKET, SO_TYPE, &socktype, &optlen);\n\tif(!((fam  == AF_INET || fam == AF_INET6) && socktype == SOCK_STREAM))\n\t\treturn true_connect(sock, addr, len);\n\n\tint v6 = dest_ip.is_v6 = fam == AF_INET6;\n\n\tp_addr_in = &((struct sockaddr_in *) addr)->sin_addr;\n\tp_addr_in6 = &((struct sockaddr_in6 *) addr)->sin6_addr;\n\tport = !v6 ? ntohs(((struct sockaddr_in *) addr)->sin_port)\n\t           : ntohs(((struct sockaddr_in6 *) addr)->sin6_port);\n\tstruct in_addr v4inv6;\n\tif(v6 && is_v4inv6(p_addr_in6)) {\n\t\tmemcpy(&v4inv6.s_addr, &p_addr_in6->s6_addr[12], 4);\n\t\tv6 = dest_ip.is_v6 = 0;\n\t\tp_addr_in = &v4inv6;\n\t}\n\tif(!v6 && !memcmp(p_addr_in, \"\\0\\0\\0\\0\", 4)) {\n\t\terrno = ECONNREFUSED;\n\t\treturn -1;\n\t}\n\n//      PDEBUG(\"localnet: %s; \", inet_ntop(AF_INET,&in_addr_localnet, str, sizeof(str)));\n//      PDEBUG(\"netmask: %s; \" , inet_ntop(AF_INET, &in_addr_netmask, str, sizeof(str)));\n\tPDEBUG(\"target: %s\\n\", inet_ntop(v6 ? AF_INET6 : AF_INET, v6 ? (void*)p_addr_in6 : (void*)p_addr_in, str, sizeof(str)));\n\tPDEBUG(\"port: %d\\n\", port);\n\n\t// check if connect called from proxydns\n        remote_dns_connect = !v6 && (ntohl(p_addr_in->s_addr) >> 24 == remote_dns_subnet);\n\n\t// more specific first\n\tif (!v6) for(i = 0; i < num_dnats && !remote_dns_connect && !dnat; i++)\n\t\tif(dnats[i].orig_dst.s_addr == p_addr_in->s_addr)\n\t\t\tif(dnats[i].orig_port && (dnats[i].orig_port == port))\n\t\t\t\tdnat = &dnats[i];\n\n\tif (!v6) for(i = 0; i < num_dnats && !remote_dns_connect && !dnat; i++)\n\t\tif(dnats[i].orig_dst.s_addr == p_addr_in->s_addr)\n\t\t\tif(!dnats[i].orig_port)\n\t\t\t\tdnat = &dnats[i];\n\n\tif (dnat) {\n\t\tp_addr_in = &dnat->new_dst;\n\t\tif (dnat->new_port)\n\t\t\tport = dnat->new_port;\n\t}\n\n\tfor(i = 0; i < num_localnet_addr && !remote_dns_connect; i++) {\n\t\tif (localnet_addr[i].port && localnet_addr[i].port != port)\n\t\t\tcontinue;\n\t\tif (localnet_addr[i].family != (v6 ? AF_INET6 : AF_INET))\n\t\t\tcontinue;\n\t\tif (v6) {\n\t\t\tsize_t prefix_bytes = localnet_addr[i].in6_prefix / CHAR_BIT;\n\t\t\tsize_t prefix_bits = localnet_addr[i].in6_prefix % CHAR_BIT;\n\t\t\tif (prefix_bytes && memcmp(p_addr_in6->s6_addr, localnet_addr[i].in6_addr.s6_addr, prefix_bytes) != 0)\n\t\t\t\tcontinue;\n\t\t\tif (prefix_bits && (p_addr_in6->s6_addr[prefix_bytes] ^ localnet_addr[i].in6_addr.s6_addr[prefix_bytes]) >> (CHAR_BIT - prefix_bits))\n\t\t\t\tcontinue;\n\t\t} else {\n\t\t\tif((p_addr_in->s_addr ^ localnet_addr[i].in_addr.s_addr) & localnet_addr[i].in_mask.s_addr)\n\t\t\t\tcontinue;\n\t\t}\n\t\tPDEBUG(\"accessing localnet using true_connect\\n\");\n\t\treturn true_connect(sock, addr, len);\n\t}\n\n\tflags = fcntl(sock, F_GETFL, 0);\n\tif(flags & O_NONBLOCK)\n\t\tfcntl(sock, F_SETFL, !O_NONBLOCK);\n\n\tmemcpy(dest_ip.addr.v6, v6 ? (void*)p_addr_in6 : (void*)p_addr_in, v6?16:4);\n\n\tret = connect_proxy_chain(sock,\n\t\t\t\t  dest_ip,\n\t\t\t\t  htons(port),\n\t\t\t\t  proxychains_pd, proxychains_proxy_count, proxychains_ct, proxychains_max_chain);\n\n\tfcntl(sock, F_SETFL, flags);\n\tif(ret != SUCCESS)\n\t\terrno = ECONNREFUSED;\n\treturn ret;\n}\n\n#ifdef IS_SOLARIS\nHOOKFUNC(int, __xnet_connect, int sock, const struct sockaddr *addr, unsigned int len) {\n\treturn connect(sock, addr, len);\n}\n#endif\n\nstatic struct gethostbyname_data ghbndata;\nHOOKFUNC(struct hostent*, gethostbyname, const char *name) {\n\tINIT();\n\tPDEBUG(\"gethostbyname: %s\\n\", name);\n\n\tif(proxychains_resolver == DNSLF_FORKEXEC)\n\t\treturn proxy_gethostbyname_old(name);\n\telse if(proxychains_resolver == DNSLF_LIBC)\n\t\treturn true_gethostbyname(name);\n\telse\n\t\treturn proxy_gethostbyname(name, &ghbndata);\n\n\treturn NULL;\n}\n\nHOOKFUNC(int, getaddrinfo, const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) {\n\tINIT();\n\tPDEBUG(\"getaddrinfo: %s %s\\n\", node ? node : \"null\", service ? service : \"null\");\n\n\tif(proxychains_resolver != DNSLF_LIBC)\n\t\treturn proxy_getaddrinfo(node, service, hints, res);\n\telse\n\t\treturn true_getaddrinfo(node, service, hints, res);\n}\n\nHOOKFUNC(void, freeaddrinfo, struct addrinfo *res) {\n\tINIT();\n\tPDEBUG(\"freeaddrinfo %p \\n\", (void *) res);\n\n\tif(proxychains_resolver == DNSLF_LIBC)\n\t\ttrue_freeaddrinfo(res);\n\telse\n\t\tproxy_freeaddrinfo(res);\n}\n\nHOOKFUNC(int, getnameinfo, const struct sockaddr *sa, socklen_t salen,\n\t           char *host, GN_NODELEN_T hostlen, char *serv,\n\t           GN_SERVLEN_T servlen, GN_FLAGS_T flags)\n{\n\tINIT();\n\tPFUNC();\n\n\tif(proxychains_resolver == DNSLF_LIBC) {\n\t\treturn true_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);\n\t} else {\n\t\tif(!salen || !(SOCKFAMILY(*sa) == AF_INET || SOCKFAMILY(*sa) == AF_INET6))\n\t\t\treturn EAI_FAMILY;\n\t\tint v6 = SOCKFAMILY(*sa) == AF_INET6;\n\t\tif(salen < (v6?sizeof(struct sockaddr_in6):sizeof(struct sockaddr_in)))\n\t\t\treturn EAI_FAMILY;\n\t\tif(hostlen) {\n\t\t\tunsigned char v4inv6buf[4];\n\t\t\tconst void *ip = v6 ? (void*)&((struct sockaddr_in6*)sa)->sin6_addr\n\t\t\t                    : (void*)&((struct sockaddr_in*)sa)->sin_addr;\n\t\t\tunsigned scopeid = 0;\n\t\t\tif(v6) {\n\t\t\t\tif(is_v4inv6(&((struct sockaddr_in6*)sa)->sin6_addr)) {\n\t\t\t\t\tmemcpy(v4inv6buf, &((struct sockaddr_in6*)sa)->sin6_addr.s6_addr[12], 4);\n\t\t\t\t\tip = v4inv6buf;\n\t\t\t\t\tv6 = 0;\n\t\t\t\t} else\n\t\t\t\t\tscopeid = ((struct sockaddr_in6 *)sa)->sin6_scope_id;\n\t\t\t}\n\t\t\tif(!inet_ntop(v6?AF_INET6:AF_INET,ip,host,hostlen))\n\t\t\t\treturn EAI_OVERFLOW;\n\t\t\tif(scopeid) {\n\t\t\t\tsize_t l = strlen(host);\n\t\t\t\tif(snprintf(host+l, hostlen-l, \"%%%u\", scopeid) >= hostlen-l)\n\t\t\t\t\treturn EAI_OVERFLOW;\n\t\t\t}\n\t\t}\n\t\tif(servlen) {\n\t\t\tif(snprintf(serv, servlen, \"%d\", ntohs(SOCKPORT(*sa))) >= servlen)\n\t\t\t\treturn EAI_OVERFLOW;\n\t\t}\n\t}\n\treturn 0;\n}\n\nHOOKFUNC(struct hostent*, gethostbyaddr, const void *addr, socklen_t len, int type) {\n\tINIT();\n\tPDEBUG(\"TODO: proper gethostbyaddr hook\\n\");\n\n\tstatic char buf[16];\n\tstatic char ipv4[4];\n\tstatic char *list[2];\n\tstatic char *aliases[1];\n\tstatic struct hostent he;\n\n\tif(proxychains_resolver == DNSLF_LIBC)\n\t\treturn true_gethostbyaddr(addr, len, type);\n\telse {\n\n\t\tPDEBUG(\"len %u\\n\", len);\n\t\tif(len != 4)\n\t\t\treturn NULL;\n\t\the.h_name = buf;\n\t\tmemcpy(ipv4, addr, 4);\n\t\tlist[0] = ipv4;\n\t\tlist[1] = NULL;\n\t\the.h_addr_list = list;\n\t\the.h_addrtype = AF_INET;\n\t\taliases[0] = NULL;\n\t\the.h_aliases = aliases;\n\t\the.h_length = 4;\n\t\tpc_stringfromipv4((unsigned char *) addr, buf);\n\t\treturn &he;\n\t}\n\treturn NULL;\n}\n\n#ifndef MSG_FASTOPEN\n#   define MSG_FASTOPEN 0x20000000\n#endif\n\nHOOKFUNC(ssize_t, sendto, int sockfd, const void *buf, size_t len, int flags,\n\t       const struct sockaddr *dest_addr, socklen_t addrlen) {\n\tINIT();\n\tPFUNC();\n\tif (flags & MSG_FASTOPEN) {\n\t\tif (!connect(sockfd, dest_addr, addrlen) && errno != EINPROGRESS) {\n\t\t\treturn -1;\n\t\t}\n\t\tdest_addr = NULL;\n\t\taddrlen = 0;\n\t\tflags &= ~MSG_FASTOPEN;\n\t}\n\treturn true_sendto(sockfd, buf, len, flags, dest_addr, addrlen);\n}\n\n#ifdef MONTEREY_HOOKING\n#define SETUP_SYM(X) do { if (! true_ ## X ) true_ ## X = &X; } while(0)\n#define SETUP_SYM_OPTIONAL(X)\n#else\n#define SETUP_SYM_IMPL(X, IS_MANDATORY) do { if (! true_ ## X ) true_ ## X = load_sym( # X, X, IS_MANDATORY ); } while(0)\n#define SETUP_SYM(X) SETUP_SYM_IMPL(X, 1)\n#define SETUP_SYM_OPTIONAL(X) SETUP_SYM_IMPL(X, 0)\n#endif\n\nstatic void setup_hooks(void) {\n\tSETUP_SYM(connect);\n\tSETUP_SYM(sendto);\n\tSETUP_SYM(gethostbyname);\n\tSETUP_SYM(getaddrinfo);\n\tSETUP_SYM(freeaddrinfo);\n\tSETUP_SYM(gethostbyaddr);\n\tSETUP_SYM(getnameinfo);\n#ifdef IS_SOLARIS\n\tSETUP_SYM(__xnet_connect);\n#endif\n\tSETUP_SYM(close);\n\tSETUP_SYM_OPTIONAL(close_range);\n}\n\n#ifdef MONTEREY_HOOKING\n\n#define DYLD_INTERPOSE(_replacement,_replacee) \\\n   __attribute__((used)) static struct{ const void* replacement; const void* replacee; } _interpose_##_replacee \\\n   __attribute__((section (\"__DATA,__interpose\"))) = { (const void*)(unsigned long)&_replacement, (const void*)(unsigned long)&_replacee };\n#define DYLD_HOOK(F) DYLD_INTERPOSE(pxcng_ ## F, F)\n\nDYLD_HOOK(connect);\nDYLD_HOOK(sendto);\nDYLD_HOOK(gethostbyname);\nDYLD_HOOK(getaddrinfo);\nDYLD_HOOK(freeaddrinfo);\nDYLD_HOOK(gethostbyaddr);\nDYLD_HOOK(getnameinfo);\nDYLD_HOOK(close);\n\n#endif\n"
  },
  {
    "path": "src/main.c",
    "content": "/*   (C) 2011, 2012 rofl0r\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n ***************************************************************************/\n\n#define _DEFAULT_SOURCE\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n\n#ifdef IS_MAC\n#define _DARWIN_C_SOURCE\n#endif\n#include <dlfcn.h>\n\n#include \"common.h\"\n\nstatic int usage(char **argv) {\n\tprintf(\"\\nUsage:\\t%s -q -f config_file program_name [arguments]\\n\"\n\t       \"\\t-q makes proxychains quiet - this overrides the config setting\\n\"\n\t       \"\\t-f allows one to manually specify a configfile to use\\n\"\n\t       \"\\tfor example : proxychains telnet somehost.com\\n\" \"More help in README file\\n\\n\", argv[0]);\n\treturn EXIT_FAILURE;\n}\n\nstatic const char *dll_name = DLL_NAME;\n\nstatic char own_dir[256];\nstatic const char *dll_dirs[] = {\n#ifndef SUPER_SECURE /* CVE-2015-3887 */\n\t\".\",\n#endif\n\town_dir,\n\tLIB_DIR,\n\t\"/lib\",\n\t\"/usr/lib\",\n\t\"/usr/local/lib\",\n\t\"/lib64\",\n\tNULL\n};\n\nstatic void set_own_dir(const char *argv0) {\n\tsize_t l = strlen(argv0);\n\twhile(l && argv0[l - 1] != '/')\n\t\tl--;\n\tif(l == 0 || l >= sizeof(own_dir))\n#ifdef SUPER_SECURE\n\t\tmemcpy(own_dir, \"/dev/null/\", 11);\n#else\n\t\tmemcpy(own_dir, \".\", 2);\n#endif\n\telse {\n\t\tmemcpy(own_dir, argv0, l - 1);\n\t\town_dir[l] = 0;\n\t}\n}\n\n#define MAX_COMMANDLINE_FLAGS 2\n\nint main(int argc, char *argv[]) {\n\tchar *path = NULL;\n\tchar buf[256];\n\tchar pbuf[256];\n\tint start_argv = 1;\n\tint quiet = 0;\n\tsize_t i;\n\tconst char *prefix = NULL;\n\n\tif(argc == 2 && !strcmp(argv[1], \"--help\"))\n\t\treturn usage(argv);\n\n\tfor(i = 0; i < MAX_COMMANDLINE_FLAGS; i++) {\n\t\tif(start_argv < argc && argv[start_argv][0] == '-') {\n\t\t\tif(argv[start_argv][1] == 'q') {\n\t\t\t\tquiet = 1;\n\t\t\t\tstart_argv++;\n\t\t\t} else if(argv[start_argv][1] == 'f') {\n\n\t\t\t\tif(start_argv + 1 < argc)\n\t\t\t\t\tpath = argv[start_argv + 1];\n\t\t\t\telse\n\t\t\t\t\treturn usage(argv);\n\n\t\t\t\tstart_argv += 2;\n\t\t\t}\n\t\t} else\n\t\t\tbreak;\n\t}\n\n\tif(start_argv >= argc)\n\t\treturn usage(argv);\n\n\t/* check if path of config file has not been passed via command line */\n\tpath = get_config_path(path, pbuf, sizeof(pbuf));\n\n\tif(!quiet)\n\t\tfprintf(stderr, LOG_PREFIX \"config file found: %s\\n\", path);\n\n\t/* Set PROXYCHAINS_CONF_FILE to get proxychains lib to use new config file. */\n\tsetenv(PROXYCHAINS_CONF_FILE_ENV_VAR, path, 1);\n\n\tif(quiet)\n\t\tsetenv(PROXYCHAINS_QUIET_MODE_ENV_VAR, \"1\", 1);\n\n\n\t// search DLL\n\n\tDl_info dli;\n\tdladdr(own_dir, &dli);\n\tset_own_dir(dli.dli_fname);\n\n\ti = 0;\n\n\twhile(dll_dirs[i]) {\n\t\tsnprintf(buf, sizeof(buf), \"%s/%s\", dll_dirs[i], dll_name);\n\t\tif(access(buf, R_OK) != -1) {\n\t\t\tprefix = dll_dirs[i];\n\t\t\tbreak;\n\t\t}\n\t\ti++;\n\t}\n\n\tif(!prefix) {\n\t\tfprintf(stderr, \"couldnt locate %s\\n\", dll_name);\n\t\treturn EXIT_FAILURE;\n\t}\n\tif(!quiet)\n\t\tfprintf(stderr, LOG_PREFIX \"preloading %s/%s\\n\", prefix, dll_name);\n\n#if defined(IS_MAC) || defined(IS_OPENBSD)\n#define LD_PRELOAD_SEP \":\"\n#else\n/* Dynlinkers for Linux and most BSDs seem to support space\n   as LD_PRELOAD separator, with colon added only recently.\n   We use the old syntax for maximum compat */\n#define LD_PRELOAD_SEP \" \"\n#endif\n\n#ifdef IS_MAC\n\tputenv(\"DYLD_FORCE_FLAT_NAMESPACE=1\");\n#define LD_PRELOAD_ENV \"DYLD_INSERT_LIBRARIES\"\n#else\n#define LD_PRELOAD_ENV \"LD_PRELOAD\"\n#endif\n\tchar *old_val = getenv(LD_PRELOAD_ENV);\n\tsnprintf(buf, sizeof(buf), LD_PRELOAD_ENV \"=%s/%s%s%s\",\n\t         prefix, dll_name,\n\t         /* append previous LD_PRELOAD content, if existent */\n\t         old_val ? LD_PRELOAD_SEP : \"\",\n\t         old_val ? old_val : \"\");\n\tputenv(buf);\n\texecvp(argv[start_argv], &argv[start_argv]);\n\tfprintf(stderr, \"proxychains: can't load process '%s'.\", argv[start_argv]);\n\tperror(\" (hint: it's probably a typo)\");\n\n\treturn EXIT_FAILURE;\n}\n"
  },
  {
    "path": "src/mutex.h",
    "content": "#ifndef MUTEX_H\n#define MUTEX_H\n\n#include <pthread.h>\n# define MUTEX_LOCK(x) pthread_mutex_lock(x)\n# define MUTEX_UNLOCK(x) pthread_mutex_unlock(x)\n# define MUTEX_INIT(x) pthread_mutex_init(x, NULL)\n# define MUTEX_DESTROY(x) pthread_mutex_destroy(x)\n\n#endif\n"
  },
  {
    "path": "src/proxychains.conf",
    "content": "# proxychains.conf  VER 4.x\n#\n#        HTTP, SOCKS4a, SOCKS5 tunneling proxifier with DNS.\n\n\n# The option below identifies how the ProxyList is treated.\n# only one option should be uncommented at time,\n# otherwise the last appearing option will be accepted\n#\n#dynamic_chain\n#\n# Dynamic - Each connection will be done via chained proxies\n# all proxies chained in the order as they appear in the list\n# at least one proxy must be online to play in chain\n# (dead proxies are skipped)\n# otherwise EINTR is returned to the app\n#\nstrict_chain\n#\n# Strict - Each connection will be done via chained proxies\n# all proxies chained in the order as they appear in the list\n# all proxies must be online to play in chain\n# otherwise EINTR is returned to the app\n#\n#round_robin_chain\n#\n# Round Robin - Each connection will be done via chained proxies\n# of chain_len length\n# all proxies chained in the order as they appear in the list\n# at least one proxy must be online to play in chain\n# (dead proxies are skipped).\n# the start of the current proxy chain is the proxy after the last\n# proxy in the previously invoked proxy chain.\n# if the end of the proxy chain is reached while looking for proxies\n# start at the beginning again.\n# otherwise EINTR is returned to the app\n# These semantics are not guaranteed in a multithreaded environment.\n#\n#random_chain\n#\n# Random - Each connection will be done via random proxy\n# (or proxy chain, see  chain_len) from the list.\n# this option is good to test your IDS :)\n\n# Make sense only if random_chain or round_robin_chain\n#chain_len = 2\n\n# Quiet mode (no output from library)\n#quiet_mode\n\n## Proxy DNS requests - no leak for DNS data\n# (disable all of the 3 items below to not proxy your DNS requests)\n\n# method 1. this uses the proxychains4 style method to do remote dns:\n# a thread is spawned that serves DNS requests and hands down an ip\n# assigned from an internal list (via remote_dns_subnet).\n# this is the easiest (setup-wise) and fastest method, however on\n# systems with buggy libcs and very complex software like webbrowsers\n# this might not work and/or cause crashes.\nproxy_dns\n\n# method 2. use the old proxyresolv script to proxy DNS requests\n# in proxychains 3.1 style. requires `proxyresolv` in $PATH\n# plus a dynamically linked `dig` binary.\n# this is a lot slower than `proxy_dns`, doesn't support .onion URLs,\n# but might be more compatible with complex software like webbrowsers.\n#proxy_dns_old\n\n# method 3. use proxychains4-daemon process to serve remote DNS requests.\n# this is similar to the threaded `proxy_dns` method, however it requires\n# that proxychains4-daemon is already running on the specified address.\n# on the plus side it doesn't do malloc/threads so it should be quite\n# compatible with complex, async-unsafe software.\n# note that if you don't start proxychains4-daemon before using this,\n# the process will simply hang.\n#proxy_dns_daemon 127.0.0.1:1053\n\n# set the class A subnet number to use for the internal remote DNS mapping\n# we use the reserved 224.x.x.x range by default,\n# if the proxified app does a DNS request, we will return an IP from that range.\n# on further accesses to this ip we will send the saved DNS name to the proxy.\n# in case some control-freak app checks the returned ip, and denies to \n# connect, you can use another subnet, e.g. 10.x.x.x or 127.x.x.x.\n# of course you should make sure that the proxified app does not need\n# *real* access to this subnet. \n# i.e. dont use the same subnet then in the localnet section\n#remote_dns_subnet 127 \n#remote_dns_subnet 10\nremote_dns_subnet 224\n\n# Some timeouts in milliseconds\ntcp_read_time_out 15000\ntcp_connect_time_out 8000\n\n### Examples for localnet exclusion\n## localnet ranges will *not* use a proxy to connect.\n## note that localnet works only when plain IP addresses are passed to the app,\n## the hostname resolves via /etc/hosts, or proxy_dns is disabled or proxy_dns_old used.\n\n## Exclude connections to 192.168.1.0/24 with port 80\n# localnet 192.168.1.0:80/255.255.255.0\n\n## Exclude connections to 192.168.100.0/24\n# localnet 192.168.100.0/255.255.255.0\n\n## Exclude connections to ANYwhere with port 80\n# localnet 0.0.0.0:80/0.0.0.0\n# localnet [::]:80/0\n\n## RFC6890 Loopback address range\n## if you enable this, you have to make sure remote_dns_subnet is not 127\n## you'll need to enable it if you want to use an application that \n## connects to localhost.\n# localnet 127.0.0.0/255.0.0.0\n# localnet ::1/128\n\n## RFC1918 Private Address Ranges\n# localnet 10.0.0.0/255.0.0.0\n# localnet 172.16.0.0/255.240.0.0\n# localnet 192.168.0.0/255.255.0.0\n\n### Examples for dnat\n## Trying to proxy connections to destinations which are dnatted,\n## will result in proxying connections to the new given destinations.\n## Whenever I connect to 1.1.1.1 on port 1234 actually connect to 1.1.1.2 on port 443\n# dnat 1.1.1.1:1234  1.1.1.2:443\n\n## Whenever I connect to 1.1.1.1 on port 443 actually connect to 1.1.1.2 on port 443\n## (no need to write :443 again)\n# dnat 1.1.1.2:443  1.1.1.2\n\n## No matter what port I connect to on 1.1.1.1 port actually connect to 1.1.1.2 on port 443\n# dnat 1.1.1.1  1.1.1.2:443\n\n## Always, instead of connecting to 1.1.1.1, connect to 1.1.1.2\n# dnat 1.1.1.1  1.1.1.2\n\n# ProxyList format\n#       type  ip  port [user pass]\n#       (values separated by 'tab' or 'blank')\n#\n#       only numeric ipv4 addresses are valid\n#\n#\n#        Examples:\n#\n#            \tsocks5\t192.168.67.78\t1080\tlamer\tsecret\n#\t\thttp\t192.168.89.3\t8080\tjustu\thidden\n#\t \tsocks4\t192.168.1.49\t1080\n#\t        http\t192.168.39.93\t8080\t\n#\t\t\n#\n#       proxy types: http, socks4, socks5, raw\n#         * raw: The traffic is simply forwarded to the proxy without modification.\n#        ( auth types supported: \"basic\"-http  \"user/pass\"-socks )\n#\n[ProxyList]\n# add proxy here ...\n# meanwile\n# defaults set to \"tor\"\nsocks4 \t127.0.0.1 9050\n\n"
  },
  {
    "path": "src/proxyresolv",
    "content": "#!/bin/sh\n# This is a legacy script that uses \"dig\" or \"drill\" to do DNS lookups via TCP.\n\n# DNS server used to resolve names\ntest -z \"$DNS_SERVER\" && DNS_SERVER=8.8.8.8\n\n\nif [ $# = 0 ] ; then\n\techo \"\tusage:\"\n\techo \"\t\tproxyresolv <hostname> \"\n\texit\nfi\n\n\ntest -z $LD_PRELOAD && export LD_PRELOAD=libproxychains4.so\n\nif type dig 1>/dev/null 2>&1 ; then\ndig       $1 @$DNS_SERVER +tcp | awk '/A.?[0-9]+\\.[0-9]+\\.[0-9]/{print $5;}'\nelif type drill 1>/dev/null 2>&1 ; then\ndrill -t4 $1 @$DNS_SERVER      | awk '/A.+[0-9]+\\.[0-9]+\\.[0-9]/{print $5;}'\nelse\necho \"error: neither dig nor drill found\" >&2\nfi\n"
  },
  {
    "path": "src/rdns.c",
    "content": "#include <sys/socket.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"rdns.h\"\n#include \"allocator_thread.h\"\n#include \"remotedns.h\"\n\n#ifndef HAVE_SOCK_CLOEXEC\n#define SOCK_CLOEXEC 0\n#endif\n\n//static enum dns_lookup_flavor dns_flavor;\n#define dns_flavor rdns_get_flavor()\n\nstatic struct sockaddr_in rdns_server;\n\nsize_t rdns_daemon_get_host_for_ip(ip_type4 ip, char* readbuf) {\n\tstruct at_msg msg = {\n\t\t.h.msgtype = ATM_GETNAME,\n\t\t.h.datalen = htons(4),\n\t\t.m.ip = ip,\n\t};\n\tint fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);\n\tsendto(fd, &msg, sizeof(msg.h)+4, 0, (void*)&rdns_server, sizeof(rdns_server));\n\trecvfrom(fd, &msg, sizeof msg, 0, (void*)0, (void*)0);\n\tclose(fd);\n\tmsg.h.datalen = ntohs(msg.h.datalen);\n\tif(!msg.h.datalen || msg.h.datalen > 256) return 0;\n\tmemcpy(readbuf, msg.m.host, msg.h.datalen);\n\treturn msg.h.datalen - 1;\n}\n\nstatic ip_type4 rdns_daemon_get_ip_for_host(char* host, size_t len) {\n\tstruct at_msg msg = {\n\t\t.h.msgtype = ATM_GETIP,\n\t};\n\tif(len >= 256) return IPT4_INT(-1);\n\tmemcpy(msg.m.host, host, len+1);\n\tmsg.h.datalen = htons(len+1);\n\tint fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);\n\tsendto(fd, &msg, sizeof(msg.h)+len+1, 0, (void*)&rdns_server, sizeof(rdns_server));\n\trecvfrom(fd, &msg, sizeof msg, 0, (void*)0, (void*)0);\n\tclose(fd);\n\tif(ntohs(msg.h.datalen) != 4) return IPT4_INT(-1);\n\treturn msg.m.ip;\n}\n\nconst char *rdns_resolver_string(enum dns_lookup_flavor flavor) {\n\tstatic const char tab[][7] = {\n\t\t[DNSLF_LIBC] = \"off\",\n\t\t[DNSLF_FORKEXEC] = \"old\",\n\t\t[DNSLF_RDNS_THREAD] = \"thread\",\n\t\t[DNSLF_RDNS_DAEMON] = \"daemon\",\n\t};\n\treturn tab[flavor];\n}\n\nvoid rdns_init(enum dns_lookup_flavor flavor) {\n\tstatic int init_done = 0;\n\tif(!init_done) switch(flavor) {\n\t\tcase DNSLF_RDNS_THREAD:\n\t\t\tat_init();\n\t\t\tbreak;\n\t\tcase DNSLF_RDNS_DAEMON:\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\tinit_done = 1;\n}\n\nvoid rdns_set_daemon(struct sockaddr_in* addr) {\n\trdns_server = *addr;\n}\n\n#if 0\nenum dns_lookup_flavor rdns_get_flavor(void) {\n\treturn dns_flavor;\n}\n#endif\n\nsize_t rdns_get_host_for_ip(ip_type4 ip, char* readbuf) {\n\tswitch(dns_flavor) {\n\t\tcase DNSLF_RDNS_THREAD: return at_get_host_for_ip(ip, readbuf);\n\t\tcase DNSLF_RDNS_DAEMON: return rdns_daemon_get_host_for_ip(ip, readbuf);\n\t\tdefault:\n\t\t\tabort();\n\t}\n}\n\nip_type4 rdns_get_ip_for_host(char* host, size_t len) {\n\tswitch(dns_flavor) {\n\t\tcase DNSLF_RDNS_THREAD: return at_get_ip_for_host(host, len);\n\t\tcase DNSLF_RDNS_DAEMON: return rdns_daemon_get_ip_for_host(host, len);\n\t\tdefault:\n\t\t\tabort();\n\t}\n}\n\n"
  },
  {
    "path": "src/rdns.h",
    "content": "#ifndef RDNS_H\n#define RDNS_H\n\n#include <unistd.h>\n#include <netinet/in.h>\n#include \"ip_type.h\"\n#include \"remotedns.h\"\n\nenum dns_lookup_flavor {\n\tDNSLF_LIBC = 0,\n\tDNSLF_FORKEXEC,\n\n\tDNSLF_RDNS_START,\n\tDNSLF_RDNS_THREAD = DNSLF_RDNS_START,\n\tDNSLF_RDNS_DAEMON,\n};\n\nvoid rdns_init(enum dns_lookup_flavor flavor);\nvoid rdns_set_daemon(struct sockaddr_in* addr);\nconst char *rdns_resolver_string(enum dns_lookup_flavor flavor);\nsize_t rdns_get_host_for_ip(ip_type4 ip, char* readbuf);\nip_type4 rdns_get_ip_for_host(char* host, size_t len);\n\n//enum dns_lookup_flavor rdns_get_flavor(void);\n#define rdns_get_flavor() proxychains_resolver\nextern enum dns_lookup_flavor proxychains_resolver;\n\n#endif\n"
  },
  {
    "path": "src/remotedns.h",
    "content": "#ifndef REMOTEDNS_H\n#define REMOTEDNS_H\n\n#include <unistd.h>\n#include \"ip_type.h\"\n\n#define MSG_LEN_MAX 256\n\nenum at_msgtype {\n\tATM_GETIP = 0,\n\tATM_GETNAME,\n\tATM_FAIL,\n\tATM_EXIT,\n};\n\nstruct at_msghdr {\n\tunsigned char msgtype; /* at_msgtype */\n\tchar reserved;\n\tunsigned short datalen;\n};\n\nstruct at_msg {\n\tstruct at_msghdr h;\n\tunion {\n\t\tchar host[260];\n\t\tip_type4 ip;\n\t} m;\n};\n\n#endif\n\n"
  },
  {
    "path": "src/version.c",
    "content": "#include \"version.h\"\nstatic const char version[] = VERSION;\nconst char *proxychains_get_version(void) {\n\treturn version;\n}\n\n"
  },
  {
    "path": "tests/test_getaddrinfo.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <sys/socket.h>\n#include <assert.h>\n#include <string.h>\n\n#ifndef   NI_MAXHOST\n#define   NI_MAXHOST 1025\n#endif\n\nstatic int doit(const char* host, const char* service) {\n\tstruct addrinfo *result;\n\tstruct addrinfo *res;\n\tint error;\n\n\t/* resolve the domain name into a list of addresses */\n\terror = getaddrinfo(host, service, NULL, &result);\n\tif (error != 0)\n\t{\n\t\tfprintf(stderr, \"error in getaddrinfo: %s\\n\", gai_strerror(error));\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t/* loop over all returned results and do inverse lookup */\n\tfor (res = result; res != NULL; res = res->ai_next)\n\t{\n\t\tchar hostname[NI_MAXHOST] = \"\";\n\n\t\terror = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0);\n\t\tif (error != 0)\n\t\t{\n\t\tfprintf(stderr, \"error in getnameinfo: %s\\n\", gai_strerror(error));\n\t\tcontinue;\n\t\t}\n\t\tint port = 0;\n\t\tif(res->ai_family == AF_INET) port = ((struct sockaddr_in*)res->ai_addr)->sin_port;\n\t\telse if(res->ai_family == AF_INET6) port = ((struct sockaddr_in6*)res->ai_addr)->sin6_port;\n\t\tport = ntohs(port);\n\t\tprintf(\"hostname: %s, port: %d\\n\", hostname, port);\n\t}\n\n\tfreeaddrinfo(result);\n\treturn EXIT_SUCCESS;\n}\n\n/* reproduce use of getaddrinfo as used by nmap 7.91's canonicalize_address */\nint canonicalize_address(struct sockaddr_storage *ss, struct sockaddr_storage *output) {\n\tchar canonical_ip_string[NI_MAXHOST];\n\tstruct addrinfo *ai;\n\tint rc;\n\t/* Convert address to string. */\n\trc = getnameinfo((struct sockaddr *) ss, sizeof(*ss),\n\t\tcanonical_ip_string, sizeof(canonical_ip_string), NULL, 0, NI_NUMERICHOST);\n\tassert(rc == 0);\n\tstruct addrinfo hints = {\n\t\t.ai_family = ss->ss_family,\n\t\t.ai_socktype = SOCK_DGRAM,\n\t\t.ai_flags = AI_NUMERICHOST,\n\t};\n\trc = getaddrinfo(canonical_ip_string, NULL, &hints, &ai);\n\tif (rc != 0 || ai == NULL)\n\t\treturn -1;\n\tassert(ai->ai_addrlen > 0 && ai->ai_addrlen <= (int) sizeof(*output));\n\tmemcpy(output, ai->ai_addr, ai->ai_addrlen);\n\tfreeaddrinfo(ai);\n\treturn 0;\n}\n\nint main(void) {\n\tint ret;\n\tret = doit(\"www.example.com\", NULL);\n\tret = doit(\"www.example.com\", \"80\");\n\tstruct sockaddr_storage o, ss = {.ss_family = PF_INET};\n\tstruct sockaddr_in *v4 = &ss;\n\tstruct sockaddr_in6 *v6 = &ss;\n\tmemcpy(&v4->sin_addr, \"\\x7f\\0\\0\\1\", 4);\n\tret = canonicalize_address(&ss, &o);\n\tassert (ret == 0);\n\tss.ss_family = PF_INET6;\n\tmemcpy(&v6->sin6_addr, \"\\0\\0\\0\\0\" \"\\0\\0\\0\\0\" \"\\0\\0\\0\\0\"\"\\0\\0\\0\\1\", 16);\n\tret = canonicalize_address(&ss, &o);\n\tassert (ret == 0);\n\treturn ret;\n}\n"
  },
  {
    "path": "tests/test_gethostbyname.c",
    "content": "#include <stdio.h>\n#include <netdb.h>\n#include \"../src/common.c\"\n\nvoid printhostent(struct hostent *hp) {\n\tchar ipbuf[16];\n\tpc_stringfromipv4(hp->h_addr_list[0], ipbuf);\n\tprintf(\"alias: %p, len: %d, name: %s, addrlist: %p, addrtype: %d, ip: %s\\n\", \n\t\thp->h_aliases, \n\t\thp->h_length,\n\t\thp->h_name,\n\t\thp->h_addr_list,\n\t\thp->h_addrtype,\n\t\tipbuf\n\t);\n}\nint main(int argc, char**argv) {\n\tstruct hostent* ret;\n\tif(argc == 1) return 1;\n\tret = gethostbyname(argv[1]);\n\tif(ret) printhostent(ret);\n\treturn 0;\n}\n"
  },
  {
    "path": "tests/test_gethostent.c",
    "content": "#include <netdb.h>\n#include <stdio.h>\n#include \"../src/common.c\"\n\nvoid printhostent(struct hostent *hp) {\n\tchar ipbuf[16];\n\tpc_stringfromipv4(hp->h_addr_list[0], ipbuf);\n\tprintf(\"alias: %p, len: %d, name: %s, addrlist: %p, addrtype: %d, ip: %s\\n\", \n\t\thp->h_aliases, \n\t\thp->h_length,\n\t\thp->h_name,\n\t\thp->h_addr_list,\n\t\thp->h_addrtype,\n\t\tipbuf\n\t);\n}\n\nint main(int argc, char** argv) {\n\tstruct hostent *hp;\n\twhile((hp = gethostent())) {\n\t\tprinthostent(hp);\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "tests/test_gethostent_r.c",
    "content": "#include <netdb.h>\n#include <stdio.h>\n#include <errno.h>\n#include \"../src/common.h\"\n\n/*\nint gethostent_r( \n        struct hostent *ret, char *buf, size_t buflen,\n        struct hostent **result, int *h_errnop);\n\nGlibc2 also has reentrant versions gethostent_r(), gethostbyaddr_r(),\ngethostbyname_r() and gethostbyname2_r(). \n\nThe caller supplies a hostent structure ret which will be filled in on success, \nand a temporary work buffer buf of size buflen. \nAfter the call, result will point to the result on success. \nIn case of an error or if no entry is found result will be NULL. \nThe functions return 0 on success and a nonzero error number on failure. \nIn addition to the errors returned by the nonreentrant versions of these functions, \nif buf is too small, the functions will return ERANGE, and the call should be retried \nwith a larger buffer. \nThe global variable h_errno is not modified, but the address of a variable in which \nto store error numbers is passed in h_errnop.\n*/\n\nvoid printhostent(struct hostent *hp) {\n\tchar ipbuf[16];\n\tpc_stringfromipv4(hp->h_addr_list[0], ipbuf);\n\tprintf(\"alias: %p, len: %d, name: %s, addrlist: %p, addrtype: %d, ip: %s\\n\", \n\t\thp->h_aliases, \n\t\thp->h_length,\n\t\thp->h_name,\n\t\thp->h_addr_list,\n\t\thp->h_addrtype,\n\t\tipbuf\n\t);\n}\n\nint main(int argc, char** argv) {\n\tstruct hostent he_buf;\n\tstruct hostent *he_res;\n\tchar h_buf[1024];\n\tint ch_errno;\n\tint ret;\n\tdo {\n\t\tret = gethostent_r(&he_buf, h_buf, sizeof(h_buf), &he_res, &ch_errno);\n\t\tprintf(\"ret: %d, h_errno: %d\\n\", ret, ch_errno);\n\t\tif(ret != 0) {\n\t\t\terrno = ret;\n\t\t\tret = -1;\n\t\t}\n\t\tif(ret == -1) {\n\t\t\tperror(\"gethostent_r\");\n\t\t\tbreak;\n\t\t}\n\t\tif(he_res) {\n\t\t\tprinthostent(he_res);\n\t\t}\n\t} while (he_res);\n\treturn 0;\n}"
  },
  {
    "path": "tests/test_getnameinfo.c",
    "content": "#include <netdb.h>\n#include <stdio.h>\n#include <string.h>\n#include <assert.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n\n#define     satosin(x)      ((struct sockaddr_in *) &(x))\n#define     SOCKADDR(x)     (satosin(x)->sin_addr.s_addr)\n#define     SOCKADDR_2(x)     (satosin(x)->sin_addr)\n#define     SOCKPORT(x)     (satosin(x)->sin_port)\n#define     SOCKFAMILY(x)     (satosin(x)->sin_family)\n\n#define ASSERT(X) { if(!(X)) printf(\"ASSERTION FAILED: %s @%s:%d\\n\", # X, __FILE__, __LINE__); }\n#define CLR() { hbuf[0] = 0; sbuf[0] = 0; }\n\nint main() {\n\tstruct sockaddr_in a = {0}, *sa = &a;\n\tchar hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];\n\ta.sin_port = htons(80);\n\tmemcpy(  &a.sin_addr   , (char[]) {127,0,0,1}, 4);\n\n\tint ret;\n\n\tif ((ret = getnameinfo((void*)sa, 0, hbuf, sizeof(hbuf), sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == EAI_FAMILY);\n\tCLR();\n\n\tif ((ret = getnameinfo((void*)sa, sizeof a, hbuf, sizeof(hbuf), sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == EAI_FAMILY);\n\tCLR();\n\n\tSOCKFAMILY(a) = AF_INET;\n\n\tif ((ret = getnameinfo((void*)sa, sizeof a, hbuf, 1, sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == EAI_OVERFLOW);\n\tCLR();\n\n\tif ((ret = getnameinfo((void*)sa, sizeof a, hbuf, 0, sbuf,\n\t    1, NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == EAI_OVERFLOW);\n\tCLR();\n\n\tif ((ret = getnameinfo((void*)sa, sizeof(a) - 1, hbuf, 0, sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == EAI_FAMILY);\n\tCLR();\n\n\tif ((ret = getnameinfo((void*)sa, sizeof a, hbuf, 0, sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == 0 && !strcmp(\"80\", sbuf));\n\tCLR();\n\n\tif ((ret = getnameinfo((void*)sa, sizeof a, hbuf, sizeof hbuf, sbuf,\n\t    0, NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == 0 && !strcmp(\"127.0.0.1\",hbuf));\n\tCLR();\n\n\n\tif ((ret = getnameinfo((void*)sa, sizeof a, hbuf, sizeof(hbuf), sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == 0 && !strcmp(\"127.0.0.1\",hbuf) && !strcmp(\"80\", sbuf));\n\tCLR();\n\n\tstruct sockaddr_in6 b = {0}, *sb = &b;\n\tb.sin6_port = htons(8080);\n\tb.sin6_family = AF_INET6;\n\n\tmemcpy(&b.sin6_addr,\"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xff\\xc0\\xa8\\1\\2\", 16);\n\n\tif ((ret = getnameinfo((void*)sb, sizeof b, hbuf, sizeof(hbuf), sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == 0 && !strcmp(\"192.168.1.2\",hbuf) && !strcmp(\"8080\", sbuf));\n\tCLR();\n\n\tb.sin6_scope_id = 3;\n\tmemcpy(&b.sin6_addr,\"\\0\\0\\xaa\\0\\0\\0\\0\\0\\0\\0\\0\\xff\\xc0\\xa8\\1\\2\", 16);\n\n\tif ((ret = getnameinfo((void*)sb, sizeof b, hbuf, sizeof(hbuf), sbuf,\n\t    sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV | NI_NUMERICSCOPE)) == 0)\n\t\tprintf(\"host=%s, serv=%s\\n\", hbuf, sbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == 0);\n\n\tb.sin6_port = 0;\n\tb.sin6_scope_id = 0;\n\tmemcpy(&b.sin6_addr,\"\\0\\0\\0\\0\" \"\\0\\0\\0\\0\" \"\\0\\0\\0\\0\" \"\\0\\0\\0\\1\", 16);\n\n\tif ((ret = getnameinfo((void*)sb, sizeof b, hbuf, sizeof(hbuf), NULL,\n\t    0, NI_NUMERICHOST)) == 0)\n\t\tprintf(\"host=%s\\n\", hbuf);\n\telse\n\t\tprintf(\"%s\\n\", gai_strerror(ret));\n\n\tASSERT(ret == 0);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "tests/test_proxy_gethostbyname.c",
    "content": "#include \"../src/core.h\"\n#include \"../src/common.h\"\n#include <stdio.h>\n\nvoid printhostent(struct hostent *hp) {\n\tchar ipbuf[16];\n\tpc_stringfromipv4(hp->h_addr_list[0], ipbuf);\n\tprintf(\"alias: %p, len: %d, name: %s, addrlist: %p, addrtype: %d, ip: %s\\n\", \n\t\thp->h_aliases, \n\t\thp->h_length,\n\t\thp->h_name,\n\t\thp->h_addr_list,\n\t\thp->h_addrtype,\n\t\tipbuf\n\t);\n}\nint main(int argc, char**argv) {\n\tstruct hostent* ret;\n\tstruct gethostbyname_data data;\n\tif(argc == 1) return 1;\n\tret = proxy_gethostbyname(argv[1], &data);\n\tif(ret) printhostent(ret);\n\treturn 0;\n}"
  },
  {
    "path": "tests/test_sendto.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netdb.h>\n\n#ifndef MSG_FASTOPEN\n#   define MSG_FASTOPEN 0x20000000\n#endif\n\nvoid error(const char *msg)\n{\n\tperror(msg);\n\texit(1);\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 4) {\n\t\tprintf(\"Usage: %s host port method(connect or sendto)\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\tconst char *hostname = argv[1];\n\tconst int portno = atoi(argv[2]);\n\tconst char *method = argv[3];\n\tchar request[BUFSIZ];\n\tsprintf(request, \"GET / HTTP/1.0\\r\\nHost: %s\\r\\n\\r\\n\", hostname);\n\tint sockfd, n;\n\tstruct sockaddr_in serv_addr;\n\tstruct hostent *server;\n\n\tchar buffer[BUFSIZ];\n\tsockfd = socket(AF_INET, SOCK_STREAM, 0);\n\tif (sockfd < 0) error(\"ERROR opening socket\");\n\tserver = gethostbyname(hostname);\n\tif (server == NULL) {\n\t\tfprintf(stderr, \"%s: no such host\\n\", hostname);\n\t\treturn 1;\n\t}\n\tmemset(&serv_addr, 0, sizeof(serv_addr));\n\tserv_addr.sin_family = AF_INET;\n\tmemcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);\n\tserv_addr.sin_port = htons(portno);\n\tif (!strcmp(method, \"connect\")) {\n\t  if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)\n\t\t  error(\"connect\");\n\t  n = send(sockfd, request, strlen(request), 0);\n\t} else if (!strcmp(method, \"sendto\")) {\n\t  n = sendto(sockfd, request, strlen(request), MSG_FASTOPEN, (struct sockaddr *)&serv_addr, sizeof(serv_addr));\n\t} else {\n\t  printf(\"Unknown method %s\\n\", method);\n\t  return 1;\n\t}\n\tif (n < 0)\n\t\t error(\"send\");\n\tmemset(buffer, 0, BUFSIZ);\n\tn = read(sockfd, buffer, BUFSIZ - 1);\n\tif (n < 0)\n\t\t error(\"ERROR reading from socket\");\n\tprintf(\"%s\\n\", buffer);\n\tclose(sockfd);\n\treturn 0;\n}\n"
  },
  {
    "path": "tests/test_shm.c",
    "content": "#include \"../src/shm.h\"\n#include <assert.h>\n\n#define s(A) (sizeof(A) - 1)\n#define ss(A) (A), s(A)\n\nint main() {\n\tchar buf4096[4096];\n\tstruct stringpool sp;\n\tstringpool_init(&sp);\n\tchar *r;\n\tsize_t pos = 0;\n\tr = stringpool_add(&sp, ss(\"AAAAA\"));\n\tassert(r == sp.start);\n\t\n\tpos += s(\"AAAAA\");\n\tassert(sp.alloced == 4096);\n\tassert(sp.used == pos);\n\t\n\tr = stringpool_add(&sp, buf4096, sizeof(buf4096));\n\tassert(r == sp.start + pos);\n\t\n\tpos += sizeof(buf4096);\n\tassert(sp.alloced == 4096 * 2);\n\tassert(sp.used == pos);\n\t\n\tr = stringpool_add(&sp, buf4096, 4096 - s(\"AAAAA\"));\n\tassert(r == sp.start + pos);\n\tpos += 4096 - s(\"AAAAA\");\n\tassert(pos == 4096 * 2);\n\n\tassert(sp.alloced == 4096 * 2);\n\tassert(sp.used == pos);\n\t\n\t\n\t\n\treturn 0;\n\t\n}"
  },
  {
    "path": "tests/test_v4_in_v6.c",
    "content": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <sys/socket.h>\n\nstatic void v4_to_v6(const struct in_addr *v4, struct in6_addr *v6) {\n\tmemset(v6, 0, sizeof(*v6));\n\tv6->s6_addr[10]=0xff;\n\tv6->s6_addr[11]=0xff;\n\tmemcpy(&v6->s6_addr[12], &v4->s_addr, 4);\n}\n\nint main(void) {\n\tstruct addrinfo *result;\n\tstruct addrinfo *res;\n\tconst struct addrinfo hints = { .ai_family = AF_INET };\n\tint error, sock;\n\n\t/* resolve the domain name into a list of addresses */\n\terror = getaddrinfo(\"www.example.com\", NULL, &hints, &result);\n\tif (error != 0)\t{\n\t\tfprintf(stderr, \"error in getaddrinfo: %s\\n\", gai_strerror(error));\n\t\treturn EXIT_FAILURE;\n\t}\n\tif((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {\n\t\tperror(\"socket\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tstruct sockaddr_in6 a = { .sin6_family = AF_INET6,\n\t                          .sin6_port = htons(80) };\n\tv4_to_v6(&((struct sockaddr_in *)result->ai_addr)->sin_addr, &a.sin6_addr);\n\tfreeaddrinfo(result);\n\n\tif((error = connect(sock, (struct sockaddr *)&a, sizeof(a))) == -1) {\n\t\tperror(\"connect\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "tools/install.sh",
    "content": "#!/bin/sh\n#\n# This is an actually-safe install command which installs the new\n# file atomically in the new location, rather than overwriting\n# existing files.\n#\n\nusage() {\nprintf \"usage: %s [-D] [-l] [-m mode] src dest\\n\" \"$0\" 1>&2\nexit 1\n}\n\nmkdirp=\nsymlink=\nmode=755\n\nwhile getopts Dlm: name ; do\ncase \"$name\" in\nD) mkdirp=yes ;;\nl) symlink=yes ;;\nm) mode=$OPTARG ;;\n?) usage ;;\nesac\ndone\nshift $(($OPTIND - 1))\n\ntest \"$#\" -eq 2 || usage\nsrc=$1\ndst=$2\ntmp=\"$dst.tmp.$$\"\n\ncase \"$dst\" in\n*/) printf \"%s: %s ends in /\\n\", \"$0\" \"$dst\" 1>&2 ; exit 1 ;;\nesac\n\nset -C\nset -e\n\nif test \"$mkdirp\" ; then\numask 022\ncase \"$2\" in\n*/*) mkdir -p \"${dst%/*}\" ;;\nesac\nfi\n\ntrap 'rm -f \"$tmp\"' EXIT INT QUIT TERM HUP\n\numask 077\n\nif test \"$symlink\" ; then\nln -s \"$1\" \"$tmp\"\nelse\ncat < \"$1\" > \"$tmp\"\nchmod \"$mode\" \"$tmp\"\nfi\n\nmv -f \"$tmp\" \"$2\"\ntest -d \"$2\" && {\nrm -f \"$2/$tmp\"\nprintf \"%s: %s is a directory\\n\" \"$0\" \"$dst\" 1>&2\nexit 1\n}\n\nexit 0\n"
  },
  {
    "path": "tools/version.sh",
    "content": "#!/bin/sh\n\nif test -d .git ; then\nif type git >/dev/null 2>&1 ; then\ngit describe --tags --match 'v[0-9]*' 2>/dev/null \\\n| sed -e 's/^v//' -e 's/-/-git-/'\nelse\nsed 's/$/-git/' < VERSION\nfi\nelse\ncat VERSION\nfi\n"
  }
]