chamesle

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

pkgimport (8530B)


      1 #!/usr/bin/python3
      2 # install a .deb or .rpm: turn it into an apk that depends on the libs it links to
      3 #   sudo pkgimport install foo.deb
      4 #   pkgimport convert foo.rpm -o DIR
      5 # dpkg/rpm scripts are not run
      6 import os, re, shutil, struct, subprocess, sys, tempfile
      7 
      8 
      9 def die(msg):
     10     sys.exit(f'pkgimport: {msg}')
     11 
     12 
     13 def run(*cmd, **kw):
     14     return subprocess.run(cmd, check=True, **kw)
     15 
     16 
     17 def apkver(v, rel='0'):
     18     # 2:1.2.3~beta1-0ubuntu4 -> 1.2.3_beta1-r0, anything odd falls back to its leading numbers
     19     v = v.split(':', 1)[-1].lower()
     20     up, _, deb = v.rpartition('-') if '-' in v else (v, '', rel)
     21     m = re.match(r'\d+', deb)
     22     rev = m.group(0) if m else rel
     23     up = up.replace('~', '_').replace('+', '_p')
     24     up = re.sub(r'\.?(alpha|beta|pre|rc)(\d*)', r'_\1\2', up)
     25     if not re.fullmatch(r'\d+(\.\d+)*[a-z]?(_(alpha|beta|pre|rc|p)\d*)*', up):
     26         m = re.match(r'\d+(\.\d+)*', up)
     27         up = (m.group(0) if m else '0') + '_p0'
     28     return f'{up}-r{int(rev)}'
     29 
     30 
     31 def needed(path):
     32     # DT_NEEDED entries of a 64-bit little endian ELF file, [] for anything else
     33     try:
     34         with open(path, 'rb') as f:
     35             data = f.read()
     36     except OSError:
     37         return []
     38     if data[:4] != b'\x7fELF' or data[4] != 2 or data[5] != 1:
     39         return []
     40     shoff, = struct.unpack_from('<Q', data, 0x28)
     41     shentsize, shnum = struct.unpack_from('<HH', data, 0x3a)
     42     secs = [struct.unpack_from('<IIQQQQIIQQ', data, shoff + i * shentsize) for i in range(shnum)]
     43     out = []
     44     for name, typ, flags, addr, off, size, link, info, align, entsize in secs:
     45         if typ != 6:  # SHT_DYNAMIC
     46             continue
     47         stroff = secs[link][4]
     48         for i in range(0, size, 16):
     49             tag, val = struct.unpack_from('<qQ', data, off + i)
     50             if tag == 0:
     51                 break
     52             if tag == 1:  # DT_NEEDED
     53                 end = data.index(b'\0', stroff + val)
     54                 out.append(data[stroff + val:end].decode())
     55     return out
     56 
     57 
     58 def unpack(pkg, root):
     59     meta = {}
     60     if pkg.endswith('.deb'):
     61         ctl = tempfile.mkdtemp()
     62         run('bsdtar', '-xf', pkg, '-C', ctl)
     63         data = [f for f in os.listdir(ctl) if f.startswith('data.tar')]
     64         control = [f for f in os.listdir(ctl) if f.startswith('control.tar')]
     65         if not data or not control:
     66             die(f'{pkg}: not a debian package')
     67         run('bsdtar', '-xf', os.path.join(ctl, data[0]), '-C', root)
     68         info = os.path.join(ctl, 'info')
     69         os.mkdir(info)
     70         run('bsdtar', '-xf', os.path.join(ctl, control[0]), '-C', info)
     71         text = open(os.path.join(info, 'control'), errors='replace').read()
     72         shutil.rmtree(ctl)
     73         key = None
     74         for line in text.splitlines():
     75             if line[:1] in (' ', '\t') and key:
     76                 continue
     77             k, _, v = line.partition(':')
     78             key = k.strip().lower()
     79             meta[key] = v.strip()
     80         meta = {'name': meta.get('package'), 'version': meta.get('version', '0'),
     81                 'description': meta.get('description', ''), 'url': meta.get('homepage', ''),
     82                 'license': 'unknown', 'arch': meta.get('architecture', 'amd64')}
     83     elif pkg.endswith('.rpm'):
     84         q = '%{NAME}\n%{VERSION}\n%{RELEASE}\n%{SUMMARY}\n%{URL}\n%{LICENSE}\n%{ARCH}\n'
     85         r = subprocess.run(['rpm', '-qp', '--nosignature', '--qf', q, pkg], capture_output=True, text=True)
     86         if r.returncode == 0:
     87             name, ver, rel, summary, url, lic, arch = (r.stdout.split('\n') + [''] * 7)[:7]
     88         else:
     89             # no rpm tool: go by the file name, name-version-release.arch.rpm
     90             m = re.match(r'^(.+)-([^-]+)-([^-]+)\.([^.]+)\.rpm$', os.path.basename(pkg))
     91             if not m:
     92                 die(f'{pkg}: can\'t tell the name and version')
     93             name, ver, rel, arch = m.groups()
     94             summary, url, lic = name, '', 'unknown'
     95         run('bsdtar', '-xf', pkg, '-C', root)
     96         meta = {'name': name, 'version': f'{ver}-{re.match(r"[0-9]*", rel).group(0) or 0}',
     97                 'description': summary, 'url': url if url != '(none)' else '', 'license': lic, 'arch': arch}
     98     else:
     99         die(f'{pkg}: only .deb and .rpm')
    100     if meta['arch'] not in ('amd64', 'x86_64', 'all', 'noarch'):
    101         die(f'{pkg}: built for {meta["arch"]}, this computer is x86_64')
    102     if not meta['name']:
    103         die(f'{pkg}: no package name')
    104     return meta
    105 
    106 
    107 def merge(src, dst):
    108     # move everything in src into dst, keeping what's already there
    109     os.makedirs(dst, exist_ok=True)
    110     for f in os.listdir(src):
    111         s, d = os.path.join(src, f), os.path.join(dst, f)
    112         if os.path.isdir(s) and not os.path.islink(s) and os.path.isdir(d):
    113             merge(s, d)
    114         elif not os.path.lexists(d):
    115             os.rename(s, d)
    116     shutil.rmtree(src, ignore_errors=True)
    117 
    118 
    119 def relayout(root):
    120     # this system: everything under /usr, one lib dir, one bin dir
    121     for top in ('bin', 'sbin', 'lib', 'lib64'):
    122         p = os.path.join(root, top)
    123         if os.path.isdir(p) and not os.path.islink(p):
    124             merge(p, os.path.join(root, 'usr', top))
    125     for d in ('usr/lib/x86_64-linux-gnu', 'usr/lib64'):
    126         p = os.path.join(root, d)
    127         if os.path.isdir(p) and not os.path.islink(p):
    128             merge(p, os.path.join(root, 'usr/lib'))
    129     p = os.path.join(root, 'usr/sbin')
    130     if os.path.isdir(p) and not os.path.islink(p):
    131         merge(p, os.path.join(root, 'usr/bin'))
    132     # leftovers that would clash with the system's own symlinks
    133     for d in ('bin', 'sbin', 'lib', 'lib64', 'usr/sbin', 'usr/lib64'):
    134         p = os.path.join(root, d)
    135         if os.path.islink(p):
    136             os.remove(p)
    137 
    138 
    139 def convert(pkg, outdir):
    140     tmp = tempfile.mkdtemp(prefix='pkgimport.')
    141     root = os.path.join(tmp, 'root')
    142     os.mkdir(root)
    143     meta = unpack(pkg, root)
    144     relayout(root)
    145 
    146     have, wants = set(), set()
    147     for d, _, files in os.walk(root):
    148         for f in files:
    149             p = os.path.join(d, f)
    150             if '.so' in f:
    151                 have.add(f)
    152             if not os.path.islink(p):
    153                 wants.update(needed(p))
    154     deps = sorted('so:' + l for l in wants - have)
    155 
    156     name = re.sub(r'[^a-z0-9._+-]', '-', meta['name'].lower())
    157     ver = apkver(meta['version'])
    158     out = os.path.join(outdir, f'{name}-{ver}.apk')
    159     post = os.path.join(tmp, 'post-install')
    160     with open(post, 'w') as f:
    161         f.write('#!/bin/sh\n'
    162                 'ldconfig 2>/dev/null\n'
    163                 'update-desktop-database -q 2>/dev/null\n'
    164                 'gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor 2>/dev/null\n'
    165                 'glib-compile-schemas /usr/share/glib-2.0/schemas 2>/dev/null\n'
    166                 'exit 0\n')
    167     os.chmod(post, 0o755)
    168     args = ['apk', 'mkpkg', '--files', root, '--output', out,
    169             '--info', f'name:{name}', '--info', f'version:{ver}', '--info', 'arch:x86_64',
    170             '--info', f'description:{meta["description"] or name}', '--info', f'license:{meta["license"] or "unknown"}',
    171             '--info', f'origin:{os.path.basename(pkg)}',
    172             '--script', f'post-install:{post}', '--script', f'post-upgrade:{post}']
    173     if meta['url']:
    174         args += ['--info', f'url:{meta["url"]}']
    175     if deps:
    176         args += ['--info', 'depends:' + ' '.join(deps)]
    177     run(*args)
    178     shutil.rmtree(tmp, ignore_errors=True)
    179     return name, out
    180 
    181 
    182 def main():
    183     a = sys.argv[1:]
    184     if len(a) < 2 or a[0] not in ('install', 'convert'):
    185         sys.exit('usage: sudo pkgimport install FILE.deb|FILE.rpm ...\n'
    186                  '       pkgimport convert FILE.deb|FILE.rpm ... [-o DIR]')
    187     cmd, files = a[0], a[1:]
    188     outdir = None
    189     if '-o' in files:
    190         i = files.index('-o')
    191         outdir = files[i + 1]
    192         del files[i:i + 2]
    193     if cmd == 'install' and os.geteuid() != 0:
    194         die('installing needs root: sudo pkgimport install ...')
    195     work = outdir or tempfile.mkdtemp(prefix='pkgimport.')
    196     built = []
    197     for f in files:
    198         if not os.path.isfile(f):
    199             die(f'{f}: no such file')
    200         name, apk = convert(os.path.abspath(f), work)
    201         print(f'{f} -> {name} ({os.path.basename(apk)})')
    202         built.append(apk)
    203     if cmd == 'install':
    204         r = subprocess.run(['apk', 'add', '--allow-untrusted'] + built)
    205         if r.returncode:
    206             print('pkgimport: "so:... (no such package)" means it wants a library we don\'t have', file=sys.stderr)
    207         if not outdir:
    208             shutil.rmtree(work, ignore_errors=True)
    209         sys.exit(r.returncode)
    210 
    211 
    212 main()