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@20 | 118 | def get_payload(self, 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@6 | 131 | message = MIMEMultipart() |
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@75 | 331 | def exportKey(self, keyid): |
paul@75 | 332 | |
paul@75 | 333 | """ |
paul@75 | 334 | Return the "armoured" public key text for 'keyid' as a message part with |
paul@75 | 335 | a suitable media type. |
paul@75 | 336 | See: https://tools.ietf.org/html/rfc3156#section-7 |
paul@75 | 337 | """ |
paul@75 | 338 | |
paul@75 | 339 | text = self.run(["--armor", "--export", keyid]) |
paul@75 | 340 | return MIMEApplication(text, "pgp-keys", encode_noop) |
paul@75 | 341 | |
paul@78 | 342 | def listKeys(self, keyid=None): |
paul@78 | 343 | |
paul@78 | 344 | """ |
paul@78 | 345 | Return a list of key details for keys on the keychain, selecting only |
paul@78 | 346 | one specific key if 'keyid' is specified. |
paul@78 | 347 | """ |
paul@78 | 348 | |
paul@78 | 349 | text = self.run(["--list-keys", "--with-colons", "--with-fingerprint"] + |
paul@78 | 350 | (keyid and ["0x%s" % keyid] or [])) |
paul@78 | 351 | return self._getKeysFromResult(text) |
paul@78 | 352 | |
paul@78 | 353 | def listSignatures(self, keyid=None): |
paul@78 | 354 | |
paul@78 | 355 | """ |
paul@78 | 356 | Return a list of key and signature details for keys on the keychain, |
paul@78 | 357 | selecting only one specific key if 'keyid' is specified. |
paul@78 | 358 | """ |
paul@78 | 359 | |
paul@78 | 360 | text = self.run(["--list-sigs", "--with-colons", "--with-fingerprint"] + |
paul@78 | 361 | (keyid and ["0x%s" % keyid] or [])) |
paul@78 | 362 | return self._getKeysFromResult(text) |
paul@78 | 363 | |
paul@77 | 364 | def getKeysFromMessagePart(self, part): |
paul@77 | 365 | |
paul@77 | 366 | """ |
paul@77 | 367 | Process an application/pgp-keys message 'part', returning a list of |
paul@77 | 368 | key details. |
paul@77 | 369 | """ |
paul@77 | 370 | |
paul@93 | 371 | return self.getKeysFromString(part.get_payload(decode=True)) |
paul@77 | 372 | |
paul@77 | 373 | def getKeysFromString(self, s): |
paul@77 | 374 | |
paul@78 | 375 | """ |
paul@78 | 376 | Return a list of key details extracted from the given key block string |
paul@79 | 377 | 's'. Signature information is also included through the use of the gpg |
paul@79 | 378 | verbose option. |
paul@78 | 379 | """ |
paul@77 | 380 | |
paul@79 | 381 | text = self.run(["--with-colons", "--with-fingerprint", "-v"], s) |
paul@78 | 382 | return self._getKeysFromResult(text) |
paul@78 | 383 | |
paul@78 | 384 | def _getKeysFromResult(self, text): |
paul@78 | 385 | |
paul@78 | 386 | """ |
paul@78 | 387 | Return a list of key details extracted from the given command result |
paul@78 | 388 | 'text'. |
paul@78 | 389 | """ |
paul@78 | 390 | |
paul@77 | 391 | keys = [] |
paul@77 | 392 | for line in text.split("\n"): |
paul@77 | 393 | try: |
paul@77 | 394 | recordtype, trust, keylength, algorithm, keyid, cdate, expdate, serial, ownertrust, _rest = line.split(":", 9) |
paul@77 | 395 | except ValueError: |
paul@78 | 396 | continue |
paul@77 | 397 | |
paul@77 | 398 | if recordtype == "pub": |
paul@77 | 399 | userid, _rest = _rest.split(":", 1) |
paul@77 | 400 | keys.append({ |
paul@77 | 401 | "type" : recordtype, "trust" : trust, "keylength" : keylength, |
paul@77 | 402 | "algorithm" : algorithm, "keyid" : keyid, "cdate" : cdate, |
paul@77 | 403 | "expdate" : expdate, "userid" : userid, "ownertrust" : ownertrust, |
paul@78 | 404 | "fingerprint" : None, "subkeys" : [], "signatures" : [] |
paul@77 | 405 | }) |
paul@77 | 406 | elif recordtype == "sub" and keys: |
paul@77 | 407 | keys[-1]["subkeys"].append({ |
paul@77 | 408 | "trust" : trust, "keylength" : keylength, "algorithm" : algorithm, |
paul@77 | 409 | "keyid" : keyid, "cdate" : cdate, "expdate" : expdate, |
paul@77 | 410 | "ownertrust" : ownertrust |
paul@77 | 411 | }) |
paul@77 | 412 | elif recordtype == "fpr" and keys: |
paul@77 | 413 | fingerprint, _rest = _rest.split(":", 1) |
paul@77 | 414 | keys[-1]["fingerprint"] = fingerprint |
paul@78 | 415 | elif recordtype == "sig" and keys: |
paul@78 | 416 | userid, _rest = _rest.split(":", 1) |
paul@78 | 417 | keys[-1]["signatures"].append({ |
paul@78 | 418 | "keyid" : keyid, "cdate" : cdate, "expdate" : expdate, |
paul@78 | 419 | "userid" : userid |
paul@78 | 420 | }) |
paul@77 | 421 | |
paul@77 | 422 | return keys |
paul@77 | 423 | |
paul@105 | 424 | # Message serialisation functions, working around email module problems. |
paul@105 | 425 | |
paul@105 | 426 | def as_string(message): |
paul@105 | 427 | |
paul@105 | 428 | """ |
paul@105 | 429 | Return the string representation of 'message', attempting to preserve the |
paul@105 | 430 | precise original formatting. |
paul@105 | 431 | """ |
paul@105 | 432 | |
paul@105 | 433 | out = StringIO() |
paul@105 | 434 | generator = Generator(out, False, 0) # disable reformatting measures |
paul@105 | 435 | generator.flatten(message) |
paul@105 | 436 | return out.getvalue() |
paul@105 | 437 | |
paul@33 | 438 | # Message decoding functions. |
paul@33 | 439 | |
paul@33 | 440 | # Detect PGP/GPG-encoded payloads. |
paul@33 | 441 | # See: http://tools.ietf.org/html/rfc3156 |
paul@33 | 442 | |
paul@33 | 443 | def is_signed(message): |
paul@33 | 444 | mimetype = message.get_content_type() |
paul@33 | 445 | encoding = message.get_content_charset() |
paul@33 | 446 | |
paul@33 | 447 | return mimetype == "multipart/signed" and \ |
paul@33 | 448 | message.get_param("protocol") == "application/pgp-signature" |
paul@33 | 449 | |
paul@33 | 450 | def is_encrypted(message): |
paul@33 | 451 | mimetype = message.get_content_type() |
paul@33 | 452 | encoding = message.get_content_charset() |
paul@33 | 453 | |
paul@33 | 454 | return mimetype == "multipart/encrypted" and \ |
paul@33 | 455 | message.get_param("protocol") == "application/pgp-encrypted" |
paul@33 | 456 | |
paul@36 | 457 | def getContentAndSignature(message): |
paul@36 | 458 | |
paul@36 | 459 | """ |
paul@36 | 460 | Return the content and signature parts of the given RFC 3156 'message'. |
paul@36 | 461 | |
paul@36 | 462 | NOTE: RFC 3156 states that signed messages should employ a detached |
paul@36 | 463 | NOTE: signature but then shows "BEGIN PGP MESSAGE" for signatures |
paul@36 | 464 | NOTE: instead of "BEGIN PGP SIGNATURE". |
paul@36 | 465 | NOTE: The "micalg" parameter is currently not supported. |
paul@36 | 466 | """ |
paul@36 | 467 | |
paul@36 | 468 | try: |
paul@36 | 469 | content, signature = message.get_payload() |
paul@36 | 470 | return content, signature |
paul@36 | 471 | except ValueError: |
paul@36 | 472 | raise MoinMessageMissingPart |
paul@36 | 473 | |
paul@8 | 474 | # Communications functions. |
paul@6 | 475 | |
paul@20 | 476 | def timestamp(message): |
paul@20 | 477 | |
paul@20 | 478 | """ |
paul@20 | 479 | Timestamp the given 'message' so that its validity can be assessed by the |
paul@20 | 480 | recipient. |
paul@20 | 481 | """ |
paul@20 | 482 | |
paul@20 | 483 | datestr = formatdate() |
paul@20 | 484 | |
paul@20 | 485 | if not message.has_key("Date"): |
paul@20 | 486 | message.add_header("Date", datestr) |
paul@20 | 487 | else: |
paul@20 | 488 | message["Date"] = datestr |
paul@20 | 489 | |
paul@92 | 490 | def _getConnection(scheme): |
paul@92 | 491 | |
paul@92 | 492 | "Return the connection class for the given 'scheme'." |
paul@92 | 493 | |
paul@92 | 494 | if scheme == "http": |
paul@92 | 495 | return httplib.HTTPConnection |
paul@92 | 496 | elif scheme == "https": |
paul@92 | 497 | return httplib.HTTPSConnection |
paul@92 | 498 | else: |
paul@92 | 499 | raise MoinMessageError, "Communications protocol not supported: %s" % scheme |
paul@92 | 500 | |
paul@108 | 501 | def sendMessageOpener(message, url, method="PUT"): |
paul@6 | 502 | |
paul@44 | 503 | """ |
paul@44 | 504 | Send 'message' to the given 'url' using the given 'method' (using PUT as the |
paul@44 | 505 | default if omitted). |
paul@44 | 506 | """ |
paul@6 | 507 | |
paul@12 | 508 | scheme, host, port, path = parseURL(url) |
paul@105 | 509 | text = as_string(message) |
paul@6 | 510 | |
paul@92 | 511 | req = _getConnection(scheme)(host, port) |
paul@44 | 512 | req.request(method, path, text) |
paul@6 | 513 | resp = req.getresponse() |
paul@39 | 514 | |
paul@39 | 515 | if resp.status >= 400: |
paul@92 | 516 | raise MoinMessageError, "Message sending failed (%s): %s" % (resp.status, resp.read()) |
paul@92 | 517 | |
paul@92 | 518 | return resp |
paul@92 | 519 | |
paul@92 | 520 | def sendMessage(message, url, method="PUT"): |
paul@39 | 521 | |
paul@92 | 522 | """ |
paul@92 | 523 | Send 'message' to the given 'url' using the given 'method' (using PUT as the |
paul@92 | 524 | default if omitted). |
paul@92 | 525 | """ |
paul@92 | 526 | |
paul@108 | 527 | resp = sendMessageOpener(message, url, method) |
paul@6 | 528 | return resp.read() |
paul@6 | 529 | |
paul@12 | 530 | def parseURL(url): |
paul@12 | 531 | |
paul@12 | 532 | "Return the scheme, host, port and path for the given 'url'." |
paul@12 | 533 | |
paul@12 | 534 | scheme, host_port, path, query, fragment = urlsplit(url) |
paul@12 | 535 | host_port = host_port.split(":") |
paul@12 | 536 | |
paul@12 | 537 | if query: |
paul@12 | 538 | path += "?" + query |
paul@12 | 539 | |
paul@12 | 540 | if len(host_port) > 1: |
paul@12 | 541 | host = host_port[0] |
paul@12 | 542 | port = int(host_port[1]) |
paul@12 | 543 | else: |
paul@12 | 544 | host = host_port[0] |
paul@12 | 545 | port = 80 |
paul@12 | 546 | |
paul@12 | 547 | return scheme, host, port, path |
paul@12 | 548 | |
paul@109 | 549 | # Message handling. |
paul@109 | 550 | |
paul@109 | 551 | class MessageInterface: |
paul@109 | 552 | |
paul@109 | 553 | "A command-based interface to a message store, inspired by RFC 1939 (POP3)." |
paul@109 | 554 | |
paul@109 | 555 | def __init__(self, store): |
paul@109 | 556 | self.store = store |
paul@109 | 557 | |
paul@109 | 558 | def execute(self, commands): |
paul@109 | 559 | |
paul@109 | 560 | """ |
paul@109 | 561 | Access messages according to the given 'commands' script, acting on the |
paul@109 | 562 | store provided during initialisation and returning a message object |
paul@109 | 563 | containing the results. |
paul@109 | 564 | """ |
paul@109 | 565 | |
paul@109 | 566 | # Build a container for the responses. |
paul@109 | 567 | |
paul@109 | 568 | message = Message() |
paul@109 | 569 | |
paul@109 | 570 | # Process each command. |
paul@109 | 571 | |
paul@109 | 572 | for command in commands.split("\n"): |
paul@109 | 573 | command = command.strip() |
paul@109 | 574 | |
paul@109 | 575 | # Get the command and arguments. |
paul@109 | 576 | |
paul@109 | 577 | command_parts = command.split(None, 1) |
paul@109 | 578 | cmd = command_parts[0] |
paul@109 | 579 | |
paul@109 | 580 | try: |
paul@109 | 581 | if cmd in self.commands: |
paul@109 | 582 | getattr(self, cmd)(command_parts, message) |
paul@109 | 583 | else: |
paul@109 | 584 | self.add_result(cmd, command, "ERR", message) |
paul@109 | 585 | except Exception, exc: |
paul@109 | 586 | self.add_result(cmd, "\n".join([command, str(exc)]), "ERR", message) |
paul@109 | 587 | |
paul@109 | 588 | return message |
paul@109 | 589 | |
paul@109 | 590 | def get_count(self, command_parts): |
paul@109 | 591 | |
paul@109 | 592 | # Select all messages by default. |
paul@109 | 593 | |
paul@109 | 594 | count = None |
paul@109 | 595 | |
paul@109 | 596 | if len(command_parts) > 1: |
paul@109 | 597 | count = int(command_parts[1]) |
paul@109 | 598 | |
paul@109 | 599 | return count |
paul@109 | 600 | |
paul@109 | 601 | def add_result(self, cmd, result, status, message): |
paul@109 | 602 | part = MIMEText(result, "x-moinmessage-fetch-result") |
paul@109 | 603 | part["Request-Type"] = cmd |
paul@109 | 604 | part["Request-Status"] = status |
paul@109 | 605 | message.add_update(part) |
paul@109 | 606 | |
paul@109 | 607 | def add_messages(self, resources, message): |
paul@109 | 608 | container = Message() |
paul@109 | 609 | |
paul@109 | 610 | for message_text in resources: |
paul@109 | 611 | message_item = Parser().parsestr(message_text) |
paul@109 | 612 | container.add_update(message_item) |
paul@109 | 613 | |
paul@109 | 614 | # Convert the container to a proper multipart section. |
paul@109 | 615 | |
paul@109 | 616 | message.add_update(container.get_payload()) |
paul@109 | 617 | |
paul@109 | 618 | def STAT(self, command_parts, message): |
paul@109 | 619 | |
paul@109 | 620 | # A request to count the messages is returned in a part. |
paul@109 | 621 | |
paul@109 | 622 | self.add_result("STAT", str(len(self.store)), "OK", message) |
paul@109 | 623 | |
paul@109 | 624 | def RETR(self, command_parts, message): |
paul@109 | 625 | |
paul@109 | 626 | # A request for specific messages returns each message |
paul@109 | 627 | # in its own part within a collection part. |
paul@109 | 628 | |
paul@109 | 629 | count = self.get_count(command_parts) |
paul@109 | 630 | |
paul@109 | 631 | self.add_messages(islice(iter(self.store), count), message) |
paul@109 | 632 | |
paul@109 | 633 | def DELE(self, command_parts, message): |
paul@109 | 634 | |
paul@109 | 635 | # A request to delete messages is performed immediately. |
paul@109 | 636 | |
paul@109 | 637 | count = self.get_count(command_parts) |
paul@109 | 638 | |
paul@109 | 639 | keys = self.store.keys()[:count] |
paul@109 | 640 | |
paul@109 | 641 | for key in keys: |
paul@109 | 642 | del self.store[key] |
paul@109 | 643 | |
paul@109 | 644 | self.add_result("DELE", str(len(keys)), "OK", message) |
paul@109 | 645 | |
paul@109 | 646 | # Command manifest, may be extended by subclasses. |
paul@109 | 647 | |
paul@109 | 648 | commands = "STAT", "RETR", "DELE" |
paul@109 | 649 | |
paul@6 | 650 | # vim: tabstop=4 expandtab shiftwidth=4 |