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