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