示例#1
0
    def test_flow(self):
        """
            normal flow:

                connect -> request -> response
        """
        c = flow.State()
        f = tutils.tflow()
        c.add_flow(f)
        assert f
        assert c.flow_count() == 1
        assert c.active_flow_count() == 1

        newf = tutils.tflow()
        assert c.add_flow(newf)
        assert c.active_flow_count() == 2

        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        assert c.update_flow(f)
        assert c.flow_count() == 2
        assert c.active_flow_count() == 1

        assert not c.update_flow(None)
        assert c.active_flow_count() == 1

        newf.response = HTTPResponse.wrap(netlib.tutils.tresp())
        assert c.update_flow(newf)
        assert c.active_flow_count() == 0
示例#2
0
def _restore(flow, rawhead):
    # Building usable headers
    headers = Headers()

    lines = rawhead.decode('utf-8')[:-2].split("\r\n")
    for line in lines:
        temp = line.split(": ")
        headers[temp[0]] = temp[1]

    body = cache.get('http.cache.body.%s' % flow.request.pretty_url)

    if len(body) == 0:
        print("Cache hit but body empty, let's doing a real request")
        cache.delete('http.cache.body.%s' % flow.request.pretty_url)
        cache.delete('http.cache.head.%s' % flow.request.pretty_url)
        return

    # Building response from cache
    response = HTTPResponse(b"HTTP/1.1", 200, b"OK", headers, body)

    print(response)
    
    response.headers["X-GIG-Cache"] = "from-cache"

    # Send forged response
    flow.reply.send(response)
示例#3
0
    def test_flow(self):
        """
            normal flow:

                connect -> request -> response
        """
        c = flow.State()
        f = tutils.tflow()
        c.add_flow(f)
        assert f
        assert c.flow_count() == 1
        assert c.active_flow_count() == 1

        newf = tutils.tflow()
        assert c.add_flow(newf)
        assert c.active_flow_count() == 2

        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        assert c.update_flow(f)
        assert c.flow_count() == 2
        assert c.active_flow_count() == 1

        assert not c.update_flow(None)
        assert c.active_flow_count() == 1

        newf.response = HTTPResponse.wrap(netlib.tutils.tresp())
        assert c.update_flow(newf)
        assert c.active_flow_count() == 0
示例#4
0
 def map_local_file(self, context, flow):
     host = flow.request.host
     if host in self.local_rule:
         rule, pathname = self.local_rule[host], flow.request.path.split(
             "?")[0]
         for match in rule:
             if match in pathname:
                 form = flow.request.urlencoded_form
                 local_file = rule[match] + pathname.replace(
                     '/', sep).replace(match, '', 1).lstrip(sep)
                 striped_file = re.sub(
                     r'[a-f0-9]{6}\.(js|css|jpg|png|jpeg|gif)$', r'.\1',
                     local_file)
                 if path.isfile(local_file) or path.isfile(striped_file):
                     if path.exists(striped_file): local_file = striped_file
                     content_type = mimetypes.guess_type(local_file)[0]
                     if content_type[0] is None: break
                     body = str(open(local_file).read())
                     h = self.custom_header(host, content_type,
                                            str(len(body)))
                     response = HTTPResponse(http_version=b"HTTP/1.1",
                                             status_code=200,
                                             reason="local",
                                             headers=h,
                                             content=body)
                     response.is_replay = True
                     flow.response = response
                     context.log(
                         "\n%s\n%s\nReplied with Local File:\n%s\n%s\n%s\n"
                         % (flow.request.path, '-' * 60, '-' * 80,
                            local_file, "-" * 80))
                     break
     else:
         if flow.live and DEFAULT_PROXY is not None:
             self.proxy_request_to_upstream(context, flow, DEFAULT_PROXY)
示例#5
0
 def response_config_rule(self, context, flow):
     host, path = flow.request.host, flow.request.path
     h = self.custom_header(host, 'text/plain', '7')
     h['location'] = 'http://' + host + path
     response = HTTPResponse(http_version=b"HTTP/1.1",
                             status_code=200,
                             reason='ok',
                             headers=h,
                             content='{ret:0}')
     response.is_replay = True
     flow.reply(response)
示例#6
0
 def redirect_https_to_http(self, context, flow):
     host, path = flow.request.host, flow.request.path
     h = self.custom_header(host, None, '0')
     h['location'] = 'http://' + host + path
     response = HTTPResponse(http_version=b"HTTP/1.1",
                             status_code=302,
                             reason='redirect',
                             headers=h,
                             content='')
     response.is_replay = True
     flow.reply(response)
示例#7
0
    def test_set_limit(self):
        c = flow.State()

        f = tutils.tflow()
        assert len(c.view) == 0

        c.add_flow(f)
        assert len(c.view) == 1

        c.set_limit("~s")
        assert c.limit_txt == "~s"
        assert len(c.view) == 0
        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        c.update_flow(f)
        assert len(c.view) == 1
        c.set_limit(None)
        assert len(c.view) == 1

        f = tutils.tflow()
        c.add_flow(f)
        assert len(c.view) == 2
        c.set_limit("~q")
        assert len(c.view) == 1
        c.set_limit("~s")
        assert len(c.view) == 1

        assert "Invalid" in c.set_limit("~")
示例#8
0
 def inline_flash(self, swf):
     content = base64.standard_b64encode(swf)
 
     return HTTPResponse(
         "HTTP/1.1", 200, "OK",
         Headers(content_type="text/html", content_length=str(len(content))),
         content)
示例#9
0
    def test_server_playback(self):
        s = flow.State()

        f = tutils.tflow()
        f.response = HTTPResponse.wrap(netlib.tutils.tresp(content=f.request))
        pb = [f]

        fm = flow.FlowMaster(None, s)
        fm.refresh_server_playback = True
        assert not fm.do_server_playback(tutils.tflow())

        fm.start_server_playback(pb, False, [], False, False, None, False,
                                 None, False)
        assert fm.do_server_playback(tutils.tflow())

        fm.start_server_playback(pb, False, [], True, False, None, False, None,
                                 False)
        r = tutils.tflow()
        r.request.content = "gibble"
        assert not fm.do_server_playback(r)
        assert fm.do_server_playback(tutils.tflow())

        q = queue.Queue()
        fm.tick(q, 0)
        assert fm.should_exit.is_set()

        fm.stop_server_playback()
        assert not fm.server_playback
示例#10
0
def tflow(client_conn=True, server_conn=True, req=True, resp=None, err=None):
    """
    @type client_conn: bool | None | mitmproxy.proxy.connection.ClientConnection
    @type server_conn: bool | None | mitmproxy.proxy.connection.ServerConnection
    @type req:         bool | None | mitmproxy.protocol.http.HTTPRequest
    @type resp:        bool | None | mitmproxy.protocol.http.HTTPResponse
    @type err:         bool | None | mitmproxy.protocol.primitives.Error
    @return:           mitmproxy.protocol.http.HTTPFlow
    """
    if client_conn is True:
        client_conn = tclient_conn()
    if server_conn is True:
        server_conn = tserver_conn()
    if req is True:
        req = netlib.tutils.treq()
    if resp is True:
        resp = netlib.tutils.tresp()
    if err is True:
        err = terr()

    if req:
        req = HTTPRequest.wrap(req)
    if resp:
        resp = HTTPResponse.wrap(resp)

    f = HTTPFlow(client_conn, server_conn)
    f.request = req
    f.response = resp
    f.error = err
    f.reply = controller.DummyReply()
    return f
示例#11
0
 def test_replace(self):
     r = HTTPResponse.wrap(netlib.tutils.tresp())
     r.headers["Foo"] = "fOo"
     r.content = "afoob"
     assert r.replace("foo(?i)", "boo") == 3
     assert not "foo" in r.content
     assert r.headers["boo"] == "boo"
示例#12
0
    def test_set_view_filter(self):
        c = flow.State()

        f = tutils.tflow()
        assert len(c.view) == 0

        c.add_flow(f)
        assert len(c.view) == 1

        c.set_view_filter("~s")
        assert c.filter_txt == "~s"
        assert len(c.view) == 0
        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        c.update_flow(f)
        assert len(c.view) == 1
        c.set_view_filter(None)
        assert len(c.view) == 1

        f = tutils.tflow()
        c.add_flow(f)
        assert len(c.view) == 2
        c.set_view_filter("~q")
        assert len(c.view) == 1
        c.set_view_filter("~s")
        assert len(c.view) == 1

        assert "Invalid" in c.set_view_filter("~")
示例#13
0
 def test_replace(self):
     r = HTTPResponse.wrap(netlib.tutils.tresp())
     r.headers["Foo"] = "fOo"
     r.content = b"afoob"
     assert r.replace("foo(?i)", "boo") == 3
     assert b"foo" not in r.content
     assert r.headers["boo"] == "boo"
示例#14
0
 def map_local_file(self, flow):
     _host = flow.request.host
     if _host in self.local_rule:
         (rule, pathname
          ) = self.local_rule[_host], flow.request.path.split("?")[0]
         for match in rule:
             if match in pathname:
                 local_file = rule[match] + pathname.replace(
                     '/', sep).replace(match, '', 1).lstrip(sep)
                 #process hash filename like my_program_xxxxxx.js to local_file my_program_.js'
                 striped_file = re.sub(
                     r'[a-f0-9]{6}\.(js|css|jpg|png|jpeg|gif)$', r'.\1',
                     local_file)
                 if path.isfile(local_file) or path.isfile(striped_file):
                     if path.exists(striped_file): local_file = striped_file
                     content_type = mimetypes.guess_type(local_file)[0]
                     if content_type is None: break
                     body = str(open(local_file).read())
                     header = self.custom_header(_host, content_type,
                                                 len(body))
                     _response = HTTPResponse(b"HTTP/1.1",
                                              200,
                                              "local",
                                              header,
                                              body,
                                              is_replay=True)
                     flow.response = _response
                     self.log(
                         "\n%s\n%s\nReplied with Local File:\n%s\n%s\n%s\n"
                         % (flow.request.path, '=' * 80, '-' * 80,
                            local_file, "-" * 80))
                     break
                 elif _host == 'config.qq.com':
                     header = self.custom_header(_host, 'text/html', 0)
                     flow.response = HTTPResponse(b"HTTP/1.1",
                                                  404,
                                                  "not found",
                                                  header,
                                                  '',
                                                  is_replay=True)
                     self.log("\n%s\n%s\nReplied with empty file%s\n" %
                              (flow.request.path, '=' * 80, '-' * 80))
                     break
     elif DEFAULT_PROXY is not None:
         self.proxy_request_to_upstream(flow, DEFAULT_PROXY)
示例#15
0
 def test_backup(self):
     f = tutils.tflow()
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
     f.request.content = b"foo"
     assert not f.modified()
     f.backup()
     f.request.content = b"bar"
     assert f.modified()
     f.revert()
     assert f.request.content == b"foo"
示例#16
0
 def test_backup(self):
     f = tutils.tflow()
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
     f.request.content = "foo"
     assert not f.modified()
     f.backup()
     f.request.content = "bar"
     assert f.modified()
     f.revert()
     assert f.request.content == "foo"
示例#17
0
    def test_server_playback(self):
        s = flow.State()

        f = tutils.tflow()
        f.response = HTTPResponse.wrap(netlib.tutils.tresp(content=f.request))
        pb = [f]

        fm = flow.FlowMaster(None, s)
        fm.refresh_server_playback = True
        assert not fm.do_server_playback(tutils.tflow())

        fm.start_server_playback(
            pb,
            False,
            [],
            False,
            False,
            None,
            False,
            None,
            False)
        assert fm.do_server_playback(tutils.tflow())

        fm.start_server_playback(
            pb,
            False,
            [],
            True,
            False,
            None,
            False,
            None,
            False)
        r = tutils.tflow()
        r.request.content = "gibble"
        assert not fm.do_server_playback(r)
        assert fm.do_server_playback(tutils.tflow())

        fm.start_server_playback(
            pb,
            False,
            [],
            True,
            False,
            None,
            False,
            None,
            False)
        q = Queue.Queue()
        fm.tick(q, 0)
        assert fm.should_exit.is_set()

        fm.stop_server_playback()
        assert not fm.server_playback
示例#18
0
 def test_missing_content(self):
     cs = StringIO()
     o = dump.Options(flow_detail=3)
     m = dump.DumpMaster(None, o, outfile=cs)
     f = tutils.tflow()
     f.request.content = None
     m.handle_request(f)
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
     f.response.content = None
     m.handle_response(f)
     assert "content missing" in cs.getvalue()
示例#19
0
 def response_config_rule(self, flow):
     (_host, _path) = flow.request.host, flow.request.path
     header = self.custom_header(_host, 'text/plain', 7)
     header['location'] = 'http://' + _host + _path
     _response = HTTPResponse(b"HTTP/1.1",
                              200,
                              'ok',
                              header,
                              content='{ret:0}',
                              is_replay=True)
     flow.response = _response
示例#20
0
 def test_missing_content(self):
     cs = StringIO()
     o = dump.Options(flow_detail=3)
     m = dump.DumpMaster(None, o, outfile=cs)
     f = tutils.tflow()
     f.request.content = CONTENT_MISSING
     m.handle_request(f)
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
     f.response.content = CONTENT_MISSING
     m.handle_response(f)
     assert "content missing" in cs.getvalue()
示例#21
0
 def redirect_https_to_http(flow):
     (_host, _path) = flow.request.host, flow.request.path
     header = Smarthost.custom_header(_host, None, 0)
     header['location'] = 'http://' + _host + _path
     _response = HTTPResponse(b"HTTP/1.1",
                              302,
                              'redirect temporary',
                              header,
                              '',
                              is_replay=True)
     flow.response = _response
示例#22
0
 def _cycle(self, m, content):
     f = tutils.tflow(req=netlib.tutils.treq(content=content))
     l = Log("connect")
     l.reply = mock.MagicMock()
     m.handle_log(l)
     m.handle_clientconnect(f.client_conn)
     m.handle_serverconnect(f.server_conn)
     m.handle_request(f)
     f.response = HTTPResponse.wrap(netlib.tutils.tresp(content=content))
     f = m.handle_response(f)
     m.handle_clientdisconnect(f.client_conn)
     return f
示例#23
0
 def _cycle(self, m, content):
     f = tutils.tflow(req=netlib.tutils.treq(content=content))
     l = Log("connect")
     l.reply = mock.MagicMock()
     m.handle_log(l)
     m.handle_clientconnect(f.client_conn)
     m.handle_serverconnect(f.server_conn)
     m.handle_request(f)
     f.response = HTTPResponse.wrap(netlib.tutils.tresp(content=content))
     f = m.handle_response(f)
     m.handle_clientdisconnect(f.client_conn)
     return f
示例#24
0
def request(flow):
    # pretty_host takes the "Host" header of the request into account,
    # which is useful in transparent mode where we usually only have the IP
    # otherwise.

    # Method 1: Answer with a locally generated response
    if flow.request.pretty_host.endswith("example.com"):
        flow.response = HTTPResponse.make(200, b"Hello World",
                                          {"Content-Type": "text/html"})

    # Method 2: Redirect the request to a different server
    if flow.request.pretty_host.endswith("example.org"):
        flow.request.host = "mitmproxy.org"
def request(flow):
    # pretty_host takes the "Host" header of the request into account,
    # which is useful in transparent mode where we usually only have the IP
    # otherwise.

    # Method 1: Answer with a locally generated response
    if flow.request.pretty_host.endswith("example.com"):
        resp = HTTPResponse.make(200, b"Hello World", {"Content-Type": "text/html"})
        flow.reply.send(resp)

    # Method 2: Redirect the request to a different server
    if flow.request.pretty_host.endswith("example.org"):
        flow.request.host = "mitmproxy.org"
示例#26
0
def request(context, flow):
    # pretty_host takes the "Host" header of the request into account,
    # which is useful in transparent mode where we usually only have the IP
    # otherwise.

    # Method 1: Answer with a locally generated response
    if flow.request.pretty_host.endswith("example.com"):
        resp = HTTPResponse("HTTP/1.1", 200, "OK",
                            Headers(Content_Type="text/html"), "helloworld")
        flow.reply(resp)

    # Method 2: Redirect the request to a different server
    if flow.request.pretty_host.endswith("example.org"):
        flow.request.host = "mitmproxy.org"
示例#27
0
    def test_refresh_cookie(self):
        r = HTTPResponse.wrap(netlib.tutils.tresp())

        # Invalid expires format, sent to us by Reddit.
        c = "rfoo=bar; Domain=reddit.com; expires=Thu, 31 Dec 2037 23:59:59 GMT; Path=/"
        assert r._refresh_cookie(c, 60)

        c = "MOO=BAR; Expires=Tue, 08-Mar-2011 00:20:38 GMT; Path=foo.com; Secure"
        assert "00:21:38" in r._refresh_cookie(c, 60)

        # https://github.com/mitmproxy/mitmproxy/issues/773
        c = ">=A"
        with tutils.raises(ValueError):
            r._refresh_cookie(c, 60)
示例#28
0
    def test_refresh_cookie(self):
        r = HTTPResponse.wrap(netlib.tutils.tresp())

        # Invalid expires format, sent to us by Reddit.
        c = "rfoo=bar; Domain=reddit.com; expires=Thu, 31 Dec 2037 23:59:59 GMT; Path=/"
        assert r._refresh_cookie(c, 60)

        c = "MOO=BAR; Expires=Tue, 08-Mar-2011 00:20:38 GMT; Path=foo.com; Secure"
        assert "00:21:38" in r._refresh_cookie(c, 60)

        # https://github.com/mitmproxy/mitmproxy/issues/773
        c = ">=A"
        with tutils.raises(ValueError):
            r._refresh_cookie(c, 60)
示例#29
0
    def test_server_playback_kill(self):
        s = flow.State()
        f = tutils.tflow()
        f.response = HTTPResponse.wrap(netlib.tutils.tresp(content=f.request))
        pb = [f]
        fm = flow.FlowMaster(None, s)
        fm.refresh_server_playback = True
        fm.start_server_playback(pb, True, [], False, False, None, False, None,
                                 False)

        f = tutils.tflow()
        f.request.host = "nonexistent"
        fm.process_new_request(f)
        assert "killed" in f.error.msg
示例#30
0
    def test_refresh(self):
        r = HTTPResponse.wrap(netlib.tutils.tresp())
        n = time.time()
        r.headers["date"] = email.utils.formatdate(n)
        pre = r.headers["date"]
        r.refresh(n)
        assert pre == r.headers["date"]
        r.refresh(n + 60)

        d = email.utils.parsedate_tz(r.headers["date"])
        d = email.utils.mktime_tz(d)
        # Weird that this is not exact...
        assert abs(60 - (d - n)) <= 1

        r.headers["set-cookie"] = "MOO=BAR; Expires=Tue, 08-Mar-2011 00:20:38 GMT; Path=foo.com; Secure"
        r.refresh()
示例#31
0
    def test_refresh(self):
        r = HTTPResponse.wrap(netlib.tutils.tresp())
        n = time.time()
        r.headers["date"] = email.utils.formatdate(n)
        pre = r.headers["date"]
        r.refresh(n)
        assert pre == r.headers["date"]
        r.refresh(n + 60)

        d = email.utils.parsedate_tz(r.headers["date"])
        d = email.utils.mktime_tz(d)
        # Weird that this is not exact...
        assert abs(60 - (d - n)) <= 1

        r.headers[
            "set-cookie"] = "MOO=BAR; Expires=Tue, 08-Mar-2011 00:20:38 GMT; Path=foo.com; Secure"
        r.refresh()
示例#32
0
    def test_all(self):
        s = flow.State()
        fm = flow.FlowMaster(None, None, s)
        f = tutils.tflow(req=None)
        fm.clientconnect(f.client_conn)
        f.request = HTTPRequest.wrap(netlib.tutils.treq())
        fm.request(f)
        assert s.flow_count() == 1

        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        fm.response(f)
        assert s.flow_count() == 1

        fm.clientdisconnect(f.client_conn)

        f.error = Error("msg")
        fm.error(f)

        fm.shutdown()
示例#33
0
    def handle_request(self, flow):
        hid = (flow.request.host, flow.request.port)

        host = flow.request.pretty_host
        path = flow.request.path[1:]

        if self.is_supported_api(host) and os.path.isfile(path):

            print "Stubbing: %s/%s" % (host, path)
            f = open(path, 'r')
            resp = HTTPResponse("HTTP/1.1", 200, "OK",
                                Headers(Content_Type="text/json"), f.read())
            f.close()
            flow.reply(resp)
        elif self.is_supported_host(host):
            print "Should we capture ?: %s/%s" % (host, path)
            flow.reply()
        else:
            flow.reply()
示例#34
0
    def test_all(self):
        s = flow.State()
        fm = flow.FlowMaster(None, None, s)
        f = tutils.tflow(req=None)
        fm.clientconnect(f.client_conn)
        f.request = HTTPRequest.wrap(netlib.tutils.treq())
        fm.request(f)
        assert s.flow_count() == 1

        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        fm.response(f)
        assert s.flow_count() == 1

        fm.clientdisconnect(f.client_conn)

        f.error = Error("msg")
        fm.error(f)

        fm.shutdown()
示例#35
0
    def test_all(self):
        s = flow.State()
        fm = flow.FlowMaster(None, None, s)
        f = tutils.tflow(req=None)
        fm.clientconnect(f.client_conn)
        f.request = HTTPRequest.wrap(netlib.tutils.treq())
        fm.request(f)
        assert s.flow_count() == 1

        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        fm.response(f)
        assert s.flow_count() == 1

        fm.clientdisconnect(f.client_conn)

        f.error = Error("msg")
        f.error.reply = controller.DummyReply()
        fm.error(f)

        fm.load_script(tutils.test_data.path("data/scripts/a.py"))
        fm.shutdown()
示例#36
0
    def test_server_playback_kill(self):
        s = flow.State()
        f = tutils.tflow()
        f.response = HTTPResponse.wrap(netlib.tutils.tresp(content=f.request))
        pb = [f]
        fm = flow.FlowMaster(None, s)
        fm.refresh_server_playback = True
        fm.start_server_playback(
            pb,
            True,
            [],
            False,
            False,
            None,
            False,
            None,
            False)

        f = tutils.tflow()
        f.request.host = "nonexistent"
        fm.process_new_request(f)
        assert "killed" in f.error.msg
示例#37
0
    def test_all(self):
        s = flow.State()
        fm = flow.FlowMaster(None, s)
        fm.anticache = True
        fm.anticomp = True
        f = tutils.tflow(req=None)
        fm.clientconnect(f.client_conn)
        f.request = HTTPRequest.wrap(netlib.tutils.treq())
        fm.request(f)
        assert s.flow_count() == 1

        f.response = HTTPResponse.wrap(netlib.tutils.tresp())
        fm.response(f)
        assert s.flow_count() == 1

        fm.clientdisconnect(f.client_conn)

        f.error = Error("msg")
        f.error.reply = controller.DummyReply()
        fm.error(f)

        fm.load_script(tutils.test_data.path("data/scripts/a.py"))
        fm.shutdown()
示例#38
0
    def request(self, flow):
        # This will often cause problems later, so we just remove it
        if "Accept-Encoding" in flow.request.headers:
            del flow.request.headers["Accept-Encoding"]

        ll = common.bcpConfig.foundMatch(flow.request.headers["host"],
                                         flow.request.path, "inject", True)
        ll2 = common.bcpConfig.foundMatch(flow.request.headers["host"],
                                          flow.request.path, "serve", False)

        # Can only be one response, if multiple we take the first
        res = None
        if len(ll) > 0:
            res = ll[0]
        if len(ll2) > 0:
            res = ll2[0]

        if res != None:
            r = HTTPResponse.make(200, "",
                                  common.list2headers(res.get("headers", [])))
            r.raw_content = res.get("data").encode()
            flow.response = r
        return
示例#39
0
def requests2mitmproxy(resp):
    # We first remove some troublesome headers

    # Content is automatically decoded
    if "Content-Encoding" in resp.headers: del resp.headers["Content-Encoding"]

    # Remove clickjacking protections
    if "X-Frame-Options" in resp.headers: del resp.headers["X-Frame-Options"]

    # Ensure that cookies can be sent over HTTP
    if "Set-Cookie" in resp.headers:
        resp.headers["Set-Cookie"] = resp.headers["Set-Cookie"].replace(
            " Secure;", " ")
        resp.headers["Set-Cookie"] = resp.headers["Set-Cookie"].replace(
            " Secure", " ")

    h = list(resp.headers.items())
    headers = []
    for i in h:
        headers.append((i[0].encode(), i[1].encode()))

    r = HTTPResponse.make(200, stripHttpsLinks(resp.content), headers)
    return r
示例#40
0
 def test_get_content_type(self):
     resp = HTTPResponse.wrap(netlib.tutils.tresp())
     resp.headers = Headers(content_type="text/plain")
     assert resp.headers["content-type"] == "text/plain"
示例#41
0
 def request(self, f):
     resp = HTTPResponse.wrap(netlib.tutils.tresp())
     f.reply(resp)
示例#42
0
 def request(self, f):
     resp = HTTPResponse.wrap(netlib.tutils.tresp())
     resp.content = None
     f.reply(resp)
示例#43
0
 def _add_response(self, state):
     f = tutils.tflow()
     state.add_flow(f)
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
     state.update_flow(f)
示例#44
0
 def request(self, f):
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
示例#45
0
def request(context, flow):
    print flow.request.path
    m = re.match("^/geoserver/i/([\d]+)/([\d]+)/([\d]+)$", flow.request.path)
    if m is not None:
        print "match success!"
        imagename = flow.request.path_components[1] + '_' + flow.request.path_components[2] + '_' + flow.request.path_components[3] + '_' + flow.request.path_components[4];
        imagequerycache = "/home/root/accesscache " + imagename;
        imagequerycacheresult = os.popen(imagequerycache).read();
        if (imagequerycacheresult != "No" and imagequerycacheresult != "ERROR"):
        	resp = HTTPResponse(
		"HTTP/1.1", 200, "OK", Headers(Content_Type="image/png"), "helloworld")
                with open(imagequerycacheresult, 'r') as f:
             		payload = f.read()
             		resp.content = payload
             		resp.headers["Content-Length"] = str(len(payload))
                        resp.headers["Access-Control-Allow-Origin"] = "*"
                        print len(payload)
                        f.close()
                flow.reply(resp)
                return
	else:
		imagefilepath = "/home/root/bpqrecv/" + imagename;
                randregid = randrange(0, 32768);
		print randregid;
		querycomm = "/home/root/DTN2/apps/dtnquery/dtnquery -m send -s dtn://dtn1.dtn -d dtn://dtn2.dtn -q " + imagename + " -i " + str(randregid);
                print querycomm;
		os.system(querycomm);
                for x in range(0, 60):
			imagequerycacheresult = os.popen(imagequerycache).read();
			if (imagequerycacheresult != "No" and imagequerycacheresult != "ERROR"):
				resp = HTTPResponse(
				"HTTP/1.1", 200, "OK", Headers(Content_Type="image/png"), "helloworld")
                		with open(imagequerycacheresult, 'r') as f:
             				payload = f.read()
             				resp.content = payload
             				resp.headers["Content-Length"] = str(len(payload))
					resp.headers["Access-Control-Allow-Origin"] = "*"
                       			print len(payload)
                        		f.close()
                		flow.reply(resp)
                		return
                	else:	
                		time.sleep(1);
    z = re.match("^/geoserver/z/([\d]+)/([\d]+)/([\d]+)$", flow.request.path)
    if z is not None:
        vectorname = flow.request.path_components[1] + '_' +  flow.request.path_components[2] + '_' + flow.request.path_components[3] + '_' + flow.request.path_components[4]
        vectorquerycache = "/tmp/ramdisk0/accesscache " + vectorname;
	vectorquerycacheresult = os.popen(vectorquerycache).read();
        if (vectorquerycacheresult != "No" and vectorquerycacheresult != "ERROR"):
        	resp = HTTPResponse(
		"HTTP/1.1", 200, "OK", Headers(Content_Type="application/octet-stream"), "helloworld")
                with open(vectorquerycacheresult, 'r') as f:
             		payload = f.read()
             		resp.content = payload
             		resp.headers["Content-Length"] = str(len(payload))
			resp.headers["Access-Control-Allow-Origin"] = "*"
                        resp.headers["Cache-Control"]= "public, max-age=86400"
                        print len(payload)
                        f.close()
                flow.reply(resp)
                return
        else:
                waitingcomm = "/tmp/ramdisk0/waiting " + vectorname;
                os.system(waitingcomm);
        	vectorquerycacheresult = os.popen(vectorquerycache).read();
                print "vectorquerycacheresult: " + vectorquerycacheresult;
                if (vectorquerycacheresult != "No" and vectorquerycacheresult != "ERROR"):
        		resp = HTTPResponse(
			"HTTP/1.1", 200, "OK", Headers(Content_Type="application/octet-stream"), "helloworld")
                	with open(vectorquerycacheresult, 'r') as f:
             			payload = f.read()
             			resp.content = payload
             			resp.headers["Content-Length"] = str(len(payload))
				resp.headers["Access-Control-Allow-Origin"] = "*"
                                resp.headers["Cache-Control"]= "public, max-age=86400"
                        	print len(payload)
                        	f.close()
                	flow.reply(resp)
                        return
    v = re.match("^/geoserver/v/([\d]+)/([\d]+)/([\d]+)$", flow.request.path)
    if v is not None:
        vectorname = flow.request.path_components[1] + '_' +  flow.request.path_components[2] + '_' + flow.request.path_components[3] + '_' + flow.request.path_components[4]
        print "vectorname: " + vectorname;
        vectorquerycache = "/tmp/ramdisk0/accesscache " + vectorname;
	vectorquerycacheresult = os.popen(vectorquerycache).read();
        if (vectorquerycacheresult != "No" and vectorquerycacheresult != "ERROR"):
        	resp = HTTPResponse(
		"HTTP/1.1", 200, "OK", Headers(Content_Type="application/json"), "helloworld")
                with open(vectorquerycacheresult, 'r') as f:
             		payload = f.read()
             		resp.content = payload
             		resp.headers["Content-Length"] = str(len(payload))
			resp.headers["Access-Control-Allow-Origin"] = "*"
                        resp.headers["Cache-Control"]= "public, max-age=86400"
                        print len(payload)
                        f.close()
                flow.reply(resp)
                return
        else:
                waitingcomm = "/tmp/ramdisk0/waiting " + vectorname;
                os.system(waitingcomm);
        	vectorquerycacheresult = os.popen(vectorquerycache).read();
                if (vectorquerycacheresult != "No" and vectorquerycacheresult != "ERROR"):
        		resp = HTTPResponse(
			"HTTP/1.1", 200, "OK", Headers(Content_Type="application/json"), "helloworld")
                	with open(vectorquerycacheresult, 'r') as f:
             			payload = f.read()
             			resp.content = payload
             			resp.headers["Content-Length"] = str(len(payload))
				resp.headers["Access-Control-Allow-Origin"] = "*"
                                resp.headers["Cache-Control"]= "public, max-age=86400"
                        	print len(payload)
                        	f.close()
                	flow.reply(resp)
                	return
    resp = HTTPResponse(
		"HTTP/1.1", 404, "Not Found", Headers(Content_Type="text/html"), "Not Found")
    resp.headers["Content-Length"] = str(len("Not Found"))
    flow.reply(resp)
示例#46
0
 def request(self, f):
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
示例#47
0
 def test_get_content_type(self):
     resp = HTTPResponse.wrap(netlib.tutils.tresp())
     resp.headers = Headers(content_type="text/plain")
     assert resp.headers["content-type"] == "text/plain"
示例#48
0
 def request(self, f):
     resp = HTTPResponse.wrap(netlib.tutils.tresp())
     resp.content = None
     f.response = resp
示例#49
0
 def handle_request(self, f):
     resp = HTTPResponse.wrap(netlib.tutils.tresp())
     resp.content = CONTENT_MISSING
     f.reply(resp)
示例#50
0
 def _add_response(self, state):
     f = tutils.tflow()
     state.add_flow(f)
     f.response = HTTPResponse.wrap(netlib.tutils.tresp())
     state.update_flow(f)