File: prewikka-httpd

package info (click to toggle)
prewikka 5.2.0-2.4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 9,560 kB
  • sloc: javascript: 72,921; python: 11,979; sh: 83; makefile: 30
file content (115 lines) | stat: -rw-r--r-- 4,344 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env python

# Copyright (C) 2004-2020 CS GROUP - France. All Rights Reserved.
# Author: Nicolas Delon <nicolas.delon@prelude-ids.com>
#
# This file is part of the Prewikka program.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import argparse
import locale
import multiprocessing
import socket
import ssl
import sys

from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server

from prewikka import localization, main, siteconfig, version
from prewikka.web import wsgi

global options


class WSGIRequest(WSGIRequestHandler):
    def log_message(self, format, *args):
        pass


class MyWSGIServer(WSGIServer):
    def handle_error(self, request, client_address):
        exc_type, exc_value = sys.exc_info()[:2]
        if issubclass(exc_type, socket.error) and exc_value.args[0] == 32:  # EPIPE
            return

        WSGIServer.handle_error(self, request, client_address)

    def serve_forever(self):
        # Preload Prewikka server
        main.Core.from_config(options.config)

        try:
            WSGIServer.serve_forever(self)
        except KeyboardInterrupt:
            pass


def application(environ, start_response):
    environ["PREWIKKA_CONFIG"] = options.config

    if options.root:
        if not environ['PATH_INFO'].startswith(options.root):
            start_response('301 Redirect', [('Location', options.root), ])
            return []

        environ['SCRIPT_NAME'] = options.root[:-1]
        environ['PATH_INFO'] = environ['PATH_INFO'][len(options.root) - 1:]

    return wsgi.application(environ, start_response)


def set_locale(lang):
    if lang[0] not in localization.get_languages():
        lang = "en_GB.utf8"
    else:
        lang = ".".join(lang)

    localization.translation.set_locale(lang)


if __name__ == "__main__":
    set_locale(locale.getdefaultlocale())

    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument("-r", "--root", help=_("root where the server is accessible"))
    parser.add_argument("-a", "--address", default="0.0.0.0", help=_("IP to bind to (default: %(default)s)"))
    parser.add_argument("-p", "--port", type=int, default=8000, help=_("port number to use (default: %(default)d)"))
    parser.add_argument("--key", help=_("SSL private key to use (default: no SSL)"))
    parser.add_argument("--cert", help=_("SSL certificate to use (default: no SSL)"))
    parser.add_argument("-c", "--config", default="%s/prewikka.conf" % siteconfig.conf_dir, help=_("configuration file to use (default: %(default)s)"))
    parser.add_argument("-m", "--multiprocess", type=int, default=multiprocessing.cpu_count(),
                        help=_("number of processes to use. Default value matches the number of available CPUs (i.e. %d)") % multiprocessing.cpu_count())
    parser.add_argument("-h", "--help", action="help", help=_("show this help message and exit"))
    parser.add_argument("-v", "--version", action="version", version=version.__version__, help=_("show program's version number and exit"))

    options = parser.parse_args()

    if options.root:
        options.root = "/%s/" % (options.root.strip("/"))

    server = make_server(options.address, options.port, application, server_class=MyWSGIServer, handler_class=WSGIRequest)
    if options.key and options.cert:
        server.socket = ssl.wrap_socket(server.socket, keyfile=options.key, certfile=options.cert, server_side=True)
        server.base_environ["HTTPS"] = "on"  # This is used by wsgiref to determine url_scheme

    for i in range(options.multiprocess - 1):
        p = multiprocessing.Process(target=server.serve_forever)
        p.daemon = True

        p.start()

    server.serve_forever()