1 from zeroinstall
import SafeException
2 from zeroinstall
.injector
import gpg
3 import tempfile
, os
, base64
, sys
, shutil
, signal
5 from rox
import tasks
, g
17 while '\n' in self
.data
:
18 command
, self
.data
= self
.data
.split('\n', 1)
21 def _io_callback(src
, cond
, blocker
):
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."""
30 def __init__(self
, stream
):
31 tasks
.Blocker
.__init
__(self
)
34 def add_task(self
, task
):
35 tasks
.Blocker
.add_task(self
, task
)
37 self
._tag
= gobject
.io_add_watch(self
._stream
, gobject
.IO_IN | gobject
.IO_HUP
,
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
)
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()
52 raise Exception("GPG failed with exit code %d" % status
)
54 for line
in stdout
.split('\n'):
55 line
= line
.split(':')
57 keys
.append([None, line
[9]])
58 elif line
[0] == 'fpr':
62 def check_signature(path
):
63 data
= file(path
).read()
64 xml_comment
= data
.rfind('\n<!-- Base64 Signature')
66 data_stream
, sigs
= gpg
.check_stream(file(path
))
68 data
= data
[:xml_comment
+ 1]
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()
75 return data
, sign_unsigned
, None
77 if isinstance(sig
, gpg
.ValidSig
):
78 return data
, sign_fn
, sig
.fingerprint
79 error
= "ERROR: No valid signatures found!\n"
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')
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
):
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()
122 tmp
= write_tmp(path
, data
)
124 child
= subprocess
.Popen(('gpg', '--default-key', key
,
125 '--detach-sign', '--status-fd', str(w
),
130 preexec_fn
= setup_child
,
131 stdin
= subprocess
.PIPE
)
136 input = InputBlocker(r
)
138 msg
= os
.read(r
, 100)
141 for command
in buffer:
142 if command
.startswith('[GNUPG:] NEED_PASSPHRASE '):
147 if resp
== g
.RESPONSE_OK
:
148 child
.stdin
.write(entry
.get_text() + '\n')
151 os
.kill(child
.pid
, signal
.SIGTERM
)
154 status
= child
.wait()
156 raise Exception("GPG failed with exit code %d" % status
)
158 # No generator finally blocks in Python 2.4...
161 if r
is not None: os
.close(r
)
162 if w
is not None: os
.close(w
)
163 if tmp
is not None: os
.unlink(tmp
)
169 encoded
= base64
.encodestring(file(tmp
).read())
171 sig
= "<!-- Base64 Signature\n" + encoded
+ "\n-->\n"
172 os
.rename(write_tmp(path
, data
+ sig
), path
)
174 if callback
: callback()
176 def export_key(dir, fingerprint
):
177 assert fingerprint
is not None
178 # Convert fingerprint to key ID
179 stream
= os
.popen('gpg --with-colons --list-keys %s' % fingerprint
)
183 parts
= line
.split(':')
184 if parts
[0] == 'pub':
186 raise Exception('Two key IDs returned from GPG!')
190 key_file
= os
.path
.join(dir, keyID
+ '.gpg')
191 if os
.path
.isfile(key_file
):
193 key_stream
= file(key_file
, 'w')
194 stream
= os
.popen("gpg -a --export '%s'" % fingerprint
)
195 shutil
.copyfileobj(stream
, key_stream
)