1 #!/usr/bin/env python 2 3 """ 4 A processing framework for iMIP content. 5 6 Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from email import message_from_file 23 from imiptools.client import Client 24 from imiptools.content import handle_itip_part 25 from imiptools.data import get_address, get_addresses, get_uri 26 from imiptools.mail import Messenger 27 import imip_store 28 import sys 29 30 # Postfix exit codes. 31 32 EX_TEMPFAIL = 75 33 34 # Permitted iTIP content types. 35 36 itip_content_types = [ 37 "text/calendar", # from RFC 6047 38 "text/x-vcalendar", "application/ics", # other possibilities 39 ] 40 41 # Processing of incoming messages. 42 43 def get_all_values(msg, key): 44 l = [] 45 for v in msg.get_all(key) or []: 46 l += [s.strip() for s in v.split(",")] 47 return l 48 49 class Processor: 50 51 "The processing framework." 52 53 def __init__(self, handlers): 54 self.handlers = handlers 55 self.messenger = None 56 self.lmtp_socket = None 57 self.store_dir = None 58 self.publishing_dir = None 59 self.preferences_dir = None 60 self.debug = False 61 62 def get_store(self): 63 return imip_store.FileStore(self.store_dir) 64 65 def get_publisher(self): 66 return self.publishing_dir and imip_store.FilePublisher(self.publishing_dir) or None 67 68 def process(self, f, original_recipients, outgoing_only): 69 70 """ 71 Process content from the stream 'f' accompanied by the given 72 'original_recipients'. 73 """ 74 75 msg = message_from_file(f) 76 senders = get_addresses(msg.get_all("Reply-To") or msg.get_all("From") or []) 77 78 messenger = self.messenger 79 store = self.get_store() 80 publisher = self.get_publisher() 81 preferences_dir = self.preferences_dir 82 83 # Handle messages with iTIP parts. 84 # Typically, the details of recipients are of interest in handling 85 # messages. 86 87 if not outgoing_only: 88 original_recipients = original_recipients or get_addresses(get_all_values(msg, "To") or []) 89 for recipient in original_recipients: 90 Recipient(get_uri(recipient), messenger, store, publisher, preferences_dir, self.handlers, self.debug).process(msg, senders, outgoing_only) 91 92 # However, outgoing messages do not usually presume anything about the 93 # eventual recipients. 94 95 else: 96 Recipient(None, messenger, store, publisher, preferences_dir, self.handlers, self.debug).process(msg, senders, outgoing_only) 97 98 def process_args(self, args, stream): 99 100 """ 101 Interpret the given program arguments 'args' and process input from the 102 given 'stream'. 103 """ 104 105 # Obtain the different kinds of recipients plus sender address. 106 107 original_recipients = [] 108 recipients = [] 109 senders = [] 110 lmtp = [] 111 store_dir = [] 112 publishing_dir = [] 113 preferences_dir = [] 114 outgoing_only = False 115 116 l = [] 117 118 for arg in args: 119 120 # Detect outgoing processing mode. 121 122 if arg == "-O": 123 outgoing_only = True 124 125 # Switch to collecting recipients. 126 127 if arg == "-o": 128 l = original_recipients 129 130 # Switch to collecting senders. 131 132 elif arg == "-s": 133 l = senders 134 135 # Switch to getting the LMTP socket. 136 137 elif arg == "-l": 138 l = lmtp 139 140 # Switch to getting the store directory. 141 142 elif arg == "-S": 143 l = store_dir 144 145 # Switch to getting the publishing directory. 146 147 elif arg == "-P": 148 l = publishing_dir 149 150 # Switch to getting the preferences directory. 151 152 elif arg == "-p": 153 l = preferences_dir 154 155 # Ignore debugging options. 156 157 elif arg == "-d": 158 self.debug = True 159 else: 160 l.append(arg) 161 162 self.messenger = Messenger(lmtp_socket=lmtp and lmtp[0] or None, sender=senders and senders[0] or None) 163 self.store_dir = store_dir and store_dir[0] or None 164 self.publishing_dir = publishing_dir and publishing_dir[0] or None 165 self.preferences_dir = preferences_dir and preferences_dir[0] or None 166 self.process(stream, original_recipients, outgoing_only) 167 168 def __call__(self): 169 170 """ 171 Obtain arguments from the command line to initialise the processor 172 before invoking it. 173 """ 174 175 args = sys.argv[1:] 176 177 if "-d" in args: 178 self.process_args(args, sys.stdin) 179 else: 180 try: 181 self.process_args(args, sys.stdin) 182 except SystemExit, value: 183 sys.exit(value) 184 except Exception, exc: 185 if "-v" in args: 186 raise 187 type, value, tb = sys.exc_info() 188 while tb.tb_next: 189 tb = tb.tb_next 190 f = tb.tb_frame 191 co = f and f.f_code 192 filename = co and co.co_filename 193 print >>sys.stderr, "Exception %s at %d in %s" % (exc, tb.tb_lineno, filename) 194 #import traceback 195 #traceback.print_exc(file=open("/tmp/mail.log", "a")) 196 sys.exit(EX_TEMPFAIL) 197 sys.exit(0) 198 199 class Recipient(Client): 200 201 "A processor acting as a client on behalf of a recipient." 202 203 def __init__(self, user, messenger, store, publisher, preferences_dir, handlers, debug): 204 205 """ 206 Initialise the recipient with the given 'user' identity, 'messenger', 207 'store', 'publisher', 'preferences_dir', 'handlers' and 'debug' status. 208 """ 209 210 Client.__init__(self, user, messenger, store, publisher, preferences_dir) 211 self.handlers = handlers 212 self.debug = debug 213 214 def process(self, msg, senders, outgoing_only): 215 216 """ 217 Process the given 'msg' for a single recipient, having the given 218 'senders', and with the given 'outgoing_only' status. 219 220 Processing individually means that contributions to resulting messages 221 may be constructed according to individual preferences. 222 """ 223 224 handlers = dict([(name, cls(senders, self.user and get_address(self.user), 225 self.messenger, self.store, self.publisher, 226 self.preferences_dir)) 227 for name, cls in self.handlers]) 228 handled = False 229 230 # Check for returned messages. 231 232 for part in msg.walk(): 233 if part.get_content_type() == "message/delivery-status": 234 break 235 else: 236 for part in msg.walk(): 237 if part.get_content_type() in itip_content_types and \ 238 part.get_param("method"): 239 240 handle_itip_part(part, handlers) 241 handled = True 242 243 # When processing outgoing messages, no replies or deliveries are 244 # performed. 245 246 if outgoing_only: 247 return 248 249 # Get responses from the handlers. 250 251 all_responses = [] 252 for handler in handlers.values(): 253 all_responses += handler.get_results() 254 255 # Pack any returned parts into messages. 256 257 if all_responses: 258 outgoing_parts = {} 259 forwarded_parts = [] 260 261 for outgoing_recipients, part in all_responses: 262 if outgoing_recipients: 263 for outgoing_recipient in outgoing_recipients: 264 if not outgoing_parts.has_key(outgoing_recipient): 265 outgoing_parts[outgoing_recipient] = [] 266 outgoing_parts[outgoing_recipient].append(part) 267 else: 268 forwarded_parts.append(part) 269 270 # Reply using any outgoing parts in a new message. 271 272 if outgoing_parts: 273 274 # Obtain free/busy details, if configured to do so. 275 276 fb = self.can_provide_freebusy(handlers) and self.get_freebusy_part() 277 278 for outgoing_recipient, parts in outgoing_parts.items(): 279 280 # Bundle free/busy messages, if configured to do so. 281 282 if fb: parts.append(fb) 283 message = self.messenger.make_outgoing_message(parts, [outgoing_recipient]) 284 285 if self.debug: 286 print >>sys.stderr, "Outgoing parts for %s..." % outgoing_recipient 287 print message 288 else: 289 self.messenger.sendmail([outgoing_recipient], message.as_string()) 290 291 # Forward messages to their recipients either wrapping the existing 292 # message, accompanying it or replacing it. 293 294 if forwarded_parts: 295 296 # Determine whether to wrap, accompany or replace the message. 297 298 prefs = self.get_preferences() 299 300 incoming = prefs.get("incoming") 301 302 if incoming == "message-only": 303 messages = [msg] 304 else: 305 summary = self.messenger.make_summary_message(msg, forwarded_parts) 306 if incoming == "summary-then-message": 307 messages = [summary, msg] 308 elif incoming == "message-then-summary": 309 messages = [msg, summary] 310 elif incoming == "summary-only": 311 messages = [summary] 312 else: # incoming == "summary-wraps-message": 313 messages = [self.messenger.wrap_message(msg, forwarded_parts)] 314 315 for message in messages: 316 if self.debug: 317 print >>sys.stderr, "Forwarded parts..." 318 print message 319 elif self.messenger.local_delivery(): 320 self.messenger.sendmail(get_address(self.user), message.as_string()) 321 322 # Unhandled messages are delivered as they are. 323 324 if not handled: 325 if self.debug: 326 print >>sys.stderr, "Unhandled parts..." 327 print msg 328 elif self.messenger.local_delivery(): 329 self.messenger.sendmail(get_address(self.user), msg.as_string()) 330 331 def can_provide_freebusy(self, handlers): 332 333 "Test for any free/busy information produced by 'handlers'." 334 335 fbhandler = handlers.get("VFREEBUSY") 336 if fbhandler: 337 fbmethods = fbhandler.get_outgoing_methods() 338 return not "REPLY" in fbmethods and not "PUBLISH" in fbmethods 339 else: 340 return False 341 342 # vim: tabstop=4 expandtab shiftwidth=4