Release 0.9
[0publish-gui.git] / signing.py
blobcb6fd5503804472f4717ecf7845973e6dc700a3c
1 from zeroinstall import SafeException
2 from zeroinstall.injector import gpg
3 import tempfile, os, base64, sys, shutil, signal
4 import subprocess
5 from rox import tasks, g
6 import gobject
8 umask = os.umask(0)
9 os.umask(umask)
11 class LineBuffer:
12 def __init__(self):
13 self.data = ''
15 def add(self, new):
16 assert new
17 self.data += new
19 def __iter__(self):
20 while '\n' in self.data:
21 command, self.data = self.data.split('\n', 1)
22 yield command
24 def _io_callback(src, cond, blocker):
25 blocker.trigger()
26 return False
28 # (version in ROX-Lib < 2.0.4 is buggy; missing IO_HUP)
29 class InputBlocker(tasks.Blocker):
30 """Triggers when os.read(stream) would not block."""
31 _tag = None
32 _stream = None
33 def __init__(self, stream):
34 tasks.Blocker.__init__(self)
35 self._stream = stream
37 def add_task(self, task):
38 tasks.Blocker.add_task(self, task)
39 if self._tag is None:
40 self._tag = gobject.io_add_watch(self._stream, gobject.IO_IN | gobject.IO_HUP,
41 _io_callback, self)
43 def remove_task(self, task):
44 tasks.Blocker.remove_task(self, task)
45 if not self._rox_lib_tasks:
46 gobject.source_remove(self._tag)
47 self._tag = None
49 def get_secret_keys():
50 child = subprocess.Popen(('gpg', '--list-secret-keys', '--with-colons', '--with-fingerprint'),
51 stdout = subprocess.PIPE)
52 stdout, _ = child.communicate()
53 status = child.wait()
54 if status:
55 raise Exception("GPG failed with exit code %d" % status)
56 keys = []
57 for line in stdout.split('\n'):
58 line = line.split(':')
59 if line[0] == 'sec':
60 keys.append([None, line[9]])
61 elif line[0] == 'fpr':
62 keys[-1][0] = line[9]
63 elif line[0] == 'uid':
64 keys.append([keys[-1][0], line[9]])
65 return keys
67 def check_signature(path):
68 data = file(path).read()
69 xml_comment = data.rfind('\n<!-- Base64 Signature')
70 if xml_comment >= 0:
71 data_stream, sigs = gpg.check_stream(file(path))
72 sign_fn = sign_xml
73 data = data[:xml_comment + 1]
74 data_stream.close()
75 elif data.startswith('-----BEGIN'):
76 data_stream, sigs = gpg.check_stream(file(path))
77 sign_fn = sign_xml # Don't support saving as plain
78 data = data_stream.read()
79 else:
80 return data, sign_unsigned, None
81 for sig in sigs:
82 if isinstance(sig, gpg.ValidSig):
83 return data, sign_fn, sig.fingerprint
84 error = "ERROR: No valid signatures found!\n"
85 for sig in sigs:
86 error += "\nGot: %s" % sig
87 error += '\n\nTo edit it anyway, remove the signature using a text editor.'
88 raise Exception(error)
90 def write_tmp(path, data):
91 """Create a temporary file in the same directory as 'path' and write data to it."""
92 fd, tmp = tempfile.mkstemp(prefix = 'tmp-', dir = os.path.dirname(path))
93 stream = os.fdopen(fd, 'w')
94 stream.write(data)
95 stream.close()
96 os.chmod(tmp, 0644 &~umask)
97 return tmp
99 def run_gpg(default_key, *arguments):
100 arguments = list(arguments)
101 if default_key is not None:
102 arguments = ['--default-key', default_key] + arguments
103 arguments.insert(0, 'gpg')
104 if os.spawnvp(os.P_WAIT, 'gpg', arguments):
105 raise SafeException("Command '%s' failed" % arguments)
107 def sign_unsigned(path, data, key, callback):
108 os.rename(write_tmp(path, data), path)
109 if callback: callback()
111 def sign_xml(path, data, key, callback):
112 import main
113 wTree = g.glade.XML(main.gladefile, 'get_passphrase')
114 box = wTree.get_widget('get_passphrase')
115 box.set_default_response(g.RESPONSE_OK)
116 entry = wTree.get_widget('passphrase')
118 buffer = LineBuffer()
120 killed = False
121 error = False
122 tmp = None
123 r, w = os.pipe()
124 try:
125 def setup_child():
126 os.close(r)
128 tmp = write_tmp(path, data)
129 sigtmp = tmp + '.sig'
131 hasAgent = os.environ["GPG_AGENT_INFO"]
132 child = subprocess.Popen(('gpg', '--default-key', key,
133 '--detach-sign', '--status-fd', str(w),
134 '--command-fd', '0',
135 '--no-tty',
136 '--output', sigtmp,
137 '--use-agent',
138 '-q',
139 tmp),
140 preexec_fn = setup_child,
141 stdin = subprocess.PIPE)
143 os.close(w)
144 w = None
145 while True:
146 input = InputBlocker(r)
147 yield input
148 msg = os.read(r, 100)
149 if not msg: break
150 buffer.add(msg)
151 for command in buffer:
152 if command.startswith('[GNUPG:] NEED_PASSPHRASE ') and not hasAgent:
153 entry.set_text('')
154 box.present()
155 resp = box.run()
156 box.hide()
157 if resp == g.RESPONSE_OK:
158 child.stdin.write(entry.get_text() + '\n')
159 child.stdin.flush()
160 else:
161 os.kill(child.pid, signal.SIGTERM)
162 killed = True
164 status = child.wait()
165 if status:
166 raise Exception("GPG failed with exit code %d" % status)
167 except:
168 # No generator finally blocks in Python 2.4...
169 error = True
171 if r is not None: os.close(r)
172 if w is not None: os.close(w)
173 if tmp is not None: os.unlink(tmp)
175 if killed: return
176 if error: raise
178 encoded = base64.encodestring(file(sigtmp).read())
179 os.unlink(sigtmp)
180 sig = "<!-- Base64 Signature\n" + encoded + "\n-->\n"
181 os.rename(write_tmp(path, data + sig), path)
183 if callback: callback()
185 def export_key(dir, fingerprint):
186 assert fingerprint is not None
187 # Convert fingerprint to key ID
188 stream = os.popen('gpg --with-colons --list-keys %s' % fingerprint)
189 try:
190 keyID = None
191 for line in stream:
192 parts = line.split(':')
193 if parts[0] == 'pub':
194 if keyID:
195 raise Exception('Two key IDs returned from GPG!')
196 keyID = parts[4]
197 finally:
198 stream.close()
199 key_file = os.path.join(dir, keyID + '.gpg')
200 if os.path.isfile(key_file):
201 return None
202 key_stream = file(key_file, 'w')
203 stream = os.popen("gpg -a --export '%s'" % fingerprint)
204 shutil.copyfileobj(stream, key_stream)
205 stream.close()
206 key_stream.close()
207 return key_file