def setup_function(function): global maindomain maindomain = _get_maindomain() assert backup_test_dependencies_are_met() clean_tmp_backup_directory() reset_ssowat_conf() delete_all_backups() uninstall_test_apps_if_needed() assert len(backup_list()["archives"]) == 0 markers = { m.name: { 'args': m.args, 'kwargs': m.kwargs } for m in function.__dict__.get("pytestmark", []) } if "with_wordpress_archive_from_2p4" in markers: add_archive_wordpress_from_2p4() assert len(backup_list()["archives"]) == 1 if "with_legacy_app_installed" in markers: assert not app_is_installed("legacy_app") install_app("legacy_app_ynh", "/yolo") assert app_is_installed("legacy_app") if "with_backup_recommended_app_installed" in markers: assert not app_is_installed("backup_recommended_app") install_app("backup_recommended_app_ynh", "/yolo", "&helper_to_test=ynh_restore_file") assert app_is_installed("backup_recommended_app") if "with_backup_recommended_app_installed_with_ynh_restore" in markers: assert not app_is_installed("backup_recommended_app") install_app("backup_recommended_app_ynh", "/yolo", "&helper_to_test=ynh_restore") assert app_is_installed("backup_recommended_app") if "with_system_archive_from_2p4" in markers: add_archive_system_from_2p4() assert len(backup_list()["archives"]) == 1 if "with_permission_app_installed" in markers: assert not app_is_installed("permissions_app") user_create("alice", "Alice", "White", maindomain, "test123Ynh") install_app("permissions_app_ynh", "/urlpermissionapp" "&admin=alice") assert app_is_installed("permissions_app") if "with_custom_domain" in markers: domain = markers['with_custom_domain']['args'][0] if domain not in domain_list()['domains']: domain_add(domain)
def test_add_domain_conf_already_exists(): os.system("echo ' ' >> %s" % TEST_DOMAIN_NGINX_CONFIG) domain_add(TEST_DOMAIN) assert os.path.exists(TEST_DOMAIN_NGINX_CONFIG) assert TEST_DOMAIN_NGINX_CONFIG in _get_conf_hashes("nginx") assert TEST_DOMAIN_NGINX_CONFIG not in manually_modified_files()
def test_add_domain(): domain_add(TEST_DOMAIN) assert TEST_DOMAIN in domain_list()["domains"] assert os.path.exists(TEST_DOMAIN_NGINX_CONFIG) assert TEST_DOMAIN_NGINX_CONFIG in _get_conf_hashes("nginx") assert TEST_DOMAIN_NGINX_CONFIG not in manually_modified_files()
def tools_maindomain(auth, old_domain=None, new_domain=None, dyndns=False): """ Main domain change tool Keyword argument: new_domain old_domain """ if not old_domain: with open('/etc/yunohost/current_host', 'r') as f: old_domain = f.readline().rstrip() if not new_domain: return {'current_main_domain': old_domain} if not new_domain: raise MoulinetteError(errno.EINVAL, m18n.n('new_domain_required')) if new_domain not in domain_list(auth)['domains']: domain_add(auth, new_domain) os.system('rm /etc/ssl/private/yunohost_key.pem') os.system('rm /etc/ssl/certs/yunohost_crt.pem') command_list = [ 'ln -s /etc/yunohost/certs/%s/key.pem /etc/ssl/private/yunohost_key.pem' % new_domain, 'ln -s /etc/yunohost/certs/%s/crt.pem /etc/ssl/certs/yunohost_crt.pem' % new_domain, 'echo %s > /etc/yunohost/current_host' % new_domain, ] for command in command_list: if os.system(command) != 0: raise MoulinetteError(errno.EPERM, m18n.n('maindomain_change_failed')) if dyndns and len(new_domain.split('.')) >= 3: try: r = requests.get('https://dyndns.yunohost.org/domains') except requests.ConnectionError: pass else: dyndomains = json.loads(r.text) dyndomain = '.'.join(new_domain.split('.')[1:]) if dyndomain in dyndomains: dyndns_subscribe(domain=new_domain) try: with open('/etc/yunohost/installed', 'r') as f: service_regen_conf() except IOError: pass logger.success(m18n.n('maindomain_changed'))
def secondary_domain(request): if "example.test" not in domain_list()["domains"]: domain_add("example.test") def remove_example_domain(): domain_remove("example.test") request.addfinalizer(remove_example_domain) return "example.test"
def tools_maindomain(auth, old_domain=None, new_domain=None, dyndns=False): """ Main domain change tool Keyword argument: new_domain old_domain """ if not old_domain: with open('/etc/yunohost/current_host', 'r') as f: old_domain = f.readline().rstrip() if not new_domain: return { 'current_main_domain': old_domain } if not new_domain: raise MoulinetteError(errno.EINVAL, m18n.n('new_domain_required')) if new_domain not in domain_list(auth)['domains']: domain_add(auth, new_domain) os.system('rm /etc/ssl/private/yunohost_key.pem') os.system('rm /etc/ssl/certs/yunohost_crt.pem') command_list = [ 'ln -s /etc/yunohost/certs/%s/key.pem /etc/ssl/private/yunohost_key.pem' % new_domain, 'ln -s /etc/yunohost/certs/%s/crt.pem /etc/ssl/certs/yunohost_crt.pem' % new_domain, 'echo %s > /etc/yunohost/current_host' % new_domain, ] for command in command_list: if os.system(command) != 0: raise MoulinetteError(errno.EPERM, m18n.n('maindomain_change_failed')) if dyndns and len(new_domain.split('.')) >= 3: try: r = requests.get('https://dyndns.yunohost.org/domains') except requests.ConnectionError: pass else: dyndomains = json.loads(r.text) dyndomain = '.'.join(new_domain.split('.')[1:]) if dyndomain in dyndomains: dyndns_subscribe(domain=new_domain) try: with open('/etc/yunohost/installed', 'r') as f: service_regen_conf() except IOError: pass logger.success(m18n.n('maindomain_changed'))
def test_stale_hashes_get_removed_if_empty(): """ This is intended to test that if a file gets removed and is indeed removed, we don't keep a useless empty hash corresponding to an old file. In this case, we test this using the dnsmasq conf file (we don't do this using the nginx conf file because it's already force-removed during domain_remove()) """ domain_add(TEST_DOMAIN) assert os.path.exists(TEST_DOMAIN_DNSMASQ_CONFIG) assert TEST_DOMAIN_DNSMASQ_CONFIG in _get_conf_hashes("dnsmasq") domain_remove(TEST_DOMAIN) assert not os.path.exists(TEST_DOMAIN_DNSMASQ_CONFIG) assert TEST_DOMAIN_DNSMASQ_CONFIG not in _get_conf_hashes("dnsmasq")
def test_stale_hashes_if_file_manually_deleted(): """ Same as other test, but manually delete the file in between and check behavior """ domain_add(TEST_DOMAIN) assert os.path.exists(TEST_DOMAIN_DNSMASQ_CONFIG) assert TEST_DOMAIN_DNSMASQ_CONFIG in _get_conf_hashes("dnsmasq") os.remove(TEST_DOMAIN_DNSMASQ_CONFIG) assert not os.path.exists(TEST_DOMAIN_DNSMASQ_CONFIG) regen_conf(names=["dnsmasq"]) assert not os.path.exists(TEST_DOMAIN_DNSMASQ_CONFIG) assert TEST_DOMAIN_DNSMASQ_CONFIG in _get_conf_hashes("dnsmasq") domain_remove(TEST_DOMAIN) assert not os.path.exists(TEST_DOMAIN_DNSMASQ_CONFIG) assert TEST_DOMAIN_DNSMASQ_CONFIG not in _get_conf_hashes("dnsmasq")
def tools_postinstall( operation_logger, domain, password, ignore_dyndns=False, force_password=False, force_diskspace=False, ): """ YunoHost post-install Keyword argument: domain -- YunoHost main domain ignore_dyndns -- Do not subscribe domain to a DynDNS service (only needed for nohost.me, noho.st domains) password -- YunoHost admin password """ from yunohost.utils.password import assert_password_is_strong_enough from yunohost.domain import domain_main_domain import psutil dyndns_provider = "dyndns.yunohost.org" # Do some checks at first if os.path.isfile("/etc/yunohost/installed"): raise YunohostValidationError("yunohost_already_installed") if os.path.isdir( "/etc/yunohost/apps") and os.listdir("/etc/yunohost/apps") != []: raise YunohostValidationError( "It looks like you're trying to re-postinstall a system that was already working previously ... If you recently had some bug or issues with your installation, please first discuss with the team on how to fix the situation instead of savagely re-running the postinstall ...", raw_msg=True, ) # Check there's at least 10 GB on the rootfs... disk_partitions = sorted(psutil.disk_partitions(), key=lambda k: k.mountpoint) main_disk_partitions = [ d for d in disk_partitions if d.mountpoint in ["/", "/var"] ] main_space = sum( [psutil.disk_usage(d.mountpoint).total for d in main_disk_partitions]) GB = 1024**3 if not force_diskspace and main_space < 10 * GB: raise YunohostValidationError("postinstall_low_rootfsspace") # Check password if not force_password: assert_password_is_strong_enough("admin", password) if not ignore_dyndns: # Check if yunohost dyndns can handle the given domain # (i.e. is it a .nohost.me ? a .noho.st ?) try: is_nohostme_or_nohost = _dyndns_provides(dyndns_provider, domain) # If an exception is thrown, most likely we don't have internet # connectivity or something. Assume that this domain isn't manageable # and inform the user that we could not contact the dyndns host server. except Exception: logger.warning( m18n.n("dyndns_provider_unreachable", provider=dyndns_provider)) is_nohostme_or_nohost = False # If this is a nohost.me/noho.st, actually check for availability if is_nohostme_or_nohost: # (Except if the user explicitly said he/she doesn't care about dyndns) if ignore_dyndns: dyndns = False # Check if the domain is available... elif _dyndns_available(dyndns_provider, domain): dyndns = True # If not, abort the postinstall else: raise YunohostValidationError("dyndns_unavailable", domain=domain) else: dyndns = False else: dyndns = False if os.system("iptables -V >/dev/null 2>/dev/null") != 0: raise YunohostValidationError( "iptables/nftables does not seems to be working on your setup. You may be in a container or your kernel does have the proper modules loaded. Sometimes, rebooting the machine may solve the issue.", raw_msg=True, ) operation_logger.start() logger.info(m18n.n("yunohost_installing")) # New domain config domain_add(domain, dyndns) domain_main_domain(domain) # Change LDAP admin password tools_adminpw(password, check_strength=not force_password) # Enable UPnP silently and reload firewall firewall_upnp("enable", no_refresh=True) # Initialize the apps catalog system _initialize_apps_catalog_system() # Try to update the apps catalog ... # we don't fail miserably if this fails, # because that could be for example an offline installation... try: _update_apps_catalog() except Exception as e: logger.warning(str(e)) # Init migrations (skip them, no need to run them on a fresh system) _skip_all_migrations() os.system("touch /etc/yunohost/installed") # Enable and start YunoHost firewall at boot time service_enable("yunohost-firewall") service_start("yunohost-firewall") regen_conf(names=["ssh"], force=True) # Restore original ssh conf, as chosen by the # admin during the initial install # # c.f. the install script and in particular # https://github.com/YunoHost/install_script/pull/50 # The user can now choose during the install to keep # the initial, existing sshd configuration # instead of YunoHost's recommended conf # original_sshd_conf = "/etc/ssh/sshd_config.before_yunohost" if os.path.exists(original_sshd_conf): os.rename(original_sshd_conf, "/etc/ssh/sshd_config") regen_conf(force=True) logger.success(m18n.n("yunohost_configured")) logger.warning(m18n.n("yunohost_postinstall_end_tip"))
def setup_function(function): clean_user_groups_permission() global maindomain global other_domains maindomain = _get_maindomain() markers = { m.name: { 'args': m.args, 'kwargs': m.kwargs } for m in function.__dict__.get("pytestmark", []) } if "other_domains" in markers: other_domains = [ "domain_%s.dev" % string.ascii_lowercase[number] for number in range(markers['other_domains']['kwargs']['number']) ] for domain in other_domains: if domain not in domain_list()['domains']: domain_add(domain) # Dirty patch of DNS resolution. Force the DNS to 127.0.0.1 address even if dnsmasq have the public address. # Mainly used for 'can_access_webpage' function dns_cache = {(maindomain, 443, 0, 1): [(2, 1, 6, '', ('127.0.0.1', 443))]} for domain in other_domains: dns_cache[(domain, 443, 0, 1)] = [(2, 1, 6, '', ('127.0.0.1', 443))] def new_getaddrinfo(*args): try: return dns_cache[args] except KeyError: res = prv_getaddrinfo(*args) dns_cache[args] = res return res socket.getaddrinfo = new_getaddrinfo user_create("alice", "Alice", "White", maindomain, dummy_password) user_create("bob", "Bob", "Snow", maindomain, dummy_password) _permission_create_with_dummy_app( permission="wiki.main", url="/", additional_urls=['/whatever', '/idontnow'], auth_header=False, label="Wiki", show_tile=True, allowed=["all_users"], protected=False, sync_perm=False, domain=maindomain, path='/wiki') _permission_create_with_dummy_app(permission="blog.main", url="/", auth_header=True, show_tile=False, protected=False, sync_perm=False, allowed=["alice"], domain=maindomain, path='/blog') _permission_create_with_dummy_app(permission="blog.api", allowed=["visitors"], protected=True, sync_perm=True)
def tools_postinstall(domain, password, ignore_dyndns=False): """ YunoHost post-install Keyword argument: domain -- YunoHost main domain ignore_dyndns -- Do not subscribe domain to a DynDNS service (only needed for nohost.me, noho.st domains) password -- YunoHost admin password """ dyndns = not ignore_dyndns # Do some checks at first if os.path.isfile('/etc/yunohost/installed'): raise MoulinetteError(errno.EPERM, m18n.n('yunohost_already_installed')) if len(domain.split('.')) >= 3 and not ignore_dyndns: try: r = requests.get('https://dyndns.yunohost.org/domains') except requests.ConnectionError: pass else: dyndomains = json.loads(r.text) dyndomain = '.'.join(domain.split('.')[1:]) if dyndomain in dyndomains: if requests.get('https://dyndns.yunohost.org/test/%s' % domain).status_code == 200: dyndns = True else: raise MoulinetteError(errno.EEXIST, m18n.n('dyndns_unavailable')) else: dyndns = False else: dyndns = False logger.info(m18n.n('yunohost_installing')) # Initialize LDAP for YunoHost # TODO: Improve this part by integrate ldapinit into conf_regen hook auth = tools_ldapinit() # Create required folders folders_to_create = [ '/etc/yunohost/apps', '/etc/yunohost/certs', '/var/cache/yunohost/repo', '/home/yunohost.backup', '/home/yunohost.app' ] for folder in folders_to_create: try: os.listdir(folder) except OSError: os.makedirs(folder) # Change folders permissions os.system('chmod 755 /home/yunohost.app') # Set hostname to avoid amavis bug if os.system('hostname -d') != 0: os.system('hostname yunohost.yunohost.org') # Add a temporary SSOwat rule to redirect SSO to admin page try: with open('/etc/ssowat/conf.json.persistent') as json_conf: ssowat_conf = json.loads(str(json_conf.read())) except ValueError as e: raise MoulinetteError( errno.EINVAL, m18n.n('ssowat_persistent_conf_read_error', error=e.strerror)) except IOError: ssowat_conf = {} if 'redirected_urls' not in ssowat_conf: ssowat_conf['redirected_urls'] = {} ssowat_conf['redirected_urls']['/'] = domain + '/yunohost/admin' try: with open('/etc/ssowat/conf.json.persistent', 'w+') as f: json.dump(ssowat_conf, f, sort_keys=True, indent=4) except IOError as e: raise MoulinetteError( errno.EPERM, m18n.n('ssowat_persistent_conf_write_error', error=e.strerror)) os.system('chmod 644 /etc/ssowat/conf.json.persistent') # Create SSL CA service_regen_conf(['ssl'], force=True) ssl_dir = '/usr/share/yunohost/yunohost-config/ssl/yunoCA' command_list = [ 'echo "01" > %s/serial' % ssl_dir, 'rm %s/index.txt' % ssl_dir, 'touch %s/index.txt' % ssl_dir, 'cp %s/openssl.cnf %s/openssl.ca.cnf' % (ssl_dir, ssl_dir), 'sed -i "s/yunohost.org/%s/g" %s/openssl.ca.cnf ' % (domain, ssl_dir), 'openssl req -x509 -new -config %s/openssl.ca.cnf -days 3650 -out %s/ca/cacert.pem -keyout %s/ca/cakey.pem -nodes -batch' % (ssl_dir, ssl_dir, ssl_dir), 'cp %s/ca/cacert.pem /etc/ssl/certs/ca-yunohost_crt.pem' % ssl_dir, 'update-ca-certificates' ] for command in command_list: if os.system(command) != 0: raise MoulinetteError(errno.EPERM, m18n.n('yunohost_ca_creation_failed')) # New domain config domain_add(auth, domain, dyndns) tools_maindomain(auth, domain) # Generate SSOwat configuration file app_ssowatconf(auth) # Change LDAP admin password tools_adminpw(auth, password) # Enable UPnP silently and reload firewall firewall_upnp('enable', no_refresh=True) os.system('touch /etc/yunohost/installed') # Enable and start YunoHost firewall at boot time os.system('update-rc.d yunohost-firewall enable') os.system('service yunohost-firewall start') service_regen_conf(force=True) logger.success(m18n.n('yunohost_configured'))
def tools_postinstall(operation_logger, domain, password, ignore_dyndns=False, force_password=False): """ YunoHost post-install Keyword argument: domain -- YunoHost main domain ignore_dyndns -- Do not subscribe domain to a DynDNS service (only needed for nohost.me, noho.st domains) password -- YunoHost admin password """ from yunohost.utils.password import assert_password_is_strong_enough from yunohost.domain import domain_main_domain dyndns_provider = "dyndns.yunohost.org" # Do some checks at first if os.path.isfile('/etc/yunohost/installed'): raise YunohostError('yunohost_already_installed') if os.path.isdir( "/etc/yunohost/apps") and os.listdir("/etc/yunohost/apps") != []: raise YunohostError( "It looks like you're trying to re-postinstall a system that was already working previously ... If you recently had some bug or issues with your installation, please first discuss with the team on how to fix the situation instead of savagely re-running the postinstall ...", raw_msg=True) # Check password if not force_password: assert_password_is_strong_enough("admin", password) if not ignore_dyndns: # Check if yunohost dyndns can handle the given domain # (i.e. is it a .nohost.me ? a .noho.st ?) try: is_nohostme_or_nohost = _dyndns_provides(dyndns_provider, domain) # If an exception is thrown, most likely we don't have internet # connectivity or something. Assume that this domain isn't manageable # and inform the user that we could not contact the dyndns host server. except: logger.warning( m18n.n('dyndns_provider_unreachable', provider=dyndns_provider)) is_nohostme_or_nohost = False # If this is a nohost.me/noho.st, actually check for availability if is_nohostme_or_nohost: # (Except if the user explicitly said he/she doesn't care about dyndns) if ignore_dyndns: dyndns = False # Check if the domain is available... elif _dyndns_available(dyndns_provider, domain): dyndns = True # If not, abort the postinstall else: raise YunohostError('dyndns_unavailable', domain=domain) else: dyndns = False else: dyndns = False if os.system("iptables -V >/dev/null 2>/dev/null") != 0: raise YunohostError( "iptables/nftables does not seems to be working on your setup. You may be in a container or your kernel does have the proper modules loaded. Sometimes, rebooting the machine may solve the issue.", raw_msg=True) operation_logger.start() logger.info(m18n.n('yunohost_installing')) regen_conf(['nslcd', 'nsswitch'], force=True) # Initialize LDAP for YunoHost # TODO: Improve this part by integrate ldapinit into conf_regen hook tools_ldapinit() # Create required folders folders_to_create = [ '/etc/yunohost/apps', '/etc/yunohost/certs', '/var/cache/yunohost/repo', '/home/yunohost.backup', '/home/yunohost.app' ] for folder in [x for x in folders_to_create if not os.path.exists(x)]: os.makedirs(folder) # Change folders permissions os.system('chmod 755 /home/yunohost.app') # Init ssowat's conf.json.persistent if not os.path.exists('/etc/ssowat/conf.json.persistent'): write_to_json('/etc/ssowat/conf.json.persistent', {}) os.system('chmod 644 /etc/ssowat/conf.json.persistent') # Create SSL CA regen_conf(['ssl'], force=True) ssl_dir = '/usr/share/yunohost/yunohost-config/ssl/yunoCA' # (Update the serial so that it's specific to this very instance) os.system("openssl rand -hex 19 > %s/serial" % ssl_dir) commands = [ 'rm %s/index.txt' % ssl_dir, 'touch %s/index.txt' % ssl_dir, 'cp %s/openssl.cnf %s/openssl.ca.cnf' % (ssl_dir, ssl_dir), 'sed -i s/yunohost.org/%s/g %s/openssl.ca.cnf ' % (domain, ssl_dir), 'openssl req -x509 -new -config %s/openssl.ca.cnf -days 3650 -out %s/ca/cacert.pem -keyout %s/ca/cakey.pem -nodes -batch -subj /CN=%s/O=%s' % (ssl_dir, ssl_dir, ssl_dir, domain, os.path.splitext(domain)[0]), 'cp %s/ca/cacert.pem /etc/ssl/certs/ca-yunohost_crt.pem' % ssl_dir, 'update-ca-certificates' ] for command in commands: p = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = p.communicate() if p.returncode != 0: logger.warning(out) raise YunohostError('yunohost_ca_creation_failed') else: logger.debug(out) logger.success(m18n.n('yunohost_ca_creation_success')) # New domain config regen_conf(['nsswitch'], force=True) domain_add(domain, dyndns) domain_main_domain(domain) # Change LDAP admin password tools_adminpw(password, check_strength=not force_password) # Enable UPnP silently and reload firewall firewall_upnp('enable', no_refresh=True) # Initialize the apps catalog system _initialize_apps_catalog_system() # Try to update the apps catalog ... # we don't fail miserably if this fails, # because that could be for example an offline installation... try: _update_apps_catalog() except Exception as e: logger.warning(str(e)) # Create the archive directory (makes it easier for people to upload backup # archives, otherwise it's only created after running `yunohost backup # create` once. from yunohost.backup import _create_archive_dir _create_archive_dir() # Init migrations (skip them, no need to run them on a fresh system) _skip_all_migrations() os.system('touch /etc/yunohost/installed') # Enable and start YunoHost firewall at boot time service_enable("yunohost-firewall") service_start("yunohost-firewall") regen_conf(names=["ssh"], force=True) # Restore original ssh conf, as chosen by the # admin during the initial install # # c.f. the install script and in particular # https://github.com/YunoHost/install_script/pull/50 # The user can now choose during the install to keep # the initial, existing sshd configuration # instead of YunoHost's recommended conf # original_sshd_conf = '/etc/ssh/sshd_config.before_yunohost' if os.path.exists(original_sshd_conf): os.rename(original_sshd_conf, '/etc/ssh/sshd_config') regen_conf(force=True) logger.success(m18n.n('yunohost_configured')) logger.warning(m18n.n('yunohost_postinstall_end_tip'))
def tools_maindomain(auth, old_domain=None, new_domain=None, dyndns=False): """ Main domain change tool Keyword argument: new_domain old_domain """ from yunohost.domain import domain_add from yunohost.dyndns import dyndns_subscribe if not old_domain: with open('/etc/yunohost/current_host', 'r') as f: old_domain = f.readline().rstrip() if not new_domain: return { 'current_main_domain': old_domain } config_files = [ '/etc/postfix/main.cf', '/etc/metronome/metronome.cfg.lua', '/etc/dovecot/dovecot.conf', '/usr/share/yunohost/yunohost-config/others/startup', '/home/yunohost.backup/tahoe/tahoe.cfg', '/etc/amavis/conf.d/05-node_id', '/etc/amavis/conf.d/50-user' ] config_dir = [] for dir in config_dir: for file in os.listdir(dir): config_files.append(dir + '/' + file) for file in config_files: with open(file, "r") as sources: lines = sources.readlines() with open(file, "w") as sources: for line in lines: sources.write(re.sub(r''+ old_domain +'', new_domain, line)) domain_add(auth, [new_domain], main=True) os.system('rm /etc/ssl/private/yunohost_key.pem') os.system('rm /etc/ssl/certs/yunohost_crt.pem') command_list = [ 'ln -s /etc/yunohost/certs/%s/key.pem /etc/ssl/private/yunohost_key.pem' % new_domain, 'ln -s /etc/yunohost/certs/%s/crt.pem /etc/ssl/certs/yunohost_crt.pem' % new_domain, 'echo %s > /etc/yunohost/current_host' % new_domain, 'service metronome restart', 'service postfix restart', 'service dovecot restart', 'service amavis restart', 'service nginx restart', ] for command in command_list: if os.system(command) != 0: raise MoulinetteError(errno.EPERM, m18n.n('maindomain_change_failed')) if dyndns: dyndns_subscribe(domain=new_domain) elif len(new_domain.split('.')) >= 3: try: r = requests.get('http://dyndns.yunohost.org/domains') except ConnectionError: pass else: dyndomains = json.loads(r.text) dyndomain = '.'.join(new_domain.split('.')[1:]) if dyndomain in dyndomains: dyndns_subscribe(domain=new_domain) msignals.display(m18n.n('maindomain_changed'), 'success')
def tools_maindomain(auth, old_domain=None, new_domain=None, dyndns=False): """ Main domain change tool Keyword argument: new_domain old_domain """ from yunohost.domain import domain_add, domain_list from yunohost.dyndns import dyndns_subscribe if not old_domain: with open('/etc/yunohost/current_host', 'r') as f: old_domain = f.readline().rstrip() if not new_domain: return { 'current_main_domain': old_domain } if not new_domain: raise MoulinetteError(errno.EINVAL, m18n.n('new_domain_required')) if new_domain not in domain_list(auth)['domains']: domain_add(auth, new_domain) config_files = [ '/etc/postfix/main.cf', '/etc/metronome/metronome.cfg.lua', '/etc/dovecot/dovecot.conf', '/usr/share/yunohost/yunohost-config/others/startup', '/etc/amavis/conf.d/05-node_id', '/etc/amavis/conf.d/50-user' ] config_dir = [] for dir in config_dir: for file in os.listdir(dir): config_files.append(dir + '/' + file) for file in config_files: with open(file, "r") as sources: lines = sources.readlines() with open(file, "w") as sources: for line in lines: sources.write(re.sub(r''+ old_domain +'', new_domain, line)) ## Update DNS zone file for old and new domains main_subdomains = ['pubsub', 'muc', 'vjud'] try: with open('/var/lib/bind/%s.zone' % old_domain, 'r') as f: old_zone = f.read() except IOError: pass else: # Remove unneeded subdomains entries for sub in main_subdomains: old_zone = re.sub( r'^({sub}.{domain}.|{sub})[\ \t]+(IN).*$[\n]?'.format( sub=sub, domain=old_domain), '', old_zone, 1, re.MULTILINE) with open('/var/lib/bind/%s.zone' % old_domain, 'w') as f: f.write(old_zone) try: with open('/var/lib/bind/%s.zone' % new_domain, 'r') as f: new_zone = f.read() except IOError: msignals.display(m18n.n('domain_zone_not_found', new_domain), 'warning') else: # Add main subdomains entries for sub in main_subdomains: new_zone += '{sub} IN CNAME {domain}.\n'.format( sub=sub, domain=new_domain) with open('/var/lib/bind/%s.zone' % new_domain, 'w') as f: f.write(new_zone) os.system('rm /etc/ssl/private/yunohost_key.pem') os.system('rm /etc/ssl/certs/yunohost_crt.pem') command_list = [ 'rm -f /etc/nginx/conf.d/%s.d/yunohost_local.conf' % old_domain, 'cp /usr/share/yunohost/yunohost-config/nginx/yunohost_local.conf /etc/nginx/conf.d/%s.d/' % new_domain, 'ln -s /etc/yunohost/certs/%s/key.pem /etc/ssl/private/yunohost_key.pem' % new_domain, 'ln -s /etc/yunohost/certs/%s/crt.pem /etc/ssl/certs/yunohost_crt.pem' % new_domain, 'echo %s > /etc/yunohost/current_host' % new_domain, 'service metronome restart', 'service postfix restart', 'service dovecot restart', 'service amavis restart', 'service nginx restart', ] for command in command_list: if os.system(command) != 0: raise MoulinetteError(errno.EPERM, m18n.n('maindomain_change_failed')) if dyndns and len(new_domain.split('.')) >= 3: try: r = requests.get('https://dyndns.yunohost.org/domains') except ConnectionError: pass else: dyndomains = json.loads(r.text) dyndomain = '.'.join(new_domain.split('.')[1:]) if dyndomain in dyndomains: dyndns_subscribe(domain=new_domain) msignals.display(m18n.n('maindomain_changed'), 'success')