Added x86_64 (and ppc) cpu types to the default list.
[0publish-gui.git] / signing.py
blobaf767598492c3c3b1327709a72a38aae83940eb9
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 return keys
65 def check_signature(path):
66 data = file(path).read()
67 xml_comment = data.rfind('\n<!-- Base64 Signature')
68 if xml_comment >= 0:
69 data_stream, sigs = gpg.check_stream(file(path))
70 sign_fn = sign_xml
71 data = data[:xml_comment + 1]
72 data_stream.close()
73 elif data.startswith('-----BEGIN'):
74 data_stream, sigs = gpg.check_stream(file(path))
75 sign_fn = sign_xml # Don't support saving as plain
76 data = data_stream.read()
77 else:
78 return data, sign_unsigned, None
79 for sig in sigs:
80 if isinstance(sig, gpg.ValidSig):
81 return data, sign_fn, sig.fingerprint
82 error = "ERROR: No valid signatures found!\n"
83 for sig in sigs:
84 error += "\nGot: %s" % sig
85 error += '\n\nTo edit it anyway, remove the signature using a text editor.'
86 raise Exception(error)
88 def write_tmp(path, data):
89 """Create a temporary file in the same directory as 'path' and write data to it."""
90 fd, tmp = tempfile.mkstemp(prefix = 'tmp-', dir = os.path.dirname(path))
91 stream = os.fdopen(fd, 'w')
92 stream.write(data)
93 stream.close()
94 os.chmod(tmp, 0644 &~umask)
95 return tmp
97 def run_gpg(default_key, *arguments):
98 arguments = list(arguments)
99 if default_key is not None:
100 arguments = ['--default-key', default_key] + arguments
101 arguments.insert(0, 'gpg')
102 if os.spawnvp(os.P_WAIT, 'gpg', arguments):
103 raise SafeException("Command '%s' failed" % arguments)
105 def sign_unsigned(path, data, key, callback):
106 os.rename(write_tmp(path, data), path)
107 if callback: callback()
109 def sign_xml(path, data, key, callback):
110 import main
111 wTree = g.glade.XML(main.gladefile, 'get_passphrase')
112 box = wTree.get_widget('get_passphrase')
113 box.set_default_response(g.RESPONSE_OK)
114 entry = wTree.get_widget('passphrase')
116 buffer = LineBuffer()
118 killed = False
119 error = False
120 tmp = None
121 r, w = os.pipe()
122 try:
123 def setup_child():
124 os.close(r)
126 tmp = write_tmp(path, data)
127 sigtmp = tmp + '.sig'
129 child = subprocess.Popen(('gpg', '--default-key', key,
130 '--detach-sign', '--status-fd', str(w),
131 '--command-fd', '0',
132 '--no-tty',
133 '--output', sigtmp,
134 '-q',
135 tmp),
136 preexec_fn = setup_child,
137 stdin = subprocess.PIPE)
139 os.close(w)
140 w = None
141 while True:
142 input = InputBlocker(r)
143 yield input
144 msg = os.read(r, 100)
145 if not msg: break
146 buffer.add(msg)
147 for command in buffer:
148 if command.startswith('[GNUPG:] NEED_PASSPHRASE '):
149 entry.set_text('')
150 box.present()
151 resp = box.run()
152 box.hide()
153 if resp == g.RESPONSE_OK:
154 child.stdin.write(entry.get_text() + '\n')
155 child.stdin.flush()
156 else:
157 os.kill(child.pid, signal.SIGTERM)
158 killed = True
160 status = child.wait()
161 if status:
162 raise Exception("GPG failed with exit code %d" % status)
163 except:
164 # No generator finally blocks in Python 2.4...
165 error = True
167 if r is not None: os.close(r)
168 if w is not None: os.close(w)
169 if tmp is not None: os.unlink(tmp)
171 if killed: return
172 if error: raise
174 encoded = base64.encodestring(file(sigtmp).read())
175 os.unlink(sigtmp)
176 sig = "<!-- Base64 Signature\n" + encoded + "\n-->\n"
177 os.rename(write_tmp(path, data + sig), path)
179 if callback: callback()
181 def export_key(dir, fingerprint):
182 assert fingerprint is not None
183 # Convert fingerprint to key ID
184 stream = os.popen('gpg --with-colons --list-keys %s' % fingerprint)
185 try:
186 keyID = None
187 for line in stream:
188 parts = line.split(':')
189 if parts[0] == 'pub':
190 if keyID:
191 raise Exception('Two key IDs returned from GPG!')
192 keyID = parts[4]
193 finally:
194 stream.close()
195 key_file = os.path.join(dir, keyID + '.gpg')
196 if os.path.isfile(key_file):
197 return None
198 key_stream = file(key_file, 'w')
199 stream = os.popen("gpg -a --export '%s'" % fingerprint)
200 shutil.copyfileobj(stream, key_stream)
201 stream.close()
202 key_stream.close()
203 return key_file