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