#!/usr/bin/env bash set -euo pipefail command -v python3 >/dev/null || { echo 'Python 3 is required. Setup stopped.'; exit 1; } python3 - <<'PYTHON' import email.message import email.utils import fcntl import getpass import json import os from pathlib import Path import pwd import re import secrets import shutil import socket import ssl import subprocess import sys import time DOMAIN = '345mail.net' ADDRESS = 'ray@345mail.net' VPS_IP = '153.79.252.128' STATE_DIR = Path('/root/345mail-setup') hidden_values = [] def stop(message): raise RuntimeError(message) def run(args, *, data=None, timeout=45): return subprocess.run(args, input=data, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, check=False) def safe(message): result = str(message) for value in hidden_values: for encoded in (value, repr(value)[1:-1], json.dumps(value)[1:-1]): result = result.replace(encoded, '[redacted]') return result def api_payload(raw): decoder = json.JSONDecoder() for match in re.finditer(r'\{', raw): try: value, _ = decoder.raw_decode(raw[match.start():]) except ValueError: continue if isinstance(value, dict): return value stop('Webuzo returned an unreadable response. Setup stopped.') def api(args, label): response = run([WEBUZO, *args], timeout=180) value = api_payload(response.stdout) error = value.get('error') or value.get('errors') if error: stop(label + ' failed. ' + safe(json.dumps(error, ensure_ascii=True))) if response.returncode: stop(label + ' failed with exit code ' + str(response.returncode)) return value def domain_owner(): path = Path('/etc/userdomains') if not path.exists(): return None for line in path.read_text().splitlines(): domain, separator, owner = line.partition(':') if separator and domain.strip().lower() == DOMAIN: return owner.strip() return None def save_state(value): temporary = STATE_DIR / 'state.new' fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'w') as handle: json.dump(value, handle) handle.flush() os.fsync(handle.fileno()) temporary.replace(STATE_DIR / 'state.json') def tls_check(hostname, port): try: with socket.create_connection(('127.0.0.1', port), timeout=5) as sock: with ssl.create_default_context().wrap_socket(sock, server_hostname=hostname): return True except (OSError, ssl.SSLError): return False try: if os.geteuid() != 0: stop('Run this from the VPS root prompt.') ip_tool = shutil.which('ip') if not ip_tool: stop('The ip utility is unavailable. Setup stopped.') interfaces = json.loads(run([ip_tool, '-j', '-4', 'address', 'show']).stdout) local_ips = {item.get('local') for interface in interfaces for item in interface.get('addr_info', [])} if VPS_IP not in local_ips: stop('This is not the expected VPS at ' + VPS_IP + '. Setup stopped.') WEBUZO = shutil.which('webuzo') DOVEADM = shutil.which('doveadm') EXIM = shutil.which('exim') or shutil.which('exim4') if not all((WEBUZO, DOVEADM, EXIM)): stop('Webuzo, Exim and doveadm must already be installed. Setup stopped.') if STATE_DIR.is_symlink(): stop('The setup directory is a symbolic link. Setup stopped.') STATE_DIR.mkdir(mode=0o700, exist_ok=True) os.chmod(STATE_DIR, 0o700) lock_fd = os.open(STATE_DIR / 'lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) state_path = STATE_DIR / 'state.json' if state_path.is_symlink(): stop('The saved setup state is a symbolic link. Setup stopped.') state = json.loads(state_path.read_text()) if state_path.exists() else {} if state.get('hosting_password'): hidden_values.append(state['hosting_password']) print('345 Mail setup on ' + VPS_IP, flush=True) owner = domain_owner() if not owner: try: pwd.getpwnam('mailadmin') except KeyError: pass else: stop('mailadmin already exists without a domain mapping. Review that account first.') password = state.get('hosting_password') or ('Aa9@' + secrets.token_hex(20)) hidden_values.append(password) state['hosting_password'] = password save_state(state) limits = { 'max_disk_limit': 4096, 'max_inode': 200000, 'max_bandwidth_limit': 20480, 'max_ftp_account': 1, 'max_email_account': 1, 'max_quota_email': 1024, 'max_database': 1, 'max_subdomain': 1, 'max_parked_domain': 1, 'max_addon_domain': 1, 'max_hourly_email': 100, 'max_percent_failed': 50, } args = ['--api', 'act=add_user', '--create_user=1', '--user=mailadmin', '--domain=' + DOMAIN, '--email=rdsokla@yahoo.com', '--user_passwd=' + password, '--cnf_user_passwd=' + password] args.extend('--' + key + '=' + str(value) for key, value in limits.items()) print('Adding the hosting account and domain...', flush=True) api(args, 'Hosting account creation') owner = domain_owner() if owner != 'mailadmin': stop('Webuzo has not confirmed the domain mapping. Setup stopped.') print('DOMAIN OK - ' + DOMAIN + ' belongs to ' + owner, flush=True) pwd.getpwnam(owner) mailbox = run([DOVEADM, 'user', ADDRESS]) if mailbox.returncode: print('Choose a mailbox password. Typing stays hidden.', flush=True) with open('/dev/tty', 'r+') as terminal: password = getpass.getpass('New mailbox password: ', stream=terminal) confirmation = getpass.getpass('Repeat mailbox password: ', stream=terminal) if password != confirmation: stop('The passwords differ. Run setup again to retry.') if len(password) < 12: stop('Use at least 12 characters. Run setup again to retry.') hidden_values.extend([password, confirmation]) print('Creating ' + ADDRESS + '...', flush=True) api(['--enduser-api', '--loginAs=' + owner, '--act=add_email_account', '--add=1', '--login=ray', '--domain=' + DOMAIN, '--newpass=' + password, '--conf=' + password, '--quota=limited', '--quota_limit=1024'], 'Mailbox creation') del password, confirmation if run([DOVEADM, 'user', ADDRESS]).returncode: stop('Dovecot cannot find the mailbox after creation. Setup stopped.') print('MAILBOX OK - ' + ADDRESS, flush=True) route = run([EXIM, '-bt', ADDRESS]) if route.returncode: stop('Local mail routing failed. ' + safe(route.stdout + route.stderr)[-1200:]) print('ROUTING OK', flush=True) message = email.message.EmailMessage() message['From'] = ADDRESS message['To'] = ADDRESS message['Subject'] = '345 Mail local delivery test' message['Date'] = email.utils.formatdate(localtime=True) message_id = email.utils.make_msgid(domain=DOMAIN) message['Message-ID'] = message_id message.set_content('This message verifies delivery into the local mailbox.') delivery = run([EXIM, '-i', '-odf', '-f', ADDRESS, ADDRESS], data=message.as_string()) if delivery.returncode: stop('Exim did not accept the local test message. ' + safe(delivery.stderr)[-800:]) delivered = False for attempt in range(6): found = run([DOVEADM, 'search', '-u', ADDRESS, 'HEADER', 'Message-ID', message_id]) if found.returncode == 0 and found.stdout.strip(): delivered = True break time.sleep(1) if not delivered: stop('The local test message was accepted but its arrival is unverified. Check the Exim queue.') print('LOCAL DELIVERY PASSED', flush=True) state['mailbox'] = ADDRESS state['local_delivery_verified_at'] = email.utils.formatdate(usegmt=True) save_state(state) secure_host = next((host for host in ('mail.345mail.net', 'server1.345mail.net') if tls_check(host, 993)), None) if secure_host: print('IMAP TLS PASSED - ' + secure_host + ' port 993', flush=True) else: print('IMAP TLS NEEDS ATTENTION - certificate verification did not pass.', flush=True) print('External sending, external receiving and app login still require verification.', flush=True) print('Setup result saved in /root/345mail-setup/state.json.', flush=True) except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as error: print('SETUP STOPPED - ' + safe(error), flush=True) sys.exit(1) PYTHON