Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial stub for proxy

  • Loading branch information...
commit 6a74d82362e0ba10397691d21b595e06c93a78c0 0 parents
@Jc2k Jc2k authored
7 .gitignore
@@ -0,0 +1,7 @@
+.installed.cfg
+bin/
+develop-eggs/
+eggs/
+parts/
+*.egg-info
+*.pyc
64 README.rst
@@ -0,0 +1,64 @@
+badgerproxy
+===========
+
+This is a HTTP proxy that supports content rewriting of HTTP and HTTPS traffic
+that passes through. Note that rewriting HTTPS obviously means SSL is stripped
+and reapplied. The SSL certificate that is used to reencrypt will be invalid.
+
+There are 2 ways to set up a development environment. You can use buildout::
+
+ $ python bootstrap.py
+ $ bin/buildout
+
+A ``badgerproxy`` and ``badgerproxyctl`` script will be created in the bin/
+directory.
+
+You can also use virtualenv::
+
+ $ virtualenv --no-site-packages .
+ $ source ./bin/active
+ $ python setup.py develop
+
+
+To run a server in foreground::
+
+ $ badgerproxy -c badger-sample start -n
+
+``badger-sample`` is a Yay file in the root of the repository that contains a
+description of which services and triggers to start with the main service. It
+looks something like this::
+
+ socket: /var/local/badgerproxy/var/badgerproxy.sock
+
+ services:
+ - listen: localhost:8084
+ methods:
+ allowed:
+ - HEAD
+ - POST
+ - GET
+ - CONECT
+
+ ports:
+ allowed:
+ - 80
+ - 443
+
+ rewriter:
+ cls: badgerproxy.rewriting.waraningbanner
+ image: https://www.myhost.com/images/banner.gif
+
+ - listen: localhost:8084
+ methods:
+ allowed:
+ - CONNECT
+
+ ports:
+ allowed:
+ - 22
+
+
+To dynamically add an allowed URL::
+
+ $ badgerproxyctl -s /var/local/badgerproxy/var/badgerproxy.sock add-dns www.wibble.com 4.4.4.4 60
+
33 badgerproxy-example
@@ -0,0 +1,33 @@
+socket: /tmp/badgerproxy.sock
+pidfile: /tmp/badgerpoxy.pid
+resolvercache: /tmp/badgerproxy.resolvercache
+
+services:
+ - listen: localhost:8084
+ methods:
+ allowed:
+ - HEAD
+ - POST
+ - GET
+ - CONECT
+
+ ports:
+ allowed:
+ - 80
+ - 443
+
+ rewriter:
+ cls: badgerproxy.rewriting.waraningbanner
+ height: 20px
+ image: https://www.myhost.com/images/banner.gif
+
+
+ - listen: localhost:8085
+ methods:
+ allowed:
+ - CONNECT
+
+ ports:
+ allowed:
+ - 22
+
0  badgerproxy/__init__.py
No changes.
38 badgerproxy/badgerproxy.py
@@ -0,0 +1,38 @@
+# Copyright 2012 Isotoma Limited
+#
+# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from twisted.application.service import MultiService
+
+from .pb import PbService
+from .dns import Resolver
+from .proxy import ProxyService
+
+class BadgerProxy(MultiService):
+
+ def __init__(self, config=None):
+ MultiService.__init__(self)
+ self.config = config
+
+ self.pb = PbService(self.config['socket'])
+ self.setServiceParent(self)
+
+ self.resolver = Resolver(self.config['resolver-cache'])
+ self.setServiceParent(self)
+
+ self.services = []
+ for service in self.config['services']:
+ p = ProxyService(service)
+ p.setServiceParent(self)
+ self.services.append(p)
+
56 badgerproxy/dns.py
@@ -0,0 +1,56 @@
+# Copyright 2012 Isotoma Limited
+#
+# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import shelve
+import datetime
+
+
+from twisted.application.service import Service
+from twisted.internet import task
+from twisted.python import log
+
+
+class Resolver(Service):
+
+ interval = 60 * 5
+
+ def __init__(self, cachepath):
+ self.domains = shelve.load(cachepath)
+ self._expire_task = task.LoopingCall(self.expire)
+
+ def add_dns(self, domain, ip, ttl):
+ delta = datetime.timedelta(0, 0, ttl)
+ expires = datetime.datetime.now() + delta
+ log.msg("Adding '%s' -> %s, will espire at %s" % (domain, ip, expires))
+ self.domains[domain] = (ip, expires)
+
+ def remove_dns(self, domain):
+ log.msg("Removing domain entry for: '%s'" % domain)
+ del self.domains[domain]
+
+ def expire(self):
+ now = datetime.datetime.now()
+ for k, v in self.domains.items():
+ if v[1] < now:
+ self.remove_dns(domain)
+
+ def startService(self):
+ Service.startService(self):
+ self._expire_task.start(self.interval, now=True)
+
+ def stopService(self):
+ Service.stopService(self)
+ if self._expire_task.running:
+ self._expire_task.stop()
+
70 badgerproxy/pb.py
@@ -0,0 +1,70 @@
+# Copyright 2012 Isotoma Limited
+#
+# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from optparse import OptionParser
+
+from zope.interface import implements
+
+from twisted.spread import pb
+from twisted.cred.portal import IRealm, Portal
+from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
+from twisted.internet import reactor
+from twisted.cred.credentials import UsernamePassword
+from twisted.application import strports, service
+
+
+class PbPerspective(pb.Avatar):
+
+ def __init__(self, badgerproxy):
+ self.badgerproxy = badgerproxy
+
+ def perspective_add_dns(self, domain, ip, ttl):
+ t = self.badgerproxy.resolver.add_domain(domain, ip, ttl)
+
+ def logout(self):
+ pass
+
+
+class PbRealm(object):
+
+ implements(IRealm)
+
+ def __init__(self, badgerproxy):
+ self.badgerproxy = badgerproxy
+
+ def requestAvatar(self, avatarId, mind, *interfaces):
+ if pb.IPerspective in interfaces:
+ avatar = PbPerspective(self.badgerproxy)
+ return pb.IPerspective, avatar, avatar.logout
+ raise NotImplementedError("no interface")
+
+
+class PbService(service.Service):
+
+ def __init__(self, socket):
+ service.Service.__init__(self)
+ self.socket = socket
+
+ def setServiceParent(self, parent):
+ service.Service.__init__(self, parent)
+
+ portal = Portal(PbRealm(parent))
+
+ checker = InMemoryUsernamePasswordDatabaseDontUse()
+ checker.addUser("guest", "guest")
+ portal.registerChecker(checker)
+
+ service = strports.service("unix:%s" % socket, pb.PBServerFactory(portal))
+ service.setServiceParent(self)
+
263 badgerproxy/proxy.py
@@ -0,0 +1,263 @@
+# Copyright 2012 Isotoma Limited
+#
+# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from twisted.application import service
+from twisted.python import usage
+from twisted.internet.protocol import Protocol, ClientFactory
+from twisted.web import http
+from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient
+from twisted.web.proxy import ReverseProxy
+
+from twisted.application import internet
+from StringIO import StringIO
+
+banner = """
+<style>
+HTML {
+ padding-top: %(height)s;
+ background: url('%(bannerurl)s') 0 0 repeat-x !important;
+}
+</style>
+</head>
+"""
+
+class RewritingProxyClient(ProxyClient):
+ def __init__(self, *args, **kwargs):
+ ProxyClient.__init__(self, *args, **kwargs)
+ self.rewrite = False
+ self.length = None
+ self.buffer = ''
+
+ def sendHeader(self, name, value):
+ log.msg(">>> %s: %s" % (name, value))
+ if name.lower() == "accept-encoding":
+ value = "identity"
+ ProxyClient.sendHeader(self, name, value)
+
+ def handleHeader(self, key, value):
+ log.msg("<<< %s: %s" % (key, value))
+ if key.lower() == "content-type":
+ if value.startswith("text/html"):
+ self.rewrite = True
+ ProxyClient.handleHeader(self, key, value)
+ elif key.lower() == "content-length":
+ self.length = value
+ else:
+ ProxyClient.handleHeader(self, key, value)
+
+ def handleEndHeaders(self):
+ if not self.rewrite:
+ if self.length:
+ ProxyClient.handleHeader(self, "Content-Length", self.length)
+ ProxyClient.handleEndHeaders(self)
+
+ def handleResponsePart(self, buffer):
+ if self.rewrite:
+ self.buffer += buffer
+ else:
+ ProxyClient.handleResponsePart(self, buffer)
+
+ def handleResponseEnd(self):
+ log.msg("handleResponseEnd")
+ if self.rewrite:
+ buffer = self.buffer.replace("</head>", banner)
+ ProxyClient.handleHeader(self, "Content-Length", str(len(buffer)))
+ ProxyClient.handleEndHeaders(self)
+ ProxyClient.handleResponsePart(self, buffer)
+ self.rewrite = False
+ ProxyClient.handleResponseEnd(self)
+
+
+class RewritingProxyClientFactory(ProxyClientFactory):
+ protocol = RewritingProxyClient
+
+
+from twisted.internet import ssl
+from twisted.protocols.tls import TLSMemoryBIOProtocol
+
+
+from twisted.internet import reactor
+from twisted.web.http import Request, HTTPChannel
+
+class ReverseProxyRequest(Request):
+ proxyClientFactoryClass = RewritingProxyClientFactory
+
+ def __init__(self, channel, queued, reactor=reactor):
+ Request.__init__(self, channel, queued)
+ self.reactor = reactor
+
+ def process(self):
+ self.received_headers['host'] = self.channel.factory.host
+ if 'accept' in self.received_headers:
+ del self.received_headers['accept']
+
+ clientFactory = self.proxyClientFactoryClass(
+ self.method, self.uri, self.clientproto, self.getAllHeaders(),
+ self.content.read(), self)
+
+ port = self.channel.factory.port
+ host = self.channel.factory.host
+
+ if port == 443:
+ connect = self.reactor.connectSSL
+ connect(host, port, clientFactory, ssl.ClientContextFactory())
+ else:
+ connect = self.reactor.connectTCP
+ connect(host, port, clientFactory)
+
+
+
+class ReverseProxy(HTTPChannel):
+ requestFactory = ReverseProxyRequest
+
+
+class TunnelProxyRequest (ProxyRequest):
+
+ protocols = {'http': RewritingProxyClientFactory}
+
+ def process(self):
+ if self.method.upper() == 'CONNECT':
+ self._process_connect()
+ else:
+ return ProxyRequest.process(self)
+
+ def _process_connect(self):
+ try:
+ host, portStr = self.uri.split(':', 1)
+ port = int(portStr)
+ except ValueError:
+ # Either the connect parameter is not HOST:PORT or PORT is
+ # not an integer, in which case this request is invalid.
+ self.setResponseCode(400)
+ self.finish()
+ else:
+ #restrictedToPort = self.channel.factory.restrictedToPort
+ #if (restrictedToPort is not None) and (port != restrictedToPort):
+ if port != 443:
+ self.setResponseCode(403, 'Forbidden port')
+ self.finish()
+ else:
+ #self.reactor.connectTCP(host, port, TunnelProtocolFactory(self, host, port))
+
+ class FakeFactory:
+ def log(self, meh):
+ pass
+ FakeFactory.host = host
+ FakeFactory.port = port
+ rp = ReverseProxy()
+ rp.factory = FakeFactory()
+
+ contextFactory = ssl.DefaultOpenSSLContextFactory('server.key', 'server.crt')
+
+ class FakeFactory2:
+ _contextFactory = contextFactory
+ _isClient = False
+ def registerProtocol(self, meh):
+ pass
+ def unregisterProtocol(self, meh):
+ pass
+ ssl_rp = TLSMemoryBIOProtocol(FakeFactory2(), rp)
+
+ self.channel._registerTunnel(ssl_rp)
+ ssl_rp.makeConnection(self.transport)
+
+ self.setResponseCode(200)
+ self.write("")
+
+
+class TunnelProxy (Proxy):
+ """
+ This class implements a simple web proxy with CONNECT support.
+
+ It inherits from L{Proxy} and expects
+ L{twisted.web.proxy.TunnelProxyFactory} as a factory.
+
+ f = TunnelProxyFactory()
+
+ Make the TunnelProxyFactory a listener on a port as per usual,
+ and you have a fully-functioning web proxy which supports CONNECT.
+ This should support typical web usage with common browsers.
+
+ @ivar _tunnelproto: This is part of a private interface between
+ TunnelProxy and TunnelProtocol. This is either None or a
+ TunnelProtocol connected to a server due to a CONNECT request.
+ If this is set, then the stream from the user agent is forwarded
+ to the target HOST:PORT of the CONNECT request.
+ """
+ requestFactory = TunnelProxyRequest
+
+ def __init__(self):
+ self._tunnelproto = None
+ Proxy.__init__(self)
+
+ def _registerTunnel(self, tunnelproto):
+ """
+ This is a private interface for L{TunnelProtocol}. This sets
+ L{_tunnelproto} to which to forward the stream from the user
+ agent. This should only be set after the tunnel to the target
+ HOST:PORT is established.
+ """
+ assert self._tunnelproto is None, 'Precondition failure: Multiple TunnelProtocols set: self._tunnelproto == %r; new tunnelproto == %r' % (self._tunnelproto, tunnelproto)
+ self._tunnelproto = tunnelproto
+
+ def dataReceived(self, data):
+ """
+ If there is a tunnel connection, forward the stream; otherwise
+ behave just like Proxy.
+ """
+ if self._tunnelproto is None:
+ Proxy.dataReceived(self, data)
+ else:
+ self._tunnelproto.dataReceived(data)
+
+
+class TunnelProxyFactory (http.HTTPFactory):
+ protocol = TunnelProxy
+
+
+class ProxyService(service.Service):
+
+ def __init__(self, config):
+ service.Service.__init__(self)
+ self.config = config
+
+ def is_method_allowed(self. method):
+ if not "methods" in self.config:
+ return True
+ methods = self.config["methods"]
+ if "allowed" in method:
+ if method in method["allowed"]:
+ return True
+ return False
+ elif "blocked" in method:
+ if method in method["blocked"]:
+ return False
+ return True
+ return True
+
+ def setServiceParent(self, parent):
+ service.Service.__init__(self, parent)
+
+ service = strports.service(self.config['listen'], TunnelProxyFactory())
+ service.setServiceParent(self)
+
+
+if __name__ == "__main__":
+ from twisted.internet import reactor
+ from twisted.python import log
+ import sys
+ log.startLogging(sys.stdout)
+ reactor.listenTCP(8181, TunnelProxyFactory())
+ reactor.run()
+
0  badgerproxy/scripts/__init__.py
No changes.
120 badgerproxy/scripts/badgerproxy.py
@@ -0,0 +1,120 @@
+# Copyright 2011 Isotoma Limited
+#
+# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import
+
+import sys
+import os
+
+from twisted.python import usage
+from twisted.python.util import sibpath
+
+from twisted.application import app, service
+from twisted.python.runtime import platformType
+
+if platformType == "win32":
+ from twisted.scripts._twistw import ServerOptions, \
+ WindowsApplicationRunner as _SomeApplicationRunner
+else:
+ from twisted.scripts._twistd_unix import ServerOptions, \
+ UnixApplicationRunner as _SomeApplicationRunner
+
+import yay, StringIO
+from badgerproxy.badgerproxy import BadgerProxy
+
+
+class StartOptions(ServerOptions):
+
+ """
+ Options for starting a badgerproxy daemon.
+
+ Subclasses ServerOptions from twistd - either a Unix or Win32 version.
+ """
+
+ longdesc = "Start the service"
+
+ @property
+ def subCommands(self):
+ # There are no subcommands for start - but twistd uses a hasattr check
+ # so we have to raise an AttributeError to trick it
+ raise AttributeError
+
+ @property
+ def synopsis(self):
+ # Need to undo the fact that ServerOptions overrides the default synopsis
+ # as it stops us nesting the ServerOptions
+ raise AttributeError
+
+
+class StopOptions(usage.Options):
+
+ longdesc = "Stop the service"
+
+
+class Options(usage.Options):
+ subCommands = [
+ ['start', None, StartOptions, "Start the service"],
+ ['stop', None, StopOptions, "Stop the service"],
+ ]
+
+ optParameters = [
+ ['config', 'c', '/etc/badgerproxy', 'Server configuration file'],
+ ]
+
+ def postOptions(self):
+ if not "config" in self:
+ raise usage.UsageError("No configuration file provided")
+
+ if not os.path.exists(self['config']):
+ raise usage.UsageError("The configuration file '%s' does not exist" % self['config'])
+
+
+class BadgerProxyRunner(_SomeApplicationRunner):
+
+ def createOrGetApplication(self):
+ application = service.Application("BadgerProxy")
+
+ config = yay.load_uri(self.config.parent["config"])
+
+ badgerproxy = BadgerProxy(config)
+ badgerproxy.setServiceParent(application)
+
+ return application
+
+
+def run():
+ config = Options()
+
+ try:
+ config.parseOptions()
+ except usage.error, ue:
+ print "Error: %s" % ue
+ print config.opt_help()
+ sys.exit(1)
+
+ if config.subCommand == "start":
+ BadgerProxyRunner(config.subOptions).run()
+
+ elif config.subCommand == "stop":
+ try:
+ pid = int(open(pidfile).read())
+ except IOError:
+ print "Server is not running"
+ return 255
+ os.kill(pid, 15)
+
+ else:
+ config.opt_help()
+ sys.exit(1)
+
51 badgerproxy/scripts/badgerproxyctl.py
@@ -0,0 +1,51 @@
+# Copyright 2012 Isotoma Limited
+#
+# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import sys
+
+from twisted.internet import reactor
+from optparse import OptionParser
+from twisted.spread import pb
+from twisted.cred.credentials import UsernamePassword
+
+def run():
+
+ p = OptionParser("%prog [options] [command]")
+ p.add_option("-S", "--socket", default="", help="Socket to connect to")
+ options, args = p.parse_args()
+
+
+
+ task = stream.read()
+
+ def success(message):
+ print "Task '%s' finished executing" % message
+ reactor.stop()
+
+ def failure(error):
+ #t = error.trap(DefinedError)
+ print "error received:", error
+ reactor.stop()
+
+ def connected(perspective):
+ perspective.callRemote('execute', task).addCallbacks(success, failure)
+ print "connected."
+
+ factory = pb.PBClientFactory()
+ reactor.connectTCP(options.hostname, options.port, factory)
+ factory.login(
+ UsernamePassword(options.username, options.password)).addCallbacks(connected, failure)
+
+ reactor.run()
+
263 bootstrap.py
@@ -0,0 +1,263 @@
+##############################################################################
+#
+# Copyright (c) 2006 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Bootstrap a buildout-based project
+
+Simply run this script in a directory containing a buildout.cfg.
+The script accepts buildout command-line options, so you can
+use the -c option to specify an alternate configuration file.
+"""
+
+import os, shutil, sys, tempfile, textwrap, urllib, urllib2, subprocess
+from optparse import OptionParser
+
+if sys.platform == 'win32':
+ def quote(c):
+ if ' ' in c:
+ return '"%s"' % c # work around spawn lamosity on windows
+ else:
+ return c
+else:
+ quote = str
+
+# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
+stdout, stderr = subprocess.Popen(
+ [sys.executable, '-Sc',
+ 'try:\n'
+ ' import ConfigParser\n'
+ 'except ImportError:\n'
+ ' print 1\n'
+ 'else:\n'
+ ' print 0\n'],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
+has_broken_dash_S = bool(int(stdout.strip()))
+
+# In order to be more robust in the face of system Pythons, we want to
+# run without site-packages loaded. This is somewhat tricky, in
+# particular because Python 2.6's distutils imports site, so starting
+# with the -S flag is not sufficient. However, we'll start with that:
+if not has_broken_dash_S and 'site' in sys.modules:
+ # We will restart with python -S.
+ args = sys.argv[:]
+ args[0:0] = [sys.executable, '-S']
+ args = map(quote, args)
+ os.execv(sys.executable, args)
+# Now we are running with -S. We'll get the clean sys.path, import site
+# because distutils will do it later, and then reset the path and clean
+# out any namespace packages from site-packages that might have been
+# loaded by .pth files.
+clean_path = sys.path[:]
+import site
+sys.path[:] = clean_path
+for k, v in sys.modules.items():
+ if k in ('setuptools', 'pkg_resources') or (
+ hasattr(v, '__path__') and
+ len(v.__path__)==1 and
+ not os.path.exists(os.path.join(v.__path__[0],'__init__.py'))):
+ # This is a namespace package. Remove it.
+ sys.modules.pop(k)
+
+is_jython = sys.platform.startswith('java')
+
+setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
+distribute_source = 'http://python-distribute.org/distribute_setup.py'
+
+# parsing arguments
+def normalize_to_url(option, opt_str, value, parser):
+ if value:
+ if '://' not in value: # It doesn't smell like a URL.
+ value = 'file://%s' % (
+ urllib.pathname2url(
+ os.path.abspath(os.path.expanduser(value))),)
+ if opt_str == '--download-base' and not value.endswith('/'):
+ # Download base needs a trailing slash to make the world happy.
+ value += '/'
+ else:
+ value = None
+ name = opt_str[2:].replace('-', '_')
+ setattr(parser.values, name, value)
+
+usage = '''\
+[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
+
+Bootstraps a buildout-based project.
+
+Simply run this script in a directory containing a buildout.cfg, using the
+Python that you want bin/buildout to use.
+
+Note that by using --setup-source and --download-base to point to
+local resources, you can keep this script from going over the network.
+'''
+
+parser = OptionParser(usage=usage)
+parser.add_option("-v", "--version", dest="version",
+ help="use a specific zc.buildout version", default="1.4.3")
+parser.add_option("-d", "--distribute",
+ action="store_true", dest="use_distribute", default=True,
+ help="Use Distribute rather than Setuptools.")
+parser.add_option("--distribute-version", dest="distribute_version", default="0.6.21")
+parser.add_option("--setup-source", action="callback", dest="setup_source",
+ callback=normalize_to_url, nargs=1, type="string",
+ help=("Specify a URL or file location for the setup file. "
+ "If you use Setuptools, this will default to " +
+ setuptools_source + "; if you use Distribute, this "
+ "will default to " + distribute_source +"."))
+parser.add_option("--download-base", action="callback", dest="download_base",
+ callback=normalize_to_url, nargs=1, type="string",
+ help=("Specify a URL or directory for downloading "
+ "zc.buildout and either Setuptools or Distribute. "
+ "Defaults to PyPI."))
+parser.add_option("--eggs",
+ help=("Specify a directory for storing eggs. Defaults to "
+ "a temporary directory that is deleted when the "
+ "bootstrap script completes."))
+parser.add_option("-t", "--accept-buildout-test-releases",
+ dest='accept_buildout_test_releases',
+ action="store_true", default=False,
+ help=("Normally, if you do not specify a --version, the "
+ "bootstrap script and buildout gets the newest "
+ "*final* versions of zc.buildout and its recipes and "
+ "extensions for you. If you use this flag, "
+ "bootstrap and buildout will get the newest releases "
+ "even if they are alphas or betas."))
+parser.add_option("-c", None, action="store", dest="config_file",
+ help=("Specify the path to the buildout configuration "
+ "file to be used."))
+
+options, args = parser.parse_args()
+
+# if -c was provided, we push it back into args for buildout's main function
+if options.config_file is not None:
+ args += ['-c', options.config_file]
+
+if options.eggs:
+ eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
+else:
+ eggs_dir = tempfile.mkdtemp()
+
+if options.setup_source is None:
+ if options.use_distribute:
+ options.setup_source = distribute_source
+ else:
+ options.setup_source = setuptools_source
+
+if options.accept_buildout_test_releases:
+ args.append('buildout:accept-buildout-test-releases=true')
+args.append('bootstrap')
+
+try:
+ import pkg_resources
+ import setuptools # A flag. Sometimes pkg_resources is installed alone.
+ if not hasattr(pkg_resources, '_distribute'):
+ raise ImportError
+except ImportError:
+ ez_code = urllib2.urlopen(
+ options.setup_source).read().replace('\r\n', '\n')
+ ez = {}
+ exec ez_code in ez
+ setup_args = dict(to_dir=eggs_dir, download_delay=0)
+ if options.download_base:
+ setup_args['download_base'] = options.download_base
+ if options.use_distribute:
+ setup_args['no_fake'] = True
+ if options.distribute_version:
+ setup_args['version'] = options.distribute_version
+ ez['use_setuptools'](**setup_args)
+ if 'pkg_resources' in sys.modules:
+ reload(sys.modules['pkg_resources'])
+ import pkg_resources
+ # This does not (always?) update the default working set. We will
+ # do it.
+ for path in sys.path:
+ if path not in pkg_resources.working_set.entries:
+ pkg_resources.working_set.add_entry(path)
+
+cmd = [quote(sys.executable),
+ '-c',
+ quote('from setuptools.command.easy_install import main; main()'),
+ '-mqNxd',
+ quote(eggs_dir)]
+
+if not has_broken_dash_S:
+ cmd.insert(1, '-S')
+
+find_links = options.download_base
+if not find_links:
+ find_links = os.environ.get('bootstrap-testing-find-links')
+if find_links:
+ cmd.extend(['-f', quote(find_links)])
+
+if options.use_distribute:
+ setup_requirement = 'distribute'
+else:
+ setup_requirement = 'setuptools'
+ws = pkg_resources.working_set
+setup_requirement_path = ws.find(
+ pkg_resources.Requirement.parse(setup_requirement)).location
+env = dict(
+ os.environ,
+ PYTHONPATH=setup_requirement_path)
+
+requirement = 'zc.buildout'
+version = options.version
+if version is None and not options.accept_buildout_test_releases:
+ # Figure out the most recent final version of zc.buildout.
+ import setuptools.package_index
+ _final_parts = '*final-', '*final'
+ def _final_version(parsed_version):
+ for part in parsed_version:
+ if (part[:1] == '*') and (part not in _final_parts):
+ return False
+ return True
+ index = setuptools.package_index.PackageIndex(
+ search_path=[setup_requirement_path])
+ if find_links:
+ index.add_find_links((find_links,))
+ req = pkg_resources.Requirement.parse(requirement)
+ if index.obtain(req) is not None:
+ best = []
+ bestv = None
+ for dist in index[req.project_name]:
+ distv = dist.parsed_version
+ if _final_version(distv):
+ if bestv is None or distv > bestv:
+ best = [dist]
+ bestv = distv
+ elif distv == bestv:
+ best.append(dist)
+ if best:
+ best.sort()
+ version = best[-1].version
+if version:
+ requirement = '=='.join((requirement, version))
+cmd.append(requirement)
+
+if is_jython:
+ import subprocess
+ exitcode = subprocess.Popen(cmd, env=env).wait()
+else: # Windows prefers this, apparently; otherwise we would prefer subprocess
+ exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
+if exitcode != 0:
+ sys.stdout.flush()
+ sys.stderr.flush()
+ print ("An error occurred when trying to install zc.buildout. "
+ "Look above this message for any errors that "
+ "were output by easy_install.")
+ sys.exit(exitcode)
+
+ws.add_entry(eggs_dir)
+ws.require(requirement)
+import zc.buildout.buildout
+zc.buildout.buildout.main(args)
+if not options.eggs: # clean up temporary egg directory
+ shutil.rmtree(eggs_dir)
17 buildout.cfg
@@ -0,0 +1,17 @@
+[buildout]
+parts =
+ var
+ badgerproxy
+develop = .
+
+[var]
+recipe = z3c.recipe.mkdir
+paths =
+ var
+ var/run
+ var/log
+
+[badgerproxy]
+recipe = zc.recipe.egg:scripts
+eggs = badgerproxy
+
33 setup.py
@@ -0,0 +1,33 @@
+from setuptools import setup, find_packages
+import os
+
+version = '0.0.0dev'
+
+setup(name='badgerproxy',
+ version=version,
+ url="http://www.isotoma.com/",
+ description="badgerproxy",
+ long_description=open("README.rst").read(),
+ author="Isotoma Limited",
+ author_email="john.carr@isotoma.com",
+ license="Apache Software License",
+ classifiers = [
+ "Intended Audience :: System Administrators",
+ "Operating System :: POSIX",
+ "License :: OSI Approved :: Apache Software License",
+ ],
+ packages=find_packages(exclude=['ez_setup']),
+ include_package_data=True,
+ zip_safe=False,
+ install_requires=[
+ 'setuptools',
+ 'yay >= 0.0.24',
+ ],
+ entry_points = {
+ "console_scripts": [
+ 'badgerproxyctl=badgerproxy.scripts.badgerproxyctl:run',
+ 'badgerproxy=badgerproxy.scripts.badgerproxy:run',
+ ],
+ }
+ )
+

0 comments on commit 6a74d82

Please sign in to comment.
Something went wrong with that request. Please try again.