chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

account.py (4780B)


      1 # first start without gtk: the time zones, the network, making the account
      2 import gettext
      3 import os
      4 import re
      5 import subprocess
      6 
      7 gettext.textdomain("chamesle")
      8 _ = gettext.gettext
      9 
     10 MARK = "/etc/chamesle/firstboot"
     11 GROUPS = "wheel audio video input network storage optical scanner lp plugdev bluetooth users kvm".split()
     12 
     13 
     14 def zones():
     15     out = []
     16     try:
     17         for line in open("/usr/share/zoneinfo/zone1970.tab"):
     18             if not line.startswith("#"):
     19                 out.append(line.split("\t")[2].strip())
     20     except OSError:
     21         out = ["UTC"]
     22     return sorted(out)
     23 
     24 
     25 def online():
     26     r = subprocess.run(["nmcli", "-t", "-f", "STATE", "general"], text=True, stdout=subprocess.PIPE,
     27                        stderr=subprocess.DEVNULL)
     28     return r.stdout.strip() == "connected"
     29 
     30 
     31 def username_from(name):
     32     return re.sub(r"[^a-z0-9_-]", "", name.split(" ")[0].lower())
     33 
     34 
     35 # names the system has, and ones the desktops add while jiggity installs them: useradd fails on any of these, and
     36 # the computer would start with no account to sign in with
     37 SYSTEM_NAMES = set("""root live daemon bin sys nobody admin adm wheel users user audio video input render kvm disk
     38     tty utmp lp mail news uucp man games ftp www http sshd dbus polkitd sddm gdm lightdm colord avahi rtkit pulse
     39     pipewire geoclue flatpak usbmux saned scanner optical storage network plugdev bluetooth cups dnsmasq ntp chrony
     40     upower tss nm-openvpn nm-openconnect openvpn tor mpd postfix steam gamemode xbuilder _apt""".split())
     41 
     42 
     43 def taken(root="/"):
     44     names = set(SYSTEM_NAMES)
     45     for f in ("etc/passwd", "etc/group"):
     46         try:
     47             names |= {line.split(":")[0] for line in open(os.path.join(root, f))}
     48         except OSError:
     49             pass
     50     return names
     51 
     52 
     53 # what's wrong with a username, or ""
     54 def bad_username(u):
     55     if u and not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", u):
     56         return _("A username is lowercase letters and numbers, starting with a letter.")
     57     if u in taken():
     58         return _("That username is taken by the system. Pick another one.")
     59     return ""
     60 
     61 
     62 def make(zone, user, name, pw, host=None, root="/"):
     63     # root: the new system, when jiggity makes the account while it installs
     64     r = root.rstrip("/")
     65     inside = [] if root == "/" else ["chroot", root]
     66     groups = [g.split(":")[0] for g in open(r + "/etc/group")]
     67     # a name the desktop's packages took after it was picked: say so, rather than finish with nobody to sign in as
     68     for cmd, inp in ((["useradd", "-m", "-s", "/bin/bash", "-c", name, "-G",
     69                        ",".join(g for g in GROUPS if g in groups), user], None),
     70                      (["chpasswd", "-c", "SHA512"], "%s:%s\n" % (user, pw))):
     71         p = subprocess.run(inside + cmd, input=inp, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
     72         if p.returncode:
     73             raise RuntimeError("making the account %s failed: %s" % (user, p.stdout.strip().splitlines()[-1:] and
     74                                                                     p.stdout.strip().splitlines()[-1] or cmd[0]))
     75     subprocess.run(["ln", "-sf", "/usr/share/zoneinfo/" + zone, r + "/etc/localtime"])
     76     with open(r + "/etc/timezone", "w") as f:
     77         f.write(zone + "\n")
     78     host = host or hostname_from(user)
     79     with open(r + "/etc/hostname", "w") as f:
     80         f.write(host + "\n")
     81     with open(r + "/etc/hosts", "w") as f:
     82         f.write("127.0.0.1\tlocalhost\n127.0.1.1\t%s\n::1\tlocalhost ip6-localhost ip6-loopback\n" % host)
     83     if root == "/":
     84         subprocess.run(["hostname", host])
     85     remember_session(user, r)
     86     if os.path.exists(r + MARK):
     87         os.unlink(r + MARK)
     88 
     89 
     90 def hostname_from(user):
     91     return re.sub(r"[^a-z0-9-]", "", user.lower())[:20] + "-pc"
     92 
     93 
     94 # what's wrong with a computer name, or ""
     95 def bad_hostname(h):
     96     if not re.fullmatch(r"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?", h or ""):
     97         return _("A computer name is lowercase letters, numbers and dashes.")
     98     return ""
     99 
    100 
    101 # sddm lists wayland sessions first and would pick one (xfce's isn't ready): the edition's own session is the
    102 # last one used, so it's the one that starts
    103 def remember_session(user, r=""):
    104     try:
    105         name = open(r + "/etc/chamesle/session").read().strip()
    106     except OSError:
    107         return
    108     for d in ("/usr/share/xsessions", "/usr/share/wayland-sessions"):
    109         path = "%s/%s.desktop" % (d, name)
    110         if os.path.exists(r + path) and os.path.isdir(r + "/var/lib/sddm"):
    111             with open(r + "/var/lib/sddm/state.conf", "w") as f:
    112                 f.write("[Last]\nSession=%s\nUser=%s\n" % (path, user))
    113             subprocess.run((["chroot", r] if r else []) + ["chown", "sddm:sddm", "/var/lib/sddm/state.conf"],
    114                            stderr=subprocess.DEVNULL)
    115             return