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