utils.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import os.path
  2. CONF_DIR = os.path.join(os.path.dirname(__file__), "../conf")
  3. def load_environment():
  4. # Load settings from /etc/mailinabox.conf.
  5. return load_env_vars_from_file("/etc/mailinabox.conf")
  6. def load_env_vars_from_file(fn):
  7. # Load settings from a KEY=VALUE file.
  8. import collections
  9. env = collections.OrderedDict()
  10. for line in open(fn): env.setdefault(*line.strip().split("=", 1))
  11. return env
  12. def save_environment(env):
  13. with open("/etc/mailinabox.conf", "w") as f:
  14. for k, v in env.items():
  15. f.write("%s=%s\n" % (k, v))
  16. def safe_domain_name(name):
  17. # Sanitize a domain name so it is safe to use as a file name on disk.
  18. import urllib.parse
  19. return urllib.parse.quote(name, safe='')
  20. def sort_domains(domain_names, env):
  21. # Put domain names in a nice sorted order. For web_update, PRIMARY_HOSTNAME
  22. # must appear first so it becomes the nginx default server.
  23. # First group PRIMARY_HOSTNAME and its subdomains, then parent domains of PRIMARY_HOSTNAME, then other domains.
  24. groups = ( [], [], [] )
  25. for d in domain_names:
  26. if d == env['PRIMARY_HOSTNAME'] or d.endswith("." + env['PRIMARY_HOSTNAME']):
  27. groups[0].append(d)
  28. elif env['PRIMARY_HOSTNAME'].endswith("." + d):
  29. groups[1].append(d)
  30. else:
  31. groups[2].append(d)
  32. # Within each group, sort parent domains before subdomains and after that sort lexicographically.
  33. def sort_group(group):
  34. # Find the top-most domains.
  35. top_domains = sorted(d for d in group if len([s for s in group if d.endswith("." + s)]) == 0)
  36. ret = []
  37. for d in top_domains:
  38. ret.append(d)
  39. ret.extend( sort_group([s for s in group if s.endswith("." + d)]) )
  40. return ret
  41. groups = [sort_group(g) for g in groups]
  42. return groups[0] + groups[1] + groups[2]
  43. def sort_email_addresses(email_addresses, env):
  44. email_addresses = set(email_addresses)
  45. domains = set(email.split("@", 1)[1] for email in email_addresses if "@" in email)
  46. ret = []
  47. for domain in sort_domains(domains, env):
  48. domain_emails = set(email for email in email_addresses if email.endswith("@" + domain))
  49. ret.extend(sorted(domain_emails))
  50. email_addresses -= domain_emails
  51. ret.extend(sorted(email_addresses)) # whatever is left
  52. return ret
  53. def exclusive_process(name):
  54. # Ensure that a process named `name` does not execute multiple
  55. # times concurrently.
  56. import os, sys, atexit
  57. pidfile = '/var/run/mailinabox-%s.pid' % name
  58. mypid = os.getpid()
  59. # Attempt to get a lock on ourself so that the concurrency check
  60. # itself is not executed in parallel.
  61. with open(__file__, 'r+') as flock:
  62. # Try to get a lock. This blocks until a lock is acquired. The
  63. # lock is held until the flock file is closed at the end of the
  64. # with block.
  65. os.lockf(flock.fileno(), os.F_LOCK, 0)
  66. # While we have a lock, look at the pid file. First attempt
  67. # to write our pid to a pidfile if no file already exists there.
  68. try:
  69. with open(pidfile, 'x') as f:
  70. # Successfully opened a new file. Since the file is new
  71. # there is no concurrent process. Write our pid.
  72. f.write(str(mypid))
  73. atexit.register(clear_my_pid, pidfile)
  74. return
  75. except FileExistsError:
  76. # The pid file already exixts, but it may contain a stale
  77. # pid of a terminated process.
  78. with open(pidfile, 'r+') as f:
  79. # Read the pid in the file.
  80. existing_pid = None
  81. try:
  82. existing_pid = int(f.read().strip())
  83. except ValueError:
  84. pass # No valid integer in the file.
  85. # Check if the pid in it is valid.
  86. if existing_pid:
  87. if is_pid_valid(existing_pid):
  88. print("Another %s is already running (pid %d)." % (name, existing_pid), file=sys.stderr)
  89. sys.exit(1)
  90. # Write our pid.
  91. f.seek(0)
  92. f.write(str(mypid))
  93. f.truncate()
  94. atexit.register(clear_my_pid, pidfile)
  95. def clear_my_pid(pidfile):
  96. import os
  97. os.unlink(pidfile)
  98. def is_pid_valid(pid):
  99. """Checks whether a pid is a valid process ID of a currently running process."""
  100. # adapted from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
  101. import os, errno
  102. if pid <= 0: raise ValueError('Invalid PID.')
  103. try:
  104. os.kill(pid, 0)
  105. except OSError as err:
  106. if err.errno == errno.ESRCH: # No such process
  107. return False
  108. elif err.errno == errno.EPERM: # Not permitted to send signal
  109. return True
  110. else: # EINVAL
  111. raise
  112. else:
  113. return True
  114. def shell(method, cmd_args, env={}, capture_stderr=False, return_bytes=False, trap=False, input=None):
  115. # A safe way to execute processes.
  116. # Some processes like apt-get require being given a sane PATH.
  117. import subprocess
  118. env.update({ "PATH": "/sbin:/bin:/usr/sbin:/usr/bin" })
  119. kwargs = {
  120. 'env': env,
  121. 'stderr': None if not capture_stderr else subprocess.STDOUT,
  122. }
  123. if method == "check_output" and input is not None:
  124. kwargs['input'] = input
  125. if not trap:
  126. ret = getattr(subprocess, method)(cmd_args, **kwargs)
  127. else:
  128. try:
  129. ret = getattr(subprocess, method)(cmd_args, **kwargs)
  130. code = 0
  131. except subprocess.CalledProcessError as e:
  132. ret = e.output
  133. code = e.returncode
  134. if not return_bytes and isinstance(ret, bytes): ret = ret.decode("utf8")
  135. if not trap:
  136. return ret
  137. else:
  138. return code, ret
  139. def create_syslog_handler():
  140. import logging.handlers
  141. handler = logging.handlers.SysLogHandler(address='/dev/log')
  142. handler.setLevel(logging.WARNING)
  143. return handler