/
mailcap-server.py
191 lines (162 loc) · 5.78 KB
/
mailcap-server.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!python3
import struct
import socket
import os
import tempfile
import mailcap
import sys
import argparse
import daemon
import hashlib
sockpath = "mailcap.sock"
if os.path.exists(sockpath):
os.remove(sockpath)
class Server(object):
class Connection(object):
def __init__(self, conn):
self._conn = conn
def timeout(self, timeout):
return self._conn.settimeout(timeout)
def close(self):
self._conn.close()
def recv(self, size):
data = self._conn.recv(size)
return data
def send(self, data):
return self._conn.send(data)
def recv_exact(self, length):
retval = bytes()
while len(retval) < length:
data = self.recv(length - len(retval))
if len(data) == 0:
return None
retval += data
return retval
def __init__(self, path="mailcap.sock", dir = None):
self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._socket.bind(path)
self._socket.listen(3)
if dir:
if not os.path.exists(dir):
os.makedirs(dir)
self._dir = dir
else:
self._dir = tempfile.TemporaryDirectory()
def close(self):
self._socket.close()
self._dir.cleanup()
def next_file(self, initial_timeout=None, timeout=5):
conn = self.Connection(self._socket.accept()[0])
conn.timeout(initial_timeout)
# Receive filename length
data = conn.recv_exact(1)
if data is None:
return None
fn_len = struct.unpack("B", data)[0]
conn.timeout(timeout)
# Receive filename
data = conn.recv_exact(fn_len)
if data is None:
return None
fn = data.decode('utf-8')
# Strip the filename of /, do sanity checks
fn = fn.replace("/", "_")
if len(fn) == 0 or fn in ['.', '..']:
s.close()
return None
# Receive the mime type length
data = conn.recv_exact(1)
if data is None:
return None
mime_len = struct.unpack("B", data)[0]
# Receive the mime type
data = conn.recv_exact(mime_len)
if data is None:
return None
mime = data.decode('utf-8')
# Receive the SHA256 hash
data = conn.recv_exact(hashlib.sha256().digest_size)
if data is None:
return None
full_name = os.path.join(self._dir.name, fn)
append = 0
# While the filename already exists, check if we have a hash match
while os.path.exists(full_name):
hash = hashlib.sha256()
hash.update(open(full_name, "rb").read())
# Found a matching file. Do not receive the file.
if data == hash.digest():
conn.send(b'\x00')
conn.close()
return full_name, mime
append += 1
hash = hashlib.sha256()
name_parts = fn.split('.')
if len(name_parts) > 1:
full_name = os.path.join(self._dir.name, "%s-%d.%s" % ('.'.join(name_parts[:-1]), append, name_parts[-1]))
else:
full_name = os.path.join(self._dir.name, "%s-%d" % (fn, append, name_parts[-1]))
conn.send(b'\x01')
# Receive the file length
data = conn.recv_exact(4)
if data is None:
return None
file_len = struct.unpack("!I", data)[0]
# Receive the file data
fn = os.path.join(self._dir.name, fn)
with open(fn, "wb+") as f:
while file_len > 0:
data = conn.recv(min(4096, file_len))
f.write(data)
file_len -= len(data)
conn.close()
if file_len is 0:
return fn, mime
else:
os.remove(fn)
return None
def run_server(args):
sv = Server(path=args.socket, dir=args.dir)
caps = mailcap.getcaps()
open(args.pid, "w+").write(str(os.getpid()))
while True:
rv = sv.next_file()
if rv:
f, mime = rv
print(f, mime)
match = mailcap.findmatch(caps, mime.split(';')[0], filename=f)
if match and match[0]:
os.system(match[0])
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--pid', '-p', default=os.path.join(os.environ['HOME'], '.mailcap.pid'))
parser.add_argument('--action', '-a', default='run', choices=['run', 'kill'])
parser.add_argument('--no-daemonize', '-n', action='store_true')
parser.add_argument('--socket', '-s', default=os.path.join(os.environ['HOME'], '.mailcap.sock'))
parser.add_argument('--dir', '-d', default=None)
parser.add_argument('--force', '-f', action='store_true')
args = parser.parse_args()
if args.action == 'kill' or args.force:
if os.path.exists(args.socket):
os.remove(args.socket)
if os.path.exists(args.pid):
pid = int(open(args.pid).read())
try:
os.kill(pid, 3)
except ProcessLookupError as e:
if not args.force:
print("Failed to kill process with pid %d:" % (pid,), str(e))
os.remove(args.pid)
if os.path.exists(args.socket):
os.remove(args.socket)
if args.action == 'run':
if os.path.exists(args.pid):
print("Already running with pid %d" % (int(open(args.pid).read()),))
exit()
if os.path.exists(args.socket):
os.remove(args.socket)
if args.no_daemonize:
run_server(args)
else:
with daemon.DaemonContext():
run_server(args)