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