paul@6 | 1 | # -*- coding: iso-8859-1 -*- |
paul@6 | 2 | """ |
paul@6 | 3 | MoinMoin - MoinMessage library |
paul@6 | 4 | |
paul@134 | 5 | @copyright: 2012, 2013, 2014, 2015 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@134 | 22 | from GPGUtils import GPG, GPGError, GPGDecodingError, GPGMissingPart, GPGBadContent, \ |
paul@134 | 23 | as_string, is_signed, is_encrypted, getContentAndSignature |
paul@6 | 24 | import httplib |
paul@8 | 25 | import os |
paul@6 | 26 | |
paul@105 | 27 | try: |
paul@105 | 28 | from cStringIO import StringIO |
paul@105 | 29 | except ImportError: |
paul@105 | 30 | from StringIO import StringIO |
paul@105 | 31 | |
paul@109 | 32 | # Message inspection functions. |
paul@109 | 33 | |
paul@15 | 34 | def is_collection(message): |
paul@15 | 35 | return message.get("Update-Type") == "collection" |
paul@15 | 36 | |
paul@29 | 37 | def to_replace(message): |
paul@29 | 38 | return message.get("Update-Action") == "replace" |
paul@29 | 39 | |
paul@29 | 40 | def to_store(message): |
paul@29 | 41 | return message.get("Update-Action") == "store" |
paul@29 | 42 | |
paul@85 | 43 | def get_update_action(message): |
paul@85 | 44 | return message.get("Update-Action", "update") |
paul@85 | 45 | |
paul@109 | 46 | # Core abstractions. |
paul@109 | 47 | |
paul@6 | 48 | class Message: |
paul@6 | 49 | |
paul@6 | 50 | "An update message." |
paul@6 | 51 | |
paul@15 | 52 | def __init__(self, text=None): |
paul@20 | 53 | self.date = None |
paul@6 | 54 | self.updates = [] |
paul@15 | 55 | if text: |
paul@15 | 56 | self.parse_text(text) |
paul@15 | 57 | |
paul@20 | 58 | def init_date(self, message): |
paul@20 | 59 | |
paul@20 | 60 | "Obtain the date of the given 'message'." |
paul@20 | 61 | |
paul@137 | 62 | self.date = message.get("Date") |
paul@20 | 63 | |
paul@15 | 64 | def parse_text(self, text): |
paul@15 | 65 | |
paul@15 | 66 | "Parse the given 'text' as a message." |
paul@15 | 67 | |
paul@15 | 68 | self.handle_message(message_from_string(text)) |
paul@15 | 69 | |
paul@15 | 70 | def handle_message(self, message): |
paul@15 | 71 | |
paul@15 | 72 | "Handle the given 'message', recording the separate updates." |
paul@15 | 73 | |
paul@20 | 74 | self.init_date(message) |
paul@20 | 75 | |
paul@15 | 76 | # The message either consists of a collection of updates. |
paul@15 | 77 | |
paul@15 | 78 | if message.is_multipart() and is_collection(message): |
paul@15 | 79 | for part in message.get_payload(): |
paul@15 | 80 | self.updates.append(part) |
paul@15 | 81 | |
paul@15 | 82 | # Or the message is a single update. |
paul@15 | 83 | |
paul@15 | 84 | else: |
paul@15 | 85 | self.updates.append(message) |
paul@6 | 86 | |
paul@16 | 87 | def add_updates(self, parts): |
paul@13 | 88 | |
paul@13 | 89 | """ |
paul@16 | 90 | Add the given 'parts' to a message. |
paul@13 | 91 | """ |
paul@13 | 92 | |
paul@16 | 93 | for part in updates: |
paul@16 | 94 | self.add_update(part) |
paul@16 | 95 | |
paul@16 | 96 | def add_update(self, part): |
paul@16 | 97 | |
paul@16 | 98 | """ |
paul@16 | 99 | Add an update 'part' to a message. |
paul@16 | 100 | """ |
paul@16 | 101 | |
paul@16 | 102 | self.updates.append(part) |
paul@16 | 103 | |
paul@16 | 104 | def get_update(self, alternatives): |
paul@16 | 105 | |
paul@16 | 106 | """ |
paul@16 | 107 | Return a suitable multipart object containing the supplied |
paul@16 | 108 | 'alternatives'. |
paul@16 | 109 | """ |
paul@16 | 110 | |
paul@109 | 111 | part = MIMEMultipart("alternative") |
paul@16 | 112 | for alternative in alternatives: |
paul@16 | 113 | part.attach(alternative) |
paul@16 | 114 | return part |
paul@6 | 115 | |
paul@115 | 116 | def get_payload(self, subtype="mixed", timestamped=True): |
paul@13 | 117 | |
paul@20 | 118 | """ |
paul@20 | 119 | Get the multipart payload for the message. If the 'timestamped' |
paul@20 | 120 | parameter is omitted or set to a true value, the payload will be given a |
paul@20 | 121 | date header set to the current date and time that can be used to assess |
paul@20 | 122 | the validity of a message and to determine whether it has already been |
paul@20 | 123 | received by a recipient. |
paul@20 | 124 | """ |
paul@13 | 125 | |
paul@6 | 126 | if len(self.updates) == 1: |
paul@6 | 127 | message = self.updates[0] |
paul@6 | 128 | else: |
paul@115 | 129 | message = MIMEMultipart(subtype) |
paul@6 | 130 | message.add_header("Update-Type", "collection") |
paul@6 | 131 | for update in self.updates: |
paul@6 | 132 | message.attach(update) |
paul@6 | 133 | |
paul@20 | 134 | if timestamped: |
paul@20 | 135 | timestamp(message) |
paul@20 | 136 | self.init_date(message) |
paul@20 | 137 | |
paul@6 | 138 | return message |
paul@6 | 139 | |
paul@134 | 140 | MoinMessageError = GPGError |
paul@134 | 141 | MoinMessageDecodingError = GPGDecodingError |
paul@134 | 142 | MoinMessageMissingPart = GPGMissingPart |
paul@134 | 143 | MoinMessageBadContent = GPGBadContent |
paul@36 | 144 | |
paul@136 | 145 | class MoinMessageTransferError(MoinMessageError): |
paul@136 | 146 | def __init__(self, code, message, body): |
paul@136 | 147 | MoinMessageError.__init__(self, message) |
paul@136 | 148 | self.code = code |
paul@136 | 149 | self.body = body |
paul@136 | 150 | |
paul@8 | 151 | # Communications functions. |
paul@6 | 152 | |
paul@20 | 153 | def timestamp(message): |
paul@20 | 154 | |
paul@20 | 155 | """ |
paul@20 | 156 | Timestamp the given 'message' so that its validity can be assessed by the |
paul@20 | 157 | recipient. |
paul@20 | 158 | """ |
paul@20 | 159 | |
paul@20 | 160 | datestr = formatdate() |
paul@20 | 161 | |
paul@20 | 162 | if not message.has_key("Date"): |
paul@20 | 163 | message.add_header("Date", datestr) |
paul@20 | 164 | else: |
paul@119 | 165 | message.replace_header("Date", datestr) |
paul@20 | 166 | |
paul@92 | 167 | def _getConnection(scheme): |
paul@92 | 168 | |
paul@92 | 169 | "Return the connection class for the given 'scheme'." |
paul@92 | 170 | |
paul@92 | 171 | if scheme == "http": |
paul@92 | 172 | return httplib.HTTPConnection |
paul@92 | 173 | elif scheme == "https": |
paul@92 | 174 | return httplib.HTTPSConnection |
paul@92 | 175 | else: |
paul@92 | 176 | raise MoinMessageError, "Communications protocol not supported: %s" % scheme |
paul@92 | 177 | |
paul@108 | 178 | def sendMessageOpener(message, url, method="PUT"): |
paul@6 | 179 | |
paul@44 | 180 | """ |
paul@44 | 181 | Send 'message' to the given 'url' using the given 'method' (using PUT as the |
paul@44 | 182 | default if omitted). |
paul@44 | 183 | """ |
paul@6 | 184 | |
paul@12 | 185 | scheme, host, port, path = parseURL(url) |
paul@105 | 186 | text = as_string(message) |
paul@6 | 187 | |
paul@92 | 188 | req = _getConnection(scheme)(host, port) |
paul@44 | 189 | req.request(method, path, text) |
paul@6 | 190 | resp = req.getresponse() |
paul@39 | 191 | |
paul@39 | 192 | if resp.status >= 400: |
paul@120 | 193 | raise MoinMessageTransferError(resp.status, "Message sending failed (%s)" % resp.status, resp.read()) |
paul@92 | 194 | |
paul@92 | 195 | return resp |
paul@92 | 196 | |
paul@92 | 197 | def sendMessage(message, url, method="PUT"): |
paul@39 | 198 | |
paul@92 | 199 | """ |
paul@92 | 200 | Send 'message' to the given 'url' using the given 'method' (using PUT as the |
paul@92 | 201 | default if omitted). |
paul@92 | 202 | """ |
paul@92 | 203 | |
paul@108 | 204 | resp = sendMessageOpener(message, url, method) |
paul@6 | 205 | return resp.read() |
paul@6 | 206 | |
paul@12 | 207 | def parseURL(url): |
paul@12 | 208 | |
paul@12 | 209 | "Return the scheme, host, port and path for the given 'url'." |
paul@12 | 210 | |
paul@12 | 211 | scheme, host_port, path, query, fragment = urlsplit(url) |
paul@12 | 212 | host_port = host_port.split(":") |
paul@12 | 213 | |
paul@12 | 214 | if query: |
paul@12 | 215 | path += "?" + query |
paul@12 | 216 | |
paul@12 | 217 | if len(host_port) > 1: |
paul@12 | 218 | host = host_port[0] |
paul@12 | 219 | port = int(host_port[1]) |
paul@12 | 220 | else: |
paul@12 | 221 | host = host_port[0] |
paul@12 | 222 | port = 80 |
paul@12 | 223 | |
paul@12 | 224 | return scheme, host, port, path |
paul@12 | 225 | |
paul@109 | 226 | # Message handling. |
paul@109 | 227 | |
paul@109 | 228 | class MessageInterface: |
paul@109 | 229 | |
paul@109 | 230 | "A command-based interface to a message store, inspired by RFC 1939 (POP3)." |
paul@109 | 231 | |
paul@109 | 232 | def __init__(self, store): |
paul@109 | 233 | self.store = store |
paul@109 | 234 | |
paul@109 | 235 | def execute(self, commands): |
paul@109 | 236 | |
paul@109 | 237 | """ |
paul@109 | 238 | Access messages according to the given 'commands' script, acting on the |
paul@109 | 239 | store provided during initialisation and returning a message object |
paul@109 | 240 | containing the results. |
paul@109 | 241 | """ |
paul@109 | 242 | |
paul@109 | 243 | # Build a container for the responses. |
paul@109 | 244 | |
paul@109 | 245 | message = Message() |
paul@109 | 246 | |
paul@109 | 247 | # Process each command. |
paul@109 | 248 | |
paul@109 | 249 | for command in commands.split("\n"): |
paul@109 | 250 | command = command.strip() |
paul@109 | 251 | |
paul@109 | 252 | # Get the command and arguments. |
paul@109 | 253 | |
paul@109 | 254 | command_parts = command.split(None, 1) |
paul@109 | 255 | cmd = command_parts[0] |
paul@109 | 256 | |
paul@109 | 257 | try: |
paul@109 | 258 | if cmd in self.commands: |
paul@109 | 259 | getattr(self, cmd)(command_parts, message) |
paul@109 | 260 | else: |
paul@109 | 261 | self.add_result(cmd, command, "ERR", message) |
paul@109 | 262 | except Exception, exc: |
paul@109 | 263 | self.add_result(cmd, "\n".join([command, str(exc)]), "ERR", message) |
paul@109 | 264 | |
paul@109 | 265 | return message |
paul@109 | 266 | |
paul@109 | 267 | def get_count(self, command_parts): |
paul@109 | 268 | |
paul@109 | 269 | # Select all messages by default. |
paul@109 | 270 | |
paul@109 | 271 | count = None |
paul@109 | 272 | |
paul@109 | 273 | if len(command_parts) > 1: |
paul@109 | 274 | count = int(command_parts[1]) |
paul@109 | 275 | |
paul@109 | 276 | return count |
paul@109 | 277 | |
paul@109 | 278 | def add_result(self, cmd, result, status, message): |
paul@109 | 279 | part = MIMEText(result, "x-moinmessage-fetch-result") |
paul@109 | 280 | part["Request-Type"] = cmd |
paul@109 | 281 | part["Request-Status"] = status |
paul@109 | 282 | message.add_update(part) |
paul@109 | 283 | |
paul@109 | 284 | def add_messages(self, resources, message): |
paul@109 | 285 | container = Message() |
paul@109 | 286 | |
paul@109 | 287 | for message_text in resources: |
paul@109 | 288 | message_item = Parser().parsestr(message_text) |
paul@109 | 289 | container.add_update(message_item) |
paul@109 | 290 | |
paul@109 | 291 | # Convert the container to a proper multipart section. |
paul@109 | 292 | |
paul@109 | 293 | message.add_update(container.get_payload()) |
paul@109 | 294 | |
paul@109 | 295 | def STAT(self, command_parts, message): |
paul@109 | 296 | |
paul@109 | 297 | # A request to count the messages is returned in a part. |
paul@109 | 298 | |
paul@109 | 299 | self.add_result("STAT", str(len(self.store)), "OK", message) |
paul@109 | 300 | |
paul@109 | 301 | def RETR(self, command_parts, message): |
paul@109 | 302 | |
paul@109 | 303 | # A request for specific messages returns each message |
paul@109 | 304 | # in its own part within a collection part. |
paul@109 | 305 | |
paul@109 | 306 | count = self.get_count(command_parts) |
paul@109 | 307 | |
paul@109 | 308 | self.add_messages(islice(iter(self.store), count), message) |
paul@109 | 309 | |
paul@109 | 310 | def DELE(self, command_parts, message): |
paul@109 | 311 | |
paul@109 | 312 | # A request to delete messages is performed immediately. |
paul@109 | 313 | |
paul@109 | 314 | count = self.get_count(command_parts) |
paul@109 | 315 | |
paul@109 | 316 | keys = self.store.keys()[:count] |
paul@109 | 317 | |
paul@109 | 318 | for key in keys: |
paul@109 | 319 | del self.store[key] |
paul@109 | 320 | |
paul@109 | 321 | self.add_result("DELE", str(len(keys)), "OK", message) |
paul@109 | 322 | |
paul@109 | 323 | # Command manifest, may be extended by subclasses. |
paul@109 | 324 | |
paul@109 | 325 | commands = "STAT", "RETR", "DELE" |
paul@109 | 326 | |
paul@6 | 327 | # vim: tabstop=4 expandtab shiftwidth=4 |