1 #!/usr/bin/env python 2 3 """ 4 A processing framework for iMIP content. 5 6 Copyright (C) 2014, 2015, 2016 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 from imiptools.stores import get_store, get_publisher, get_journal 29 import sys, os 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_type = None 60 self.store_dir = None 61 self.publishing_dir = None 62 self.journal_dir = None 63 self.preferences_dir = None 64 self.debug = False 65 66 def get_store(self): 67 return get_store(self.store_type, self.store_dir) 68 69 def get_publisher(self): 70 return self.publishing_dir and get_publisher(self.publishing_dir) or None 71 72 def get_journal(self): 73 return get_journal(self.store_type, self.journal_dir) 74 75 def process(self, f, original_recipients): 76 77 """ 78 Process content from the stream 'f' accompanied by the given 79 'original_recipients'. 80 """ 81 82 msg = message_from_file(f) 83 senders = get_addresses(get_all_values(msg, "Reply-To") or get_all_values(msg, "From") or []) 84 85 messenger = self.messenger 86 store = self.get_store() 87 publisher = self.get_publisher() 88 journal = self.get_journal() 89 preferences_dir = self.preferences_dir 90 91 # Handle messages with iTIP parts. 92 # Typically, the details of recipients are of interest in handling 93 # messages. 94 95 if not self.outgoing_only: 96 original_recipients = original_recipients or get_addresses(get_all_values(msg, "To") or []) 97 for recipient in original_recipients: 98 Recipient(get_uri(recipient), messenger, store, publisher, journal, preferences_dir, self.handlers, self.outgoing_only, self.debug 99 ).process(msg, senders) 100 101 # However, outgoing messages do not usually presume anything about the 102 # eventual recipients and focus on the sender instead. If possible, the 103 # sender is identified, but since this may be the calendar system (and 104 # the actual sender is defined in the object), and since the recipient 105 # may be in a Bcc header that is not available here, it may be left as 106 # None and deduced from the object content later. 107 108 else: 109 senders = [sender for sender in get_addresses(get_all_values(msg, "From") or []) if sender != config.MESSAGE_SENDER] 110 Recipient(senders and senders[0] or None, messenger, store, publisher, journal, preferences_dir, self.handlers, self.outgoing_only, self.debug 111 ).process(msg, senders) 112 113 def process_args(self, args, stream): 114 115 """ 116 Interpret the given program arguments 'args' and process input from the 117 given 'stream'. 118 """ 119 120 # Obtain the different kinds of recipients plus sender address. 121 122 original_recipients = [] 123 recipients = [] 124 senders = [] 125 lmtp = [] 126 store_type = [] 127 store_dir = [] 128 publishing_dir = [] 129 preferences_dir = [] 130 journal_dir = [] 131 local_smtp = False 132 133 l = [] 134 135 for arg in args: 136 137 # Switch to collecting recipients. 138 139 if arg == "-o": 140 l = original_recipients 141 142 # Switch to collecting senders. 143 144 elif arg == "-s": 145 l = senders 146 147 # Switch to getting the LMTP socket. 148 149 elif arg == "-l": 150 l = lmtp 151 152 # Detect sending to local users via SMTP. 153 154 elif arg == "-L": 155 local_smtp = True 156 157 # Switch to getting the store type. 158 159 elif arg == "-T": 160 l = store_type 161 162 # Switch to getting the store directory. 163 164 elif arg == "-S": 165 l = store_dir 166 167 # Switch to getting the publishing directory. 168 169 elif arg == "-P": 170 l = publishing_dir 171 172 # Switch to getting the preferences directory. 173 174 elif arg == "-p": 175 l = preferences_dir 176 177 # Switch to getting the journal directory. 178 179 elif arg == "-j": 180 l = journal_dir 181 182 # Ignore debugging options. 183 184 elif arg == "-d": 185 self.debug = True 186 else: 187 l.append(arg) 188 189 getvalue = lambda value, default=None: value and value[0] or default 190 191 self.messenger = Messenger(lmtp_socket=getvalue(lmtp), local_smtp=local_smtp, sender=getvalue(senders)) 192 self.store_type = getvalue(store_type, config.STORE_TYPE) 193 self.store_dir = getvalue(store_dir) 194 self.publishing_dir = getvalue(publishing_dir) 195 self.preferences_dir = getvalue(preferences_dir) 196 self.journal_dir = getvalue(journal_dir) 197 self.process(stream, original_recipients) 198 199 def __call__(self): 200 201 """ 202 Obtain arguments from the command line to initialise the processor 203 before invoking it. 204 """ 205 206 args = sys.argv[1:] 207 208 if "--help" in args: 209 print >>sys.stderr, """\ 210 Usage: %s [ -o <recipient> ... ] [-s <sender> ... ] [ -l <socket> | -L ] \\ 211 [ -T <store type ] \\ 212 [ -S <store directory> ] [ -P <publishing directory> ] \\ 213 [ -p <preferences directory> ] [ -j <journal directory> ] [ -d ] 214 215 Address options: 216 217 -o Indicate the original recipients of the message, overriding any found in 218 the message headers 219 -s Indicate the senders of the message, overriding any found in the message 220 headers 221 222 Delivery options: 223 224 -l The socket filename for LMTP communication with a mailbox solution, 225 selecting the LMTP delivery method 226 -L Selects the local SMTP delivery method, requiring a suitable mail system 227 configuration 228 229 (Where a program needs to deliver messages, one of the above options must be 230 specified.) 231 232 Configuration options: 233 234 -j Indicates the location of quota-related journal information 235 -P Indicates the location of published free/busy resources 236 -p Indicates the location of user preference directories 237 -S Indicates the location of the calendar data store containing user storage 238 directories 239 -T Indicates the store and journal type (the configured value if omitted) 240 241 Output options: 242 243 -d Run in debug mode, producing informative output describing the behaviour 244 of the program 245 """ % os.path.split(sys.argv[0])[-1] 246 elif "-d" in args: 247 self.process_args(args, sys.stdin) 248 else: 249 try: 250 self.process_args(args, sys.stdin) 251 except SystemExit, value: 252 sys.exit(value) 253 except Exception, exc: 254 if "-v" in args: 255 raise 256 type, value, tb = sys.exc_info() 257 while tb.tb_next: 258 tb = tb.tb_next 259 f = tb.tb_frame 260 co = f and f.f_code 261 filename = co and co.co_filename 262 print >>sys.stderr, "Exception %s at %d in %s" % (exc, tb.tb_lineno, filename) 263 #import traceback 264 #traceback.print_exc(file=open("/tmp/mail.log", "a")) 265 sys.exit(EX_TEMPFAIL) 266 sys.exit(0) 267 268 class Recipient(Client): 269 270 "A processor acting as a client on behalf of a recipient." 271 272 def __init__(self, user, messenger, store, publisher, journal, preferences_dir, 273 handlers, outgoing_only, debug): 274 275 """ 276 Initialise the recipient with the given 'user' identity, 'messenger', 277 'store', 'publisher', 'journal', 'preferences_dir', 'handlers', 278 'outgoing_only' and 'debug' status. 279 """ 280 281 Client.__init__(self, user, messenger, store, publisher, journal, preferences_dir) 282 self.handlers = handlers 283 self.outgoing_only = outgoing_only 284 self.debug = debug 285 286 def process(self, msg, senders): 287 288 """ 289 Process the given 'msg' for a single recipient, having the given 290 'senders'. 291 292 Processing individually means that contributions to resulting messages 293 may be constructed according to individual preferences. 294 """ 295 296 handlers = dict([(name, cls(senders, self.user and get_address(self.user), 297 self.messenger, self.store, self.publisher, 298 self.journal, self.preferences_dir)) 299 for name, cls in self.handlers]) 300 handled = False 301 302 # Check for participating recipients. Non-participating recipients will 303 # have their messages left as being unhandled. 304 305 if self.outgoing_only or self.is_participating(): 306 307 # Check for returned messages. 308 309 for part in msg.walk(): 310 if part.get_content_type() == "message/delivery-status": 311 break 312 else: 313 for part in msg.walk(): 314 if part.get_content_type() in itip_content_types and \ 315 part.get_param("method"): 316 317 handle_itip_part(part, handlers) 318 handled = True 319 320 # When processing outgoing messages, no replies or deliveries are 321 # performed. 322 323 if self.outgoing_only: 324 return 325 326 # Get responses from the handlers. 327 328 all_responses = [] 329 for handler in handlers.values(): 330 all_responses += handler.get_results() 331 332 # Pack any returned parts into messages. 333 334 if all_responses: 335 outgoing_parts = {} 336 forwarded_parts = [] 337 338 for outgoing_recipients, part in all_responses: 339 if outgoing_recipients: 340 for outgoing_recipient in outgoing_recipients: 341 if not outgoing_parts.has_key(outgoing_recipient): 342 outgoing_parts[outgoing_recipient] = [] 343 outgoing_parts[outgoing_recipient].append(part) 344 else: 345 forwarded_parts.append(part) 346 347 # Reply using any outgoing parts in a new message. 348 349 if outgoing_parts: 350 351 # Obtain free/busy details, if configured to do so. 352 353 fb = self.can_provide_freebusy(handlers) and self.get_freebusy_part() 354 355 for outgoing_recipient, parts in outgoing_parts.items(): 356 357 # Bundle free/busy messages, if configured to do so. 358 359 if fb: parts.append(fb) 360 message = self.messenger.make_outgoing_message(parts, [outgoing_recipient]) 361 362 if self.debug: 363 print >>sys.stderr, "Outgoing parts for %s..." % outgoing_recipient 364 print message 365 else: 366 self.messenger.sendmail([outgoing_recipient], message.as_string()) 367 368 # Forward messages to their recipients either wrapping the existing 369 # message, accompanying it or replacing it. 370 371 if forwarded_parts: 372 373 # Determine whether to wrap, accompany or replace the message. 374 375 prefs = self.get_preferences() 376 incoming = prefs.get("incoming", config.INCOMING_DEFAULT) 377 378 if incoming == "message-only": 379 messages = [msg] 380 else: 381 summary = self.messenger.make_summary_message(msg, forwarded_parts) 382 if incoming == "summary-then-message": 383 messages = [summary, msg] 384 elif incoming == "message-then-summary": 385 messages = [msg, summary] 386 elif incoming == "summary-only": 387 messages = [summary] 388 else: # incoming == "summary-wraps-message": 389 messages = [self.messenger.wrap_message(msg, forwarded_parts)] 390 391 for message in messages: 392 if self.debug: 393 print >>sys.stderr, "Forwarded parts..." 394 print message 395 elif self.messenger.local_delivery(): 396 self.messenger.sendmail([get_address(self.user)], message.as_string()) 397 398 # Unhandled messages are delivered as they are. 399 400 if not handled: 401 if self.debug: 402 print >>sys.stderr, "Unhandled parts..." 403 print msg 404 elif self.messenger.local_delivery(): 405 self.messenger.sendmail([get_address(self.user)], msg.as_string()) 406 407 def can_provide_freebusy(self, handlers): 408 409 "Test for any free/busy information produced by 'handlers'." 410 411 fbhandler = handlers.get("VFREEBUSY") 412 if fbhandler: 413 fbmethods = fbhandler.get_outgoing_methods() 414 return not "REPLY" in fbmethods and not "PUBLISH" in fbmethods 415 else: 416 return False 417 418 # vim: tabstop=4 expandtab shiftwidth=4