Skip to content

Commit

Permalink
enable multiprocess logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Felix Bartler committed Apr 28, 2023
1 parent 671c2c1 commit 43bfb15
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 9 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ def main():
```
The ProxySwapContext takes essentially 3 mandatory arguments.


#### Logging and Debugging
```python
from SocketSwap import ProxySwapContext

# debug level logging
import logging
socket_swap_logger = logging.getLogger("SocketSwap")
socket_swap_logger.addHandler(logging.StreamHandler())
socket_swap_logger.setLevel(logging.DEBUG)

```
By default logging is not enabled. You can do so by assigning a handler to the "SocketSwap" logger and choosing a level.

## Credits:

The TCP Proxy part is a slim modified version of https://github.com/ickerwx/tcpproxy.
48 changes: 48 additions & 0 deletions examples/basic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
Demo Szenario - Redirect traffic just locally
Setup:
A TCP Hello World Server on Port 4444 example: https://gist.github.com/fyx99/cb6389e3c1942729cdbfc7ad3a9e1c71
"""
import socket
from SocketSwap import SocketSwapContext

# debug level logging
import logging
socket_swap_logger = logging.getLogger("SocketSwap")
socket_swap_logger.addHandler(logging.StreamHandler())
socket_swap_logger.setLevel(logging.DEBUG)

def socket_factory():
target_host = "localhost"
target_port = 4444
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((target_host, target_port))
return remote_socket

def basic_traffic_redirect():
"""
This function demos how to easily setup the local proxy using the SocketSwapContext-Manager.
It exposes a local proxy on the localhost 127.0.0.1 on port 2222
The socket_factory is provided to handle the creation of a socket to the remote target
"""

with SocketSwapContext(socket_factory, "127.0.0.1", 2222):
# Set up a connection to the PostgreSQL database
target_host = "127.0.0.1"
target_port = 2222
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((target_host, target_port))

remote_socket.send(b"")
response = remote_socket.recv(4096)
print(response)






if __name__ == '__main__':
# for testing
basic_traffic_redirect()
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

setup(
name='SocketSwap',
version='0.1.8',
version='0.1.10',
description='SocketSwap is a python package that allows to proxy any third-party libraries traffic through a local TCP Proxy',
long_description=long_description,
long_description_content_type='text/markdown',
Expand Down
2 changes: 1 addition & 1 deletion socketswap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
SocketSwap is a python package that allows to proxy any third-party libraries traffic through a local TCP Proxy
"""

__version__ = "0.1.0"
__version__ = "0.1.10"
__author__ = 'fyx99'
__credits__ = 'No credits'

Expand Down
14 changes: 12 additions & 2 deletions socketswap/context_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
import SocketSwap.proxy as proxy
import time
import logging
from logging.handlers import QueueListener

logger = logging.getLogger("SocketSwap")
logger.addHandler(logging.StreamHandler())
logger.addHandler(logging.NullHandler())
logger.setLevel(logging.DEBUG)


Expand All @@ -18,15 +19,24 @@ def __init__(self, *args):

def __enter__(self):
logger.info("Starting Proxy Server")
self.proxy_process = multiprocessing.Process(target=proxy.start_local_proxy, args=(self.args))
log_queue = multiprocessing.Queue()

self.proxy_process = multiprocessing.Process(target=proxy.start_local_proxy, args=([log_queue, *self.args]))
self.proxy_process.daemon = True
self.proxy_process.start()
log_queue_listener = QueueListener(log_queue, *logger.handlers)
log_queue_listener.start()
time.sleep(1)
return self

def __exit__(self, exc_type, exc_value, traceback):
logger.info("Exiting proxy server")
time.sleep(0.1)
self.proxy_process.terminate()
if exc_type:
logger.error(str(exc_type))
logger.error(str(exc_value))
logger.error(str(traceback))



16 changes: 11 additions & 5 deletions socketswap/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@
import select
import errno
import logging
from logging.handlers import QueueHandler
from typing import Callable, List

logger = logging.getLogger("SocketSwap")
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)


logger = None
proxy_socket = None

def is_valid_ip4(ip):
Expand Down Expand Up @@ -199,6 +197,7 @@ def proxy_thread(socket_factory: Callable[[], socket.socket], local_socket: sock
raise socket_error
return None

logger.info("Remote Socket connected successfully")

running = True
while running:
Expand Down Expand Up @@ -255,9 +254,15 @@ def proxy_thread(socket_factory: Callable[[], socket.socket], local_socket: sock



def start_local_proxy(socket_factory, local_host, local_port, server_key=None, server_certificate=None, client_key=None, client_certificate=None, use_ssl=False):
def start_local_proxy(log_queue, socket_factory, local_host, local_port, server_key=None, server_certificate=None, client_key=None, client_certificate=None, use_ssl=False):
"""starts a local proxy server"""
global proxy_socket
global logger

logger = logging.getLogger("SocketSwapProxy")
logger.addHandler(QueueHandler(log_queue))
logger.setLevel(logging.DEBUG)

logger.info("Starting local proxy server")

if ((client_key is None) ^ (client_certificate is None)):
Expand Down Expand Up @@ -302,6 +307,7 @@ def start_local_proxy(socket_factory, local_host, local_port, server_key=None, s
sys.exit(0)



def stop_local_proxy():
"""
Stops the local proxy server by closing the listening socket.
Expand Down

0 comments on commit 43bfb15

Please sign in to comment.