Esempio n. 1
0
def standalone_main(config: SectionProxy) -> None:
    """Run REDbot as a standalone Web server."""

    # load static files
    static_types = {
        b'.js': b'text/javascript',
        b'.css': b'text/css',
        b'.png': b'image/png',
    }
    static_files = {}
    for root, dirs, files in os.walk(config['static_dir']):
        for name in files:
            try:
                path = os.path.join(root, name)
                uri = os.path.relpath(path, config['static_dir'])
                static_files[b"/static/%s" % uri.encode('utf-8')] = open(path, 'rb').read()
            except IOError:
                sys.stderr.write("* Problem loading %s\n" % path)

    def red_handler(x: EventEmitter) -> None:
        @thor.events.on(x)
        def request_start(method: bytes, uri: bytes, req_hdrs: RawHeaderListType) -> None:
            p_uri = urlsplit(uri)
            if p_uri.path in static_files:
                headers = []
                file_ext = os.path.splitext(p_uri.path)[1].lower()
                content_encoding = static_types.get(file_ext, b'application/octet-stream')
                headers.append((b'Content-Encoding', content_encoding))
                headers.append((b'Cache-Control', b'max-age=300'))
                x.response_start(b"200", b"OK", headers)
                x.response_body(static_files[p_uri.path])
                x.response_done([])
            elif p_uri.path == b"/":
                try:
                    RedWebUi(config, method.decode(config['charset']), p_uri.query,
                             x.response_start, x.response_body, x.response_done)
                except Exception:
                    sys.stderr.write("""

*** FATAL ERROR
REDbot has encountered a fatal error which it really, really can't recover from
in standalone server mode. Details follow.

""")
                    import traceback
                    traceback.print_exc()
                    thor.stop()
                    sys.exit(1)
            else:
                x.response_start(b"404", b"Not Found", [])
                x.response_done([])

    server = thor.http.HttpServer(config.get('host', ''), int(config['port']))
    server.on('exchange', red_handler)

    try:
        thor.run()
    except KeyboardInterrupt:
        sys.stderr.write("Stopping...\n")
        thor.stop()
Esempio n. 2
0
def cgi_main():
    """Run RED as a CGI Script."""
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 
    base_uri = "%s://%s%s%s" % (
      os.environ.has_key('HTTPS') and "https" or "http",
      os.environ.get('HTTP_HOST'),
      os.environ.get('SCRIPT_NAME'),
      os.environ.get('PATH_INFO', '')
    )
    method = os.environ.get('REQUEST_METHOD')
    query_string = cgi.parse_qs(os.environ.get('QUERY_STRING', ""))
    
    def response_start(code, phrase, res_hdrs):
        sys.stdout.write("Status: %s %s\n" % (code, phrase))
        for k, v in res_hdrs:
            sys.stdout.write("%s: %s\n" % (k, v))
        sys.stdout.write("\n")
        return sys.stdout.write, thor.stop
    def response_done(trailers):
        thor.schedule(0, thor.stop)
    try:
        RedWebUi(base_uri, method, query_string, 
                 response_start, sys.stdout.write, response_done)
        thor.run()
    except:
        except_handler_factory(sys.stdout.write)()
Esempio n. 3
0
def standalone_main(host, port, static_dir):
    """Run RED as a standalone Web server."""
    
    # load static files
    static_files = {}
    def static_walker(arg, dirname, names):
        for name in names:
            try:
                path = os.path.join(dirname, name)
                if os.path.isdir(path):
                    continue
                uri = os.path.relpath(path, static_dir)
                static_files["/static/%s" % uri] = open(path).read()
            except IOError:
                sys.stderr.write(
                  "* Problem loading %s\n" % path
                )
    os.path.walk(static_dir, static_walker, "")

    def red_handler(x):
        @thor.events.on(x)
        def request_start(method, uri, req_hdrs):
            p_uri = urlsplit(uri)
            if static_files.has_key(p_uri.path):
                x.response_start("200", "OK", []) # TODO: headers
                x.response_body(static_files[p_uri.path])
                x.response_done([])
            elif p_uri.path == "/":
                query_string = cgi.parse_qs(p_uri.query)
                try:
                    RedWebUi('/', method, query_string,
                             x.response_start, 
                             x.response_body,
                             x.response_done
                            )
                except RuntimeError:
                    raise
                    sys.stderr.write("""

*** FATAL ERROR
RED has encountered a fatal error which it really, really can't recover from
in standalone server mode. Details follow.

""")
                    except_handler_factory(sys.stderr.write)()
                    sys.stderr.write("\n")
                    thor.stop()
                    sys.exit(1)
            else:
                x.response_start("404", "Not Found", [])
                x.response_done([])

    server = thor.http.HttpServer(host, port)
    server.on('exchange', red_handler)
    
    try:
        thor.run()
    except KeyboardInterrupt:
        sys.stderr.write("Stopping...\n")
        thor.stop()
Esempio n. 4
0
def cgi_main():
    """Run RED as a CGI Script."""
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    base_uri = "http://%s%s%s" % (  # TODO: only supports HTTP
        os.environ.get('HTTP_HOST'), os.environ.get('SCRIPT_NAME'),
        os.environ.get('PATH_INFO', ''))
    method = os.environ.get('REQUEST_METHOD')
    query_string = cgi.parse_qs(os.environ.get('QUERY_STRING', ""))

    def response_start(code, phrase, res_hdrs):
        sys.stdout.write("Status: %s %s\n" % (code, phrase))
        for k, v in res_hdrs:
            sys.stdout.write("%s: %s\n" % (k, v))
        sys.stdout.write("\n")
        return sys.stdout.write, thor.stop

    def response_done(trailers):
        thor.schedule(0, thor.stop)

    try:
        RedWebUi(base_uri, method, query_string, response_start,
                 sys.stdout.write, response_done)
        thor.run()
    except:
        except_handler_factory(sys.stdout.write)()
Esempio n. 5
0
def standalone_main(port, static_dir):
    """Run RED as a standalone Web server."""

    # load static files
    static_files = {}

    def static_walker(arg, dirname, names):
        for name in names:
            try:
                path = os.path.join(dirname, name)
                if os.path.isdir(path):
                    continue
                uri = os.path.relpath(path, static_dir)
                static_files["/static/%s" % uri] = open(path).read()
            except IOError:
                sys.stderr.write("* Problem loading %s\n" % path)

    os.path.walk(static_dir, static_walker, "")
    sys.stderr.write("* Static files loaded.\n")

    def red_handler(x):
        @thor.events.on(x)
        def request_start(method, uri, req_hdrs):
            p_uri = urlsplit(uri)
            if static_files.has_key(p_uri.path):
                x.response_start("200", "OK", [])  # TODO: headers
                x.response_body(static_files[p_uri.path])
                x.response_done([])
            elif p_uri.path == "/":
                query_string = cgi.parse_qs(p_uri.query)
                try:
                    RedWebUi('/', method, query_string, x.response_start,
                             x.response_body, x.response_done)
                except RuntimeError:
                    raise
                    sys.stderr.write("""

*** FATAL ERROR
RED has encountered a fatal error which it really, really can't recover from
in standalone server mode. Details follow.

""")
                    except_handler_factory(sys.stderr.write)()
                    sys.stderr.write("\n")
                    thor.stop()
                    sys.exit(1)
            else:
                x.response_start("404", "Not Found", [])
                x.response_done([])

    server = thor.HttpServer("", port)
    server.on('exchange', red_handler)

    try:
        thor.run()
    except KeyboardInterrupt:
        sys.stderr.write("Stopping...\n")
        thor.stop()
Esempio n. 6
0
 def __init__(self, inp, handle_result, processor, *proc_args):
     self.input = inp
     self.handle_result = handle_result
     self.processor = processor
     self.proc_args = proc_args
     self.running = True
     self.outstanding = 0
     self.line_num = 0
     schedule(0, self.schedule_lines)
     run()
Esempio n. 7
0
 def __init__(self) -> None:
     # Set up the watchdog
     if os.environ.get("SYSTEMD_WATCHDOG"):
         thor.schedule(self.watchdog_freq, self.watchdog_ping)
         signal.signal(signal.SIGABRT, self.abrt_handler)
     # Set up the server
     server = thor.http.HttpServer(config.get("host", ""),
                                   int(config["port"]))
     server.on("exchange", RedHandler)
     try:
         thor.run()
     except KeyboardInterrupt:
         sys.stderr.write("Stopping...\n")
         thor.stop()
Esempio n. 8
0
def cgi_main(config: SectionProxy) -> None:
    """Run REDbot as a CGI Script."""
    def out(inbytes: bytes) -> None:
        try:
            sys.stdout.buffer.write(inbytes)
            sys.stdout.flush()
        except IOError:
            pass

    config['ui_uri'] = "%s://%s%s%s" % ('HTTPS' in os.environ and "https"
                                        or "http", os.environ.get('HTTP_HOST'),
                                        os.environ.get('SCRIPT_NAME'),
                                        os.environ.get('PATH_INFO', ''))
    method = os.environ.get('REQUEST_METHOD').encode(config['charset'])
    query_string = os.environ.get('QUERY_STRING', "").encode(config['charset'])
    req_hdrs = []  # type: RawHeaderListType
    for (k, v) in os.environ:
        if k[:5] == 'HTTP_':
            req_hdrs.append((k[:5].lower().encode('ascii'), v.encode('ascii')))

    def response_start(code: bytes, phrase: bytes,
                       res_hdrs: RawHeaderListType) -> None:
        out_v = [b"Status: %s %s" % (code, phrase)]
        for name, value in res_hdrs:
            out_v.append(b"%s: %s" % (name, value))
        out_v.append(b"")
        out_v.append(b"")
        out(b"\n".join(out_v))

    freak_ceiling = 20000

    def response_body(chunk: bytes) -> None:
        rest = None
        if len(chunk) > freak_ceiling:
            rest = chunk[freak_ceiling:]
            chunk = chunk[:freak_ceiling]
        out(chunk)
        if rest:
            response_body(rest)

    def response_done(trailers: RawHeaderListType) -> None:
        thor.schedule(0, thor.stop)

    try:
        RedWebUi(config, method.decode(config['charset']), query_string,
                 req_hdrs, response_start, response_body, response_done)
        thor.run()
    except Exception:
        except_handler_factory(config,
                               qs=query_string.decode(config['charset']))()
Esempio n. 9
0
def cgi_main(config: SectionProxy) -> None:
    """Run REDbot as a CGI Script."""
    def out(inbytes: bytes) -> None:
        try:
            sys.stdout.buffer.write(inbytes)
            sys.stdout.flush()
        except IOError:
            pass

    config['ui_uri'] = "%s://%s%s%s" % (
        'HTTPS' in os.environ and "https" or "http",
        os.environ.get('HTTP_HOST'),
        os.environ.get('SCRIPT_NAME'),
        os.environ.get('PATH_INFO', ''))
    method = os.environ.get('REQUEST_METHOD').encode(config['charset'])
    query_string = os.environ.get('QUERY_STRING', "").encode(config['charset'])
    req_hdrs = [] # type: RawHeaderListType
    for (k,v) in os.environ:
        if k[:5] == 'HTTP_':
            req_hdrs.append((k[:5].lower().encode('ascii'), v.encode('ascii')))

    def response_start(code: bytes, phrase: bytes, res_hdrs: RawHeaderListType) -> None:
        out_v = [b"Status: %s %s" % (code, phrase)]
        for name, value in res_hdrs:
            out_v.append(b"%s: %s" % (name, value))
        out_v.append(b"")
        out_v.append(b"")
        out(b"\n".join(out_v))

    freak_ceiling = 20000
    def response_body(chunk: bytes) -> None:
        rest = None
        if len(chunk) > freak_ceiling:
            rest = chunk[freak_ceiling:]
            chunk = chunk[:freak_ceiling]
        out(chunk)
        if rest:
            response_body(rest)

    def response_done(trailers: RawHeaderListType) -> None:
        thor.schedule(0, thor.stop)

    try:
        RedWebUi(config, method.decode(config['charset']), query_string, req_hdrs,
                 response_start, response_body, response_done)
        thor.run()
    except Exception:
        except_handler_factory(config, qs=query_string.decode(config['charset']))()
Esempio n. 10
0
 def __init__(self, config: SectionProxy) -> None:
     self.config = config
     self.static_files = {}    # type: Dict[bytes, bytes]
     # Load static files
     self.walk_files(config['asset_dir'], b"static/")
     if config.get('extra_base_dir'):
         self.walk_files(config['extra_base_dir'])
     # Set up the watchdog
     if os.environ.get("SYSTEMD_WATCHDOG"):
         thor.schedule(self.watchdog_freq, self.watchdog_ping)
     # Set up the server
     server = thor.http.HttpServer(config.get('host', ''), int(config['port']))
     server.on('exchange', self.red_handler)
     try:
         thor.run()
     except KeyboardInterrupt:
         sys.stderr.write("Stopping...\n")
         thor.stop()
Esempio n. 11
0
def cgi_main():
    """Run REDbot as a CGI Script."""
    def out(inbytes):
        try:
            sys.stdout.buffer.write(inbytes)
            sys.stdout.flush()
        except IOError:
            pass

    ui_uri = "%s://%s%s%s" % ('HTTPS' in os.environ and "https"
                              or "http", os.environ.get('HTTP_HOST'),
                              os.environ.get('SCRIPT_NAME'),
                              os.environ.get('PATH_INFO', ''))
    method = os.environ.get('REQUEST_METHOD').encode(Config.charset)
    query_string = os.environ.get('QUERY_STRING', "").encode(Config.charset)

    def response_start(code, phrase, res_hdrs):
        out_v = [b"Status: %s %s" % (code, phrase)]
        for k, v in res_hdrs:
            out_v.append(b"%s: %s" % (k, v))
        out_v.append(b"")
        out_v.append(b"")
        out(b"\n".join(out_v))

    freak_ceiling = 20000

    def response_body(chunk):
        rest = None
        if len(chunk) > freak_ceiling:
            rest = chunk[freak_ceiling:]
            chunk = chunk[:freak_ceiling]
        out(chunk)
        if rest:
            response_body(rest)

    def response_done(trailers):
        thor.schedule(0, thor.stop)

    try:
        RedWebUi(Config, ui_uri, method, query_string, response_start,
                 response_body, response_done)
        thor.run()
    except:
        except_handler_factory(Config, qs=query_string)()
Esempio n. 12
0
 def __init__(self, config: SectionProxy) -> None:
     self.config = config
     self.static_files = {}  # type: Dict[bytes, bytes]
     # Load static files
     self.walk_files(config['asset_dir'], b"static/")
     if config.get('extra_base_dir'):
         self.walk_files(config['extra_base_dir'])
     # Set up the watchdog
     if os.environ.get("SYSTEMD_WATCHDOG"):
         thor.schedule(self.watchdog_freq, self.watchdog_ping)
     # Set up the server
     server = thor.http.HttpServer(config.get('host', ''),
                                   int(config['port']))
     server.on('exchange', self.red_handler)
     try:
         thor.run()
     except KeyboardInterrupt:
         sys.stderr.write("Stopping...\n")
         thor.stop()
Esempio n. 13
0
def cgi_main():
    """Run REDbot as a CGI Script."""
    def out(inbytes):
        try:
            sys.stdout.buffer.write(inbytes)             
            sys.stdout.flush()
        except IOError: 
            pass
            
    ui_uri = "%s://%s%s%s" % (
        'HTTPS' in os.environ and "https" or "http",
        os.environ.get('HTTP_HOST'),
        os.environ.get('SCRIPT_NAME'),
        os.environ.get('PATH_INFO', ''))
    method = os.environ.get('REQUEST_METHOD').encode(Config.charset)
    query_string = os.environ.get('QUERY_STRING', "").encode(Config.charset)

    def response_start(code, phrase, res_hdrs):
        out_v = [b"Status: %s %s" % (code, phrase)]
        for k, v in res_hdrs:
            out_v.append(b"%s: %s" % (k, v))
        out_v.append(b"")
        out_v.append(b"")
        out(b"\n".join(out_v))

    freak_ceiling = 20000
    def response_body(chunk):
        rest = None
        if len(chunk) > freak_ceiling:
            rest = chunk[freak_ceiling:]
            chunk = chunk[:freak_ceiling]
        out(chunk)
        if rest:
            response_body(rest)

    def response_done(trailers):
        thor.schedule(0, thor.stop)
    try:
        RedWebUi(Config, ui_uri, method, query_string,
                 response_start, response_body, response_done)
        thor.run()
    except:
        except_handler_factory(Config, qs=query_string)()
Esempio n. 14
0
    def __init__(self, config: SectionProxy) -> None:
        self.config = config
        self.handler = partial(RedHandler, server=self)

        # Set up the watchdog
        if os.environ.get("SYSTEMD_WATCHDOG"):
            thor.schedule(self.watchdog_freq, self.watchdog_ping)
            signal.signal(signal.SIGABRT, self.abrt_handler)

        # Read static files
        self.static_files = self.walk_files(self.config["asset_dir"], b"static/")
        if self.config.get("extra_base_dir"):
            self.static_files.update(self.walk_files(self.config["extra_base_dir"]))

        # Set up the server
        server = thor.http.HttpServer(
            self.config.get("host", ""), int(self.config["port"])
        )
        server.on("exchange", self.handler)
        try:
            thor.run()
        except KeyboardInterrupt:
            sys.stderr.write("Stopping...\n")
            thor.stop()
Esempio n. 15
0
        if isinstance(error, httperr.BodyForbiddenError):
            self.add_note('header-none', rs.BODY_NOT_ALLOWED)
#        elif isinstance(error, httperr.ExtraDataErr):
#            res.payload_len += len(err.get('detail', ''))
        elif isinstance(error, httperr.ChunkError):
            err_msg = error.detail[:20] or ""
            self.add_note('header-transfer-encoding', rs.BAD_CHUNK,
                chunk_sample=err_msg.encode('string_escape')
            )
        self.done()
        self.finish_task()


if "__main__" == __name__:
    import sys
    def status_p(msg):
        "Print status"
        print msg
    class TestFetcher(RedFetcher):
        "Test a fetcher."
        def done(self):
            print self.notes
    T = TestFetcher(
         sys.argv[1],
         req_hdrs=[(u'Accept-Encoding', u'gzip')],
         status_cb=status_p,
         name='test'
    )
    T.run()
    thor.run()
Esempio n. 16
0
def mod_python_handler(r):
    """Run RED as a mod_python handler."""
    from mod_python import apache
    status_lookup = {
     100: apache.HTTP_CONTINUE                     ,
     101: apache.HTTP_SWITCHING_PROTOCOLS          ,
     102: apache.HTTP_PROCESSING                   ,
     200: apache.HTTP_OK                           ,
     201: apache.HTTP_CREATED                      ,
     202: apache.HTTP_ACCEPTED                     ,
     200: apache.HTTP_OK                           ,
     200: apache.HTTP_OK                           ,
     201: apache.HTTP_CREATED                      ,
     202: apache.HTTP_ACCEPTED                     ,
     203: apache.HTTP_NON_AUTHORITATIVE            ,
     204: apache.HTTP_NO_CONTENT                   ,
     205: apache.HTTP_RESET_CONTENT                ,
     206: apache.HTTP_PARTIAL_CONTENT              ,
     207: apache.HTTP_MULTI_STATUS                 ,
     300: apache.HTTP_MULTIPLE_CHOICES             ,
     301: apache.HTTP_MOVED_PERMANENTLY            ,
     302: apache.HTTP_MOVED_TEMPORARILY            ,
     303: apache.HTTP_SEE_OTHER                    ,
     304: apache.HTTP_NOT_MODIFIED                 ,
     305: apache.HTTP_USE_PROXY                    ,
     307: apache.HTTP_TEMPORARY_REDIRECT           ,
     400: apache.HTTP_BAD_REQUEST                  ,
     401: apache.HTTP_UNAUTHORIZED                 ,
     402: apache.HTTP_PAYMENT_REQUIRED             ,
     403: apache.HTTP_FORBIDDEN                    ,
     404: apache.HTTP_NOT_FOUND                    ,
     405: apache.HTTP_METHOD_NOT_ALLOWED           ,
     406: apache.HTTP_NOT_ACCEPTABLE               ,
     407: apache.HTTP_PROXY_AUTHENTICATION_REQUIRED,
     408: apache.HTTP_REQUEST_TIME_OUT             ,
     409: apache.HTTP_CONFLICT                     ,
     410: apache.HTTP_GONE                         ,
     411: apache.HTTP_LENGTH_REQUIRED              ,
     412: apache.HTTP_PRECONDITION_FAILED          ,
     413: apache.HTTP_REQUEST_ENTITY_TOO_LARGE     ,
     414: apache.HTTP_REQUEST_URI_TOO_LARGE        ,
     415: apache.HTTP_UNSUPPORTED_MEDIA_TYPE       ,
     416: apache.HTTP_RANGE_NOT_SATISFIABLE        ,
     417: apache.HTTP_EXPECTATION_FAILED           ,
     422: apache.HTTP_UNPROCESSABLE_ENTITY         ,
     423: apache.HTTP_LOCKED                       ,
     424: apache.HTTP_FAILED_DEPENDENCY            ,
     426: apache.HTTP_UPGRADE_REQUIRED             ,
     500: apache.HTTP_INTERNAL_SERVER_ERROR        ,
     501: apache.HTTP_NOT_IMPLEMENTED              ,
     502: apache.HTTP_BAD_GATEWAY                  ,
     503: apache.HTTP_SERVICE_UNAVAILABLE          ,
     504: apache.HTTP_GATEWAY_TIME_OUT             ,
     505: apache.HTTP_VERSION_NOT_SUPPORTED        ,
     506: apache.HTTP_VARIANT_ALSO_VARIES          ,
     507: apache.HTTP_INSUFFICIENT_STORAGE         ,
     510: apache.HTTP_NOT_EXTENDED                 ,
    }    
    
    r.content_type = "text/html"
    def response_start(code, phrase, hdrs):
        r.status = status_lookup.get(
            int(code), 
            apache.HTTP_INTERNAL_SERVER_ERROR
        )
        for hdr in hdrs:
            r.headers_out[hdr[0]] = hdr[1]
    def response_done(trailers):
        thor.schedule(thor.stop)
    query_string = cgi.parse_qs(r.args or "")
    try:
        RedWebUi(r.unparsed_uri, r.method, query_string, 
                 response_start, r.write, response_done)
        thor.run()
    except:
        except_handler_factory(r.write)()
    return apache.OK
Esempio n. 17
0
File: tls.py Progetto: mnot/thor
            if isinstance(why, sys_ssl.SSLWantReadError):
#            if why == sys_ssl.SSL_ERROR_WANT_READ:
#                self.once('fd_readable', self.handshake)
                self.once('fd_writable', self.handshake) # Oh, Linux...
#            elif why == sys_ssl.SSL_ERROR_WANT_WRITE:
            elif isinstance(why, sys_ssl.SSLWantWriteError):
                self.once('fd_writable', self.handshake)
            else:
                self.handle_socket_error(why, 'ssl')
        except socket.error as why:
            self.handle_socket_error(why, 'ssl')


if __name__ == "__main__":
    import sys
    from thor import run
    test_host = sys.argv[1].encode('utf-8')

    def out(outbytes: bytes) -> None:
        sys.stdout.write(outbytes.decode('utf-8', 'replace'))

    def go(conn: TcpConnection) -> None:
        conn.on('data', out)
        conn.write(b"GET / HTTP/1.1\r\nHost: %s\r\n\r\n" % test_host)
        conn.pause(False)

    c = TlsClient()
    c.on('connect', go)
    c.connect(test_host, 443)
    run()
Esempio n. 18
0
 def work():
     red.run(thor.stop)
     thor.run()
     self.io_loop.add_callback(self.stop)
Esempio n. 19
0

if __name__ == "__main__":
    import sys
    import thor
    from redbot.resource.fetch import RedFetcher  # pylint: disable=ungrouped-imports

    T = RedFetcher()
    T.set_request(sys.argv[1], req_hdrs=[('Accept-Encoding', "gzip")])

    def show_link(base: str, link: str, tag: str, title: str) -> None:
        print("* [%s] %s -- %s" % (tag, base, link))

    P = HTMLLinkParser(T.response, [show_link], sys.stderr.write)

    @thor.events.on(T)
    def fetch_done() -> None:
        print('done')
        thor.stop()

    @thor.events.on(T)
    def status(msg: str) -> None:
        print(msg)

    @thor.events.on(T.response)
    def chunk(decoded_chunk: bytes) -> None:
        P.feed(decoded_chunk.decode(P.message.character_encoding, 'ignore'))

    T.check()
    thor.run()
Esempio n. 20
0
 def work():
     red.run(thor.stop)
     thor.run()
     self.io_loop.add_callback(self.stop)
Esempio n. 21
0
def standalone_main(host, port, static_dir):
    """Run REDbot as a standalone Web server."""

    # load static files
    static_types = {
        '.js': b'text/javascript',
        '.css': b'text/css',
        '.png': b'image/png',
    }
    static_files = {}
    for root, dirs, files in os.walk(static_dir):
        for name in files:
            try:
                path = os.path.join(root, name)
                uri = os.path.relpath(path, static_dir)
                static_files[b"/static/%s" % uri.encode('utf-8')] = open(
                    path, 'rb').read()
            except IOError:
                sys.stderr.write("* Problem loading %s\n" % path)

    def red_handler(x):
        @thor.events.on(x)
        def request_start(method, uri, req_hdrs):
            p_uri = urlsplit(uri)
            if p_uri.path in static_files:
                headers = []
                file_ext = os.path.splitext(p_uri.path)[1].lower()
                content_encoding = static_types.get(
                    file_ext, b'application/octet-stream')
                headers.append((b'Content-Encoding', content_encoding))
                headers.append((b'Cache-Control', b'max-age=300'))
                x.response_start(b"200", b"OK", headers)
                x.response_body(static_files[p_uri.path])
                x.response_done([])
            elif p_uri.path == b"/":
                try:
                    RedWebUi(Config, '/', method, p_uri.query,
                             x.response_start, x.response_body,
                             x.response_done)
                except Exception:
                    sys.stderr.write("""

*** FATAL ERROR
REDbot has encountered a fatal error which it really, really can't recover from
in standalone server mode. Details follow.

""")
                    import traceback
                    traceback.print_exc()
                    thor.stop()
            else:
                x.response_start(b"404", b"Not Found", [])
                x.response_done([])

    server = thor.http.HttpServer(host, port)
    server.on('exchange', red_handler)

    try:
        thor.run()
    except KeyboardInterrupt:
        sys.stderr.write("Stopping...\n")
        thor.stop()
Esempio n. 22
0
def cgi_main(config: SectionProxy) -> None:
    """Run REDbot as a CGI Script."""
    def out(inbytes: bytes) -> None:
        try:
            sys.stdout.buffer.write(inbytes)
            sys.stdout.flush()
        except IOError:
            pass

    config["ui_uri"] = "%s://%s%s%s" % (
        "HTTPS" in os.environ and "https" or "http",
        os.environ.get("HTTP_HOST"),
        os.environ.get("SCRIPT_NAME"),
        os.environ.get("PATH_INFO", ""),
    )
    method = os.environ.get("REQUEST_METHOD").encode(config["charset"])
    query_string = os.environ.get("QUERY_STRING", "").encode(config["charset"])
    req_hdrs = []  # type: RawHeaderListType
    for (k, v) in os.environ:
        if k[:5] == "HTTP_":
            req_hdrs.append((k[:5].lower().encode("ascii"), v.encode("ascii")))
    req_body = sys.stdin.read().encode("utf-8")

    class Exchange(HttpResponseExchange):
        @staticmethod
        def response_start(code: bytes, phrase: bytes,
                           res_hdrs: RawHeaderListType) -> None:
            out_v = [b"Status: %s %s" % (code, phrase)]
            for name, value in res_hdrs:
                out_v.append(b"%s: %s" % (name, value))
            out_v.append(b"")
            out_v.append(b"")
            out(b"\n".join(out_v))

        @staticmethod
        def response_body(chunk: bytes) -> None:
            freak_ceiling = 20000
            rest = None
            if len(chunk) > freak_ceiling:
                rest = chunk[freak_ceiling:]
                chunk = chunk[:freak_ceiling]
            out(chunk)
            if rest:
                Exchange.response_body(rest)

        @staticmethod
        def response_done(trailers: RawHeaderListType) -> None:
            thor.schedule(0, thor.stop)

    try:
        RedWebUi(
            config,
            method.decode(config["charset"]),
            query_string,
            req_hdrs,
            req_body,
            Exchange(),
        )
        thor.run()
    except Exception:
        except_handler_factory(config,
                               qs=query_string.decode(config["charset"]))()
Esempio n. 23
0
def mod_python_handler(r):
    """Run RED as a mod_python handler."""
    from mod_python import apache
    status_lookup = {
        100: apache.HTTP_CONTINUE,
        101: apache.HTTP_SWITCHING_PROTOCOLS,
        102: apache.HTTP_PROCESSING,
        200: apache.HTTP_OK,
        201: apache.HTTP_CREATED,
        202: apache.HTTP_ACCEPTED,
        200: apache.HTTP_OK,
        200: apache.HTTP_OK,
        201: apache.HTTP_CREATED,
        202: apache.HTTP_ACCEPTED,
        203: apache.HTTP_NON_AUTHORITATIVE,
        204: apache.HTTP_NO_CONTENT,
        205: apache.HTTP_RESET_CONTENT,
        206: apache.HTTP_PARTIAL_CONTENT,
        207: apache.HTTP_MULTI_STATUS,
        300: apache.HTTP_MULTIPLE_CHOICES,
        301: apache.HTTP_MOVED_PERMANENTLY,
        302: apache.HTTP_MOVED_TEMPORARILY,
        303: apache.HTTP_SEE_OTHER,
        304: apache.HTTP_NOT_MODIFIED,
        305: apache.HTTP_USE_PROXY,
        307: apache.HTTP_TEMPORARY_REDIRECT,
        400: apache.HTTP_BAD_REQUEST,
        401: apache.HTTP_UNAUTHORIZED,
        402: apache.HTTP_PAYMENT_REQUIRED,
        403: apache.HTTP_FORBIDDEN,
        404: apache.HTTP_NOT_FOUND,
        405: apache.HTTP_METHOD_NOT_ALLOWED,
        406: apache.HTTP_NOT_ACCEPTABLE,
        407: apache.HTTP_PROXY_AUTHENTICATION_REQUIRED,
        408: apache.HTTP_REQUEST_TIME_OUT,
        409: apache.HTTP_CONFLICT,
        410: apache.HTTP_GONE,
        411: apache.HTTP_LENGTH_REQUIRED,
        412: apache.HTTP_PRECONDITION_FAILED,
        413: apache.HTTP_REQUEST_ENTITY_TOO_LARGE,
        414: apache.HTTP_REQUEST_URI_TOO_LARGE,
        415: apache.HTTP_UNSUPPORTED_MEDIA_TYPE,
        416: apache.HTTP_RANGE_NOT_SATISFIABLE,
        417: apache.HTTP_EXPECTATION_FAILED,
        422: apache.HTTP_UNPROCESSABLE_ENTITY,
        423: apache.HTTP_LOCKED,
        424: apache.HTTP_FAILED_DEPENDENCY,
        426: apache.HTTP_UPGRADE_REQUIRED,
        500: apache.HTTP_INTERNAL_SERVER_ERROR,
        501: apache.HTTP_NOT_IMPLEMENTED,
        502: apache.HTTP_BAD_GATEWAY,
        503: apache.HTTP_SERVICE_UNAVAILABLE,
        504: apache.HTTP_GATEWAY_TIME_OUT,
        505: apache.HTTP_VERSION_NOT_SUPPORTED,
        506: apache.HTTP_VARIANT_ALSO_VARIES,
        507: apache.HTTP_INSUFFICIENT_STORAGE,
        510: apache.HTTP_NOT_EXTENDED,
    }

    r.content_type = "text/html"

    def response_start(code, phrase, hdrs):
        r.status = status_lookup.get(int(code),
                                     apache.HTTP_INTERNAL_SERVER_ERROR)
        for hdr in hdrs:
            r.headers_out[hdr[0]] = hdr[1]

    def response_done(trailers):
        thor.schedule(thor.stop)

    query_string = cgi.parse_qs(r.args or "")
    try:
        RedWebUi(r.unparsed_uri, r.method, query_string, response_start,
                 r.write, response_done)
        thor.run()
    except:
        except_handler_factory(r.write)()
    return apache.OK