2019-11-22 05:16:01 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
proxy.py
|
|
|
|
~~~~~~~~
|
|
|
|
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
|
|
|
|
Network monitoring, controls & Application development, testing, debugging.
|
|
|
|
|
|
|
|
:copyright: (c) 2013-present by Abhinav Singh and contributors.
|
|
|
|
:license: BSD, see LICENSE for more details.
|
|
|
|
"""
|
|
|
|
import logging
|
|
|
|
import os
|
2020-10-14 05:21:56 +00:00
|
|
|
import tempfile
|
2019-11-22 05:16:01 +00:00
|
|
|
from typing import Optional, BinaryIO
|
2020-02-01 16:51:25 +00:00
|
|
|
from uuid import UUID
|
2019-11-22 05:16:01 +00:00
|
|
|
|
2020-10-14 05:21:56 +00:00
|
|
|
from ....common.flag import flags
|
2019-11-22 05:16:01 +00:00
|
|
|
from ....common.utils import text_
|
|
|
|
from ....http.parser import HttpParser
|
|
|
|
|
|
|
|
from .base import CacheStore
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2020-10-14 05:21:56 +00:00
|
|
|
flags.add_argument(
|
|
|
|
'--cache-dir',
|
|
|
|
type=str,
|
|
|
|
default=tempfile.gettempdir(),
|
|
|
|
help='Default: A temporary directory. Flag only applicable when cache plugin is used with on-disk storage.'
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2019-11-22 05:16:01 +00:00
|
|
|
class OnDiskCacheStore(CacheStore):
|
|
|
|
|
2020-02-01 16:51:25 +00:00
|
|
|
def __init__(self, uid: UUID, cache_dir: str) -> None:
|
2019-11-22 05:16:01 +00:00
|
|
|
super().__init__(uid)
|
|
|
|
self.cache_dir = cache_dir
|
|
|
|
self.cache_file_path: Optional[str] = None
|
|
|
|
self.cache_file: Optional[BinaryIO] = None
|
|
|
|
|
|
|
|
def open(self, request: HttpParser) -> None:
|
|
|
|
self.cache_file_path = os.path.join(
|
|
|
|
self.cache_dir,
|
2020-02-01 16:51:25 +00:00
|
|
|
'%s-%s.txt' % (text_(request.host), self.uid.hex))
|
2019-11-22 05:16:01 +00:00
|
|
|
self.cache_file = open(self.cache_file_path, "wb")
|
|
|
|
|
|
|
|
def cache_request(self, request: HttpParser) -> Optional[HttpParser]:
|
|
|
|
return request
|
|
|
|
|
2019-11-27 01:59:26 +00:00
|
|
|
def cache_response_chunk(self, chunk: memoryview) -> memoryview:
|
2019-11-22 05:16:01 +00:00
|
|
|
if self.cache_file:
|
2019-11-27 01:59:26 +00:00
|
|
|
self.cache_file.write(chunk.tobytes())
|
2019-11-22 05:16:01 +00:00
|
|
|
return chunk
|
|
|
|
|
|
|
|
def close(self) -> None:
|
|
|
|
if self.cache_file:
|
|
|
|
self.cache_file.close()
|
|
|
|
logger.info('Cached response at %s', self.cache_file_path)
|