3177N/A#!/usr/bin/python2.7
20N/A#
20N/A# CDDL HEADER START
20N/A#
20N/A# The contents of this file are subject to the terms of the
20N/A# Common Development and Distribution License (the "License").
20N/A# You may not use this file except in compliance with the License.
20N/A#
20N/A# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
20N/A# or http://www.opensolaris.org/os/licensing.
20N/A# See the License for the specific language governing permissions
20N/A# and limitations under the License.
20N/A#
20N/A# When distributing Covered Code, include this CDDL HEADER in each
20N/A# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
20N/A# If applicable, add the following below this CDDL HEADER, with the
20N/A# fields enclosed by brackets "[]" replaced with your own identifying
20N/A# information: Portions Copyright [yyyy] [name of copyright owner]
20N/A#
20N/A# CDDL HEADER END
20N/A#
3339N/A# Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
20N/A#
20N/A
3143N/Afrom __future__ import print_function
3143N/A
22N/A# pkg.depotd - package repository daemon
0N/A
50N/A# XXX The prototype pkg.depotd combines both the version management server that
50N/A# answers to pkgsend(1) sessions and the HTTP file server that answers to the
50N/A# various GET operations that a pkg(1) client makes. This split is expected to
50N/A# be made more explicit, by constraining the pkg(1) operations such that they
50N/A# can be served as a typical HTTP/HTTPS session. Thus, pkg.depotd will reduce
50N/A# to a special purpose HTTP/HTTPS server explicitly for the version management
50N/A# operations, and must manipulate the various state files--catalogs, in
50N/A# particular--such that the pkg(1) pull client can operately accurately with
50N/A# only a basic HTTP/HTTPS server in place.
50N/A
50N/A# XXX Although we pushed the evaluation of next-version, etc. to the pull
50N/A# client, we should probably provide a query API to do same on the server, for
50N/A# dumb clients (like a notification service).
50N/A
589N/A# The default path for static and other web content.
589N/ACONTENT_PATH_DEFAULT = "/usr/share/lib/pkg"
965N/A# cherrypy has a max_request_body_size parameter that determines whether the
965N/A# server should abort requests with REQUEST_ENTITY_TOO_LARGE when the request
965N/A# body is larger than the specified size (in bytes). The maximum size supported
965N/A# by cherrypy is 2048 * 1024 * 1024 - 1 (just short of 2048MB), but the default
965N/A# here is purposefully conservative.
2951N/AMAX_REQUEST_BODY_SIZE = 512 * 1024 * 1024
1836N/A# The default host/port(s) to serve data from.
1836N/AHOST_DEFAULT = "0.0.0.0"
382N/APORT_DEFAULT = 80
812N/ASSL_PORT_DEFAULT = 443
382N/A# The minimum number of threads allowed.
382N/ATHREADS_MIN = 1
382N/A# The default number of threads to start.
1963N/ATHREADS_DEFAULT = 60
382N/A# The maximum number of threads that can be started.
1963N/ATHREADS_MAX = 5000
382N/A# The default server socket timeout in seconds. We want this to be longer than
382N/A# the normal default of 10 seconds to accommodate clients with poor quality
382N/A# connections.
382N/ASOCKET_TIMEOUT_DEFAULT = 60
382N/A
26N/Aimport getopt
689N/Aimport gettext
689N/Aimport locale
466N/Aimport logging
0N/Aimport os
468N/Aimport os.path
812N/Aimport OpenSSL.crypto as crypto
3273N/Aimport shlex
3274N/Aimport six
3274N/Aimport string
812N/Aimport subprocess
52N/Aimport sys
812N/Aimport tempfile
0N/A
3339N/Aif sys.version_info[:2] >= (3, 4):
3339N/A from importlib import reload
3339N/Aelse:
3339N/A from imp import reload
3234N/Afrom six.moves.urllib.parse import urlparse, urlunparse
3194N/A
382N/Atry:
382N/A import cherrypy
382N/A version = cherrypy.__version__.split('.')
3234N/A # comparison requires same type, therefore list conversion is needed
3234N/A if list(map(int, version)) < [3, 1, 0]:
382N/A raise ImportError
382N/Aexcept ImportError:
3274N/A print("""cherrypy 3.1.0 or greater is required to use this program.""",
3274N/A file=sys.stderr)
382N/A sys.exit(2)
22N/A
1836N/Aimport cherrypy.process.servers
2507N/Afrom cherrypy.process.plugins import Daemonizer
3274N/Afrom cherrypy._cpdispatch import Dispatcher
1836N/A
1836N/Afrom pkg.misc import msg, emsg, setlocale
2962N/Afrom pkg.client.debugvalues import DebugValues
2962N/A
2962N/Aimport pkg
1431N/Aimport pkg.client.api_errors as api_errors
1968N/Aimport pkg.config as cfg
873N/Aimport pkg.portable.util as os_util
812N/Aimport pkg.search_errors as search_errors
1431N/Aimport pkg.server.depot as ds
1431N/Aimport pkg.server.repository as sr
466N/A
1431N/A
3274N/A# Starting in CherryPy 3.2, its default dispatcher converts all punctuation to
3274N/A# underscore. Since publisher name can contain the hyphen symbol "-", in order
3274N/A# to let the dispatcher to find the correct page handler, we need to skip
3274N/A# converting the hyphen symbol.
3274N/Apunc = string.punctuation.replace("-", "_")
3274N/Aif six.PY2:
3274N/A translate = string.maketrans(punc, "_" * len(string.punctuation))
3274N/Aelse:
3274N/A translate = str.maketrans(punc, "_" * len(string.punctuation))
3274N/Aclass Pkg5Dispatcher(Dispatcher):
3274N/A def __init__(self, **args):
3274N/A Dispatcher.__init__(self, translate=translate)
3274N/A
3274N/A
466N/Aclass LogSink(object):
466N/A """This is a dummy object that we can use to discard log entries
466N/A without relying on non-portable interfaces such as /dev/null."""
23N/A
466N/A def write(self, *args, **kwargs):
466N/A """Discard the bits."""
466N/A pass
466N/A
466N/A def flush(self, *args, **kwargs):
466N/A """Discard the bits."""
466N/A pass
466N/A
1431N/A
1633N/Adef usage(text=None, retcode=2, full=False):
1633N/A """Optionally emit a usage message and then exit using the specified
1633N/A exit code."""
1633N/A
466N/A if text:
466N/A emsg(text)
466N/A
1633N/A if not full:
1633N/A # The full usage message isn't desired.
1633N/A emsg(_("Try `pkg.depotd --help or -?' for more "
1633N/A "information."))
1633N/A sys.exit(retcode)
1633N/A
3143N/A print("""\
2230N/AUsage: /usr/lib/pkg.depotd [-a address] [-d inst_root] [-p port] [-s threads]
1968N/A [-t socket_timeout] [--cfg] [--content-root]
1633N/A [--disable-ops op[/1][,...]] [--debug feature_list]
2515N/A [--image-root dir] [--log-access dest] [--log-errors dest]
2816N/A [--mirror] [--nasty] [--nasty-sleep] [--proxy-base url]
2816N/A [--readonly] [--ssl-cert-file] [--ssl-dialog] [--ssl-key-file]
1937N/A [--sort-file-max-size size] [--writable-root dir]
382N/A
2230N/A -a address The IP address on which to listen for connections. The
2230N/A default value is 0.0.0.0 (INADDR_ANY) which will listen
2230N/A on all active interfaces. To listen on all active IPv6
2230N/A interfaces, use '::'.
2028N/A -d inst_root The file system path at which the server should find its
1968N/A repository data. Required unless PKG_REPO has been set
1968N/A in the environment.
2028N/A -p port The port number on which the instance should listen for
1968N/A incoming package requests. The default value is 80 if
1968N/A ssl certificate and key information has not been
1968N/A provided; otherwise, the default value is 443.
2028N/A -s threads The number of threads that will be started to serve
2028N/A requests. The default value is 10.
2028N/A -t timeout The maximum number of seconds the server should wait for
1968N/A a response from a client before closing a connection.
1968N/A The default value is 60.
1968N/A --cfg The pathname of the file to use when reading and writing
1968N/A depot configuration data, or a fully qualified service
1968N/A fault management resource identifier (FMRI) of the SMF
1968N/A service or instance to read configuration data from.
589N/A --content-root The file system path to the directory containing the
589N/A the static and other web content used by the depot's
589N/A browser user interface. The default value is
589N/A '/usr/share/lib/pkg'.
1431N/A --disable-ops A comma separated list of operations that the depot
1431N/A should not configure. If, for example, you wanted
1431N/A to omit loading search v1, 'search/1' should be
1431N/A provided as an argument, or to disable all search
1431N/A operations, simply 'search'.
858N/A --debug The name of a debug feature to enable; or a whitespace
1633N/A or comma separated list of features to enable.
2962N/A Possible values are: headers, hash=sha1+sha256,
3445N/A hash=sha256, hash=sha1+sha512t_256, hash=sha512t_256
2515N/A --image-root The path to the image whose file information will be
2515N/A used as a cache for file data.
466N/A --log-access The destination for any access related information
466N/A logged by the depot process. Possible values are:
466N/A stderr, stdout, none, or an absolute pathname. The
466N/A default value is stdout if stdout is a tty; otherwise
466N/A the default value is none.
466N/A --log-errors The destination for any errors or other information
466N/A logged by the depot process. Possible values are:
466N/A stderr, stdout, none, or an absolute pathname. The
466N/A default value is stderr.
589N/A --mirror Package mirror mode; publishing and metadata operations
589N/A disallowed. Cannot be used with --readonly or
589N/A --rebuild.
1191N/A --nasty Instruct the server to misbehave. At random intervals
1191N/A it will time-out, send bad responses, hang up on
1191N/A clients, and generally be hostile. The option
1191N/A takes a value (1 to 100) for how nasty the server
1191N/A should be.
2816N/A --nasty-sleep In nasty mode (see --nasty), how many seconds to
2816N/A randomly sleep when a random sleep occurs.
589N/A --proxy-base The url to use as the base for generating internal
589N/A redirects and content.
589N/A --readonly Read-only operation; modifying operations disallowed.
589N/A Cannot be used with --mirror or --rebuild.
812N/A --ssl-cert-file The absolute pathname to a PEM-encoded Certificate file.
812N/A This option must be used with --ssl-key-file. Usage of
812N/A this option will cause the depot to only respond to SSL
812N/A requests on the provided port.
812N/A --ssl-dialog Specifies what method should be used to obtain the
812N/A passphrase needed to decrypt the file specified by
812N/A --ssl-key-file. Supported values are: builtin,
1968N/A exec:/path/to/program, smf, or an SMF FMRI. The
1968N/A default value is builtin. If smf is specified, an
1968N/A SMF FMRI must be provided using the --cfg option.
812N/A --ssl-key-file The absolute pathname to a PEM-encoded Private Key file.
812N/A This option must be used with --ssl-cert-file. Usage of
812N/A this option will cause the depot to only respond to SSL
812N/A requests on the provided port.
1475N/A --sort-file-max-size
1475N/A The maximum size of the indexer sort file. Used to
1475N/A limit the amount of RAM the depot uses for indexing,
1475N/A or increase it for speed.
975N/A --writable-root The path to a directory to which the program has write
975N/A access. Used with --readonly to allow server to
975N/A create needed files, such as search indices, without
975N/A needing write access to the package information.
1633N/AOptions:
1633N/A --help or -?
1633N/A
1633N/AEnvironment:
2028N/A PKG_REPO Used as default inst_root if -d not provided.
1633N/A PKG_DEPOT_CONTENT Used as default content_root if --content-root
3143N/A not provided.""")
1633N/A sys.exit(retcode)
14N/A
382N/Aclass OptionError(Exception):
429N/A """Option exception. """
14N/A
404N/A def __init__(self, *args):
404N/A Exception.__init__(self, *args)
30N/A
382N/Aif __name__ == "__main__":
30N/A
791N/A setlocale(locale.LC_ALL, "")
2728N/A gettext.install("pkg", "/usr/share/locale",
2728N/A codeset=locale.getpreferredencoding())
689N/A
1968N/A add_content = False
1968N/A exit_ready = False
1968N/A rebuild = False
1968N/A reindex = False
1191N/A nasty = False
258N/A
1968N/A # Track initial configuration values.
2816N/A ivalues = { "pkg": {}, "nasty": {} }
382N/A if "PKG_REPO" in os.environ:
1968N/A ivalues["pkg"]["inst_root"] = os.environ["PKG_REPO"]
30N/A
589N/A try:
589N/A content_root = os.environ["PKG_DEPOT_CONTENT"]
1968N/A ivalues["pkg"]["content_root"] = content_root
589N/A except KeyError:
589N/A try:
589N/A content_root = os.path.join(os.environ['PKG_HOME'],
589N/A 'share/lib/pkg')
1968N/A ivalues["pkg"]["content_root"] = content_root
589N/A except KeyError:
1968N/A pass
466N/A
466N/A opt = None
2230N/A addresses = set()
1968N/A debug_features = []
1968N/A disable_ops = []
1431N/A repo_props = {}
1968N/A socket_path = ""
1968N/A user_cfg = None
54N/A try:
1968N/A long_opts = ["add-content", "cfg=", "cfg-file=",
1968N/A "content-root=", "debug=", "disable-ops=", "exit-ready",
2515N/A "help", "image-root=", "log-access=", "log-errors=",
2816N/A "llmirror", "mirror", "nasty=", "nasty-sleep=",
2816N/A "proxy-base=", "readonly", "rebuild", "refresh-index",
2816N/A "set-property=", "ssl-cert-file=", "ssl-dialog=",
2816N/A "ssl-key-file=", "sort-file-max-size=", "writable-root="]
1475N/A
2230N/A opts, pargs = getopt.getopt(sys.argv[1:], "a:d:np:s:t:?",
466N/A long_opts)
1633N/A
1633N/A show_usage = False
135N/A for opt, arg in opts:
2230N/A if opt == "-a":
2230N/A addresses.add(arg)
2230N/A elif opt == "-n":
135N/A sys.exit(0)
135N/A elif opt == "-d":
1968N/A ivalues["pkg"]["inst_root"] = arg
135N/A elif opt == "-p":
1968N/A ivalues["pkg"]["port"] = arg
382N/A elif opt == "-s":
382N/A threads = int(arg)
382N/A if threads < THREADS_MIN:
3194N/A raise OptionError(
3158N/A "minimum value is {0:d}".format(
3194N/A THREADS_MIN))
382N/A if threads > THREADS_MAX:
3194N/A raise OptionError(
3158N/A "maximum value is {0:d}".format(
3194N/A THREADS_MAX))
1968N/A ivalues["pkg"]["threads"] = threads
382N/A elif opt == "-t":
1968N/A ivalues["pkg"]["socket_timeout"] = arg
1542N/A elif opt == "--add-content":
1542N/A add_content = True
1968N/A elif opt == "--cfg":
1968N/A user_cfg = arg
812N/A elif opt == "--cfg-file":
1968N/A ivalues["pkg"]["cfg_file"] = arg
589N/A elif opt == "--content-root":
1968N/A ivalues["pkg"]["content_root"] = arg
858N/A elif opt == "--debug":
858N/A if arg is None or arg == "":
1968N/A continue
858N/A
858N/A # A list of features can be specified using a
858N/A # "," or any whitespace character as separators.
858N/A if "," in arg:
858N/A features = arg.split(",")
858N/A else:
858N/A features = arg.split()
1968N/A debug_features.extend(features)
2962N/A
2962N/A # We also allow key=value debug flags, which
2962N/A # get set in pkg.client.debugvalues
2962N/A for feature in features:
2962N/A try:
2962N/A key, val = feature.split("=", 1)
2962N/A DebugValues.set_value(key, val)
2962N/A except (AttributeError, ValueError):
2962N/A pass
2962N/A
1431N/A elif opt == "--disable-ops":
1431N/A if arg is None or arg == "":
3194N/A raise OptionError(
3194N/A "An argument must be specified.")
1431N/A
1431N/A disableops = arg.split(",")
1431N/A for s in disableops:
1431N/A if "/" in s:
1431N/A op, ver = s.rsplit("/", 1)
1431N/A else:
1431N/A op = s
1431N/A ver = "*"
1431N/A
1431N/A if op not in \
1431N/A ds.DepotHTTP.REPO_OPS_DEFAULT:
1431N/A raise OptionError(
1431N/A "Invalid operation "
3158N/A "'{0}'.".format(s))
1968N/A disable_ops.append(s)
1542N/A elif opt == "--exit-ready":
1542N/A exit_ready = True
2515N/A elif opt == "--image-root":
2515N/A ivalues["pkg"]["image_root"] = arg
1968N/A elif opt.startswith("--log-"):
3158N/A prop = "log_{0}".format(opt.lstrip("--log-"))
1968N/A ivalues["pkg"][prop] = arg
1633N/A elif opt in ("--help", "-?"):
1633N/A show_usage = True
589N/A elif opt == "--mirror":
1968N/A ivalues["pkg"]["mirror"] = True
1902N/A elif opt == "--llmirror":
1968N/A ivalues["pkg"]["mirror"] = True
1968N/A ivalues["pkg"]["ll_mirror"] = True
1968N/A ivalues["pkg"]["readonly"] = True
1191N/A elif opt == "--nasty":
2816N/A # ValueError is caught by caller.
2816N/A nasty_value = int(arg)
2816N/A if (nasty_value > 100 or nasty_value < 1):
3194N/A raise OptionError("Invalid value "
3194N/A "for nasty option.\n Please "
3194N/A "choose a value between 1 and 100.")
1191N/A nasty = True
2816N/A ivalues["nasty"]["nasty_level"] = nasty_value
2816N/A elif opt == "--nasty-sleep":
2816N/A # ValueError is caught by caller.
2816N/A sleep_value = int(arg)
2816N/A ivalues["nasty"]["nasty_sleep"] = sleep_value
589N/A elif opt == "--proxy-base":
589N/A # Attempt to decompose the url provided into
589N/A # its base parts. This is done so we can
589N/A # remove any scheme information since we
589N/A # don't need it.
589N/A scheme, netloc, path, params, query, \
3234N/A fragment = urlparse(arg,
765N/A "http", allow_fragments=0)
765N/A
765N/A if not netloc:
3194N/A raise OptionError("Unable to "
3194N/A "determine the hostname from "
3194N/A "the provided URL; please use a "
3194N/A "fully qualified URL.")
589N/A
765N/A scheme = scheme.lower()
765N/A if scheme not in ("http", "https"):
3194N/A raise OptionError("Invalid URL; http "
3194N/A "and https are the only supported "
3194N/A "schemes.")
765N/A
765N/A # Rebuild the url with the sanitized components.
1968N/A ivalues["pkg"]["proxy_base"] = \
3234N/A urlunparse((scheme, netloc, path,
1968N/A params, query, fragment))
135N/A elif opt == "--readonly":
1968N/A ivalues["pkg"]["readonly"] = True
157N/A elif opt == "--rebuild":
382N/A rebuild = True
429N/A elif opt == "--refresh-index":
429N/A # Note: This argument is for internal use
2028N/A # only.
2028N/A #
429N/A # This flag is purposefully omitted in usage.
429N/A # The supported way to forcefully reindex is to
429N/A # kill any pkg.depot using that directory,
429N/A # remove the index directory, and restart the
429N/A # pkg.depot process. The index will be rebuilt
429N/A # automatically on startup.
429N/A reindex = True
2028N/A exit_ready = True
1968N/A elif opt == "--set-property":
1968N/A try:
1968N/A prop, p_value = arg.split("=", 1)
1968N/A p_sec, p_name = prop.split(".", 1)
1968N/A except ValueError:
1968N/A usage(_("property arguments must be of "
1968N/A "the form '<section.property>="
1968N/A "<value>'."))
1968N/A repo_props.setdefault(p_sec, {})
1968N/A repo_props[p_sec][p_name] = p_value
812N/A elif opt == "--ssl-cert-file":
1968N/A if arg == "none" or arg == "":
1968N/A # Assume this is an override to clear
1968N/A # the value.
1968N/A arg = ""
1968N/A elif not os.path.isabs(arg):
3194N/A raise OptionError("The path to "
3194N/A "the Certificate file must be "
3194N/A "absolute.")
1968N/A elif not os.path.exists(arg):
3194N/A raise OptionError("The specified "
3194N/A "file does not exist.")
1968N/A elif not os.path.isfile(arg):
3194N/A raise OptionError("The specified "
3194N/A "pathname is not a file.")
1968N/A ivalues["pkg"]["ssl_cert_file"] = arg
812N/A elif opt == "--ssl-key-file":
1968N/A if arg == "none" or arg == "":
1968N/A # Assume this is an override to clear
1968N/A # the value.
1968N/A arg = ""
1968N/A elif not os.path.isabs(arg):
3194N/A raise OptionError("The path to "
3194N/A "the Private Key file must be "
3194N/A "absolute.")
1968N/A elif not os.path.exists(arg):
3194N/A raise OptionError("The specified "
3194N/A "file does not exist.")
1968N/A elif not os.path.isfile(arg):
3194N/A raise OptionError("The specified "
3194N/A "pathname is not a file.")
1968N/A ivalues["pkg"]["ssl_key_file"] = arg
812N/A elif opt == "--ssl-dialog":
1968N/A if arg != "builtin" and \
1968N/A arg != "smf" and not \
812N/A arg.startswith("exec:/") and not \
1968N/A arg.startswith("svc:"):
3194N/A raise OptionError("Invalid value "
3194N/A "specified. Expected: builtin, "
3194N/A "exec:/path/to/program, smf, or "
3194N/A "an SMF FMRI.")
812N/A
1968N/A if arg.startswith("exec:"):
812N/A if os_util.get_canonical_os_type() != \
812N/A "unix":
873N/A # Don't allow a somewhat
873N/A # insecure authentication method
873N/A # on some platforms.
3194N/A raise OptionError("exec is "
3194N/A "not a supported dialog "
3194N/A "type for this operating "
3194N/A "system.")
812N/A
1968N/A f = os.path.abspath(arg.split(
812N/A "exec:")[1])
812N/A if not os.path.isfile(f):
3194N/A raise OptionError("Invalid "
3194N/A "file path specified for "
3194N/A "exec.")
1968N/A ivalues["pkg"]["ssl_dialog"] = arg
1475N/A elif opt == "--sort-file-max-size":
1968N/A ivalues["pkg"]["sort_file_max_size"] = arg
975N/A elif opt == "--writable-root":
1968N/A ivalues["pkg"]["writable_root"] = arg
1968N/A
1968N/A # Set accumulated values.
1968N/A if debug_features:
1968N/A ivalues["pkg"]["debug"] = debug_features
1968N/A if disable_ops:
1968N/A ivalues["pkg"]["disable_ops"] = disable_ops
2230N/A if addresses:
2230N/A ivalues["pkg"]["address"] = list(addresses)
1968N/A
2962N/A if DebugValues:
2962N/A reload(pkg.digest)
2962N/A
1968N/A # Build configuration object.
1968N/A dconf = ds.DepotConfig(target=user_cfg, overrides=ivalues)
3171N/A except getopt.GetoptError as _e:
3158N/A usage("pkg.depotd: {0}".format(_e.msg))
3171N/A except api_errors.ApiException as _e:
3158N/A usage("pkg.depotd: {0}".format(str(_e)))
3171N/A except OptionError as _e:
3158N/A usage("pkg.depotd: option: {0} -- {1}".format(opt, _e))
382N/A except (ArithmeticError, ValueError):
3158N/A usage("pkg.depotd: illegal option value: {0} specified " \
3158N/A "for option: {1}".format(arg, opt))
451N/A
1633N/A if show_usage:
1633N/A usage(retcode=0, full=True)
1633N/A
1968N/A if not dconf.get_property("pkg", "log_errors"):
1968N/A dconf.set_property("pkg", "log_errors", "stderr")
1968N/A
1968N/A # If stdout is a tty, then send access output there by default instead
1968N/A # of discarding it.
1968N/A if not dconf.get_property("pkg", "log_access"):
1968N/A if os.isatty(sys.stdout.fileno()):
1968N/A dconf.set_property("pkg", "log_access", "stdout")
1968N/A else:
1968N/A dconf.set_property("pkg", "log_access", "none")
1968N/A
1968N/A # Check for invalid option combinations.
2515N/A image_root = dconf.get_property("pkg", "image_root")
2515N/A inst_root = dconf.get_property("pkg", "inst_root")
1968N/A mirror = dconf.get_property("pkg", "mirror")
2230N/A ll_mirror = dconf.get_property("pkg", "ll_mirror")
1968N/A readonly = dconf.get_property("pkg", "readonly")
1968N/A writable_root = dconf.get_property("pkg", "writable_root")
1542N/A if rebuild and add_content:
1542N/A usage("--add-content cannot be used with --rebuild")
445N/A if rebuild and reindex:
466N/A usage("--refresh-index cannot be used with --rebuild")
1542N/A if (rebuild or add_content) and (readonly or mirror):
1633N/A usage("--readonly and --mirror cannot be used with --rebuild "
1633N/A "or --add-content")
1020N/A if reindex and mirror:
1020N/A usage("--mirror cannot be used with --refresh-index")
1020N/A if reindex and readonly and not writable_root:
1020N/A usage("--readonly can only be used with --refresh-index if "
1020N/A "--writable-root is used")
2515N/A if image_root and not ll_mirror:
2515N/A usage("--image-root can only be used with --llmirror.")
2515N/A if image_root and writable_root:
2515N/A usage("--image_root and --writable-root cannot be used "
2515N/A "together.")
2515N/A if image_root and inst_root:
2515N/A usage("--image-root and -d cannot be used together.")
2515N/A
2515N/A # If the image format changes this may need to be reexamined.
2515N/A if image_root:
2515N/A inst_root = os.path.join(image_root, "var", "pkg")
451N/A
1968N/A # Set any values using defaults if they weren't provided.
2230N/A
2230N/A # Only use the first value for now; multiple bind addresses may be
2230N/A # supported later.
2230N/A address = dconf.get_property("pkg", "address")
2230N/A if address:
2230N/A address = address[0]
2230N/A elif not address:
2230N/A dconf.set_property("pkg", "address", [HOST_DEFAULT])
2230N/A address = dconf.get_property("pkg", "address")[0]
2230N/A
2515N/A if not inst_root:
2515N/A usage("Either PKG_REPO or -d must be provided")
1902N/A
1968N/A content_root = dconf.get_property("pkg", "content_root")
1968N/A if not content_root:
1968N/A dconf.set_property("pkg", "content_root", CONTENT_PATH_DEFAULT)
1968N/A content_root = dconf.get_property("pkg", "content_root")
1968N/A
1968N/A port = dconf.get_property("pkg", "port")
1968N/A ssl_cert_file = dconf.get_property("pkg", "ssl_cert_file")
1968N/A ssl_key_file = dconf.get_property("pkg", "ssl_key_file")
812N/A if (ssl_cert_file and not ssl_key_file) or (ssl_key_file and not
812N/A ssl_cert_file):
812N/A usage("The --ssl-cert-file and --ssl-key-file options must "
812N/A "must both be provided when using either option.")
1968N/A elif not port:
1968N/A if ssl_cert_file and ssl_key_file:
1968N/A dconf.set_property("pkg", "port", SSL_PORT_DEFAULT)
1968N/A else:
1968N/A dconf.set_property("pkg", "port", PORT_DEFAULT)
1968N/A port = dconf.get_property("pkg", "port")
1968N/A
1968N/A socket_timeout = dconf.get_property("pkg", "socket_timeout")
1968N/A if not socket_timeout:
1968N/A dconf.set_property("pkg", "socket_timeout",
1968N/A SOCKET_TIMEOUT_DEFAULT)
1968N/A socket_timeout = dconf.get_property("pkg", "socket_timeout")
1968N/A
1968N/A threads = dconf.get_property("pkg", "threads")
1968N/A if not threads:
1968N/A dconf.set_property("pkg", "threads", THREADS_DEFAULT)
1968N/A threads = dconf.get_property("pkg", "threads")
812N/A
429N/A # If the program is going to reindex, the port is irrelevant since
429N/A # the program will not bind to a port.
2028N/A if not exit_ready:
1836N/A try:
2230N/A cherrypy.process.servers.check_port(address, port)
3171N/A except Exception as e:
1836N/A emsg("pkg.depotd: unable to bind to the specified "
3158N/A "port: {0:d}. Reason: {1}".format(port, e))
429N/A sys.exit(1)
612N/A else:
1542N/A # Not applicable if we're not going to serve content
1968N/A dconf.set_property("pkg", "content_root", "")
1968N/A
1968N/A # Any relative paths should be made absolute using pkg_root. 'pkg_root'
1968N/A # is a special property that was added to enable internal deployment of
1968N/A # multiple disparate versions of the pkg.depotd software.
1968N/A pkg_root = dconf.get_property("pkg", "pkg_root")
1968N/A
1968N/A repo_config_file = dconf.get_property("pkg", "cfg_file")
1968N/A if repo_config_file and not os.path.isabs(repo_config_file):
1968N/A repo_config_file = os.path.join(pkg_root, repo_config_file)
1968N/A
1968N/A if content_root and not os.path.isabs(content_root):
1968N/A content_root = os.path.join(pkg_root, content_root)
1968N/A
1968N/A if inst_root and not os.path.isabs(inst_root):
1968N/A inst_root = os.path.join(pkg_root, inst_root)
1968N/A
1968N/A if ssl_cert_file:
1968N/A if ssl_cert_file == "none":
1968N/A ssl_cert_file = None
1968N/A elif not os.path.isabs(ssl_cert_file):
1968N/A ssl_cert_file = os.path.join(pkg_root, ssl_cert_file)
1968N/A
1968N/A if ssl_key_file:
1968N/A if ssl_key_file == "none":
1968N/A ssl_key_file = None
1968N/A elif not os.path.isabs(ssl_key_file):
1968N/A ssl_key_file = os.path.join(pkg_root, ssl_key_file)
1968N/A
1968N/A if writable_root and not os.path.isabs(writable_root):
1968N/A writable_root = os.path.join(pkg_root, writable_root)
1968N/A
1968N/A # Setup SSL if requested.
812N/A key_data = None
1968N/A ssl_dialog = dconf.get_property("pkg", "ssl_dialog")
2028N/A if not exit_ready and ssl_cert_file and ssl_key_file and \
812N/A ssl_dialog != "builtin":
812N/A cmdline = None
812N/A def get_ssl_passphrase(*ignored):
812N/A p = None
812N/A try:
3273N/A if cmdline:
3273N/A cmdargs = shlex.split(cmdline)
3273N/A else:
3273N/A cmdargs = []
3273N/A p = subprocess.Popen(cmdargs,
812N/A stdout=subprocess.PIPE,
812N/A stderr=None)
812N/A p.wait()
3171N/A except Exception as __e:
1836N/A emsg("pkg.depotd: an error occurred while "
3158N/A "executing [{0}]; unable to obtain the "
1836N/A "passphrase needed to decrypt the SSL "
3158N/A "private key file: {1}".format(cmdline,
3158N/A __e))
812N/A sys.exit(1)
3339N/A return p.stdout.read().strip(b"\n")
812N/A
812N/A if ssl_dialog.startswith("exec:"):
1968N/A exec_path = ssl_dialog.split("exec:")[1]
1968N/A if not os.path.isabs(exec_path):
1968N/A exec_path = os.path.join(pkg_root, exec_path)
3158N/A cmdline = "{0} {1} {2:d}".format(exec_path, "''", port)
1968N/A elif ssl_dialog == "smf" or ssl_dialog.startswith("svc:"):
1968N/A if ssl_dialog == "smf":
1968N/A # Assume the configuration target was an SMF
1968N/A # FMRI and let svcprop fail with an error if
1968N/A # it wasn't.
1968N/A svc_fmri = dconf.target
1968N/A else:
1968N/A svc_fmri = ssl_dialog
812N/A cmdline = "/usr/bin/svcprop -p " \
3158N/A "pkg_secure/ssl_key_passphrase {0}".format(svc_fmri)
812N/A
812N/A # The key file requires decryption, but the user has requested
812N/A # exec-based authentication, so it will have to be decoded first
812N/A # to an un-named temporary file.
812N/A try:
3234N/A with open(ssl_key_file, "rb") as key_file:
1968N/A pkey = crypto.load_privatekey(
1968N/A crypto.FILETYPE_PEM, key_file.read(),
1968N/A get_ssl_passphrase)
812N/A
3339N/A key_data = tempfile.NamedTemporaryFile(dir=pkg_root,
3339N/A delete=True)
812N/A key_data.write(crypto.dump_privatekey(
812N/A crypto.FILETYPE_PEM, pkey))
812N/A key_data.seek(0)
3171N/A except EnvironmentError as _e:
1836N/A emsg("pkg.depotd: unable to read the SSL private key "
3158N/A "file: {0}".format(_e))
812N/A sys.exit(1)
3171N/A except crypto.Error as _e:
1836N/A emsg("pkg.depotd: authentication or cryptography "
1836N/A "failure while attempting to decode\nthe SSL "
3158N/A "private key file: {0}".format(_e))
812N/A sys.exit(1)
812N/A else:
812N/A # Redirect the server to the decrypted key file.
3339N/A ssl_key_file = key_data.name
812N/A
452N/A # Setup our global configuration.
466N/A gconf = {
858N/A "checker.on": True,
382N/A "environment": "production",
466N/A "log.screen": False,
965N/A "server.max_request_body_size": MAX_REQUEST_BODY_SIZE,
858N/A "server.shutdown_timeout": 0,
2230N/A "server.socket_host": address,
382N/A "server.socket_port": port,
858N/A "server.socket_timeout": socket_timeout,
858N/A "server.ssl_certificate": ssl_cert_file,
858N/A "server.ssl_private_key": ssl_key_file,
382N/A "server.thread_pool": threads,
742N/A "tools.log_headers.on": True,
3339N/A "tools.encode.on": True,
3339N/A "tools.encode.encoding": "utf-8",
466N/A }
466N/A
1968N/A if "headers" in dconf.get_property("pkg", "debug"):
858N/A # Despite its name, this only logs headers when there is an
858N/A # error; it's redundant with the debug feature enabled.
858N/A gconf["tools.log_headers.on"] = False
858N/A
858N/A # Causes the headers of every request to be logged to the error
858N/A # log; even if an exception occurs.
858N/A gconf["tools.log_headers_always.on"] = True
858N/A cherrypy.tools.log_headers_always = cherrypy.Tool(
858N/A "on_start_resource",
858N/A cherrypy.lib.cptools.log_request_headers)
858N/A
2992N/A log_cfg = {
2992N/A "access": dconf.get_property("pkg", "log_access"),
2992N/A "errors": dconf.get_property("pkg", "log_errors")
2992N/A }
2992N/A
2992N/A # If stdin is not a tty and the pkgdepot controller isn't being used,
2992N/A # then assume process will be daemonized and redirect output.
2992N/A if not os.environ.get("PKGDEPOT_CONTROLLER") and \
2992N/A not os.isatty(sys.stdin.fileno()):
2992N/A # Ensure log handlers are setup to use the file descriptors for
2992N/A # stdout and stderr as the Daemonizer (used for test suite and
2992N/A # SMF service) requires this.
2992N/A if log_cfg["access"] == "stdout":
3158N/A log_cfg["access"] = "/dev/fd/{0:d}".format(
3158N/A sys.stdout.fileno())
2992N/A elif log_cfg["access"] == "stderr":
3158N/A log_cfg["access"] = "/dev/fd/{0:d}".format(
3158N/A sys.stderr.fileno())
2992N/A elif log_cfg["access"] == "none":
2992N/A log_cfg["access"] = "/dev/null"
2992N/A
2992N/A if log_cfg["errors"] == "stderr":
3158N/A log_cfg["errors"] = "/dev/fd/{0:d}".format(
3158N/A sys.stderr.fileno())
2992N/A elif log_cfg["errors"] == "stdout":
3158N/A log_cfg["errors"] = "/dev/fd/{0:d}".format(
3158N/A sys.stdout.fileno())
2992N/A elif log_cfg["errors"] == "none":
2992N/A log_cfg["errors"] = "/dev/null"
2992N/A
466N/A log_type_map = {
466N/A "errors": {
466N/A "param": "log.error_file",
466N/A "attr": "error_log"
466N/A },
466N/A "access": {
466N/A "param": "log.access_file",
466N/A "attr": "access_log"
466N/A }
466N/A }
466N/A
466N/A for log_type in log_type_map:
2992N/A dest = log_cfg[log_type]
466N/A if dest in ("stdout", "stderr", "none"):
466N/A if dest == "none":
466N/A h = logging.StreamHandler(LogSink())
466N/A else:
3158N/A h = logging.StreamHandler(eval("sys.{0}".format(
3158N/A dest)))
466N/A
466N/A h.setLevel(logging.DEBUG)
466N/A h.setFormatter(cherrypy._cplogging.logfmt)
3158N/A log_obj = eval("cherrypy.log.{0}".format(
3158N/A log_type_map[log_type]["attr"]))
466N/A log_obj.addHandler(h)
466N/A # Since we've replaced cherrypy's log handler with our
466N/A # own, we don't want the output directed to a file.
466N/A dest = ""
1968N/A elif dest:
1968N/A if not os.path.isabs(dest):
1968N/A dest = os.path.join(pkg_root, dest)
466N/A gconf[log_type_map[log_type]["param"]] = dest
382N/A
612N/A cherrypy.config.update(gconf)
612N/A
612N/A # Now that our logging, etc. has been setup, it's safe to perform any
612N/A # remaining preparation.
1431N/A
1431N/A # Initialize repository state.
2028N/A if not readonly:
2028N/A # Not readonly, so assume a new repository should be created.
2028N/A try:
2028N/A sr.repository_create(inst_root, properties=repo_props)
2028N/A except sr.RepositoryExistsError:
2028N/A # Already exists, nothing to do.
2028N/A pass
3171N/A except (api_errors.ApiException, sr.RepositoryError) as _e:
3158N/A emsg("pkg.depotd: {0}".format(_e))
2028N/A sys.exit(1)
2028N/A
1431N/A try:
1968N/A sort_file_max_size = dconf.get_property("pkg",
1968N/A "sort_file_max_size")
1968N/A
2028N/A repo = sr.Repository(cfgpathname=repo_config_file,
2515N/A log_obj=cherrypy, mirror=mirror, properties=repo_props,
2515N/A read_only=readonly, root=inst_root,
2515N/A sort_file_max_size=sort_file_max_size,
1431N/A writable_root=writable_root)
3171N/A except (RuntimeError, sr.RepositoryError) as _e:
3158N/A emsg("pkg.depotd: {0}".format(_e))
1431N/A sys.exit(1)
3171N/A except search_errors.IndexingException as _e:
3158N/A emsg("pkg.depotd: {0}".format(str(_e)), "INDEX")
1672N/A sys.exit(1)
3171N/A except api_errors.ApiException as _e:
3158N/A emsg("pkg.depotd: {0}".format(str(_e)))
1431N/A sys.exit(1)
1431N/A
2028N/A if not rebuild and not add_content and not repo.mirror and \
2028N/A not (repo.read_only and not repo.writable_root):
2028N/A # Automatically update search indexes on startup if not already
2028N/A # told to, and not in readonly/mirror mode.
2028N/A reindex = True
2028N/A
612N/A if reindex:
617N/A try:
2065N/A # Only execute a index refresh here if --exit-ready was
2065N/A # requested; it will be handled later in the setup
2065N/A # process for other cases.
2065N/A if repo.root and exit_ready:
2028N/A repo.refresh_index()
2028N/A except (sr.RepositoryError, search_errors.IndexingException,
3171N/A api_errors.ApiException) as e:
2028N/A emsg(str(e), "INDEX")
2028N/A sys.exit(1)
2028N/A elif rebuild:
2028N/A try:
2028N/A repo.rebuild(build_index=True)
3171N/A except sr.RepositoryError as e:
1431N/A emsg(str(e), "REBUILD")
1431N/A sys.exit(1)
975N/A except (search_errors.IndexingException,
1779N/A api_errors.UnknownErrors,
3171N/A api_errors.PermissionsException) as e:
1431N/A emsg(str(e), "INDEX")
617N/A sys.exit(1)
1542N/A elif add_content:
1542N/A try:
1542N/A repo.add_content()
2028N/A repo.refresh_index()
3171N/A except sr.RepositoryError as e:
1542N/A emsg(str(e), "ADD_CONTENT")
1542N/A sys.exit(1)
1542N/A except (search_errors.IndexingException,
1779N/A api_errors.UnknownErrors,
3171N/A api_errors.PermissionsException) as e:
1542N/A emsg(str(e), "INDEX")
1542N/A sys.exit(1)
1542N/A
2028N/A # Ready to start depot; exit now if requested.
1542N/A if exit_ready:
1542N/A sys.exit(0)
1542N/A
1431N/A # Next, initialize depot.
1431N/A if nasty:
1968N/A depot = ds.NastyDepotHTTP(repo, dconf)
1431N/A else:
1968N/A depot = ds.DepotHTTP(repo, dconf)
612N/A
451N/A # Now build our site configuration.
382N/A conf = {
3274N/A "/": {},
382N/A "/robots.txt": {
382N/A "tools.staticfile.on": True,
1431N/A "tools.staticfile.filename": os.path.join(depot.web_root,
382N/A "robots.txt")
382N/A },
382N/A }
3274N/A if list(map(int, version)) >= [3, 2, 0]:
3274N/A conf["/"]["request.dispatch"] = Pkg5Dispatcher()
145N/A
1968N/A proxy_base = dconf.get_property("pkg", "proxy_base")
451N/A if proxy_base:
451N/A # This changes the base URL for our server, and is primarily
451N/A # intended to allow our depot process to operate behind Apache
451N/A # or some other webserver process.
451N/A #
451N/A # Visit the following URL for more information:
451N/A # http://cherrypy.org/wiki/BuiltinTools#tools.proxy
451N/A proxy_conf = {
451N/A "tools.proxy.on": True,
451N/A "tools.proxy.local": "",
451N/A "tools.proxy.base": proxy_base
451N/A }
451N/A
451N/A # Now merge or add our proxy configuration information into the
451N/A # existing configuration.
451N/A for entry in proxy_conf:
451N/A conf["/"][entry] = proxy_conf[entry]
451N/A
1902N/A if ll_mirror:
2230N/A ds.DNSSD_Plugin(cherrypy.engine, gconf).subscribe()
1902N/A
2065N/A if reindex:
2065N/A # Tell depot to update search indexes when possible;
2065N/A # this is done as a background task so that packages
2065N/A # can be served immediately while search indexes are
2065N/A # still being updated.
2065N/A depot._queue_refresh_index()
2065N/A
2507N/A # If stdin is not a tty and the pkgdepot controller isn't being used,
2507N/A # then assume process should be daemonized.
2507N/A if not os.environ.get("PKGDEPOT_CONTROLLER") and \
2507N/A not os.isatty(sys.stdin.fileno()):
2992N/A # Translate the values in log_cfg into paths.
2992N/A Daemonizer(cherrypy.engine, stderr=log_cfg["errors"],
2992N/A stdout=log_cfg["access"]).subscribe()
2507N/A
814N/A try:
1431N/A root = cherrypy.Application(depot)
466N/A cherrypy.quickstart(root, config=conf)
3171N/A except Exception as _e:
812N/A emsg("pkg.depotd: unknown error starting depot server, " \
812N/A "illegal option value specified?")
873N/A emsg(_e)
812N/A sys.exit(1)