From b39163fd596e1a038205c0e7e5300169ccb1fb65 Mon Sep 17 00:00:00 2001 From: Packit Date: Sep 23 2020 13:34:30 +0000 Subject: libproxy-0.4.15 base --- diff --git a/.cproject b/.cproject new file mode 100644 index 0000000..7bf7857 --- /dev/null +++ b/.cproject @@ -0,0 +1,1307 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/usr/bin/gmake + +install +true +false + + +/usr/bin/gmake + +install/local +true +false + + +/usr/bin/gmake + +install/strip +true +false + + +/usr/bin/gmake + +list_install_components +true +false + + +/usr/bin/gmake + +rebuild_cache +true +false + + +/usr/bin/gmake + +test +true +false + + +/usr/bin/gmake + +all +true +false + + +/usr/bin/gmake + +clean +true +false + + +/usr/bin/gmake + +libmodman +true +false + + +/usr/bin/gmake + +libmodman/fast +true +false + + +/usr/bin/gmake + +all +true +false + + +/usr/bin/gmake + +clean +true +false + + +/usr/bin/gmake + +module_manager.cpp.o +true +false + + +/usr/bin/gmake + +module_manager.cpp.i +true +false + + +/usr/bin/gmake + +module_manager.cpp.s +true +false + + +/usr/bin/gmake + +condition +true +false + + +/usr/bin/gmake + +condition/fast +true +false + + +/usr/bin/gmake + +condition_one +true +false + + +/usr/bin/gmake + +condition_one/fast +true +false + + +/usr/bin/gmake + +condition_two +true +false + + +/usr/bin/gmake + +condition_two/fast +true +false + + +/usr/bin/gmake + +singleton +true +false + + +/usr/bin/gmake + +singleton/fast +true +false + + +/usr/bin/gmake + +singleton_one +true +false + + +/usr/bin/gmake + +singleton_one/fast +true +false + + +/usr/bin/gmake + +singleton_two +true +false + + +/usr/bin/gmake + +singleton_two/fast +true +false + + +/usr/bin/gmake + +sorted +true +false + + +/usr/bin/gmake + +sorted/fast +true +false + + +/usr/bin/gmake + +sorted_one +true +false + + +/usr/bin/gmake + +sorted_one/fast +true +false + + +/usr/bin/gmake + +sorted_two +true +false + + +/usr/bin/gmake + +sorted_two/fast +true +false + + +/usr/bin/gmake + +symbol +true +false + + +/usr/bin/gmake + +symbol/fast +true +false + + +/usr/bin/gmake + +symbol_one +true +false + + +/usr/bin/gmake + +symbol_one/fast +true +false + + +/usr/bin/gmake + +symbol_two +true +false + + +/usr/bin/gmake + +symbol_two/fast +true +false + + +/usr/bin/gmake + +symbollnk +true +false + + +/usr/bin/gmake + +symbollnk/fast +true +false + + +/usr/bin/gmake + +all +true +false + + +/usr/bin/gmake + +clean +true +false + + +/usr/bin/gmake + +libmodman/test/condition_one.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/condition_one.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/condition_one.cpp.s +true +false + + +/usr/bin/gmake + +libmodman/test/condition_two.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/condition_two.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/condition_two.cpp.s +true +false + + +/usr/bin/gmake + +libmodman/test/singleton_one.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/singleton_one.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/singleton_one.cpp.s +true +false + + +/usr/bin/gmake + +libmodman/test/singleton_two.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/singleton_two.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/singleton_two.cpp.s +true +false + + +/usr/bin/gmake + +libmodman/test/sorted_one.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/sorted_one.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/sorted_one.cpp.s +true +false + + +/usr/bin/gmake + +libmodman/test/sorted_two.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/sorted_two.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/sorted_two.cpp.s +true +false + + +/usr/bin/gmake + +libmodman/test/symbol_one.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/symbol_one.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/symbol_one.cpp.s +true +false + + +/usr/bin/gmake + +libmodman/test/symbol_two.cpp.o +true +false + + +/usr/bin/gmake + +libmodman/test/symbol_two.cpp.i +true +false + + +/usr/bin/gmake + +libmodman/test/symbol_two.cpp.s +true +false + + +/usr/bin/gmake + +main.cpp.o +true +false + + +/usr/bin/gmake + +main.cpp.i +true +false + + +/usr/bin/gmake + +main.cpp.s +true +false + + +/usr/bin/gmake + +config_envvar +true +false + + +/usr/bin/gmake + +config_envvar/fast +true +false + + +/usr/bin/gmake + +config_gnome +true +false + + +/usr/bin/gmake + +config_gnome/fast +true +false + + +/usr/bin/gmake + +config_kde4 +true +false + + +/usr/bin/gmake + +config_kde4/fast +true +false + + +/usr/bin/gmake + +ignore_domain +true +false + + +/usr/bin/gmake + +ignore_domain/fast +true +false + + +/usr/bin/gmake + +ignore_hostname +true +false + + +/usr/bin/gmake + +ignore_hostname/fast +true +false + + +/usr/bin/gmake + +ignore_ip +true +false + + +/usr/bin/gmake + +ignore_ip/fast +true +false + + +/usr/bin/gmake + +libproxy +true +false + + +/usr/bin/gmake + +libproxy/fast +true +false + + +/usr/bin/gmake + +network_networkmanager +true +false + + +/usr/bin/gmake + +network_networkmanager/fast +true +false + + +/usr/bin/gmake + +pacrunner_mozjs +true +false + + +/usr/bin/gmake + +pacrunner_mozjs/fast +true +false + + +/usr/bin/gmake + +pacrunner_webkit +true +false + + +/usr/bin/gmake + +pacrunner_webkit/fast +true +false + + +/usr/bin/gmake + +pxgconf +true +false + + +/usr/bin/gmake + +pxgconf/fast +true +false + + +/usr/bin/gmake + +uninstall +true +false + + +/usr/bin/gmake + +wpad_dns_alias +true +false + + +/usr/bin/gmake + +wpad_dns_alias/fast +true +false + + +/usr/bin/gmake + +all +true +false + + +/usr/bin/gmake + +clean +true +false + + +/usr/bin/gmake + +extension_config.cpp.o +true +false + + +/usr/bin/gmake + +extension_config.cpp.i +true +false + + +/usr/bin/gmake + +extension_config.cpp.s +true +false + + +/usr/bin/gmake + +extension_pacrunner.cpp.o +true +false + + +/usr/bin/gmake + +extension_pacrunner.cpp.i +true +false + + +/usr/bin/gmake + +extension_pacrunner.cpp.s +true +false + + +/usr/bin/gmake + +extension_wpad.cpp.o +true +false + + +/usr/bin/gmake + +extension_wpad.cpp.i +true +false + + +/usr/bin/gmake + +extension_wpad.cpp.s +true +false + + +/usr/bin/gmake + +modules/config_envvar.cpp.o +true +false + + +/usr/bin/gmake + +modules/config_envvar.cpp.i +true +false + + +/usr/bin/gmake + +modules/config_envvar.cpp.s +true +false + + +/usr/bin/gmake + +modules/config_gnome.cpp.o +true +false + + +/usr/bin/gmake + +modules/config_gnome.cpp.i +true +false + + +/usr/bin/gmake + +modules/config_gnome.cpp.s +true +false + + +/usr/bin/gmake + +modules/config_kde4.cpp.o +true +false + + +/usr/bin/gmake + +modules/config_kde4.cpp.i +true +false + + +/usr/bin/gmake + +modules/config_kde4.cpp.s +true +false + + +/usr/bin/gmake + +modules/ignore_domain.cpp.o +true +false + + +/usr/bin/gmake + +modules/ignore_domain.cpp.i +true +false + + +/usr/bin/gmake + +modules/ignore_domain.cpp.s +true +false + + +/usr/bin/gmake + +modules/ignore_hostname.cpp.o +true +false + + +/usr/bin/gmake + +modules/ignore_hostname.cpp.i +true +false + + +/usr/bin/gmake + +modules/ignore_hostname.cpp.s +true +false + + +/usr/bin/gmake + +modules/ignore_ip.cpp.o +true +false + + +/usr/bin/gmake + +modules/ignore_ip.cpp.i +true +false + + +/usr/bin/gmake + +modules/ignore_ip.cpp.s +true +false + + +/usr/bin/gmake + +modules/network_networkmanager.cpp.o +true +false + + +/usr/bin/gmake + +modules/network_networkmanager.cpp.i +true +false + + +/usr/bin/gmake + +modules/network_networkmanager.cpp.s +true +false + + +/usr/bin/gmake + +modules/pacrunner_mozjs.cpp.o +true +false + + +/usr/bin/gmake + +modules/pacrunner_mozjs.cpp.i +true +false + + +/usr/bin/gmake + +modules/pacrunner_mozjs.cpp.s +true +false + + +/usr/bin/gmake + +modules/pacrunner_webkit.cpp.o +true +false + + +/usr/bin/gmake + +modules/pacrunner_webkit.cpp.i +true +false + + +/usr/bin/gmake + +modules/pacrunner_webkit.cpp.s +true +false + + +/usr/bin/gmake + +modules/pxgconf.cpp.o +true +false + + +/usr/bin/gmake + +modules/pxgconf.cpp.i +true +false + + +/usr/bin/gmake + +modules/pxgconf.cpp.s +true +false + + +/usr/bin/gmake + +modules/wpad_dns_alias.cpp.o +true +false + + +/usr/bin/gmake + +modules/wpad_dns_alias.cpp.i +true +false + + +/usr/bin/gmake + +modules/wpad_dns_alias.cpp.s +true +false + + +/usr/bin/gmake + +proxy.cpp.o +true +false + + +/usr/bin/gmake + +proxy.cpp.i +true +false + + +/usr/bin/gmake + +proxy.cpp.s +true +false + + +/usr/bin/gmake + +url.cpp.o +true +false + + +/usr/bin/gmake + +url.cpp.i +true +false + + +/usr/bin/gmake + +url.cpp.s +true +false + + +/usr/bin/gmake + +all +true +false + + +/usr/bin/gmake + +clean +true +false + + +/usr/bin/gmake + +proxy +true +false + + +/usr/bin/gmake + +proxy/fast +true +false + + +/usr/bin/gmake + +all +true +false + + +/usr/bin/gmake + +clean +true +false + + +/usr/bin/gmake + +proxy.c.o +true +false + + +/usr/bin/gmake + +proxy.c.i +true +false + + +/usr/bin/gmake + +proxy.c.s +true +false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..222a67b --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +CMakeFiles +*.cmake +Makefile +CMakeCache.txt +*.swp +Temporary +*.tcl +*.so* +*.pm + +/bindings/perl/src/Libproxy.c +/libproxy-1.0.pc +/libproxy/pxgsettings +/libproxy/pxgconf +/libproxy/test/get-pac-test +/libproxy/test/url-test +/libproxy/test/url-encode +/utils/proxy diff --git a/.project b/.project new file mode 100644 index 0000000..0cbd4af --- /dev/null +++ b/.project @@ -0,0 +1,111 @@ + + + libproxy@libproxy + + + + + + org.eclipse.cdt.make.core.makeBuilder + clean,full,incremental, + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.enabledIncrementalBuild + true + + + org.eclipse.cdt.make.core.build.command + /usr/bin/gmake + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.build.target.inc + all + + + org.eclipse.cdt.make.core.build.arguments + + + + org.eclipse.cdt.make.core.buildLocation + /home/nathaniel/Projects/libproxy + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + false + + + org.eclipse.cdt.make.core.environment + VERBOSE=1| + + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.build.target.auto + all + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.build.target.clean + clean + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.build.location + /home/nathaniel/Projects/libproxy + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.core.errorOutputParser + org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;org.eclipse.cdt.core.GASErrorParser;org.eclipse.cdt.core.GLDErrorParser; + + + + + org.eclipse.cdt.make.core.ScannerConfigBuilder + + + + + + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.make.core.makeNature + org.eclipse.cdt.make.core.ScannerConfigNature + org.eclipse.cdt.core.cnature + + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..5ab2a02 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,31 @@ +language: cpp + +os: + - linux + - osx + +compiler: + - clang + - gcc + +install: +# create /etc/sysconfig so that the build process enables this module (build test) + - | + if [[ "$TRAVIS_OS_NAME" = "linux" ]]; then + sudo mkdir /etc/sysconfig + sudo apt-get -qq update + sudo apt-get install -y libjavascriptcoregtk-3.0-dev + fi + +script: + - | + cmake . \ + -DWITH_PERL=ON \ + -DWITH_PYTHON2=ON \ + -DWITH_GNOME3=ON \ + -DWITH_KDE=ON \ + -DWITH_WEBKIT3=ON \ + -DBIPR=0 + - make + - sudo make install + - make test diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..7594699 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,5 @@ +Nathaniel McCallum +Alex Panait +Dominique Leuenberger +Gonéri Le Bouder - Perl bindings +Nicolas Dufresne diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..451e7a6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,60 @@ +### Required +cmake_minimum_required(VERSION 2.6) +if(POLICY CMP0011) + cmake_policy(SET CMP0011 NEW) +endif(POLICY CMP0011) +if(POLICY CMP0054) + cmake_policy(SET CMP0054 NEW) +endif(POLICY CMP0054) + +# Make sure we look in our cmake folder for additional definitions +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake ) + +### Make sure we have a build type +# This fixes an install issue where installs fail +# when find_package(KDE4) is present. I'm still +# not sure why this happens, but this definitely fixes +# it. It also fixes tests not running in this case. +# See issues 127 and 128. +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE RelWithDebInfo) + set(CMAKE_INSTALL_CONFIG_NAME RelWithDebInfo) +else() + set(CMAKE_INSTALL_CONFIG_NAME ${CMAKE_BUILD_TYPE}) +endif() + +include(cmake/cpack.cmk) +include(cmake/ctest.cmk) +include(cmake/paths.cmk) + +option(WITH_WEBKIT3 "Build against gtk-3 version of webkitgtk" OFF) + +### Subdirectories +# Conditionally build bundled libmodman +option(FORCE_SYSTEM_LIBMODMAN "Force using system libmodman" OFF) +find_package(libmodman QUIET) +if(LIBMODMAN_FOUND) + if("${LIBMODMAN_VERSION_MAJOR}" STREQUAL "2") + message(STATUS "Building with system libmodman") + else() + message(FATAL_ERROR "Found incompatible libmodman on your system (libmodman 2.X is needed)") + endif() +else() + if(FORCE_SYSTEM_LIBMODMAN) + message(FATAL_ERROR "Libmodman could not be found on your system") + else() + message(STATUS "Building with bundled libmodman") + add_subdirectory(libmodman) + include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + endif() +endif() + +# Conditionally build bindings +if(NOT WIN32) + add_subdirectory(bindings) +endif() + +# Always build these +add_subdirectory(libproxy) +add_subdirectory(utils) + diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..4362b49 --- /dev/null +++ b/COPYING @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..27cc851 --- /dev/null +++ b/ChangeLog @@ -0,0 +1,162 @@ +Wed Sep 1 16:03:00 2010 Nicolas Dufresne + * == Released 0.4.6 === + * Fixed a crash in the URL parser + * Fixed build issues with Visual Studio + * Updated the INSTALL file + * Install Python binding in prefix path if site-packages exists + * Fixed compilation with Visual Studio + * Complete list of bug fixes: + + 135, 136, 138 + +Mon Jun 7 11:37:00 2010 Nicolas Dufresne + * === Released 0.4.5 === + * C# bindings are installable (-DWITH_DOTNET=ON) + * C# bindings installation path can be changed using -DGAC_DIR= + * Internal libmodman build fixed + * Installation dirs are now all relative to CMAKE_INSTALL_PREFIX + * Fixed test while using --as-needed linker flag + * Fixed generation of libproxy-1.0.pc + * Basic support for Mingw added (not yet 100% functional) + * Ruby binding implemented (not yet in the build system) + * Fixed modules not being found caused by relative LIBEXEC_INSTALL_DIR + * Fixed bug with builtin plugins (Issue 133) + * Vala bindings installation path can be changed using -DVAPI_DIR= + * Python bindings installation path can be changed using -DPYTHON_SITEPKG_DIR= + * Perl bindings can be installed in vendor directory (-DPERL_VENDORARCH=ON) + * Perl bindings installation path can be change using -DPX_PERL_ARCH= + * Unit test now builds on OSX + * Complete list of bug fixes: + + 125, 126, 130, 132, 133 + +Sun Jun 13 11:00:00 2010 Nathaniel McCallum + * === Released 0.4.4 === + * Add support for optionally building using a system libmodman + * Rework build system to be cleaner + * Fix two major build system bugs: 127, 128 + +Mon Jun 7 11:37:00 2010 Nicolas Dufresne + * === Released 0.4.3 === + * Test can now be out-compiled using BUILD_TESTING=OFF + * Fixed python binding not handling NULL pointer + * Pyhton binding now support Python version 3 + * Implented URL unit test + * Rewrote URL parser to comply with unit test + * Username and password are now URL encoded + * Scheme comparison is now non-case sensitive + * Fixed deadlock using WebKit has PAC runner + * Fixed OS X compilation of Perl bindings + * Complete list of bug fixes: + + 123, 122, 121, 117, 116, 112, 109 + +Tue May 18 11:54:00 2010 Nicolas Dufresne + * === Released 0.4.2 === + * Fixed python binding that failed on missing px_free symbole + * Workaround cmake bug with dynamic libraries in non-standard folders + +Tue May 18 10:30:00 2010 Nicolas Dufresne + * === Released 0.4.1 === + * Improved cross-platform build + * Added Perl and Vala bindings + * Fix multiple infinite loop bugs + * Fix random crash with Gnome backend + * Standardized Gnome backend based on Mozilla and Chrome behavior + * Removed dependency to X11 in Gnome backend + * Allow disabling features at build time using WITH_* cmake options + * Module path can now be altered using PX_MODULE_PATH environment + * pxgconf helper location can be altered using PX_GCONF environment + * Removed proxy scheme filtering, we now trust config modules + * socks5:// and socks4:// is now allowed + * Fix crash when password is empty string + * Complete list of bug fixes: + + 19, 59, 65, 86, 87, 88, 89, 90, 91, 92, 93, 97, 98, + 99, 100, 101, 102, 103, 106, 108, 110 + * Known issues: + + 109 - Scheme comparison is case sensitive + + 112 - Username and password are not URI encoded + +Thu Feb 25 20:12:57 2010 Nathaniel McCallum + * === Released 0.4.0 === + * C++ rewrite + * Small API change (px_proxy_factory_get_proxy() can now return NULL) + * SOVERSION bump + * libmodman is now a seperate library + * Migrate to cmake + * Windows support (config_w32reg, ignore_hostname; VC++ support) + * MacOSX support (config_macosx, ignore_hostname) + * Built-in modules support + * Support for chunked encoding + * Move to hidden visibility by default + * KDE's KConfig symantics are fully supported + * Removeal of all PX_* env variables (no longer needed) + * Symbol based detection of relevant pacrunner + * Reworked config_gnome to not suck (its *much* faster) + * Many other things I can't remember + +Thu Oct 08 21:26:00 2009 Dominique Leuenberger + * === Released 0.3.1 === + * Bugfixes + + config file parser reads all sections + + KDE session detection based on environment varibales, + as suggested by KDE upstream. + * KDE configuration module is the first module in C++ and + now links to libkdecore4 in order to properly detect the + configuration folder for kde. + * At the moment we're not compatible with KDE3. Sorry. + * .NET bindings can now properly be installed and it should + be possible for packagers to provide them. + +Thu Aug 14 15:38:00 2009 Nathaniel McCallum + * === Released 0.3.0 === + * WARNING!!! Slight API change (still ABI compat)!!! + see docs for px_proxy_factory_get_proxies() + * Credentials support (see API change above) + * A complete rewrite of the module manager + * file:// as valid PAC URLs + * Sample Mono application + * Automake 1.11 shaved output + * gnome backend rewrite (now w/o thread issues) + * Test suite base functionality exists + * Many solaris build fixes + * Seamonkey support as JS pacrunner + * Bugfixes + * Compiles for MS Windows using Mingw + +Thu Jun 05 17:05:12 2008 Nathaniel McCallum + * === Released 0.2.3 === + * New plugin: webkit (JavaScript) + * Massive speed improvements in all javascript plugins + * Bug fixes + * Memory leak fixes + * pkgconfig support + +Wed Jan 09 04:18:45 2008 Jeff Schroeder + * === Released 0.2.2 === + * Python bindings fix + * Added pthreads support from r191 in trunk + * Removed local copy of strdup() in proxy.c for OS X build issues + +Wed Dec 20 19:11:23 2007 Nathaniel McCallum + * === Released 0.2.1 === + * Build fix for mozjs + * Python bindings fix for renamed function + * Split off x_has_client() into its own file + +Wed Dec 12 20:12:56 2007 Nathaniel McCallum + * === Released 0.2 === + * Added Python bindings + * Added .NET bindings + * NetworkManager plugin + * KDE plugin + * File plugin + * More accurate GNOME session detection + * Ignore pattern support + * px_proxy_factory_get_proxy() renamed to px_proxy_factory_get_proxies() + * Relicense from LGPLv3+ to LGPLv2.1+ + * Sacrifice re-homeing session support for massive performance gains + * Tons of bug fixes, memory leaks, etc + +Wed Oct 31 13:09:10 2007 Nathaniel McCallum + * === Released 0.1 === + * AUTHORS: Added authors + * README: basic readme info + * src/lib/proxy.h: add missing doc line diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..bf04881 --- /dev/null +++ b/INSTALL @@ -0,0 +1,157 @@ + +Quick Start +########### + +From source directory +1. mkdir build +2. cd build +3. cmake .. +4. make +5. make install + +More advanced installation options: +################################### + +Example: + cmake .. + -DCMAKE_INSTALL_PREFIX=/usr + -DLIB_SUFIX=64 + -DWITH_VALA=yes + -DWITH_DOTNET=yes + -DPERL_VENDORINSTALL=yes + -DCMAKE_BUILD_TYPE=None + -DCMAKE_CXX_FLAGS="-O2" + -DCMAKE_C_FLAGS="-O2" + +This example would configure libproxy to be installed in /usr with all other +location using defaults relative to it, except that libraries will be install in +/usr/lib64. It also enable Vala and .NET bindings and tell the build system +to install the Perl binding in the vendor directory (the one used by +distribution, in contrast to the one used by users). + +Path options: +============= + +CMAKE_INSTALL_PREFIX: Default to "/usr/local". This is the base install + directory. All other path, except SYSCONF_INSTALL_DIR + are by default relative to this one. + +BIN_INSTALL_DIR: Default to "bin". This is where executable are install. + +LIB_INSTALL_DIR: Default to "lib${LIB_SUFFIX}". This is where libraries + are insalled. + +LIB_SUFFIX: Default to "". This is used on multilib 64bit OS where it + would be set to "64". + +LIBEXEC_INSTALL_DIR: Default to "libexec". This is where non-interactive helper + executable are installed (e.g. pxgconf for Gnome support). + +INCLUDE_INSTALL_DIR: Default to "include". This is where libproxy header is + installed (proxy.h). + +SYSCONF_INSTALL_DIR: Default to "/etc". This is the place where system wide + configuration files are placed, currently unused. Note + that this path does not have a relative path has default. + +SHARE_INSTALL_DIR: Default to "share". This base path used for CMake modules + finders and the Vala bindings. + +MODULE_INSTALL_DIR: Default to "${LIB_INSTALL_DIR}/${PROJECT_NAME}/${PROJECT_VERSION}/modules". + This is where libproxy extensions are installed. Note that + extentions API/ABI is not yet stable, so you should be + carefull when changing this path not to mix different + version of extensions together. The module path can also + be altered at runtime using PX_MODULE_PATH environement. + + +Boolean options: +================ + +BIPR: Default to ON. Build Internal Pac Runner. + If only one pacrunner is to be built, then the default + is to link it internal to libproxy. As soon as two are + to be built, they are always made as a module. + Setting this to OFF allows to build a pacrunner as + module even if only one is to be built. + +FORCE_SYSTEM_LIBMODMAN: Default to OFF. Forces the build system to generate an + error if libmodman cannot be found on your system. By + default libmodman will fallback to using internal copy + of that library. + +PERL_VENDORINSTALL: Default to OFF. Tells cmake to install the perl binding + in the vendor directory, which is the one used by most + packagers. + +PERL_LINK_LIBPERL: Default to ON if PERL_VENDORINSTALL is OFF, default to + OFF otherwise. Explicitly links the Perl binding + against libperl.so. It must be ON for linking to work + when --no-undefined is passed to the linker. + +WITH_DOTNET: Default to OFF. Enable Mono .NET bindings. + +WITH_GNOME: Default to ON. Enable Gnome2/GConf bindings. + +WITH_GNOME3: Default to ON. Build the Gnome3/GSettings bindings. + instead of Gnome2/GConf based one. + +WITH_KDE: Default to ON. Enables plug-in to read proxy settings + from either KDE4 or KDE Frameworks 5. + Note: this plug-in only has a *runtime* dependency on + either kreadconfig or kreadconfig5. + +WITH_MOZJS: Default to ON. Enable Mozilla javascript bindings. As + Mozilla Javascript engine is often installed multiple + you can set prefered order using MOZJS_SEARCH_ORDER, + wich defaults to "xulrunner-js;firefox-js;mozilla-js;seamonkey-js". + +WITH_NM: Default to ON. Enable NetworkManager bindings. + +WITH_PERL: Default to ON. Enable Perl bindings. + +WITH_PYTHON2: Default to ON. Enable Python bindings. + +WITH_PYTHON3: Default to ON. Enable Python bindings. + +WITH_VALA: Default to OFF. Enable Vala bindings. + +WITH_WEBKIT: Default to ON. Enable Webkit Java Script engine. + +WITH_WEBKIT3: Default to OFF: Enable Webkit GTK3 support. + + +Bindings Path: +============== + +Most bindings require to be installed in a system specific directory. Libproxy +build system tries to find those directory. Sometimes this behaviour can be +annoying since bindings will not be installed relatively to CMAKE_INSTALL_PREFIX. +For this reason, all bindings provides path overrides. + +GAC_DIR: For the Mono .NET binding +VAPI_DIR: For the Vala bindings +PX_PERL_ARCH: For the Perl bindings +PYTHON_SITEPKG_DIR: For the Python bindings + + +Make options: +============= + +Of course you can use parallel build using "make -j2". It's also nice to see +the exact compile/link command being executed. This can be done using +"make VERBOSE=1" command. + +To install in a sub-directory, DESTDIR can be used has make parameter. + make install [DESTDIR=/any/prefix/to/prepend] + +CFLAGS in libproxy: +=================== + +We are currently having issue with CMake and CFLAGS. As shown in the example, +we have found a simple way that prevents CMAKE from choosing for you the +CFLAGS you want. As being demonstrated, you can disable CMAKE default CFLAGS +by setting an invalid (but not empty) CMAKE_BUILD_TYPE (e.g. None). You can +then set your flags using CMAKE_CXX_FLAGS, and CMAKE_C_FLAGS. Both variable +are required since libproxy contains C++ and C code. + diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..34319e1 --- /dev/null +++ b/NEWS @@ -0,0 +1,204 @@ +New in Version 0.4.15: +============================== +* Port to, and require, SpiderMonkey 38. +* Fix "NetworkManager plugin not being built" (gh#libproxy/libproxy#53). +* Fix "networkmanager plugin not working (gh#libproxy/libproxy#58). +* Fix "Invalid read after free" (gh#libproxy/libproxy#59). +* Fix intermittent unit test failures. + +New in Version 0.4.14: +============================== +* Parallel build support for python2 and python3. + -DWITH_PYTHON has been replaced with -DWITH_PYTHON2 and + -DWITH_PYTHON3 to have full control over this. Default is + ON for both (issue#22) +* Minor fixes to the PAC retriever code (issue#40) +* Fallback to mcs instead of gmcs for the mono bindings (issue#37) +* Fix build using cmake 3.7 +* Fix deprecation warnings of pxgsettings with glib 2.46 +* Improve the get-pac test suite (issue#47) + +New in Version 0.4.13 +============================== +* Allow linking webkit pacrunner against javascriptcore-4.0 + (webkit2). +* Allow to disable building of the KDE module (-DWITH_KDE=ON/OFF). +* Fix compilation errors with CLang on MacOSX. +* bindings: perl: Add an option to explicitly link against libperl.so + Some distributions want to do it, other prefer not to, the library + is anyway in context of perl. +* config_kde: Add a basic cache and invalidation: performance improvement + for the KDE module. + +New in version 0.4.12 +============================== +* Move development to github.com/libproxy/libproxy +* Fix fd leak in get_pac (Bug #185) +* Detect running MATE session (Bug #186, Part1). +* Fix linking of perl bindings to pthread (Bug #182) +* Correctly detect spidermonky (mozjs185) (Bug #188) +* Stop pxgsettings from segfaulting on exit (Bug #192) +* Fix test #10 (Bug #189) +* Fix build on Mac OS X (Bug #183) +* Add a generic KDE Config module (fix crashes of Qt5 based + apps) (issue#4) + +New in version 0.4.11 +============================== +* Build fixes with cmake 2.8.10+ +* Quick release without built binaries / files (Address Bug #184) + +New in version 0.4.10 +============================== +* Fix http chunk encoded PAC that was broken in previous release +* Add HTTP client unit test +* Fix more coding style issues + +New in version 0.4.9 +============================== +* CVE-2012-4504 Fixed buffer overflow when downloading PAC +* Fix infinit loop uppon network errors + +New in version 0.4.8 +============================== +* Only support standalone mozjs185 as mozilla js engine. + xulrunner being part of the now lightning fast moving firefox + is impossible to be tracked as a dependency and it is not + supported by Mozilla to be used in this scenario. +* Support building with javascritpcoregtk 1.5 + (got split out of webkitgtk). +* Support sending multiple results. +* Issues fixed: + - #166: Libproxy does not parse NO_PROXY correct when the line + contains spaces + - #164: If gconf's value is an empty list, pxgconf will make + /usr/bin/proxy wait forever + - #60: use lib js for embedded solutions + - #160: strdup and gethostbyname not declared on OSX 10.7 + - #168: .pc file should be installed under OSX as well. + - #170: Also check for "Transfer-Encoding: chunked". + - #171: mozjs pacrunner: Fix parameters of dnsResolve_() + - #172: Allow to forcibly build pacrunner as module (-DBIPR={ON,OFF}) + - #173: Libproxy doesn't build with gcc 4.7 + - #147: Use ${CMAKE_DL_LIBS} instead of assuming libdl is correct. + - #176: python bindings: guard the destructor. + - #177: Speed up importing of libproxy in python. + - #179: CMAKE 2.8.8 does not define PKG_CONFIG_FOUND + +New in version 0.4.7 +============================== +* Support/require xulrunner 2.0+ +* Support linking againgst libwebkit-gtk3 (-DWITH_WEBKIT3=ON) +* Port to gsettings for gnome3. (-DWITH_GNOME3=ON[default]) +* Issues closed: + - #149: always test for the right python noarch module path + - #155: Cannot compile with Firefox 4 + - #156: libproxy should build against webkitgtk-3.0 + - #158: Won't compile w/ xulrunner 2.0 final + - #159: libproxy fails with autoconfiguration "http://proxy.domain.com" + - #131: GSettings-based GNOME plugin + - #150: SUSE sysconfig/proxy config support + +New in version 0.4.6 +============================== +* Fixed a crash in the URL parser +* Fixed build issues with Visual Studio +* Updated the INSTALL file +* Install Python binding in prefix path if site-packages exists +* Fixed compilation with Visual Studio + + +New in version 0.4.5 +=============================== +* C# bindings are installable (-DWITH_DOTNET=ON) +* C# bindings installation path can be changed using -DGAC_DIR= +* Internal libmodman build fixed +* Installation dirs are now all relative to CMAKE_INSTALL_PREFIX +* Fixed test while using --as-needed linker flag +* Fixed generation of libproxy-1.0.pc +* Basic support for Mingw added (not yet 100% functional) +* Ruby binding implemented (not yet in the build system) +* Fixed modules not being found caused by relative LIBEXEC_INSTALL_DIR +* Fixed bug with builtin plugins (Issue 133) +* Vala bindings installation path can be changed using -DVAPI_DIR= +* Python bindings installation path can be changed using -DPYTHON_SITEPKG_DIR= +* Perl bindings can be installed in vendor directory (-DPERL_VENDORARCH=ON) +* Perl bindings installation path can be change using -DPX_PERL_ARCH= +* Unit test now builds on OSX + +New in version 0.4.4 +=============================== +* Add support for optionally building using a system libmodman +* Rework build system to be cleaner +* Fix two major build system bugs: 127, 128 + +New in version 0.4.3 +=============================== +* Test can now be out-compiled using BUILD_TESTING=OFF +* Fixed python binding not handling NULL pointer +* Pyhton binding now support Python version 3 +* Rewrote URL parser to comply with unit test +* Username and password are now URL encoded +* Scheme comparison is now non-case sensitive +* Fixed deadlock using WebKit has PAC runner +* Fixed OS X compilation of Perl bindings + +New in version 0.4.2 +=============================== +* Fixed python binding that failed on missing px_free symbole +* Workaround cmake bug with dynamic libraries in non-standard folders + +New in version 0.4.1 +=============================== +* Perl bindings have been integrated into the CMake Build System +* Vala bindings are installed if -DWITH_VALA=yes is passed to cmake +* All extensions can be disabled using WITH_*=OFF cmake options +* socks5:// and socks4:// can now be returned +* Many bugfixes + +New in version 0.4.0 +=============================== +* C++ rewrite +* Small API change (px_proxy_factory_get_proxy() can now return NULL) +* SOVERSION bump +* libmodman is now a seperate library +* Migrate to cmake +* Windows support (config_w32reg, ignore_hostname; VC++ support) +* MacOSX support (config_macosx, ignore_hostname) +* Built-in modules support +* Support for chunked encoding +* Move to hidden visibility by default +* KDE's KConfig symantics are fully supported +* Removeal of all PX_* env variables (no longer needed) +* Symbol based detection of relevant pacrunner +* Reworked config_gnome to not suck (its *much* faster) +* Many other things I can't remember + +New in version 0.3.1 +==================== +- Bugfixes + + config file parser reads all sections + + KDE session detection based on environment varibales, + as suggested by KDE upstream. +- KDE configuration module is the first module in C++ and + now links to libkdecore4 in order to properly detect the + configuration folder for kde. +- At the moment we're not compatible with KDE3. Sorry. +- .NET bindings can now properly be installed and it should + be possible for packagers to provide them. + +New in version 0.3.0 +==================== +* WARNING!!! Slight API change!!! see docs + for px_proxy_factory_get_proxies() +* Credentials support (see API change above) +* A complete rewrite of the module manager +* file:// as valid PAC URLs +* Sample Mono application +* Automake 1.11 shaved output +* gnome backend rewrite (now w/o thread issues) +* Test suite base functionality exists +* Many solaris build fixes +* Seamonkey support as JS pacrunner +* Bugfixes +* Compiles for MS Windows using Mingw diff --git a/README b/README new file mode 100644 index 0000000..85d2d6e --- /dev/null +++ b/README @@ -0,0 +1,4 @@ +Thanks for trying libproxy! + +To use libproxy in your application, check out the external API in the +proxy.h. diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 0000000..2df3945 --- /dev/null +++ b/autogen.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +cmake ./ diff --git a/bindings/CMakeLists.txt b/bindings/CMakeLists.txt new file mode 100644 index 0000000..2b0ede4 --- /dev/null +++ b/bindings/CMakeLists.txt @@ -0,0 +1,30 @@ +option(WITH_PYTHON2 "Enables Python 2 bindings" ON) +if (WITH_PYTHON2) + add_subdirectory(python/python2) +endif() + +option(WITH_PYTHON3 "Enables Python 3 bindings" ON) +if (WITH_PYTHON3) + add_subdirectory(python/python3) +endif() + +option(WITH_DOTNET "Enables C# bindings" OFF) +if (WITH_DOTNET) + add_subdirectory(csharp) +endif() + +#perl bindings live in their own subdir. +option(WITH_PERL "Enables Perl bindings" ON) +if (WITH_PERL) + add_subdirectory(perl) +endif() + +# Install Vala bindings / Install only when -DWITH_VALA is passed to cmake. +option(WITH_VALA "Enables Vala bindings" OFF) +if(WITH_VALA) + if (NOT VAPI_DIR) + set(VAPI_DIR ${SHARE_INSTALL_DIR}/vala/vapi) + endif() + install(FILES vala/libproxy-1.0.vapi DESTINATION ${VAPI_DIR}) + set(VAPI_DIR ${VAPI_DIR} CACHE PATH "Vala API directory") +endif() diff --git a/bindings/csharp/AssemblyInfo.cs b/bindings/csharp/AssemblyInfo.cs new file mode 100644 index 0000000..2baa161 --- /dev/null +++ b/bindings/csharp/AssemblyInfo.cs @@ -0,0 +1,33 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2008-2010 Dominique Leuenberger + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly:AssemblyVersion("0.4.6")] +[assembly:AssemblyTitle ("LibProxy#")] +[assembly:AssemblyDescription ("A library that provides automatic proxy configuration management.")] +[assembly:AssemblyCopyright ("Copyright (c) 2006-2009 Nathaniel McCallum")] +[assembly:AssemblyCompany ("")] +[assembly:AssemblyDelaySign(false)] +[assembly:AssemblyKeyFile("libproxy.snk")] +[assembly:CLSCompliant(false)] + diff --git a/bindings/csharp/CMakeLists.txt b/bindings/csharp/CMakeLists.txt new file mode 100644 index 0000000..d433fc6 --- /dev/null +++ b/bindings/csharp/CMakeLists.txt @@ -0,0 +1,14 @@ +PROJECT(libproxy-sharp) + +enable_language(CSharp) + +SET(KEYFILE ${CMAKE_CURRENT_SOURCE_DIR}/libproxy.snk) + +CSHARP_ADD_LIBRARY(libproxy-sharp libproxy.cs AssemblyInfo.cs COMPILE_FLAGS /warn:0 "/keyfile:${KEYFILE}") +SET_PROPERTY(TARGET libproxy-sharp PROPERTY pkg-config_template_basename libproxy-sharp-1.0) + +GET_LIBRARY_OUTPUT_DIR(library_target_dir) +FILE(WRITE ${library_target_dir}/libproxy-sharp.dll.config "") + +INSTALL_ASSEMBLY(libproxy-sharp DESTINATION lib PACKAGE libproxy-sharp) + diff --git a/bindings/csharp/libproxy.cs b/bindings/csharp/libproxy.cs new file mode 100644 index 0000000..b2ceeb2 --- /dev/null +++ b/bindings/csharp/libproxy.cs @@ -0,0 +1,79 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +namespace libproxy { + using System; + using System.Runtime.InteropServices; + + public class ProxyFactory { + private HandleRef self; + + [DllImport ("proxy")] + private static extern + IntPtr px_proxy_factory_new(); + + [DllImport ("proxy")] + private static extern + IntPtr px_proxy_factory_get_proxies(HandleRef self, string url); + + [DllImport ("proxy")] + private static extern + void px_proxy_factory_free(HandleRef self); + + public ProxyFactory() + { + this.self = new HandleRef(this, px_proxy_factory_new()); + } + + public string[] GetProxies(string url) + { + int count = 0; + + // Get the results + // TODO: If we call both this function and px_proxy_factory_free() + // this crashes, figure out why... + IntPtr array = px_proxy_factory_get_proxies(this.self, url); + + // Count the number of returned strings + while (Marshal.ReadIntPtr(array, count * IntPtr.Size) != IntPtr.Zero) count++; + + // Allocate a correctly sized array + string[] proxies = new string[count]; + + // Fill the response array + for (int i=0 ; i < count ; i++) + { + IntPtr p = Marshal.ReadIntPtr(array, i * IntPtr.Size); + proxies[i] = Marshal.PtrToStringAnsi(p); + Marshal.FreeCoTaskMem(p); // Free the string + } + + // Free the array itself + Marshal.FreeCoTaskMem(array); + + return proxies; + } + + ~ProxyFactory() + { + // TODO: See note above... + px_proxy_factory_free(this.self); + } + } +} diff --git a/bindings/csharp/libproxy.snk b/bindings/csharp/libproxy.snk new file mode 100644 index 0000000..3dc1731 Binary files /dev/null and b/bindings/csharp/libproxy.snk differ diff --git a/bindings/perl/CMakeLists.txt b/bindings/perl/CMakeLists.txt new file mode 100644 index 0000000..4db28e1 --- /dev/null +++ b/bindings/perl/CMakeLists.txt @@ -0,0 +1,42 @@ +find_package(Perl) +include (FindPerlLibs) + +if(PERL_FOUND AND PERLLIBS_FOUND) + + # Enable override of perl packge install directory. + set(PX_PERL_ARCH ${PX_PERL_ARCH} CACHE PATH "Install directory for Perl package.") + + if(NOT PX_PERL_ARCH) + # Some distributions install perl packages in vendor when shipped with the distro. + # Let's make their lifes easier by offering an install flag for this usecase. + option(PERL_VENDORINSTALL "Install Perl package in vendor directory" OFF) + + # Offer an option to explicitly link against libperl.so, with a default + # that depends on the value of the PERL_VENDORINSTALL option: if the + # binding is installed into a version-independent directory such as + # vendor_perl the chances of it needing a rebuild on each Perl update are + # lower. Note: not linking against libperl.so does not work if + # --no-undefined is passed to the linker. + if(PERL_VENDORINSTALL) + option(PERL_LINK_LIBPERL "Explicitly link against libperl.so" OFF) + else() + option(PERL_LINK_LIBPERL "Explicitly link against libperl.so" ON) + endif() + + if(PERL_VENDORINSTALL) + set (PX_PERL_ARCH ${PERL_VENDORARCH}) + set (PX_PERL_LIB ${PERL_VENDORLIB}) + else() + # PERL_SITEARCH is actually not defined in latest FindPerlLibs.cmake macros, thus + # we have to find the correct path on our own. + EXECUTE_PROCESS(COMMAND ${PERL_EXECUTABLE} -MConfig -e "print \$Config{sitearch}" + OUTPUT_VARIABLE PX_PERL_ARCH) + set (PX_PERL_LIB ${PERL_SITELIB}) + endif() + endif() + + add_subdirectory(lib) + add_subdirectory(src) + add_subdirectory(t) +endif() + diff --git a/bindings/perl/lib/CMakeLists.txt b/bindings/perl/lib/CMakeLists.txt new file mode 100644 index 0000000..9856627 --- /dev/null +++ b/bindings/perl/lib/CMakeLists.txt @@ -0,0 +1,2 @@ +add_custom_target(PMlibproxy ALL ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/Libproxy.pm ${CMAKE_BINARY_DIR}/perl/blib/lib/Libproxy.pm) +install( FILES Libproxy.pm DESTINATION ${PX_PERL_ARCH}/Net ) diff --git a/bindings/perl/src/CMakeLists.txt b/bindings/perl/src/CMakeLists.txt new file mode 100644 index 0000000..05176c4 --- /dev/null +++ b/bindings/perl/src/CMakeLists.txt @@ -0,0 +1,24 @@ +include_directories( ${PERL_INCLUDE_PATH} ${CMAKE_SOURCE_DIR}/libproxy ) + +# Run doxsubpp.pl to run xsubpp on Libproxy.xs +add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Libproxy.c + COMMAND ${PERL_EXECUTABLE} ARGS ${CMAKE_CURRENT_SOURCE_DIR}/doxsubpp.pl + ${PERL_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Libproxy.xs ${CMAKE_CURRENT_BINARY_DIR}/Libproxy.c + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Libproxy.xs libproxy + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + +set(Libproxy_LIB_SRCS Libproxy.c) + +set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/perl/blib/arch/auto/Net) +add_library(PLlibproxy SHARED ${Libproxy_LIB_SRCS}) + +set(PLlibproxy_LIB_DEPENDENCIES libproxy pthread) +if(PERL_LINK_LIBPERL) + set(PLlibproxy_LIB_DEPENDENCIES ${PERL_LIBRARY} ${PLlibproxy_LIB_DEPENDENCIES}) +endif() + +target_link_libraries(PLlibproxy ${PLlibproxy_LIB_DEPENDENCIES}) +set_target_properties(PLlibproxy PROPERTIES OUTPUT_NAME "Libproxy") +set_target_properties(PLlibproxy PROPERTIES PREFIX "") + +install( TARGETS PLlibproxy DESTINATION ${PX_PERL_ARCH}/auto/Net/Libproxy ) diff --git a/bindings/perl/src/Libproxy.xs b/bindings/perl/src/Libproxy.xs new file mode 100644 index 0000000..cacdfd9 --- /dev/null +++ b/bindings/perl/src/Libproxy.xs @@ -0,0 +1,62 @@ +#include "EXTERN.h" +#include "perl.h" +#include "XSUB.h" + +#include + + +void XS_pack_charPtrPtr( SV * arg, char ** array, int count) { + int i; + AV * avref; + avref = (AV*)sv_2mortal((SV*)newAV()); + for (i=0; inew( { + NAME => 'Libproxy', + NEEDS_LINKING => 1, +} ); + +my $perl_include_path = $mm->{PERL_INC}; +my @xsubinfo = split "\n", $mm->tool_xsubpp(); + +my $xsubppdir = (map{ my $foo = $_; $foo =~ s/XSUBPPDIR = //; $foo } grep{ m/^XSUBPPDIR =/ } @xsubinfo)[0]; +my $xsubpp = "$xsubppdir/xsubpp"; + +my $xsubppargs = (map{ my $foo = $_; $foo =~ s/XSUBPPARGS = //; $foo } grep{ m/^XSUBPPARGS =/ } @xsubinfo)[0]; + +my $cmd = "$perl $xsubpp $xsubppargs -typemap typemap $in > $out"; +system $cmd; diff --git a/bindings/perl/src/typemap b/bindings/perl/src/typemap new file mode 100644 index 0000000..62be990 --- /dev/null +++ b/bindings/perl/src/typemap @@ -0,0 +1,2 @@ +TYPEMAP +pxProxyFactory * T_PTROBJ diff --git a/bindings/perl/t/CMakeLists.txt b/bindings/perl/t/CMakeLists.txt new file mode 100644 index 0000000..8007124 --- /dev/null +++ b/bindings/perl/t/CMakeLists.txt @@ -0,0 +1 @@ +add_custom_target(test prove -b ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/bindings/perl/t/Libproxy.t b/bindings/perl/t/Libproxy.t new file mode 100644 index 0000000..5c4fe61 --- /dev/null +++ b/bindings/perl/t/Libproxy.t @@ -0,0 +1,15 @@ +# Before `make install' is performed this script should be runnable with +# `make test'. After `make install' it should work as `perl Foo.t' + +######################### + +# change 'tests => 1' to 'tests => last_test_to_print'; + +use Test::More tests => 1; +BEGIN { use_ok('Net::Libproxy') }; + +######################### + +# Insert your test code below, the Test::More module is use()ed here so read +# its man page ( perldoc Test::More ) for help writing this test script. + diff --git a/bindings/python/libproxy.py b/bindings/python/libproxy.py new file mode 100644 index 0000000..7bddba9 --- /dev/null +++ b/bindings/python/libproxy.py @@ -0,0 +1,132 @@ +############################################################################### +# libproxy - A library for proxy configuration +# Copyright (C) 2006 Nathaniel McCallum +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +############################################################################### + +"A library for proxy configuration and autodetection." + +import ctypes +import ctypes.util +import platform + +import sys + +def _load(name, *versions): + for ver in versions: + try: return ctypes.cdll.LoadLibrary('lib%s.so.%s' % (name, ver)) + except: pass + name_ver = ctypes.util.find_library(name) + if name_ver: + return ctypes.cdll.LoadLibrary(name_ver) + raise ImportError("Unable to find %s library" % name) + +# Load C library +if platform.system() == "Windows": + _libc = ctypes.cdll.msvcrt +else: + _libc = _load("c", 6) + +_libc.free.argtypes = ctypes.c_void_p, + +# Load libproxy +_libproxy = _load("proxy", 1) +_libproxy.px_proxy_factory_new.restype = ctypes.POINTER(ctypes.c_void_p) +_libproxy.px_proxy_factory_free.argtypes = ctypes.c_void_p, +_libproxy.px_proxy_factory_get_proxies.restype = ctypes.POINTER(ctypes.c_void_p) + +class ProxyFactory(object): + """A ProxyFactory object is used to provide potential proxies to use + in order to reach a given URL (via 'getProxies(url)'). + + This instance should be kept around as long as possible as it contains + cached data to increase performance. Memory usage should be minimal (cache + is small) and the cache lifespan is handled automatically. + + Usage is pretty simple: + pf = libproxy.ProxyFactory() + for url in urls: + proxies = pf.getProxies(url) + for proxy in proxies: + if proxy == "direct://": + # Fetch URL without using a proxy + elif proxy.startswith("http://"): + # Fetch URL using an HTTP proxy + elif proxy.startswith("socks://"): + # Fetch URL using a SOCKS proxy + + if fetchSucceeded: + break + """ + + class ProxyResolutionError(RuntimeError): + """Exception raised when proxy cannot be resolved generally + due to invalid URL""" + pass + + def __init__(self): + self._pf = _libproxy.px_proxy_factory_new() + + def getProxies(self, url): + """Given a URL, returns a list of proxies in priority order to be used + to reach that URL. + + A list of proxy strings is returned. If the first proxy fails, the + second should be tried, etc... In all cases, at least one entry in the + list will be returned. There are no error conditions. + + Regarding performance: this method always blocks and may be called + in a separate thread (is thread-safe). In most cases, the time + required to complete this function call is simply the time required + to read the configuration (e.g from GConf, Kconfig, etc). + + In the case of PAC, if no valid PAC is found in the cache (i.e. + configuration has changed, cache is invalid, etc), the PAC file is + downloaded and inserted into the cache. This is the most expensive + operation as the PAC is retrieved over the network. Once a PAC exists + in the cache, it is merely a JavaScript invocation to evaluate the PAC. + One should note that DNS can be called from within a PAC during + JavaScript invocation. + + In the case of WPAD, WPAD is used to automatically locate a PAC on the + network. Currently, we only use DNS for this, but other methods may + be implemented in the future. Once the PAC is located, normal PAC + performance (described above) applies. + + """ + if type(url) != str: + raise TypeError("url must be a string!") + + proxies = [] + array = _libproxy.px_proxy_factory_get_proxies(self._pf, url) + + if not bool(array): + raise ProxyFactory.ProxyResolutionError( + "Can't resolve proxy for '%s'" % url) + + i=0 + while array[i]: + proxies.append(str(ctypes.cast(array[i], ctypes.c_char_p).value)) + _libc.free(array[i]) + i += 1 + _libc.free(array) + + return proxies + + def __del__(self): + if _libproxy: + _libproxy.px_proxy_factory_free(self._pf) + diff --git a/bindings/python/python2/CMakeLists.txt b/bindings/python/python2/CMakeLists.txt new file mode 100644 index 0000000..00df551 --- /dev/null +++ b/bindings/python/python2/CMakeLists.txt @@ -0,0 +1,25 @@ +find_package(Python2Interp) + +if(PYTHON2INTERP_FOUND) + set(PYTHON2_SITEPKG_DIR "${PYTHON2_SITEPKG_DIR}" CACHE PATH "Python 2 site-package directory.") + + if(NOT PYTHON2_SITEPKG_DIR) + execute_process(COMMAND + ${PYTHON2_EXECUTABLE} + -c "import sys; print (sys.version[0:3])" + OUTPUT_VARIABLE PYTHON2_VERSION + OUTPUT_STRIP_TRAILING_WHITESPACE) + + message(STATUS "Found python 2 version ${PYTHON2_VERSION}") + + execute_process(COMMAND + ${PYTHON2_EXECUTABLE} + -c "import distutils.sysconfig ; print (distutils.sysconfig.get_python_lib(plat_specific=0))" + OUTPUT_VARIABLE PYTHON2_SITEPKG_DIR + OUTPUT_STRIP_TRAILING_WHITESPACE) + endif() + + message(STATUS "Using PYTHON2_SITEPKG_DIR=${PYTHON2_SITEPKG_DIR}") + + install(FILES ../libproxy.py DESTINATION ${PYTHON2_SITEPKG_DIR}) +endif() diff --git a/bindings/python/python3/CMakeLists.txt b/bindings/python/python3/CMakeLists.txt new file mode 100644 index 0000000..bf87dfc --- /dev/null +++ b/bindings/python/python3/CMakeLists.txt @@ -0,0 +1,25 @@ +find_package(Python3Interp) + +if(PYTHON3INTERP_FOUND) + set(PYTHON3_SITEPKG_DIR "${PYTHON3_SITEPKG_DIR}" CACHE PATH "Python 3 site-package directory.") + + if(NOT PYTHON3_SITEPKG_DIR) + execute_process(COMMAND + ${PYTHON3_EXECUTABLE} + -c "import sys; print (sys.version[0:3])" + OUTPUT_VARIABLE PYTHON3_VERSION + OUTPUT_STRIP_TRAILING_WHITESPACE) + + message(STATUS "Found python 3 version ${PYTHON3_VERSION}") + + execute_process(COMMAND + ${PYTHON3_EXECUTABLE} + -c "import distutils.sysconfig ; print (distutils.sysconfig.get_python_lib(plat_specific=0))" + OUTPUT_VARIABLE PYTHON3_SITEPKG_DIR + OUTPUT_STRIP_TRAILING_WHITESPACE) + endif() + + message(STATUS "Using PYTHON3_SITEPKG_DIR=${PYTHON3_SITEPKG_DIR}") + + install(FILES ../libproxy.py DESTINATION ${PYTHON3_SITEPKG_DIR}) +endif() diff --git a/bindings/ruby/Libproxy.i b/bindings/ruby/Libproxy.i new file mode 100644 index 0000000..183acba --- /dev/null +++ b/bindings/ruby/Libproxy.i @@ -0,0 +1,21 @@ +/* libproxy.i */ +%module Libproxy +%{ +#include "../../libproxy/proxy.h" +%} + +%typemap(out) char ** { + VALUE arr = rb_ary_new2(255); + int i; + for (i=0; $1[i]; i++) { + rb_ary_push(arr, rb_str_new2($1[i])); + } + $result = arr; +} + +%typemap(freearg) char ** { + free($source); +} + +%include "../../libproxy/proxy.h" + diff --git a/bindings/ruby/extconf.rb b/bindings/ruby/extconf.rb new file mode 100644 index 0000000..efd13eb --- /dev/null +++ b/bindings/ruby/extconf.rb @@ -0,0 +1,3 @@ +require 'mkmf' +$libs = append_library($libs, "proxy") +create_makefile('Libproxy') diff --git a/bindings/ruby/test.rb b/bindings/ruby/test.rb new file mode 100644 index 0000000..5730a32 --- /dev/null +++ b/bindings/ruby/test.rb @@ -0,0 +1,7 @@ +require 'Libproxy' + +pf = Libproxy.px_proxy_factory_new +proxies = Libproxy.px_proxy_factory_get_proxies(pf, "http://www.google.com") + +proxies.each { |proxy| print proxy + " " } +print "\n" diff --git a/bindings/vala/libproxy-1.0.vapi b/bindings/vala/libproxy-1.0.vapi new file mode 100644 index 0000000..bec22d0 --- /dev/null +++ b/bindings/vala/libproxy-1.0.vapi @@ -0,0 +1,10 @@ +[CCode (cprefix = "px", lower_case_cprefix = "px_", cheader_filename = "proxy.h")] +namespace Libproxy { + [Compact] + [CCode (free_function = "px_proxy_factory_free")] + public class ProxyFactory { + public ProxyFactory (); + [CCode (array_length = false, array_null_terminated = true)] + public string[] get_proxies (string url); + } +} diff --git a/cmake/CMakeCSharpCompiler.cmake.in b/cmake/CMakeCSharpCompiler.cmake.in new file mode 100644 index 0000000..a14bade --- /dev/null +++ b/cmake/CMakeCSharpCompiler.cmake.in @@ -0,0 +1,10 @@ +set(CMAKE_CSharp_COMPILER "@CMAKE_CSharp_COMPILER@") +set(CMAKE_CSharp_COMPILER_LOADED @CMAKE_CSharp_COMPILER_LOADED@) + +# Don't do that otherwise you can't change the path later +#set(GAC_DIR @GAC_DIR@) + +set(_csc_default_lib_path @_csc_default_lib_path@ CACHE INTERNAL "") + +set(CMAKE_CSharp_COMPILER_ENV_VAR "CSC") + diff --git a/cmake/cpack.cmk b/cmake/cpack.cmk new file mode 100644 index 0000000..2098fd5 --- /dev/null +++ b/cmake/cpack.cmk @@ -0,0 +1,21 @@ +set(CPACK_IGNORE_FILES "CMakeCache.txt;install_manifest.txt;/Testing/;/Makefile$;\\\\.tar.gz$;\\\\.so[.0-9]*$;/build/;/_CPack_Packages/;/CMakeFiles/;/CVS/;/\\\\.svn/;/\\\\.git/;\\\\.swp$;\\\\.#;/#") +set(CPACK_SOURCE_IGNORE_FILES ${CPACK_IGNORE_FILES}) +set(CPACK_SOURCE_GENERATOR TXZ ZIP) +set(CPACK_SOURCE_TOPLEVEL_TAG "") + +function(set_project_version MAJOR MINOR PATCH) + if(NOT PROJECT_NAME OR "${PROJECT_NAME}" STREQUAL "Project") + message(FATAL_ERROR "PROJECT_NAME MUST be defined before calling set_project_version()") + endif() + set(CPACK_PACKAGE_VERSION_MAJOR ${MAJOR}) + set(CPACK_PACKAGE_VERSION_MINOR ${MINOR}) + set(CPACK_PACKAGE_VERSION_PATCH ${PATCH}) + set(CPACK_PACKAGE_VERSION "${MAJOR}.${MINOR}.${PATCH}") + set(CPACK_SOURCE_PACKAGE_FILE_NAME "${PROJECT_NAME}-${CPACK_PACKAGE_VERSION}") + set(PROJECT_VERSION "${CPACK_PACKAGE_VERSION}" PARENT_SCOPE) + set(PROJECT_VERSION_MAJOR "${MAJOR}" PARENT_SCOPE) + set(PROJECT_VERSION_MINOR "${MINOR}" PARENT_SCOPE) + set(PROJECT_VERSION_PATCH "${PATCH}" PARENT_SCOPE) + include(CPack) +endfunction(set_project_version) + diff --git a/cmake/ctest.cmk b/cmake/ctest.cmk new file mode 100644 index 0000000..2e5223a --- /dev/null +++ b/cmake/ctest.cmk @@ -0,0 +1,8 @@ +include(CTest) +enable_testing() + +function(add_testdirectory DIR) + if (BUILD_TESTING) + add_subdirectory(${DIR}) + endif (BUILD_TESTING) +endfunction(add_testdirectory) diff --git a/cmake/paths.cmk b/cmake/paths.cmk new file mode 100644 index 0000000..593ebc1 --- /dev/null +++ b/cmake/paths.cmk @@ -0,0 +1,17 @@ +if(WIN32 AND NOT MINGW) + set(CMAKE_INSTALL_PREFIX "" CACHE PATH "Install prefix") + set(BIN_INSTALL_DIR . CACHE PATH "Binary install dir") + set(LIB_INSTALL_DIR . CACHE PATH "Library install dir") + set(LIBEXEC_INSTALL_DIR . CACHE PATH "Private executable install dir") + set(INCLUDE_INSTALL_DIR include CACHE PATH "Include install dir") + set(SYSCONF_INSTALL_DIR . CACHE PATH "Configuration install dir") + set(SHARE_INSTALL_DIR . CACHE PATH "Data install dir") +else(WIN32 AND NOT MINGW) + set(CMAKE_INSTALL_PREFIX /usr/local CACHE PATH "Install prefix") + set(BIN_INSTALL_DIR bin CACHE PATH "Binary install dir") + set(LIB_INSTALL_DIR lib${LIB_SUFFIX} CACHE PATH "Library install dir") + set(LIBEXEC_INSTALL_DIR libexec CACHE PATH "Private executable install dir") + set(INCLUDE_INSTALL_DIR include CACHE PATH "Include install dir") + set(SYSCONF_INSTALL_DIR /etc CACHE PATH "Configuration install dir") + set(SHARE_INSTALL_DIR share CACHE PATH "Data install dir") +endif(WIN32 AND NOT MINGW) diff --git a/doc/libproxy_files.dia b/doc/libproxy_files.dia new file mode 100644 index 0000000..ba61fa6 Binary files /dev/null and b/doc/libproxy_files.dia differ diff --git a/libmodman/CMakeLists.txt b/libmodman/CMakeLists.txt new file mode 100644 index 0000000..8264b33 --- /dev/null +++ b/libmodman/CMakeLists.txt @@ -0,0 +1,19 @@ +### Main library +# Flags / Definitions / Environment +if (WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS=1) +else(WIN32) + set(CMAKE_CXX_FLAGS "-fvisibility=hidden -fPIC ${CMAKE_CXX_FLAGS}") +endif(WIN32) +include_directories(${CMAKE_SOURCE_DIR}) + +add_library(modman STATIC + module.hpp + module_manager.hpp + module_manager.cpp) +if(NOT WIN32) + target_link_libraries(modman ${CMAKE_DL_LIBS}) +endif() + +### Tests +add_testdirectory(test) diff --git a/libmodman/module.hpp b/libmodman/module.hpp new file mode 100644 index 0000000..2d974aa --- /dev/null +++ b/libmodman/module.hpp @@ -0,0 +1,113 @@ +/******************************************************************************* + * libmodman - A library for extending applications + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef MODULE_HPP_ +#define MODULE_HPP_ + +#include // For NULL + +#ifndef MM_MODULE_BUILTIN +#define MM_MODULE_BUILTIN +#endif + +#ifdef _MSC_VER +#define __MM_DLL_EXPORT __declspec(dllexport) +#else +#define __MM_DLL_EXPORT __attribute__ ((visibility("default"))) +#endif + +#define __MM_MODULE_VERSION 2 +#define __MM_MODULE_VARNAME__(suffix, name) mm_ ## name ## _ ## suffix +#define __MM_MODULE_VARNAME_(suffix, name) __MM_MODULE_VARNAME__(suffix, name) +#define __MM_MODULE_VARNAME(name) __MM_MODULE_VARNAME_(MM_MODULE_BUILTIN, name) + +#define MM_MODULE_INIT(mtype, minit, mtest, msymb, msmod) \ + extern "C" __MM_DLL_EXPORT struct mm_module __MM_MODULE_VARNAME(info); \ + struct mm_module __MM_MODULE_VARNAME(info) = { \ + __MM_MODULE_VERSION, \ + # mtype, \ + mtype::base_type, \ + minit, mtest, msymb, msmod \ + } + +#define MM_MODULE_INIT_EZ(clsname, mtest, msymb, msmod) \ + static libmodman::base_extension** clsname ## _init() { \ + libmodman::base_extension** retval = new libmodman::base_extension*[2]; \ + retval[0] = new clsname(); \ + retval[1] = NULL; \ + return retval; \ + } \ + static bool clsname ## _test() { return mtest; } \ + MM_MODULE_INIT(clsname, clsname ## _init, clsname ## _test, msymb, msmod) + +/* Helper macro for loading builtins */ + +#define MM_DEF_BUILTIN(modname) \ + extern "C" struct mm_module __MM_MODULE_VARNAME_(modname,info) + +#define MM_BUILTIN(modname) __MM_MODULE_VARNAME_(modname,info) + + +namespace libmodman { + +class __MM_DLL_EXPORT base_extension { +public: + static const char* base_type() { return NULL; } + static bool singleton() { return false; } + virtual ~base_extension() {} + virtual const char* get_base_type() const =0; + virtual bool operator<(const base_extension&) const =0; +}; + +template +class __MM_DLL_EXPORT extension : public base_extension { +public: +#ifdef _MSC_VER + static const char* base_type() { return __FUNCSIG__; } +#else + static const char* base_type() { return __PRETTY_FUNCTION__; } +#endif + + static bool singleton() { return sngl; } + virtual const char* get_base_type() const { return basetype::base_type(); } + virtual bool operator<(const base_extension&) const { return false; }; +}; + +} + +extern "C" { + +struct __MM_DLL_EXPORT mm_module +{ +/* For some unknown reason, when vers is const VC++ (win32) NULLs out the whole struct. + * This obviously breaks module loading. I'd love to know the reason for this, so if + * anyone knows, please tell me. In the meantime, vers not being const is by design, + * so don't change it. */ + unsigned int vers; + const char* name; + const char* (*type)(); + libmodman::base_extension** (*init)(); + bool (*test)(); + const char* symb; + const char* smod; +}; + +} + +#endif /* MODULE_HPP_ */ diff --git a/libmodman/module_manager.cpp b/libmodman/module_manager.cpp new file mode 100644 index 0000000..192f8c3 --- /dev/null +++ b/libmodman/module_manager.cpp @@ -0,0 +1,330 @@ +/******************************************************************************* + * libmodman - A library for extending applications + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include // For sort() +#include // For stat() +#include +#include + +#ifdef WIN32 +#include +#else +#include // For dlopen(), etc... +#include // For opendir(), readdir(), closedir() +#endif + +#include "module_manager.hpp" +using namespace libmodman; + +#include + +#define _LOAD_FAIL -1 +#define _LOAD_LAZY 0 +#define _LOAD_SUCC 1 + +#ifdef WIN32 +#define pdlmtype HMODULE +#define pdlopenl(filename) LoadLibraryEx(filename, NULL, DONT_RESOLVE_DLL_REFERENCES) +#define pdlclose(module) FreeLibrary((pdlmtype) module) +static void* pdlsym(pdlmtype mod, string sym) { + return (void *) GetProcAddress(mod, sym.c_str()); +} + +static pdlmtype pdlreopen(const char* filename, pdlmtype module) { + pdlclose(module); + return LoadLibrary(filename); +} + +static string pdlerror() { + std::string e; + LPTSTR msg; + + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &msg, + 0, + NULL); + e = std::string((const char*) msg); + LocalFree(msg); + return e; +} + +static bool pdlsymlinked(const char* modn, const char* symb) { + return (GetProcAddress(GetModuleHandle(modn), symb) != NULL || \ + GetProcAddress(GetModuleHandle(NULL), symb) != NULL); +} + +static string prep_type_name(string name) { + string prefix = " >::iterator i=this->extensions.begin() ; i != this->extensions.end() ; i++) { + for (vector::iterator j=i->second.begin() ; j != i->second.end() ; j++) + delete *j; + i->second.clear(); + } + this->extensions.clear(); + + // Free all modules + for (set::iterator i=this->modules.begin() ; i != this->modules.end() ; i++) + pdlclose(*i); + this->modules.clear(); +} + +static int load(map >& extensions, + set& singletons, + mm_module *mod, + bool lazy, + bool symbreq) { + const char* debug = getenv("_MM_DEBUG"); + + if (!mod || mod->vers != __MM_MODULE_VERSION || !mod->type || !mod->init) { + if (debug) + cerr << "failed!" << endl + << "\tUnable to find basic module info!" << endl; + return _LOAD_FAIL; + } + + // Get the module type + string types = mod->type(); + + // Make sure the type is registered + if (extensions.find(types) == extensions.end()) { + if (debug) + cerr << "failed!" << endl + << "\tUnknown extension type: " << prep_type_name(types) << endl; + return _LOAD_FAIL; + } + + // If this is a singleton and we already have an instance, don't instantiate + if (singletons.find(types) != singletons.end() && + extensions[types].size() > 0) { + if (debug) + cerr << "failed!" << endl + << "\tNot loading subsequent singleton for: " << prep_type_name(types) << endl; + return _LOAD_FAIL; + } + + // If a symbol is defined, we'll search for it in the main process + if (mod->symb && mod->smod && !pdlsymlinked(mod->smod, mod->symb)) { + // If the symbol is not found and the symbol is required, error + if (symbreq) { + if (debug) + cerr << "failed!" << endl + << "\tUnable to find required symbol: " + << mod->symb << endl; + return _LOAD_FAIL; + } + + // If the symbol is not found and not required, we'll load only + // if there are no other modules of this type + else if (extensions[types].size() > 0) { + if (debug) + cerr << "failed!" << endl + << "\tUnable to find required symbol: " + << mod->symb << endl; + return _LOAD_FAIL; + } + } + + // We've passed all the tests this far, do it again in non-lazy mode + if (lazy) return _LOAD_LAZY; + + // If our execution test succeeds, call init() + if ((mod->test && mod->test()) || !mod->test) { + base_extension** exts = mod->init(); + if (!exts) { + if (debug) + cerr << "failed!" << endl + << "\tinit() returned no extensions!" << endl; + return _LOAD_FAIL; + } + + if (debug) + cerr << "success" << endl; + + // init() returned extensions we need to register + for (unsigned int i=0 ; exts[i] ; i++) { + if (debug) + cerr << "\tRegistering " + << typeid(*exts[i]).name() << "(" + << prep_type_name(exts[i]->get_base_type()) << ")" << endl; + extensions[exts[i]->get_base_type()].push_back(exts[i]); + } + delete[] exts; + return _LOAD_SUCC; + } + + if (debug) + cerr << "failed!" << endl + << "\tTest execution failed." << endl; + return _LOAD_FAIL; +} + +bool module_manager::load_builtin(mm_module *mod) { + const char* debug = getenv("_MM_DEBUG"); + if (debug) + cerr << "loading : builtin module " << mod->name << CR; + + // Do the load with the specified prefix + int status = load(this->extensions, this->singletons, mod, false, false); + return status == _LOAD_SUCC; +} + +bool module_manager::load_file(string filename, bool symbreq) { + const char* debug = getenv("_MM_DEBUG"); + + // Stat the file to make sure it is a file + struct stat st; + if (stat(filename.c_str(), &st) != 0) return false; + if ((st.st_mode & S_IFMT) != S_IFREG) return false; + + if (debug) + cerr << "loading : " << filename << CR; + + // Open the module + pdlmtype dlobj = pdlopenl(filename.c_str()); + if (!dlobj) { + if (debug) + cerr << "failed!" << endl + << "\t" << pdlerror() << endl; + return false; + } + + // If we have already loaded this module, return true + if (this->modules.find((void*) dlobj) != this->modules.end()) { + if (debug) + cerr << "preload" << endl; + pdlclose(dlobj); + return true; + } + + // Try and finish the load + struct mm_module *mod_info = (mm_module*) pdlsym(dlobj, __str(__MM_MODULE_VARNAME(info))); + int status = load(this->extensions, this->singletons, mod_info, true, symbreq); + if (status == _LOAD_LAZY) { // Reload the module in non-lazy mode + dlobj = pdlreopen(filename.c_str(), dlobj); + if (!dlobj) { + if (debug) + cerr << "failed!" << endl + << "\tUnable to reload module: " << pdlerror() << endl; + return false; + } + mod_info = (mm_module*) pdlsym(dlobj, __str(__MM_MODULE_VARNAME(info))); + status = load(this->extensions, this->singletons, mod_info, false, symbreq); + } + if (status == _LOAD_FAIL) { + pdlclose(dlobj); + return false; + } + + // Add the dlobject to our known modules + this->modules.insert((void*) dlobj); + + // Yay, we did it! + return true; +} + +bool module_manager::load_dir(string dirname, bool symbreq) { + vector files; + +#ifdef WIN32 + WIN32_FIND_DATA fd; + HANDLE search; + + string srch = dirname + "\\*." + _MOD_SUFFIX; + search = FindFirstFile(srch.c_str(), &fd); + if (search != INVALID_HANDLE_VALUE) { + do { + files.push_back(dirname + "\\" + fd.cFileName); + } while (FindNextFile(search, &fd)); + FindClose(search); + } +#else + struct dirent *ent; + + DIR *moduledir = opendir(dirname.c_str()); + if (moduledir) { + while((ent = readdir(moduledir))) { + string tmp = ent->d_name; + if (tmp.find(_MOD_SUFFIX, tmp.size() - string(_MOD_SUFFIX).size()) != tmp.npos) + files.push_back(dirname + "/" + tmp); + } + closedir(moduledir); + } +#endif + + // Perform our load alphabetically + sort(files.begin(), files.end()); + + // Try to do the load + bool loaded = false; + for (vector::iterator it = files.begin() ; it != files.end() ; it++) + loaded = this->load_file(*it, symbreq) || loaded; + return loaded; +} diff --git a/libmodman/module_manager.hpp b/libmodman/module_manager.hpp new file mode 100644 index 0000000..f221bff --- /dev/null +++ b/libmodman/module_manager.hpp @@ -0,0 +1,86 @@ +/******************************************************************************* + * libmodman - A library for extending applications + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef MODULE_MANAGER_HPP_ +#define MODULE_MANAGER_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "module.hpp" + +namespace libmodman { +using namespace std; + +class __MM_DLL_EXPORT module_manager { +public: + ~module_manager(); + bool load_builtin(mm_module *mod); + bool load_file(string filename, bool symbreq=true); + bool load_dir(string dirname, bool symbreq=true); + + template vector get_extensions() const { + struct pcmp { + static bool cmp(T* x, T* y) { return *x < *y; } + }; + + map >::const_iterator it = this->extensions.find(T::base_type()); + vector retlist; + + if (it != this->extensions.end()) { + vector extlist = it->second; + + for (size_t i=0 ; i < extlist.size() ; i++) { + T* obj = dynamic_cast(extlist[i]); + if (obj) + retlist.push_back(obj); + else + assert (obj != NULL); + } + + sort(retlist.begin(), retlist.end(), &pcmp::cmp); + } + + return retlist; + } + + template bool register_type() { + if (T::singleton()) { + if (!this->singletons.insert(T::base_type()).second) + return false; + } + else + this->singletons.erase(T::base_type()); + this->extensions[T::base_type()]; + return true; + } + +private: + set modules; + set singletons; + map > extensions; +}; + +} + +#endif /* MODULE_MANAGER_HPP_ */ diff --git a/libmodman/test/CMakeLists.txt b/libmodman/test/CMakeLists.txt new file mode 100644 index 0000000..168b130 --- /dev/null +++ b/libmodman/test/CMakeLists.txt @@ -0,0 +1,79 @@ +##### +## LibModMan Tests +#### + +# Functions +function(mm_create_module MODTYPE MODNAME MODCOND MODSYMB MODSMOD) + configure_file(module.cpp.in + ${CMAKE_CURRENT_BINARY_DIR}/${MODTYPE}_${MODNAME}.cpp + @ONLY) + add_library(${MODTYPE}_${MODNAME} + MODULE + ${CMAKE_CURRENT_BINARY_DIR}/${MODTYPE}_${MODNAME}.cpp) + set_target_properties(${MODTYPE}_${MODNAME} + PROPERTIES PREFIX "" + LIBRARY_OUTPUT_DIRECTORY + ${CMAKE_CURRENT_BINARY_DIR}/modules/${MODTYPE}) + target_link_libraries(${MODTYPE}_${MODNAME} modman) +endfunction(mm_create_module) + +function(mm_create_program name EXTTYPE) + add_executable(${name} main.cpp) + target_link_libraries(${name} modman) + set_property(TARGET ${name} PROPERTY + COMPILE_DEFINITIONS + EXTTYPE=${EXTTYPE}_extension) + if(${ARGC} GREATER 2) + target_link_libraries(${name} ${ARGN};modman) + set_property(TARGET ${name} PROPERTY + COMPILE_DEFINITIONS + EXTTYPE=${EXTTYPE}_extension;SYMB=1) + if(NOT WIN32 AND NOT APPLE) + set_property(TARGET ${name} PROPERTY + LINK_FLAGS -Wl,--no-as-needed) + endif() + endif() +endfunction(mm_create_program) + +# Modules +mm_create_module(condition one false NULL NULL) +mm_create_module(condition two true NULL NULL) +mm_create_module(singleton one true NULL NULL) +mm_create_module(singleton two true NULL NULL) +mm_create_module(sorted one true NULL NULL) +mm_create_module(sorted two true NULL NULL) +mm_create_module(builtin one true NULL NULL) +if (WIN32) + mm_create_module(symbol one true \"asdfoia\" \"ws2_32\") + mm_create_module(symbol two true \"recv\" \"ws2_32\") +else() + mm_create_module(symbol one true \"asdfoia\" \"z\") + mm_create_module(symbol two true \"deflate\" \"z\") +endif() + +# Programs +mm_create_program(condition condition) +mm_create_program(singleton singleton) +mm_create_program(sorted sorted) +mm_create_program(symbol symbol) +if (WIN32) + mm_create_program(symbollnk symbol ws2_32) +else() + mm_create_program(symbollnk symbol z) +endif() +add_executable(builtin + builtin.cpp + ${CMAKE_CURRENT_BINARY_DIR}/builtin_one.cpp) +target_link_libraries(builtin modman) +set_property(TARGET builtin PROPERTY COMPILE_DEFINITIONS + EXTTYPE=builtin_extension;BUILTIN_MODULE=extension;MM_MODULE_BUILTIN=extension) + +# Tests +add_test(NAME condition COMMAND condition $ two) +add_test(NAME singleton COMMAND singleton $ one) +add_test(NAME sorted COMMAND sorted $ two one) +add_test(NAME symbol COMMAND symbollnk $ two) +add_test(NAME nosymbol COMMAND symbol $) +add_test(NAME nosymreq COMMAND symbol $ one) +add_test(NAME builtin COMMAND builtin) + diff --git a/libmodman/test/builtin.cpp b/libmodman/test/builtin.cpp new file mode 100644 index 0000000..8a3f328 --- /dev/null +++ b/libmodman/test/builtin.cpp @@ -0,0 +1,28 @@ +/******************************************************************************* + * libmodman - A library for extending applications + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "main.hpp" + +MM_DEF_BUILTIN(BUILTIN_MODULE); + +int main() { + module_manager mm; + mm.register_type(); + return !mm.load_builtin(& MM_BUILTIN(BUILTIN_MODULE)); +} diff --git a/libmodman/test/main.cpp b/libmodman/test/main.cpp new file mode 100644 index 0000000..cf930c1 --- /dev/null +++ b/libmodman/test/main.cpp @@ -0,0 +1,72 @@ +/******************************************************************************* + * libmodman - A library for extending applications + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include +#include +#include +#ifdef WIN32 +#ifdef SYMB +#include +#endif +#endif + +#include "main.hpp" + +int main(int argc, const char** argv) { + module_manager mm; +#ifdef WIN32 +#ifdef SYMB + void* symb = recv; +#endif +#endif + + if (argc < 2) { + cout << "Usage: " << argv[0] << " MODULEDIR MODNAME ..." << endl; + return 1; + } + + if (!mm.register_type()) { + cout << "Unable to register type!" << endl; + return 2; + } + + if (!mm.load_dir(argv[1]) && argc > 2) { + if (!mm.load_dir(argv[1], false)) { + cout << "Unable to load modules!" << endl; + return 3; + } + } + + vector exts = mm.get_extensions(); + if (exts.size() != (unsigned int) argc - 2) { + cout << "Wrong number of extensions found!" << endl; + return 4; + } + + for (unsigned int i=0 ; i < exts.size() ; i++) { + if (!strstr(typeid(*(exts[i])).name(), argv[i+2])) { + cout << "Unable to find extension! Here's the list:" << endl; + for (unsigned int j=0 ; j < exts.size() ; j++) + cout << "\t" << typeid(*(exts[j])).name() << endl; + return 5; + } + } + + return 0; +} diff --git a/libmodman/test/main.hpp b/libmodman/test/main.hpp new file mode 100644 index 0000000..0a08c63 --- /dev/null +++ b/libmodman/test/main.hpp @@ -0,0 +1,43 @@ +/******************************************************************************* + * libmodman - A library for extending applications + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef MAIN_HPP_ +#define MAIN_HPP_ + +#include + +#include "../module_manager.hpp" + +using namespace std; +using namespace libmodman; + +class __MM_DLL_EXPORT singleton_extension : public extension {}; + +class __MM_DLL_EXPORT sorted_extension : public extension { +public: + virtual bool operator<(const base_extension& other) const { + return string(typeid(*this).name()) > string(typeid(other).name()); + } +}; + +class __MM_DLL_EXPORT symbol_extension : public extension {}; +class __MM_DLL_EXPORT condition_extension : public extension {}; +class __MM_DLL_EXPORT builtin_extension : public extension {}; + +#endif /* MAIN_HPP_ */ diff --git a/libmodman/test/module.cpp.in b/libmodman/test/module.cpp.in new file mode 100644 index 0000000..3390ead --- /dev/null +++ b/libmodman/test/module.cpp.in @@ -0,0 +1,24 @@ +/******************************************************************************* + * libmodman - A library for extending applications + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include +#include + +class @MODNAME@ : public @MODTYPE@_extension {}; +MM_MODULE_INIT_EZ(@MODNAME@, @MODCOND@, @MODSYMB@, @MODSMOD@); diff --git a/libproxy.spec.in b/libproxy.spec.in new file mode 100644 index 0000000..550a855 --- /dev/null +++ b/libproxy.spec.in @@ -0,0 +1,398 @@ +# +# spec file for package libproxy (Version 0.4.0) +# +# Copyright (c) 2010 SUSE LINUX Products GmbH, Nuernberg, Germany. +# +# All modifications and additions to the file contributed by third parties +# remain the property of their copyright owners, unless otherwise agreed +# upon. The license for this file, and modifications and additions to the +# file, is the same license as for the pristine package itself (unless the +# license for the pristine package is not an Open Source License, in which +# case the license is the MIT License). An "Open Source License" is a +# license that conforms to the Open Source Definition (Version 1.9) +# published by the Open Source Initiative. + +# Please submit bugfixes or comments via http://bugs.opensuse.org/ +# + +# norootforbuild + +%define build_core_not_modules 1 +%if 0%{suse_version} > 1120 +%define xulrunner_ver 192 +%else +%if 0%{suse_version} > 1110 +%define xulrunner_ver 191 +%else +%if 0%{suse_version} >= 1100 +%define xulrunner_ver 190 +%else +%define xulrunner_ver 181 +%endif +%endif +%endif +Url: http://code.google.com/p/libproxy/ +%define _name libproxy + +Name: libproxy +Group: System/Libraries +Summary: Libproxy provides consistent proxy configuration to applications +Version: @VERSION@ +Release: 4 +Source: http://libproxy.googlecode.com/files/%{_name}-%{version}.tar.bz2 +Source99: baselibs.conf +License: LGPLv2.1+ +BuildRoot: %{_tmppath}/%{name}-%{version}-build +BuildRequires: cmake +BuildRequires: gcc-c++ +BuildRequires: pkg-config +BuildRequires: zlib-devel +%if !%build_core_not_modules +BuildRequires: dbus-1-devel +BuildRequires: gconf2-devel +# For directory ownership, but also because we want to rebuild the modules if +# the library changed +BuildRequires: libproxy1 +BuildRequires: libwebkit-devel +BuildRequires: mozilla-xulrunner%{xulrunner_ver}-devel +BuildRequires: NetworkManager-devel +BuildRequires: libkde4-devel +BuildRequires: libqt4-devel +%else +BuildRequires: python-devel +%endif + +%if %suse_version <= 1110 +%define python_sitelib %{py_sitedir} +%endif + +%description +libproxy offers the following features: * extremely small core + footprint (< 35K) + +* no external dependencies within libproxy core (libproxy modules + may have dependencies) + +* only 3 functions in the stable external API + +* dynamic adjustment to changing network topology + +* a standard way of dealing with proxy settings across all scenarios + + +%if %build_core_not_modules + +%package tools +License: GPLv2+ ; LGPLv2.1+ +Summary: A simple application using libproxy +Group: System/Libraries +Requires: libproxy1 = %{version} + +%description tools +A simple application that will use libproxy to give the results you can +expect from other applications. It can be used to debug what would +happen in various cases. + + +%package devel +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy provides consistent proxy configuration to applications - Development Files +Group: Development/Libraries/C and C++ +Requires: libproxy1 = %{version} + +%description devel +libproxy offers the following features: * extremely small core + footprint (< 35K) + +* no external dependencies within libproxy core (libproxy modules + may have dependencies) + +* only 3 functions in the stable external API + +* dynamic adjustment to changing network topology + +* a standard way of dealing with proxy settings across all scenarios + + +%package -n libproxy1 +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy provides consistent proxy configuration to applications +Group: System/Libraries + +%description -n libproxy1 +libproxy offers the following features: * extremely small core + footprint (< 35K) + +* no external dependencies within libproxy core (libproxy modules + may have dependencies) + +* only 3 functions in the stable external API + +* dynamic adjustment to changing network topology + +* a standard way of dealing with proxy settings across all scenarios + +%package -n libmodman0_0_0 +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy's Module Management Library +Group: System/Libraries + +%description -n libmodman0_0_0 +A module management library taking care of loading / unload modules +including heuristics in detecting which bindings might already +be used by an application and favouring this one. + + +%package -n python-libproxy +License: GPLv2+ ; LGPLv2.1+ +Summary: Python bindings for libproxy +Group: System/Libraries +BuildArch: noarch +Requires: libproxy1 = %{version} +%py_requires + +%description -n python-libproxy +libproxy offers the following features: * extremely small core + footprint (< 35K) + +* no external dependencies within libproxy core (libproxy modules + may have dependencies) + +* only 3 functions in the stable external API + +* dynamic adjustment to changing network topology + +* a standard way of dealing with proxy settings across all scenarios + + +%package -n perl-Net-Libproxy +License: GPLv2+ ; LGPLv2.1+ +Summary: Perl bindings for libproxy +Group: Development/Libraries/Perl +Requires: libproxy1 = %{version} +Requires: perl = %{perl_version}%py_requires + +%description -n perl-Net-Libproxy +libproxy offers the following features: * extremely small core + footprint (< 35K) + +* no external dependencies within libproxy core (libproxy modules + may have dependencies) + +* only 3 functions in the stable external API + +* dynamic adjustment to changing network topology + +* a standard way of dealing with proxy settings across all scenarios + + +%package -n libproxy-sharp +License: GPLv2+ ; LGPLv2.1+ +Summary: .Net bindings for libproxy +Group: Development/Languages/Mono +Requires: libproxy1 = %{version} + +%description -n libproxy-sharp +libproxy offers the following features: * extremely small core + footprint (< 35K) + +* no external dependencies within libproxy core (libproxy modules + may have dependencies) + +* only 3 functions in the stable external API + +* dynamic adjustment to changing network topology + +* a standard way of dealing with proxy settings across all scenarios + + +%else + +%package -n libproxy1-config-gnome +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy module for GNOME configuration +Group: System/Libraries +Requires: libproxy1 = %{version} +Recommends: libproxy1-pacrunner = %{version} +Recommends: libproxy1-wpad-dns = %{version} +Supplements: packageand(libproxy1:gconf2) +Provides: libproxy-gnome = %{version} +Obsoletes: libproxy-gnome < %{version} + +%description -n libproxy1-config-gnome +A module to extend libproxy with capabilities to query GNOME about +proxy settings. + + +%package -n libproxy1-config-kde4 +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy module for KDE configuration +Group: System/Libraries +Requires: libproxy1 = %{version} +Recommends: libproxy1-pacrunner = %{version} +Recommends: libproxy1-wpad-dns = %{version} +Supplements: packageand(libproxy1:libkde4) +Provides: libproxy-kde = %{version} +Obsoletes: libproxy-kde < %{version} + +%description -n libproxy1-config-kde4 +A module to extend libproxy with capabilities to query KDE4 about proxy +settings. + + +%package -n libproxy1-pacrunner-mozjs +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy module to support wpad/pac parsing via Mozilla JavaScript Engine +Group: System/Libraries +Requires: libproxy1 = %{version} +Supplements: packageand(libproxy1:mozilla-xulrunner%{xulrunner_ver}) +# A virtual symbol to identify that this is a pacrunner. +Provides: libproxy1-pacrunner = %{version} + +%description -n libproxy1-pacrunner-mozjs +A module to extend libproxy with capabilities to pass addresses to a +WPAD/PAC script and have it find the correct proxy. + + +%package -n libproxy1-pacrunner-webkit +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy module to support WPAD/PAC parsing via WebKit JavaScript Engine +Group: System/Libraries +Requires: libproxy1 = %{version} +Supplements: packageand(libproxy1:libwebkit-1) +# A virtual symbol to identify that this is a pacrunner. +Provides: libproxy1-pacrunner = %{version} + +%description -n libproxy1-pacrunner-webkit +A module to extend libproxy with capabilities to pass addresses to a +WPAD/PAC script and have it find the correct proxy. + + +%package -n libproxy1-networkmanager +License: GPLv2+ ; LGPLv2.1+ +Summary: Libproxy module for NetworkManager configuration +Group: System/Libraries +Requires: libproxy1 = %{version} +Supplements: packageand(libproxy1:NetworkManager) + +%description -n libproxy1-networkmanager +A module to extend libproxy with capabilities to query NetworkManager +about network configuration changes. + +%endif + +%prep +%setup -q -n %{_name}-%{version} +mkdir build + +%build +cd build +cmake \ + -DCMAKE_INSTALL_PREFIX=%{_prefix} \ + -Dlibdir=%{_libdir} \ + -Dlibexecdir=%{_libexecdir}/libproxy \ + -Ddatadir=%{_datadir} \ + -Dmoduledir=%{_libdir}/libproxy/%{version}/modules \ + -DWITH_VALA=yes \ + -DPERL_VENDORINSTALL=yes \ +.. +%{__make} %{?jobs:-j%jobs} VERBOSE=1 + +%install +cd build +%makeinstall +%if %build_core_not_modules +# Build the basic directory structure for the modules so we can +# own the directories in the main library package +install -d %{buildroot}%{_libexecdir}/libproxy +install -d %{buildroot}%{_libdir}/%{name}/%{version}/modules +%else +# remove files that are part of the core +rm %{buildroot}%{_includedir}/*.h +# Delete all files that exist in the base libproxy package +rm %{buildroot}%{_bindir}/proxy +rm %{buildroot}%{_libdir}/libproxy.so* +rm %{buildroot}%{_libdir}/libmodman.so* +rm %{buildroot}%{python_sitelib}/*.py +rm %{buildroot}%{_libdir}/pkgconfig/libproxy-1.0.pc +rm %{buildroot}%{_datadir}/cmake/Modules/Findlibproxy.cmake +rm %{buildroot}%{_datadir}/vala/vapi/libproxy-1.0.vapi +rm %{buildroot}%{perl_vendorarch}/Net/Libproxy.pm +rm %{buildroot}%{perl_vendorarch}/auto/Net/Libproxy/Libproxy.so +%endif +%if %build_core_not_modules + +%post -n libproxy1 -p /sbin/ldconfig + +%post -n libmodman0_0_0 -p /sbin/ldconfig + +%postun -n libproxy1 -p /sbin/ldconfig + +%postun -n libmodman0_0_0 -p /sbin/ldconfig + +%files tools +%defattr(-, root, root) +%{_bindir}/proxy + +%files -n libproxy1 +%defattr(-, root, root) +%{_libdir}/libproxy.so.* +%dir %{_libexecdir}/libproxy +%dir %{_libdir}/libproxy +%dir %{_libdir}/libproxy/%{version} +%dir %{_libdir}/libproxy/%{version}/modules +#%{_libdir}/libproxy/%{version}/modules/config_envvar.so +#%{_libdir}/libproxy/%{version}/modules/config_file.so +#%{_libdir}/libproxy/%{version}/modules/config_direct.so +#%{_libdir}/libproxy/%{version}/modules/ignore_*.so + +%files -n libmodman0_0_0 +%defattr(-, root, root) +%{_libdir}/libmodman.so.* + +%files devel +%defattr(-, root, root) +%{_includedir}/*.h +%{_libdir}/*.so +%{_libdir}/pkgconfig/libproxy-1.0.pc +%{_datadir}/cmake/Modules/Findlibproxy.cmake +%dir %{_datadir}/vala +%dir %{_datadir}/vala/vapi +%{_datadir}/vala/vapi/libproxy-1.0.vapi + +%files -n python-libproxy +%defattr(-, root, root) +%{python_sitelib}/*.py + +%files -n perl-Net-Libproxy +%defattr(-,root,root) +%dir %{perl_vendorarch}/Net +%dir %{perl_vendorarch}/auto/Net +%dir %{perl_vendorarch}/auto/Net/Libproxy +%{perl_vendorarch}/Net/Libproxy.pm +%{perl_vendorarch}/auto/Net/Libproxy/Libproxy.so +%else + +%files -n libproxy1-config-kde4 +%defattr(-, root, root) +%{_libdir}/libproxy/%{version}/modules/config_kde4.so + +%files -n libproxy1-config-gnome +%defattr(-, root, root) +%{_libdir}/libproxy/%{version}/modules/config_gnome.so +%{_libexecdir}/libproxy/pxgconf + +%files -n libproxy1-networkmanager +%defattr(-, root, root) +%{_libdir}/libproxy/%{version}/modules/network_networkmanager.so + +%files -n libproxy1-pacrunner-webkit +%defattr(-, root, root) +%{_libdir}/libproxy/%{version}/modules/pacrunner_webkit.so + +%files -n libproxy1-pacrunner-mozjs +%defattr(-, root, root) +%{_libdir}/libproxy/%{version}/modules/pacrunner_mozjs.so +%endif + +%changelog diff --git a/libproxy/CMakeLists.txt b/libproxy/CMakeLists.txt new file mode 100644 index 0000000..9151030 --- /dev/null +++ b/libproxy/CMakeLists.txt @@ -0,0 +1,23 @@ +### Project info +project(libproxy) +set_project_version(0 4 15) + +### Add a global compilation stuff +if (WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS=1) +else(WIN32) + add_definitions(-D_POSIX_C_SOURCE=200112L) + set(CMAKE_CXX_FLAGS "-fvisibility=hidden ${CMAKE_CXX_FLAGS}") +endif(WIN32) + +### Modules +include(cmake/modules.cmk) + +### Dev files +include(cmake/devfiles.cmk) + +### Main library +include(cmake/libproxy.cmk) + +### Tests +add_testdirectory(test) diff --git a/libproxy/Findlibproxy.cmake.in b/libproxy/Findlibproxy.cmake.in new file mode 100644 index 0000000..ef44489 --- /dev/null +++ b/libproxy/Findlibproxy.cmake.in @@ -0,0 +1,26 @@ +# - Try to find libproxy +# Once done this will define +# +# LIBPROXY_FOUND - system has libproxy +# LIBPROXY_INCLUDE_DIR - the libproxy include directory +# LIBPROXY_LIBRARIES - libproxy library +# +# Copyright (c) 2010, Dominique Leuenberger +# +# Redistribution and use is allowed according the license terms +# of libproxy, which this file is integrated part of. + +# Find proxy.h and the corresponding library (libproxy.so) +FIND_PATH(LIBPROXY_INCLUDE_DIR proxy.h ) +FIND_LIBRARY(LIBPROXY_LIBRARIES NAMES proxy ) + +# Set library version +SET(LIBPROXY_VERSION @PROJECT_VERSION@) +SET(LIBPROXY_VERSION_MAJOR @PROJECT_VERSION_MAJOR@) +SET(LIBPROXY_VERSION_MINOR @PROJECT_VERSION_MINOR@) +SET(LIBPROXY_VERSION_PATCH @PROJECT_VERSION_PATCH@) + +# Give output, should this be wished (this handles also QUIET and REQUIRED +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(libproxy DEFAULT_MSG LIBPROXY_LIBRARIES LIBPROXY_INCLUDE_DIR) + diff --git a/libproxy/cmake/devfiles.cmk b/libproxy/cmake/devfiles.cmk new file mode 100644 index 0000000..0301dce --- /dev/null +++ b/libproxy/cmake/devfiles.cmk @@ -0,0 +1,23 @@ +if(NOT WIN32 OR MINGW) + # PkgConfig file + set (PKGCONFIG_PREFIX ${CMAKE_INSTALL_PREFIX}) + + if(IS_ABSOLUTE ${LIB_INSTALL_DIR}) + set (PKGCONFIG_LIBDIR ${LIB_INSTALL_DIR}) + else(IS_ABSOLUTE ${LIB_INSTALL_DIR}) + set (PKGCONFIG_LIBDIR "\${prefix}/${LIB_INSTALL_DIR}") + endif (IS_ABSOLUTE ${LIB_INSTALL_DIR}) + + if(IS_ABSOLUTE ${INCLUDE_INSTALL_DIR}) + set (PKGCONFIG_INCLUDEDIR ${INCLUDE_INSTALL_DIR}) + else(IS_ABSOLUTE ${INCLUDE_INSTALL_DIR}) + set (PKGCONFIG_INCLUDEDIR "\${prefix}/${INCLUDE_INSTALL_DIR}") + endif(IS_ABSOLUTE ${INCLUDE_INSTALL_DIR}) + + configure_file(${CMAKE_SOURCE_DIR}/libproxy/libproxy-1.0.pc.in ${CMAKE_BINARY_DIR}/libproxy-1.0.pc @ONLY) + install(FILES ${CMAKE_BINARY_DIR}/libproxy-1.0.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) + + # CMake Find helper + configure_file(${CMAKE_SOURCE_DIR}/libproxy/Findlibproxy.cmake.in ${CMAKE_BINARY_DIR}/Findlibproxy.cmake @ONLY) + install(FILES ${CMAKE_BINARY_DIR}/Findlibproxy.cmake DESTINATION ${SHARE_INSTALL_DIR}/cmake/Modules) +endif(NOT WIN32 OR MINGW) diff --git a/libproxy/cmake/libproxy.cmk b/libproxy/cmake/libproxy.cmk new file mode 100644 index 0000000..aab7593 --- /dev/null +++ b/libproxy/cmake/libproxy.cmk @@ -0,0 +1,25 @@ +add_library(libproxy SHARED extension_config.cpp extension_pacrunner.cpp extension_wpad.cpp proxy.cpp url.cpp ${LIBPROXY_SOURCES}) +if(WIN32) + target_link_libraries(libproxy modman;ws2_32;${LIBPROXY_LIBRARIES}) +else() + target_link_libraries(libproxy modman;m;pthread;${CMAKE_DL_LIBS};${LIBPROXY_LIBRARIES}) +endif() +file(TO_NATIVE_PATH ${MODULE_INSTALL_DIR} MODULE_INSTALL_DIR) +if(WIN32) + string(REGEX REPLACE "\\\\" "\\\\\\\\" MODULE_INSTALL_DIR ${MODULE_INSTALL_DIR}) +endif() + +if(IS_ABSOLUTE "${MODULE_INSTALL_DIR}") + set(MODULEDIR "${MODULE_INSTALL_DIR}") +else () + set(MODULEDIR "${CMAKE_INSTALL_PREFIX}/${MODULE_INSTALL_DIR}") +endif() + +set_property(SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/proxy.cpp + PROPERTY COMPILE_DEFINITIONS MODULEDIR="${MODULEDIR}";BUILTIN_MODULES=${BUILTIN_MODULES}) +# When changing the SOVERSION here remember to also bump the 'favorite proxy .so' in python bindings. +set_target_properties(libproxy PROPERTIES PREFIX "" VERSION 1.0.0 SOVERSION 1) +set_target_properties(libproxy PROPERTIES INTERFACE_LINK_LIBRARIES "") +set_target_properties(libproxy PROPERTIES LINK_INTERFACE_LIBRARIES "") +install(TARGETS libproxy DESTINATION ${LIB_INSTALL_DIR}) +install(FILES proxy.h DESTINATION ${INCLUDE_INSTALL_DIR}) diff --git a/libproxy/cmake/modules.cmk b/libproxy/cmake/modules.cmk new file mode 100644 index 0000000..b3211f2 --- /dev/null +++ b/libproxy/cmake/modules.cmk @@ -0,0 +1,49 @@ +# Setup module path +if(WIN32) + set(MODULE_INSTALL_DIR ${LIB_INSTALL_DIR}/modules CACHE PATH "Module install dir") +else() + set(MODULE_INSTALL_DIR ${LIB_INSTALL_DIR}/${PROJECT_NAME}/${PROJECT_VERSION}/modules CACHE PATH "Module install dir") +endif() + +# Do module determination +include(cmake/pxmodule.cmk) +include(cmake/pkgconfig.cmk) +include(cmake/modules/config_envvar.cmk) +include(cmake/modules/config_sysconfig.cmk) +include(cmake/modules/config_gnome.cmk) +include(cmake/modules/config_kde.cmk) +include(cmake/modules/config_macosx.cmk) +include(cmake/modules/network_networkmanager.cmk) +include(cmake/modules/pacrunner_mozjs.cmk) +include(cmake/modules/pacrunner_natus.cmk) +include(cmake/modules/pacrunner_webkit.cmk) + +# Build the pacrunner into libproxy unless we are building for multiple engines +set(BIPR 1 CACHE BOOL "Build internal pacrunner? (Always false when building more than one PR") +if((MOZJS_FOUND AND WEBKIT_FOUND) OR (MOZJS_FOUND AND NATUS_FOUND) OR (WEBKIT_FOUND AND NATUS_FOUND)) + set(BIPR 0) +endif() + +# +## Module definition +# +message("MODULES TO BUILD:") +px_module(config_envvar "${ENVVAR_FOUND}" 1) +px_module(config_sysconfig "${SYSCONFIG_FOUND}" 1) +px_module(config_gnome "${GNOME2_FOUND}" 0) +px_module(config_gnome3 "${GNOME3_FOUND}" 0) +px_module(config_kde "${WITH_KDE}" 0) +px_module(config_macosx "${SC_FOUND}" 1 ${SC_LIBRARIES} ${CF_LIBRARIES}) +px_module(config_w32reg "${WIN32}" 1) +px_module(ignore_domain 1 1) +px_module(ignore_hostname 1 1) +px_module(ignore_ip 1 1) +if(NM_FOUND OR NMold_FOUND) + set(NM_BUILD 1) +endif(NM_FOUND OR NMold_FOUND) +px_module(network_networkmanager "${NM_BUILD}" 0 ${NM_LIBRARIES}${NMold_LIBRARIES}) +px_module(pacrunner_mozjs "${MOZJS_FOUND}" ${BIPR} ${MOZJS_LIBRARIES}) +px_module(pacrunner_natus "${NATUS_FOUND}" ${BIPR} ${NATUS_LIBRARIES}) +px_module(pacrunner_webkit "${WEBKIT_FOUND}" ${BIPR} ${WEBKIT_LIBRARIES}) +px_module(wpad_dns_alias 1 1) +message("") diff --git a/libproxy/cmake/modules/config_envvar.cmk b/libproxy/cmake/modules/config_envvar.cmk new file mode 100644 index 0000000..e9445a4 --- /dev/null +++ b/libproxy/cmake/modules/config_envvar.cmk @@ -0,0 +1,3 @@ +if (NOT WIN32 AND NOT APPLE) + set(ENVVAR_FOUND 1) +endif() \ No newline at end of file diff --git a/libproxy/cmake/modules/config_gnome.cmk b/libproxy/cmake/modules/config_gnome.cmk new file mode 100644 index 0000000..4326972 --- /dev/null +++ b/libproxy/cmake/modules/config_gnome.cmk @@ -0,0 +1,22 @@ +if (NOT WIN32 AND NOT APPLE) + option(WITH_GNOME2 "Target a GNOME 2 system (gconf)" OFF) + option(WITH_GNOME3 "Target a GNOME 3 system (gsettings)" ON) + if(WITH_GNOME3) + px_check_modules(GNOME3 gio-2.0>=2.26 gobject-2.0) + else(WITH_GNOME3) + px_check_modules(GNOME2 gconf-2.0 gobject-2.0) + endif(WITH_GNOME3) + + # GNOME (gconf) helper + if(GNOME2_FOUND OR GNOME3_FOUND) + if(WITH_GNOME3) + add_executable(pxgsettings modules/pxgsettings.cpp) + target_link_libraries(pxgsettings ${GNOME3_LIBRARIES}) + install(TARGETS pxgsettings RUNTIME DESTINATION ${LIBEXEC_INSTALL_DIR}) + else(WITH_GNOME3) + add_executable(pxgconf modules/pxgconf.cpp) + target_link_libraries(pxgconf ${GNOME2_LIBRARIES}) + install(TARGETS pxgconf RUNTIME DESTINATION ${LIBEXEC_INSTALL_DIR}) + endif(WITH_GNOME3) + endif() +endif() diff --git a/libproxy/cmake/modules/config_kde.cmk b/libproxy/cmake/modules/config_kde.cmk new file mode 100644 index 0000000..ed2f828 --- /dev/null +++ b/libproxy/cmake/modules/config_kde.cmk @@ -0,0 +1,4 @@ +option(WITH_KDE "Build module to read proxy settings from KDE4/KF5" ON) + +# There are no additional detections; kreadconfig (from KDE4) and kreadconfig5 +# (from KF5) are only needed at runtime. diff --git a/libproxy/cmake/modules/config_macosx.cmk b/libproxy/cmake/modules/config_macosx.cmk new file mode 100644 index 0000000..110d4b8 --- /dev/null +++ b/libproxy/cmake/modules/config_macosx.cmk @@ -0,0 +1,10 @@ +if(APPLE) + find_library(SC_LIBRARIES SystemConfiguration) + find_library(CF_LIBRARIES CoreFoundation) + if(SC_LIBRARIES) + set(SC_FOUND 1) + endif() + if(CF_LIBRARIES) + set(CF_FOUND 1) + endif() +endif() \ No newline at end of file diff --git a/libproxy/cmake/modules/config_sysconfig.cmk b/libproxy/cmake/modules/config_sysconfig.cmk new file mode 100644 index 0000000..4dba046 --- /dev/null +++ b/libproxy/cmake/modules/config_sysconfig.cmk @@ -0,0 +1,5 @@ +if (NOT WIN32 AND NOT APPLE) + if (EXISTS "/etc/sysconfig" AND IS_DIRECTORY "/etc/sysconfig") + set(SYSCONFIG_FOUND 1) + endif() +endif() \ No newline at end of file diff --git a/libproxy/cmake/modules/network_networkmanager.cmk b/libproxy/cmake/modules/network_networkmanager.cmk new file mode 100644 index 0000000..6ef6ead --- /dev/null +++ b/libproxy/cmake/modules/network_networkmanager.cmk @@ -0,0 +1,6 @@ +if (NOT WIN32 AND NOT APPLE) + px_check_modules(NM libnm dbus-1) + if (NOT NM_FOUND) + px_check_modules(NMold NetworkManager dbus-1) + endif (NOT NM_FOUND) +endif() diff --git a/libproxy/cmake/modules/pacrunner_mozjs.cmk b/libproxy/cmake/modules/pacrunner_mozjs.cmk new file mode 100644 index 0000000..c2ae3db --- /dev/null +++ b/libproxy/cmake/modules/pacrunner_mozjs.cmk @@ -0,0 +1,22 @@ +if(WIN32) + set(MOZJS_INCLUDE_DIR "MOZJS_INCLUDE_DIR-NOTFOUND" CACHE PATH "Path to the MOZJS include directory") + set(MOZJS_LIBRARIES "MOZJS_LIBRARIES-NOTFOUND" CACHE FILEPATH "Path to the MOZJS .lib file") + if(MOZJS_LIBRARIES AND MOZJS_INCLUDE_DIR) + set(MOZJS_FOUND 1) + link_directories(MOZJS_LIBRARIES) + include_directories("${MOZJS_INCLUDE_DIR}") + endif() +elseif(NOT APPLE) + option(WITH_MOZJS "Search for MOZJS package" ON) + if (WITH_MOZJS) + pkg_search_module(MOZJS mozjs-38) + if(MOZJS_FOUND) + include_directories(${MOZJS_INCLUDE_DIRS}) + link_directories(${MOZJS_LIBRARY_DIRS}) + else() + set(MOZJS_FOUND 0) + endif() + else() + set(MOZJS_FOUND 0) + endif() +endif() diff --git a/libproxy/cmake/modules/pacrunner_natus.cmk b/libproxy/cmake/modules/pacrunner_natus.cmk new file mode 100644 index 0000000..7b14c93 --- /dev/null +++ b/libproxy/cmake/modules/pacrunner_natus.cmk @@ -0,0 +1,7 @@ +if(WIN32) + set(NATUS_FOUND 0) +elseif(APPLE) + set(NATUS_FOUND 0) +else() + px_check_modules(NATUS natus) +endif() \ No newline at end of file diff --git a/libproxy/cmake/modules/pacrunner_webkit.cmk b/libproxy/cmake/modules/pacrunner_webkit.cmk new file mode 100644 index 0000000..c5afcc2 --- /dev/null +++ b/libproxy/cmake/modules/pacrunner_webkit.cmk @@ -0,0 +1,26 @@ +if(WIN32) + set(WEBKIT_INCLUDE_DIR "WEBKIT_INCLUDE_DIR-NOTFOUND" CACHE PATH "Path to the WEBKIT include directory") + set(WEBKIT_LIBRARIES "WEBKIT_LIBRARIES-NOTFOUND" CACHE FILEPATH "Path to the WEBKIT .lib file") + if(WEBKIT_LIBRARIES AND WEBKIT_INCLUDE_DIR) + set(WEBKIT_FOUND 1) + link_directories(WEBKIT_LIBRARIES) + include_directories("${WEBKIT_INCLUDE_DIR}") + endif() +elseif(APPLE) + find_library(WEBKIT_LIBRARIES JavaScriptCore) + if(WEBKIT_LIBRARIES) + set(WEBKIT_FOUND 1) + endif() +else() + if(WITH_WEBKIT3) + px_check_modules(WEBKIT "javascriptcoregtk-4.0") + if(NOT WEBKIT_LIBRARIES) + px_check_modules(WEBKIT "javascriptcoregtk-3.0 >= 1.5.0") + if(NOT WEBKIT_LIBRARIES) + px_check_modules(WEBKIT "webkitgtk-3.0 < 1.5.0") + endif(NOT WEBKIT_LIBRARIES) + endif(NOT WEBKIT_LIBRARIES) + else(WITH_WEBKIT3) + px_check_modules(WEBKIT webkit-1.0) + endif() +endif() diff --git a/libproxy/cmake/pkgconfig.cmk b/libproxy/cmake/pkgconfig.cmk new file mode 100644 index 0000000..89bfc62 --- /dev/null +++ b/libproxy/cmake/pkgconfig.cmk @@ -0,0 +1,23 @@ +if(NOT WIN32 AND NOT APPLE) + find_package(PkgConfig) + + # Define our magical px_check_modules function + function(px_check_modules name) + if(PKG_CONFIG_EXECUTABLE) + option(WITH_${name} "Search for ${name} package" ON) + if (WITH_${name}) + pkg_check_modules(${name} ${ARGN}) + if(${${name}_FOUND}) + include_directories(${${name}_INCLUDE_DIRS}) + link_directories(${${name}_LIBRARY_DIRS}) + else() + set(${name}_FOUND 0 PARENT_SCOPE) + endif() + else() + set(${name}_FOUND 0 PARENT_SCOPE) + endif() + endif() + endfunction(px_check_modules) +endif() + + diff --git a/libproxy/cmake/pxmodule.cmk b/libproxy/cmake/pxmodule.cmk new file mode 100644 index 0000000..bbbd989 --- /dev/null +++ b/libproxy/cmake/pxmodule.cmk @@ -0,0 +1,30 @@ +# Module function +function(px_module name build builtin) + if(IS_ABSOLUTE "${LIBEXEC_INSTALL_DIR}") + set(LIBEXECDIR "${LIBEXEC_INSTALL_DIR}") + else () + set(LIBEXECDIR "${CMAKE_INSTALL_PREFIX}/${LIBEXEC_INSTALL_DIR}") + endif() + if(build) + if(builtin) + set(built "*") + set_property(SOURCE modules/${name}.cpp PROPERTY COMPILE_DEFINITIONS LIBEXECDIR="${LIBEXECDIR}";MM_MODULE_BUILTIN=${name}) + set(LIBPROXY_SOURCES ${LIBPROXY_SOURCES} modules/${name}.cpp PARENT_SCOPE) + set(BUILTIN_MODULES "${BUILTIN_MODULES} X\(${name}\)" PARENT_SCOPE) + if(${ARGC} GREATER 3) + set(LIBPROXY_LIBRARIES ${LIBPROXY_LIBRARIES} ${ARGN} PARENT_SCOPE) + endif() + else() + set(built "m") + set_property(SOURCE modules/${name}.cpp PROPERTY COMPILE_DEFINITIONS LIBEXECDIR="${LIBEXECDIR}") + add_library(${name} MODULE modules/${name}.cpp) + target_link_libraries(${name} libproxy) + set_target_properties(${name} PROPERTIES PREFIX "") + install(TARGETS ${name} LIBRARY DESTINATION ${MODULE_INSTALL_DIR}) + if(${ARGC} GREATER 3) + target_link_libraries(${name} ${ARGN}) + endif() + endif() + endif() + message("\t${built}\t${name}") +endfunction(px_module) diff --git a/libproxy/config.hpp b/libproxy/config.hpp new file mode 100644 index 0000000..4efb08d --- /dev/null +++ b/libproxy/config.hpp @@ -0,0 +1,52 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2010 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef CONFIG_HPP_ +#define CONFIG_HPP_ + +#ifdef WIN32 +#pragma warning(disable: 4251) +#pragma warning(disable: 4290) +#pragma warning(disable: 4275) +#define DLL_PUBLIC __declspec(dllexport) +#define PATHSEP '\\' +#define MODULEEXT "dll" +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0501 +#endif +#include +#include +#include +typedef unsigned __int64 uint64_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int8 uint8_t; +typedef unsigned short int sa_family_t; +#else +#define DLL_PUBLIC __attribute__ ((visibility("default"))) +#define PATHSEP '/' +#define MODULEEXT "so" +#include +#include +#include +#include +#include +#endif + +#endif /* CONFIG_HPP_ */ diff --git a/libproxy/extension_config.cpp b/libproxy/extension_config.cpp new file mode 100644 index 0000000..075b91a --- /dev/null +++ b/libproxy/extension_config.cpp @@ -0,0 +1,41 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "extension_config.hpp" +using namespace libproxy; + +string config_extension::get_ignore(const url&) { + return ""; +} + +bool config_extension::set_creds(const url&, const string&, const string&) { + return false; +} + +bool config_extension::operator<(const base_extension&) const { + return true; +} + +bool config_extension::get_valid() { + return this->valid; +} + +void config_extension::set_valid(bool valid) { + this->valid = valid; +} diff --git a/libproxy/extension_config.hpp b/libproxy/extension_config.hpp new file mode 100644 index 0000000..79f1624 --- /dev/null +++ b/libproxy/extension_config.hpp @@ -0,0 +1,51 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef EXTENSION_CONFIG_HPP_ +#define EXTENSION_CONFIG_HPP_ + +#include +#include "url.hpp" + +namespace libproxy { +using namespace std; +using namespace libmodman; + +// Config module +class DLL_PUBLIC config_extension : public extension { +public: + // Abstract methods + virtual vector get_config(const url &dst) throw (runtime_error)=0; + + // Virtual methods + virtual string get_ignore(const url &dst); + virtual bool set_creds(const url &proxy, const string &username, const string &password); + + // Final methods + bool get_valid(); + void set_valid(bool valid); + virtual bool operator<(const base_extension&) const; + +private: + bool valid; +}; + +} + +#endif /* EXTENSION_CONFIG_HPP_ */ diff --git a/libproxy/extension_ignore.hpp b/libproxy/extension_ignore.hpp new file mode 100644 index 0000000..63845fe --- /dev/null +++ b/libproxy/extension_ignore.hpp @@ -0,0 +1,38 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef EXTENSION_IGNORE_HPP_ +#define EXTENSION_IGNORE_HPP_ + +#include + +#include "url.hpp" + +namespace libproxy { +using namespace std; +using namespace libmodman; + +class DLL_PUBLIC ignore_extension : public extension { +public: + virtual bool ignore(url& dst, const string &ignorestr)=0; +}; + +} + +#endif /* EXTENSION_IGNORE_HPP_ */ diff --git a/libproxy/extension_network.hpp b/libproxy/extension_network.hpp new file mode 100644 index 0000000..1a8fc46 --- /dev/null +++ b/libproxy/extension_network.hpp @@ -0,0 +1,37 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef EXTENSION_NETWORK_HPP_ +#define EXTENSION_NETWORK_HPP_ + +#include +#include "config.hpp" + +namespace libproxy { +using namespace libmodman; + +// Network module +class DLL_PUBLIC network_extension : public extension { +public: + virtual bool changed()=0; +}; + +} + +#endif /* EXTENSION_NETWORK_HPP_ */ diff --git a/libproxy/extension_pacrunner.cpp b/libproxy/extension_pacrunner.cpp new file mode 100644 index 0000000..c53c4f0 --- /dev/null +++ b/libproxy/extension_pacrunner.cpp @@ -0,0 +1,41 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "extension_pacrunner.hpp" +using namespace libproxy; + +pacrunner::pacrunner(string, const url&) {} + +pacrunner_extension::pacrunner_extension() { + this->pr = NULL; +} + +pacrunner_extension::~pacrunner_extension() { + if (this->pr) delete this->pr; +} + +pacrunner* pacrunner_extension::get(string pac, const url& pacurl) throw (bad_alloc) { + if (this->pr) { + if (this->last == pac) + return this->pr; + delete this->pr; + } + + return this->pr = this->create(pac, pacurl); +} diff --git a/libproxy/extension_pacrunner.hpp b/libproxy/extension_pacrunner.hpp new file mode 100644 index 0000000..de7abb5 --- /dev/null +++ b/libproxy/extension_pacrunner.hpp @@ -0,0 +1,67 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef EXTENSION_PACRUNNER_HPP_ +#define EXTENSION_PACRUNNER_HPP_ + +#include +#include "url.hpp" + +#define PX_PACRUNNER_MODULE_EZ(name, symb, smod) \ + class name ## _pacrunner_extension : public pacrunner_extension { \ + protected: \ + virtual pacrunner* create(string pac, const url& pacurl) throw (bad_alloc) { \ + return new name ## _pacrunner(pac, pacurl); \ + } \ + }; \ + MM_MODULE_INIT_EZ(name ## _pacrunner_extension, true, symb, smod) + +namespace libproxy { +using namespace std; +using namespace libmodman; + +// PACRunner module +class DLL_PUBLIC pacrunner { +public: + pacrunner(string pac, const url& pacurl); + virtual ~pacrunner() {}; + virtual string run(const url& url) throw (bad_alloc)=0; +}; + +class DLL_PUBLIC pacrunner_extension : public extension { +public: + // Virtual methods + virtual pacrunner* get(string pac, const url& pacurl) throw (bad_alloc); + virtual ~pacrunner_extension(); + + // Final methods + pacrunner_extension(); + +protected: + // Abstract methods + virtual pacrunner* create(string pac, const url& pacurl) throw (bad_alloc)=0; + +private: + pacrunner* pr; + string last; +}; + +} + +#endif /* EXTENSION_PACRUNNER_HPP_ */ diff --git a/libproxy/extension_wpad.cpp b/libproxy/extension_wpad.cpp new file mode 100644 index 0000000..1f4d9b0 --- /dev/null +++ b/libproxy/extension_wpad.cpp @@ -0,0 +1,23 @@ +#include "extension_wpad.hpp" +using namespace libproxy; + +#include + +static const char *DEFAULT_WPAD_ORDER[] = { + "dhcp", + "slp", + "dns_srv", + "dns_txt", + "dns_alias", + NULL +}; + +bool wpad_extension::operator<(const wpad_extension& other) const { + for (int i=0 ; DEFAULT_WPAD_ORDER[i] ; i++) { + if (strstr(other.get_base_type(), DEFAULT_WPAD_ORDER[i])) + break; + if (strstr(this->get_base_type(), DEFAULT_WPAD_ORDER[i])) + return true; + } + return false; +} diff --git a/libproxy/extension_wpad.hpp b/libproxy/extension_wpad.hpp new file mode 100644 index 0000000..6c2f52d --- /dev/null +++ b/libproxy/extension_wpad.hpp @@ -0,0 +1,45 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef EXTENSION_WPAD_HPP_ +#define EXTENSION_WPAD_HPP_ + +#include +#include "url.hpp" + +namespace libproxy { +using namespace std; +using namespace libmodman; + +// WPAD module +class DLL_PUBLIC wpad_extension : public extension { +public: + // Abstract methods + virtual bool found()=0; + virtual url* next(char** pac)=0; + virtual void rewind()=0; + + // Virtual methods + virtual bool operator<(const wpad_extension& module) const; + using extension::operator<; +}; + +} + +#endif /* EXTENSION_WPAD_HPP_ */ diff --git a/libproxy/libproxy-1.0.pc.in b/libproxy/libproxy-1.0.pc.in new file mode 100644 index 0000000..bfc031c --- /dev/null +++ b/libproxy/libproxy-1.0.pc.in @@ -0,0 +1,10 @@ +prefix=@PKGCONFIG_PREFIX@ +libdir=@PKGCONFIG_LIBDIR@ +includedir=@PKGCONFIG_INCLUDEDIR@ + +Name: libproxy-1.0 +Description: Proxy Configuration Library +Version: @PROJECT_VERSION@ +Libs: -L${libdir} -lproxy +Libs.private: -lpthread -lm +Cflags: -I${includedir} diff --git a/libproxy/modules/config_envvar.cpp b/libproxy/modules/config_envvar.cpp new file mode 100644 index 0000000..37713c7 --- /dev/null +++ b/libproxy/modules/config_envvar.cpp @@ -0,0 +1,68 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include + +#include "../extension_config.hpp" +using namespace libproxy; + +class envvar_config_extension : public config_extension { +public: + vector get_config(const url &dst) throw (runtime_error) { + const char *proxy = NULL; + vector response; + + // If the URL is an ftp url, try to read the ftp proxy + if (dst.get_scheme() == "ftp") { + if (!(proxy = getenv("ftp_proxy"))) + proxy = getenv("FTP_PROXY"); + } + + // If the URL is an https url, try to read the https proxy + if (dst.get_scheme() == "https") { + if (!(proxy = getenv("https_proxy"))) + proxy = getenv("HTTPS_PROXY"); + } + + // If the URL is not ftp or no ftp_proxy was found, get the http_proxy + if (!proxy) { + if (!(proxy = getenv("http_proxy"))) + proxy = getenv("HTTP_PROXY"); + } + + if (!proxy) + throw runtime_error("Unable to read configuration"); + + response.push_back(url(proxy)); + return response; + } + + string get_ignore(const url&) { + char *ignore = getenv("no_proxy"); + ignore = ignore ? ignore : getenv("NO_PROXY"); + return string(ignore ? ignore : ""); + } + + // Make sure that envvar is pushed to the back behind all other config extensions + virtual bool operator<(const base_extension&) const { + return false; + } +}; + +MM_MODULE_INIT_EZ(envvar_config_extension, true, NULL, NULL); diff --git a/libproxy/modules/config_gnome.cpp b/libproxy/modules/config_gnome.cpp new file mode 100644 index 0000000..e6cda95 --- /dev/null +++ b/libproxy/modules/config_gnome.cpp @@ -0,0 +1,307 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include // For fileno(), fread(), pclose(), popen(), sscanf() +#include // For select() +#include // For fcntl() +#include // For errno stuff +#include // For stat() +#include // For stat() +#include // For pipe(), close(), vfork(), dup(), execl(), _exit() +#include // For kill() + +#include "../extension_config.hpp" +using namespace libproxy; + +#define BUFFERSIZE 10240 + +#define PROXY_MODE "/system/proxy/mode" +#define PROXY_USE_AUTHENTICATION "/system/http_proxy/use_authentication" +#define PROXY_AUTH_PASSWORD "/system/http_proxy/authentication_password" +#define PROXY_AUTH_USER "/system/http_proxy/authentication_user" +#define PROXY_AUTOCONFIG_URL "/system/proxy/autoconfig_url" +#define PROXY_IGNORE_HOSTS "/system/http_proxy/ignore_hosts" +#define PROXY_HTTP_HOST "/system/http_proxy/host" +#define PROXY_HTTP_PORT "/system/http_proxy/port" +#define PROXY_FTP_HOST "/system/proxy/ftp_host" +#define PROXY_FTP_PORT "/system/proxy/ftp_port" +#define PROXY_SECURE_HOST "/system/proxy/secure_host" +#define PROXY_SECURE_PORT "/system/proxy/secure_port" +#define PROXY_SOCKS_HOST "/system/proxy/socks_host" +#define PROXY_SOCKS_PORT "/system/proxy/socks_port" +#define PROXY_SAME_FOR_ALL "/system/http_proxy/use_same_proxy" + +static const char *all_keys[] = { + PROXY_MODE, + PROXY_USE_AUTHENTICATION, + PROXY_AUTH_PASSWORD, + PROXY_AUTH_USER, + PROXY_AUTOCONFIG_URL, + PROXY_IGNORE_HOSTS, + PROXY_HTTP_HOST, + PROXY_HTTP_PORT, + PROXY_FTP_HOST, + PROXY_FTP_PORT, + PROXY_SECURE_HOST, + PROXY_SECURE_PORT, + PROXY_SOCKS_HOST, + PROXY_SOCKS_PORT, + PROXY_SAME_FOR_ALL, + NULL +}; + +static int popen2(const char *program, FILE** read, FILE** write, pid_t* pid) { + if (!read || !write || !pid || !program || !*program) + return EINVAL; + *read = NULL; + *write = NULL; + *pid = 0; + + // Open the pipes + int rpipe[2]; + int wpipe[2]; + if (pipe(rpipe) < 0) + return errno; + if (pipe(wpipe) < 0) { + close(rpipe[0]); + close(rpipe[1]); + return errno; + } + + switch (*pid = vfork()) { + case -1: // Error + close(rpipe[0]); + close(rpipe[1]); + close(wpipe[0]); + close(wpipe[1]); + return errno; + + case 0: // Child + close(STDIN_FILENO); // Close stdin + close(STDOUT_FILENO); // Close stdout + + // Dup the read end of the write pipe to stdin + // Dup the write end of the read pipe to stdout + if (dup2(wpipe[0], STDIN_FILENO) != STDIN_FILENO) _exit(1); + if (dup2(rpipe[1], STDOUT_FILENO) != STDOUT_FILENO) _exit(2); + + // Close unneeded fds + for (int i = 3; i < sysconf(_SC_OPEN_MAX); i++) + close(i); + + // Exec + execl("/bin/sh", "sh", "-c", program, (char*) NULL); + _exit(127); // Whatever we do, don't return + + default: // Parent + close(rpipe[1]); + close(wpipe[0]); + *read = fdopen(rpipe[0], "r"); + *write = fdopen(wpipe[1], "w"); + if (*read == NULL || *write == NULL) { + if (*read != NULL) fclose(*read); + if (*write != NULL) fclose(*write); + return errno; + } + return 0; + } +} + +static inline uint16_t get_port(const string &port) +{ + uint16_t retval; + + if (sscanf(port.c_str(), "%hu", &retval) != 1) + retval = 0; + + return retval; +} + +void store_response(const string &type, + const string &host, + const string &port, + bool auth, + const string &username, + const string &password, + vector &response) { + if (host != "" && get_port(port) != 0) { + string tmp = type + "://"; + if (auth) + tmp += username + ":" + password + "@"; + tmp += host + ":" + port; + response.push_back(url(tmp)); + } +} + +class gnome_config_extension : public config_extension { +public: + gnome_config_extension() { + // Build the command + int count; + struct stat st; + string cmd = LIBEXECDIR "/pxgconf"; + const char *pxgconf = getenv("PX_GCONF"); + + if (pxgconf) + cmd = string (pxgconf); + + if (stat(cmd.c_str(), &st)) + throw runtime_error ("Unable to open gconf helper!"); + + for (count=0 ; all_keys[count] ; count++) + cmd += string(" ", 1) + all_keys[count]; + + // Get our pipes + if (popen2(cmd.c_str(), &this->read, &this->write, &this->pid) != 0) + throw runtime_error("Unable to run gconf helper!"); + + // Read in our initial data + this->read_data(count); + + // Set the read pipe to non-blocking + if (fcntl(fileno(this->read), F_SETFL, O_NONBLOCK) == -1) { + fclose(this->read); + fclose(this->write); + kill(this->pid, SIGTERM); + throw runtime_error("Unable to set pipe to non-blocking!"); + } + } + + ~gnome_config_extension() { + fclose(this->read); + fclose(this->write); + kill(this->pid, SIGTERM); + } + + vector get_config(const url &dest) throw (runtime_error) { + // Check for changes in the config + fd_set rfds; + struct timeval timeout = { 0, 0 }; + vector response; + + FD_ZERO(&rfds); + FD_SET(fileno(this->read), &rfds); + if (select(fileno(this->read)+1, &rfds, NULL, NULL, &timeout) > 0) + this->read_data(); + + // Mode is wpad:// or pac+http://... + if (this->data[PROXY_MODE] == "auto") { + string pac = this->data[PROXY_AUTOCONFIG_URL]; + response.push_back(url::is_valid(pac) ? url(string("pac+") + pac) : url("wpad://")); + return response; + } + + // Mode is http://... or socks://... + else if (this->data[PROXY_MODE] == "manual") { + bool auth = this->data[PROXY_USE_AUTHENTICATION] == "true"; + string username = url::encode(this->data[PROXY_AUTH_USER], URL_ALLOWED_IN_USERINFO_ELEMENT); + string password = url::encode(this->data[PROXY_AUTH_PASSWORD], URL_ALLOWED_IN_USERINFO_ELEMENT); + + // Get the per-scheme proxy settings + if (dest.get_scheme() == "http") + store_response("http", this->data[PROXY_HTTP_HOST], + this->data[PROXY_HTTP_PORT], auth, username, password, response); + else if (dest.get_scheme() == "https") + // It is expected that the configured server is an + // HTTP server that support CONNECT method. + store_response("http", this->data[PROXY_SECURE_HOST], + this->data[PROXY_SECURE_PORT], auth, username, password, response); + else if (dest.get_scheme() == "ftp") + // It is expected that the configured server is an + // HTTP server that handles proxying FTP URLs + // (e.g. request with header "Host: ftp://ftp.host.org") + store_response("http", this->data[PROXY_FTP_HOST], + this->data[PROXY_FTP_PORT], auth, username, password, response); + + store_response("socks", this->data[PROXY_SOCKS_HOST], + this->data[PROXY_SOCKS_PORT], auth, username, password, response); + + // In case nothing matched, try HTTP Connect and fallback to direct. + // If there is not secure HTTP proxy, this will only add direct:// to + // the response + if (response.size() == 0 && dest.get_scheme() != "http") { + store_response("http", this->data[PROXY_SECURE_HOST], + this->data[PROXY_SECURE_PORT], auth, username, password, response); + response.push_back(url("direct://")); + } + } + + return response; + } + + string get_ignore(const url&) { + return this->data[PROXY_IGNORE_HOSTS]; + } + + virtual bool set_creds(url /*proxy*/, string username, string password) { + string auth = PROXY_USE_AUTHENTICATION "\ttrue\n"; + string user = string(PROXY_AUTH_USER "\t") + username + "\n"; + string pass = string(PROXY_AUTH_PASSWORD "\t") + password + "\n"; + + return (fwrite(auth.c_str(), 1, auth.size(), this->write) == auth.size() && + fwrite(user.c_str(), 1, user.size(), this->write) == user.size() && + fwrite(pass.c_str(), 1, pass.size(), this->write) == pass.size()); + } + +private: + FILE* read; + FILE* write; + pid_t pid; + map data; + + bool read_data(int num=-1) { + if (num == 0) return true; + if (!this->read) return false; // We need the pipe to be open + + for (char l[BUFFERSIZE] ; num != 0 && fgets(l, BUFFERSIZE, this->read) != NULL ; ) { + string line = l; + line = line.substr(0, line.rfind('\n')); + string key = line.substr(0, line.find("\t")); + string val = line.substr(line.find("\t")+1); + this->data[key] = val; + if (num > 0) num--; + } + + return (num <= 0); + } +}; + +static base_extension** gnome_config_extension_init() { + base_extension** retval = new base_extension*[2]; + retval[1] = NULL; + try { + retval[0] = new gnome_config_extension(); + return retval; + } + catch (runtime_error) { + delete[] retval; + return NULL; + } +} + +static bool gnome_config_extension_test() { + return (getenv("GNOME_DESKTOP_SESSION_ID") + || (getenv("DESKTOP_SESSION") + && string(getenv("DESKTOP_SESSION")) == "gnome")); +} + +MM_MODULE_INIT(gnome_config_extension, + gnome_config_extension_init, + gnome_config_extension_test, + NULL, NULL); diff --git a/libproxy/modules/config_gnome3.cpp b/libproxy/modules/config_gnome3.cpp new file mode 100644 index 0000000..666d639 --- /dev/null +++ b/libproxy/modules/config_gnome3.cpp @@ -0,0 +1,301 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include // For fileno(), fread(), pclose(), popen(), sscanf() +#include // For select() +#include // For fcntl() +#include // For errno stuff +#include // For stat() +#include // For stat() +#include // For pipe(), close(), vfork(), dup(), execl(), _exit() +#include // For waitpid() +#include // For kill() + +#include "../extension_config.hpp" +using namespace libproxy; + +#define BUFFERSIZE 10240 + +#define PROXY_MODE "org.gnome.system.proxy/mode" +#define PROXY_USE_AUTHENTICATION "org.gnome.system.proxy.http/use-authentication" +#define PROXY_AUTH_PASSWORD "org.gnome.system.proxy.http/authentication-password" +#define PROXY_AUTH_USER "org.gnome.system.proxy.http/authentication-user" +#define PROXY_AUTOCONFIG_URL "org.gnome.system.proxy/autoconfig-url" +#define PROXY_IGNORE_HOSTS "org.gnome.system.proxy/ignore-hosts" +#define PROXY_HTTP_HOST "org.gnome.system.proxy.http/host" +#define PROXY_HTTP_PORT "org.gnome.system.proxy.http/port" +#define PROXY_FTP_HOST "org.gnome.system.proxy.ftp/host" +#define PROXY_FTP_PORT "org.gnome.system.proxy.ftp/port" +#define PROXY_SECURE_HOST "org.gnome.system.proxy.https/host" +#define PROXY_SECURE_PORT "org.gnome.system.proxy.https/port" +#define PROXY_SOCKS_HOST "org.gnome.system.proxy.socks/host" +#define PROXY_SOCKS_PORT "org.gnome.system.proxy.socks/port" +#define PROXY_SAME_FOR_ALL "org.gnome.system.proxy/use-same-proxy" + +static const char *all_keys[] = { + "org.gnome.system.proxy", + "org.gnome.system.proxy.http", + "org.gnome.system.proxy.https", + "org.gnome.system.proxy.ftp", + "org.gnome.system.proxy.socks", + NULL +}; + +static int popen2(const char *program, FILE** read, FILE** write, pid_t* pid) { + if (!read || !write || !pid || !program || !*program) + return EINVAL; + *read = NULL; + *write = NULL; + *pid = 0; + + // Open the pipes + int rpipe[2]; + int wpipe[2]; + if (pipe(rpipe) < 0) + return errno; + if (pipe(wpipe) < 0) { + close(rpipe[0]); + close(rpipe[1]); + return errno; + } + + switch (*pid = vfork()) { + case -1: // Error + close(rpipe[0]); + close(rpipe[1]); + close(wpipe[0]); + close(wpipe[1]); + return errno; + + case 0: // Child + close(STDIN_FILENO); // Close stdin + close(STDOUT_FILENO); // Close stdout + + // Dup the read end of the write pipe to stdin + // Dup the write end of the read pipe to stdout + if (dup2(wpipe[0], STDIN_FILENO) != STDIN_FILENO) _exit(1); + if (dup2(rpipe[1], STDOUT_FILENO) != STDOUT_FILENO) _exit(2); + + // Close unneeded fds + for (int i = 3; i < sysconf(_SC_OPEN_MAX); i++) + close(i); + + // Exec + execl("/bin/sh", "sh", "-c", program, (char*) NULL); + _exit(127); // Whatever we do, don't return + + default: // Parent + close(rpipe[1]); + close(wpipe[0]); + *read = fdopen(rpipe[0], "r"); + *write = fdopen(wpipe[1], "w"); + if (*read == NULL || *write == NULL) { + if (*read != NULL) fclose(*read); + if (*write != NULL) fclose(*write); + return errno; + } + return 0; + } +} + +static inline uint16_t get_port(const string &port) +{ + uint16_t retval; + + if (sscanf(port.c_str(), "%hu", &retval) != 1) + retval = 0; + + return retval; +} + +class gnome_config_extension : public config_extension { +public: + gnome_config_extension() { + // Build the command + int count; + struct stat st; + string cmd = LIBEXECDIR "/pxgsettings"; + const char *pxgconf = getenv("PX_GSETTINGS"); + + if (pxgconf) + cmd = string (pxgconf); + + if (stat(cmd.c_str(), &st)) + throw runtime_error ("Unable to open gsettings helper!"); + + for (count=0 ; all_keys[count] ; count++) + cmd += string(" ", 1) + all_keys[count]; + + // Get our pipes + if (popen2(cmd.c_str(), &this->read, &this->write, &this->pid) != 0) + throw runtime_error("Unable to run gconf helper!"); + + // Read in our initial data + this->read_data(count); + + // Set the read pipe to non-blocking + if (fcntl(fileno(this->read), F_SETFL, O_NONBLOCK) == -1) { + fclose(this->read); + fclose(this->write); + kill(this->pid, SIGTERM); + throw runtime_error("Unable to set pipe to non-blocking!"); + } + } + + ~gnome_config_extension() { + fclose(this->read); + fclose(this->write); + kill(this->pid, SIGTERM); + waitpid(this->pid, NULL, 0); + } + + void store_response(const string &type, + const string &host, + const string &port, + bool auth, + const string &username, + const string &password, + vector &response) { + if (host != "" && get_port(port) != 0) { + string tmp = type + "://"; + if (auth) + tmp += username + ":" + password + "@"; + tmp += host + ":" + port; + response.push_back(url(tmp)); + } + } + + vector get_config(const url &dest) throw (runtime_error) { + // Check for changes in the config + fd_set rfds; + struct timeval timeout = { 0, 0 }; + vector response; + + FD_ZERO(&rfds); + FD_SET(fileno(this->read), &rfds); + if (select(fileno(this->read)+1, &rfds, NULL, NULL, &timeout) > 0) + this->read_data(); + + // Mode is wpad:// or pac+http://... + if (this->data[PROXY_MODE] == "auto") { + string pac = this->data[PROXY_AUTOCONFIG_URL]; + response.push_back(url::is_valid(pac) ? url(string("pac+") + pac) : url("wpad://")); + return response; + } + + // Mode is http://... or socks://... + else if (this->data[PROXY_MODE] == "manual") { + bool auth = this->data[PROXY_USE_AUTHENTICATION] == "true"; + string username = url::encode(this->data[PROXY_AUTH_USER], URL_ALLOWED_IN_USERINFO_ELEMENT); + string password = url::encode(this->data[PROXY_AUTH_PASSWORD], URL_ALLOWED_IN_USERINFO_ELEMENT); + + // Get the per-scheme proxy settings + if (dest.get_scheme() == "http") + store_response("http", this->data[PROXY_HTTP_HOST], + this->data[PROXY_HTTP_PORT], auth, username, password, response); + else if (dest.get_scheme() == "https") + // It is expected that the configured server is an + // HTTP server that support CONNECT method. + store_response("http", this->data[PROXY_SECURE_HOST], + this->data[PROXY_SECURE_PORT], auth, username, password, response); + else if (dest.get_scheme() == "ftp") + // It is expected that the configured server is an + // HTTP server that handles proxying FTP URLs + // (e.g. request with header "Host: ftp://ftp.host.org") + store_response("http", this->data[PROXY_FTP_HOST], + this->data[PROXY_FTP_PORT], auth, username, password, response); + + store_response("socks", this->data[PROXY_SOCKS_HOST], + this->data[PROXY_SOCKS_PORT], auth, username, password, response); + + // In case nothing matched, try HTTP Connect and fallback to direct. + // If there is not secure HTTP proxy, this will only add direct:// to + // the response + if (response.size() == 0 && dest.get_scheme() != "http") { + store_response("http", this->data[PROXY_SECURE_HOST], + this->data[PROXY_SECURE_PORT], auth, username, password, response); + response.push_back(url("direct://")); + } + } + + return response; + } + + string get_ignore(const url&) { + return this->data[PROXY_IGNORE_HOSTS]; + } + + bool set_creds(url /*proxy*/, string username, string password) { + string auth = PROXY_USE_AUTHENTICATION "\ttrue\n"; + string user = string(PROXY_AUTH_USER "\t") + username + "\n"; + string pass = string(PROXY_AUTH_PASSWORD "\t") + password + "\n"; + + return (fwrite(auth.c_str(), 1, auth.size(), this->write) == auth.size() && + fwrite(user.c_str(), 1, user.size(), this->write) == user.size() && + fwrite(pass.c_str(), 1, pass.size(), this->write) == pass.size()); + } + +private: + FILE* read; + FILE* write; + pid_t pid; + map data; + + bool read_data(int num=-1) { + if (num == 0) return true; + if (!this->read) return false; // We need the pipe to be open + + for (char l[BUFFERSIZE] ; num != 0 && fgets(l, BUFFERSIZE, this->read) != NULL ; ) { + string line = l; + line = line.substr(0, line.rfind('\n')); + string key = line.substr(0, line.find("\t")); + string val = line.substr(line.find("\t")+1); + this->data[key] = val; + if (num > 0) num--; + } + + return (num <= 0); + } +}; + +static base_extension** gnome_config_extension_init() { + base_extension** retval = new base_extension*[2]; + retval[1] = NULL; + try { + retval[0] = new gnome_config_extension(); + return retval; + } + catch (runtime_error) { + delete[] retval; + return NULL; + } +} + +static bool gnome_config_extension_test() { + return (getenv("GNOME_DESKTOP_SESSION_ID") + || (getenv("DESKTOP_SESSION") + && string(getenv("DESKTOP_SESSION")) == "gnome") + || (getenv("DESKTOP_SESSION") + && string(getenv("DESKTOP_SESSION")) == "mate")); +} + +MM_MODULE_INIT(gnome_config_extension, + gnome_config_extension_init, + gnome_config_extension_test, + NULL, NULL); diff --git a/libproxy/modules/config_kde.cpp b/libproxy/modules/config_kde.cpp new file mode 100644 index 0000000..b9bd241 --- /dev/null +++ b/libproxy/modules/config_kde.cpp @@ -0,0 +1,229 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * Copyright (C) 2016 Fabian Vogt + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include +#include + +#include +#include +#include +#include + +#include "../extension_config.hpp" +using namespace libproxy; + +class kde_config_extension : public config_extension { +public: + kde_config_extension() + : cache_time(0) + { + try { + // Try the KF5 one first + command = "kreadconfig5"; + command_output("kreadconfig5 --key nonexistant"); + + try { + parse_dir_list(command_output("qtpaths --paths GenericConfigLocation")); + } + catch(...) {} + + return; // Worked + } + catch(...) {} + + try { + // The KDE4 one next + command = "kreadconfig"; + command_output(command); + + try { + parse_dir_list(command_output("kde4-config --path config")); + } + catch(...) {} + + return; // Worked + } + catch(...) {} + + // Neither worked, so throw in get_config + command = ""; + } + + vector get_config(const url &dst) throw (runtime_error) { + // See constructor + if(command.empty()) + throw runtime_error("Unable to read configuration"); + + vector response; + + string tmp, proxyType = kde_config_val("ProxyType", "-1"); + + // Just switch on the first byte, either a digit, '-' ("-1") or '\0' + switch(proxyType.c_str()[0]) + { + case '1': + tmp = kde_config_val(dst.get_scheme() + "Proxy", ""); + if(tmp.empty()) { + tmp = kde_config_val("httpProxy", ""); + if(tmp.empty()) { + tmp = kde_config_val("socksProxy", ""); + if(tmp.empty()) + tmp = "direct://"; + } + } + + // KDE uses "http://127.0.0.1 8080" instead of "http://127.0.0.1:8080" + replace(tmp.begin(), tmp.end(), ' ', ':'); + + response.push_back(url(tmp)); + break; + + case '2': + tmp = "pac+" + kde_config_val("Proxy Config Script", ""); + if (url::is_valid(tmp)) + { + response.push_back(url(tmp)); + break; + } + // else fallthrough + + case '3': + response.push_back(url(string("wpad://"))); + break; + + case '4': + throw runtime_error("User config_envvar"); // We'll bypass this config plugin and let the envvar plugin wor + + case '0': + default: // Not set or unknown/illegal + response.push_back(url("direct://")); + break; + } + + return response; + } + + string get_ignore(const url&) { + // See constructor + if(command.empty()) + return ""; + + string proxyType = kde_config_val("ProxyType", "-1"); + if(proxyType.c_str()[0] != '1') + return ""; // Not manual config + + string prefix = kde_config_val("ReversedException", "false") != "false" ? "-" : ""; + return prefix + kde_config_val("NoProxyFor", ""); // Already in the right format + } + +private: + string command_output(const string &cmdline) throw (runtime_error) { + // Capture stderr as well + const string command = "(" + cmdline + ")2>&1"; + FILE *pipe = popen(command.c_str(), "r"); + if (!pipe) + throw runtime_error("Unable to run command"); + + char buffer[128]; + string result = ""; + while (!feof(pipe)) { + if (fgets(buffer, 128, pipe) != NULL) + result += buffer; // TODO: If this throws bad_alloc, pipe is leaked + } + + if(pclose(pipe) != 0) + throw runtime_error("Command failed"); + + // Trim newlines and whitespace at end + result.erase(result.begin() + (result.find_last_not_of(" \n\t")+1), result.end()); + + return result; + } + + // Neither key nor def must contain ' + const string &kde_config_val(const string &key, const string &def) throw (runtime_error) { + if (cache_needs_refresh()) + cache.clear(); + else { + // Already in cache? + map::iterator it = cache.find(key); + if(it != cache.end()) + return it->second; + } + + // Although all values are specified internally and/or validated, + // checking is better than trusting. + if(key.find('\'') != string::npos || def.find('\'') != string::npos) + return def; + + // Add result to cache and return it + return cache[key] = command_output( + command + " --file kioslaverc --group 'Proxy Settings' --key '" + key + "' --default '" + def + "'"); + } + + // Used for cache invalidation + struct configfile { + string path; + time_t mtime; // 0 means it doesn't exist + }; + + // Parses output of qtpaths/kde4-config to fill config_locs + void parse_dir_list(const string &dirs) { + string config_path; + stringstream config_paths_stream(dirs); + + // Try each of the listed folders, seperated by ':' + while (getline(config_paths_stream, config_path, ':')) { + configfile config_loc; config_loc.path = config_path + "/kioslaverc"; + config_locs.push_back(config_loc); + } + } + + // If any of the locations in config_locs changed (different mtime), + // update config_locs and return true. + bool cache_needs_refresh() { + // Play safe here, if we can't determine the location, + // don't cache at all. + bool needs_refresh = config_locs.empty(); + struct stat config_info; + + for (unsigned int i = 0; i < config_locs.size(); ++i) { + configfile &config = config_locs[i]; + time_t current_mtime = stat(config.path.c_str(), &config_info) == 0 ? config_info.st_mtime : 0; + if (config.mtime != current_mtime) { + config.mtime = current_mtime; + needs_refresh = true; + } + } + + return needs_refresh; + } + + // Whether to use kreadconfig or kreadconfig5 + string command; + // When the cache was flushed last + time_t cache_time; + // Cache for config values + map cache; + // State of the config files at the time of the last cache flush + vector config_locs; +}; + +MM_MODULE_INIT_EZ(kde_config_extension, getenv("KDE_FULL_SESSION"), NULL, NULL); diff --git a/libproxy/modules/config_macosx.cpp b/libproxy/modules/config_macosx.cpp new file mode 100644 index 0000000..38e4065 --- /dev/null +++ b/libproxy/modules/config_macosx.cpp @@ -0,0 +1,171 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include + +#include "../extension_config.hpp" +using namespace libproxy; + +#include + +class str : public string { +public: + str(CFStringRef s) : string() { + if (!s) return; + const char* tmp = CFStringGetCStringPtr(s, CFStringGetFastestEncoding(s)); + *this += tmp ? tmp : ""; + } + + str(CFArrayRef a) : string() { + if (!a) return; + for (CFIndex i=0 ; i < CFArrayGetCount(a) ; i++) { + CFStringRef s = (CFStringRef) CFArrayGetValueAtIndex(a, i); + *this += str(s); + if (i+1 < CFArrayGetCount(a)) + *this += ","; + } + } +}; + +template +static T getobj(CFDictionaryRef settings, string key) { + if (!settings) return NULL; + CFStringRef k = CFStringCreateWithCString(NULL, key.c_str(), kCFStringEncodingMacRoman); + if (!k) return NULL; + T retval = (T) CFDictionaryGetValue(settings, k); + CFRelease(k); + return retval; +} + +static bool getint(CFDictionaryRef settings, string key, int64_t& answer) { + CFNumberRef n = getobj(settings, key); + if (!n) return false; + if (!CFNumberGetValue(n, kCFNumberSInt64Type, &answer)) + return false; + return true; +} + +static bool getbool(CFDictionaryRef settings, string key, bool dflt=false) { + int64_t i; + if (!getint(settings, key, i)) return dflt; + return i != 0; +} + +static bool protocol_url(CFDictionaryRef settings, string protocol, string& config) { + int64_t port; + string host; + + // Check ProtocolEnabled + if (!getbool(settings, protocol + "Enable")) + return false; + + // Get ProtocolPort + if (!getint(settings, protocol + "Port", port)) + return false; + + // Get ProtocolProxy + if ((host = str(getobj(settings, protocol + "Proxy"))) == "") + return false; + + stringstream ss; + if (protocol == "HTTP" || protocol == "HTTPS" || protocol == "FTP" || protocol == "Gopher") + ss << "http://"; + else if (protocol == "RTSP") + ss << "rtsp://"; + else if (protocol == "SOCKS") + ss << "socks://"; + else + return false; + ss << host; + ss << ":"; + ss << port; + + config = ss.str(); + return true; +} + +static string toupper(string str) { + string tmp; + for (unsigned int i=0 ; str.c_str()[i] ; i++) + tmp += toupper(str.c_str()[i]); + return tmp; +} + +static string capitalize(string str) { + char c = toupper(str.c_str()[0]); + return string(&c, 1) + str.substr(1); +} + +class macosx_config_extension : public config_extension { +public: + vector get_config(const url &the_url) throw (runtime_error) { + string tmp; + CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); + vector response; + + if (!proxies) throw runtime_error("Unable to fetch proxy configuration"); + + // wpad:// + if (getbool(proxies, "ProxyAutoDiscoveryEnable")) { + CFRelease(proxies); + response.push_back(url("wpad://")); + } + + // pac+http://... + else if (getbool(proxies, "ProxyAutoConfigEnable") && + (tmp = str(getobj(proxies, "ProxyAutoConfigURLString"))) != "" && + url::is_valid(tmp)) { + CFRelease(proxies); + response.push_back(url(string("pac+") + tmp)); + } + + // http:// or socks:// (TODO: gopher:// and rtsp:// ???) + else if ((protocol_url(proxies, toupper(the_url.get_scheme()), tmp) && url::is_valid(tmp)) || + (protocol_url(proxies, capitalize(the_url.get_scheme()), tmp) && url::is_valid(tmp)) || + (protocol_url(proxies, toupper("http"), tmp) && url::is_valid(tmp)) || + (protocol_url(proxies, toupper("socks"), tmp) && url::is_valid(tmp))) { + CFRelease(proxies); + response.push_back(url(tmp)); + } + else { + // direct:// + CFRelease(proxies); + response.push_back(url("direct://")); + } + + return response; + } + + string get_ignore(const url&) { + // Get config dict + CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL); + if (!proxies) return ""; + + // Get ignores + string tmp = str(getobj(proxies, "ExceptionsList")); + if (getbool(proxies, "ExcludeSimpleHostnames")) + tmp += (tmp == "" ? string("") : string(",")) + ""; + + CFRelease(proxies); + return tmp; + } +}; + +MM_MODULE_INIT_EZ(macosx_config_extension, true, NULL, NULL); + diff --git a/libproxy/modules/config_sysconfig.cpp b/libproxy/modules/config_sysconfig.cpp new file mode 100644 index 0000000..b7985ae --- /dev/null +++ b/libproxy/modules/config_sysconfig.cpp @@ -0,0 +1,173 @@ +/******************************************************************************* + * libproxy sysconfig module + * Copyright (C) 2010 Novell Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include +#include +#include +#include +#include +#include + + +#include "../extension_config.hpp" +using namespace libproxy; +using std::map; + +enum Trim { + NO_TRIM = 0x00, + L_TRIM = 0x01, + R_TRIM = 0x02, + TRIM = (L_TRIM|R_TRIM) +}; + +static std::string trim( const std::string & s, const Trim trim_r = TRIM ) { + + if (s.empty() || trim_r == NO_TRIM) + return s; + + std::string ret(s); + + if (trim_r & L_TRIM) { + std::string::size_type p = ret.find_first_not_of(" \t\n"); + if (p == std::string::npos) + return std::string(); + + ret = ret.substr(p); + } + + if (trim_r & R_TRIM) { + std::string::size_type p = ret.find_last_not_of(" \t\n"); + if (p == std::string::npos) + return std::string(); + + ret = ret.substr(0, p+1); + } + + return ret; +} + +static map sysconfig_read(const string &_path) { + + map ret; + string line; + + ifstream in(_path.c_str()); + if (in.fail()) { + return ret; + } + + while(getline( in, line)) { + + if (*line.begin() != '#') { + + string::size_type pos = line.find('=', 0); + + if (pos != string::npos) { + + string key = trim(line.substr(0, pos)); + string value = trim(line.substr(pos + 1, line.length() - pos - 1)); + + if (value.length() >= 2 + && *(value.begin()) == '"' + && *(value.rbegin()) == '"') { + value = value.substr( 1, value.length() - 2 ); + } + + if (value.length() >= 2 + && *(value.begin()) == '\'' + && *(value.rbegin()) == '\'' ) { + value = value.substr( 1, value.length() - 2 ); + } + ret[key] = value; + } // '=' found + + } // not comment + + } // while getline + return ret; +} + +static bool should_use_sysconfig() +{ + struct stat st; + if (stat("/etc/sysconfig", &st) == 0) + return (getuid() == 0); + return false; +} + +class sysconfig_config_extension : public config_extension { + + map _data; + +public: + sysconfig_config_extension() + : _data(sysconfig_read("/etc/sysconfig/proxy")) { + + } + + ~sysconfig_config_extension() { + } + + vector get_config(const url &dst) throw (runtime_error) { + map::const_iterator it = _data.find("PROXY_ENABLED"); + vector response; + + if (it != _data.end() && it->second == "no") { + response.push_back(url("direct://")); + return response; + } + + string key; + string proxy; + + // If the URL is an ftp url, try to read the ftp proxy + if (dst.get_scheme() == "ftp") + key = "FTP_PROXY"; + else if (dst.get_scheme() == "http") + key = "HTTP_PROXY"; + else if (dst.get_scheme() == "https") + key = "HTTPS_PROXY"; + + it = _data.find(key); + if (it != _data.end()) + proxy = it->second; + + if (proxy.empty()) + throw runtime_error("Unable to read configuration"); + + response.push_back(url(proxy)); + return response; + } + + string get_ignore(const url&) { + map::const_iterator it = _data.find("NO_PROXY"); + if (it != _data.end()) + return it->second; + return ""; + } + + // if we are running as root, and the module is used, then + // make sure this is the first method tried + virtual bool operator<(const base_extension&) const { + return true; + } +}; + +MM_MODULE_INIT_EZ(sysconfig_config_extension, should_use_sysconfig(), NULL, NULL); + diff --git a/libproxy/modules/config_w32reg.cpp b/libproxy/modules/config_w32reg.cpp new file mode 100644 index 0000000..fc49e41 --- /dev/null +++ b/libproxy/modules/config_w32reg.cpp @@ -0,0 +1,170 @@ +/******************************************************************************* + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "../extension_config.hpp" +using namespace libproxy; + +#define W32REG_OFFSET_PAC (1 << 2) +#define W32REG_OFFSET_WPAD (1 << 3) +#define W32REG_BASEKEY "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" +#define W32REG_BUFFLEN 1024 + +static bool get_registry(const char *key, const char *name, char **sval, uint32_t *slen, uint32_t *ival) { + HKEY hkey; + LONG result; + DWORD type; + DWORD buflen = W32REG_BUFFLEN; + BYTE buffer[W32REG_BUFFLEN]; + + // Don't allow the caller to specify both sval and ival + if (sval && ival) + return false; + + // Open the key + if (RegOpenKeyExA(HKEY_CURRENT_USER, key, 0, KEY_READ, &hkey) != ERROR_SUCCESS) + return false; + + // Read the value + result = RegQueryValueExA(hkey, name, NULL, &type, buffer, &buflen); + + // Close the key + RegCloseKey(hkey); + + // Evaluate + if (result != ERROR_SUCCESS) + return false; + switch (type) + { + case REG_BINARY: + case REG_EXPAND_SZ: + case REG_SZ: + if (!sval) return false; + if (slen) *slen = buflen; + *sval = new char[buflen]; + return memcpy(*sval, buffer, buflen) != NULL; + case REG_DWORD: + if (ival) return memcpy(ival, buffer, buflen < sizeof(uint32_t) ? buflen : sizeof(uint32_t)) != NULL; + } + return false; +} + +static bool is_enabled(uint8_t type) { + char *data = NULL; + uint32_t dlen = 0; + bool result = false; + + // Get the binary value DefaultConnectionSettings + if (!get_registry(W32REG_BASEKEY "\\Connections", "DefaultConnectionSettings", &data, &dlen, NULL)) + return false; + + // WPAD and PAC are contained in the 9th value + if (dlen >= 9) + result = (data[8] & type) == type; // Check to see if the bit is set + + delete data; + return result; +} + +static map parse_manual(string data) { + // ProxyServer comes in two formats: + // 1.2.3.4:8080 or ftp=1.2.3.4:8080;https=1.2.3.4:8080... + map rval; + + // If we have the second format, do recursive parsing, + // then handle just the first entry + if (data.find(";") != string::npos) { + rval = parse_manual(data.substr(data.find(";")+1)); + data = data.substr(0, data.find(";")); + } + + // If we have the first format, just assign HTTP and we're done + if (data.find("=") == string::npos) { + rval["http"] = string("http://") + data; + return rval; + } + + // Otherwise set the value for this single entry and return + string protocol = data.substr(0, data.find("=")); + try { rval[protocol] = url(protocol + "://" + data.substr(data.find("=")+1)).to_string(); } + catch (parse_error&) {} + + return rval; +} + +class w32reg_config_extension : public config_extension { +public: + vector get_config(const url &dst) throw (runtime_error) { + char *tmp = NULL; + uint32_t enabled = 0; + vector response; + + // WPAD + if (is_enabled(W32REG_OFFSET_WPAD)) { + response.push_back(url("wpad://")); + return response; + } + + // PAC + if (is_enabled(W32REG_OFFSET_PAC) && + get_registry(W32REG_BASEKEY, "AutoConfigURL", &tmp, NULL, NULL) && + url::is_valid(string("pac+") + tmp)) { + response.push_back(url(string("pac+") + tmp)); + delete tmp; + return response; + } + + // Manual proxy + // Check to see if we are enabled and get the value of ProxyServer + if (get_registry(W32REG_BASEKEY, "ProxyEnable", NULL, NULL, &enabled) && enabled && + get_registry(W32REG_BASEKEY, "ProxyServer", &tmp, NULL, NULL)) { + map manual = parse_manual(tmp); + delete tmp; + + // First we look for an exact match + if (manual.find(dst.get_scheme()) != manual.end()) + response.push_back(manual[dst.get_scheme()]); + + // Next we look for http + else if (manual.find("http") != manual.end()) + response.push_back(manual["http"]); + + // Last we look for socks + else if (manual.find("socks") != manual.end()) + response.push_back(manual["socks"]); + + return response; + } + + // Direct + response.push_back(url("direct://")); + return response; + } + + string get_ignore(const url &dst) { + char *tmp; + if (get_registry(W32REG_BASEKEY, "ProxyOverride", &tmp, NULL, NULL)) { + string po = tmp; + delete tmp; + if (po == "") + return po; + } + return ""; + } +}; + +MM_MODULE_INIT_EZ(w32reg_config_extension, true, NULL, NULL); diff --git a/libproxy/modules/ignore_domain.cpp b/libproxy/modules/ignore_domain.cpp new file mode 100644 index 0000000..f39e545 --- /dev/null +++ b/libproxy/modules/ignore_domain.cpp @@ -0,0 +1,59 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include + +#include "../extension_ignore.hpp" +using namespace libproxy; + +class domain_ignore_extension : public ignore_extension { +public: + virtual bool ignore(url& url, const string &ignorestr) { + /* Get our URL's hostname and port */ + string host = url.get_host(); + int port = url.get_port(); + + /* Get our ignore pattern's hostname and port */ + string ihost = ignorestr; + int iport = 0; + if (ihost.find(':') != string::npos) { + if (sscanf(ignorestr.substr(ihost.find(':')+1).c_str(), "%d", &iport) == 1) + ihost = ihost.substr(0, ihost.find(':')); + else + iport = 0; + } + + /* Hostname match (domain.com or domain.com:80) */ + if (host == ihost) + return (iport == 0 || port == iport); + + /* Endswith (.domain.com or .domain.com:80) */ + if (ihost[0] == '.' && host.find(ihost) == host.size() - ihost.size() && host.size() >= ihost.size()) + return (iport == 0 || port == iport); + + /* Glob (*.domain.com or *.domain.com:80) */ + if (ihost[0] == '*' && host.find(ihost.substr(1)) == host.size() - ihost.substr(1).size() && host.size() >= ihost.substr(1).size()) + return (iport == 0 || port == iport); + + /* No match was found */ + return false; + } +}; + +MM_MODULE_INIT_EZ(domain_ignore_extension, true, NULL, NULL); diff --git a/libproxy/modules/ignore_hostname.cpp b/libproxy/modules/ignore_hostname.cpp new file mode 100644 index 0000000..6caa291 --- /dev/null +++ b/libproxy/modules/ignore_hostname.cpp @@ -0,0 +1,36 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include + +#include "../extension_ignore.hpp" +using namespace libproxy; + +class hostname_ignore_extension : public ignore_extension { +public: + virtual bool ignore(url& url, const string &ignorestr) { + if (ignorestr == "" && + url.get_host().find(':') == string::npos && // Make sure it's not IPv6 + url.get_host().find('.') == string::npos) + return true; + return false; + } +}; + +MM_MODULE_INIT_EZ(hostname_ignore_extension, true, NULL, NULL); diff --git a/libproxy/modules/ignore_ip.cpp b/libproxy/modules/ignore_ip.cpp new file mode 100644 index 0000000..9f795c4 --- /dev/null +++ b/libproxy/modules/ignore_ip.cpp @@ -0,0 +1,188 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include +#include + +#include "../extension_ignore.hpp" +using namespace libproxy; + +static inline bool +sockaddr_equals(const struct sockaddr *ip_a, const struct sockaddr *ip_b, const struct sockaddr *nm) +{ + if (!ip_a || !ip_b) return false; + if (ip_a->sa_family != ip_b->sa_family) return false; + if (nm && ip_a->sa_family != nm->sa_family) return false; + + /* Setup the arrays */ + uint8_t bytes = 0, *a_data = NULL, *b_data = NULL, *nm_data = NULL; + if (ip_a->sa_family == AF_INET) + { + bytes = 32 / 8; + a_data = (uint8_t *) &((struct sockaddr_in *) ip_a)->sin_addr; + b_data = (uint8_t *) &((struct sockaddr_in *) ip_b)->sin_addr; + nm_data = nm ? (uint8_t *) &((struct sockaddr_in *) nm)->sin_addr : NULL; + } + else if (ip_a->sa_family == AF_INET6) + { + bytes = 128 / 8; + a_data = (uint8_t *) &((struct sockaddr_in6 *) ip_a)->sin6_addr; + b_data = (uint8_t *) &((struct sockaddr_in6 *) ip_b)->sin6_addr; + nm_data = nm ? (uint8_t *) &((struct sockaddr_in6 *) nm)->sin6_addr : NULL; + } + else + return false; + + for (int i=0 ; i < bytes ; i++) + { + if (nm && (a_data[i] & nm_data[i]) != (b_data[i] & nm_data[i])) + return false; + else if (!nm && (a_data[i] != b_data[i])) + return false; + } + return true; +} + +static inline sockaddr * +sockaddr_from_string(string ip) +{ + struct sockaddr *result = NULL; + + /* Try to parse */ + struct addrinfo *info = NULL; + struct addrinfo flags; + flags.ai_family = AF_UNSPEC; + flags.ai_socktype = 0; + flags.ai_protocol = 0; + flags.ai_flags = AI_NUMERICHOST; + if (getaddrinfo(ip.c_str(), NULL, &flags, &info) != 0 || !info) return result; + + /* Copy the results into our buffer */ + result = (sockaddr *) new char[info->ai_addrlen]; + if (!result) { + freeaddrinfo(info); + return result; + } + memcpy(result, info->ai_addr, info->ai_addrlen); + freeaddrinfo(info); + return result; +} + +static inline sockaddr * +sockaddr_from_cidr(sa_family_t af, uint8_t cidr) +{ + /* IPv4 */ + if (af == AF_INET) + { + sockaddr_in *mask = (sockaddr_in*) new char[sizeof(sockaddr_in)]; + mask->sin_family = af; + mask->sin_addr.s_addr = htonl(~0 << (32 - (cidr > 32 ? 32 : cidr))); + + return (struct sockaddr *) mask; + } + + /* IPv6 */ + else if (af == AF_INET6) + { + sockaddr_in6 *mask = (sockaddr_in6*) new char[sizeof(sockaddr_in6)]; + mask->sin6_family = af; + for (uint8_t i=0 ; i < sizeof(mask->sin6_addr) ; i++) + mask->sin6_addr.s6_addr[i] = ~0 << (8 - (8*i > cidr ? 0 : cidr-8*i < 8 ? cidr-8*i : 8) ); + + return (sockaddr *) mask; + } + + return NULL; +} + +class ip_ignore_extension : public ignore_extension { +public: + virtual bool ignore(url& url, const string &ignore) { + bool result = false; + uint16_t port = 0; + const struct sockaddr *dst_ip = url.get_ips(false) ? url.get_ips(false)[0] : NULL; + struct sockaddr *ign_ip = NULL, *net_ip = NULL; + + /* + * IPv4 + * IPv6 + */ + if ((ign_ip = sockaddr_from_string(ignore))) + goto out; + + /* + * IPv4/CIDR + * IPv4/IPv4 + * IPv6/CIDR + * IPv6/IPv6 + */ + if (ignore.find('/') != string::npos) + { + ign_ip = sockaddr_from_string(ignore.substr(0, ignore.find('/'))); + + uint32_t cidr = 0; + string mask = ignore.substr(ignore.find('/') + 1); + + if (mask.find('.') != string::npos) + { + /* A dotted netmask was used */ + net_ip = sockaddr_from_string(mask); + } + else + { + /* If CIDR notation was used, get the netmask */ + if (ign_ip && sscanf(mask.c_str(), "%d", &cidr) == 1) + net_ip = sockaddr_from_cidr(ign_ip->sa_family, cidr); + } + + if (ign_ip && net_ip && ign_ip->sa_family == net_ip->sa_family) + goto out; + + delete[] ign_ip; + delete[] net_ip; + ign_ip = NULL; + net_ip = NULL; + } + + /* + * IPv4:port + * [IPv6]:port + */ + if (ignore.rfind(':') != string::npos && sscanf(ignore.substr(ignore.rfind(':')).c_str(), ":%hu", &port) == 1 && port > 0) + { + ign_ip = sockaddr_from_string(ignore.substr(ignore.rfind(':')).c_str()); + + /* Make sure this really is just a port and not just an IPv6 address */ + if (ign_ip && (ign_ip->sa_family != AF_INET6 || ignore[0] == '[')) + goto out; + + delete[] ign_ip; + ign_ip = NULL; + port = 0; + } + + out: + result = sockaddr_equals(dst_ip, ign_ip, net_ip); + delete[] ign_ip; + delete[] net_ip; + return port != 0 ? (port == url.get_port() && result) : result; + } +}; + +MM_MODULE_INIT_EZ(ip_ignore_extension, true, NULL, NULL); diff --git a/libproxy/modules/network_networkmanager.cpp b/libproxy/modules/network_networkmanager.cpp new file mode 100644 index 0000000..546a8ee --- /dev/null +++ b/libproxy/modules/network_networkmanager.cpp @@ -0,0 +1,98 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include // For uint32_t + +#include "../extension_network.hpp" +using namespace libproxy; + +#include +#include + +// Backwards compatibility: with the switch to libnm, NM_STATE_CONNECTED is no +// longer defined. NM_STATE_CONNECTED_GLOBAL appeared with NM 0.9 and was aliased +#ifndef NM_STATE_CONNECTED + #define NM_STATE_CONNECTED NM_STATE_CONNECTED_GLOBAL +#endif + +class networkmanager_network_extension : public network_extension { +public: + networkmanager_network_extension() { + this->conn = NULL; + } + + ~networkmanager_network_extension() { + if (this->conn) dbus_connection_close(this->conn); + } + + bool changed() { + // Make sure we have a valid connection with a proper match + DBusConnection *conn = this->conn; + if (!conn || !dbus_connection_get_is_connected(conn)) + { + // If the connection was disconnected, + // close it an clear the queue + if (conn) + { + dbus_connection_close(conn); + dbus_connection_read_write(conn, 0); + for (DBusMessage *msg=NULL ; (msg = dbus_connection_pop_message(conn)) ; dbus_message_unref(msg)) {}; + } + + // Create a new connections + conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, NULL); + this->conn = conn; + if (!conn) return false; + + // If connection was successful, set it up + dbus_connection_set_exit_on_disconnect(conn, false); + dbus_bus_add_match(conn, "type='signal',interface='" NM_DBUS_INTERFACE "',member='StateChanged'", NULL); + dbus_connection_flush(conn); + } + + // We are guaranteed a connection, + // so check for incoming messages + bool changed = false; + while (true) + { + DBusMessage *msg = NULL; + uint32_t state; + + // Pull messages off the queue + dbus_connection_read_write(conn, 0); + if (!(msg = dbus_connection_pop_message(conn))) + break; + + // If a message is the right type and value, + // we'll reset the network + if (dbus_message_get_args(msg, NULL, DBUS_TYPE_UINT32, &state, DBUS_TYPE_INVALID)) + if (state == NM_STATE_CONNECTED) + changed = true; + + dbus_message_unref(msg); + } + + return changed; + } + +private: + DBusConnection *conn; +}; + +MM_MODULE_INIT_EZ(networkmanager_network_extension, true, NULL, NULL); diff --git a/libproxy/modules/pacrunner_mozjs.cpp b/libproxy/modules/pacrunner_mozjs.cpp new file mode 100644 index 0000000..a70b2e9 --- /dev/null +++ b/libproxy/modules/pacrunner_mozjs.cpp @@ -0,0 +1,197 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include // ? +#include // gethostname + +#include "../extension_pacrunner.hpp" +using namespace libproxy; + +// Work around a mozjs include bug +#ifndef JS_HAS_FILE_OBJECT +#define JS_HAS_FILE_OBJECT 0 +#endif +#ifdef WIN32 +#ifndef XP_WIN +#define XP_WIN +#endif +#endif +#pragma GCC diagnostic ignored "-Winvalid-offsetof" +#include +#pragma GCC diagnostic error "-Winvalid-offsetof" +#include + +#include "pacutils.h" + +#ifndef INET_ADDRSTRLEN +#define INET_ADDRSTRLEN 16 +#endif + +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN 46 +#endif + +static void dnsResolve_(JSContext *cx, JSString *hostname, JS::CallArgs *argv) { + // Get hostname argument + char *tmp = JS_EncodeString(cx, hostname); + + // Set the default return value + argv->rval().setNull(); + + // Look it up + struct addrinfo *info = nullptr; + if (getaddrinfo(tmp, NULL, NULL, &info)) + goto out; + + // Allocate the IP address + JS_free(cx, tmp); + tmp = (char *) JS_malloc(cx, INET6_ADDRSTRLEN+1); + memset(tmp, 0, INET6_ADDRSTRLEN+1); + + // Try for IPv4 and IPv6 + if (getnameinfo(info->ai_addr, info->ai_addrlen, + tmp, INET6_ADDRSTRLEN+1, + NULL, 0, + NI_NUMERICHOST)) goto out; + + // We succeeded + argv->rval().setString(JS_NewStringCopyZ(cx, tmp)); + tmp = nullptr; + + out: + if (info) freeaddrinfo(info); + JS_free(cx, tmp); +} + +static bool dnsResolve(JSContext *cx, unsigned argc, JS::Value *vp) { + JS::CallArgs argv=JS::CallArgsFromVp(argc,vp); + dnsResolve_(cx, argv[0].toString(), &argv); + return true; +} + +static bool myIpAddress(JSContext *cx, unsigned argc, JS::Value *vp) { + JS::CallArgs argv=JS::CallArgsFromVp(argc,vp); + char *hostname = (char *) JS_malloc(cx, 1024); + + if (!gethostname(hostname, 1023)) { + JSString *myhost = JS_NewStringCopyN(cx, hostname, strlen(hostname)); + dnsResolve_(cx, myhost, &argv); + } else { + argv.rval().setNull(); + } + + JS_free(cx, hostname); + return true; +} + +// Setup Javascript global class +// This MUST be a static global +static JSClass cls = { + "global", JSCLASS_GLOBAL_FLAGS, +}; + +class mozjs_pacrunner : public pacrunner { +public: + mozjs_pacrunner(string pac, const url& pacurl) throw (bad_alloc) : pacrunner(pac, pacurl) { + + // Set defaults + this->jsrun = nullptr; + this->jsctx = nullptr; + JS_Init(); + + // Initialize Javascript runtime environment + if (!(this->jsrun = JS_NewRuntime(1024 * 1024))) goto error; + if (!(this->jsctx = JS_NewContext(this->jsrun, 1024 * 1024))) goto error; + { + JS::RootedValue rval(this->jsctx); + JS::CompartmentOptions compart_opts; + compart_opts.setVersion(JSVERSION_LATEST); + + this->jsglb = new JS::Heap(JS_NewGlobalObject( + this->jsctx, &cls, + nullptr, JS::DontFireOnNewGlobalHook, + compart_opts)); + + if (!(this->jsglb)) goto error; + JS::RootedObject global(this->jsctx,this->jsglb->get()); + if (!(this->jsac = new JSAutoCompartment(this->jsctx, global))) goto error; + if (!JS_InitStandardClasses(this->jsctx, global)) goto error; + + // Define Javascript functions + JS_DefineFunction(this->jsctx, global, "dnsResolve", dnsResolve, 1, 0); + JS_DefineFunction(this->jsctx, global, "myIpAddress", myIpAddress, 0, 0); + JS::CompileOptions options(this->jsctx); + options.setUTF8(true); + + JS::Evaluate(this->jsctx, global, options, JAVASCRIPT_ROUTINES, + strlen(JAVASCRIPT_ROUTINES), &rval); + + // Add PAC to the environment + JS::Evaluate(this->jsctx, global, options, pac.c_str(), pac.length(), &rval); + return; + } + error: + if (this->jsctx) JS_DestroyContext(this->jsctx); + if (this->jsrun) JS_DestroyRuntime(this->jsrun); + throw bad_alloc(); + } + + ~mozjs_pacrunner() { + if (this->jsac) delete this->jsac; + if (this->jsglb) delete this->jsglb; + if (this->jsctx) JS_DestroyContext(this->jsctx); + if (this->jsrun) JS_DestroyRuntime(this->jsrun); + JS_ShutDown(); + } + + string run(const url& url_) throw (bad_alloc) { + // Build arguments to the FindProxyForURL() function + char *tmpurl = JS_strdup(this->jsctx, url_.to_string().c_str()); + char *tmphost = JS_strdup(this->jsctx, url_.get_host().c_str()); + if (!tmpurl || !tmphost) { + if (tmpurl) JS_free(this->jsctx, tmpurl); + if (tmphost) JS_free(this->jsctx, tmphost); + throw bad_alloc(); + } + JS::AutoValueArray<2> args(this->jsctx); + args[0].setString(JS_NewStringCopyZ(this->jsctx, tmpurl)); + args[1].setString(JS_NewStringCopyZ(this->jsctx, tmphost)); + + // Find the proxy (call FindProxyForURL()) + JS::RootedValue rval(this->jsctx); + JS::RootedObject global(this->jsctx,this->jsglb->get()); + bool result = JS_CallFunctionName(this->jsctx, global, "FindProxyForURL", args, &rval); + if (!result) return ""; + + char * tmpanswer = JS_EncodeString(this->jsctx, rval.toString()); + string answer = string(tmpanswer); + JS_free(this->jsctx, tmpanswer); + + if (answer == "undefined") return ""; + return answer; + } + +private: + JSRuntime *jsrun; + JSContext *jsctx; + JS::Heap *jsglb; + JSAutoCompartment *jsac; +}; + +PX_PACRUNNER_MODULE_EZ(mozjs, "JS_DefineFunction", "mozjs"); diff --git a/libproxy/modules/pacrunner_natus.cpp b/libproxy/modules/pacrunner_natus.cpp new file mode 100644 index 0000000..72ef6ff --- /dev/null +++ b/libproxy/modules/pacrunner_natus.cpp @@ -0,0 +1,112 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "../extension_pacrunner.hpp" +#include // gethostname +using namespace libproxy; + +#define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE +#include +#include "pacutils.h" + +using namespace natus; + +static Value dnsResolve(Value& ths, Value& fnc, vector& arg) { + Value exc = checkArguments(ths, arg, "s"); + if (exc.isException()) return exc; + + // Look it up + struct addrinfo *info; + if (getaddrinfo(arg[0].toString().c_str(), NULL, NULL, &info)) + return NULL; + + // Try for IPv4 + char* tmp = new char[INET6_ADDRSTRLEN+1]; + if (getnameinfo(info->ai_addr, info->ai_addrlen, + tmp, INET6_ADDRSTRLEN+1, + NULL, 0, + NI_NUMERICHOST)) { + freeaddrinfo(info); + delete[] tmp; + return NULL; + } + freeaddrinfo(info); + + // Create the return value + Value ret = ths.newString(tmp); + delete[] tmp; + return ret; +} + +static Value myIpAddress(Value& ths, Value& fnc, vector& arg) { + char hostname[1024]; + if (!gethostname(hostname, 1023)) { + vector dnsargs; + dnsargs.push_back(ths.newString(hostname)); + return dnsResolve(ths, fnc, dnsargs); + } + return ths.newString("Unable to find hostname!").toException(); +} + +class natus_pacrunner : public pacrunner { +public: + natus_pacrunner(string pac, const url& pacurl) throw (bad_alloc) : pacrunner(pac, pacurl) { + Value exc; + + // Create the basic context + if (!eng.initialize()) goto error; + glb = this->eng.newGlobal(); + if (glb.isException()) goto error; + + // Add dnsResolve into the context + if (!glb.set("dnsResolve", glb.newFunction(dnsResolve))) goto error; + + // Add myIpAddress into the context + if (!glb.set("myIpAddress", glb.newFunction(myIpAddress))) goto error; + + // Add all other routines into the context + exc = glb.evaluate(JAVASCRIPT_ROUTINES); + if (exc.isException()) goto error; + + // Add the PAC into the context + exc = glb.evaluate(pac.c_str(), pacurl.to_string()); + if (exc.isException()) goto error; + return; + + error: + throw bad_alloc(); + } + + string run(const url& url_) throw (bad_alloc) { + vector args; + args.push_back(glb.newString(url_.to_string())); + args.push_back(glb.newString(url_.get_host())); + + Value res = glb.call("FindProxyForURL", args); + if (res.isString() && !res.isException()) + return res.toString(); + return ""; + } + +private: + Engine eng; + Value glb; +}; + +PX_PACRUNNER_MODULE_EZ(natus, "nt_engine_init", "natus"); diff --git a/libproxy/modules/pacrunner_webkit.cpp b/libproxy/modules/pacrunner_webkit.cpp new file mode 100644 index 0000000..bef2056 --- /dev/null +++ b/libproxy/modules/pacrunner_webkit.cpp @@ -0,0 +1,171 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "../extension_pacrunner.hpp" +#include // gethostname +using namespace libproxy; + +#ifdef __APPLE__ +// JavaScriptCore.h requires CoreFoundation +// This is only found on Mac OS X +#include +#else +#include +#endif +#include "pacutils.h" + +#ifndef INET_ADDRSTRLEN +#define INET_ADDRSTRLEN 16 +#endif + +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN 46 +#endif + +static char *jstr2str(JSStringRef str, bool release) throw (bad_alloc) +{ + char *tmp = new char[JSStringGetMaximumUTF8CStringSize(str)+1]; + JSStringGetUTF8CString(str, tmp, JSStringGetMaximumUTF8CStringSize(str)+1); + if (release) JSStringRelease(str); + return tmp; +} + +static JSValueRef dnsResolve(JSContextRef ctx, JSObjectRef /*func*/, JSObjectRef /*self*/, size_t argc, const JSValueRef argv[], JSValueRef* /*exception*/) +{ + if (argc != 1) return NULL; + if (!JSValueIsString(ctx, argv[0])) return NULL; + + // Get hostname argument + char *tmp = jstr2str(JSValueToStringCopy(ctx, argv[0], NULL), true); + + // Look it up + struct addrinfo *info; + if (getaddrinfo(tmp, NULL, NULL, &info)) + return NULL; + delete[] tmp; + + // Try for IPv4 + tmp = new char[INET6_ADDRSTRLEN+1]; + if (getnameinfo(info->ai_addr, info->ai_addrlen, + tmp, INET6_ADDRSTRLEN+1, + NULL, 0, + NI_NUMERICHOST)) { + freeaddrinfo(info); + delete[] tmp; + return NULL; + } + freeaddrinfo(info); + + // Create the return value + JSStringRef str = JSStringCreateWithUTF8CString(tmp); + JSValueRef ret = JSValueMakeString(ctx, str); + JSStringRelease(str); + delete[] tmp; + + return ret; +} + +static JSValueRef myIpAddress(JSContextRef ctx, JSObjectRef func, JSObjectRef self, size_t /*argc*/, const JSValueRef[] /*argv*/, JSValueRef* /*exception*/) +{ + char hostname[1024]; + if (!gethostname(hostname, 1023)) { + JSStringRef str = JSStringCreateWithUTF8CString(hostname); + JSValueRef val = JSValueMakeString(ctx, str); + JSStringRelease(str); + JSValueRef ip = dnsResolve(ctx, func, self, 1, &val, NULL); + return ip; + } + return NULL; +} + +class webkit_pacrunner : public pacrunner { +public: + ~webkit_pacrunner() { + JSGarbageCollect(this->jsctx); + JSGlobalContextRelease(this->jsctx); + } + + webkit_pacrunner(string pac, const url& pacurl) throw (bad_alloc) : pacrunner(pac, pacurl) { + JSStringRef str = NULL; + JSObjectRef func = NULL; + + // Create the basic context + if (!(this->jsctx = JSGlobalContextCreate(NULL))) goto error; + + // Add dnsResolve into the context + str = JSStringCreateWithUTF8CString("dnsResolve"); + func = JSObjectMakeFunctionWithCallback(this->jsctx, str, dnsResolve); + JSObjectSetProperty(this->jsctx, JSContextGetGlobalObject(this->jsctx), str, func, kJSPropertyAttributeNone, NULL); + JSStringRelease(str); + + // Add myIpAddress into the context + str = JSStringCreateWithUTF8CString("myIpAddress"); + func = JSObjectMakeFunctionWithCallback(this->jsctx, str, myIpAddress); + JSObjectSetProperty(this->jsctx, JSContextGetGlobalObject(this->jsctx), str, func, kJSPropertyAttributeNone, NULL); + JSStringRelease(str); + + // Add all other routines into the context + str = JSStringCreateWithUTF8CString(JAVASCRIPT_ROUTINES); + if (!JSCheckScriptSyntax(this->jsctx, str, NULL, 0, NULL)) goto error; + JSEvaluateScript(this->jsctx, str, NULL, NULL, 1, NULL); + JSStringRelease(str); + + // Add the PAC into the context + str = JSStringCreateWithUTF8CString(pac.c_str()); + if (!JSCheckScriptSyntax(this->jsctx, str, NULL, 0, NULL)) goto error; + JSEvaluateScript(this->jsctx, str, NULL, NULL, 1, NULL); + JSStringRelease(str); + return; + + error: + if (str) JSStringRelease(str); + if (this->jsctx) { + JSGarbageCollect(this->jsctx); + JSGlobalContextRelease(this->jsctx); + } + throw bad_alloc(); + } + + string run(const url& url_) throw (bad_alloc) { + JSStringRef str = NULL; + JSValueRef val = NULL; + string tmp; + + // Run the PAC + tmp = string("FindProxyForURL(\"") + url_.to_string() + string("\", \"") + url_.get_host() + "\");"; + str = JSStringCreateWithUTF8CString(tmp.c_str()); + if (!str) throw bad_alloc(); + if (!JSCheckScriptSyntax(this->jsctx, str, NULL, 0, NULL)) goto error; + if (!(val = JSEvaluateScript(this->jsctx, str, NULL, NULL, 1, NULL))) goto error; + if (!JSValueIsString(this->jsctx, val)) goto error; + JSStringRelease(str); + + // Convert the return value to a string + return jstr2str(JSValueToStringCopy(this->jsctx, val, NULL), true); + + error: + JSStringRelease(str); + return ""; + } + +private: + JSGlobalContextRef jsctx; +}; + +PX_PACRUNNER_MODULE_EZ(webkit, "JSObjectMakeFunctionWithCallback", "webkit"); diff --git a/libproxy/modules/pacutils.h b/libproxy/modules/pacutils.h new file mode 100644 index 0000000..3826014 --- /dev/null +++ b/libproxy/modules/pacutils.h @@ -0,0 +1,242 @@ +/* + * The following Javascript code was taken from Mozilla (http://www.mozilla.org) + * and is licensed according to the LGPLv2.1+. Below is the original copyright + * header as contained in the source file (nsProxyAutoConfig.js) + */ + +/* ***** BEGIN LICENSE BLOCK ***** + * Version: NPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Netscape Public License + * Version 1.1 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * http://www.mozilla.org/NPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is mozilla.org code. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Akhil Arora + * Tomi Leppikangas + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the NPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the NPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#define JAVASCRIPT_ROUTINES \ +"function dnsDomainIs(host, domain) {\n" \ +" return (host.length >= domain.length &&\n" \ +" host.substring(host.length - domain.length) == domain);\n" \ +"}\n" \ +"function dnsDomainLevels(host) {\n" \ +" return host.split('.').length-1;\n" \ +"}\n" \ +"function convert_addr(ipchars) {\n" \ +" var bytes = ipchars.split('.');\n" \ +" var result = ((bytes[0] & 0xff) << 24) |\n" \ +" ((bytes[1] & 0xff) << 16) |\n" \ +" ((bytes[2] & 0xff) << 8) |\n" \ +" (bytes[3] & 0xff);\n" \ +" return result;\n" \ +"}\n" \ +"function isInNet(ipaddr, pattern, maskstr) {\n"\ +" var test = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(ipaddr);\n"\ +" if (test == null) {\n"\ +" ipaddr = dnsResolve(ipaddr);\n"\ +" if (ipaddr == null)\n"\ +" return false;\n"\ +" } else if (test[1] > 255 || test[2] > 255 || \n"\ +" test[3] > 255 || test[4] > 255) {\n"\ +" return false; // not an IP address\n"\ +" }\n"\ +" var host = convert_addr(ipaddr);\n"\ +" var pat = convert_addr(pattern);\n"\ +" var mask = convert_addr(maskstr);\n"\ +" return ((host & mask) == (pat & mask));\n"\ +" \n"\ +"}\n"\ +"function isPlainHostName(host) {\n" \ +" return (host.search('\\\\.') == -1);\n" \ +"}\n" \ +"function isResolvable(host) {\n" \ +" var ip = dnsResolve(host);\n" \ +" return (ip != null);\n" \ +"}\n" \ +"function localHostOrDomainIs(host, hostdom) {\n" \ +" if (isPlainHostName(host)) {\n" \ +" return (hostdom.search('/^' + host + '/') != -1);\n" \ +" }\n" \ +" else {\n" \ +" return (host == hostdom);\n" \ +" }\n" \ +"}\n" \ +"function shExpMatch(url, pattern) {\n" \ +" pattern = pattern.replace(/\\./g, '\\\\.');\n" \ +" pattern = pattern.replace(/\\*/g, '.*');\n" \ +" pattern = pattern.replace(/\\?/g, '.');\n" \ +" var newRe = new RegExp('^'+pattern+'$');\n" \ +" return newRe.test(url);\n" \ +"}\n" \ +"var wdays = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6};\n" \ +"var months = {JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11};\n"\ +"function weekdayRange() {\n" \ +" function getDay(weekday) {\n" \ +" if (weekday in wdays) {\n" \ +" return wdays[weekday];\n" \ +" }\n" \ +" return -1;\n" \ +" }\n" \ +" var date = new Date();\n" \ +" var argc = arguments.length;\n" \ +" var wday;\n" \ +" if (argc < 1)\n" \ +" return false;\n" \ +" if (arguments[argc - 1] == 'GMT') {\n" \ +" argc--;\n" \ +" wday = date.getUTCDay();\n" \ +" } else {\n" \ +" wday = date.getDay();\n" \ +" }\n" \ +" var wd1 = getDay(arguments[0]);\n" \ +" var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n" \ +" return (wd1 == -1 || wd2 == -1) ? false\n" \ +" : (wd1 <= wday && wday <= wd2);\n" \ +"}\n" \ +"function dateRange() {\n" \ +" function getMonth(name) {\n" \ +" if (name in months) {\n" \ +" return months[name];\n" \ +" }\n" \ +" return -1;\n" \ +" }\n" \ +" var date = new Date();\n" \ +" var argc = arguments.length;\n" \ +" if (argc < 1) {\n" \ +" return false;\n" \ +" }\n" \ +" var isGMT = (arguments[argc - 1] == 'GMT');\n" \ +" if (isGMT) {\n" \ +" argc--;\n" \ +" }\n" \ +" if (argc == 1) {\n" \ +" var tmp = parseInt(arguments[0]);\n" \ +" if (isNaN(tmp)) {\n" \ +" return ((isGMT ? date.getUTCMonth() : date.getMonth()) == getMonth(arguments[0]));\n" \ +" } else if (tmp < 32) {\n" \ +" return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n" \ +" } else {\n" \ +" return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) == tmp);\n" \ +" }\n" \ +" }\n" \ +" var year = date.getFullYear();\n" \ +" var date1, date2;\n" \ +" date1 = new Date(year, 0, 1, 0, 0, 0);\n" \ +" date2 = new Date(year, 11, 31, 23, 59, 59);\n" \ +" var adjustMonth = false;\n" \ +" for (var i = 0; i < (argc >> 1); i++) {\n" \ +" var tmp = parseInt(arguments[i]);\n" \ +" if (isNaN(tmp)) {\n" \ +" var mon = getMonth(arguments[i]);\n" \ +" date1.setMonth(mon);\n" \ +" } else if (tmp < 32) {\n" \ +" adjustMonth = (argc <= 2);\n" \ +" date1.setDate(tmp);\n" \ +" } else {\n" \ +" date1.setFullYear(tmp);\n" \ +" }\n" \ +" }\n" \ +" for (var i = (argc >> 1); i < argc; i++) {\n" \ +" var tmp = parseInt(arguments[i]);\n" \ +" if (isNaN(tmp)) {\n" \ +" var mon = getMonth(arguments[i]);\n" \ +" date2.setMonth(mon);\n" \ +" } else if (tmp < 32) {\n" \ +" date2.setDate(tmp);\n" \ +" } else {\n" \ +" date2.setFullYear(tmp);\n" \ +" }\n" \ +" }\n" \ +" if (adjustMonth) {\n" \ +" date1.setMonth(date.getMonth());\n" \ +" date2.setMonth(date.getMonth());\n" \ +" }\n" \ +" if (isGMT) {\n" \ +" var tmp = date;\n" \ +" tmp.setFullYear(date.getUTCFullYear());\n" \ +" tmp.setMonth(date.getUTCMonth());\n" \ +" tmp.setDate(date.getUTCDate());\n" \ +" tmp.setHours(date.getUTCHours());\n" \ +" tmp.setMinutes(date.getUTCMinutes());\n" \ +" tmp.setSeconds(date.getUTCSeconds());\n" \ +" date = tmp;\n" \ +" }\n" \ +" return ((date1 <= date) && (date <= date2));\n" \ +"}\n" \ +"function timeRange() {\n" \ +" var argc = arguments.length;\n" \ +" var date = new Date();\n" \ +" var isGMT= false;\n" \ +" if (argc < 1) {\n" \ +" return false;\n" \ +" }\n" \ +" if (arguments[argc - 1] == 'GMT') {\n" \ +" isGMT = true;\n" \ +" argc--;\n" \ +" }\n" \ +" var hour = isGMT ? date.getUTCHours() : date.getHours();\n" \ +" var date1, date2;\n" \ +" date1 = new Date();\n" \ +" date2 = new Date();\n" \ +" if (argc == 1) {\n" \ +" return (hour == arguments[0]);\n" \ +" } else if (argc == 2) {\n" \ +" return ((arguments[0] <= hour) && (hour <= arguments[1]));\n" \ +" } else {\n" \ +" switch (argc) {\n" \ +" case 6:\n" \ +" date1.setSeconds(arguments[2]);\n" \ +" date2.setSeconds(arguments[5]);\n" \ +" case 4:\n" \ +" var middle = argc >> 1;\n" \ +" date1.setHours(arguments[0]);\n" \ +" date1.setMinutes(arguments[1]);\n" \ +" date2.setHours(arguments[middle]);\n" \ +" date2.setMinutes(arguments[middle + 1]);\n" \ +" if (middle == 2) {\n" \ +" date2.setSeconds(59);\n" \ +" }\n" \ +" break;\n" \ +" default:\n" \ +" throw 'timeRange: bad number of arguments'\n" \ +" }\n" \ +" }\n" \ +" if (isGMT) {\n" \ +" date.setFullYear(date.getUTCFullYear());\n" \ +" date.setMonth(date.getUTCMonth());\n" \ +" date.setDate(date.getUTCDate());\n" \ +" date.setHours(date.getUTCHours());\n" \ +" date.setMinutes(date.getUTCMinutes());\n" \ +" date.setSeconds(date.getUTCSeconds());\n" \ +" }\n" \ +" return ((date1 <= date) && (date <= date2));\n" \ +"}\n" \ +"" diff --git a/libproxy/modules/pxgconf.cpp b/libproxy/modules/pxgconf.cpp new file mode 100644 index 0000000..ff7890f --- /dev/null +++ b/libproxy/modules/pxgconf.cpp @@ -0,0 +1,194 @@ +#include +#include +#include +#include + +#include +#include +#include + +using namespace std; + +static GMainLoop* loop = NULL; + +static int print_value(const GConfValue *value, const char *suffix) { + int count = 0; + GSList* cursor = NULL; + + if (!value) return 0; + + switch (value->type) { + case GCONF_VALUE_STRING: + return printf("%s%s", gconf_value_get_string(value), suffix); + case GCONF_VALUE_INT: + return printf("%d%s", gconf_value_get_int(value), suffix); + case GCONF_VALUE_FLOAT: + return printf("%f%s", gconf_value_get_float(value), suffix); + case GCONF_VALUE_BOOL: + if (gconf_value_get_bool(value)) + return printf("true%s", suffix); + return printf("false%s", suffix); + case GCONF_VALUE_LIST: + cursor = gconf_value_get_list(value); + if (g_slist_length (cursor) == 0) + count += printf("%s", suffix); + else for ( ; cursor ; cursor = g_slist_next(cursor)) + count += print_value((const GConfValue *) cursor->data, cursor->next ? "," : suffix); + return count; + case GCONF_VALUE_PAIR: + return print_value(gconf_value_get_car(value), ",") + + print_value(gconf_value_get_cdr(value), suffix); + default: + throw exception(); + } + + + return 0; +} + +static void on_value_change(GConfClient* /*client*/, guint /*cnxn_id*/, GConfEntry* entry, void* /*user_data*/) { + printf("%s\t", gconf_entry_get_key(entry)); + print_value(gconf_entry_get_value(entry), "\n"); +} + +static void on_sig(int /*signal*/) { + g_main_loop_quit(loop); +} + +static gboolean err(GIOChannel* /*source*/, GIOCondition /*condition*/, gpointer /*data*/) { + g_main_loop_quit(loop); + return false; +} + +static gboolean set_key(const char *key, const char *val) { + gboolean error = false; + GConfClient *client = gconf_client_get_default(); + GConfValue *value = gconf_client_get(client, key, NULL); + GConfValueType type = value ? value->type : GCONF_VALUE_STRING; + gconf_value_free(value); + + switch (type) { + case GCONF_VALUE_STRING: + error = !gconf_client_set_string(client, key, val, NULL); + break; + case GCONF_VALUE_INT: + int ival; + error = sscanf(val, "%d", &ival) != 1; + error = error || !gconf_client_set_int(client, key, ival, NULL); + break; + case GCONF_VALUE_FLOAT: + float fval; + error = sscanf(val, "%f", &fval) != 1; + error = error || !gconf_client_set_float(client, key, fval, NULL); + break; + case GCONF_VALUE_BOOL: + error = !gconf_client_set_float(client, key, !g_strcmp0(val, "true"), NULL); + break; + case GCONF_VALUE_LIST: + case GCONF_VALUE_PAIR: + default: + g_critical("Invalid value type!"); + error = true; + } + + g_object_unref(client); + return !error; +} + +static gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) { + gchar *key, *val; + GIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL); + + // Remove the trailing '\n' + for (int i=0 ; key && key[i] ; i++) + if (key[i] == '\n') + key[i] = '\0'; + + // If we were successful + if (key && st == G_IO_STATUS_NORMAL) { + if (!g_strrstr(key, "\t")) + goto exit; + + val = g_strrstr(key, "\t") + 1; + *(val-1) = '\0'; + + if (!set_key(key, val)) + goto exit; + + g_free(key); + return true; + } + else if (key && st == G_IO_STATUS_AGAIN) { + g_free(key); + return in(source, condition, data); + } + +exit: + g_free(key); + return err(source, condition, data); +} + +int main(int argc, char **argv) { + if (argc < 2) return 1; + + // Register sighup handler + if (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) { + fprintf(stderr, "Unable to trap signals!"); + return 2; + } + + // Switch stdout to line buffering + if (setvbuf(stdout, NULL, _IOLBF, 0)) { + fprintf(stderr, "Unable to switch stdout to line buffering!"); + return 3; + } + + // Switch stdin to line buffering + if (setvbuf(stdin, NULL, _IOLBF, 0)) { + fprintf(stderr, "Unable to switch stdin to line buffering!"); + return 4; + } + + // Init + g_type_init(); + + // Get the main loop + loop = g_main_loop_new(NULL, false); + + // Setup our GIO Channels + GIOChannel* inchan = g_io_channel_unix_new(fileno(stdin)); + GIOChannel* outchan = g_io_channel_unix_new(fileno(stdout)); + g_io_add_watch(inchan, G_IO_IN, in, NULL); + g_io_add_watch(inchan, G_IO_PRI, in, NULL); + g_io_add_watch(inchan, G_IO_ERR, err, NULL); + g_io_add_watch(inchan, G_IO_HUP, err, NULL); + g_io_add_watch(outchan, G_IO_ERR, err, NULL); + g_io_add_watch(outchan, G_IO_HUP, err, NULL); + + // Get GConf client + GConfClient* client = gconf_client_get_default(); + + // Add server notifications for all keys + for (int i=1 ; i < argc ; i++) { + GConfValue *value; + gconf_client_add_dir(client, argv[i], GCONF_CLIENT_PRELOAD_NONE, NULL); + gconf_client_notify_add(client, argv[i], on_value_change, NULL, NULL, NULL); + value = gconf_client_get(client, argv[i], NULL); + if (value) { + gconf_value_free (value); + gconf_client_notify(client, argv[i]); + } else { + printf("%s\n", argv[i]); + } + } + + g_main_loop_run(loop); + + // Cleanup + g_object_unref(client); + g_io_channel_shutdown(inchan, FALSE, NULL); + g_io_channel_shutdown(outchan, FALSE, NULL); + g_io_channel_unref(inchan); + g_io_channel_unref(outchan); + g_main_loop_unref(loop); +} diff --git a/libproxy/modules/pxgsettings.cpp b/libproxy/modules/pxgsettings.cpp new file mode 100644 index 0000000..9ed4333 --- /dev/null +++ b/libproxy/modules/pxgsettings.cpp @@ -0,0 +1,175 @@ +/******************************************************************************* + * pxgsettings - A helper binary to query gsettings + * Copyright (C) 2006 Nathaniel McCallum + * Copyright (C) 2011 Dominique Leuenberger + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include +#include +#include +#include + +#include +#include +#include + +using namespace std; + +static GMainLoop* loop = NULL; + +static int print_value(GVariant *value, const char *suffix) { + + if (!value) return 0; + if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) { + return printf("%s%s", g_variant_get_string(value, NULL), suffix); + } + else if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) { + return printf("%d%s", g_variant_get_int32(value), suffix); + } + else if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) { + gboolean result; + result = g_variant_get_boolean(value); + return printf("%s%s", result ? "true" : "false", suffix); + } + else if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) { + int count; + const gchar** items; + items = g_variant_get_strv(value, NULL); + for (count=0; items[count]; count++) { + printf("%s%s", count < 1 ? "" : ",", items[count]); + } + printf("%s", suffix); + return count; + } + else { + throw exception(); + } + + return 0; +} + +static void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) { + printf("%s/%s\t", (gchar *)user_data, key); + print_value(g_settings_get_value(settings, key), "\n"); +} + +static void on_sig(int /*signal*/) { + g_main_loop_quit(loop); +} + +static gboolean err(GIOChannel* /*source*/, GIOCondition /*condition*/, gpointer /*data*/) { + g_main_loop_quit(loop); + return false; +} + +static gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) { + gchar *key, *val; + GIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL); + + // Remove the trailing '\n' + for (int i=0 ; key && key[i] ; i++) + if (key[i] == '\n') + key[i] = '\0'; + + // If we were successful + if (key && st == G_IO_STATUS_NORMAL) { + if (!g_strrstr(key, "\t")) + goto exit; + + val = g_strrstr(key, "\t") + 1; + *(val-1) = '\0'; + + g_free(key); + return true; + } + else if (key && st == G_IO_STATUS_AGAIN) { + g_free(key); + return in(source, condition, data); + } + +exit: + g_free(key); + return err(source, condition, data); +} + +int main(int argc, char **argv) { + if (argc < 2) return 1; + + // Register sighup handler + if (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) { + fprintf(stderr, "Unable to trap signals!"); + return 2; + } + + // Switch stdout to line buffering + if (setvbuf(stdout, NULL, _IOLBF, 0)) { + fprintf(stderr, "Unable to switch stdout to line buffering!"); + return 3; + } + + // Switch stdin to line buffering + if (setvbuf(stdin, NULL, _IOLBF, 0)) { + fprintf(stderr, "Unable to switch stdin to line buffering!"); + return 4; + } + + // Init +#if !GLIB_CHECK_VERSION(2,36,0) + g_type_init(); +#endif + + // Get the main loop + loop = g_main_loop_new(NULL, false); + + // Setup our GIO Channels + GIOChannel* inchan = g_io_channel_unix_new(fileno(stdin)); + GIOChannel* outchan = g_io_channel_unix_new(fileno(stdout)); + g_io_add_watch(inchan, G_IO_IN, in, NULL); + g_io_add_watch(inchan, G_IO_PRI, in, NULL); + g_io_add_watch(inchan, G_IO_ERR, err, NULL); + g_io_add_watch(inchan, G_IO_HUP, err, NULL); + g_io_add_watch(outchan, G_IO_ERR, err, NULL); + g_io_add_watch(outchan, G_IO_HUP, err, NULL); + + // Get GSettings obkecy + GSettings* settings; + + for (int i=1; i + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "../extension_wpad.hpp" +using namespace libproxy; + +class dns_alias_wpad_extension : public wpad_extension { +public: + dns_alias_wpad_extension() : lasturl(NULL), lastpac(NULL) { } + bool found() { return lastpac != NULL; } + + void rewind() { + if (lasturl) delete lasturl; + if (lastpac) delete lastpac; + lasturl = NULL; + lastpac = NULL; + } + + url* next(char** pac) { + if (lasturl) return NULL; + + lasturl = new url("http://wpad/wpad.dat"); + lastpac = *pac = lasturl->get_pac(); + if (!lastpac) { + delete lasturl; + lasturl = NULL; + return NULL; + } + + return lasturl; + } + +private: + url* lasturl; + char* lastpac; +}; + +MM_MODULE_INIT_EZ(dns_alias_wpad_extension, true, NULL, NULL); diff --git a/libproxy/proxy.cpp b/libproxy/proxy.cpp new file mode 100644 index 0000000..17e330b --- /dev/null +++ b/libproxy/proxy.cpp @@ -0,0 +1,488 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include +#include // For strdup() +#include // For cerr +#include // For exception +#include // Only for debug messages. + +#include + +#include "extension_config.hpp" +#include "extension_ignore.hpp" +#include "extension_network.hpp" +#include "extension_pacrunner.hpp" +#include "extension_wpad.hpp" + +#ifdef WIN32 +#define strdup _strdup +#endif + +#define X(m) MM_DEF_BUILTIN(m); +BUILTIN_MODULES +#undef X + +#define X(m) &MM_BUILTIN(m), +static struct mm_module* builtin_modules[] = { + BUILTIN_MODULES + NULL +}; +#undef X + +namespace libproxy { +using namespace std; + +class proxy_factory { +public: + proxy_factory(); + ~proxy_factory(); + vector get_proxies(string url); + +private: + void lock(); + void unlock(); + + void check_network_topology(); + void get_config(url &realurl, vector &configs, string &ignore); + bool is_ignored(url &realurl, const string &ignore); + bool expand_wpad(const url &confurl); + bool expand_pac(url &configurl); + void run_pac(url &realurl, const url &confurl, vector &response); + void clear_cache(); + +#ifdef WIN32 + HANDLE mutex; +#else + pthread_mutex_t mutex; +#endif + module_manager mm; + char* pac; + url* pacurl; + bool wpad; + bool debug; +}; + +static bool istringcmp(string a, string b) { + transform( a.begin(), a.end(), a.begin(), ::tolower ); + transform( b.begin(), b.end(), b.begin(), ::tolower ); + return ( a == b ); +} + +// Convert the PAC formatted response into our proxy URL array response +static void format_pac_response(string response, vector &retval) +{ + // Skip ahead one character if we start with ';' + if (response[0] == ';') { + format_pac_response(response.substr(1), retval); + return; + } + + // If the string contains a delimiter (';') + if (response.find(';') != string::npos) { + format_pac_response(response.substr(response.find(';') + 1), retval); + response = response.substr(0, response.find(';')); + } + + // Strip whitespace + if (response.size() > 0) + response = response.substr(response.find_first_not_of(" \t\n"), response.find_last_not_of(" \t\n")+1); + + // Get the method and the server + string method = ""; + string server = ""; + if (response.find_first_of(" \t") == string::npos) + method = response; + else { + method = response.substr(0, response.find_first_of(" \t")); + server = response.substr(response.find_first_of(" \t") + 1); + } + + // Insert our url value + if (istringcmp(method, "proxy") && url::is_valid("http://" + server)) + retval.insert(retval.begin(), string("http://") + server); + else if (istringcmp(method, "socks") && url::is_valid("http://" + server)) + retval.insert(retval.begin(), string("socks://") + server); + else if (istringcmp(method, "socks4") && url::is_valid("http://" + server)) + retval.insert(retval.begin(), string("socks4://") + server); + else if (istringcmp(method, "socks4a") && url::is_valid("http://" + server)) + retval.insert(retval.begin(), string("socks4a://") + server); + else if (istringcmp(method, "socks5") && url::is_valid("http://" + server)) + retval.insert(retval.begin(), string("socks5://") + server); + else if (istringcmp(method, "direct")) + retval.insert(retval.begin(), string("direct://")); +} + +proxy_factory::proxy_factory() { + const char *module_dir; + +#ifdef WIN32 + this->mutex = CreateMutex(NULL, false, NULL); + WSADATA wsadata; + WORD vers = MAKEWORD(2, 2); + WSAStartup(vers, &wsadata); +#else + pthread_mutex_init(&this->mutex, NULL); +#endif + + lock(); + + this->pac = NULL; + this->pacurl = NULL; + this->wpad = false; + + // Register our types + this->mm.register_type(); + this->mm.register_type(); + this->mm.register_type(); + this->mm.register_type(); + this->mm.register_type(); + + // Load builtin modules + for (int i=0 ; builtin_modules[i] ; i++) + this->mm.load_builtin(builtin_modules[i]); + + // Load all modules + module_dir = getenv("PX_MODULE_PATH"); + if (!module_dir) + module_dir = MODULEDIR; + this->mm.load_dir(module_dir); + this->mm.load_dir(module_dir, false); + + this->debug = (getenv("_PX_DEBUG") != NULL); + + unlock(); +} + +proxy_factory::~proxy_factory() { + lock(); + + if (this->pac) delete[] this->pac; + if (this->pacurl) delete this->pacurl; + + unlock(); + +#ifdef WIN32 + WSACleanup(); + ReleaseMutex(this->mutex); +#else + pthread_mutex_destroy(&this->mutex); +#endif +} + + +vector proxy_factory::get_proxies(string realurl) { + vector response; + + // Check to make sure our url is valid + if (!url::is_valid(realurl)) + goto do_return; + + lock(); + + // Let trap and forward exceptions so we don't deadlock + try { + vector configs; + string ignore; + url dst(realurl); + + check_network_topology(); + get_config(dst, configs, ignore); + + if (debug) cerr << "Config is: " << endl; + + for (vector::iterator i=configs.begin() ; i != configs.end() ; i++) { + url confurl(*i); + + if (debug) cerr << "\t" << confurl.to_string() << endl; + + if (expand_wpad(confurl) || expand_pac(confurl)) { + run_pac(dst, confurl, response); + } else { + clear_cache(); + response.push_back(confurl.to_string()); + } + } + + unlock(); + } catch (exception &e) { + unlock(); + throw e; + } + +do_return: + if (response.size() == 0) + response.push_back("direct://"); + return response; +} + +void proxy_factory::check_network_topology() { + vector networks; + + // Check to see if our network topology has changed... + networks = this->mm.get_extensions(); + for (vector::iterator i=networks.begin() ; i != networks.end() ; i++) { + // If it has, reset our wpad/pac setup and we'll retry our config + if ((*i)->changed()) { + if (debug) cerr << "Network changed" << endl; + vector wpads = this->mm.get_extensions(); + for (vector::iterator j=wpads.begin() ; j != wpads.end() ; j++) + (*j)->rewind(); + if (this->pac) delete this->pac; + this->pac = NULL; + break; + } + } +} + +void proxy_factory::get_config(url &realurl, vector &config, string &ignore) { + vector configs; + + configs = this->mm.get_extensions(); + for (vector::iterator i=configs.begin() ; i != configs.end() ; i++) { + config_extension *configurator = *i; + + // Try to get the configuration + try { + ignore = configurator->get_ignore(realurl); + if (!is_ignored(realurl, ignore)) + config = configurator->get_config(realurl); + if (debug) { + if (configurator) { + cerr << "Configuration extension is: " << typeid(*configurator).name() << endl; + cerr << "Ignored list is: " << ignore << endl; + } else { + cerr << "No configuration extension found." << endl; + } + } + break; + } + catch (runtime_error e) { + ignore = ""; + } + } +} + +bool proxy_factory::is_ignored(url &realurl, const string &ignore) { + vector ignores; + bool ignored = false, invign = false; + string confign = ignore; + + /* Check our ignore patterns */ + ignores = this->mm.get_extensions(); + invign = confign.size() > 0 && confign[0] == '-'; + if (invign) confign = confign.substr(1); + for (size_t i=0 ; i < confign.size() && !ignored;) { + size_t next = confign.find(',', i); + if (next == string::npos) next = confign.length(); + if (next > (i+1)) { + string ignorestr = confign.substr (i, next - i); + ignorestr = ignorestr.substr(ignorestr.find_first_not_of(" \t\n"), ignorestr.find_last_not_of(" \t\n")+1); + for (vector::iterator it=ignores.begin() ; it != ignores.end() && !ignored ; it++) + ignored = ((*it)->ignore(realurl, ignorestr)); + } + i = next+1; + } + + if (invign) + return !ignored; + else + return ignored; +} + +bool proxy_factory::expand_wpad(const url &confurl) +{ + bool rtv = false; + if (confurl.get_scheme() == "wpad") { + rtv = true; + /* If the config has just changed from PAC to WPAD, clear the PAC */ + if (!this->wpad) { + if (this->pac) delete this->pac; + if (this->pacurl) delete this->pacurl; + this->pac = NULL; + this->pacurl = NULL; + this->wpad = true; + } + + /* If we have no PAC, get one */ + if (!this->pac) { + if (debug) cerr << "Trying to find the PAC using WPAD..." << endl; + vector wpads = this->mm.get_extensions(); + for (vector::iterator i=wpads.begin() ; i != wpads.end() ; i++) { + if (debug) cerr << "WPAD search via: " << typeid(**i).name() << endl; + if ((this->pacurl = (*i)->next(&this->pac))) { + if (debug) cerr << "PAC found!" << endl; + break; + } + } + + /* If getting the PAC fails, but the WPAD cycle worked, restart the cycle */ + if (!this->pac) { + if (debug) cerr << "No PAC found..." << endl; + for (vector::iterator i=wpads.begin() ; i != wpads.end() ; i++) { + if ((*i)->found()) { + if (debug) cerr << "Resetting WPAD search..." << endl; + + /* Since a PAC was found at some point, + * rewind all the WPADS to start from the beginning */ + /* Yes, the reuse of 'i' here is intentional... + * This is because if *any* of the wpads have found a pac, + * we need to reset them all to keep consistent state. */ + for (i=wpads.begin() ; i != wpads.end() ; i++) + (*i)->rewind(); + + // Attempt to find a PAC + for (i=wpads.begin() ; i != wpads.end() ; i++) { + if (debug) cerr << "WPAD search via: " << typeid(**i).name() << endl; + if ((this->pacurl = (*i)->next(&this->pac))) { + if (debug) cerr << "PAC found!" << endl; + break; + } + } + break; + } + } + } + } + } + + return rtv; +} + +bool proxy_factory::expand_pac(url &confurl) +{ + bool rtv = false; + + // If we have a PAC config + if (confurl.get_scheme().substr(0, 4) == "pac+") { + rtv = true; + + /* Save the PAC config */ + if (this->wpad) + this->wpad = false; + + /* If a PAC already exists, but came from a different URL than the one specified, remove it */ + if (this->pac) { + if (this->pacurl->to_string() != confurl.to_string()) { + delete this->pacurl; + delete this->pac; + this->pacurl = NULL; + this->pac = NULL; + } + } + + /* Try to load the PAC if it is not already loaded */ + if (!this->pac) { + this->pacurl = new url(confurl); + this->pac = confurl.get_pac(); + if (debug) { + if (!this->pac) + cerr << "Unable to download PAC!" << endl; + else + cerr << "PAC received!" << endl; + } + } + } + + return rtv; +} + +void proxy_factory::run_pac(url &realurl, const url &confurl, vector &response) { + /* In case of either PAC or WPAD, we'll run the PAC */ + if (this->pac && (confurl.get_scheme() == "wpad" || confurl.get_scheme().substr(0, 4) == "pac+") ) { + vector pacrunners = this->mm.get_extensions(); + + /* No PAC runner found, fall back to direct */ + if (pacrunners.size() == 0) { + if (debug) cerr << "Unable to find a required pacrunner!" << endl; + return; + } + + /* Run the PAC, but only try one PACRunner */ + if (debug) cerr << "Using pacrunner: " << typeid(*pacrunners[0]).name() << endl; + string pacresp = pacrunners[0]->get(this->pac, this->pacurl->to_string())->run(realurl); + if (debug) cerr << "Pacrunner returned: " << pacresp << endl; + format_pac_response(pacresp, response); + } +} + +void proxy_factory::clear_cache() { + this->wpad = false; + if (this->pac) { delete this->pac; this->pac = NULL; } + if (this->pacurl) { delete this->pacurl; this->pacurl = NULL; } +} + +void proxy_factory::lock() { +#ifdef WIN32 + WaitForSingleObject(this->mutex, INFINITE); +#else + pthread_mutex_lock(&this->mutex); +#endif +} + +void proxy_factory::unlock() { +#ifdef WIN32 + ReleaseMutex(this->mutex); +#else + pthread_mutex_unlock(&this->mutex); +#endif +} + +}; + +struct pxProxyFactory_ { + libproxy::proxy_factory pf; +}; + +extern "C" DLL_PUBLIC struct pxProxyFactory_ *px_proxy_factory_new(void) { + return new struct pxProxyFactory_; +} + +extern "C" DLL_PUBLIC char** px_proxy_factory_get_proxies(struct pxProxyFactory_ *self, const char *url) { + std::vector proxies; + char** retval; + + // Call the main method + try { + proxies = self->pf.get_proxies(url); + retval = (char**) malloc(sizeof(char*) * (proxies.size() + 1)); + if (!retval) return NULL; + } catch (std::exception&) { + // Return NULL on any exception + return NULL; + } + + // Copy the results into an array + // Return NULL on memory allocation failure + retval[proxies.size()] = NULL; + for (size_t i=0 ; i < proxies.size() ; i++) { + retval[i] = strdup(proxies[i].c_str()); + if (retval[i] == NULL) { + for (int j=i-1 ; j >= 0 ; j--) + free(retval[j]); + free(retval); + return NULL; + } + } + return retval; +} + +extern "C" DLL_PUBLIC void px_proxy_factory_free(struct pxProxyFactory_ *self) { + delete self; +} diff --git a/libproxy/proxy.h b/libproxy/proxy.h new file mode 100644 index 0000000..fb8275b --- /dev/null +++ b/libproxy/proxy.h @@ -0,0 +1,102 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef PROXY_H_ +#define PROXY_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef struct pxProxyFactory_ pxProxyFactory; + +/** + * Creates a new pxProxyFactory instance. This instance should be kept + * around as long as possible as it contains cached data to increase + * performance. Memory usage should be minimal (cache is small) and the + * cache lifespan is handled automatically. + * + * @return A new pxProxyFactory instance or NULL on error + */ +pxProxyFactory *px_proxy_factory_new(void); + +/** + * Get which proxies to use for the specified URL. + * + * A NULL-terminated array of proxy strings is returned. + * If the first proxy fails, the second should be tried, etc... + * Don't forget to free the strings/array when you are done. + * If an unrecoverable error occurs, this function returns NULL. + * + * Regarding performance: this method always blocks and may be called + * in a separate thread (is thread-safe). In most cases, the time + * required to complete this function call is simply the time required + * to read the configuration (i.e. from gconf, kconfig, etc). + * + * In the case of PAC, if no valid PAC is found in the cache (i.e. + * configuration has changed, cache is invalid, etc), the PAC file is + * downloaded and inserted into the cache. This is the most expensive + * operation as the PAC is retrieved over the network. Once a PAC exists + * in the cache, it is merely a javascript invocation to evaluate the PAC. + * One should note that DNS can be called from within a PAC during + * javascript invocation. + * + * In the case of WPAD, WPAD is used to automatically locate a PAC on the + * network. Currently, we only use DNS for this, but other methods may + * be implemented in the future. Once the PAC is located, normal PAC + * performance (described above) applies. + * + * The format of the returned proxy strings are as follows: + * - http://[username:password@]proxy:port + * - socks://[username:password@]proxy:port + * - socks5://[username:password@]proxy:port + * - socks4://[username:password@]proxy:port + * - ://[username:password@]proxy:port + * - direct:// + * Please note that the username and password in the above URLs are optional + * and should be use to authenticate the connection if present. + * + * For SOCKS proxies, when the protocol version is specified (socks4:// or + * sock5://), it is expected that only this version is used. When only + * socks:// is set, the client MUST try SOCKS version 5 protocol and, on + * connection failure, fallback to SOCKS version 4. + * + * Other proxying protocols may exist. It is expected that the returned + * configuration scheme shall match the network service name of the + * proxy protocol or the service name of the protocol being proxied if the + * previous does not exist. As an example, on Mac OS X you can configure a + * RTSP streaming proxy. The expected returned configuration would be: + * - rtsp://[username:password@]proxy:port + * + * @url The URL we are trying to reach + * @return A NULL-terminated array of proxy strings to use + */ +char **px_proxy_factory_get_proxies(pxProxyFactory *self, const char *url); + +/** + * Frees the pxProxyFactory instance when no longer used. + */ +void px_proxy_factory_free(pxProxyFactory *self); + +#ifdef __cplusplus +} +#endif + +#endif /*PROXY_H_*/ diff --git a/libproxy/test/CMakeLists.txt b/libproxy/test/CMakeLists.txt new file mode 100644 index 0000000..8894425 --- /dev/null +++ b/libproxy/test/CMakeLists.txt @@ -0,0 +1,26 @@ +#### +## Libproxy Tests +#### + +include_directories(${PROJECT_SOURCE_DIR}) + +# URL Test +add_executable(url-test ${CMAKE_CURRENT_SOURCE_DIR}/url-test.cpp ${PROJECT_SOURCE_DIR}/url.cpp) +if(WIN32) + target_link_libraries(url-test ws2_32) +endif() +add_test(NAME url-test COMMAND ${CMAKE_CURRENT_BINARY_DIR}/url-test) + +# URL Encode +add_executable(url-encode ${CMAKE_CURRENT_SOURCE_DIR}/url-encode.cpp ${PROJECT_SOURCE_DIR}/url.cpp) +if(WIN32) + target_link_libraries(url-encode ws2_32) +endif() +add_test(NAME url-encode COMMAND ${CMAKE_CURRENT_BINARY_DIR}/url-encode) + +# Get PAC +if (NOT WIN32) +add_executable(get-pac-test ${CMAKE_CURRENT_SOURCE_DIR}/get-pac-test.cpp ${PROJECT_SOURCE_DIR}/url.cpp) +target_link_libraries(get-pac-test pthread) +add_test(NAME get-pac-test COMMAND ${CMAKE_CURRENT_BINARY_DIR}/get-pac-test) +endif() diff --git a/libproxy/test/get-pac-test.cpp b/libproxy/test/get-pac-test.cpp new file mode 100644 index 0000000..00b4564 --- /dev/null +++ b/libproxy/test/get-pac-test.cpp @@ -0,0 +1,316 @@ +#include +#include +#include +#include + +#include // for abort() +#include // for EINTR +#include +#include +#include +#include +#include +#include +#include +#include + +#include "url.hpp" + +// macOS does not define MSG_NOSIGNAL, but uses the SO_NOSIGPIPE option instead +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#endif + +using namespace libproxy; + +class TestServer { + public: + TestServer(in_port_t port) + : m_port(port) + ,m_sock(-1) + + { + m_pipe[0] = -1; + m_pipe[1] = -1; + } + + void start() + { + struct sockaddr_in addr = {0}; + int ret; + int i = 1; + + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = inet_addr("127.0.0.1"); + addr.sin_port = ntohs(m_port); + + if (m_sock != -1) + return; + + m_sock = socket(AF_INET, SOCK_STREAM, 0); + assert(m_sock > 0); + + setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i)); + + ret = bind(m_sock, (sockaddr*)&addr, sizeof (struct sockaddr_in)); + assert(!ret); + + ret = listen(m_sock, 1); + assert(!ret); + + ret = pipe(m_pipe); + assert(!ret); + + ret = pthread_create(&m_thread, NULL, TestServer::server_thread, this); + assert(!ret); + } + + void stop() + { + int ret; + do + { + ret = write(m_pipe[1], (void*)"q", 1); + } while (errno == EINTR); + if (ret < 0) abort(); // We could not write to the pipe anymore + pthread_join (m_thread, NULL); + close(m_pipe[1]); + m_pipe[1] = -1; + close(m_sock); + m_sock = -1; + } + + private: + static void * server_thread(void *data) + { + TestServer *server = (TestServer*)data; + while (server->loop()) {} + return NULL; + } + + bool loop() + { + int ret; + fd_set fds; + struct sockaddr_in addr; + int lf_count = 0; + bool done = false; + char buffer[1024]; + char *ptr; + int csock; + socklen_t len = sizeof (struct sockaddr_in); + + FD_ZERO (&fds); + FD_SET (m_pipe[0], &fds); + FD_SET (m_sock, &fds); + + memset(buffer, 0, 1024); + + // Wait for connection + ret = select(max(m_pipe[0], m_sock) + 1, &fds, NULL, NULL, NULL); + assert(ret > 0); + + if (FD_ISSET (m_pipe[0], &fds)) { + close(m_pipe[0]); + m_pipe[0] = -1; + + return false; + } + + csock = accept(m_sock, (sockaddr*) &addr, &len); + assert(csock > 0); + // OSX/BSD may not have MSG_NOSIGNAL, try SO_NOSIGPIPE instead +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#ifdef SO_NOSIGPIPE + int no_sig_pipe = 1; + setsockopt(csock, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, sizeof(int)); +#endif +#endif + +#ifdef SO_NOSIGPIPE + int i = 1; + setsockopt(c_sock, SOL_SOCKET, SO_NOSIGPIPE, &i, sizeof(i)); +#endif + + // Read request + ptr = buffer; + do { + ret = recv (csock, ptr, 1, 0); + if (ret <= 0) + goto done; + + if (*ptr == '\n') { + lf_count++; + } else if (*ptr != '\r') { + lf_count = 0; + } + + if (lf_count == 2) + done = true; + + ptr++; + assert((int) (ptr - buffer) < 1024); + } while (!done); + + if (strstr(buffer, "basic")) { + sendBasic(csock); + } else if (strstr(buffer, "truncated")) { + sendTruncated(csock); + } else if (strstr(buffer, "overflow")) { + sendOverflow(csock); + } else if (strstr(buffer, "chunked")) { + sendChunked(csock); + } else if (strstr(buffer, "without_content_length")) { + sendWithoutContentLength(csock); + } else if (strstr(buffer, "parameterized")) { + assert(strstr(buffer, "?arg1=foo&arg2=bar") != NULL); + sendBasic(csock); + } else { + assert(!"Unsupported request"); + } + +done: + close(csock); + return true; + } + + void sendBasic(int csock) + { + int ret; + const char *basic = + "HTTP/1.1 200 OK\n" \ + "Content-Type: text/plain\n" \ + "Content-Length: 10\n" \ + "\n" \ + "0123456789"; + ret = send(csock, (void*)basic, strlen(basic), 0); + assert(ret == strlen(basic)); + shutdown(csock, SHUT_RDWR); + close(csock); + } + + void sendTruncated(int csock) + { + int ret; + const char *basic = + "HTTP/1.1 200 OK\n" \ + "Content-Type: text/plain\n" \ + "Content-Length: 10\n" \ + "\n" \ + "01234"; + ret = send(csock, (void*)basic, strlen(basic), 0); + assert(ret == strlen(basic)); + shutdown(csock, SHUT_RDWR); + close(csock); + } + + void sendOverflow(int csock) + { + int ret; + int size = 50000000; // Must be larger than the kernel TCP receive buffer + char *buf = new char[size]; + memset(buf, 1, size); + + const char *basic = + "HTTP/1.1 200 OK\n" \ + "Content-Type: text/plain\n" \ + "Content-Length: 50000000\n" \ + "\n"; + ret = send(csock, (void*)basic, strlen(basic), MSG_NOSIGNAL); + assert(ret == strlen(basic)); + ret = send(csock, (void*)buf, size, MSG_NOSIGNAL); + if (ret == size) + abort(); // Test failed... the socket should not accept the whole buffer + delete[] buf; + shutdown(csock, SHUT_RDWR); + close(csock); + } + + void sendChunked(int csock) + { + int ret; + const char *chunked = + "HTTP/1.1 200 OK\n" \ + "Content-Type: text/plain\n" \ + "Transfer-Encoding: chunked\n" \ + "\n" \ + "5\n" \ + "01234" \ + "\n" \ + "5\n" \ + "56789" \ + "\n"; + ret = send(csock, (void*)chunked, strlen(chunked), 0); + assert(ret == strlen(chunked)); + shutdown(csock, SHUT_RDWR); + close(csock); + } + + void sendWithoutContentLength(int csock) + { + int ret; + const char *basic = + "HTTP/1.1 200 OK\n" \ + "Content-Type: text/plain\n" \ + "\n" \ + "0123456789"; + ret = send(csock, (void*)basic, strlen(basic), 0); + assert(ret == strlen(basic)); + shutdown(csock, SHUT_RDWR); + close(csock); + } + + in_port_t m_port; + int m_sock; + int m_pipe[2]; + pthread_t m_thread; +}; + + +int main() +{ + TestServer server(1983); + int rtv = 0; + char *pac; + + url basic("http://localhost:1983/basic.js"); + url truncated("http://localhost:1983/truncated.js"); + url overflow("http://localhost:1983/overflow.js"); + url chunked("http://localhost:1983/chunked.js"); + url without_content_length("http://localhost:1983/without_content_length.js"); + url parameterized("http://localhost:1983/parameterized.js?arg1=foo&arg2=bar"); + + server.start(); + + pac = basic.get_pac(); + if (!(pac != NULL && strlen(pac) == 10 && !strcmp("0123456789", pac))) + return 1; // test failed, exit with error code + delete[] pac; // test succesful, cleanup + + pac = truncated.get_pac(); + if (pac != NULL) + return 2; // Test failed, exit with error code + + pac = overflow.get_pac(); + if (pac != NULL) + return 3; // Test failed, exit with error code + + pac = chunked.get_pac(); + if (!(pac != NULL && strlen(pac) == 10 && !strcmp("0123456789", pac))) + return 4; // Test failed, exit with error code + + pac = without_content_length.get_pac(); + if (!(pac != NULL && strlen(pac) == 10 && !strcmp("0123456789", pac))) + return 5; // Test failed, exit with error code + delete[] pac; + + pac = parameterized.get_pac(); + if (!(pac != NULL && strlen(pac) == 10 && !strcmp("0123456789", pac))) + return 5; // Test failed, exit with error code + delete[] pac; + + server.stop(); + + return 0; +} diff --git a/libproxy/test/url-encode.cpp b/libproxy/test/url-encode.cpp new file mode 100644 index 0000000..e37383a --- /dev/null +++ b/libproxy/test/url-encode.cpp @@ -0,0 +1,29 @@ +#include +#include +#include + + +#include "url.hpp" + +using namespace libproxy; + +#define test(cond,rtv) _test(#cond, (cond), (rtv)) +void _test (string exp, bool condition, bool &rtv) +{ + if (!condition) { + cerr << "Failed: " << exp << endl; + rtv = false; + } +} + +int main() +{ + bool rtv = true; + string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; + + test(url::encode(valid) == valid, rtv); + test(url::encode("é") == "%c3%a9", rtv); + test(url::encode("+!@#$^\r%", "!#^") == "%2b!%40#%24^%0d%25", rtv); + + return !rtv; +} diff --git a/libproxy/test/url-test.cpp b/libproxy/test/url-test.cpp new file mode 100644 index 0000000..f5ede04 --- /dev/null +++ b/libproxy/test/url-test.cpp @@ -0,0 +1,175 @@ +#include +#include +#include +#include + + +#include "url.hpp" + +using namespace libproxy; + +void assert_equal_str (const std::string &what, + const std::string &in, + const std::string &value, + const std::string &ref) +{ + if (value != ref) + throw logic_error(what + " in URL " + in + " is '" + + value + "' instead of '" + ref + "'"); +} + +void assert_equal_int (const std::string &what, + const std::string &in, + int value, + int ref) +{ + if (value != ref) { + ostringstream s; + s << what << " in URL " << in << " is " + << value << " instead of " << ref; + throw logic_error(s.str()); + } +} + +void try_url (std::string link, bool &rtv, + const std::string &scheme, + const std::string &user, + const std::string &pass, + const std::string &host, + int port, + const std::string &path) +{ + try { + url u(link); + + assert_equal_str ("Scheme", u.to_string(), u.get_scheme(), scheme); + assert_equal_str ("User", u.to_string(), u.get_username(), user); + assert_equal_str ("Pass", u.to_string(), u.get_password(), pass); + assert_equal_str ("Host", u.to_string(), u.get_host(), host); + assert_equal_int ("Port", u.to_string(), u.get_port(), port); + assert_equal_str ("Path", u.to_string(), u.get_path(), path); + } + catch (exception &e) { + std::cerr << e.what() << std::endl; + rtv = false; + } +} + +int main() +{ + bool rtv = true; + +#ifdef WIN32 + WSADATA wsadata; + WORD vers = MAKEWORD(2, 2); + WSAStartup(vers, &wsadata); +#endif + + try_url ("file:///allo", rtv, + "file", + "", "", + "", 0, + "/allo"); + + try_url ("http://test.com", rtv, + "http", + "", "", + "test.com", 80, + ""); + + try_url ("http://test.com/", rtv, + "http", + "", "", + "test.com", 80, + "/"); + + try_url ("http://test.com#", rtv, + "http", + "", "", + "test.com", 80, + ""); + + try_url ("http://test.com?", rtv, + "http", + "", "", + "test.com", 80, + ""); + + try_url ("http://nicolas@test.com", rtv, + "http", + "nicolas", "", + "test.com", 80, + ""); + + try_url ("http://nicolas:@test.com", rtv, + "http", + "nicolas", "", + "test.com", 80, + ""); + + try_url ("http://nicolas:secret@test.com", rtv, + "http", + "nicolas", "secret", + "test.com", 80, + ""); + + try_url ("http://:secret@test.com", rtv, + "http", + "", "secret", + "test.com", 80, + ""); + + try_url ("http+ssh://:secret@test.com", rtv, + "http+ssh", + "", "secret", + "test.com", 22, + ""); + + try_url ("HtTp://TeSt.CoM/ALLO", rtv, + "http", + "", "", + "test.com", 80, + "/ALLO"); + + /* This is a very uncommon but valid case that use to cause crash */ + try_url ("www.google.com:80", rtv, + "www.google.com", + "", "", + "", 0, + "80"); + + /* Handle the case where there is nothing other than the scheme */ + try_url ("http://", rtv, + "http", + "", "", + "", 80, + ""); + + /* Check windows style URL */ + try_url ("file:///E:/dir/file.pac", rtv, + "file", + "", "", + "", 0, +#ifdef WIN32 + "E:\\dir\\file.pac"); +#else + "/E:/dir/file.pac"); +#endif + + /* UNC windows URL */ + try_url ("file://server/dir/file.pac", rtv, + "file", + "", "", + "server", 0, +#ifdef WIN32 + "\\\\server\\dir\\file.pac"); +#else + "/dir/file.pac"); +#endif + +#ifdef WIN32 + WSACleanup(); +#endif + + return !rtv; +} diff --git a/libproxy/url.cpp b/libproxy/url.cpp new file mode 100644 index 0000000..b61a9bc --- /dev/null +++ b/libproxy/url.cpp @@ -0,0 +1,532 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * Based on work found in GLib GIO: + * Copyright (C) 2006-2007 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + ******************************************************************************/ +#ifdef WIN32 +#include +#define open _open +#define O_RDONLY _O_RDONLY +#define close _close +#endif +#include // For ::open() +#include // For memcpy() +#include // For int/string conversion (using stringstream) +#include // For sscanf() +#include // For atoi() +#include // For stat() +#include // For transform() +#include // For read() close() + +#ifdef WIN32 +#include +#define close _close +#define read _read +#define SHUT_RDWR SD_BOTH +#endif + +#include "url.hpp" +using namespace libproxy; +using namespace std; + +// This mime type should be reported by the web server +#define PAC_MIME_TYPE "application/x-ns-proxy-autoconfig" +// Fall back to checking for this mime type, which servers often report wrong +#define PAC_MIME_TYPE_FB "text/plain" + +// This is the maximum pac size (to avoid memory attacks) +#define PAC_MAX_SIZE 102400 +// This is the default block size to use when receiving via HTTP +#define PAC_HTTP_BLOCK_SIZE 512 + +static inline int get_default_port(string scheme) { + struct servent *serv; + size_t plus = scheme.find('+'); + + if (plus != string::npos) + scheme = scheme.substr(plus + 1); + + if ((serv = getservbyname(scheme.c_str(), NULL))) + return ntohs(serv->s_port); + + return 0; +} + +template +static inline string to_string_ (const T& t) { + stringstream ss; + ss << t; + return ss.str(); +} + +#define _copyaddr_t(type, addr) (sockaddr*) memcpy(new type, &(addr), sizeof(type)) +static inline sockaddr* copyaddr(const struct sockaddr& addr) { + switch (addr.sa_family) { + case (AF_INET): + return _copyaddr_t(sockaddr_in, addr); + case (AF_INET6): + return _copyaddr_t(sockaddr_in6, addr); + default: + return NULL; + } +} + +bool url::is_valid(const string url_) { + bool rtv = true; + + try { + url url(url_); + } catch (parse_error&) { + rtv = false; + } + + return rtv; +} + +string url::encode(const string &data, const string &valid_reserved) { + ostringstream encoded; + for (unsigned int i=0; i < data.size(); i++) { + if (isalnum((unsigned char)data[i]) + || valid_reserved.find(data[i]) != string::npos + || string("-._~").find(data[i]) != string::npos) + encoded << data[i]; + else + encoded << '%' + << ((unsigned char)data[i] < 16 ? "0" : "") + << hex << (((int)data[i]) & 0xff); + } + return encoded.str(); +} + +url::url(const string &url) throw(parse_error) + : m_orig(url), m_port(0), m_ips(NULL) { + size_t idx = 0; + size_t hier_part_start, hier_part_end; + size_t query_part_start; + size_t path_start, path_end; + string hier_part; + + /* From RFC 3986 Decodes: + * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] + */ + + idx = 0; + + /* Decode scheme: + * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + */ + + if (!isalpha(url[idx])) + throw parse_error("Invalid URL: " + url); + + while (1) { + char c = url[idx++]; + + if (c == ':') break; + + if (!(isalnum(c) || + c == '+' || + c == '-' || + c == '.')) + throw parse_error("Invalid URL: " + url); + } + + m_scheme = url.substr(0, idx - 1); + transform(m_scheme.begin(), m_scheme.end(), m_scheme.begin(), ::tolower); + + hier_part_start = idx; + hier_part_end = url.find('#', idx); + query_part_start = url.find('?', idx); + if (query_part_start != string::npos) + { + if (hier_part_end == string::npos) + m_query = url.substr(query_part_start); + else { + m_query = url.substr(query_part_start, hier_part_end - query_part_start); + } + hier_part_end = query_part_start; + } + + hier_part = url.substr(hier_part_start, + hier_part_end == string::npos ? + string::npos : hier_part_end - hier_part_start); + + /* 3: + * hier-part = "//" authority path-abempty + * / path-absolute + * / path-rootless + * / path-empty + */ + + if (hier_part.size() >= 2 && hier_part[0] == '/' && hier_part[1] == '/') { + size_t authority_start, authority_end; + size_t userinfo_start, userinfo_end; + size_t host_start, host_end; + + authority_start = 2; + /* authority is always followed by / or nothing */ + authority_end = hier_part.find('/', authority_start); + if (authority_end == string::npos) + authority_end = hier_part.size(); + path_start = authority_end; + + /* 3.2: + * authority = [ userinfo "@" ] host [ ":" port ] + */ + + /* Get user and password */ + userinfo_start = authority_start; + userinfo_end = hier_part.find('@', authority_start); + if (userinfo_end != string::npos) { + size_t user_end; + + user_end = hier_part.rfind(':', userinfo_end); + if (user_end == string::npos) + user_end = userinfo_end; + else + m_pass = hier_part.substr(user_end + 1, userinfo_end - (user_end + 1)); + + m_user = hier_part.substr(userinfo_start, user_end - userinfo_start); + } + + /* Get hostname */ + if (userinfo_end == string::npos) + host_start = authority_start; + else + host_start = userinfo_end + 1; + + /* Check for IPv6 IP */ + if (host_start < hier_part.size() + && hier_part[host_start] == '[') { + host_end = hier_part.find(']', host_start); + if (host_end == string::npos) + throw parse_error("Invalid URL: " + url); + host_end++; + if (hier_part[host_end] == '\0') + host_end = string::npos; + } else { + host_end = hier_part.find(':', host_start); + if (path_start < host_end) + host_end = path_start; + } + + /* If not port, host ends where path starts */ + if (host_end == string::npos) + host_end = path_start; + + m_host = hier_part.substr(host_start, host_end - host_start); + transform(m_host.begin(), m_host.end(), m_host.begin(), ::tolower); + + /* Get port */ + m_port = get_default_port(m_scheme); + + if (host_end < hier_part.size() + && hier_part[host_end] == ':') { + size_t port_start = host_end + 1; + m_port = atoi(hier_part.c_str() + port_start); + } + } else { + path_start = 0; + } + + /* Get path */ + if (path_start != string::npos) + { + path_end = hier_part_end; + if (path_end == string::npos) + m_path = hier_part.substr(path_start); + else + m_path = hier_part.substr(path_start, path_end - path_start); + } +} + +url::url(const url &url) : m_ips(NULL) { + *this = url; +} + +url::~url() { + empty_cache(); +} + +bool url::operator==(const url& url) const { + return m_orig == url.to_string(); +} + +url& url::operator=(const url& url) { + // Ensure these aren't the same objects + if (&url == this) + return *this; + + m_host = url.m_host; + m_orig = url.m_orig; + m_pass = url.m_pass; + m_path = url.m_path; + m_query = url.m_query; + m_port = url.m_port; + m_scheme = url.m_scheme; + m_user = url.m_user; + + empty_cache(); + + if (url.m_ips) { + int i; + + // Copy the new ip cache + for (i=0 ; url.m_ips[i] ; i++) {}; + m_ips = new sockaddr*[i]; + for (i=0 ; url.m_ips[i] ; i++) + m_ips[i] = copyaddr(*url.m_ips[i]); + } + + return *this; +} + +url& url::operator=(string strurl) throw (parse_error) { + url tmp(strurl); + *this = tmp; + return *this; +} + +string url::get_host() const { + return m_host; +} + +sockaddr const* const* url::get_ips(bool usedns) { + // Check the cache + if (m_ips) + return m_ips; + + // Check without DNS first + if (usedns && get_ips(false)) + return m_ips; + + // Check DNS for IPs + struct addrinfo* info; + struct addrinfo flags; + memset(&flags, '\0', sizeof(addrinfo)); + flags.ai_family = AF_UNSPEC; + flags.ai_socktype = 0; + flags.ai_protocol = 0; + flags.ai_flags = AI_NUMERICHOST; + if (!getaddrinfo(m_host.c_str(), NULL, usedns ? NULL : &flags, &info)) { + struct addrinfo* first = info; + unsigned int i = 0; + + // Get the size of our array + for (info = first ; info ; info = info->ai_next) + i++; + + // Return NULL if no IPs found + if (i == 0) + return m_ips = NULL; + + // Create our array since we actually have a result + m_ips = new sockaddr*[++i]; + memset(m_ips, '\0', sizeof(sockaddr*)*i); + + // Copy the sockaddr's into m_ips + for (i = 0, info = first ; info ; info = info->ai_next) { + if (info->ai_addr->sa_family == AF_INET || info->ai_addr->sa_family == AF_INET6) { + m_ips[i] = copyaddr(*(info->ai_addr)); + if (!m_ips[i]) break; + ((sockaddr_in **) m_ips)[i++]->sin_port = htons(m_port); + } + } + + freeaddrinfo(first); + return m_ips; + } + + // No addresses found + return NULL; +} + +string url::get_password() const { + return m_pass; +} + +string url::get_path() const { + return m_path; +} + +string url::get_query() const { + return m_query; +} + +uint16_t url::get_port() const { + return m_port; +} + +string url::get_scheme() const { + return m_scheme; +} + +string url::get_username() const { + return m_user; +} + +string url::to_string() const { + return m_orig; +} + +static inline string recvline(int fd) { + // Read a character. + // If we don't get a character, return empty string. + // If we are at the end of the line, return empty string. + char c = '\0'; + + if (recv(fd, &c, 1, 0) != 1 || c == '\n') + return ""; + + return string(1, c) + recvline(fd); +} + +char* url::get_pac() { + int sock = -1; + bool chunked = false; + unsigned long int content_length = 0, status = 0; + char* buffer = NULL; + string request; + + // In case of a file:// url we open the file and read it + if (m_scheme == "file" || m_scheme == "pac+file") { + struct stat st; + if ((sock = ::open(m_path.c_str(), O_RDONLY)) < 0) + return NULL; + + if (!fstat(sock, &st) && st.st_size < PAC_MAX_SIZE) { + buffer = new char[st.st_size+1]; + memset(buffer, 0, st.st_size+1); + if (read(sock, buffer, st.st_size) == 0) { + delete[] buffer; + buffer = NULL; + } + } + close(sock); + return buffer; + } + + // DNS lookup of host + if (!get_ips(true)) + return NULL; + + // Iterate through each IP trying to make a connection + // Stop at the first one + for (int i=0 ; m_ips[i] ; i++) { + sock = socket(m_ips[i]->sa_family, SOCK_STREAM, 0); + if (sock < 0) continue; + + if (m_ips[i]->sa_family == AF_INET && + !connect(sock, m_ips[i], sizeof(struct sockaddr_in))) + break; + else if (m_ips[i]->sa_family == AF_INET6 && + !connect(sock, m_ips[i], sizeof(struct sockaddr_in6))) + break; + + close(sock); + sock = -1; + } + + // Test our socket + if (sock < 0) return NULL; + + // Build the request string + request = "GET " + (m_path.size() > 0 ? m_path : "/") + m_query + " HTTP/1.1\r\n"; + request += "Host: " + m_host + "\r\n"; + request += "Accept: " + string(PAC_MIME_TYPE) + "\r\n"; + request += "Connection: close\r\n"; + request += "\r\n"; + + // Send HTTP request + if ((size_t) send(sock, request.c_str(), request.size(), 0) != request.size()) { + close(sock); + return NULL; + } + + /* Verify status line */ + string line = recvline(sock); + if (sscanf(line.c_str(), "HTTP/1.%*d %lu", &status) == 1 && status == 200) { + /* Check for correct mime type and content length */ + content_length = 0; + for (line = recvline(sock) ; line != "\r" && line != "" ; line = recvline(sock)) { + // Check for chunked encoding + if (line.find("Content-Transfer-Encoding: chunked") == 0 || line.find("Transfer-Encoding: chunked") == 0) + chunked = true; + + // Check for content length + else if (content_length == 0) + sscanf(line.c_str(), "Content-Length: %lu", &content_length); + } + + // Get content + unsigned int recvd = 0; + buffer = new char[PAC_MAX_SIZE]; + memset(buffer, 0, PAC_MAX_SIZE); + do { + unsigned int chunk_length; + + if (chunked) { + // Discard the empty line if we received a previous chunk + if (recvd > 0) recvline(sock); + + // Get the chunk-length line as an integer + if (sscanf(recvline(sock).c_str(), "%x", &chunk_length) != 1 || chunk_length == 0) break; + + // Add this chunk to our content length, + // ensuring that we aren't over our max size + content_length += chunk_length; + } + + if (content_length >= PAC_MAX_SIZE) break; + + while (content_length == 0 || recvd != content_length) { + int r = recv(sock, buffer + recvd, + content_length == 0 ? PAC_HTTP_BLOCK_SIZE + : content_length - recvd, 0); + if (r <= 0) { + chunked = false; + break; + } + recvd += r; + } + } while (chunked); + + if (content_length != 0 && string(buffer).size() != content_length) { + delete[] buffer; + buffer = NULL; + } + } + + // Clean up + shutdown(sock, SHUT_RDWR); + close(sock); + return buffer; +} + +void url::empty_cache() +{ + if (m_ips) { + // Free any existing ip cache + for (int i=0 ; m_ips[i] ; i++) + delete m_ips[i]; + delete[] m_ips; + m_ips = NULL; + } +} diff --git a/libproxy/url.hpp b/libproxy/url.hpp new file mode 100644 index 0000000..33ac256 --- /dev/null +++ b/libproxy/url.hpp @@ -0,0 +1,85 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#ifndef URL_HPP_ +#define URL_HPP_ + +#include +#include +#include +#include + +#include "config.hpp" + +#define URL_GENERIC_DELIMITERS ":/?#[]@" +#define URL_SUBCOMPONENT_DELIMITERS "!$&'()*+,;=" +#define URL_ALLOWED_IN_USERINFO_ELEMENT URL_SUBCOMPONENT_DELIMITERS +#define URL_ALLOWED_IN_USERINFO URL_ALLOWED_IN_USERINFO_ELEMENT ":" +#define URL_ALLOWED_IN_PATH_ELEMENT URL_SUBCOMPONENT_DELIMITERS ":@" +#define URL_ALLOWED_IN_PATH URL_ALLOWED_IN_PATH_ELEMENT "/" + +namespace libproxy { + +using namespace std; + +class DLL_PUBLIC parse_error : public runtime_error { +public: + parse_error(const string& arg): runtime_error(arg) {} +}; + +class DLL_PUBLIC url { +public: + static bool is_valid(const string url); + static string encode(const string &data, const string &valid_reserved = ""); + + ~url(); + url(const url& url); + url(const string& url) throw (parse_error); + bool operator==(const url& url) const; + url& operator=(const url& url); + url& operator=(string url) throw (parse_error); + + string get_host() const; + sockaddr const* const* get_ips(bool usedns); + string get_password() const; + string get_path() const; + string get_query() const; + uint16_t get_port() const; + string get_scheme() const; + string get_username() const; + string to_string() const; + char* get_pac(); // Allocated, must free. NULL on error. + +private: + void empty_cache(); + + string m_orig; + string m_scheme; + string m_user; + string m_pass; + string m_host; + uint16_t m_port; + string m_path; + string m_query; + sockaddr** m_ips; +}; + +} + +#endif /*URL_HPP_*/ diff --git a/samples/dotnet/proxy.cs b/samples/dotnet/proxy.cs new file mode 100644 index 0000000..a8ce5e4 --- /dev/null +++ b/samples/dotnet/proxy.cs @@ -0,0 +1,38 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2009 Dominique Leuenberger + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +using System; +using libproxy; + +public class proxy { + public static int Main (string[] args) + { + if (args.Length > 0) { + ProxyFactory pf = new ProxyFactory(); + string[] Proxies = pf.GetProxies(args[0]); + Console.WriteLine(Proxies[0]); + pf = null; + return 0; + } else { + Console.WriteLine("Please start the program with one parameter"); + Console.WriteLine("Example: proxy.exe http://libproxy.googlecode.com/"); + return 1; + } + } +} diff --git a/samples/libcurl/curlget.c b/samples/libcurl/curlget.c new file mode 100644 index 0000000..a0a1c2d --- /dev/null +++ b/samples/libcurl/curlget.c @@ -0,0 +1,111 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * Copyright (C) 2008 Dominique Leuenberger + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ + +#include "proxy.h" +#include "curl/curl.h" +#include +#include + +int main(int argc, char * argv[]) { + pxProxyFactory *pf = NULL; + CURL *curl = NULL; + CURLcode result = 1; + + /* Check if we have a parameter passed, otherwise bail out... I need one */ + if (argc < 2) + { + printf("libcurl / libproxy example implementation\n"); + printf("=========================================\n"); + printf("The program has to be started with one parameter\n"); + printf("Defining the URL that should be downloaded\n\n"); + printf("Example: %s http://code.google.com/p/libproxy/\n", argv[0]); + return -1; + } + + /* Initializing curl... has to happen exactly once in the program */ + if (curl_global_init( CURL_GLOBAL_ALL )) return -4; + + /* Create pxProxyFactory object */ + if (!(pf = px_proxy_factory_new())) + { + printf("Unable to create pxProxyFactory object!\n"); + curl_global_cleanup(); + return -2; + } + + /* Create curl handle */ + if (!(curl = curl_easy_init())) + { + printf("Unable to get libcurl handle!\n"); + px_proxy_factory_free(pf); + curl_global_cleanup(); + return -3; + } + + /* Get the array of proxies to try */ + char **proxies = px_proxy_factory_get_proxies(pf, argv[1]); + + /* Set the URL into the curl handle */ + curl_easy_setopt(curl, CURLOPT_URL, argv[1]); + + /* Try to fetch our url using each proxy */ + for (int i=0 ; proxies[i] ; i++) + { + if (result != 0) + { + /* Setup our proxy's config into curl */ + curl_easy_setopt(curl, CURLOPT_PROXY, proxies[i]); + + /* HTTP Proxy */ + if (!strncmp("http", proxies[i], 4)) + curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); + + /* SOCKS Proxy, is this correct??? */ + /* What about SOCKS 4A, 5 and 5_HOSTNAME??? */ + else if (!strncmp("socks", proxies[i], 4)) + curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); + + /* Attempt to fetch the page */ + result = curl_easy_perform(curl); + } + + /* Free the proxy */ + free(proxies[i]); + + /* If we reached the end of the proxies array and still did not + succeed to conntect, let's inform the user that we failed. */ + if (proxies[i+1] == NULL && result != 0) + printf ("The requested URL (%s) could not be retrieved using the current setup\n", argv[1]); + + } + + /* Free the (now empty) proxy array */ + free(proxies); + + /* Free the curl and libproxy handles */ + px_proxy_factory_free(pf); + curl_easy_cleanup(curl); + + /* Cleanup the libcurl library */ + curl_global_cleanup(); + return 0; + +} + diff --git a/samples/perl/sample.pl b/samples/perl/sample.pl new file mode 100644 index 0000000..e8850fc --- /dev/null +++ b/samples/perl/sample.pl @@ -0,0 +1,7 @@ +use Net::Libproxy; + +$p = new Net::Libproxy; +$proxies = $p->getProxies('http://www.google.com'); +foreach my $proxy (@$proxies) { + print $proxy."\n"; +} diff --git a/samples/vala/sample.vala b/samples/vala/sample.vala new file mode 100644 index 0000000..1cec8cf --- /dev/null +++ b/samples/vala/sample.vala @@ -0,0 +1,9 @@ +using Libproxy; + +void main () { + var pf = new ProxyFactory (); + string[] proxies = pf.get_proxies ("http://www.google.com"); + foreach (string proxy in proxies) { + stdout.printf ("%s\n", proxy); + } +} diff --git a/utils/CMakeLists.txt b/utils/CMakeLists.txt new file mode 100644 index 0000000..52010c6 --- /dev/null +++ b/utils/CMakeLists.txt @@ -0,0 +1,5 @@ +include_directories("../libproxy") + +add_executable(proxy proxy.c) +target_link_libraries(proxy libproxy) +install(TARGETS proxy RUNTIME DESTINATION ${BIN_INSTALL_DIR}) diff --git a/utils/proxy.c b/utils/proxy.c new file mode 100644 index 0000000..2e54bb0 --- /dev/null +++ b/utils/proxy.c @@ -0,0 +1,105 @@ +/******************************************************************************* + * libproxy - A library for proxy configuration + * Copyright (C) 2006 Nathaniel McCallum + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + ******************************************************************************/ +#define _BSD_SOURCE + +#include +#include +#include +#include + +/* Import libproxy API */ +#include + +void * +malloc0(size_t s) +{ + void *tmp = malloc(s); + if (!tmp) return NULL; + memset(tmp, '\0', s); + return tmp; +} + +/** + * Prints an array of proxies. Proxies are space separated. + * @proxies an array containing the proxies returned by libproxy. + */ +void +print_proxies(char **proxies) +{ + int j; + + if (!proxies) { + printf("\n"); + return; + } + + for (j=0; proxies[j] ; j++) + { + printf("%s%s", proxies[j], proxies[j+1] ? " " : "\n"); + free(proxies[j]); + } + free(proxies); +} + +int +main(int argc, char **argv) +{ + int i; + char url[102400]; // Should be plently long for most URLs + + /* Create the proxy factory object */ + pxProxyFactory *pf = px_proxy_factory_new(); + if (!pf) + { + fprintf(stderr, "An unknown error occurred!\n"); + return 1; + } + /* User entered some arguments on startup. skip interactive */ + if (argc > 1) + { + for (i=1; i < argc ; i++) + { + /* + * Get an array of proxies to use. These should be used + * in the order returned. Only move on to the next proxy + * if the first one fails (etc). + */ + print_proxies(px_proxy_factory_get_proxies(pf, argv[i])); + } + } + /* Interactive mode */ + else + { + /* For each URL we read on STDIN, get the proxies to use */ + for (url[0] = '\0' ; fgets(url, 102400, stdin) != NULL ; ) + { + if (url[strlen(url)-1] == '\n') url[strlen(url)-1] = '\0'; + + /* + * Get an array of proxies to use. These should be used + * in the order returned. Only move on to the next proxy + * if the first one fails (etc). + */ + print_proxies(px_proxy_factory_get_proxies(pf, url)); + } + } + /* Destroy the proxy factory object */ + px_proxy_factory_free(pf); + return 0; +}