paul@6 | 1 | # -*- coding: iso-8859-1 -*- |
paul@6 | 2 | """ |
paul@6 | 3 | MoinMoin - MoinMessage library |
paul@6 | 4 | |
paul@98 | 5 | @copyright: 2012, 2013, 2014 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@105 | 11 | from email.generator import Generator |
paul@6 | 12 | from email.mime.multipart import MIMEMultipart |
paul@6 | 13 | from email.mime.application import MIMEApplication |
paul@6 | 14 | from email.mime.base import MIMEBase |
paul@109 | 15 | from email.mime.text import MIMEText |
paul@88 | 16 | from email.parser import Parser |
paul@103 | 17 | from email.utils import formatdate |
paul@109 | 18 | from itertools import islice |
paul@6 | 19 | from subprocess import Popen, PIPE |
paul@8 | 20 | from tempfile import mkstemp |
paul@12 | 21 | from urlparse import urlsplit |
paul@103 | 22 | from DateSupport import getDateTimeFromRFC2822 |
paul@6 | 23 | import httplib |
paul@8 | 24 | import os |
paul@6 | 25 | |
paul@105 | 26 | try: |
paul@105 | 27 | from cStringIO import StringIO |
paul@105 | 28 | except ImportError: |
paul@105 | 29 | from StringIO import StringIO |
paul@105 | 30 | |
paul@109 | 31 | # Message inspection functions. |
paul@109 | 32 | |
paul@15 | 33 | def is_collection(message): |
paul@15 | 34 | return message.get("Update-Type") == "collection" |
paul@15 | 35 | |
paul@29 | 36 | def to_replace(message): |
paul@29 | 37 | return message.get("Update-Action") == "replace" |
paul@29 | 38 | |
paul@29 | 39 | def to_store(message): |
paul@29 | 40 | return message.get("Update-Action") == "store" |
paul@29 | 41 | |
paul@85 | 42 | def get_update_action(message): |
paul@85 | 43 | return message.get("Update-Action", "update") |
paul@85 | 44 | |
paul@109 | 45 | # Core abstractions. |
paul@109 | 46 | |
paul@6 | 47 | class Message: |
paul@6 | 48 | |
paul@6 | 49 | "An update message." |
paul@6 | 50 | |
paul@15 | 51 | def __init__(self, text=None): |
paul@20 | 52 | self.date = None |
paul@6 | 53 | self.updates = [] |
paul@15 | 54 | if text: |
paul@15 | 55 | self.parse_text(text) |
paul@15 | 56 | |
paul@20 | 57 | def init_date(self, message): |
paul@20 | 58 | |
paul@20 | 59 | "Obtain the date of the given 'message'." |
paul@20 | 60 | |
paul@20 | 61 | if message.has_key("Date"): |
paul@103 | 62 | self.date = getDateTimeFromRFC2822(message["Date"]) |
paul@20 | 63 | else: |
paul@20 | 64 | self.date = None |
paul@20 | 65 | |
paul@15 | 66 | def parse_text(self, text): |
paul@15 | 67 | |
paul@15 | 68 | "Parse the given 'text' as a message." |
paul@15 | 69 | |
paul@15 | 70 | self.handle_message(message_from_string(text)) |
paul@15 | 71 | |
paul@15 | 72 | def handle_message(self, message): |
paul@15 | 73 | |
paul@15 | 74 | "Handle the given 'message', recording the separate updates." |
paul@15 | 75 | |
paul@20 | 76 | self.init_date(message) |
paul@20 | 77 | |
paul@15 | 78 | # The message either consists of a collection of updates. |
paul@15 | 79 | |
paul@15 | 80 | if message.is_multipart() and is_collection(message): |
paul@15 | 81 | for part in message.get_payload(): |
paul@15 | 82 | self.updates.append(part) |
paul@15 | 83 | |
paul@15 | 84 | # Or the message is a single update. |
paul@15 | 85 | |
paul@15 | 86 | else: |
paul@15 | 87 | self.updates.append(message) |
paul@6 | 88 | |
paul@16 | 89 | def add_updates(self, parts): |
paul@13 | 90 | |
paul@13 | 91 | """ |
paul@16 | 92 | Add the given 'parts' to a message. |
paul@13 | 93 | """ |
paul@13 | 94 | |
paul@16 | 95 | for part in updates: |
paul@16 | 96 | self.add_update(part) |
paul@16 | 97 | |
paul@16 | 98 | def add_update(self, part): |
paul@16 | 99 | |
paul@16 | 100 | """ |
paul@16 | 101 | Add an update 'part' to a message. |
paul@16 | 102 | """ |
paul@16 | 103 | |
paul@16 | 104 | self.updates.append(part) |
paul@16 | 105 | |
paul@16 | 106 | def get_update(self, alternatives): |
paul@16 | 107 | |
paul@16 | 108 | """ |
paul@16 | 109 | Return a suitable multipart object containing the supplied |
paul@16 | 110 | 'alternatives'. |
paul@16 | 111 | """ |
paul@16 | 112 | |
paul@109 | 113 | part = MIMEMultipart("alternative") |
paul@16 | 114 | for alternative in alternatives: |
paul@16 | 115 | part.attach(alternative) |
paul@16 | 116 | return part |
paul@6 | 117 | |
paul@115 | 118 | def get_payload(self, subtype="mixed", timestamped=True): |
paul@13 | 119 | |
paul@20 | 120 | """ |
paul@20 | 121 | Get the multipart payload for the message. If the 'timestamped' |
paul@20 | 122 | parameter is omitted or set to a true value, the payload will be given a |
paul@20 | 123 | date header set to the current date and time that can be used to assess |
paul@20 | 124 | the validity of a message and to determine whether it has already been |
paul@20 | 125 | received by a recipient. |
paul@20 | 126 | """ |
paul@13 | 127 | |
paul@6 | 128 | if len(self.updates) == 1: |
paul@6 | 129 | message = self.updates[0] |
paul@6 | 130 | else: |
paul@115 | 131 | message = MIMEMultipart(subtype) |
paul@6 | 132 | message.add_header("Update-Type", "collection") |
paul@6 | 133 | for update in self.updates: |
paul@6 | 134 | message.attach(update) |
paul@6 | 135 | |
paul@20 | 136 | if timestamped: |
paul@20 | 137 | timestamp(message) |
paul@20 | 138 | self.init_date(message) |
paul@20 | 139 | |
paul@6 | 140 | return message |
paul@6 | 141 | |
paul@6 | 142 | class MoinMessageError(Exception): |
paul@6 | 143 | pass |
paul@6 | 144 | |
paul@33 | 145 | class MoinMessageDecodingError(Exception): |
paul@33 | 146 | pass |
paul@33 | 147 | |
paul@33 | 148 | class MoinMessageMissingPart(MoinMessageDecodingError): |
paul@33 | 149 | pass |
paul@33 | 150 | |
paul@33 | 151 | class MoinMessageBadContent(MoinMessageDecodingError): |
paul@33 | 152 | pass |
paul@33 | 153 | |
paul@8 | 154 | class GPG: |
paul@8 | 155 | |
paul@8 | 156 | "A wrapper around the gpg command using a particular configuration." |
paul@6 | 157 | |
paul@8 | 158 | def __init__(self, homedir=None): |
paul@8 | 159 | self.conf_args = [] |
paul@6 | 160 | |
paul@8 | 161 | if homedir: |
paul@8 | 162 | self.conf_args += ["--homedir", homedir] |
paul@8 | 163 | |
paul@8 | 164 | self.errors = None |
paul@6 | 165 | |
paul@8 | 166 | def run(self, args, text=None): |
paul@6 | 167 | |
paul@8 | 168 | """ |
paul@8 | 169 | Invoke gpg with the given 'args', supplying the given 'text' to the |
paul@8 | 170 | command directly or, if 'text' is omitted, using a file provided as part |
paul@8 | 171 | of the 'args' if appropriate. |
paul@6 | 172 | |
paul@8 | 173 | Failure to complete the operation will result in a MoinMessageError |
paul@8 | 174 | being raised. |
paul@8 | 175 | """ |
paul@8 | 176 | |
paul@8 | 177 | cmd = Popen(["gpg"] + self.conf_args + list(args), stdin=PIPE, stdout=PIPE, stderr=PIPE) |
paul@6 | 178 | |
paul@58 | 179 | # Attempt to write input to the command and to read output from the |
paul@58 | 180 | # command. |
paul@11 | 181 | |
paul@58 | 182 | text, self.errors = cmd.communicate(text) |
paul@8 | 183 | |
paul@58 | 184 | # Test for a zero result. |
paul@6 | 185 | |
paul@58 | 186 | if not cmd.returncode: |
paul@58 | 187 | return text |
paul@58 | 188 | else: |
paul@58 | 189 | raise MoinMessageError, self.errors |
paul@6 | 190 | |
paul@33 | 191 | def verifyMessageText(self, signature, content): |
paul@8 | 192 | |
paul@8 | 193 | "Using the given 'signature', verify the given message 'content'." |
paul@6 | 194 | |
paul@8 | 195 | # Write the detached signature and content to files. |
paul@8 | 196 | |
paul@8 | 197 | signature_fd, signature_filename = mkstemp() |
paul@8 | 198 | content_fd, content_filename = mkstemp() |
paul@6 | 199 | |
paul@8 | 200 | try: |
paul@8 | 201 | signature_fp = os.fdopen(signature_fd, "w") |
paul@8 | 202 | content_fp = os.fdopen(content_fd, "w") |
paul@8 | 203 | try: |
paul@8 | 204 | signature_fp.write(signature) |
paul@8 | 205 | content_fp.write(content) |
paul@8 | 206 | finally: |
paul@8 | 207 | signature_fp.close() |
paul@8 | 208 | content_fp.close() |
paul@6 | 209 | |
paul@8 | 210 | # Verify the message text. |
paul@6 | 211 | |
paul@10 | 212 | text = self.run(["--status-fd", "1", "--verify", signature_filename, content_filename]) |
paul@10 | 213 | |
paul@10 | 214 | # Return the details of the signing key. |
paul@10 | 215 | |
paul@11 | 216 | identity = None |
paul@11 | 217 | fingerprint = None |
paul@11 | 218 | |
paul@10 | 219 | for line in text.split("\n"): |
paul@10 | 220 | try: |
paul@11 | 221 | prefix, msgtype, digest, details = line.strip().split(" ", 3) |
paul@10 | 222 | except ValueError: |
paul@10 | 223 | continue |
paul@10 | 224 | |
paul@10 | 225 | # Return the fingerprint and identity details. |
paul@10 | 226 | |
paul@10 | 227 | if msgtype == "GOODSIG": |
paul@11 | 228 | identity = details |
paul@11 | 229 | elif msgtype == "VALIDSIG": |
paul@11 | 230 | fingerprint = digest |
paul@11 | 231 | |
paul@11 | 232 | if identity and fingerprint: |
paul@11 | 233 | return fingerprint, identity |
paul@10 | 234 | |
paul@10 | 235 | return None |
paul@6 | 236 | |
paul@8 | 237 | finally: |
paul@8 | 238 | os.remove(signature_filename) |
paul@8 | 239 | os.remove(content_filename) |
paul@8 | 240 | |
paul@33 | 241 | def verifyMessage(self, message): |
paul@33 | 242 | |
paul@33 | 243 | """ |
paul@33 | 244 | Verify the given RFC 3156 'message', returning a tuple of the form |
paul@33 | 245 | (fingerprint, identity, content). |
paul@33 | 246 | """ |
paul@33 | 247 | |
paul@36 | 248 | content, signature = getContentAndSignature(message) |
paul@33 | 249 | |
paul@33 | 250 | # Verify the message format. |
paul@33 | 251 | |
paul@33 | 252 | if signature.get_content_type() != "application/pgp-signature": |
paul@33 | 253 | raise MoinMessageBadContent |
paul@33 | 254 | |
paul@33 | 255 | # Verify the message. |
paul@33 | 256 | |
paul@105 | 257 | fingerprint, identity = self.verifyMessageText(signature.get_payload(decode=True), as_string(content)) |
paul@105 | 258 | return fingerprint, identity, content |
paul@33 | 259 | |
paul@8 | 260 | def signMessage(self, message, keyid): |
paul@6 | 261 | |
paul@8 | 262 | """ |
paul@8 | 263 | Return a signed version of 'message' using the given 'keyid'. |
paul@8 | 264 | """ |
paul@6 | 265 | |
paul@88 | 266 | # Sign the container's representation. |
paul@88 | 267 | |
paul@105 | 268 | signature = self.run(["--armor", "-u", keyid, "--detach-sig"], as_string(message)) |
paul@8 | 269 | |
paul@8 | 270 | # Make the container for the message. |
paul@8 | 271 | |
paul@8 | 272 | signed_message = MIMEMultipart("signed", protocol="application/pgp-signature") |
paul@105 | 273 | signed_message.attach(message) |
paul@6 | 274 | |
paul@8 | 275 | signature_part = MIMEBase("application", "pgp-signature") |
paul@8 | 276 | signature_part.set_payload(signature) |
paul@8 | 277 | signed_message.attach(signature_part) |
paul@8 | 278 | |
paul@8 | 279 | return signed_message |
paul@8 | 280 | |
paul@33 | 281 | def decryptMessageText(self, message): |
paul@6 | 282 | |
paul@8 | 283 | "Return a decrypted version of 'message'." |
paul@8 | 284 | |
paul@8 | 285 | return self.run(["--decrypt"], message) |
paul@6 | 286 | |
paul@33 | 287 | def decryptMessage(self, message): |
paul@33 | 288 | |
paul@33 | 289 | """ |
paul@33 | 290 | Decrypt the given RFC 3156 'message', returning the message text. |
paul@33 | 291 | """ |
paul@33 | 292 | |
paul@33 | 293 | try: |
paul@33 | 294 | declaration, content = message.get_payload() |
paul@33 | 295 | except ValueError: |
paul@33 | 296 | raise MoinMessageMissingPart |
paul@33 | 297 | |
paul@33 | 298 | # Verify the message format. |
paul@33 | 299 | |
paul@33 | 300 | if content.get_content_type() != "application/octet-stream": |
paul@33 | 301 | raise MoinMessageBadContent |
paul@33 | 302 | |
paul@33 | 303 | # Return the decrypted message text. |
paul@33 | 304 | |
paul@92 | 305 | return self.decryptMessageText(content.get_payload(decode=True)) |
paul@33 | 306 | |
paul@8 | 307 | def encryptMessage(self, message, keyid): |
paul@6 | 308 | |
paul@8 | 309 | """ |
paul@8 | 310 | Return an encrypted version of 'message' using the given 'keyid'. |
paul@8 | 311 | """ |
paul@6 | 312 | |
paul@105 | 313 | text = as_string(message) |
paul@8 | 314 | encrypted = self.run(["--armor", "-r", keyid, "--encrypt", "--trust-model", "always"], text) |
paul@8 | 315 | |
paul@8 | 316 | # Make the container for the message. |
paul@8 | 317 | |
paul@8 | 318 | encrypted_message = MIMEMultipart("encrypted", protocol="application/pgp-encrypted") |
paul@8 | 319 | |
paul@8 | 320 | # For encrypted content, add the declaration and content. |
paul@6 | 321 | |
paul@8 | 322 | declaration = MIMEBase("application", "pgp-encrypted") |
paul@8 | 323 | declaration.set_payload("Version: 1") |
paul@8 | 324 | encrypted_message.attach(declaration) |
paul@6 | 325 | |
paul@8 | 326 | content = MIMEApplication(encrypted, "octet-stream", encode_noop) |
paul@8 | 327 | encrypted_message.attach(content) |
paul@6 | 328 | |
paul@8 | 329 | return encrypted_message |
paul@8 | 330 | |
paul@115 | 331 | def importKeys(self, text): |
paul@115 | 332 | |
paul@115 | 333 | """ |
paul@115 | 334 | Import the keys provided by the given 'text'. |
paul@115 | 335 | """ |
paul@115 | 336 | |
paul@115 | 337 | self.run(["--import"], text) |
paul@115 | 338 | |
paul@75 | 339 | def exportKey(self, keyid): |
paul@75 | 340 | |
paul@75 | 341 | """ |
paul@75 | 342 | Return the "armoured" public key text for 'keyid' as a message part with |
paul@75 | 343 | a suitable media type. |
paul@75 | 344 | See: https://tools.ietf.org/html/rfc3156#section-7 |
paul@75 | 345 | """ |
paul@75 | 346 | |
paul@75 | 347 | text = self.run(["--armor", "--export", keyid]) |
paul@75 | 348 | return MIMEApplication(text, "pgp-keys", encode_noop) |
paul@75 | 349 | |
paul@78 | 350 | def listKeys(self, keyid=None): |
paul@78 | 351 | |
paul@78 | 352 | """ |
paul@78 | 353 | Return a list of key details for keys on the keychain, selecting only |
paul@78 | 354 | one specific key if 'keyid' is specified. |
paul@78 | 355 | """ |
paul@78 | 356 | |
paul@78 | 357 | text = self.run(["--list-keys", "--with-colons", "--with-fingerprint"] + |
paul@78 | 358 | (keyid and ["0x%s" % keyid] or [])) |
paul@78 | 359 | return self._getKeysFromResult(text) |
paul@78 | 360 | |
paul@78 | 361 | def listSignatures(self, keyid=None): |
paul@78 | 362 | |
paul@78 | 363 | """ |
paul@78 | 364 | Return a list of key and signature details for keys on the keychain, |
paul@78 | 365 | selecting only one specific key if 'keyid' is specified. |
paul@78 | 366 | """ |
paul@78 | 367 | |
paul@78 | 368 | text = self.run(["--list-sigs", "--with-colons", "--with-fingerprint"] + |
paul@78 | 369 | (keyid and ["0x%s" % keyid] or [])) |
paul@78 | 370 | return self._getKeysFromResult(text) |
paul@78 | 371 | |
paul@77 | 372 | def getKeysFromMessagePart(self, part): |
paul@77 | 373 | |
paul@77 | 374 | """ |
paul@77 | 375 | Process an application/pgp-keys message 'part', returning a list of |
paul@77 | 376 | key details. |
paul@77 | 377 | """ |
paul@77 | 378 | |
paul@93 | 379 | return self.getKeysFromString(part.get_payload(decode=True)) |
paul@77 | 380 | |
paul@77 | 381 | def getKeysFromString(self, s): |
paul@77 | 382 | |
paul@78 | 383 | """ |
paul@78 | 384 | Return a list of key details extracted from the given key block string |
paul@79 | 385 | 's'. Signature information is also included through the use of the gpg |
paul@79 | 386 | verbose option. |
paul@78 | 387 | """ |
paul@77 | 388 | |
paul@79 | 389 | text = self.run(["--with-colons", "--with-fingerprint", "-v"], s) |
paul@78 | 390 | return self._getKeysFromResult(text) |
paul@78 | 391 | |
paul@78 | 392 | def _getKeysFromResult(self, text): |
paul@78 | 393 | |
paul@78 | 394 | """ |
paul@78 | 395 | Return a list of key details extracted from the given command result |
paul@78 | 396 | 'text'. |
paul@78 | 397 | """ |
paul@78 | 398 | |
paul@77 | 399 | keys = [] |
paul@77 | 400 | for line in text.split("\n"): |
paul@77 | 401 | try: |
paul@77 | 402 | recordtype, trust, keylength, algorithm, keyid, cdate, expdate, serial, ownertrust, _rest = line.split(":", 9) |
paul@77 | 403 | except ValueError: |
paul@78 | 404 | continue |
paul@77 | 405 | |
paul@77 | 406 | if recordtype == "pub": |
paul@77 | 407 | userid, _rest = _rest.split(":", 1) |
paul@77 | 408 | keys.append({ |
paul@77 | 409 | "type" : recordtype, "trust" : trust, "keylength" : keylength, |
paul@77 | 410 | "algorithm" : algorithm, "keyid" : keyid, "cdate" : cdate, |
paul@77 | 411 | "expdate" : expdate, "userid" : userid, "ownertrust" : ownertrust, |
paul@78 | 412 | "fingerprint" : None, "subkeys" : [], "signatures" : [] |
paul@77 | 413 | }) |
paul@77 | 414 | elif recordtype == "sub" and keys: |
paul@77 | 415 | keys[-1]["subkeys"].append({ |
paul@77 | 416 | "trust" : trust, "keylength" : keylength, "algorithm" : algorithm, |
paul@77 | 417 | "keyid" : keyid, "cdate" : cdate, "expdate" : expdate, |
paul@77 | 418 | "ownertrust" : ownertrust |
paul@77 | 419 | }) |
paul@77 | 420 | elif recordtype == "fpr" and keys: |
paul@77 | 421 | fingerprint, _rest = _rest.split(":", 1) |
paul@77 | 422 | keys[-1]["fingerprint"] = fingerprint |
paul@78 | 423 | elif recordtype == "sig" and keys: |
paul@78 | 424 | userid, _rest = _rest.split(":", 1) |
paul@78 | 425 | keys[-1]["signatures"].append({ |
paul@78 | 426 | "keyid" : keyid, "cdate" : cdate, "expdate" : expdate, |
paul@78 | 427 | "userid" : userid |
paul@78 | 428 | }) |
paul@77 | 429 | |
paul@77 | 430 | return keys |
paul@77 | 431 | |
paul@105 | 432 | # Message serialisation functions, working around email module problems. |
paul@105 | 433 | |
paul@105 | 434 | def as_string(message): |
paul@105 | 435 | |
paul@105 | 436 | """ |
paul@105 | 437 | Return the string representation of 'message', attempting to preserve the |
paul@105 | 438 | precise original formatting. |
paul@105 | 439 | """ |
paul@105 | 440 | |
paul@105 | 441 | out = StringIO() |
paul@105 | 442 | generator = Generator(out, False, 0) # disable reformatting measures |
paul@105 | 443 | generator.flatten(message) |
paul@105 | 444 | return out.getvalue() |
paul@105 | 445 | |
paul@33 | 446 | # Message decoding functions. |
paul@33 | 447 | |
paul@33 | 448 | # Detect PGP/GPG-encoded payloads. |
paul@33 | 449 | # See: http://tools.ietf.org/html/rfc3156 |
paul@33 | 450 | |
paul@33 | 451 | def is_signed(message): |
paul@33 | 452 | mimetype = message.get_content_type() |
paul@33 | 453 | encoding = message.get_content_charset() |
paul@33 | 454 | |
paul@33 | 455 | return mimetype == "multipart/signed" and \ |
paul@33 | 456 | message.get_param("protocol") == "application/pgp-signature" |
paul@33 | 457 | |
paul@33 | 458 | def is_encrypted(message): |
paul@33 | 459 | mimetype = message.get_content_type() |
paul@33 | 460 | encoding = message.get_content_charset() |
paul@33 | 461 | |
paul@33 | 462 | return mimetype == "multipart/encrypted" and \ |
paul@33 | 463 | message.get_param("protocol") == "application/pgp-encrypted" |
paul@33 | 464 | |
paul@36 | 465 | def getContentAndSignature(message): |
paul@36 | 466 | |
paul@36 | 467 | """ |
paul@36 | 468 | Return the content and signature parts of the given RFC 3156 'message'. |
paul@36 | 469 | |
paul@36 | 470 | NOTE: RFC 3156 states that signed messages should employ a detached |
paul@36 | 471 | NOTE: signature but then shows "BEGIN PGP MESSAGE" for signatures |
paul@36 | 472 | NOTE: instead of "BEGIN PGP SIGNATURE". |
paul@36 | 473 | NOTE: The "micalg" parameter is currently not supported. |
paul@36 | 474 | """ |
paul@36 | 475 | |
paul@36 | 476 | try: |
paul@36 | 477 | content, signature = message.get_payload() |
paul@36 | 478 | return content, signature |
paul@36 | 479 | except ValueError: |
paul@36 | 480 | raise MoinMessageMissingPart |
paul@36 | 481 | |
paul@8 | 482 | # Communications functions. |
paul@6 | 483 | |
paul@20 | 484 | def timestamp(message): |
paul@20 | 485 | |
paul@20 | 486 | """ |
paul@20 | 487 | Timestamp the given 'message' so that its validity can be assessed by the |
paul@20 | 488 | recipient. |
paul@20 | 489 | """ |
paul@20 | 490 | |
paul@20 | 491 | datestr = formatdate() |
paul@20 | 492 | |
paul@20 | 493 | if not message.has_key("Date"): |
paul@20 | 494 | message.add_header("Date", datestr) |
paul@20 | 495 | else: |
paul@20 | 496 | message["Date"] = datestr |
paul@20 | 497 | |
paul@92 | 498 | def _getConnection(scheme): |
paul@92 | 499 | |
paul@92 | 500 | "Return the connection class for the given 'scheme'." |
paul@92 | 501 | |
paul@92 | 502 | if scheme == "http": |
paul@92 | 503 | return httplib.HTTPConnection |
paul@92 | 504 | elif scheme == "https": |
paul@92 | 505 | return httplib.HTTPSConnection |
paul@92 | 506 | else: |
paul@92 | 507 | raise MoinMessageError, "Communications protocol not supported: %s" % scheme |
paul@92 | 508 | |
paul@108 | 509 | def sendMessageOpener(message, url, method="PUT"): |
paul@6 | 510 | |
paul@44 | 511 | """ |
paul@44 | 512 | Send 'message' to the given 'url' using the given 'method' (using PUT as the |
paul@44 | 513 | default if omitted). |
paul@44 | 514 | """ |
paul@6 | 515 | |
paul@12 | 516 | scheme, host, port, path = parseURL(url) |
paul@105 | 517 | text = as_string(message) |
paul@6 | 518 | |
paul@92 | 519 | req = _getConnection(scheme)(host, port) |
paul@44 | 520 | req.request(method, path, text) |
paul@6 | 521 | resp = req.getresponse() |
paul@39 | 522 | |
paul@39 | 523 | if resp.status >= 400: |
paul@92 | 524 | raise MoinMessageError, "Message sending failed (%s): %s" % (resp.status, resp.read()) |
paul@92 | 525 | |
paul@92 | 526 | return resp |
paul@92 | 527 | |
paul@92 | 528 | def sendMessage(message, url, method="PUT"): |
paul@39 | 529 | |
paul@92 | 530 | """ |
paul@92 | 531 | Send 'message' to the given 'url' using the given 'method' (using PUT as the |
paul@92 | 532 | default if omitted). |
paul@92 | 533 | """ |
paul@92 | 534 | |
paul@108 | 535 | resp = sendMessageOpener(message, url, method) |
paul@6 | 536 | return resp.read() |
paul@6 | 537 | |
paul@12 | 538 | def parseURL(url): |
paul@12 | 539 | |
paul@12 | 540 | "Return the scheme, host, port and path for the given 'url'." |
paul@12 | 541 | |
paul@12 | 542 | scheme, host_port, path, query, fragment = urlsplit(url) |
paul@12 | 543 | host_port = host_port.split(":") |
paul@12 | 544 | |
paul@12 | 545 | if query: |
paul@12 | 546 | path += "?" + query |
paul@12 | 547 | |
paul@12 | 548 | if len(host_port) > 1: |
paul@12 | 549 | host = host_port[0] |
paul@12 | 550 | port = int(host_port[1]) |
paul@12 | 551 | else: |
paul@12 | 552 | host = host_port[0] |
paul@12 | 553 | port = 80 |
paul@12 | 554 | |
paul@12 | 555 | return scheme, host, port, path |
paul@12 | 556 | |
paul@109 | 557 | # Message handling. |
paul@109 | 558 | |
paul@109 | 559 | class MessageInterface: |
paul@109 | 560 | |
paul@109 | 561 | "A command-based interface to a message store, inspired by RFC 1939 (POP3)." |
paul@109 | 562 | |
paul@109 | 563 | def __init__(self, store): |
paul@109 | 564 | self.store = store |
paul@109 | 565 | |
paul@109 | 566 | def execute(self, commands): |
paul@109 | 567 | |
paul@109 | 568 | """ |
paul@109 | 569 | Access messages according to the given 'commands' script, acting on the |
paul@109 | 570 | store provided during initialisation and returning a message object |
paul@109 | 571 | containing the results. |
paul@109 | 572 | """ |
paul@109 | 573 | |
paul@109 | 574 | # Build a container for the responses. |
paul@109 | 575 | |
paul@109 | 576 | message = Message() |
paul@109 | 577 | |
paul@109 | 578 | # Process each command. |
paul@109 | 579 | |
paul@109 | 580 | for command in commands.split("\n"): |
paul@109 | 581 | command = command.strip() |
paul@109 | 582 | |
paul@109 | 583 | # Get the command and arguments. |
paul@109 | 584 | |
paul@109 | 585 | command_parts = command.split(None, 1) |
paul@109 | 586 | cmd = command_parts[0] |
paul@109 | 587 | |
paul@109 | 588 | try: |
paul@109 | 589 | if cmd in self.commands: |
paul@109 | 590 | getattr(self, cmd)(command_parts, message) |
paul@109 | 591 | else: |
paul@109 | 592 | self.add_result(cmd, command, "ERR", message) |
paul@109 | 593 | except Exception, exc: |
paul@109 | 594 | self.add_result(cmd, "\n".join([command, str(exc)]), "ERR", message) |
paul@109 | 595 | |
paul@109 | 596 | return message |
paul@109 | 597 | |
paul@109 | 598 | def get_count(self, command_parts): |
paul@109 | 599 | |
paul@109 | 600 | # Select all messages by default. |
paul@109 | 601 | |
paul@109 | 602 | count = None |
paul@109 | 603 | |
paul@109 | 604 | if len(command_parts) > 1: |
paul@109 | 605 | count = int(command_parts[1]) |
paul@109 | 606 | |
paul@109 | 607 | return count |
paul@109 | 608 | |
paul@109 | 609 | def add_result(self, cmd, result, status, message): |
paul@109 | 610 | part = MIMEText(result, "x-moinmessage-fetch-result") |
paul@109 | 611 | part["Request-Type"] = cmd |
paul@109 | 612 | part["Request-Status"] = status |
paul@109 | 613 | message.add_update(part) |
paul@109 | 614 | |
paul@109 | 615 | def add_messages(self, resources, message): |
paul@109 | 616 | container = Message() |
paul@109 | 617 | |
paul@109 | 618 | for message_text in resources: |
paul@109 | 619 | message_item = Parser().parsestr(message_text) |
paul@109 | 620 | container.add_update(message_item) |
paul@109 | 621 | |
paul@109 | 622 | # Convert the container to a proper multipart section. |
paul@109 | 623 | |
paul@109 | 624 | message.add_update(container.get_payload()) |
paul@109 | 625 | |
paul@109 | 626 | def STAT(self, command_parts, message): |
paul@109 | 627 | |
paul@109 | 628 | # A request to count the messages is returned in a part. |
paul@109 | 629 | |
paul@109 | 630 | self.add_result("STAT", str(len(self.store)), "OK", message) |
paul@109 | 631 | |
paul@109 | 632 | def RETR(self, command_parts, message): |
paul@109 | 633 | |
paul@109 | 634 | # A request for specific messages returns each message |
paul@109 | 635 | # in its own part within a collection part. |
paul@109 | 636 | |
paul@109 | 637 | count = self.get_count(command_parts) |
paul@109 | 638 | |
paul@109 | 639 | self.add_messages(islice(iter(self.store), count), message) |
paul@109 | 640 | |
paul@109 | 641 | def DELE(self, command_parts, message): |
paul@109 | 642 | |
paul@109 | 643 | # A request to delete messages is performed immediately. |
paul@109 | 644 | |
paul@109 | 645 | count = self.get_count(command_parts) |
paul@109 | 646 | |
paul@109 | 647 | keys = self.store.keys()[:count] |
paul@109 | 648 | |
paul@109 | 649 | for key in keys: |
paul@109 | 650 | del self.store[key] |
paul@109 | 651 | |
paul@109 | 652 | self.add_result("DELE", str(len(keys)), "OK", message) |
paul@109 | 653 | |
paul@109 | 654 | # Command manifest, may be extended by subclasses. |
paul@109 | 655 | |
paul@109 | 656 | commands = "STAT", "RETR", "DELE" |
paul@109 | 657 | |
paul@6 | 658 | # vim: tabstop=4 expandtab shiftwidth=4 |