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.content import handle_itip_part 24 from imiptools.data import get_addresses, get_uri 25 from imiptools.mail import Messenger 26 from imiptools.profile import Preferences 27 import sys 28 29 # Postfix exit codes. 30 31 EX_TEMPFAIL = 75 32 33 # Permitted iTIP content types. 34 35 itip_content_types = [ 36 "text/calendar", # from RFC 6047 37 "text/x-vcalendar", "application/ics", # other possibilities 38 ] 39 40 # Processing of incoming messages. 41 42 def get_all_values(msg, key): 43 l = [] 44 for v in msg.get_all(key) or []: 45 l += [s.strip() for s in v.split(",")] 46 return l 47 48 class Processor: 49 50 "The processing framework." 51 52 def __init__(self, handlers, messenger=None): 53 self.handlers = handlers 54 self.messenger = messenger or Messenger() 55 self.lmtp_socket = None 56 57 def process(self, f, original_recipients, recipients, outgoing_only): 58 59 """ 60 Process content from the stream 'f' accompanied by the given 61 'original_recipients' and 'recipients'. 62 """ 63 64 msg = message_from_file(f) 65 senders = get_addresses(msg.get_all("Reply-To") or msg.get_all("From") or []) 66 original_recipients = original_recipients or get_addresses(get_all_values(msg, "To") or []) 67 68 # Handle messages with iTIP parts. 69 70 for recipient in original_recipients: 71 self.process_for_recipient(msg, recipient, senders, outgoing_only) 72 73 def process_for_recipient(self, msg, recipient, senders, outgoing_only): 74 75 """ 76 Process the given 'msg' for a single 'recipient', having the given 77 'senders', and with the given 'outgoing_only' status. 78 79 Processing individually means that contributions to resulting messages 80 may be constructed according to individual preferences. 81 """ 82 83 all_responses = [] 84 handled = False 85 86 handlers = dict([(name, cls(senders, recipient, self.messenger)) for name, cls in self.handlers]) 87 88 for part in msg.walk(): 89 if part.get_content_type() in itip_content_types and \ 90 part.get_param("method"): 91 92 all_responses += handle_itip_part(part, handlers) 93 handled = True 94 95 # When processing outgoing messages, no replies or deliveries are 96 # performed. 97 98 if outgoing_only: 99 return 100 101 # Pack any returned parts into messages. 102 103 if all_responses: 104 outgoing_parts = {} 105 forwarded_parts = [] 106 107 for outgoing_recipients, part in all_responses: 108 if outgoing_recipients: 109 for outgoing_recipient in outgoing_recipients: 110 if not outgoing_parts.has_key(outgoing_recipient): 111 outgoing_parts[outgoing_recipient] = [] 112 outgoing_parts[outgoing_recipient].append(part) 113 else: 114 forwarded_parts.append(part) 115 116 # Reply using any outgoing parts in a new message. 117 118 if outgoing_parts: 119 for outgoing_recipient, parts in outgoing_parts.items(): 120 message = self.messenger.make_outgoing_message(parts, [outgoing_recipient]) 121 122 if "-d" in sys.argv: 123 print >>sys.stderr, "Outgoing parts for %s..." % outgoing_recipient 124 print message 125 else: 126 self.messenger.sendmail([outgoing_recipient], message.as_string()) 127 128 # Forward messages to their recipients either wrapping the existing 129 # message, accompanying it or replacing it. 130 131 if forwarded_parts: 132 133 # Determine whether to wrap, accompany or replace the message. 134 135 preferences = Preferences(get_uri(recipient)) 136 137 incoming = preferences.get("incoming") 138 139 if incoming == "message-only": 140 messages = [msg] 141 else: 142 summary = self.messenger.make_summary_message(msg, forwarded_parts) 143 if incoming == "summary-then-message": 144 messages = [summary, msg] 145 elif incoming == "message-then-summary": 146 messages = [msg, summary] 147 elif incoming == "summary-only": 148 messages = [summary] 149 else: # incoming == "summary-wraps-message": 150 messages = [self.messenger.wrap_message(msg, forwarded_parts)] 151 152 for message in messages: 153 if "-d" in sys.argv: 154 print >>sys.stderr, "Forwarded parts..." 155 print message 156 elif self.lmtp_socket: 157 self.messenger.sendmail(recipient, message.as_string(), lmtp_socket=self.lmtp_socket) 158 159 # Unhandled messages are delivered as they are. 160 161 if not handled: 162 if "-d" in sys.argv: 163 print >>sys.stderr, "Unhandled parts..." 164 print msg 165 elif self.lmtp_socket: 166 self.messenger.sendmail(recipient, msg.as_string(), lmtp_socket=self.lmtp_socket) 167 168 def process_args(self, args, stream): 169 170 """ 171 Interpret the given program arguments 'args' and process input from the 172 given 'stream'. 173 """ 174 175 # Obtain the different kinds of recipients plus sender address. 176 177 original_recipients = [] 178 recipients = [] 179 senders = [] 180 lmtp = [] 181 outgoing_only = False 182 183 l = [] 184 185 for arg in args: 186 187 # Detect outgoing processing mode. 188 189 if arg == "-O": 190 outgoing_only = True 191 192 # Switch to collecting recipients. 193 194 if arg == "-o": 195 l = original_recipients 196 elif arg == "-r": 197 l = recipients 198 199 # Switch to collecting senders. 200 201 elif arg == "-s": 202 l = senders 203 204 # Switch to getting the LMTP socket. 205 206 elif arg == "-l": 207 l = lmtp 208 209 # Ignore debugging options. 210 211 elif arg == "-d": 212 pass 213 else: 214 l.append(arg) 215 216 self.messenger.sender = senders and senders[0] or self.messenger.sender 217 self.lmtp_socket = lmtp and lmtp[0] or None 218 self.process(stream, original_recipients, recipients, outgoing_only) 219 220 def __call__(self): 221 222 """ 223 Obtain arguments from the command line to initialise the processor 224 before invoking it. 225 """ 226 227 args = sys.argv[1:] 228 229 if "-d" in args: 230 self.process_args(args, sys.stdin) 231 else: 232 try: 233 self.process_args(args, sys.stdin) 234 except SystemExit, value: 235 sys.exit(value) 236 except Exception, exc: 237 if "-v" in args: 238 raise 239 type, value, tb = sys.exc_info() 240 print >>sys.stderr, "Exception %s at %d" % (exc, tb.tb_lineno) 241 #import traceback 242 #traceback.print_exc(file=open("/tmp/mail.log", "a")) 243 sys.exit(EX_TEMPFAIL) 244 sys.exit(0) 245 246 # vim: tabstop=4 expandtab shiftwidth=4