summaryrefslogtreecommitdiff
path: root/notmuch-tcp-client
blob: b29d6b2454b3431721e9cf82ce814cdd9c1fda82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!@python@/bin/python

from os import environ
from os.path import expanduser
import socket
import ssl
from shlex import quote
from sys import argv, stdin, stdout
from multiprocessing import Process
from select import select


port = environ.get('NOTMUCH_TCP')
host = environ.get('NOTMUCH_HOST')
hostname = socket.gethostname()

if port is None:
    port = 2010
if host is None:
    host = "odin.asgard.yggdrasil"


sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
sslcontext.load_verify_locations(cafile = expanduser('~/.notmuch-tcp/ca.pem'))
sslcontext.load_cert_chain(certfile = expanduser(f"~/.notmuch-tcp/{hostname}.pem"), keyfile = expanduser(f"~/.notmuch-tcp/{hostname}.key"))

with socket.create_connection((host, port)) as sock:
    with sslcontext.wrap_socket(sock, server_hostname = host) as ssock:
        def send_args():
            escaped_args = ' '.join(map(quote, argv[1:]))
            ssock.sendall(f"{escaped_args}\n".encode())

        def send_stdin():
            with open(0, 'rb') as stdin_bin:
                while True:
                    to_send = stdin_bin.read(256)

                    if to_send:
                        ssock.sendall(to_send)
                    else:
                        break

        def recv_stdout():
            with open(1, 'wb') as stdout_bin:
                while True:
                    ready = select([ssock], [], [], 5)
                    if ready[0]:
                        received = ssock.recv(256)
                        if len(received) <= 0:
                            break
                        stdout_bin.write(received)
                    else:
                        break

        send_args()
        send = Process(target = send_stdin)
        recv = Process(target = recv_stdout)
        send.start()
        recv.start()
        recv.join()
        send.terminate()