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