diff options
Diffstat (limited to 'notmuch-tcp-client')
| -rw-r--r-- | notmuch-tcp-client | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/notmuch-tcp-client b/notmuch-tcp-client new file mode 100644 index 0000000..b29d6b2 --- /dev/null +++ b/notmuch-tcp-client | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | #!@python@/bin/python | ||
| 2 | |||
| 3 | from os import environ | ||
| 4 | from os.path import expanduser | ||
| 5 | import socket | ||
| 6 | import ssl | ||
| 7 | from shlex import quote | ||
| 8 | from sys import argv, stdin, stdout | ||
| 9 | from multiprocessing import Process | ||
| 10 | from select import select | ||
| 11 | |||
| 12 | |||
| 13 | port = environ.get('NOTMUCH_TCP') | ||
| 14 | host = environ.get('NOTMUCH_HOST') | ||
| 15 | hostname = socket.gethostname() | ||
| 16 | |||
| 17 | if port is None: | ||
| 18 | port = 2010 | ||
| 19 | if host is None: | ||
| 20 | host = "odin.asgard.yggdrasil" | ||
| 21 | |||
| 22 | |||
| 23 | sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) | ||
| 24 | sslcontext.load_verify_locations(cafile = expanduser('~/.notmuch-tcp/ca.pem')) | ||
| 25 | sslcontext.load_cert_chain(certfile = expanduser(f"~/.notmuch-tcp/{hostname}.pem"), keyfile = expanduser(f"~/.notmuch-tcp/{hostname}.key")) | ||
| 26 | |||
| 27 | with socket.create_connection((host, port)) as sock: | ||
| 28 | with sslcontext.wrap_socket(sock, server_hostname = host) as ssock: | ||
| 29 | def send_args(): | ||
| 30 | escaped_args = ' '.join(map(quote, argv[1:])) | ||
| 31 | ssock.sendall(f"{escaped_args}\n".encode()) | ||
| 32 | |||
| 33 | def send_stdin(): | ||
| 34 | with open(0, 'rb') as stdin_bin: | ||
| 35 | while True: | ||
| 36 | to_send = stdin_bin.read(256) | ||
| 37 | |||
| 38 | if to_send: | ||
| 39 | ssock.sendall(to_send) | ||
| 40 | else: | ||
| 41 | break | ||
| 42 | |||
| 43 | def recv_stdout(): | ||
| 44 | with open(1, 'wb') as stdout_bin: | ||
| 45 | while True: | ||
| 46 | ready = select([ssock], [], [], 5) | ||
| 47 | if ready[0]: | ||
| 48 | received = ssock.recv(256) | ||
| 49 | if len(received) <= 0: | ||
| 50 | break | ||
| 51 | stdout_bin.write(received) | ||
| 52 | else: | ||
| 53 | break | ||
| 54 | |||
| 55 | send_args() | ||
| 56 | send = Process(target = send_stdin) | ||
| 57 | recv = Process(target = recv_stdout) | ||
| 58 | send.start() | ||
| 59 | recv.start() | ||
| 60 | recv.join() | ||
| 61 | send.terminate() | ||
