django-orchestra-test/orchestra/apps/mails/backends.py

191 lines
7.0 KiB
Python
Raw Normal View History

import textwrap
2014-08-22 15:31:44 +00:00
import os
2014-10-06 14:57:02 +00:00
from django.core.exceptions import ObjectDoesNotExist
2014-08-22 15:31:44 +00:00
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from orchestra.apps.orchestration import ServiceController
from orchestra.apps.resources import ServiceMonitor
from . import settings
2014-09-26 15:05:20 +00:00
from .models import Address
2014-08-22 15:31:44 +00:00
2014-10-06 14:57:02 +00:00
# TODO http://wiki2.dovecot.org/HowTo/SimpleVirtualInstall
# TODO http://wiki2.dovecot.org/HowTo/VirtualUserFlatFilesPostfix
# TODO Set first/last_valid_uid/gid settings to contain only the range actually used by mail processes
# TODO Insert "/./" inside the returned home directory, eg.: home=/home/./user to chroot into /home, or home=/home/user/./ to chroot into /home/user.
# TODO mount the filesystem with "nosuid" option
2014-08-22 15:31:44 +00:00
2014-10-06 14:57:02 +00:00
class PasswdVirtualUserBackend(ServiceController):
verbose_name = _("Mail virtual user (passwd-file)")
2014-09-23 11:13:50 +00:00
model = 'mails.Mailbox'
2014-09-30 14:46:29 +00:00
# TODO related_models = ('resources__content_type') ?? needed for updating disk usage from resource.data
2014-08-22 15:31:44 +00:00
DEFAULT_GROUP = 'postfix'
2014-10-06 14:57:02 +00:00
def set_user(self, context):
self.append(textwrap.dedent("""
if [[ $( grep "^%(username)s:" %(passwd_path)s ) ]]; then
2014-10-07 13:08:59 +00:00
sed -i 's#^%(username)s:.*#%(passwd)s#' %(passwd_path)s
else
2014-10-06 14:57:02 +00:00
echo '%(passwd)s' >> %(passwd_path)s
fi""" % context
))
2014-08-22 15:31:44 +00:00
self.append("mkdir -p %(home)s" % context)
2014-10-06 14:57:02 +00:00
self.append("chown %(uid)s.%(gid)s %(home)s" % context)
2014-08-22 15:31:44 +00:00
def generate_filter(self, mailbox, context):
now = timezone.now().strftime("%B %d, %Y, %H:%M")
context['filtering'] = (
"# Sieve Filter\n"
"# Generated by Orchestra %s\n\n" % now
)
2014-09-30 14:46:29 +00:00
if mailbox.custom_filtering:
2014-08-22 15:31:44 +00:00
context['filtering'] += mailbox.custom_filtering
else:
2014-10-06 14:57:02 +00:00
context['filtering'] += settings.MAILS_DEFAUL_FILTERING
2014-08-22 15:31:44 +00:00
context['filter_path'] = os.path.join(context['home'], '.orchestra.sieve')
self.append("echo '%(filtering)s' > %(filter_path)s" % context)
def save(self, mailbox):
context = self.get_context(mailbox)
2014-10-06 14:57:02 +00:00
self.set_user(context)
2014-08-22 15:31:44 +00:00
self.generate_filter(mailbox, context)
def delete(self, mailbox):
context = self.get_context(mailbox)
2014-10-06 14:57:02 +00:00
self.append("{ sleep 2 && killall -u %(uid)s -s KILL; } &" % context)
2014-10-07 13:08:59 +00:00
self.append("killall -u %(uid)s || true" % context)
2014-10-06 14:57:02 +00:00
self.append("sed -i '/^%(username)s:.*/d' %(passwd_path)s" % context)
2014-10-07 13:08:59 +00:00
# TODO delete
context['deleted'] = context['home'].rstrip('/') + '.deleted'
self.append("mv %(home)s %(deleted)s" % context)
2014-08-22 15:31:44 +00:00
2014-10-06 14:57:02 +00:00
def get_extra_fields(self, mailbox, context):
context['quota'] = self.get_quota(mailbox)
return 'userdb_mail=maildir:~/Maildir {quota}'.format(**context)
def get_quota(self, mailbox):
try:
quota = mailbox.resources.disk.allocated
except (AttributeError, ObjectDoesNotExist):
return ''
unit = mailbox.resources.disk.unit[0].upper()
return 'userdb_quota_rule=*:bytes=%i%s' % (quota, unit)
2014-08-22 15:31:44 +00:00
def get_context(self, mailbox):
context = {
2014-09-30 14:46:29 +00:00
'name': mailbox.name,
2014-09-29 12:22:45 +00:00
'username': mailbox.name,
2014-10-06 14:57:02 +00:00
'password': mailbox.password if mailbox.active else '*%s' % mailbox.password,
'uid': 10000 + mailbox.pk,
'gid': 10000 + mailbox.pk,
'group': self.DEFAULT_GROUP,
'quota': self.get_quota(mailbox),
'passwd_path': settings.MAILS_PASSWD_PATH,
'home': mailbox.get_home(),
2014-08-22 15:31:44 +00:00
}
2014-10-06 14:57:02 +00:00
context['extra_fields'] = self.get_extra_fields(mailbox, context)
context['passwd'] = '{username}:{password}:{uid}:{gid}:,,,:{home}:{extra_fields}'.format(**context)
2014-08-22 15:31:44 +00:00
return context
class PostfixAddressBackend(ServiceController):
verbose_name = _("Postfix address")
2014-09-23 11:13:50 +00:00
model = 'mails.Address'
2014-08-22 15:31:44 +00:00
def include_virtdomain(self, context):
self.append(
'[[ $(grep "^\s*%(domain)s\s*$" %(virtdomains)s) ]]'
2014-10-06 14:57:02 +00:00
' || { echo "%(domain)s" >> %(virtdomains)s; UPDATED_VIRTDOMAINS=1; }' % context
2014-08-22 15:31:44 +00:00
)
def exclude_virtdomain(self, context):
domain = context['domain']
if not Address.objects.filter(domain=domain).exists():
self.append('sed -i "s/^%(domain)s//" %(virtdomains)s' % context)
def update_virtusertable(self, context):
2014-10-06 14:57:02 +00:00
self.append(textwrap.dedent("""
LINE="%(email)s\t%(destination)s"
if [[ ! $(grep "^%(email)s\s" %(virtusertable)s) ]]; then
2014-10-06 14:57:02 +00:00
echo "${LINE}" >> %(virtusertable)s
UPDATED_VIRTUSERTABLE=1
else
if [[ ! $(grep "^${LINE}$" %(virtusertable)s) ]]; then
sed -i "s/^%(email)s\s.*$/${LINE}/" %(virtusertable)s
2014-10-06 14:57:02 +00:00
UPDATED_VIRTUSERTABLE=1
fi
fi""" % context
))
2014-08-22 15:31:44 +00:00
def exclude_virtusertable(self, context):
2014-10-06 14:57:02 +00:00
self.append(textwrap.dedent("""
if [[ $(grep "^%(email)s\s") ]]; then
sed -i "s/^%(email)s\s.*$//" %(virtusertable)s
UPDATED=1
fi"""
))
2014-08-22 15:31:44 +00:00
def save(self, address):
context = self.get_context(address)
self.include_virtdomain(context)
self.update_virtusertable(context)
def delete(self, address):
context = self.get_context(address)
self.exclude_virtdomain(context)
self.exclude_virtusertable(context)
def commit(self):
context = self.get_context_files()
2014-10-06 14:57:02 +00:00
self.append(textwrap.dedent("""
[[ $UPDATED_VIRTUSERTABLE == 1 ]] && { postmap %(virtusertable)s; }
# TODO not sure if always needed
[[ $UPDATED_VIRTDOMAINS == 1 ]] && { /etc/init.d/postfix reload; }
""" % context
))
2014-08-22 15:31:44 +00:00
def get_context_files(self):
return {
2014-10-06 14:57:02 +00:00
'virtdomains': settings.MAILS_VIRTDOMAINS_PATH,
'virtusertable': settings.MAILS_VIRTUSERTABLE_PATH,
2014-08-22 15:31:44 +00:00
}
def get_context(self, address):
context = self.get_context_files()
context.update({
'domain': address.domain,
'email': address.email,
'destination': address.destination,
})
return context
class AutoresponseBackend(ServiceController):
verbose_name = _("Mail autoresponse")
model = 'mail.Autoresponse'
class MaildirDisk(ServiceMonitor):
2014-09-23 11:13:50 +00:00
model = 'mails.Mailbox'
2014-08-22 15:31:44 +00:00
resource = ServiceMonitor.DISK
verbose_name = _("Maildir disk usage")
def monitor(self, mailbox):
context = self.get_context(mailbox)
self.append(
"SIZE=$(sed -n '2p' %(maildir_path)s | cut -d' ' -f1)\n"
"echo %(object_id)s ${SIZE:-0}" % context
)
def get_context(self, mailbox):
2014-09-26 15:05:20 +00:00
context = MailSystemUserBackend().get_context(mailbox)
2014-10-06 14:57:02 +00:00
context.update({
'rr_path': os.path.join(context['home'], 'Maildir/maildirsize'),
'object_id': mailbox.pk
})
2014-08-22 15:31:44 +00:00
return context