Ejemplo n.º 1
0
	def apply_aliasing(self, user, mailfrom, rcpttos, msg):
		""" Applies an alias as the sender of a message or attempts to infer
		it if none was given by the sender.

		Handles cases 1d and 1e of the specification.
		"""
		usralias = None
		alias_addx = None
		is_alias_address = lambda entry: entry.parse_alias_address()

		logging.debug('Attempting to apply aliasing')

		# look for use of existing alias in To field (case 1d);
		for cur_addx in msg.search_header_addresses('to', is_alias_address):
			alias_pair = cur_addx.parse_alias_address()
			alias_data = self.db.get_alias_data(*alias_pair,	\
							    uid=user.get_uid())

			if not alias_data:
				continue

			usralias = Alias(**alias_data)
			alias_addx = cur_addx

			#if not usralias.is_active():
			#	continue

			# remove alias from rcpttos and all To fields
			for i in range(len(rcpttos)):
				if alias_addx == rcpttos[i]:
					del rcpttos[i]
					break

			msg.replace_address('to', alias_addx, None)
			break

		# if no alias in To field, try to infer the correct one (case 1e);
		if not alias_addx:

			logging.debug("Couldn't find alias to use in headers; " \
				      'attempting to infer correct alias')

			alias_data = self.db.infer_alias(user.get_uid(),
							 msg.get_header_addresses('to'),
							 user.get_salt())

			if not alias_data:
				logging.debug('Failed to infer alias')

				err = ErrorMessage('applyalias.noinfer',
						   fromaddx = self.cfg.SVCALIAS,
						   toaddx = user.get_account_address(),
						   subject = msg['Subject'])
	
				self.send(err['From'], [user.get_forwarding_address()], err)

				return False

			usralias = Alias(**alias_data)

			#if not usralias.is_active():
			#	return False

			logging.debug('Succesfully inferred alias "%s"', str(usralias))

			alias_addx = Address(usralias.get_alias_address())

		# if we found an alias to use, apply it, send the
		# message, and record in history table;
		alias_addx.realname = Address(mailfrom).realname

		msg.replace_address('from', None, alias_addx)
		#del msg['message-id']

		if rcpttos == []:
			logging.info('No recipients left; ignoring');
			return

		rcpt_aliases = []
		rcpt_nonaliases = []

		for entry in rcpttos:
			rcpt_addx = Address(entry)
			if rcpt_addx.is_servername():
				rcpt_aliases.append(entry)
			else:
				rcpt_nonaliases.append(entry)

		self.send(str(alias_addx), rcpt_nonaliases, msg)
		self.forward(str(alias_addx), rcpt_aliases, msg)

		self.db.add_history(usralias.get_rid(),
				    True,
				    address.getaddresses(rcpttos),
				    msg['Message-ID'],
				    user.get_salt())

		return
Ejemplo n.º 2
0
	def forward(self, mailfrom, rcpttos, msg):
		""" Handles Case 2, where email is not from a service user and so
		needs to be forwarded to various aliases.
		"""
		for rcpt in rcpttos:
			prcpt = Address(rcpt)
			alias_pair = prcpt.parse_alias_address()
			logging.debug(rcpt)
			if not alias_pair:
				# if the domain is SERVERNAME, sender screwed up; return error to sender...
				if prcpt.is_servername():
					logging.info('Encountered improperly formatted '
						     'address "%s" in recipients field', prcpt.address)

					# Create error response message
					err = ErrorMessage('forward.badformat',
							   fromaddx	= self.cfg.SVCALIAS,
							   toaddx	= mailfrom,
							   badalias	= prcpt.address)

					self.send(err['From'], [mailfrom], err)

				# ... otherwise ignore; not our job to send to non-users
				logging.info('Encountered recipient outside our domain; ignoring')

			else:
				alias_data = self.db.get_alias_data(*alias_pair)

				if alias_data:
					fwd_alias = Alias(**alias_data)

					userdata = self.db.get_user(uid=fwd_alias.get_uid())
					assert userdata is not None
					user = User(**userdata)

					logging.debug('is trusted? %s', fwd_alias.is_trusted())

					# handle trustedness here;
					if not fwd_alias.is_trusted():

						mfrom = Address(mailfrom)

						# if sender is in trusted group, then it's all right;
						if self.db.is_trusted_correspondent(mfrom,			\
										    user.get_salt(),		\
										    fwd_alias.get_rid(),	\
										    fwd_alias.get_trusted_timestamp()):
							pass # TODO: send/append something about newer alias to send to?

						else:
							capstat = self.db.get_capstat(mfrom,		\
										      user.get_salt(),	\
										      fwd_alias.get_rid())

							logging.debug('capstat=%s', capstat)

							if capstat < self.db.CAPTCHA_PENDING:
								logging.debug('captcha not yet sent; trying to send one')
								# If not approved, send captcha to sender and drop mail.
								# TODO: Perhaps we can cache the mail somewhere.
								cid = self.db.get_cid(mfrom, user.get_salt())
								self.send_captcha(mailfrom, cid, fwd_alias)
								#self.db.set_capstat(cid,
								#		    fwd_alias.get_rid(),
								#		    self.db.CAPTCHA_PENDING)
								logging.debug('done sending captcha')

							elif capstat == self.db.CAPTCHA_PENDING:
								logging.debug('captcha was already sent; still waiting for solution')

							elif capstat == self.db.CAPTCHA_APPROVED:
								logging.debug('captcha approved, but not yet user approved')
								# if user denied,
								# TODO: just ignore? or do something more?
								#	pass

								# if user judgement pending, send message
								# informing them they must wait for user's approval?
								if capstat == self.db.USER_PENDING:
									pass # TODO: send message

							return

					# TODO: can consult a whitelist/blacklist/etc. here

					fwd_addx = Address(user.get_forwarding_address())
					fwd_addx.realname = prcpt.realname

					logging.info('Found alias for account (%s) Forwarding message to %s', \
						      user.get_username(), fwd_addx.address)

					# Add hint as recipient name. The hint/domain is used as a reminder
					# to the user where this email address was originally created for.
					# But since we did not update Reply-To, it will drop off when the
					# user replies to the message.
					rcptaddr = Address(rcpt)

					if rcptaddr.get_realname() == '':
						if fwd_alias.get_hint() != None:
							rcptaddr.set_realname(fwd_alias.get_hint())

						elif fwd_alias.get_domain() != None:
							rcptaddr.set_realname(fwd_alias.get_domain())

						msg.replace_address('To', rcpt, rcptaddr)

					acct_addx = Address(user.get_account_address())
					acct_addx.realname = prcpt.realname

					#del msg['message-id']
					#del msg['DKIM-Signature']

					if 'To' in msg:
						msg.replace_header('To', msg['To'] + ', ' + str(acct_addx))

					if 'Reply-To' in msg:
						msg.replace_header('Reply-To', msg['reply-to'] + ', ' + rcpt);
					else:
						msg.add_header('Reply-To', mailfrom + ', ' + rcpt);

					if 'Message-ID' not in msg:
						msg.generate_message_id(self.cfg.DOMAIN)

					self.send(mailfrom, [str(fwd_addx)], msg)
					self.db.add_history(fwd_alias.get_rid(), False, [Address(mailfrom)], msg['Message-ID'], user.get_salt())

				else:
					logging.info("Couldn't find data for alias (%s,%d)", *alias_pair)

		return