paul@6 | 1 | # -*- coding: iso-8859-1 -*- |
paul@6 | 2 | """ |
paul@6 | 3 | MoinMoin - MoinMessage library |
paul@6 | 4 | |
paul@16 | 5 | @copyright: 2012, 2013 by Paul Boddie <paul@boddie.org.uk> |
paul@6 | 6 | @license: GNU GPL (v2 or later), see COPYING.txt for details. |
paul@6 | 7 | """ |
paul@6 | 8 | |
paul@6 | 9 | from email import message_from_string |
paul@6 | 10 | from email.encoders import encode_noop |
paul@6 | 11 | from email.mime.multipart import MIMEMultipart |
paul@6 | 12 | from email.mime.application import MIMEApplication |
paul@6 | 13 | from email.mime.base import MIMEBase |
paul@20 | 14 | from email.utils import formatdate, parsedate |
paul@6 | 15 | from subprocess import Popen, PIPE |
paul@8 | 16 | from tempfile import mkstemp |
paul@12 | 17 | from urlparse import urlsplit |
paul@6 | 18 | import httplib |
paul@8 | 19 | import os |
paul@6 | 20 | |
paul@15 | 21 | def is_collection(message): |
paul@15 | 22 | return message.get("Update-Type") == "collection" |
paul@15 | 23 | |
paul@6 | 24 | class Message: |
paul@6 | 25 | |
paul@6 | 26 | "An update message." |
paul@6 | 27 | |
paul@15 | 28 | def __init__(self, text=None): |
paul@20 | 29 | self.date = None |
paul@6 | 30 | self.updates = [] |
paul@15 | 31 | if text: |
paul@15 | 32 | self.parse_text(text) |
paul@15 | 33 | |
paul@20 | 34 | def init_date(self, message): |
paul@20 | 35 | |
paul@20 | 36 | "Obtain the date of the given 'message'." |
paul@20 | 37 | |
paul@20 | 38 | if message.has_key("Date"): |
paul@20 | 39 | self.date = parsedate(message["Date"]) |
paul@20 | 40 | else: |
paul@20 | 41 | self.date = None |
paul@20 | 42 | |
paul@15 | 43 | def parse_text(self, text): |
paul@15 | 44 | |
paul@15 | 45 | "Parse the given 'text' as a message." |
paul@15 | 46 | |
paul@15 | 47 | self.handle_message(message_from_string(text)) |
paul@15 | 48 | |
paul@15 | 49 | def handle_message(self, message): |
paul@15 | 50 | |
paul@15 | 51 | "Handle the given 'message', recording the separate updates." |
paul@15 | 52 | |
paul@20 | 53 | self.init_date(message) |
paul@20 | 54 | |
paul@15 | 55 | # The message either consists of a collection of updates. |
paul@15 | 56 | |
paul@15 | 57 | if message.is_multipart() and is_collection(message): |
paul@15 | 58 | for part in message.get_payload(): |
paul@15 | 59 | self.updates.append(part) |
paul@15 | 60 | |
paul@15 | 61 | # Or the message is a single update. |
paul@15 | 62 | |
paul@15 | 63 | else: |
paul@15 | 64 | self.updates.append(message) |
paul@6 | 65 | |
paul@16 | 66 | def add_updates(self, parts): |
paul@13 | 67 | |
paul@13 | 68 | """ |
paul@16 | 69 | Add the given 'parts' to a message. |
paul@13 | 70 | """ |
paul@13 | 71 | |
paul@16 | 72 | for part in updates: |
paul@16 | 73 | self.add_update(part) |
paul@16 | 74 | |
paul@16 | 75 | def add_update(self, part): |
paul@16 | 76 | |
paul@16 | 77 | """ |
paul@16 | 78 | Add an update 'part' to a message. |
paul@16 | 79 | """ |
paul@16 | 80 | |
paul@16 | 81 | self.updates.append(part) |
paul@16 | 82 | |
paul@16 | 83 | def get_update(self, alternatives): |
paul@16 | 84 | |
paul@16 | 85 | """ |
paul@16 | 86 | Return a suitable multipart object containing the supplied |
paul@16 | 87 | 'alternatives'. |
paul@16 | 88 | """ |
paul@16 | 89 | |
paul@16 | 90 | part = MIMEMultipart() |
paul@16 | 91 | for alternative in alternatives: |
paul@16 | 92 | part.attach(alternative) |
paul@16 | 93 | return part |
paul@6 | 94 | |
paul@20 | 95 | def get_payload(self, timestamped=True): |
paul@13 | 96 | |
paul@20 | 97 | """ |
paul@20 | 98 | Get the multipart payload for the message. If the 'timestamped' |
paul@20 | 99 | parameter is omitted or set to a true value, the payload will be given a |
paul@20 | 100 | date header set to the current date and time that can be used to assess |
paul@20 | 101 | the validity of a message and to determine whether it has already been |
paul@20 | 102 | received by a recipient. |
paul@20 | 103 | """ |
paul@13 | 104 | |
paul@6 | 105 | if len(self.updates) == 1: |
paul@6 | 106 | message = self.updates[0] |
paul@6 | 107 | else: |
paul@6 | 108 | message = MIMEMultipart() |
paul@6 | 109 | message.add_header("Update-Type", "collection") |
paul@6 | 110 | for update in self.updates: |
paul@6 | 111 | message.attach(update) |
paul@6 | 112 | |
paul@20 | 113 | if timestamped: |
paul@20 | 114 | timestamp(message) |
paul@20 | 115 | self.init_date(message) |
paul@20 | 116 | |
paul@6 | 117 | return message |
paul@6 | 118 | |
paul@15 | 119 | class Mailbox: |
paul@15 | 120 | |
paul@15 | 121 | "A collection of messages within a multipart message." |
paul@15 | 122 | |
paul@15 | 123 | def __init__(self, text=None): |
paul@15 | 124 | self.messages = [] |
paul@15 | 125 | if text: |
paul@15 | 126 | self.parse_text(text) |
paul@15 | 127 | |
paul@15 | 128 | def parse_text(self, text): |
paul@15 | 129 | |
paul@15 | 130 | "Parse the given 'text' as a mailbox." |
paul@15 | 131 | |
paul@15 | 132 | message = message_from_string(text) |
paul@15 | 133 | |
paul@15 | 134 | if message.is_multipart(): |
paul@15 | 135 | for part in message.get_payload(): |
paul@15 | 136 | self.messages.append(part) |
paul@15 | 137 | else: |
paul@15 | 138 | self.messages.append(message) |
paul@15 | 139 | |
paul@15 | 140 | def add_message(self, message): |
paul@15 | 141 | |
paul@15 | 142 | "Add the given 'message' to the mailbox." |
paul@15 | 143 | |
paul@15 | 144 | self.messages.append(message) |
paul@15 | 145 | |
paul@15 | 146 | def get_payload(self): |
paul@15 | 147 | |
paul@15 | 148 | "Get the multipart payload for the mailbox." |
paul@15 | 149 | |
paul@15 | 150 | mailbox = MIMEMultipart() |
paul@15 | 151 | for message in self.messages: |
paul@15 | 152 | mailbox.attach(message) |
paul@15 | 153 | |
paul@15 | 154 | return mailbox |
paul@15 | 155 | |
paul@6 | 156 | class MoinMessageError(Exception): |
paul@6 | 157 | pass |
paul@6 | 158 | |
paul@8 | 159 | class GPG: |
paul@8 | 160 | |
paul@8 | 161 | "A wrapper around the gpg command using a particular configuration." |
paul@6 | 162 | |
paul@8 | 163 | def __init__(self, homedir=None): |
paul@8 | 164 | self.conf_args = [] |
paul@6 | 165 | |
paul@8 | 166 | if homedir: |
paul@8 | 167 | self.conf_args += ["--homedir", homedir] |
paul@8 | 168 | |
paul@8 | 169 | self.errors = None |
paul@6 | 170 | |
paul@8 | 171 | def run(self, args, text=None): |
paul@6 | 172 | |
paul@8 | 173 | """ |
paul@8 | 174 | Invoke gpg with the given 'args', supplying the given 'text' to the |
paul@8 | 175 | command directly or, if 'text' is omitted, using a file provided as part |
paul@8 | 176 | of the 'args' if appropriate. |
paul@6 | 177 | |
paul@8 | 178 | Failure to complete the operation will result in a MoinMessageError |
paul@8 | 179 | being raised. |
paul@8 | 180 | """ |
paul@8 | 181 | |
paul@8 | 182 | cmd = Popen(["gpg"] + self.conf_args + list(args), stdin=PIPE, stdout=PIPE, stderr=PIPE) |
paul@6 | 183 | |
paul@11 | 184 | try: |
paul@11 | 185 | # Attempt to write input to the command and to read output from the |
paul@11 | 186 | # command. |
paul@11 | 187 | |
paul@11 | 188 | try: |
paul@11 | 189 | if text: |
paul@11 | 190 | cmd.stdin.write(text) |
paul@11 | 191 | cmd.stdin.close() |
paul@6 | 192 | |
paul@11 | 193 | text = cmd.stdout.read() |
paul@11 | 194 | |
paul@11 | 195 | # I/O errors can indicate the failure of the command. |
paul@8 | 196 | |
paul@11 | 197 | except IOError: |
paul@11 | 198 | pass |
paul@11 | 199 | |
paul@11 | 200 | self.errors = cmd.stderr.read() |
paul@8 | 201 | |
paul@8 | 202 | # Test for a zero result. |
paul@6 | 203 | |
paul@8 | 204 | if not cmd.wait(): |
paul@8 | 205 | return text |
paul@8 | 206 | else: |
paul@10 | 207 | raise MoinMessageError, self.errors |
paul@8 | 208 | |
paul@8 | 209 | finally: |
paul@8 | 210 | cmd.stdout.close() |
paul@8 | 211 | cmd.stderr.close() |
paul@6 | 212 | |
paul@8 | 213 | def verifyMessage(self, signature, content): |
paul@8 | 214 | |
paul@8 | 215 | "Using the given 'signature', verify the given message 'content'." |
paul@6 | 216 | |
paul@8 | 217 | # Write the detached signature and content to files. |
paul@8 | 218 | |
paul@8 | 219 | signature_fd, signature_filename = mkstemp() |
paul@8 | 220 | content_fd, content_filename = mkstemp() |
paul@6 | 221 | |
paul@8 | 222 | try: |
paul@8 | 223 | signature_fp = os.fdopen(signature_fd, "w") |
paul@8 | 224 | content_fp = os.fdopen(content_fd, "w") |
paul@8 | 225 | try: |
paul@8 | 226 | signature_fp.write(signature) |
paul@8 | 227 | content_fp.write(content) |
paul@8 | 228 | finally: |
paul@8 | 229 | signature_fp.close() |
paul@8 | 230 | content_fp.close() |
paul@6 | 231 | |
paul@8 | 232 | # Verify the message text. |
paul@6 | 233 | |
paul@10 | 234 | text = self.run(["--status-fd", "1", "--verify", signature_filename, content_filename]) |
paul@10 | 235 | |
paul@10 | 236 | # Return the details of the signing key. |
paul@10 | 237 | |
paul@11 | 238 | identity = None |
paul@11 | 239 | fingerprint = None |
paul@11 | 240 | |
paul@10 | 241 | for line in text.split("\n"): |
paul@10 | 242 | try: |
paul@11 | 243 | prefix, msgtype, digest, details = line.strip().split(" ", 3) |
paul@10 | 244 | except ValueError: |
paul@10 | 245 | continue |
paul@10 | 246 | |
paul@10 | 247 | # Return the fingerprint and identity details. |
paul@10 | 248 | |
paul@10 | 249 | if msgtype == "GOODSIG": |
paul@11 | 250 | identity = details |
paul@11 | 251 | elif msgtype == "VALIDSIG": |
paul@11 | 252 | fingerprint = digest |
paul@11 | 253 | |
paul@11 | 254 | if identity and fingerprint: |
paul@11 | 255 | return fingerprint, identity |
paul@10 | 256 | |
paul@10 | 257 | return None |
paul@6 | 258 | |
paul@8 | 259 | finally: |
paul@8 | 260 | os.remove(signature_filename) |
paul@8 | 261 | os.remove(content_filename) |
paul@8 | 262 | |
paul@8 | 263 | def signMessage(self, message, keyid): |
paul@6 | 264 | |
paul@8 | 265 | """ |
paul@8 | 266 | Return a signed version of 'message' using the given 'keyid'. |
paul@8 | 267 | """ |
paul@6 | 268 | |
paul@8 | 269 | text = message.as_string() |
paul@8 | 270 | signature = self.run(["--armor", "-u", keyid, "--detach-sig"], text) |
paul@8 | 271 | |
paul@8 | 272 | # Make the container for the message. |
paul@8 | 273 | |
paul@8 | 274 | signed_message = MIMEMultipart("signed", protocol="application/pgp-signature") |
paul@8 | 275 | signed_message.attach(message) |
paul@6 | 276 | |
paul@8 | 277 | signature_part = MIMEBase("application", "pgp-signature") |
paul@8 | 278 | signature_part.set_payload(signature) |
paul@8 | 279 | signed_message.attach(signature_part) |
paul@8 | 280 | |
paul@8 | 281 | return signed_message |
paul@8 | 282 | |
paul@8 | 283 | def decryptMessage(self, message): |
paul@6 | 284 | |
paul@8 | 285 | "Return a decrypted version of 'message'." |
paul@8 | 286 | |
paul@8 | 287 | return self.run(["--decrypt"], message) |
paul@6 | 288 | |
paul@8 | 289 | def encryptMessage(self, message, keyid): |
paul@6 | 290 | |
paul@8 | 291 | """ |
paul@8 | 292 | Return an encrypted version of 'message' using the given 'keyid'. |
paul@8 | 293 | """ |
paul@6 | 294 | |
paul@8 | 295 | text = message.as_string() |
paul@8 | 296 | encrypted = self.run(["--armor", "-r", keyid, "--encrypt", "--trust-model", "always"], text) |
paul@8 | 297 | |
paul@8 | 298 | # Make the container for the message. |
paul@8 | 299 | |
paul@8 | 300 | encrypted_message = MIMEMultipart("encrypted", protocol="application/pgp-encrypted") |
paul@8 | 301 | |
paul@8 | 302 | # For encrypted content, add the declaration and content. |
paul@6 | 303 | |
paul@8 | 304 | declaration = MIMEBase("application", "pgp-encrypted") |
paul@8 | 305 | declaration.set_payload("Version: 1") |
paul@8 | 306 | encrypted_message.attach(declaration) |
paul@6 | 307 | |
paul@8 | 308 | content = MIMEApplication(encrypted, "octet-stream", encode_noop) |
paul@8 | 309 | encrypted_message.attach(content) |
paul@6 | 310 | |
paul@8 | 311 | return encrypted_message |
paul@8 | 312 | |
paul@8 | 313 | # Communications functions. |
paul@6 | 314 | |
paul@20 | 315 | def timestamp(message): |
paul@20 | 316 | |
paul@20 | 317 | """ |
paul@20 | 318 | Timestamp the given 'message' so that its validity can be assessed by the |
paul@20 | 319 | recipient. |
paul@20 | 320 | """ |
paul@20 | 321 | |
paul@20 | 322 | datestr = formatdate() |
paul@20 | 323 | |
paul@20 | 324 | if not message.has_key("Date"): |
paul@20 | 325 | message.add_header("Date", datestr) |
paul@20 | 326 | else: |
paul@20 | 327 | message["Date"] = datestr |
paul@20 | 328 | |
paul@12 | 329 | def sendMessage(message, url): |
paul@6 | 330 | |
paul@12 | 331 | "Send 'message' to the given 'url." |
paul@6 | 332 | |
paul@12 | 333 | scheme, host, port, path = parseURL(url) |
paul@6 | 334 | text = message.as_string() |
paul@6 | 335 | |
paul@12 | 336 | if scheme == "http": |
paul@12 | 337 | cls = httplib.HTTPConnection |
paul@12 | 338 | elif scheme == "https": |
paul@12 | 339 | cls = httplib.HTTPSConnection |
paul@12 | 340 | else: |
paul@12 | 341 | raise MoinMessageError, "Communications protocol not supported: %s" % scheme |
paul@12 | 342 | |
paul@12 | 343 | req = cls(host, port) |
paul@12 | 344 | req.request("PUT", path, text) |
paul@6 | 345 | resp = req.getresponse() |
paul@6 | 346 | return resp.read() |
paul@6 | 347 | |
paul@12 | 348 | def parseURL(url): |
paul@12 | 349 | |
paul@12 | 350 | "Return the scheme, host, port and path for the given 'url'." |
paul@12 | 351 | |
paul@12 | 352 | scheme, host_port, path, query, fragment = urlsplit(url) |
paul@12 | 353 | host_port = host_port.split(":") |
paul@12 | 354 | |
paul@12 | 355 | if query: |
paul@12 | 356 | path += "?" + query |
paul@12 | 357 | |
paul@12 | 358 | if len(host_port) > 1: |
paul@12 | 359 | host = host_port[0] |
paul@12 | 360 | port = int(host_port[1]) |
paul@12 | 361 | else: |
paul@12 | 362 | host = host_port[0] |
paul@12 | 363 | port = 80 |
paul@12 | 364 | |
paul@12 | 365 | return scheme, host, port, path |
paul@12 | 366 | |
paul@6 | 367 | # vim: tabstop=4 expandtab shiftwidth=4 |