Пример #1
0
    def post(self, *args, **kwargs):
        self.set_header("Server", "API Server v" + version.version)
        log("Enter CommandHandler.put()")
        header = str(self.request.headers["Content-Type"]).lower()
        log("request header: %s" % header)

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)
        if not passed:
            log('%s\t%s://%s%s\tForbidden\tIP Restricted: %s' % (config.http_response_codes["forbidden"], \
                    self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")
            log('ip_restrict failed.')
            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])

        try:
            log("processing body: %s" % self.request.body)
            self.json_data = json.loads(self.request.body)
            if not self.json_data.has_key('command'):
                raise CmdError

            if(self.json_data.get('command') == 'purge'):
                self.process_purge_requests()
        except CmdError:
            log('CommandHandler post handler, must provide command value in json data.')
            self.set_status(500)
            self.write('{”success”: ”False", "message" : "no command" }')
            raise tornado.web.HTTPError(config.http_response_codes["general_error"])
Пример #2
0
    def get(self, urlQuery):
        self.set_header("Server", "API Server v" + version)

        json_data = "{}"

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        try:
            if urlQuery == "port":
                json_data = value_to_json("port", config.port)
            elif urlQuery == "log_when":
                json_data = value_to_json("log_when", config.log_when)
            elif urlQuery == "log_utc":
                json_data = value_to_json("log_utc", config.log_utc)
            elif urlQuery == "log_rotation":
                json_data = value_to_json("log_rotation", config.log_rotation)
            elif urlQuery == "log_backups":
                json_data = value_to_json("log_backups", config.log_backups)
            elif urlQuery == "http_response_codes":
                json_data = list_to_json_array(config.http_response_codes, "http_response_codes")
            elif urlQuery == "alert_email":
                json_data = list_to_json_array(config.alert_email, "alert_email")
            elif urlQuery == "keys":
                json_data = list_to_json_array(config.keys, "keys")
            elif urlQuery == "version":
                json_data = value_to_json("version", version)
            elif len(urlQuery) == 0:  # All
                json_data = value_to_json("port", config.port, stop=False)
                json_data += value_to_json("log_when", config.log_when, start=False, stop=False)
                json_data += value_to_json("log_utc", config.log_utc, start=False, stop=False)
                json_data += value_to_json("log_rotation", config.log_rotation, start=False, stop=False)
                json_data += value_to_json("log_backups", config.log_backups, start=False, stop=False)
                json_data += list_to_json_array(config.http_response_codes, "http_response_codes", start=False, stop=False)
                json_data += list_to_json_array(config.alert_email, "alert_email", start=False, stop=False)
                json_data += list_to_json_array(config.api_ip_allow_range, "api_ip_allow_range", start=False, stop=False)
                json_data += list_to_json_array(config.keys, "keys", start=False, stop=False)
                json_data += value_to_json("version", version, start=False)

            if config.logging:
                log("GET %s\t%s://%s%s\t%s\t%s" % (
                    config.http_response_codes["found"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"]))
        except BaseException, e:
            log("GET %s\t%s://%s%s\t%s\t%s\t%s" % (
                config.http_response_codes["found"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"], e), "CRITICAL")
Пример #3
0
    def get(self, urlQuery):
        self.set_header("Server", "API Server v" + version.version)

        json_data = "{}"

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        try:
            if urlQuery == "servers":
                json_data = list_to_json_array(config.servers_with_weights, "servers")
            elif urlQuery == "server_defaults":
                json_data = list_to_json_array(config.server_defaults, "server_defaults")
            elif urlQuery == "server_ports":
                json_data = list_to_json_array(config.server_ports, "server_ports")
            elif urlQuery == "servers_interface_ip":
                json_data = list_to_json_array(config.servers_interface_ip, "servers_interface_ip")
            elif urlQuery == "server_config":
                json_data = list_to_json_array(config.servers_server_config, "server_config")
            elif urlQuery == "purge":
                json_data = list_to_json_array(config.servers_purge, "purge")
            elif len(urlQuery) == 0:  # All
                json_data = list_to_json_array(config.servers_with_weights, "servers", start=False, stop=False)
                json_data += list_to_json_array(config.server_defaults, "server_defaults", start=False, stop=False)
                json_data += list_to_json_array(config.server_ports, "server_ports", start=False, stop=False)
                json_data += list_to_json_array(config.servers_interface_ip, "servers_interface_ip", start=False)
                json_data += list_to_json_array(config.servers_server_config, "server_config", start=False, stop=False)
                json_data += list_to_json_array(config.servers_purge, "purge", start=False)

            if config.logging:
                log("GET %s\t%s://%s%s\t%s\t%s" % (
                    config.http_response_codes["found"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"]))
        except BaseException, e:
            log("GET %s\t%s://%s%s\t%s\t%s\t%s" % (
                config.http_response_codes["general_error"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"], e), "CRITICAL")
Пример #4
0
    def get(self, urlQuery):
        self.set_header("Server", "API Server v" + version.version)

        json_data = "{}"

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            if config.logging:
                log("%s\t%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")
        tcs_config_stream = None

        try:
            # temp for now
            tcs_config_stream = file('%s%s' % (config.servers_server_config.get('path'), config.servers_server_config.get('file')), 'r')
            tcs_config = yaml.load(tcs_config_stream)

            if urlQuery == 'services':
                json_data = list_to_json_array(tcs_config['services'], "services")
            elif len(urlQuery) == 0:  # All
                json_data = json.dumps(tcs_config)

                #json_data = value_to_json('version', tcs_config['version'], stop=False)
                #json_data += value_to_json('modeofoperation', tcs_config['modeofoperation'], start=False, stop=False)
                #json_data += value_to_json('monitoringinterface', tcs_config['monitoringinterface'], start=False,stop=False)
                #json_data += value_to_json('outgoinginterface', tcs_config['outgoinginterface'], start=False,stop=False)
                #json_data += value_to_json('redirectaddress', tcs_config['redirectaddress'], start=False,stop=False)
                #json_data += value_to_json('pcap-filter', tcs_config['pcap-filter'], start=False,stop=False)
                #json_data += list_to_json_array(tcs_config['services'], "services", start=False, stop=True)

            #if config.logging:
            #    log("GET %s\t%s://%s%s\t%s\t%s" % (
            #        config.http_response_codes["found"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"]))
        except BaseException, e:
            log("GET %s\t%s://%s%s\t%s\t%s\t%s" % (
                config.http_response_codes["general_error"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"], e), "CRITICAL")
Пример #5
0
    def get(self, urlQuery):
        """
        The urlQuery is NOT the query string portion but the path AFTER the domain.
        If URI query parameters are needed then use a get_argument command.
        """

        # Add redirected edge host to cookie so that we know the original request once subsequent requests from the
        # client sends back keep-alive options, etc...
        # NOTE: Cookie may not set because of cross site and since it may only apply to page and not player.

        # Cookie setting routine was removed since Safari did not set it for the video object and it's the only one
        # that send an Accept-Encoding: Identity which means there are multiple redirects for a single request.

        # IMPORTANT - Update version.py when a new version rolls out...
        self.set_header("Server", "Request Router v" + version.version)

        #file_name = None
        #if str(urlQuery).find('crossdomain.xml'):
        #    file_name = 'crossdomain.xml'
        #elif str(urlQuery).find('clientaccesspolicy.xml'):
        #    file_name = 'clientaccesspolicy.xml'

        #if file_name is not None:
        #    content = self.get_content(os.path.join(os.path.dirname(__file__), '../static/' + file_name))
        #content_length = 0
        #for chunk in content:
        #        content_length += len(chunk)
        #    self.set_header("Content-Length", content_length)

        index = 0  # Set a default value if the items below fail for some reason
        passed = True  # Used for geo restricting if enabled in the config.yaml file
        http_error = False  # Used by the try/catch to force a forbidden error

        if config.geo["restrict"] or config.ip["restrict"]:
            try:
                # Geo Restrictions - if any
                if config.geo["restrict"]:
                    passed = geo_restrict(self.request.remote_ip)

                if not passed:
                    if len(config.geo["redirect_url"]) > 0:
                        #if config.logging:
                        #    log(config.geo["log_prefix"] + config.log_message_formats["requested_prefix"] + self.request.protocol + "://" + self.request.host + self.request.uri + "\t" + config.log_message_formats["routed_prefix"] + config.geo["redirect_url"] + "\tIP: " + self.request.remote_ip, "WARNING")
                        self.redirect(config.geo["redirect_url"])
                    else:
                        if config.logging:
                            redirect = "%s://%s%s" % (self.request.protocol,
                                                      self.request.host,
                                                      self.request.uri)
                            log(
                                "%s - - \"GET %s\" %s %s \"%s\" \"%s\" \"-\"" %
                                (self.request.remote_ip, self.request.uri,
                                 config.http_response_codes["forbidden"],
                                 str(len(redirect)), redirect,
                                 self.request.headers["User-Agent"]),
                                "WARNING")

                        raise tornado.web.HTTPError(
                            config.http_response_codes["forbidden"])

                # IP restrictions - if any
                if config.ip["restrict"]:
                    passed = ip_restrict(self.request.remote_ip)

                if not passed:
                    if len(config.ip["redirect_url"]) > 0:
                        #if config.logging:
                        #    log(config.ip["log_prefix"] + config.log_message_formats["requested_prefix"] + self.request.protocol + "://" + self.request.host + self.request.uri + "\t" + config.log_message_formats["routed_prefix"] + config.ip["redirect_url"] + "\tIP: " + self.request.remote_ip, "WARNING")
                        self.redirect(config.ip["redirect_url"])
                    else:
                        if config.logging:
                            redirect = "%s://%s%s" % (self.request.protocol,
                                                      self.request.host,
                                                      self.request.uri)
                            log(
                                "%s - - \"GET %s\" %s %s \"%s\" \"%s\" \"-\"" %
                                (self.request.remote_ip, self.request.uri,
                                 config.http_response_codes["forbidden"],
                                 str(len(redirect)), redirect,
                                 self.request.headers["User-Agent"]),
                                "WARNING")

                        raise tornado.web.HTTPError(
                            config.http_response_codes["forbidden"]
                        )  # The exception will catch this so force it again

            except BaseException, e:
                http_error = True

            if http_error:
                if config.logging:
                    redirect = "%s://%s%s" % (self.request.protocol,
                                              self.request.host,
                                              self.request.uri)
                    log(
                        "%s - - \"GET %s\" %s %s \"%s\" \"%s\" \"-\"" %
                        (self.request.remote_ip, self.request.uri,
                         config.http_response_codes["forbidden"],
                         str(len(redirect)), redirect,
                         self.request.headers["User-Agent"]), "WARNING")
                raise tornado.web.HTTPError(
                    config.http_response_codes["forbidden"]
                )  # The previous block was caught but this forces the error to be thrown.
Пример #6
0
    def post(self, *args, **kwargs):
        """
        Add XSRF back in after testing...
        Check the header for the 'application/json' Content-Type
        """
        self.set_header("Server", "API Server v" + version.version)

        json_data = "{}"
        update_queue = False

        header = str(self.request.headers["Content-Type"]).lower(
        )  # If Content-Type is not there or malformed then the server catches before this point.

        if args is None or args[0] == "" or header != "application/json":
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tHeader not set correctly" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats[
            #        "requested_prefix"], self.request.protocol, self.request.host, self.request.uri), "WARNING")

            raise tornado.web.HTTPError(
                config.http_response_codes["forbidden"])

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(
                config.http_response_codes["forbidden"]
            )  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        command = str(args[0]).lower()

        # Break down the json into a dictionary. Some will be a simple name/value pair and others an array and others a list.
        dict_data = "{}"
        try:
            dict_data = convert(json.loads(self.request.body))
            if command == "servers_interface_ip":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.servers_interface_ip[:] = []  # Clears a list
                    for data in dict_data[command]:
                        config.servers_interface_ip.append(data)
            elif command == "server_defaults":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.server_defaults.clear()
                    config.server_defaults = dict_data[command]
                    config.server_default_port = ":" + str(
                        config.server_defaults["port"]
                    )  # Must be present in the servers.yaml file.
                    if config.server_default_port == ":80" or config.server_default_port == ":":
                        config.server_default_port = ""  # Set it to empty since it's not needed for browsers/players.
            elif command == "server_ports":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.server_ports.clear()
                    config.server_ports = dict_data[command]
            elif command == "server_config":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.servers_server_config.clear()
                    config.servers_server_config = dict_data[command]
            elif command == "purge":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.servers_purge.clear()
                    config.servers_purge = dict_data[command]
            elif command == "servers" or command == "servers/add" or command == "servers/delete":
                if len(dict_data["servers"]) > 0:
                    update_queue = True
                    add_servers = False
                    if command == "servers/add":
                        add_servers = True

                    config.server_count = len(config.servers)
                    config.servers_weighted_count = len(
                        config.servers_weighted)
            elif command == "write":  # Writes out the yaml file
                yaml_write("servers", "servers.yaml")

            if update_queue:
                config.server_queue.put_nowait("update")

            if config.logging:
                log("POST %s\t%s://%s%s\t%s\t%s\t%s" %
                    (config.http_response_codes["found"],
                     self.request.protocol, self.request.host,
                     self.request.uri, self.request.remote_ip,
                     self.request.headers["User-Agent"], dict_data))

            self.write("{\"%s\": %s}" % ("success", True))
        except BaseException, e:
            log(
                "POST %s\t%s://%s%s\t%s\t%s\t%s\t%s" %
                (config.http_response_codes["general_error"],
                 self.request.protocol, self.request.host, self.request.uri,
                 self.request.remote_ip, self.request.headers["User-Agent"], e,
                 dict_data), "CRITICAL")
            self.write("{\"%s\": %s}" % ("success", False))
Пример #7
0
    def get(self, urlQuery):
        self.set_header("Server", "API Server v" + version.version)

        json_data = "{}"

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(
                config.http_response_codes["forbidden"]
            )  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        try:
            if urlQuery == "servers":
                json_data = list_to_json_array(config.servers_with_weights,
                                               "servers")
            elif urlQuery == "server_defaults":
                json_data = list_to_json_array(config.server_defaults,
                                               "server_defaults")
            elif urlQuery == "server_ports":
                json_data = list_to_json_array(config.server_ports,
                                               "server_ports")
            elif urlQuery == "servers_interface_ip":
                json_data = list_to_json_array(config.servers_interface_ip,
                                               "servers_interface_ip")
            elif urlQuery == "server_config":
                json_data = list_to_json_array(config.servers_server_config,
                                               "server_config")
            elif urlQuery == "purge":
                json_data = list_to_json_array(config.servers_purge, "purge")
            elif len(urlQuery) == 0:  # All
                json_data = list_to_json_array(config.servers_with_weights,
                                               "servers",
                                               start=False,
                                               stop=False)
                json_data += list_to_json_array(config.server_defaults,
                                                "server_defaults",
                                                start=False,
                                                stop=False)
                json_data += list_to_json_array(config.server_ports,
                                                "server_ports",
                                                start=False,
                                                stop=False)
                json_data += list_to_json_array(config.servers_interface_ip,
                                                "servers_interface_ip",
                                                start=False)
                json_data += list_to_json_array(config.servers_server_config,
                                                "server_config",
                                                start=False,
                                                stop=False)
                json_data += list_to_json_array(config.servers_purge,
                                                "purge",
                                                start=False)

            if config.logging:
                log("GET %s\t%s://%s%s\t%s\t%s" %
                    (config.http_response_codes["found"],
                     self.request.protocol, self.request.host,
                     self.request.uri, self.request.remote_ip,
                     self.request.headers["User-Agent"]))
        except BaseException, e:
            log(
                "GET %s\t%s://%s%s\t%s\t%s\t%s" %
                (config.http_response_codes["general_error"],
                 self.request.protocol, self.request.host, self.request.uri,
                 self.request.remote_ip, self.request.headers["User-Agent"],
                 e), "CRITICAL")
Пример #8
0
    def post(self, *args, **kwargs):
        """
        Add XSRF back in after testing...
        Check the header for the 'application/json' Content-Type
        """
        # curl -X POST -H "Content-Type: application/json" -d @config.json http://localhost:8088/v1/components/configurations/transparentcache/config/
        self.set_header("Server", "API Server v" + version.version)

        header = str(self.request.headers["Content-Type"]).lower()  # If Content-Type is not there or malformed then the server catches before this point.

        # NOTE: Not checking for arguments now since the whole json file is being sent
        #if args is None or args[0] == "" or header != "application/json":
        #if header != 'application/json':
            #if config.logging:
            #    log("%s\t%s%s://%s%s\tForbidden\tHeader not set correctly" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], self.request.protocol, self.request.host, self.request.uri), "WARNING")

        #    raise tornado.web.HTTPError(config.http_response_codes["forbidden"])

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            if config.logging:
                log("%s\t%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        # NOTE: Not currently used since the whole json file is being sent.
        #command = str(args[0]).lower()

        tcs_config_stream = None
        socket = None
        try:
            #yaml_datax = yaml.safe_dump(json.loads(self.request.body))
            #yaml_data = str(yaml_data).replace('!!python/unicode ', '')
            yaml_data = json_to_yaml(json.loads(self.request.body))

            file_name = '%s%s' % (config.servers_server_config.get('path'), config.servers_server_config.get('file'))
            dest_file = config.servers_server_config.get('file') + "_" + str(datetime.datetime.now()).replace("-", "").replace(" ", "").replace(":", "").replace(".", "")

            shutil.copyfile(file_name, '%s%s' % (config.servers_server_config.get('path'), 'yamls/') + dest_file)

            tcs_config_stream = file(file_name, 'w')
            fcntl.flock(tcs_config_stream.fileno(), fcntl.LOCK_EX) #unlocked by close
            # Read in the current yaml and write it out to a new file with the current time appended
            # Take the config settings and build a json data string
            # Write the json data to the yaml.dump method using the write enabled stream for the yaml file

            tcs_config_stream.write(yaml_data)
            tcs_config_stream.close() #unlocks the file
            tcs_config_stream = None
            #log("closing stream","INFO")
            #log("yaml data:%s" % (yaml_datax),"INFO")
            #if config.logging:
            #    log("POST %s\t%s://%s%s\t%s\t%s" % (
            #        config.http_response_codes["found"], self.request.protocol, self.request.host, self.request.uri,
            #        self.request.remote_ip, self.request.headers["User-Agent"]))
            # Fire the zeromq message to let the system know to read the config.yaml again
            context = zmq.Context()
            socket = context.socket(zmq.REQ)
            #socket.setsockopt(zmq.LINGER, 0)
            socket.connect("tcp://localhost:5555")  # The PORT is fixed for this release and on the same server as the TCS.
            socket.send('10')  # Value is fixed
            msg = socket.recv()  # Have to recv since it blocks...
            if msg == "END":
                self.write("{\"success\": true}")
            else:
                self.write("{\"success\": false}")
                #log("socket.recv() err")
        except BaseException, e:
            log("POST %s\t%s://%s%s\t%s\t%s\t%s" % (
                config.http_response_codes["general_error"], self.request.protocol, self.request.host, self.request.uri,
                self.request.remote_ip, self.request.headers["User-Agent"], e), "CRITICAL")
            self.write("{\"success\": false}")
Пример #9
0
    def post(self, *args, **kwargs):
        """
        Add XSRF back in after testing...
        Check the header for the 'application/json' Content-Type
        """
        self.set_header("Server", "API Server v" + version.version)

        json_data = "{}"
        update_queue = False

        header = str(self.request.headers["Content-Type"]).lower()  # If Content-Type is not there or malformed then the server catches before this point.

        if args is None or args[0] == "" or header != "application/json":
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tHeader not set correctly" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats[
            #        "requested_prefix"], self.request.protocol, self.request.host, self.request.uri), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        command = str(args[0]).lower()

        # Break down the json into a dictionary. Some will be a simple name/value pair and others an array and others a list.
        dict_data = "{}"
        try:
            dict_data = convert(json.loads(self.request.body))
            if command == "servers_interface_ip":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.servers_interface_ip[:] = []  # Clears a list
                    for data in dict_data[command]:
                        config.servers_interface_ip.append(data)
            elif command == "server_defaults":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.server_defaults.clear()
                    config.server_defaults = dict_data[command]
                    config.server_default_port = ":" + str(config.server_defaults["port"])  # Must be present in the servers.yaml file.
                    if config.server_default_port == ":80" or config.server_default_port == ":":
                        config.server_default_port = ""  # Set it to empty since it's not needed for browsers/players.
            elif command == "server_ports":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.server_ports.clear()
                    config.server_ports = dict_data[command]
            elif command == "server_config":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.servers_server_config.clear()
                    config.servers_server_config = dict_data[command]
            elif command == "purge":
                if len(dict_data[command]) > 0:
                    update_queue = True
                    config.servers_purge.clear()
                    config.servers_purge = dict_data[command]
            elif command == "servers" or command == "servers/add" or command == "servers/delete":
                if len(dict_data["servers"]) > 0:
                    update_queue = True
                    add_servers = False
                    if command == "servers/add":
                        add_servers = True

                    config.server_count = len(config.servers)
                    config.servers_weighted_count = len(config.servers_weighted)
            elif command == "write":  # Writes out the yaml file
                yaml_write("servers", "servers.yaml")

            if update_queue:
                config.server_queue.put_nowait("update")

            if config.logging:
                log("POST %s\t%s://%s%s\t%s\t%s\t%s" % (
                    config.http_response_codes["found"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"], dict_data))

            self.write("{\"%s\": %s}" % ("success", True))
        except BaseException, e:
            log("POST %s\t%s://%s%s\t%s\t%s\t%s\t%s" % (
                config.http_response_codes["general_error"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"], e, dict_data), "CRITICAL")
            self.write("{\"%s\": %s}" % ("success", False))
Пример #10
0
    def get(self, urlQuery):
        self.set_header("Server", "API Server v" + version)

        json_data = "{}"

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(
                config.http_response_codes["forbidden"]
            )  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        try:
            if urlQuery == "port":
                json_data = value_to_json("port", config.port)
            elif urlQuery == "log_when":
                json_data = value_to_json("log_when", config.log_when)
            elif urlQuery == "log_utc":
                json_data = value_to_json("log_utc", config.log_utc)
            elif urlQuery == "log_rotation":
                json_data = value_to_json("log_rotation", config.log_rotation)
            elif urlQuery == "log_backups":
                json_data = value_to_json("log_backups", config.log_backups)
            elif urlQuery == "http_response_codes":
                json_data = list_to_json_array(config.http_response_codes,
                                               "http_response_codes")
            elif urlQuery == "alert_email":
                json_data = list_to_json_array(config.alert_email,
                                               "alert_email")
            elif urlQuery == "keys":
                json_data = list_to_json_array(config.keys, "keys")
            elif urlQuery == "version":
                json_data = value_to_json("version", version)
            elif len(urlQuery) == 0:  # All
                json_data = value_to_json("port", config.port, stop=False)
                json_data += value_to_json("log_when",
                                           config.log_when,
                                           start=False,
                                           stop=False)
                json_data += value_to_json("log_utc",
                                           config.log_utc,
                                           start=False,
                                           stop=False)
                json_data += value_to_json("log_rotation",
                                           config.log_rotation,
                                           start=False,
                                           stop=False)
                json_data += value_to_json("log_backups",
                                           config.log_backups,
                                           start=False,
                                           stop=False)
                json_data += list_to_json_array(config.http_response_codes,
                                                "http_response_codes",
                                                start=False,
                                                stop=False)
                json_data += list_to_json_array(config.alert_email,
                                                "alert_email",
                                                start=False,
                                                stop=False)
                json_data += list_to_json_array(config.api_ip_allow_range,
                                                "api_ip_allow_range",
                                                start=False,
                                                stop=False)
                json_data += list_to_json_array(config.keys,
                                                "keys",
                                                start=False,
                                                stop=False)
                json_data += value_to_json("version", version, start=False)

            if config.logging:
                log("GET %s\t%s://%s%s\t%s\t%s" %
                    (config.http_response_codes["found"],
                     self.request.protocol, self.request.host,
                     self.request.uri, self.request.remote_ip,
                     self.request.headers["User-Agent"]))
        except BaseException, e:
            log(
                "GET %s\t%s://%s%s\t%s\t%s\t%s" %
                (config.http_response_codes["found"], self.request.protocol,
                 self.request.host, self.request.uri, self.request.remote_ip,
                 self.request.headers["User-Agent"], e), "CRITICAL")
Пример #11
0
    def post(self, *args, **kwargs):
        """
        Add XSRF back in after testing...
        Check the header for the 'application/json' Content-Type
        """
        self.set_header("Server", "API Server v" + version)

        dict_data = "{}"

        header = str(self.request.headers["Content-Type"]).lower(
        )  # If Content-Type is not there or malformed then the server catches before this point.

        if args is None or args[0] == "" or header != "application/json":
            #if config.logging:
            #    log("%s\t%s://%s%s\tForbidden\tHeader not set correctly" % (config.http_response_codes["forbidden"], self.request.protocol, self.request.host, self.request.uri), "WARNING")

            raise tornado.web.HTTPError(
                config.http_response_codes["forbidden"])

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(
                config.http_response_codes["forbidden"]
            )  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        command = str(args[0]).lower()

        # Break down the json into a dictionary. Some will be a simple name/value pair and others an array and others a list.
        try:
            dict_data = convert(json.loads(self.request.body))
            if command == "log_rotation":
                if len(dict_data[command]) > 0:
                    config.log_rotation = dict_data[command]
            elif command == "log_backups":
                if len(dict_data[command]) > 0:
                    config.log_backups = dict_data[command]
            elif command == "log_when":
                if len(dict_data[command]) > 0:
                    config.log_when = dict_data[command]
            elif command == "alert_email":
                config.alert_email.clear()
                config.alert_email = dict_data[command]
            elif command == "keys":
                if len(dict_data[command]) > 0:
                    config.keys.clear()
                    config.keys = dict_data[command]
            elif command == "read":
                read()
            elif command == "write":  # Writes out the yaml file
                yaml_write("config", "config.yaml")

            if config.logging:
                log("POST %s\t%s://%s%s\t%s\t%s\t%s" %
                    (config.http_response_codes["found"],
                     self.request.protocol, self.request.host,
                     self.request.uri, self.request.remote_ip,
                     self.request.headers["User-Agent"], dict_data))

            self.write("{\"%s\": %s}" % ("success", True))
        except BaseException, e:
            log(
                "POST %s\t%s://%s%s\t%s\t%s\t%s\t%s" %
                (config.http_response_codes["general_error"],
                 self.request.protocol, self.request.host, self.request.uri,
                 self.request.remote_ip, self.request.headers["User-Agent"], e,
                 dict_data), "CRITICAL")
            self.write("{\"%s\": %s}" % ("success", False))
Пример #12
0
    def get(self, urlQuery):
        """
        The urlQuery is NOT the query string portion but the path AFTER the domain.
        If URI query parameters are needed then use a get_argument command.
        """

        # Add redirected edge host to cookie so that we know the original request once subsequent requests from the
        # client sends back keep-alive options, etc...
        # NOTE: Cookie may not set because of cross site and since it may only apply to page and not player.

        # Cookie setting routine was removed since Safari did not set it for the video object and it's the only one
        # that send an Accept-Encoding: Identity which means there are multiple redirects for a single request.

        # IMPORTANT - Update version.py when a new version rolls out...
        self.set_header("Server", "Request Router v" + version.version)

        #file_name = None
        #if str(urlQuery).find('crossdomain.xml'):
        #    file_name = 'crossdomain.xml'
        #elif str(urlQuery).find('clientaccesspolicy.xml'):
        #    file_name = 'clientaccesspolicy.xml'

        #if file_name is not None:
        #    content = self.get_content(os.path.join(os.path.dirname(__file__), '../static/' + file_name))
            #content_length = 0
            #for chunk in content:
            #        content_length += len(chunk)
            #    self.set_header("Content-Length", content_length)

        index = 0  # Set a default value if the items below fail for some reason
        passed = True  # Used for geo restricting if enabled in the config.yaml file
        http_error = False  # Used by the try/catch to force a forbidden error

        if config.geo["restrict"] or config.ip["restrict"]:
            try:
                # Geo Restrictions - if any
                if config.geo["restrict"]:
                    passed = geo_restrict(self.request.remote_ip)

                if not passed:
                    if len(config.geo["redirect_url"]) > 0:
                        #if config.logging:
                        #    log(config.geo["log_prefix"] + config.log_message_formats["requested_prefix"] + self.request.protocol + "://" + self.request.host + self.request.uri + "\t" + config.log_message_formats["routed_prefix"] + config.geo["redirect_url"] + "\tIP: " + self.request.remote_ip, "WARNING")
                        self.redirect(config.geo["redirect_url"])
                    else:
                        if config.logging:
                            redirect = "%s://%s%s" % (self.request.protocol, self.request.host, self.request.uri)
                            log("%s - - \"GET %s\" %s %s \"%s\" \"%s\" \"-\"" % (
                                self.request.remote_ip, self.request.uri, config.http_response_codes["forbidden"], str(len(redirect)), redirect, self.request.headers["User-Agent"]), "WARNING")

                        raise tornado.web.HTTPError(config.http_response_codes["forbidden"])

                # IP restrictions - if any
                if config.ip["restrict"]:
                    passed = ip_restrict(self.request.remote_ip)

                if not passed:
                    if len(config.ip["redirect_url"]) > 0:
                        #if config.logging:
                        #    log(config.ip["log_prefix"] + config.log_message_formats["requested_prefix"] + self.request.protocol + "://" + self.request.host + self.request.uri + "\t" + config.log_message_formats["routed_prefix"] + config.ip["redirect_url"] + "\tIP: " + self.request.remote_ip, "WARNING")
                        self.redirect(config.ip["redirect_url"])
                    else:
                        if config.logging:
                            redirect = "%s://%s%s" % (self.request.protocol, self.request.host, self.request.uri)
                            log("%s - - \"GET %s\" %s %s \"%s\" \"%s\" \"-\"" % (
                                self.request.remote_ip, self.request.uri, config.http_response_codes["forbidden"], str(len(redirect)), redirect, self.request.headers["User-Agent"]), "WARNING")

                        raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The exception will catch this so force it again

            except BaseException, e:
                http_error = True

            if http_error:
                if config.logging:
                    redirect = "%s://%s%s" % (self.request.protocol, self.request.host, self.request.uri)
                    log("%s - - \"GET %s\" %s %s \"%s\" \"%s\" \"-\"" % (
                        self.request.remote_ip, self.request.uri, config.http_response_codes["forbidden"], str(len(redirect)), redirect, self.request.headers["User-Agent"]), "WARNING")
                raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The previous block was caught but this forces the error to be thrown.
Пример #13
0
    def post(self, *args, **kwargs):
        """
        Add XSRF back in after testing...
        Check the header for the 'application/json' Content-Type
        """
        self.set_header("Server", "API Server v" + version)

        dict_data = "{}"

        header = str(self.request.headers["Content-Type"]).lower()  # If Content-Type is not there or malformed then the server catches before this point.

        if args is None or args[0] == "" or header != "application/json":
            #if config.logging:
            #    log("%s\t%s://%s%s\tForbidden\tHeader not set correctly" % (config.http_response_codes["forbidden"], self.request.protocol, self.request.host, self.request.uri), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])

        # Force the api ip_restrict to check.
        passed = ip_restrict(self.request.remote_ip, api=True)

        if not passed:
            #if config.logging:
            #    log("%s\t%s%s%s://%s%s\tForbidden\tIP Restricted: %s" % (config.http_response_codes["forbidden"], config.ip["log_prefix"], config.log_message_formats["requested_prefix"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip), "WARNING")

            raise tornado.web.HTTPError(config.http_response_codes["forbidden"])  # The exception will catch this so force it again

        self.set_header("Content-Type", "application/json")

        command = str(args[0]).lower()

        # Break down the json into a dictionary. Some will be a simple name/value pair and others an array and others a list.
        try:
            dict_data = convert(json.loads(self.request.body))
            if command == "log_rotation":
                if len(dict_data[command]) > 0:
                    config.log_rotation = dict_data[command]
            elif command == "log_backups":
                if len(dict_data[command]) > 0:
                    config.log_backups = dict_data[command]
            elif command == "log_when":
                if len(dict_data[command]) > 0:
                    config.log_when = dict_data[command]
            elif command == "alert_email":
                config.alert_email.clear()
                config.alert_email = dict_data[command]
            elif command == "keys":
                if len(dict_data[command]) > 0:
                    config.keys.clear()
                    config.keys = dict_data[command]
            elif command == "read":
                read()
            elif command == "write":  # Writes out the yaml file
                yaml_write("config", "config.yaml")

            if config.logging:
                log("POST %s\t%s://%s%s\t%s\t%s\t%s" % (
                    config.http_response_codes["found"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"], dict_data))

            self.write("{\"%s\": %s}" % ("success", True))
        except BaseException, e:
            log("POST %s\t%s://%s%s\t%s\t%s\t%s\t%s" % (
                config.http_response_codes["general_error"], self.request.protocol, self.request.host, self.request.uri, self.request.remote_ip, self.request.headers["User-Agent"], e, dict_data),
                "CRITICAL")
            self.write("{\"%s\": %s}" % ("success", False))