mag

a binary package manager in one C file: apk and pacman repos, CRUX, Void and Exherbo ports
git clone https://github.com/tortr-rs/mag
Log | Files | Refs | README | LICENSE

mag.c (205387B)


      1 /* mag: the package manager, one C file on c.h. it installs prebuilt packages from apk repos, and builds
      2  * CRUX ports: the repos are listed in /etc/mag/repos, their keys are in /etc/mag/keys. it does its own gzip,
      3  * tar, rsa and ed25519, so all it needs from the system is a download command, and bash for ports */
      4 #if (defined(__x86_64__) || defined(__i386__)) && !defined(LIBC)
      5 #include "c.h"
      6 #else
      7 #define _GNU_SOURCE
      8 #include <ctype.h>
      9 #include <dirent.h>
     10 #include <errno.h>
     11 #include <fcntl.h>
     12 #include <limits.h>
     13 #include <stdarg.h>
     14 #include <stdint.h>
     15 #include <stdio.h>
     16 #include <stdlib.h>
     17 #include <string.h>
     18 #include <unistd.h>
     19 #include <netdb.h>
     20 #include <strings.h>
     21 #include <sys/socket.h>
     22 #include <sys/stat.h>
     23 #include <sys/time.h>
     24 #include <sys/sysmacros.h>
     25 #include <sys/utsname.h>
     26 #include <sys/wait.h>
     27 #endif
     28 
     29 #define VERSION "0.7.4"
     30 
     31 static const char *prog = "mag";
     32 static const char *root = "";                   /* MAG_ROOT without the trailing slash, "" is / */
     33 static const char *arch;
     34 static int dry, force, yes;
     35 
     36 static void say(const char *fmt, ...)
     37 {
     38     va_list ap;
     39     fflush(stdout);
     40     fprintf(stderr, "%s: ", prog);
     41     va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
     42     fputc('\n', stderr);
     43 }
     44 static __attribute__((noreturn)) void die(const char *fmt, ...)
     45 {
     46     va_list ap;
     47     fflush(stdout);
     48     fprintf(stderr, "%s: ", prog);
     49     va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
     50     fputc('\n', stderr);
     51     exit(1);
     52 }
     53 
     54 static void *xmalloc(size_t n) { void *p = malloc(n ? n : 1); if (!p) die("out of memory"); return p; }
     55 static void *xrealloc(void *p, size_t n) { p = realloc(p, n ? n : 1); if (!p) die("out of memory"); return p; }
     56 static char *xstrdup(const char *s) { return strcpy(xmalloc(strlen(s) + 1), s); }
     57 static char *xstrndup(const char *s, size_t n) { char *d = strndup(s, n); if (!d) die("out of memory"); return d; }
     58 
     59 static char *fmt(const char *f, ...)
     60 {
     61     char buf[8192];
     62     va_list ap;
     63     va_start(ap, f); vsnprintf(buf, sizeof buf, f, ap); va_end(ap);
     64     return xstrdup(buf);
     65 }
     66 
     67 struct list { char **v; int n, cap; };
     68 
     69 static void push(struct list *l, char *s)
     70 {
     71     if (l->n == l->cap) { l->cap = l->cap ? l->cap * 2 : 16; l->v = xrealloc(l->v, l->cap * sizeof *l->v); }
     72     l->v[l->n++] = s;
     73 }
     74 static int has(const struct list *l, const char *s)
     75 {
     76     int i;
     77     for (i = 0; i < l->n; i++) if (!strcmp(l->v[i], s)) return 1;
     78     return 0;
     79 }
     80 static void list_free(struct list *l)
     81 {
     82     int i;
     83     for (i = 0; i < l->n; i++) free(l->v[i]);
     84     free(l->v);
     85     memset(l, 0, sizeof *l);
     86 }
     87 static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
     88 
     89 /* the words of s, split on spaces */
     90 static struct list words(const char *s)
     91 {
     92     struct list l = { 0 };
     93     while (s && *s) {
     94         size_t n;
     95         while (*s == ' ' || *s == '\t' || *s == '\n') s++;
     96         n = strcspn(s, " \t\n");
     97         if (n) push(&l, xstrndup(s, n));
     98         s += n;
     99     }
    100     return l;
    101 }
    102 
    103 static char *slurp(const char *path, size_t *len)
    104 {
    105     int fd = open(path, O_RDONLY);
    106     size_t n = 0, cap = 4096;
    107     char *b;
    108     ssize_t r;
    109     if (fd < 0) return NULL;
    110     b = xmalloc(cap);
    111     while ((r = read(fd, b + n, cap - n - 1)) > 0) {
    112         n += r;
    113         if (n + 1 >= cap) { cap *= 2; b = xrealloc(b, cap); }
    114     }
    115     close(fd);
    116     b[n] = 0;
    117     if (len) *len = n;
    118     return b;
    119 }
    120 
    121 static int mkpath(const char *path, mode_t mode)
    122 {
    123     char *p = xstrdup(path), *s;
    124     for (s = p + 1; *s; s++) {
    125         if (*s != '/') continue;
    126         *s = 0;
    127         mkdir(p, mode);
    128         *s = '/';
    129     }
    130     if (mkdir(p, mode) < 0 && errno != EEXIST) { free(p); return -1; }
    131     free(p);
    132     return 0;
    133 }
    134 
    135 static void mkparent(const char *path)
    136 {
    137     char *d = xstrdup(path), *s = strrchr(d, '/');
    138     if (s && s != d) { *s = 0; mkpath(d, 0755); }
    139     free(d);
    140 }
    141 
    142 static int exists(const char *p) { struct stat st; return lstat(p, &st) == 0; }
    143 
    144 static int wait_for(pid_t pid)
    145 {
    146     int st;
    147     while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {}
    148     return (st & 0x7f) ? 128 + (st & 0x7f) : (st >> 8) & 255;
    149 }
    150 
    151 static int run(char *const argv[])
    152 {
    153     pid_t pid;
    154     fflush(stdout);
    155     pid = fork();
    156     if (pid < 0) die("cannot fork");
    157     if (!pid) {
    158         execvp(argv[0], argv);
    159         fprintf(stderr, "%s: %s: %s\n", prog, argv[0], strerror(errno));
    160         _exit(127);
    161     }
    162     return wait_for(pid);
    163 }
    164 
    165 static void rmtree(const char *path)
    166 {
    167     char *av[] = { "rm", "-rf", (char *)path, NULL };
    168     run(av);
    169 }
    170 
    171 /* ---- sha1 and sha256 ---- */
    172 
    173 static const unsigned k256[64] = {
    174     0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
    175     0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
    176     0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
    177     0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
    178     0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
    179     0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
    180 
    181 #define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
    182 
    183 static void sha256_block(unsigned *h, const unsigned char *p)
    184 {
    185     unsigned w[64], v[8];
    186     int i;
    187     for (i = 0; i < 16; i++) w[i] = (unsigned)p[i * 4] << 24 | p[i * 4 + 1] << 16 | p[i * 4 + 2] << 8 | p[i * 4 + 3];
    188     for (i = 16; i < 64; i++) {
    189         unsigned s0 = ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3), s1 = ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10);
    190         w[i] = w[i - 16] + s0 + w[i - 7] + s1;
    191     }
    192     memcpy(v, h, sizeof v);
    193     for (i = 0; i < 64; i++) {
    194         unsigned t1 = v[7] + (ROR(v[4], 6) ^ ROR(v[4], 11) ^ ROR(v[4], 25)) + ((v[4] & v[5]) ^ (~v[4] & v[6])) + k256[i] + w[i];
    195         unsigned t2 = (ROR(v[0], 2) ^ ROR(v[0], 13) ^ ROR(v[0], 22)) + ((v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]));
    196         v[7] = v[6]; v[6] = v[5]; v[5] = v[4]; v[4] = v[3] + t1; v[3] = v[2]; v[2] = v[1]; v[1] = v[0]; v[0] = t1 + t2;
    197     }
    198     for (i = 0; i < 8; i++) h[i] += v[i];
    199 }
    200 
    201 static void sha1_block(unsigned *h, const unsigned char *p)
    202 {
    203     unsigned w[80], a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], t;
    204     int i;
    205     for (i = 0; i < 16; i++) w[i] = (unsigned)p[i * 4] << 24 | p[i * 4 + 1] << 16 | p[i * 4 + 2] << 8 | p[i * 4 + 3];
    206     for (; i < 80; i++) { t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; w[i] = t << 1 | t >> 31; }
    207     for (i = 0; i < 80; i++) {
    208         unsigned f, k;
    209         if (i < 20) f = (b & c) | (~b & d), k = 0x5a827999;
    210         else if (i < 40) f = b ^ c ^ d, k = 0x6ed9eba1;
    211         else if (i < 60) f = (b & c) | (b & d) | (c & d), k = 0x8f1bbcdc;
    212         else f = b ^ c ^ d, k = 0xca62c1d6;
    213         t = (a << 5 | a >> 27) + f + e + k + w[i];
    214         e = d; d = c; c = b << 30 | b >> 2; b = a; a = t;
    215     }
    216     h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;
    217 }
    218 
    219 static const uint64_t k512[80] = {
    220     0x428a2f98d728ae22ull, 0x7137449123ef65cdull, 0xb5c0fbcfec4d3b2full, 0xe9b5dba58189dbbcull, 0x3956c25bf348b538ull, 0x59f111f1b605d019ull,
    221     0x923f82a4af194f9bull, 0xab1c5ed5da6d8118ull, 0xd807aa98a3030242ull, 0x12835b0145706fbeull, 0x243185be4ee4b28cull, 0x550c7dc3d5ffb4e2ull,
    222     0x72be5d74f27b896full, 0x80deb1fe3b1696b1ull, 0x9bdc06a725c71235ull, 0xc19bf174cf692694ull, 0xe49b69c19ef14ad2ull, 0xefbe4786384f25e3ull,
    223     0x0fc19dc68b8cd5b5ull, 0x240ca1cc77ac9c65ull, 0x2de92c6f592b0275ull, 0x4a7484aa6ea6e483ull, 0x5cb0a9dcbd41fbd4ull, 0x76f988da831153b5ull,
    224     0x983e5152ee66dfabull, 0xa831c66d2db43210ull, 0xb00327c898fb213full, 0xbf597fc7beef0ee4ull, 0xc6e00bf33da88fc2ull, 0xd5a79147930aa725ull,
    225     0x06ca6351e003826full, 0x142929670a0e6e70ull, 0x27b70a8546d22ffcull, 0x2e1b21385c26c926ull, 0x4d2c6dfc5ac42aedull, 0x53380d139d95b3dfull,
    226     0x650a73548baf63deull, 0x766a0abb3c77b2a8ull, 0x81c2c92e47edaee6ull, 0x92722c851482353bull, 0xa2bfe8a14cf10364ull, 0xa81a664bbc423001ull,
    227     0xc24b8b70d0f89791ull, 0xc76c51a30654be30ull, 0xd192e819d6ef5218ull, 0xd69906245565a910ull, 0xf40e35855771202aull, 0x106aa07032bbd1b8ull,
    228     0x19a4c116b8d2d0c8ull, 0x1e376c085141ab53ull, 0x2748774cdf8eeb99ull, 0x34b0bcb5e19b48a8ull, 0x391c0cb3c5c95a63ull, 0x4ed8aa4ae3418acbull,
    229     0x5b9cca4f7763e373ull, 0x682e6ff3d6b2b8a3ull, 0x748f82ee5defb2fcull, 0x78a5636f43172f60ull, 0x84c87814a1f0ab72ull, 0x8cc702081a6439ecull,
    230     0x90befffa23631e28ull, 0xa4506cebde82bde9ull, 0xbef9a3f7b2c67915ull, 0xc67178f2e372532bull, 0xca273eceea26619cull, 0xd186b8c721c0c207ull,
    231     0xeada7dd6cde0eb1eull, 0xf57d4f7fee6ed178ull, 0x06f067aa72176fbaull, 0x0a637dc5a2c898a6ull, 0x113f9804bef90daeull, 0x1b710b35131c471bull,
    232     0x28db77f523047d84ull, 0x32caab7b40c72493ull, 0x3c9ebe0a15c9bebcull, 0x431d67c49c100d4cull, 0x4cc5d4becb3e42b6ull, 0x597f299cfc657e2aull,
    233     0x5fcb6fab3ad6faecull, 0x6c44198c4a475817ull };
    234 
    235 #define ROR64(x, n) ((x) >> (n) | (x) << (64 - (n)))
    236 
    237 static void sha512_block(uint64_t *h, const unsigned char *p)
    238 {
    239     uint64_t w[80], v[8];
    240     int i, j;
    241     for (j = 0; j < 16; j++) for (w[j] = 0, i = 0; i < 8; i++) w[j] = w[j] << 8 | p[j * 8 + i];
    242     for (j = 16; j < 80; j++)
    243         w[j] = w[j - 16] + (ROR64(w[j - 15], 1) ^ ROR64(w[j - 15], 8) ^ w[j - 15] >> 7) + w[j - 7] + (ROR64(w[j - 2], 19) ^ ROR64(w[j - 2], 61) ^ w[j - 2] >> 6);
    244     memcpy(v, h, sizeof v);
    245     for (j = 0; j < 80; j++) {
    246         uint64_t t1 = v[7] + (ROR64(v[4], 14) ^ ROR64(v[4], 18) ^ ROR64(v[4], 41)) + ((v[4] & v[5]) ^ (~v[4] & v[6])) + k512[j] + w[j];
    247         uint64_t t2 = (ROR64(v[0], 28) ^ ROR64(v[0], 34) ^ ROR64(v[0], 39)) + ((v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]));
    248         memmove(v + 1, v, 7 * sizeof *v);
    249         v[4] += t1;
    250         v[0] = t1 + t2;
    251     }
    252     for (j = 0; j < 8; j++) h[j] += v[j];
    253 }
    254 
    255 /* sha1 is 1 for sha1, 0 for sha256, 2 for sha512 */
    256 struct hash { unsigned h[8]; uint64_t h64[8]; unsigned char b[128]; uint64_t len; int sha1; };
    257 
    258 static void hash_init(struct hash *s, int sha1)
    259 {
    260     static const unsigned i1[5] = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 };
    261     static const unsigned i2[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
    262     static const uint64_t i5[8] = { 0x6a09e667f3bcc908ull, 0xbb67ae8584caa73bull, 0x3c6ef372fe94f82bull, 0xa54ff53a5f1d36f1ull,
    263         0x510e527fade682d1ull, 0x9b05688c2b3e6c1full, 0x1f83d9abfb41bd6bull, 0x5be0cd19137e2179ull };
    264     memset(s, 0, sizeof *s);
    265     s->sha1 = sha1;
    266     if (sha1 == 2) memcpy(s->h64, i5, sizeof i5);
    267     else memcpy(s->h, sha1 ? i1 : i2, sha1 ? sizeof i1 : sizeof i2);
    268 }
    269 
    270 static void hash_block(struct hash *s, const unsigned char *p)
    271 {
    272     if (s->sha1 == 2) sha512_block(s->h64, p); else if (s->sha1) sha1_block(s->h, p); else sha256_block(s->h, p);
    273 }
    274 
    275 static void hash_add(struct hash *s, const void *data, size_t n)
    276 {
    277     const unsigned char *p = data;
    278     size_t bs = s->sha1 == 2 ? 128 : 64, used = s->len % bs;
    279     s->len += n;
    280     if (used) {
    281         size_t k = bs - used < n ? bs - used : n;
    282         memcpy(s->b + used, p, k);
    283         p += k; n -= k;
    284         if (used + k < bs) return;
    285         hash_block(s, s->b);
    286     }
    287     for (; n >= bs; p += bs, n -= bs) hash_block(s, p);
    288     memcpy(s->b, p, n);
    289 }
    290 
    291 /* the digest into out, returns its length */
    292 static int hash_end(struct hash *s, unsigned char *out)
    293 {
    294     uint64_t bits = s->len * 8;
    295     unsigned char c = 0x80;
    296     int i, big = s->sha1 == 2, w = s->sha1 == 1 ? 5 : 8;
    297     hash_add(s, &c, 1);
    298     c = 0;
    299     while (s->len % (big ? 128 : 64) != (big ? 112u : 56u)) hash_add(s, &c, 1);
    300     for (i = big ? 15 : 7; i >= 0; i--) { c = i > 7 ? 0 : bits >> (i * 8); hash_add(s, &c, 1); }
    301     if (big) { for (i = 0; i < 64; i++) out[i] = s->h64[i / 8] >> (56 - 8 * (i % 8)); return 64; }
    302     for (i = 0; i < w * 4; i++) out[i] = s->h[i / 4] >> (24 - 8 * (i % 4));
    303     return w * 4;
    304 }
    305 
    306 static char *hex(const unsigned char *d, int n)
    307 {
    308     char *s = xmalloc(n * 2 + 1);
    309     int i;
    310     for (i = 0; i < n; i++) sprintf(s + i * 2, "%02x", d[i]);
    311     return s;
    312 }
    313 
    314 /* bytes from..to of a file through a hash, to = -1 for the end */
    315 static int hash_range(int fd, off_t from, off_t to, int sha1, unsigned char *out)
    316 {
    317     struct hash h;
    318     static unsigned char buf[65536];
    319     ssize_t n;
    320     hash_init(&h, sha1);
    321     lseek(fd, from, SEEK_SET);
    322     while (to < 0 || from < to) {
    323         size_t want = sizeof buf;
    324         if (to >= 0 && (off_t)want > to - from) want = to - from;
    325         if ((n = read(fd, buf, want)) <= 0) break;
    326         hash_add(&h, buf, n);
    327         from += n;
    328     }
    329     return hash_end(&h, out);
    330 }
    331 
    332 static char *sha256_file(const char *path)
    333 {
    334     unsigned char d[32];
    335     int fd = open(path, O_RDONLY);
    336     if (fd < 0) return NULL;
    337     hash_range(fd, 0, -1, 0, d);
    338     close(fd);
    339     return hex(d, 32);
    340 }
    341 
    342 static size_t unbase64(const char *s, unsigned char *out)
    343 {
    344     static const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    345     size_t n = 0;
    346     unsigned v = 0;
    347     int bits = 0;
    348     for (; *s && *s != '='; s++) {
    349         const char *p = strchr(a, *s);
    350         if (!p) continue;
    351         v = v << 6 | (p - a);
    352         bits += 6;
    353         if (bits >= 8) { bits -= 8; out[n++] = v >> bits; }
    354     }
    355     return n;
    356 }
    357 
    358 /* ---- gzip ---- */
    359 
    360 struct in { int fd; unsigned char buf[65536]; size_t pos, len; off_t off; };
    361 
    362 static void in_open(struct in *r, int fd, off_t at) { r->fd = fd; r->pos = r->len = 0; r->off = at; lseek(fd, at, SEEK_SET); }
    363 static off_t in_tell(const struct in *r) { return r->off + r->pos; }
    364 static int in_byte(struct in *r)
    365 {
    366     if (r->pos == r->len) {
    367         ssize_t n;
    368         r->off += r->len;
    369         r->pos = 0;
    370         n = read(r->fd, r->buf, sizeof r->buf);
    371         r->len = n > 0 ? n : 0;
    372         if (!r->len) return -1;
    373     }
    374     return r->buf[r->pos++];
    375 }
    376 static int in_eof(struct in *r) { if (in_byte(r) < 0) return 1; r->pos--; return 0; }
    377 
    378 typedef void outfn(void *, const unsigned char *, size_t);
    379 
    380 struct huff { unsigned short count[16], sym[320]; };
    381 
    382 struct inf {
    383     struct in *in;
    384     unsigned bitbuf;
    385     int bitcnt, bad;
    386     unsigned char win[32768];
    387     unsigned wpos;
    388     outfn *out;
    389     void *ctx;
    390 };
    391 
    392 static unsigned getbits(struct inf *s, int n)
    393 {
    394     unsigned v;
    395     while (s->bitcnt < n) {
    396         int c = in_byte(s->in);
    397         if (c < 0) { s->bad = 1; c = 0; }
    398         s->bitbuf |= (unsigned)c << s->bitcnt;
    399         s->bitcnt += 8;
    400     }
    401     v = s->bitbuf & ((1u << n) - 1);
    402     s->bitbuf >>= n;
    403     s->bitcnt -= n;
    404     return v;
    405 }
    406 
    407 static void put(struct inf *s, unsigned char c)
    408 {
    409     s->win[s->wpos++] = c;
    410     if (s->wpos == sizeof s->win) { s->out(s->ctx, s->win, s->wpos); s->wpos = 0; }
    411 }
    412 
    413 static void huff_build(struct huff *h, const unsigned char *len, int n)
    414 {
    415     unsigned short offs[16];
    416     int i, sum = 0;
    417     memset(h->count, 0, sizeof h->count);
    418     for (i = 0; i < n; i++) h->count[len[i]]++;
    419     h->count[0] = 0;
    420     for (i = 0; i < 16; i++) { offs[i] = sum; sum += h->count[i]; }
    421     for (i = 0; i < n; i++) if (len[i]) h->sym[offs[len[i]]++] = i;
    422 }
    423 
    424 static int huff_dec(struct inf *s, const struct huff *h)
    425 {
    426     int code = 0, first = 0, index = 0, l;
    427     for (l = 1; l < 16; l++) {
    428         int c = h->count[l];
    429         code |= getbits(s, 1);
    430         if (code - c < first) return h->sym[index + code - first];
    431         index += c;
    432         first = (first + c) << 1;
    433         code <<= 1;
    434     }
    435     s->bad = 1;
    436     return 256;
    437 }
    438 
    439 static const unsigned short lbase[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 };
    440 static const unsigned char lext[29] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
    441 static const unsigned short dbase[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073,
    442     4097, 6145, 8193, 12289, 16385, 24577 };
    443 static const unsigned char dext[30] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 };
    444 
    445 static void codes(struct inf *s, const struct huff *lh, const struct huff *dh)
    446 {
    447     while (!s->bad) {
    448         int sym = huff_dec(s, lh), d;
    449         unsigned len, dist;
    450         if (sym < 256) { put(s, sym); continue; }
    451         if (sym == 256) return;
    452         sym -= 257;
    453         if (sym >= 29) { s->bad = 1; return; }
    454         len = lbase[sym] + getbits(s, lext[sym]);
    455         d = huff_dec(s, dh);
    456         if (d >= 30) { s->bad = 1; return; }
    457         dist = dbase[d] + getbits(s, dext[d]);
    458         while (len--) put(s, s->win[(s->wpos - dist) & 32767]);
    459     }
    460 }
    461 
    462 static void dynamic(struct inf *s)
    463 {
    464     static const unsigned char ord[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
    465     unsigned char len[320];
    466     struct huff lh, dh;
    467     int nl = getbits(s, 5) + 257, nd = getbits(s, 5) + 1, nc = getbits(s, 4) + 4, i;
    468     memset(len, 0, sizeof len);
    469     for (i = 0; i < nc; i++) len[ord[i]] = getbits(s, 3);
    470     huff_build(&lh, len, 19);
    471     for (i = 0; i < nl + nd && !s->bad; ) {
    472         int sym = huff_dec(s, &lh), rep, v = 0;
    473         if (sym < 16) { len[i++] = sym; continue; }
    474         if (sym == 16) { if (!i) { s->bad = 1; return; } v = len[i - 1]; rep = 3 + getbits(s, 2); }
    475         else if (sym == 17) rep = 3 + getbits(s, 3);
    476         else rep = 11 + getbits(s, 7);
    477         if (i + rep > nl + nd) { s->bad = 1; return; }
    478         while (rep--) len[i++] = v;
    479     }
    480     huff_build(&lh, len, nl);
    481     huff_build(&dh, len + nl, nd);
    482     codes(s, &lh, &dh);
    483 }
    484 
    485 /* one gzip member from r, its bytes go to out. the crc is not checked: what gets unpacked was hashed first */
    486 static int gunzip(struct in *r, outfn *out, void *ctx)
    487 {
    488     static struct huff fixl, fixd;
    489     static int ready;
    490     struct inf *s;
    491     int fl, last, i, bad;
    492     if (!ready) {
    493         unsigned char l[288];
    494         for (i = 0; i < 288; i++) l[i] = i < 144 ? 8 : i < 256 ? 9 : i < 280 ? 7 : 8;
    495         huff_build(&fixl, l, 288);
    496         for (i = 0; i < 30; i++) l[i] = 5;
    497         huff_build(&fixd, l, 30);
    498         ready = 1;
    499     }
    500     if (in_byte(r) != 0x1f || in_byte(r) != 0x8b || in_byte(r) != 8) return -1;
    501     fl = in_byte(r);
    502     for (i = 0; i < 6; i++) in_byte(r);
    503     if (fl & 4) { int n = in_byte(r); n |= in_byte(r) << 8; while (n-- > 0) in_byte(r); }
    504     if (fl & 8) while (in_byte(r) > 0) {}
    505     if (fl & 16) while (in_byte(r) > 0) {}
    506     if (fl & 2) { in_byte(r); in_byte(r); }
    507     s = xmalloc(sizeof *s);
    508     s->in = r; s->bitbuf = 0; s->bitcnt = 0; s->bad = 0; s->wpos = 0; s->out = out; s->ctx = ctx;
    509     do {
    510         int type;
    511         last = getbits(s, 1);
    512         type = getbits(s, 2);
    513         if (type == 0) {
    514             unsigned n;
    515             s->bitbuf = 0; s->bitcnt = 0;
    516             n = in_byte(r); n |= in_byte(r) << 8;
    517             in_byte(r); in_byte(r);
    518             while (n--) { int c = in_byte(r); if (c < 0) { s->bad = 1; break; } put(s, c); }
    519         } else if (type == 1) codes(s, &fixl, &fixd);
    520         else if (type == 2) dynamic(s);
    521         else s->bad = 1;
    522     } while (!last && !s->bad);
    523     if (s->wpos) out(ctx, s->win, s->wpos);
    524     for (i = 0; i < 8; i++) in_byte(r);
    525     bad = s->bad;
    526     free(s);
    527     return bad ? -1 : 0;
    528 }
    529 
    530 /* ---- zstd ---- */
    531 
    532 struct rb { const unsigned char *s; size_t n; long bit; };
    533 
    534 static int rb_init(struct rb *b, const unsigned char *s, size_t n)
    535 {
    536     int h;
    537     if (!n || !s[n - 1]) return -1;
    538     for (h = 7; !(s[n - 1] >> h & 1); h--) {}
    539     b->s = s; b->n = n; b->bit = (long)(n - 1) * 8 + h;
    540     return 0;
    541 }
    542 
    543 static uint64_t rb_peek(const struct rb *b, int k)
    544 {
    545     long lo = b->bit - k;
    546     uint64_t w = 0;
    547     size_t at;
    548     int i, sh;
    549     if (!k) return 0;
    550     if (lo < 0) {
    551         uint64_t v = 0;
    552         long j;
    553         for (j = b->bit - 1; j >= lo; j--) v = v << 1 | (j >= 0 ? b->s[j >> 3] >> (j & 7) & 1 : 0);
    554         return v;
    555     }
    556     at = lo >> 3; sh = lo & 7;
    557     for (i = 0; i < 8 && at + i < b->n; i++) w |= (uint64_t)b->s[at + i] << (8 * i);
    558     return w >> sh & (((uint64_t)1 << k) - 1);
    559 }
    560 
    561 static uint64_t rb_get(struct rb *b, int k) { uint64_t v = rb_peek(b, k); b->bit -= k; return v; }
    562 
    563 struct fse { unsigned char sym, nb; unsigned short base; };
    564 struct ftab { struct fse t[512]; int al; };
    565 
    566 static int highbit(unsigned v) { int h = -1; while (v) { v >>= 1; h++; } return h; }
    567 
    568 static void fse_build(struct ftab *f, const short *norm, int nsym, int al)
    569 {
    570     int size = 1 << al, high = size - 1, pos = 0, step = (size >> 1) + (size >> 3) + 3, s, i;
    571     unsigned short next[64];
    572     f->al = al;
    573     for (s = 0; s < nsym; s++) if (norm[s] == -1) f->t[high--].sym = s;
    574     for (s = 0; s < nsym; s++)
    575         for (i = 0; i < norm[s]; i++) {
    576             f->t[pos].sym = s;
    577             do pos = (pos + step) & (size - 1); while (pos > high);
    578         }
    579     for (s = 0; s < nsym; s++) next[s] = norm[s] == -1 ? 1 : norm[s];
    580     for (i = 0; i < size; i++) {
    581         unsigned n = next[f->t[i].sym]++;
    582         f->t[i].nb = al - highbit(n);
    583         f->t[i].base = (n << f->t[i].nb) - size;
    584     }
    585 }
    586 
    587 static void fse_rle(struct ftab *f, int sym) { f->al = 0; f->t[0].sym = sym; f->t[0].nb = 0; f->t[0].base = 0; }
    588 
    589 /* a table description, read forward; the bytes it took, or -1 */
    590 static long fse_read(struct ftab *f, const unsigned char *p, size_t n, int maxsym, int maxal)
    591 {
    592     short norm[64];
    593     long pos = 0;
    594     int al, remaining, threshold, nb, sym = 0, prev0 = 0;
    595 #define FGET(k) ((size_t)((pos + (k) + 7) >> 3) > n ? -1 : (int)((((uint32_t)p[pos >> 3] | (pos / 8 + 1 < (long)n ? (uint32_t)p[pos / 8 + 1] << 8 : 0) | (pos / 8 + 2 < (long)n ? (uint32_t)p[pos / 8 + 2] << 16 : 0)) >> (pos & 7)) & ((1u << (k)) - 1)))
    596     if (!n) return -1;
    597     al = (p[0] & 15) + 5;
    598     pos = 4;
    599     if (al > maxal) return -1;
    600     remaining = (1 << al) + 1; threshold = 1 << al; nb = al + 1;
    601     while (remaining > 1 && sym <= maxsym) {
    602         int max, count, v;
    603         if (prev0) {
    604             int n0 = sym;
    605             while ((v = FGET(2)) == 3) { n0 += 3; pos += 2; }
    606             if (v < 0) return -1;
    607             n0 += v; pos += 2;
    608             if (n0 > maxsym + 1) return -1;
    609             while (sym < n0) norm[sym++] = 0;
    610             if (sym > maxsym) break;
    611         }
    612         max = (2 * threshold - 1) - remaining;
    613         if ((v = FGET(nb)) < 0 && (v = FGET(nb - 1)) < 0) return -1;
    614         if ((v & (threshold - 1)) < max) { count = v & (threshold - 1); pos += nb - 1; }
    615         else { count = v & (2 * threshold - 1); if (count >= threshold) count -= max; pos += nb; }
    616         count--;
    617         remaining -= count < 0 ? -count : count;
    618         norm[sym++] = count;
    619         prev0 = !count;
    620         while (remaining < threshold) { nb--; threshold >>= 1; }
    621     }
    622 #undef FGET
    623     if (remaining != 1 || (pos + 7) >> 3 > (long)n) return -1;
    624     while (sym <= maxsym) norm[sym++] = 0;
    625     fse_build(f, norm, maxsym + 1, al);
    626     return (pos + 7) >> 3;
    627 }
    628 
    629 struct htab { unsigned short e[2048]; int bits; };   /* sym << 8 | length */
    630 
    631 /* a Huffman tree description: the bytes it took, or -1 */
    632 static long huf_read(struct htab *h, const unsigned char *p, size_t n)
    633 {
    634     unsigned char w[256];
    635     int nw = 0, i, maxbits, rank[13];
    636     unsigned total = 0, rest;
    637     long used;
    638     if (!n) return -1;
    639     if (p[0] >= 128) {
    640         nw = p[0] - 127;
    641         used = 1 + (nw + 1) / 2;
    642         if ((size_t)used > n) return -1;
    643         for (i = 0; i < nw; i++) w[i] = i & 1 ? p[1 + i / 2] & 15 : p[1 + i / 2] >> 4;
    644     } else {
    645         struct ftab f;
    646         struct rb b;
    647         long k;
    648         int s1, s2;
    649         used = 1 + p[0];
    650         if ((size_t)used > n || (k = fse_read(&f, p + 1, p[0], 12, 6)) < 0 || rb_init(&b, p + 1 + k, p[0] - k)) return -1;
    651         s1 = rb_get(&b, f.al); s2 = rb_get(&b, f.al);
    652         for (;;) {
    653             if (nw > 254) return -1;
    654             w[nw++] = f.t[s1].sym;
    655             s1 = f.t[s1].base + rb_get(&b, f.t[s1].nb);
    656             if (b.bit < 0) { w[nw++] = f.t[s2].sym; break; }
    657             if (nw > 254) return -1;
    658             w[nw++] = f.t[s2].sym;
    659             s2 = f.t[s2].base + rb_get(&b, f.t[s2].nb);
    660             if (b.bit < 0) { w[nw++] = f.t[s1].sym; break; }
    661         }
    662     }
    663     for (i = 0; i < nw; i++) { if (w[i] > 12) return -1; if (w[i]) total += 1u << (w[i] - 1); }
    664     if (!total || nw > 255) return -1;
    665     maxbits = highbit(total) + 1;
    666     rest = (1u << maxbits) - total;
    667     if (rest & (rest - 1) || maxbits > 11) return -1;
    668     w[nw++] = highbit(rest) + 1;
    669     h->bits = maxbits;
    670     memset(rank, 0, sizeof rank);
    671     for (i = 0; i < nw; i++) rank[w[i]]++;
    672     {
    673         int start = 0, c, r;
    674         for (r = 1; r <= maxbits; r++) { c = start; start += rank[r] << (r - 1); rank[r] = c; }
    675     }
    676     for (i = 0; i < nw; i++) {
    677         int len, u;
    678         if (!w[i]) continue;
    679         len = 1 << (w[i] - 1);
    680         for (u = rank[w[i]]; u < rank[w[i]] + len; u++) h->e[u] = i << 8 | (maxbits + 1 - w[i]);
    681         rank[w[i]] += len;
    682     }
    683     return used;
    684 }
    685 
    686 static int huf_stream(const struct htab *h, const unsigned char *p, size_t n, unsigned char *out, size_t count)
    687 {
    688     struct rb b;
    689     size_t i;
    690     if (rb_init(&b, p, n)) return -1;
    691     for (i = 0; i < count; i++) {
    692         unsigned e = h->e[rb_peek(&b, h->bits)];
    693         out[i] = e >> 8;
    694         b.bit -= e & 255;
    695     }
    696     return b.bit ? -1 : 0;
    697 }
    698 
    699 static const short ll_def[36] = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 };
    700 static const short ml_def[53] = { 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1 };
    701 static const short of_def[29] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 };
    702 static const unsigned ll_base[36] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 };
    703 static const unsigned char ll_bits[36] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    704 static const unsigned ml_base[53] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
    705     35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539 };
    706 static const unsigned char ml_bits[53] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    707     1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    708 
    709 struct zst {
    710     unsigned char *w, lit[131072 + 8], blk[131072 + 8];
    711     size_t wn, cap, win, lim;
    712     struct htab huf;
    713     struct ftab ll, of, ml;
    714     int hufok, llok, ofok, mlok;
    715     uint64_t rep[3];
    716 };
    717 
    718 static int z_table(struct ftab *f, int *ok, int mode, const unsigned char **p, const unsigned char *end, const short *def, int ndef, int defal, int maxsym, int maxal)
    719 {
    720     long k;
    721     if (mode == 0) fse_build(f, def, ndef, defal);
    722     else if (mode == 1) { if (*p >= end || **p > maxsym) return -1; fse_rle(f, *(*p)++); }
    723     else if (mode == 2) { if ((k = fse_read(f, *p, end - *p, maxsym, maxal)) < 0) return -1; *p += k; }
    724     else if (!*ok) return -1;
    725     *ok = 1;
    726     return 0;
    727 }
    728 
    729 static int z_block(struct zst *z, const unsigned char *p, size_t n)
    730 {
    731     const unsigned char *end = p + n;
    732     size_t nlit, csize = 0, i, li = 0;
    733     int type, sf, nseq, modes;
    734     if (!n) return -1;
    735     type = p[0] & 3; sf = p[0] >> 2 & 3;
    736     if (type < 2) {
    737         if (sf == 1) { if (n < 2) return -1; nlit = (p[0] >> 4) + (p[1] << 4); p += 2; }
    738         else if (sf == 3) { if (n < 3) return -1; nlit = (p[0] >> 4) + (p[1] << 4) + (p[2] << 12); p += 3; }
    739         else { nlit = p[0] >> 3; p++; }
    740         if (nlit > 131072 || (size_t)(end - p) < (type ? 1 : nlit)) return -1;
    741         if (type) { memset(z->lit, *p, nlit); p++; } else { memcpy(z->lit, p, nlit); p += nlit; }
    742     } else {
    743         int streams = sf ? 4 : 1;
    744         uint32_t h;
    745         if (sf < 2) { if (n < 3) return -1; h = p[0] | p[1] << 8 | p[2] << 16; nlit = h >> 4 & 0x3ff; csize = h >> 14 & 0x3ff; p += 3; }
    746         else if (sf == 2) { if (n < 4) return -1; h = p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; nlit = h >> 4 & 0x3fff; csize = h >> 18; p += 4; }
    747         else { if (n < 5) return -1; h = p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; nlit = h >> 4 & 0x3ffff; csize = (h >> 22) | p[4] << 10; p += 5; }
    748         if (nlit > 131072 || (size_t)(end - p) < csize) return -1;
    749         {
    750             const unsigned char *q = p, *qe = p + csize;
    751             p += csize;
    752             if (type == 2) { long k = huf_read(&z->huf, q, csize); if (k < 0) return -1; q += k; z->hufok = 1; }
    753             else if (!z->hufok) return -1;
    754             if (streams == 1) { if (huf_stream(&z->huf, q, qe - q, z->lit, nlit)) return -1; }
    755             else {
    756                 size_t s[4], each = (nlit + 3) / 4, at = 0;
    757                 int j;
    758                 if (qe - q < 6) return -1;
    759                 s[0] = q[0] | q[1] << 8; s[1] = q[2] | q[3] << 8; s[2] = q[4] | q[5] << 8;
    760                 q += 6;
    761                 if (s[0] + s[1] + s[2] > (size_t)(qe - q)) return -1;
    762                 s[3] = (qe - q) - s[0] - s[1] - s[2];
    763                 for (j = 0; j < 4; j++) {
    764                     size_t c = j < 3 ? each : nlit - 3 * each;
    765                     if (j == 3 && 3 * each > nlit) return -1;
    766                     if (huf_stream(&z->huf, q, s[j], z->lit + at, c)) return -1;
    767                     q += s[j]; at += c;
    768                 }
    769             }
    770         }
    771     }
    772     if (p >= end) return -1;
    773     nseq = *p++;
    774     if (nseq >= 128) {
    775         if (p >= end) return -1;
    776         if (nseq < 255) nseq = ((nseq - 128) << 8) + *p++;
    777         else { if (end - p < 2) return -1; nseq = p[0] + (p[1] << 8) + 0x7f00; p += 2; }
    778     }
    779     if (nseq) {
    780         struct rb b;
    781         int sl, so, sm;
    782         if (p >= end) return -1;
    783         modes = *p++;
    784         if (z_table(&z->ll, &z->llok, modes >> 6, &p, end, ll_def, 36, 6, 35, 9) ||
    785             z_table(&z->of, &z->ofok, modes >> 4 & 3, &p, end, of_def, 29, 5, 31, 8) ||
    786             z_table(&z->ml, &z->mlok, modes >> 2 & 3, &p, end, ml_def, 53, 6, 52, 9) ||
    787             rb_init(&b, p, end - p)) return -1;
    788         sl = rb_get(&b, z->ll.al); so = rb_get(&b, z->of.al); sm = rb_get(&b, z->ml.al);
    789         while (nseq--) {
    790             int oc = z->of.t[so].sym, mc = z->ml.t[sm].sym, lc = z->ll.t[sl].sym;
    791             uint64_t off, ml, ll;
    792             if (oc > 31 || mc > 52 || lc > 35) return -1;
    793             off = ((uint64_t)1 << oc) + rb_get(&b, oc);
    794             ml = ml_base[mc] + rb_get(&b, ml_bits[mc]);
    795             ll = ll_base[lc] + rb_get(&b, ll_bits[lc]);
    796             if (off > 3) { z->rep[2] = z->rep[1]; z->rep[1] = z->rep[0]; z->rep[0] = off -= 3; }
    797             else {
    798                 int k = off - 1 + !ll;
    799                 if (k) {
    800                     off = k == 3 ? z->rep[0] - 1 : z->rep[k];
    801                     if (k > 1) z->rep[2] = z->rep[1];
    802                     z->rep[1] = z->rep[0]; z->rep[0] = off;
    803                 } else off = z->rep[0];
    804             }
    805             if (nseq) {
    806                 sl = z->ll.t[sl].base + rb_get(&b, z->ll.t[sl].nb);
    807                 sm = z->ml.t[sm].base + rb_get(&b, z->ml.t[sm].nb);
    808                 so = z->of.t[so].base + rb_get(&b, z->of.t[so].nb);
    809             }
    810             if (li + ll > nlit || z->wn + ll + ml > z->lim) return -1;
    811             memcpy(z->w + z->wn, z->lit + li, ll);
    812             z->wn += ll; li += ll;
    813             if (off > z->wn) return -1;
    814             for (i = 0; i < ml; i++, z->wn++) z->w[z->wn] = z->w[z->wn - off];
    815         }
    816         if (b.bit) return -1;
    817     } else if (p != end) return -1;
    818     if (z->wn + nlit - li > z->lim) return -1;
    819     memcpy(z->w + z->wn, z->lit + li, nlit - li);
    820     z->wn += nlit - li;
    821     return 0;
    822 }
    823 
    824 static int unzstd(struct in *r, outfn *out, void *ctx)
    825 {
    826     struct zst *z = xmalloc(sizeof *z);
    827     int c, bad = -1, frames = 0;
    828     memset(z, 0, sizeof *z);
    829     for (;;) {
    830         uint32_t magic = 0;
    831         uint64_t fcs = 0;
    832         int i, fhd, single, sum, did, fb, last;
    833         if (frames && in_eof(r)) { bad = 0; break; }
    834         for (i = 0; i < 4; i++) { if ((c = in_byte(r)) < 0) goto out; magic |= (uint32_t)c << (8 * i); }
    835         frames++;
    836         if ((magic & 0xfffffff0) == 0x184d2a50) {
    837             uint32_t len = 0;
    838             for (i = 0; i < 4; i++) { if ((c = in_byte(r)) < 0) goto out; len |= (uint32_t)c << (8 * i); }
    839             while (len--) if (in_byte(r) < 0) goto out;
    840             continue;
    841         }
    842         if (magic != 0xfd2fb528 || (fhd = in_byte(r)) < 0 || fhd & 8) goto out;
    843         single = fhd >> 5 & 1; sum = fhd >> 2 & 1;
    844         if (!single) {
    845             int wd = in_byte(r), e;
    846             if (wd < 0 || (e = 10 + (wd >> 3)) > 31) goto out;
    847             z->win = ((size_t)1 << e) + (((size_t)1 << e) >> 3) * (wd & 7);
    848         }
    849         did = (int[]){ 0, 1, 2, 4 }[fhd & 3];
    850         while (did--) if (in_byte(r) < 0) goto out;
    851         fb = (int[]){ single, 2, 4, 8 }[fhd >> 6];
    852         for (i = 0; i < fb; i++) { if ((c = in_byte(r)) < 0) goto out; fcs |= (uint64_t)c << (8 * i); }
    853         if (fb == 2) fcs += 256;
    854         if (single) z->win = fcs;
    855         if (z->win > (size_t)1 << 31) goto out;
    856         if (z->cap < 2 * z->win + 3 * 131072) { free(z->w); z->cap = 2 * z->win + 3 * 131072; z->w = xmalloc(z->cap); }
    857         z->wn = 0; z->rep[0] = 1; z->rep[1] = 4; z->rep[2] = 8;
    858         z->hufok = z->llok = z->ofok = z->mlok = 0;
    859         do {
    860             uint32_t h = 0, size;
    861             int type;
    862             size_t done = z->wn;
    863             for (i = 0; i < 3; i++) { if ((c = in_byte(r)) < 0) goto out; h |= (uint32_t)c << (8 * i); }
    864             last = h & 1; type = h >> 1 & 3; size = h >> 3;
    865             if (type == 3 || size > 131072) goto out;
    866             if (z->wn + 131072 > z->cap) {
    867                 size_t keep = z->win < z->wn ? z->win : z->wn;
    868                 memmove(z->w, z->w + z->wn - keep, keep);
    869                 z->wn = done = keep;
    870             }
    871             z->lim = z->wn + 131072;
    872             if (type == 1) {
    873                 if ((c = in_byte(r)) < 0) goto out;
    874                 memset(z->w + z->wn, c, size);
    875                 z->wn += size;
    876             } else {
    877                 for (i = 0; (uint32_t)i < size; i++) { if ((c = in_byte(r)) < 0) goto out; z->blk[i] = c; }
    878                 if (type == 0) { memcpy(z->w + z->wn, z->blk, size); z->wn += size; }
    879                 else if (z_block(z, z->blk, size)) goto out;
    880             }
    881             if (z->wn > done) out(ctx, z->w + done, z->wn - done);
    882         } while (!last);
    883         if (sum) for (i = 0; i < 4; i++) if (in_byte(r) < 0) goto out;
    884     }
    885 out:
    886     free(z->w);
    887     free(z);
    888     return bad;
    889 }
    890 
    891 struct buf { unsigned char *p; size_t n, cap; };
    892 
    893 static void buf_add(struct buf *b, const void *d, size_t n)
    894 {
    895     if (b->n + n + 1 > b->cap) { b->cap = (b->n + n + 1) * 2; b->p = xrealloc(b->p, b->cap); }
    896     memcpy(b->p + b->n, d, n);
    897     b->n += n;
    898     b->p[b->n] = 0;
    899 }
    900 
    901 /* ---- tar, fed a piece at a time ---- */
    902 
    903 struct ent { char *name; struct buf data; };
    904 
    905 struct tar {
    906     unsigned char hdr[512];
    907     size_t hn;
    908     uint64_t left, pad;
    909     int what;                   /* where the bytes of this entry go: 0 nowhere, 1 a file, 2 meta, 3 an ent */
    910     int type, fd, bad;
    911     struct buf meta;
    912     char *path, *link;
    913     unsigned mode, uid, gid;
    914     char uname[33], gname[33];
    915     const char *dir;            /* unpack here; NULL keeps the files in ents instead */
    916     struct ent *ents;
    917     int nents;
    918 };
    919 
    920 static uint64_t octal(const unsigned char *p, int n)
    921 {
    922     uint64_t v = 0;
    923     if (*p & 0x80) { v = *p++ & 0x7f; while (--n) v = v << 8 | *p++; return v; }
    924     while (n && *p == ' ') p++, n--;
    925     for (; n && *p >= '0' && *p <= '7'; p++, n--) v = v * 8 + (*p - '0');
    926     return v;
    927 }
    928 
    929 /* a path from an archive that stays inside the directory: no .. and no leading / */
    930 static char *clean(const char *name)
    931 {
    932     struct list parts = { 0 };
    933     char *out;
    934     size_t len = 0;
    935     int i;
    936     while (*name) {
    937         size_t n = strcspn(name, "/");
    938         if (n && !(n == 1 && *name == '.')) {
    939             if (n == 2 && name[0] == '.' && name[1] == '.') { list_free(&parts); return NULL; }
    940             push(&parts, xstrndup(name, n));
    941             len += n + 1;
    942         }
    943         name += n;
    944         if (*name) name++;
    945     }
    946     if (!parts.n) return NULL;
    947     out = xmalloc(len + 1);
    948     *out = 0;
    949     for (i = 0; i < parts.n; i++) { if (i) strcat(out, "/"); strcat(out, parts.v[i]); }
    950     list_free(&parts);
    951     return out;
    952 }
    953 
    954 static void tar_done(struct tar *t)
    955 {
    956     if (t->what == 2) {
    957         char *p = (char *)t->meta.p, *end = p + t->meta.n;
    958         if (t->type == 'L') { free(t->path); t->path = xstrdup(p); }
    959         else if (t->type == 'K') { free(t->link); t->link = xstrdup(p); }
    960         else while (p < end) {
    961             char *sp = strchr(p, ' '), *eq, *rec = p;
    962             long n = strtol(p, NULL, 10);
    963             if (!sp || n <= 0 || rec + n > end) break;
    964             eq = strchr(sp, '=');
    965             if (eq && eq < rec + n) {
    966                 char *val = xstrndup(eq + 1, rec + n - eq - 2);
    967                 if (eq - sp - 1 == 4 && !strncmp(sp + 1, "path", 4)) { free(t->path); t->path = val; }
    968                 else if (eq - sp - 1 == 8 && !strncmp(sp + 1, "linkpath", 8)) { free(t->link); t->link = val; }
    969                 else free(val);
    970             }
    971             p = rec + n;
    972         }
    973         t->meta.n = 0;
    974         t->what = 0;
    975         return;
    976     }
    977     if (t->what == 1) {
    978         if (!geteuid()) fchown(t->fd, t->uid, t->gid);
    979         fchmod(t->fd, t->mode & 07777);
    980         if (close(t->fd) < 0) t->bad = 1;
    981     }
    982     t->what = 0;
    983     free(t->path); t->path = NULL;
    984     free(t->link); t->link = NULL;
    985 }
    986 
    987 /* owners by name, "path\tuser\tgroup": the ids are the build machine's, the names are what the package means */
    988 static struct list named;
    989 
    990 static void tar_entry(struct tar *t, const char *name, const char *ln)
    991 {
    992     char *rel = clean(name), *full;
    993     int type = t->type, file = type == '0' || type == 0 || type == '7';
    994     t->what = 0;
    995     if (!rel) return;
    996     if (!t->dir) {
    997         if (file) {
    998             t->ents = xrealloc(t->ents, (t->nents + 1) * sizeof *t->ents);
    999             t->ents[t->nents].name = rel;
   1000             memset(&t->ents[t->nents].data, 0, sizeof t->ents[t->nents].data);
   1001             buf_add(&t->ents[t->nents].data, "", 0);
   1002             t->nents++;
   1003             t->what = 3;
   1004         } else free(rel);
   1005         return;
   1006     }
   1007     if ((*t->uname && strcmp(t->uname, "root")) || (*t->gname && strcmp(t->gname, "root")))
   1008         push(&named, fmt("%s\t%s\t%s", rel, *t->uname ? t->uname : "root", *t->gname ? t->gname : "root"));
   1009     full = fmt("%s/%s", t->dir, rel);
   1010     mkparent(full);
   1011     if (type == '5') {
   1012         mkpath(full, 0755);
   1013         chmod(full, t->mode & 07777);
   1014         if (!geteuid()) lchown(full, t->uid, t->gid);
   1015     } else if (type == '2') {
   1016         unlink(full);
   1017         if (symlink(ln, full) < 0) t->bad = 1;
   1018         else if (!geteuid()) lchown(full, t->uid, t->gid);
   1019     } else if (type == '1') {
   1020         char *l = clean(ln), *from = l ? fmt("%s/%s", t->dir, l) : NULL;
   1021         unlink(full);
   1022         if (!from || link(from, full) < 0) t->bad = 1;
   1023         free(l); free(from);
   1024     } else if (file) {
   1025         unlink(full);
   1026         t->fd = open(full, O_WRONLY | O_CREAT | O_TRUNC, 0600);
   1027         if (t->fd < 0) t->bad = 1; else t->what = 1;
   1028     }
   1029     free(full);
   1030     free(rel);
   1031 }
   1032 
   1033 static void tar_header(struct tar *t)
   1034 {
   1035     unsigned char *h = t->hdr;
   1036     char name[300], ln[101];
   1037     uint64_t size;
   1038     if (!h[0]) return;
   1039     size = octal(h + 124, 12);
   1040     t->type = h[156];
   1041     t->mode = octal(h + 100, 8);
   1042     t->uid = octal(h + 108, 8);
   1043     t->gid = octal(h + 116, 8);
   1044     memcpy(t->uname, h + 265, 32); t->uname[32] = 0;
   1045     memcpy(t->gname, h + 297, 32); t->gname[32] = 0;
   1046     name[0] = 0;
   1047     if (!memcmp(h + 257, "ustar", 5) && h[345]) { memcpy(name, h + 345, 155); name[155] = 0; strcat(name, "/"); }
   1048     { size_t l = strlen(name), k = 0; while (k < 100 && h[k]) { name[l + k] = h[k]; k++; } name[l + k] = 0; }
   1049     memcpy(ln, h + 157, 100); ln[100] = 0;
   1050     t->left = size;
   1051     t->pad = (512 - size % 512) % 512;
   1052     if (t->type == 'x' || t->type == 'L' || t->type == 'K') { t->what = 2; t->meta.n = 0; buf_add(&t->meta, "", 0); }
   1053     else if (t->type == 'g') t->what = 0;
   1054     else tar_entry(t, t->path ? t->path : name, t->link ? t->link : ln);
   1055     if (!size) tar_done(t);
   1056 }
   1057 
   1058 static void tar_out(void *ctx, const unsigned char *d, size_t n)
   1059 {
   1060     struct tar *t = ctx;
   1061     while (n) {
   1062         size_t k;
   1063         if (t->left) {
   1064             k = t->left < n ? t->left : n;
   1065             if (t->what == 1 && write(t->fd, d, k) != (ssize_t)k) t->bad = 1;
   1066             else if (t->what == 2) buf_add(&t->meta, d, k);
   1067             else if (t->what == 3) buf_add(&t->ents[t->nents - 1].data, d, k);
   1068             t->left -= k; d += k; n -= k;
   1069             if (!t->left) tar_done(t);
   1070         } else if (t->pad) {
   1071             k = t->pad < n ? t->pad : n;
   1072             t->pad -= k; d += k; n -= k;
   1073         } else {
   1074             k = 512 - t->hn < n ? 512 - t->hn : n;
   1075             memcpy(t->hdr + t->hn, d, k);
   1076             t->hn += k; d += k; n -= k;
   1077             if (t->hn == 512) { t->hn = 0; tar_header(t); }
   1078         }
   1079     }
   1080 }
   1081 
   1082 static struct ent *tar_find(struct tar *t, const char *name)
   1083 {
   1084     int i;
   1085     for (i = 0; i < t->nents; i++) if (!strcmp(t->ents[i].name, name)) return &t->ents[i];
   1086     return NULL;
   1087 }
   1088 
   1089 static struct ent *tar_prefix(struct tar *t, const char *prefix)
   1090 {
   1091     int i;
   1092     for (i = 0; i < t->nents; i++) if (!strncmp(t->ents[i].name, prefix, strlen(prefix))) return &t->ents[i];
   1093     return NULL;
   1094 }
   1095 
   1096 static void tar_free(struct tar *t)
   1097 {
   1098     int i;
   1099     for (i = 0; i < t->nents; i++) { free(t->ents[i].name); free(t->ents[i].data.p); }
   1100     free(t->ents); free(t->meta.p); free(t->path); free(t->link);
   1101     memset(t, 0, sizeof *t);
   1102 }
   1103 
   1104 /* ---- rsa, for the signatures ---- */
   1105 
   1106 #define LIMBS 130               /* 4160 bits, room for a 4096 bit key */
   1107 
   1108 static int big_less(const unsigned *a, const unsigned *b)
   1109 {
   1110     int i;
   1111     for (i = LIMBS; i >= 0; i--) if (a[i] != b[i]) return a[i] < b[i];
   1112     return 0;
   1113 }
   1114 
   1115 static void big_sub(unsigned *a, const unsigned *b)
   1116 {
   1117     uint64_t borrow = 0;
   1118     int i;
   1119     for (i = 0; i <= LIMBS; i++) {
   1120         uint64_t d = (uint64_t)a[i] - b[i] - borrow;
   1121         a[i] = d;
   1122         borrow = d >> 63;
   1123     }
   1124 }
   1125 
   1126 /* r = a * b mod n, all LIMBS + 1 long */
   1127 static void big_mulmod(unsigned *r, const unsigned *a, const unsigned *b, const unsigned *n)
   1128 {
   1129     unsigned p[2 * LIMBS], m[LIMBS + 1];
   1130     int i, j, top;
   1131     memset(p, 0, sizeof p);
   1132     for (i = 0; i < LIMBS; i++) {
   1133         uint64_t c = 0;
   1134         for (j = 0; j < LIMBS; j++) { c += (uint64_t)a[i] * b[j] + p[i + j]; p[i + j] = c; c >>= 32; }
   1135         p[i + LIMBS] = c;
   1136     }
   1137     memset(m, 0, sizeof m);
   1138     for (top = 2 * LIMBS * 32 - 1; top >= 0 && !(p[top / 32] >> (top % 32) & 1); top--) {}
   1139     for (i = top; i >= 0; i--) {
   1140         for (j = LIMBS; j > 0; j--) m[j] = m[j] << 1 | m[j - 1] >> 31;
   1141         m[0] = m[0] << 1 | (p[i / 32] >> (i % 32) & 1);
   1142         if (!big_less(m, n)) big_sub(m, n);
   1143     }
   1144     memcpy(r, m, sizeof m);
   1145 }
   1146 
   1147 static int big_from(unsigned *v, const unsigned char *p, size_t n)
   1148 {
   1149     size_t i;
   1150     memset(v, 0, (LIMBS + 1) * 4);
   1151     while (n && !*p) p++, n--;
   1152     if (n > LIMBS * 4) return -1;
   1153     for (i = 0; i < n; i++) v[i / 4] |= (unsigned)p[n - 1 - i] << (8 * (i % 4));
   1154     return 0;
   1155 }
   1156 
   1157 static int der(const unsigned char **p, const unsigned char *end, int tag, size_t *len)
   1158 {
   1159     const unsigned char *q = *p;
   1160     size_t n;
   1161     if (q + 2 > end || *q++ != tag) return -1;
   1162     n = *q++;
   1163     if (n & 0x80) {
   1164         int k = n & 0x7f;
   1165         if (k > 4 || q + k > end) return -1;
   1166         for (n = 0; k--; ) n = n << 8 | *q++;
   1167     }
   1168     if (q + n > end) return -1;
   1169     *p = q;
   1170     *len = n;
   1171     return 0;
   1172 }
   1173 
   1174 /* a pkcs#1 v1.5 signature over digest with the key n, e; kind 1 sha1, 0 sha256, 2 sha512 */
   1175 static int rsa_check(const unsigned char *nb, size_t nlen, const unsigned char *eb, size_t elen, const unsigned char *sig, size_t siglen, const unsigned char *digest, int kind)
   1176 {
   1177     static const unsigned char info1[] = { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
   1178     static const unsigned char info256[] = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };
   1179     static const unsigned char info512[] = { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 };
   1180     const unsigned char *info = kind == 1 ? info1 : kind == 2 ? info512 : info256;
   1181     size_t ilen = kind == 1 ? sizeof info1 : kind == 2 ? sizeof info512 : sizeof info256, dlen = kind == 1 ? 20 : kind == 2 ? 64 : 32, k, i;
   1182     unsigned n[LIMBS + 1], s[LIMBS + 1], r[LIMBS + 1], ev = 0;
   1183     unsigned char em[LIMBS * 4];
   1184     int top, bit;
   1185     while (nlen && !*nb) nb++, nlen--;
   1186     while (siglen > nlen && !*sig) sig++, siglen--;
   1187     k = nlen;
   1188     if (elen > 4 || siglen > k || big_from(n, nb, nlen) || big_from(s, sig, siglen) || !big_less(s, n)) return -1;
   1189     for (i = 0; i < elen; i++) ev = ev << 8 | eb[i];
   1190     if (!ev) return -1;
   1191     for (top = 31; top > 0 && !(ev >> top & 1); top--) {}
   1192     memcpy(r, s, sizeof r);
   1193     for (bit = top - 1; bit >= 0; bit--) {
   1194         big_mulmod(r, r, r, n);
   1195         if (ev >> bit & 1) big_mulmod(r, r, s, n);
   1196     }
   1197     for (i = 0; i < k; i++) em[k - 1 - i] = r[i / 4] >> (8 * (i % 4));
   1198     if (k < ilen + dlen + 11 || em[0] != 0 || em[1] != 1) return -1;
   1199     for (i = 2; i < k - ilen - dlen - 1; i++) if (em[i] != 0xff) return -1;
   1200     if (em[i++] != 0 || memcmp(em + i, info, ilen) || memcmp(em + i + ilen, digest, dlen)) return -1;
   1201     return 0;
   1202 }
   1203 
   1204 /* a pkcs#1 v1.5 signature over digest, checked with the public key in keyfile (pem) */
   1205 static int rsa_verify(const char *keyfile, const unsigned char *sig, size_t siglen, const unsigned char *digest, int sha1)
   1206 {
   1207     unsigned char derbuf[4096];
   1208     const unsigned char *p = derbuf, *end, *nb;
   1209     size_t len, nlen, elen;
   1210     char *pem = slurp(keyfile, NULL), *b, *e;
   1211     if (!pem || !(b = strstr(pem, "KEY-----")) || !(e = strstr(b, "-----END")) || (size_t)(e - b) * 3 / 4 > sizeof derbuf) { free(pem); return -1; }
   1212     *e = 0;
   1213     end = derbuf + unbase64(b + 8, derbuf);
   1214     free(pem);
   1215     if (der(&p, end, 0x30, &len) || der(&p, end, 0x30, &len)) return -1;
   1216     p += len;
   1217     if (der(&p, end, 0x03, &len) || ++p > end || der(&p, end, 0x30, &len)) return -1;
   1218     if (der(&p, end, 0x02, &nlen)) return -1;
   1219     nb = p; p += nlen;
   1220     if (der(&p, end, 0x02, &elen)) return -1;
   1221     {
   1222         size_t k = nlen;
   1223         const unsigned char *q = nb;
   1224         while (k && !*q) q++, k--;
   1225         if (siglen != k) return -1;
   1226     }
   1227     return rsa_check(nb, nlen, p, elen, sig, siglen, digest, sha1);
   1228 }
   1229 
   1230 /* ---- OpenPGP, for pacman repos: rsa keys from keyrings, v4 signatures over a whole file ---- */
   1231 
   1232 struct pgpkey { unsigned char fp[20]; const unsigned char *n, *e; size_t nl, el; int algo; };
   1233 static struct pgpkey *pgpkeys;
   1234 static int npgpkeys, pgploaded;
   1235 
   1236 /* one packet: its tag and body, or -1 */
   1237 static int pgp_packet(const unsigned char **p, const unsigned char *end, const unsigned char **body, size_t *len)
   1238 {
   1239     const unsigned char *q = *p;
   1240     int c, tag;
   1241     size_t n = 0;
   1242     if (q >= end || !(*q & 0x80)) return -1;
   1243     c = *q++;
   1244     if (c & 0x40) {
   1245         tag = c & 63;
   1246         if (q >= end) return -1;
   1247         if (*q < 192) n = *q++;
   1248         else if (*q < 224) { if (end - q < 2) return -1; n = ((q[0] - 192) << 8) + q[1] + 192; q += 2; }
   1249         else if (*q == 255) { if (end - q < 5) return -1; n = (size_t)q[1] << 24 | q[2] << 16 | q[3] << 8 | q[4]; q += 5; }
   1250         else return -1;
   1251     } else {
   1252         int lt = c & 3, i;
   1253         tag = c >> 2 & 15;
   1254         if (lt == 3) n = end - q;
   1255         else {
   1256             if (end - q < (1 << lt)) return -1;
   1257             for (i = 0; i < 1 << lt; i++) n = n << 8 | *q++;
   1258         }
   1259     }
   1260     if ((size_t)(end - q) < n) return -1;
   1261     *body = q; *len = n; *p = q + n;
   1262     return tag;
   1263 }
   1264 
   1265 static int mpi(const unsigned char **p, const unsigned char *end, const unsigned char **v, size_t *n)
   1266 {
   1267     size_t bits;
   1268     if (end - *p < 2) return -1;
   1269     bits = (*p)[0] << 8 | (*p)[1];
   1270     *n = (bits + 7) / 8;
   1271     if ((size_t)(end - *p - 2) < *n) return -1;
   1272     *v = *p + 2;
   1273     *p += 2 + *n;
   1274     return 0;
   1275 }
   1276 
   1277 /* the binary packets of an armored keyring, every block of it */
   1278 static unsigned char *dearmor(char *t, size_t *n)
   1279 {
   1280     unsigned char *out = xmalloc(strlen(t) + 1);
   1281     char *s = t, *e;
   1282     size_t o = 0;
   1283     while ((s = strstr(s, "-----BEGIN PGP"))) {
   1284         if (!(s = strstr(s, "\n\n")) && !(s = strstr(s, "\n\r\n"))) break;
   1285         s += 2;
   1286         for (; *s && *s != '=' && *s != '-'; s = e) {
   1287             char c;
   1288             e = s + strcspn(s, "\n");
   1289             c = *e; *e = 0;
   1290             o += unbase64(s, out + o);
   1291             *e = c;
   1292             if (*e) e++;
   1293         }
   1294     }
   1295     *n = o;
   1296     return out;
   1297 }
   1298 
   1299 static void pgp_keyring(const char *file, const struct list *revoked)
   1300 {
   1301     size_t n;
   1302     unsigned char *t = (unsigned char *)slurp(file, &n);
   1303     if (t && n > 10 && !memcmp(t, "-----", 5)) { unsigned char *b = dearmor((char *)t, &n); free(t); t = b; }
   1304     const unsigned char *p = t, *end = t + (t ? n : 0), *b;
   1305     size_t len;
   1306     int tag;
   1307     while (t && (tag = pgp_packet(&p, end, &b, &len)) >= 0) {
   1308         struct pgpkey k;
   1309         struct hash h;
   1310         unsigned char hd[3] = { 0x99, len >> 8, len };
   1311         const unsigned char *q = b + 6;
   1312         char *fp;
   1313         if ((tag != 6 && tag != 14) || len < 8 || b[0] != 4) continue;
   1314         if (b[5] >= 1 && b[5] <= 3) {
   1315             if (mpi(&q, b + len, &k.n, &k.nl) || mpi(&q, b + len, &k.e, &k.el)) continue;
   1316             k.algo = 1;
   1317         } else if (b[5] == 22) {
   1318             /* ed25519: its oid, then the point as 0x40 and 32 bytes */
   1319             if (q >= b + len || q + 1 + *q > b + len || *q != 9 || memcmp(q + 1, "\x2b\x06\x01\x04\x01\xda\x47\x0f\x01", 9)) continue;
   1320             q += 1 + *q;
   1321             if (mpi(&q, b + len, &k.n, &k.nl) || k.nl != 33 || k.n[0] != 0x40) continue;
   1322             k.n++; k.nl = 32; k.e = NULL; k.el = 0;
   1323             k.algo = 22;
   1324         } else continue;
   1325         hash_init(&h, 1);
   1326         hash_add(&h, hd, 3);
   1327         hash_add(&h, b, len);
   1328         hash_end(&h, k.fp);
   1329         fp = hex(k.fp, 20);
   1330         for (tag = 0; tag < revoked->n && strcasecmp(revoked->v[tag], fp); tag++) {}
   1331         free(fp);
   1332         if (tag < revoked->n) continue;
   1333         if (npgpkeys % 64 == 0) pgpkeys = xrealloc(pgpkeys, (npgpkeys + 64) * sizeof *pgpkeys);
   1334         pgpkeys[npgpkeys++] = k;
   1335     }
   1336 }
   1337 
   1338 static char *confdir(void);
   1339 static int ed25519_ok(const unsigned char *sig, const unsigned char *pk, const char *m, size_t n);
   1340 
   1341 /* the .gpg keyrings in mag's keys and the ones packages put in /usr/share/pacman/keyrings, without the revoked keys */
   1342 static void pgp_load(void)
   1343 {
   1344     char *dirs[2], *rev = fmt("%s/usr/share/pacman/keyrings", root), *c = confdir();
   1345     struct list revoked = { 0 };
   1346     int i;
   1347     DIR *d;
   1348     struct dirent *e;
   1349     if (pgploaded++) return;
   1350     dirs[0] = fmt("%s/keys", c); dirs[1] = rev;
   1351     free(c);
   1352     if ((d = opendir(rev))) {
   1353         while ((e = readdir(d))) {
   1354             size_t l = strlen(e->d_name);
   1355             char *f, *t, *line, *next;
   1356             if (l < 8 || strcmp(e->d_name + l - 8, "-revoked")) continue;
   1357             f = fmt("%s/%s", rev, e->d_name);
   1358             for (line = t = slurp(f, NULL); line && *line; line = next) {
   1359                 next = strchr(line, '\n');
   1360                 if (next) *next++ = 0;
   1361                 if (*line) push(&revoked, xstrdup(line));
   1362             }
   1363             free(t); free(f);
   1364         }
   1365         closedir(d);
   1366     }
   1367     for (i = 0; i < 2; i++) {
   1368         if (!(d = opendir(dirs[i]))) continue;
   1369         while ((e = readdir(d))) {
   1370             size_t l = strlen(e->d_name);
   1371             if (l > 4 && !strcmp(e->d_name + l - 4, ".gpg")) { char *f = fmt("%s/%s", dirs[i], e->d_name); pgp_keyring(f, &revoked); free(f); }
   1372         }
   1373         closedir(d);
   1374     }
   1375     list_free(&revoked);
   1376     free(dirs[0]); free(dirs[1]);
   1377 }
   1378 
   1379 /* sig is a binary OpenPGP signature of the file: 0 good, -1 bad, 1 no key for it */
   1380 static int pgp_verify(const char *file, const unsigned char *sig, size_t siglen)
   1381 {
   1382     const unsigned char *p = sig, *b, *q, *issuer = NULL, *v;
   1383     size_t len, hl, ul, vl;
   1384     unsigned char dig[64], tr[6];
   1385     struct hash h;
   1386     int tag, kind, i, area, fd;
   1387     off_t n;
   1388     static unsigned char buf[65536];
   1389     ssize_t r;
   1390     if ((tag = pgp_packet(&p, sig + siglen, &b, &len)) != 2 || len < 12 || b[0] != 4 || b[1] != 0 || (b[2] != 1 && b[2] != 22)) return -1;
   1391     kind = b[3] == 8 ? 0 : b[3] == 10 ? 2 : -1;
   1392     if (kind < 0) return -1;
   1393     hl = b[4] << 8 | b[5];
   1394     if (6 + hl + 2 > len) return -1;
   1395     ul = b[6 + hl] << 8 | b[7 + hl];
   1396     if (8 + hl + ul + 2 > len) return -1;
   1397     for (area = 0; area < 2 && !issuer; area++) {
   1398         const unsigned char *s = area ? b + 8 + hl : b + 6, *se = s + (area ? ul : hl);
   1399         while (s < se && !issuer) {
   1400             size_t sl;
   1401             if (*s < 192) sl = *s++;
   1402             else if (*s < 255) { if (se - s < 2) break; sl = ((s[0] - 192) << 8) + s[1] + 192; s += 2; }
   1403             else { if (se - s < 5) break; sl = (size_t)s[1] << 24 | s[2] << 16 | s[3] << 8 | s[4]; s += 5; }
   1404             if (!sl || (size_t)(se - s) < sl) break;
   1405             if ((s[0] & 127) == 33 && sl == 22 && s[1] == 4) issuer = s + 2;
   1406             s += sl;
   1407         }
   1408     }
   1409     q = b + 8 + hl + ul + 2;
   1410     if (mpi(&q, b + len, &v, &vl)) return -1;
   1411     pgp_load();
   1412     for (i = 0; i < npgpkeys && (!issuer || memcmp(pgpkeys[i].fp, issuer, 20) || pgpkeys[i].algo != (b[2] == 22 ? 22 : 1)); i++) {}
   1413     if (i == npgpkeys) {
   1414         /* no fingerprint subpacket: the 8 byte key id instead */
   1415         const unsigned char *s = b + 8 + hl, *se = s + ul;
   1416         const unsigned char *id = NULL;
   1417         while (s + 2 <= se && !id) { size_t sl = *s++; if (sl >= 192 || (size_t)(se - s) < sl) break; if ((s[0] & 127) == 16 && sl == 9) id = s + 1; s += sl; }
   1418         for (i = 0; id && i < npgpkeys && memcmp(pgpkeys[i].fp + 12, id, 8); i++) {}
   1419         if (!id || i == npgpkeys) return 1;
   1420     }
   1421     if ((fd = open(file, O_RDONLY)) < 0) return -1;
   1422     hash_init(&h, kind);
   1423     while ((r = read(fd, buf, sizeof buf)) > 0) hash_add(&h, buf, r);
   1424     close(fd);
   1425     hash_add(&h, b, 6 + hl);
   1426     n = 6 + hl;
   1427     tr[0] = 4; tr[1] = 0xff; tr[2] = n >> 24; tr[3] = n >> 16; tr[4] = n >> 8; tr[5] = n;
   1428     hash_add(&h, tr, 6);
   1429     hash_end(&h, dig);
   1430     if (dig[0] != b[6 + hl + 2 + ul] || dig[1] != b[6 + hl + 3 + ul]) return -1;
   1431     if (pgpkeys[i].algo == 22) {
   1432         unsigned char rs[64];
   1433         const unsigned char *w;
   1434         size_t wl;
   1435         if (vl > 32 || mpi(&q, b + len, &w, &wl) || wl > 32) return -1;
   1436         memset(rs, 0, 64);
   1437         memcpy(rs + 32 - vl, v, vl);
   1438         memcpy(rs + 64 - wl, w, wl);
   1439         return ed25519_ok(rs, pgpkeys[i].n, (const char *)dig, kind == 2 ? 64 : 32) ? 0 : -1;
   1440     }
   1441     return rsa_check(pgpkeys[i].n, pgpkeys[i].nl, pgpkeys[i].e, pgpkeys[i].el, v, vl, dig, kind) ? -1 : 0;
   1442 }
   1443 
   1444 /* ---- ed25519, for the signify signatures of port trees ---- */
   1445 
   1446 static void sha512(const unsigned char *m, size_t n, unsigned char *out)
   1447 {
   1448     struct hash h;
   1449     hash_init(&h, 2);
   1450     hash_add(&h, m, n);
   1451     hash_end(&h, out);
   1452 }
   1453 
   1454 /* the field and curve of ed25519 the way tweetnacl does them: 16 limbs of 16 bits */
   1455 typedef int64_t gf[16];
   1456 
   1457 static const gf gf0, gf1 = { 1 },
   1458     ed_d = { 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203 },
   1459     ed_d2 = { 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406 },
   1460     ed_x = { 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169 },
   1461     ed_y = { 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666 },
   1462     ed_i = { 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83 };
   1463 
   1464 static void fe_copy(gf o, const gf a) { memcpy(o, a, sizeof(gf)); }
   1465 
   1466 static void fe_carry(gf o)
   1467 {
   1468     int i;
   1469     for (i = 0; i < 16; i++) {
   1470         int64_t c;
   1471         o[i] += 1LL << 16;
   1472         c = o[i] >> 16;
   1473         o[(i + 1) * (i < 15)] += c - 1 + 37 * (c - 1) * (i == 15);
   1474         o[i] -= c << 16;
   1475     }
   1476 }
   1477 
   1478 static void fe_sel(gf p, gf q, int b)
   1479 {
   1480     int64_t t, c = ~(b - 1);
   1481     int i;
   1482     for (i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; }
   1483 }
   1484 
   1485 static void fe_pack(unsigned char *o, const gf n)
   1486 {
   1487     gf m, t;
   1488     int i, j, b;
   1489     fe_copy(t, n);
   1490     fe_carry(t); fe_carry(t); fe_carry(t);
   1491     for (j = 0; j < 2; j++) {
   1492         m[0] = t[0] - 0xffed;
   1493         for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); m[i - 1] &= 0xffff; }
   1494         m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
   1495         b = (m[15] >> 16) & 1;
   1496         m[14] &= 0xffff;
   1497         fe_sel(t, m, 1 - b);
   1498     }
   1499     for (i = 0; i < 16; i++) { o[2 * i] = t[i] & 0xff; o[2 * i + 1] = t[i] >> 8; }
   1500 }
   1501 
   1502 static int fe_neq(const gf a, const gf b)
   1503 {
   1504     unsigned char c[32], d[32];
   1505     fe_pack(c, a); fe_pack(d, b);
   1506     return memcmp(c, d, 32) != 0;
   1507 }
   1508 
   1509 static int fe_par(const gf a) { unsigned char d[32]; fe_pack(d, a); return d[0] & 1; }
   1510 
   1511 static void fe_unpack(gf o, const unsigned char *n)
   1512 {
   1513     int i;
   1514     for (i = 0; i < 16; i++) o[i] = n[2 * i] + ((int64_t)n[2 * i + 1] << 8);
   1515     o[15] &= 0x7fff;
   1516 }
   1517 
   1518 static void fe_add(gf o, const gf a, const gf b) { int i; for (i = 0; i < 16; i++) o[i] = a[i] + b[i]; }
   1519 static void fe_sub(gf o, const gf a, const gf b) { int i; for (i = 0; i < 16; i++) o[i] = a[i] - b[i]; }
   1520 
   1521 static void fe_mul(gf o, const gf a, const gf b)
   1522 {
   1523     int64_t t[31];
   1524     int i, j;
   1525     memset(t, 0, sizeof t);
   1526     for (i = 0; i < 16; i++) for (j = 0; j < 16; j++) t[i + j] += a[i] * b[j];
   1527     for (i = 0; i < 15; i++) t[i] += 38 * t[i + 16];
   1528     for (i = 0; i < 16; i++) o[i] = t[i];
   1529     fe_carry(o); fe_carry(o);
   1530 }
   1531 
   1532 static void fe_inv(gf o, const gf in)
   1533 {
   1534     gf c;
   1535     int a;
   1536     fe_copy(c, in);
   1537     for (a = 253; a >= 0; a--) { fe_mul(c, c, c); if (a != 2 && a != 4) fe_mul(c, c, in); }
   1538     fe_copy(o, c);
   1539 }
   1540 
   1541 static void fe_pow2523(gf o, const gf in)
   1542 {
   1543     gf c;
   1544     int a;
   1545     fe_copy(c, in);
   1546     for (a = 250; a >= 0; a--) { fe_mul(c, c, c); if (a != 1) fe_mul(c, c, in); }
   1547     fe_copy(o, c);
   1548 }
   1549 
   1550 static void pt_add(gf p[4], gf q[4])
   1551 {
   1552     gf a, b, c, d, t, e, f, g, h;
   1553     fe_sub(a, p[1], p[0]); fe_sub(t, q[1], q[0]); fe_mul(a, a, t);
   1554     fe_add(b, p[0], p[1]); fe_add(t, q[0], q[1]); fe_mul(b, b, t);
   1555     fe_mul(c, p[3], q[3]); fe_mul(c, c, ed_d2);
   1556     fe_mul(d, p[2], q[2]); fe_add(d, d, d);
   1557     fe_sub(e, b, a); fe_sub(f, d, c); fe_add(g, d, c); fe_add(h, b, a);
   1558     fe_mul(p[0], e, f); fe_mul(p[1], h, g); fe_mul(p[2], g, f); fe_mul(p[3], e, h);
   1559 }
   1560 
   1561 static void pt_mul(gf p[4], gf q[4], const unsigned char *s)
   1562 {
   1563     int i, j;
   1564     fe_copy(p[0], gf0); fe_copy(p[1], gf1); fe_copy(p[2], gf1); fe_copy(p[3], gf0);
   1565     for (i = 255; i >= 0; i--) {
   1566         int b = (s[i / 8] >> (i & 7)) & 1;
   1567         for (j = 0; j < 4; j++) fe_sel(p[j], q[j], b);
   1568         pt_add(q, p);
   1569         pt_add(p, p);
   1570         for (j = 0; j < 4; j++) fe_sel(p[j], q[j], b);
   1571     }
   1572 }
   1573 
   1574 static void pt_pack(unsigned char *r, gf p[4])
   1575 {
   1576     gf tx, ty, zi;
   1577     fe_inv(zi, p[2]);
   1578     fe_mul(tx, p[0], zi);
   1579     fe_mul(ty, p[1], zi);
   1580     fe_pack(r, ty);
   1581     r[31] ^= fe_par(tx) << 7;
   1582 }
   1583 
   1584 static int pt_unpackneg(gf r[4], const unsigned char *p)
   1585 {
   1586     gf t, chk, num, den, den2, den4, den6;
   1587     fe_copy(r[2], gf1);
   1588     fe_unpack(r[1], p);
   1589     fe_mul(num, r[1], r[1]);
   1590     fe_mul(den, num, ed_d);
   1591     fe_sub(num, num, r[2]);
   1592     fe_add(den, r[2], den);
   1593     fe_mul(den2, den, den); fe_mul(den4, den2, den2); fe_mul(den6, den4, den2);
   1594     fe_mul(t, den6, num); fe_mul(t, t, den);
   1595     fe_pow2523(t, t);
   1596     fe_mul(t, t, num); fe_mul(t, t, den); fe_mul(t, t, den); fe_mul(r[0], t, den);
   1597     fe_mul(chk, r[0], r[0]); fe_mul(chk, chk, den);
   1598     if (fe_neq(chk, num)) fe_mul(r[0], r[0], ed_i);
   1599     fe_mul(chk, r[0], r[0]); fe_mul(chk, chk, den);
   1600     if (fe_neq(chk, num)) return -1;
   1601     if (fe_par(r[0]) == (p[31] >> 7)) fe_sub(r[0], gf0, r[0]);
   1602     fe_mul(r[3], r[0], r[1]);
   1603     return 0;
   1604 }
   1605 
   1606 /* a 64 byte number mod the order of the curve */
   1607 static void mod_l(unsigned char *r)
   1608 {
   1609     static const int64_t l[32] = { 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
   1610         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10 };
   1611     int64_t x[64], carry;
   1612     int i, j;
   1613     for (i = 0; i < 64; i++) x[i] = r[i];
   1614     for (i = 63; i >= 32; i--) {
   1615         carry = 0;
   1616         for (j = i - 32; j < i - 12; j++) { x[j] += carry - 16 * x[i] * l[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; }
   1617         x[j] += carry;
   1618         x[i] = 0;
   1619     }
   1620     carry = 0;
   1621     for (j = 0; j < 32; j++) { x[j] += carry - (x[31] >> 4) * l[j]; carry = x[j] >> 8; x[j] &= 255; }
   1622     for (j = 0; j < 32; j++) x[j] -= carry * l[j];
   1623     for (i = 0; i < 32; i++) { x[i + 1] += x[i] >> 8; r[i] = x[i] & 255; }
   1624 }
   1625 
   1626 static int ed25519_ok(const unsigned char *sig, const unsigned char *pk, const char *m, size_t n)
   1627 {
   1628     gf p[4], q[4];
   1629     unsigned char t[32], h[64], *b;
   1630     if (pt_unpackneg(q, pk)) return 0;
   1631     b = xmalloc(n + 64);
   1632     memcpy(b, sig, 32);
   1633     memcpy(b + 32, pk, 32);
   1634     memcpy(b + 64, m, n);
   1635     sha512(b, n + 64, h);
   1636     free(b);
   1637     mod_l(h);
   1638     pt_mul(p, q, h);
   1639     fe_copy(q[0], ed_x); fe_copy(q[1], ed_y); fe_copy(q[2], gf1); fe_mul(q[3], ed_x, ed_y);
   1640     {
   1641         gf r[4];
   1642         pt_mul(r, q, sig + 32);
   1643         pt_add(p, r);
   1644     }
   1645     pt_pack(t, p);
   1646     return !memcmp(t, sig, 32);
   1647 }
   1648 
   1649 /* ---- the repos ---- */
   1650 
   1651 struct pkg { char *name, *ver, *desc, *csum, *deps, *prov, *size, *isize, *iif, *file, *sig, *mdeps, *base; int prio, repo; };
   1652 struct prov { char *key, *ver; struct pkg *p; };
   1653 
   1654 static struct pkg *pkgs;
   1655 static int npkgs;
   1656 static struct prov *provs;
   1657 static int nprovs;
   1658 static struct list repo_urls;
   1659 static int *kinds;
   1660 enum { APK, CRUX, VOID, EXHERBO, PACMAN, AUR };
   1661 static const char *const kind_name[] = { "", "crux", "void", "exherbo", "pacman", "aur" };
   1662 #define BUILT(k) ((k) != APK && (k) != PACMAN)
   1663 /* pacman's version order once a repo is a pacman one: a machine is one or the other */
   1664 static int alpm_order;
   1665 
   1666 static char *confdir(void)
   1667 {
   1668     char *d = fmt("%s/etc/mag", root);
   1669     if (*root && !exists(d)) { free(d); d = xstrdup("/etc/mag"); }
   1670     return d;
   1671 }
   1672 
   1673 static const char *machine(void)
   1674 {
   1675     static const char *map[][2] = { { "i386", "x86" }, { "i486", "x86" }, { "i586", "x86" }, { "i686", "x86" }, { "armv7l", "armv7" },
   1676         { "armv6l", "armhf" }, { NULL, NULL } };
   1677     static struct utsname u;
   1678     const char *e = getenv("MAG_ARCH");
   1679     int i;
   1680     char *d, *f, *t;
   1681     if (e && *e) return e;
   1682     d = confdir(); f = fmt("%s/arch", d); t = slurp(f, NULL);
   1683     free(d); free(f);
   1684     if (t && *t) { t[strcspn(t, " \n")] = 0; return t; }
   1685     free(t);
   1686     if (uname(&u) < 0) die("uname: %s", strerror(errno));
   1687     for (i = 0; map[i][0]; i++) if (!strcmp(u.machine, map[i][0])) return map[i][1];
   1688     return u.machine;
   1689 }
   1690 
   1691 static void load_repos(void)
   1692 {
   1693     char *d = confdir(), *f = fmt("%s/repos", d), *t = slurp(f, NULL), *line, *next;
   1694     if (!t) die("%s is missing: it lists the repos, one url a line", f);
   1695     for (line = t; line && *line; line = next) {
   1696         char *s;
   1697         int k;
   1698         next = strchr(line, '\n');
   1699         if (next) *next++ = 0;
   1700         while (*line == ' ' || *line == '\t') line++;
   1701         for (s = line + strlen(line); s > line && (s[-1] == ' ' || s[-1] == '\t' || s[-1] == '\r' || s[-1] == '/'); ) *--s = 0;
   1702         if (!*line || *line == '#') continue;
   1703         kinds = xrealloc(kinds, (repo_urls.n + 1) * sizeof *kinds);
   1704         kinds[repo_urls.n] = APK;
   1705         for (k = CRUX; k <= AUR; k++) {
   1706             size_t n = strlen(kind_name[k]);
   1707             if (!strncmp(line, kind_name[k], n) && (line[n] == ' ' || line[n] == '\t')) {
   1708                 for (kinds[repo_urls.n] = k, line += n; *line == ' ' || *line == '\t'; line++) {}
   1709                 break;
   1710             }
   1711         }
   1712         if (kinds[repo_urls.n] >= PACMAN) alpm_order = 1;
   1713         push(&repo_urls, xstrdup(line));
   1714     }
   1715     free(t); free(f); free(d);
   1716 }
   1717 
   1718 static char *repo_base(int i) { return fmt("%s/%s", repo_urls.v[i], arch); }
   1719 
   1720 /* Arch32 keeps the arch in the url (.../i686/core) and the db and packages right there; mainline Arch ends in /os
   1721  * and the arch goes after it. a pacman url that does not end in /os is the flat Arch32 kind */
   1722 static int pac_flat(int i)
   1723 {
   1724     const char *u = repo_urls.v[i];
   1725     size_t l = strlen(u);
   1726     return kinds[i] == PACMAN && !(l >= 3 && !strcmp(u + l - 3, "/os"));
   1727 }
   1728 static char *pac_base(int i) { return pac_flat(i) ? xstrdup(repo_urls.v[i]) : repo_base(i); }
   1729 
   1730 static char *flat(int i)
   1731 {
   1732     char *u = xstrdup(repo_urls.v[i]), *s;
   1733     for (s = u; *s; s++) if (*s == '/' || *s == ':' || *s == '\'') *s = '_';
   1734     return u;
   1735 }
   1736 
   1737 static char *index_file(int i)
   1738 {
   1739     char *u = flat(i), *f = fmt("%s/var/cache/mag/index/%s_%s.tar.gz", root, u, arch);
   1740     free(u);
   1741     return f;
   1742 }
   1743 
   1744 static char *tree_dir(int i)
   1745 {
   1746     char *u = flat(i), *f = fmt("%s/var/cache/mag/ports/%s", root, u);
   1747     free(u);
   1748     return f;
   1749 }
   1750 
   1751 static const char *downloader(void)
   1752 {
   1753     static const char *cmds[][2] = { { "curl", "curl -fsSL --retry 3 --retry-all-errors -o" }, { "wget", "wget -q -O" }, { "ftp", "ftp -o" } };
   1754     const char *env = getenv("MAG_FETCH"), *pa = getenv("PATH");
   1755     int i;
   1756     if (env) return env;
   1757     if (!access("/etc/ssl/cert.pem", R_OK)) cmds[0][1] = "curl -fsSL --retry 3 --retry-all-errors --cacert /etc/ssl/cert.pem --capath /etc/ssl -o";
   1758     for (i = 0; i < 3; i++) {
   1759         char *p = xstrdup(pa ? pa : "/usr/bin:/bin"), *d = p, *e;
   1760         for (; d; d = e) {
   1761             char *f;
   1762             int ok;
   1763             e = strchr(d, ':');
   1764             if (e) *e++ = 0;
   1765             f = fmt("%s/%s", d, cmds[i][0]);
   1766             ok = !access(f, X_OK);
   1767             free(f);
   1768             if (ok) { free(p); return cmds[i][1]; }
   1769         }
   1770         free(p);
   1771     }
   1772     return "curl -fsSL --retry 3 --retry-all-errors -o";
   1773 }
   1774 
   1775 static int fetch_ext(const char *url, const char *file)
   1776 {
   1777     char *av[] = { "/bin/sh", "-c", "set -f; $0 \"$1\" \"$2\"", (char *)downloader(), (char *)file, (char *)url, NULL };
   1778     return run(av);
   1779 }
   1780 
   1781 /* plain http is fetched here, no curl needed. https goes to the downloader */
   1782 static const char *hsize(double b);
   1783 
   1784 struct hconn { int fd, p, n; const char *name; long long total, got; char b[16384]; };
   1785 
   1786 /* one line that rewrites itself: the name, how far, and the size when the server gave one */
   1787 static void progress(struct hconn *c)
   1788 {
   1789     if (!isatty(2)) return;
   1790     if (c->total > 0) fprintf(stderr, "\r  %-30s %3d%%  %s", c->name, (int)(c->got * 100 / c->total), hsize(c->got));
   1791     else fprintf(stderr, "\r  %-30s %s", c->name, hsize(c->got));
   1792 }
   1793 
   1794 static void progress_done(struct hconn *c)
   1795 {
   1796     if (isatty(2) && c->got) fprintf(stderr, "\r%*s\r", (int)strlen(c->name) + 24, "");
   1797 }
   1798 
   1799 static int h_fill(struct hconn *c)
   1800 {
   1801     ssize_t r;
   1802     if (c->p < c->n) return 1;
   1803     do r = read(c->fd, c->b, sizeof c->b); while (r < 0 && errno == EINTR);
   1804     if (r <= 0) return 0;
   1805     c->p = 0;
   1806     c->n = r;
   1807     return 1;
   1808 }
   1809 
   1810 static int h_line(struct hconn *c, char *s, int max)
   1811 {
   1812     int k = 0;
   1813     while (h_fill(c)) {
   1814         char ch = c->b[c->p++];
   1815         if (ch == '\n') { if (k && s[k - 1] == '\r') k--; s[k] = 0; return 1; }
   1816         if (k < max - 1) s[k++] = ch;
   1817     }
   1818     return 0;
   1819 }
   1820 
   1821 /* n bytes to out, or everything up to the end when n < 0 */
   1822 static int h_copy(struct hconn *c, int out, long long n)
   1823 {
   1824     while (n && h_fill(c)) {
   1825         int k = c->n - c->p, o;
   1826         ssize_t w;
   1827         if (n > 0 && k > n) k = n;
   1828         for (o = 0; o < k; o += w)
   1829             if ((w = write(out, c->b + c->p + o, k - o)) <= 0) return -1;
   1830         c->p += k;
   1831         if (n > 0) n -= k;
   1832         c->got += k;
   1833         progress(c);
   1834     }
   1835     return n > 0 ? -1 : 0;
   1836 }
   1837 
   1838 static int http_get(const char *url, const char *file, const char *name, int hops)
   1839 {
   1840     struct hconn *c = xmalloc(sizeof *c);
   1841     struct addrinfo hints, *ai, *a;
   1842     struct timeval tv = { 30, 0 };
   1843     const char *h = url + 7, *path = strchr(h, '/');
   1844     char host[256], port[8] = "80", line[4096], *loc = NULL, *req, *col;
   1845     size_t hn = path ? (size_t)(path - h) : strlen(h);
   1846     int out, rc = 1, code = 0, chunked = 0;
   1847     long long len = -1;
   1848     c->fd = -1;
   1849     c->p = c->n = 0;
   1850     c->name = name;
   1851     c->total = -1;
   1852     c->got = 0;
   1853     if (!path) path = "/";
   1854     if (hn >= sizeof host) goto done;
   1855     memcpy(host, h, hn);
   1856     host[hn] = 0;
   1857     if ((col = strchr(host, ':'))) { *col++ = 0; snprintf(port, sizeof port, "%s", col); }
   1858     memset(&hints, 0, sizeof hints);
   1859     hints.ai_family = AF_UNSPEC;
   1860     hints.ai_socktype = SOCK_STREAM;
   1861     if (getaddrinfo(host, port, &hints, &ai)) { say("cannot find %s", host); goto done; }
   1862     for (a = ai; a; a = a->ai_next) {
   1863         if ((c->fd = socket(a->ai_family, SOCK_STREAM, 0)) < 0) continue;
   1864         setsockopt(c->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
   1865         if (!connect(c->fd, a->ai_addr, a->ai_addrlen)) break;
   1866         close(c->fd);
   1867         c->fd = -1;
   1868     }
   1869     freeaddrinfo(ai);
   1870     if (c->fd < 0) { say("cannot connect to %s", host); goto done; }
   1871     req = fmt("GET %s HTTP/1.1\r\nHost: %.*s\r\nUser-Agent: mag\r\nConnection: close\r\n\r\n", path, (int)hn, h);
   1872     if (write(c->fd, req, strlen(req)) != (ssize_t)strlen(req)) { free(req); goto done; }
   1873     free(req);
   1874     if (!h_line(c, line, sizeof line) || sscanf(line, "HTTP/%*s %d", &code) != 1) goto done;
   1875     while (h_line(c, line, sizeof line) && *line) {
   1876         char *v = strchr(line, ':');
   1877         if (!v) continue;
   1878         for (*v++ = 0; *v == ' ' || *v == '\t'; v++) {}
   1879         if (!strcasecmp(line, "content-length")) len = strtoll(v, NULL, 10);
   1880         else if (!strcasecmp(line, "transfer-encoding") && strstr(v, "chunked")) chunked = 1;
   1881         else if (!strcasecmp(line, "location")) { free(loc); loc = xstrdup(v); }
   1882     }
   1883     if (code / 100 == 3 && loc && hops < 5) {
   1884         char *to = *loc == '/' ? fmt("http://%.*s%s", (int)hn, h, loc) : xstrdup(loc);
   1885         close(c->fd);
   1886         c->fd = -1;
   1887         rc = strncmp(to, "http://", 7) ? fetch_ext(to, file) : http_get(to, file, name, hops + 1);
   1888         free(to);
   1889         goto done;
   1890     }
   1891     if (code != 200) { say("%s: http %d", url, code); goto done; }
   1892     if ((out = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0644)) < 0) goto done;
   1893     c->total = chunked ? -1 : len;
   1894     if (!chunked) rc = h_copy(c, out, len) ? 1 : 0;
   1895     else for (;;) {
   1896         long long k;
   1897         if (!h_line(c, line, sizeof line)) break;
   1898         if (!(k = strtoll(line, NULL, 16))) { rc = 0; break; }
   1899         if (h_copy(c, out, k) || !h_line(c, line, sizeof line)) break;
   1900     }
   1901     progress_done(c);
   1902     if (close(out) < 0) rc = 1;
   1903 done:
   1904     if (c->fd >= 0) close(c->fd);
   1905     free(loc);
   1906     free(c);
   1907     return rc;
   1908 }
   1909 
   1910 static int download(const char *url, const char *file)
   1911 {
   1912     char *part = fmt("%s.part", file), *name;
   1913     const char *s = strrchr(url, '/');
   1914     int rc;
   1915     mkparent(file);
   1916     name = xstrdup(s && s[1] ? s + 1 : url);       /* the last bit of the url reads better than the temp file */
   1917     name[strcspn(name, "?")] = 0;
   1918     rc = !strncmp(url, "http://", 7) && !getenv("MAG_FETCH") ? http_get(url, part, name, 0) : fetch_ext(url, part);
   1919     free(name);
   1920     if (!rc && rename(part, file) < 0) rc = 1;
   1921     if (rc) unlink(part);
   1922     free(part);
   1923     return rc;
   1924 }
   1925 
   1926 static void db_put_file(const char *f, const char *text);
   1927 
   1928 /* many at once when it is curl; what did not come is fetched again one by one where it is used */
   1929 static void fetch_all(const struct list *urls, const struct list *files, const char *dir)
   1930 {
   1931     const char *dl = downloader();
   1932     int k;
   1933     if (urls->n && !strncmp(dl, "curl ", 5) && !getenv("MAG_FETCH")) {
   1934         char *cfg = fmt("%s/fetch", dir), *cmd = xstrndup(dl, strlen(dl) - 3);
   1935         struct buf c = { 0 };
   1936         /* no --parallel: some curl versions cross the outputs of parallel transfers in a -K config, so a package
   1937          * lands under another's name and fails its checksum. one kept-alive connection is reliable and fast enough */
   1938         char *av[] = { "/bin/sh", "-c", "set -f; $0 --create-dirs -K \"$1\"", cmd, cfg, NULL };
   1939         buf_add(&c, "", 0);
   1940         for (k = 0; k < urls->n; k++) {
   1941             char *s = fmt("url = \"%s\"\noutput = \"%s\"\n", urls->v[k], files->v[k]);
   1942             buf_add(&c, s, strlen(s));
   1943             free(s);
   1944         }
   1945         mkpath(dir, 0755);
   1946         db_put_file(cfg, (char *)c.p);
   1947         run(av);
   1948         unlink(cfg);
   1949         free(cfg); free(cmd); free(c.p);
   1950     } else for (k = 0; k < urls->n; k++) download(urls->v[k], files->v[k]);
   1951 }
   1952 
   1953 /* a signed file starts with a gzip member holding .SIGN.RSA.key or .SIGN.RSA256.key, over the rest of the file */
   1954 static int check_signed(const char *file)
   1955 {
   1956     struct in *r = xmalloc(sizeof *r);
   1957     struct tar t;
   1958     struct ent *e;
   1959     char *d, *key;
   1960     unsigned char dig[32];
   1961     int sha1, bad = -1, fd = open(file, O_RDONLY);
   1962     off_t at;
   1963     memset(&t, 0, sizeof t);
   1964     if (fd < 0) goto out;
   1965     in_open(r, fd, 0);
   1966     if (gunzip(r, tar_out, &t)) goto out;
   1967     at = in_tell(r);
   1968     if ((e = tar_prefix(&t, ".SIGN.RSA256."))) { sha1 = 0; key = e->name + 13; }
   1969     else if ((e = tar_prefix(&t, ".SIGN.RSA."))) { sha1 = 1; key = e->name + 10; }
   1970     else { say("%s has no signature", file); goto out; }
   1971     d = confdir();
   1972     key = fmt("%s/keys/%s", d, key);
   1973     free(d);
   1974     if (!exists(key)) say("it is signed with %s, which is not there", key);
   1975     else {
   1976         hash_range(fd, at, -1, sha1, dig);
   1977         if (!(bad = rsa_verify(key, e->data.p, e->data.n, dig, sha1) ? -1 : 0)) {}
   1978         else say("the signature does not match %s", key);
   1979     }
   1980     free(key);
   1981 out:
   1982     tar_free(&t);
   1983     free(r);
   1984     if (fd >= 0) close(fd);
   1985     return bad;
   1986 }
   1987 
   1988 static void add_prov(const char *tok, struct pkg *p)
   1989 {
   1990     const char *eq = strchr(tok, '=');
   1991     if (nprovs % 1024 == 0) provs = xrealloc(provs, (nprovs + 1024) * sizeof *provs);
   1992     provs[nprovs].key = eq ? xstrndup(tok, eq - tok) : xstrdup(tok);
   1993     provs[nprovs].ver = eq ? xstrdup(eq + 1) : NULL;
   1994     provs[nprovs].p = p;
   1995     nprovs++;
   1996 }
   1997 
   1998 static int cmp_prov(const void *a, const void *b) { return strcmp(((const struct prov *)a)->key, ((const struct prov *)b)->key); }
   1999 
   2000 static void parse_index(char *t, int repo)
   2001 {
   2002     struct pkg p;
   2003     char *line, *next;
   2004     memset(&p, 0, sizeof p);
   2005     for (line = t; line; line = next) {
   2006         next = strchr(line, '\n');
   2007         if (next) *next++ = 0;
   2008         if (!*line || !next) {
   2009             if (p.name && p.ver) {
   2010                 if (npkgs % 1024 == 0) pkgs = xrealloc(pkgs, (npkgs + 1024) * sizeof *pkgs);
   2011                 p.repo = repo;
   2012                 pkgs[npkgs++] = p;
   2013             }
   2014             memset(&p, 0, sizeof p);
   2015             continue;
   2016         }
   2017         if (line[1] != ':') continue;
   2018         switch (line[0]) {
   2019         case 'P': p.name = line + 2; break;
   2020         case 'V': p.ver = line + 2; break;
   2021         case 'T': p.desc = line + 2; break;
   2022         case 'C': p.csum = line + 2; break;
   2023         case 'D': p.deps = line + 2; break;
   2024         case 'p': p.prov = line + 2; break;
   2025         case 'S': p.size = line + 2; break;
   2026         case 'I': p.isize = line + 2; break;
   2027         case 'i': p.iif = line + 2; break;
   2028         case 'k': p.prio = atoi(line + 2); break;
   2029         case 'F': p.file = line + 2; break;
   2030         case 'G': p.sig = line + 2; break;
   2031         case 'M': p.mdeps = line + 2; break;
   2032         case 'B': p.base = line + 2; break;
   2033         }
   2034     }
   2035 }
   2036 
   2037 static void load_index(void)
   2038 {
   2039     static int loaded;
   2040     int i, j;
   2041     if (loaded++) return;
   2042     for (i = 0; i < repo_urls.n; i++) {
   2043         char *f = index_file(i);
   2044         int fd;
   2045         if (kinds[i] != APK) {
   2046             char *d = tree_dir(i), *x = fmt("%s/INDEX", d), *t = slurp(x, NULL);
   2047             if (t) parse_index(t, i); else say("%s has no index yet, mag update gets it", repo_urls.v[i]);
   2048             free(d); free(x); free(f);
   2049             continue;
   2050         }
   2051         fd = open(f, O_RDONLY);
   2052         struct in *r;
   2053         struct tar t;
   2054         struct ent *e;
   2055         if (fd < 0) { say("%s has no index yet, mag update gets it", repo_urls.v[i]); free(f); continue; }
   2056         r = xmalloc(sizeof *r);
   2057         memset(&t, 0, sizeof t);
   2058         in_open(r, fd, 0);
   2059         if (gunzip(r, tar_out, &t)) die("%s is broken, mag update gets it again", f);
   2060         tar_free(&t);
   2061         if (gunzip(r, tar_out, &t) || !(e = tar_find(&t, "APKINDEX"))) die("%s is broken, mag update gets it again", f);
   2062         parse_index((char *)e->data.p, i);
   2063         e->data.p = NULL;
   2064         tar_free(&t);
   2065         free(r);
   2066         close(fd);
   2067         free(f);
   2068     }
   2069     for (i = 0; i < npkgs; i++) {
   2070         struct list w = words(pkgs[i].prov);
   2071         add_prov(pkgs[i].name, &pkgs[i]);
   2072         provs[nprovs - 1].ver = pkgs[i].ver;
   2073         for (j = 0; j < w.n; j++) add_prov(w.v[j], &pkgs[i]);
   2074         list_free(&w);
   2075     }
   2076     if (nprovs) qsort(provs, nprovs, sizeof *provs, cmp_prov);
   2077 }
   2078 
   2079 /* ---- versions and dependencies ---- */
   2080 
   2081 static int sufrank(const char *s)
   2082 {
   2083     static const char *w[] = { "alpha", "beta", "pre", "rc", "", "cvs", "svn", "git", "hg", "p" };
   2084     int i;
   2085     for (i = 0; i < 10; i++) {
   2086         size_t n = strlen(w[i]);
   2087         if (n && !strncmp(s, w[i], n) && !isalpha(s[n])) return i - 4;
   2088     }
   2089     return 0;
   2090 }
   2091 
   2092 static int vclass(const char *s)
   2093 {
   2094     if (!*s) return 0;
   2095     if (*s == '_') return sufrank(s + 1) < 0 ? -1 : 2;
   2096     if (*s == '-') return 1;
   2097     if (*s == '.') return 4;
   2098     if (isdigit(*s)) return 5;
   2099     return 3;
   2100 }
   2101 
   2102 /* rpm's order, the way pacman has it: alphanumeric runs compared, numbers as numbers, letters below numbers */
   2103 static int rpmcmp(const char *a, const char *b, const char *ae, const char *be)
   2104 {
   2105     while (a < ae && b < be) {
   2106         const char *x, *y;
   2107         int num, c;
   2108         size_t sa = 0, sb = 0;
   2109         while (a < ae && !isalnum(*a)) a++, sa++;
   2110         while (b < be && !isalnum(*b)) b++, sb++;
   2111         if (a == ae || b == be) break;
   2112         if (sa != sb) return sa < sb ? -1 : 1;
   2113         x = a; y = b;
   2114         if ((num = isdigit(*a))) { while (a < ae && isdigit(*a)) a++; while (b < be && isdigit(*b)) b++; }
   2115         else { while (a < ae && isalpha(*a)) a++; while (b < be && isalpha(*b)) b++; }
   2116         if (y == b) return num ? 1 : -1;
   2117         if (num) {
   2118             while (*x == '0' && x + 1 < a) x++;
   2119             while (*y == '0' && y + 1 < b) y++;
   2120             if (a - x != b - y) return a - x < b - y ? -1 : 1;
   2121         }
   2122         {
   2123             size_t la = a - x, lb = b - y;
   2124             c = strncmp(x, y, la < lb ? la : lb);
   2125             if (!c && la != lb) c = la < lb ? -1 : 1;
   2126         }
   2127         if (c) return c < 0 ? -1 : 1;
   2128     }
   2129     if (a == ae && b == be) return 0;
   2130     return (a == ae && !isalpha(*b)) || (a < ae && isalpha(*a)) ? -1 : 1;
   2131 }
   2132 
   2133 /* pacman's: epoch:version-release, the release only when both have one */
   2134 static int alpm_vercmp(const char *a, const char *b)
   2135 {
   2136     const char *ca = strchr(a, ':'), *cb = strchr(b, ':'), *ra, *rb, *ea = a + strlen(a), *eb = b + strlen(b);
   2137     long xa = 0, xb = 0;
   2138     int c;
   2139     if (!strcmp(a, b)) return 0;
   2140     if (ca) { for (const char *s = a; s < ca; s++) if (!isdigit(*s)) { ca = NULL; break; } }
   2141     if (cb) { for (const char *s = b; s < cb; s++) if (!isdigit(*s)) { cb = NULL; break; } }
   2142     if (ca) { xa = strtol(a, NULL, 10); a = ca + 1; }
   2143     if (cb) { xb = strtol(b, NULL, 10); b = cb + 1; }
   2144     if (xa != xb) return xa < xb ? -1 : 1;
   2145     ra = strrchr(a, '-'); rb = strrchr(b, '-');
   2146     if ((c = rpmcmp(a, b, ra ? ra : ea, rb ? rb : eb))) return c;
   2147     return ra && rb ? rpmcmp(ra + 1, rb + 1, ea, eb) : 0;
   2148 }
   2149 
   2150 static int apk_vercmp(const char *a, const char *b);
   2151 static int vercmp(const char *a, const char *b) { return alpm_order ? alpm_vercmp(a, b) : apk_vercmp(a, b); }
   2152 
   2153 /* apk's order: 1.2_rc1 < 1.2 < 1.2-r1 < 1.2_p1 < 1.2a < 1.2.1 */
   2154 static int apk_vercmp(const char *a, const char *b)
   2155 {
   2156     for (;;) {
   2157         if (isdigit(*a) && isdigit(*b)) {
   2158             const char *x, *y;
   2159             int c;
   2160             while (*a == '0' && isdigit(a[1])) a++;
   2161             while (*b == '0' && isdigit(b[1])) b++;
   2162             for (x = a; isdigit(*a); a++) {}
   2163             for (y = b; isdigit(*b); b++) {}
   2164             if (a - x != b - y) return a - x < b - y ? -1 : 1;
   2165             c = strncmp(x, y, a - x);
   2166             if (c) return c < 0 ? -1 : 1;
   2167             continue;
   2168         }
   2169         if (*a == '_' && *b == '_') {
   2170             int ra = sufrank(a + 1), rb = sufrank(b + 1);
   2171             if (ra != rb) return ra < rb ? -1 : 1;
   2172             for (a++; isalpha(*a); a++) {}
   2173             for (b++; isalpha(*b); b++) {}
   2174             continue;
   2175         }
   2176         if (*a == *b) { if (!*a) return 0; a++; b++; continue; }
   2177         {
   2178             int ca = vclass(a), cb = vclass(b);
   2179             if (ca != cb) return ca < cb ? -1 : 1;
   2180             return *a < *b ? -1 : 1;
   2181         }
   2182     }
   2183 }
   2184 
   2185 struct dep { char key[256], ver[128]; int op, neg; };
   2186 
   2187 enum { LESS = 1, EQUAL = 2, MORE = 4, FUZZY = 8 };
   2188 
   2189 static void dep_parse(const char *tok, struct dep *d)
   2190 {
   2191     size_t n;
   2192     memset(d, 0, sizeof *d);
   2193     if (*tok == '!') { d->neg = 1; tok++; }
   2194     n = strcspn(tok, "<>=~");
   2195     if (n >= sizeof d->key) n = sizeof d->key - 1;
   2196     memcpy(d->key, tok, n);
   2197     for (tok += n; *tok && strchr("<>=~", *tok); tok++)
   2198         d->op |= *tok == '<' ? LESS : *tok == '>' ? MORE : *tok == '=' ? EQUAL : FUZZY;
   2199     snprintf(d->ver, sizeof d->ver, "%s", tok);
   2200 }
   2201 
   2202 static int dep_ok(const struct dep *d, const char *ver)
   2203 {
   2204     int c;
   2205     if (!d->op) return 1;
   2206     if (!ver) return 0;
   2207     if (d->op & FUZZY) return !strncmp(ver, d->ver, strlen(d->ver));
   2208     c = vercmp(ver, d->ver);
   2209     return (c < 0 && d->op & LESS) || (!c && d->op & EQUAL) || (c > 0 && d->op & MORE);
   2210 }
   2211 
   2212 /* does name-ver, which also provides prov, meet d */
   2213 static int meets(const struct dep *d, const char *name, const char *ver, const char *prov)
   2214 {
   2215     struct list w;
   2216     int i, ok = 0;
   2217     if (!strcmp(name, d->key)) return dep_ok(d, ver);
   2218     w = words(prov);
   2219     for (i = 0; i < w.n && !ok; i++) {
   2220         char *eq = strchr(w.v[i], '=');
   2221         if (eq) *eq++ = 0;
   2222         ok = !strcmp(w.v[i], d->key) && dep_ok(d, eq);
   2223     }
   2224     list_free(&w);
   2225     return ok;
   2226 }
   2227 
   2228 static struct pkg *newest(const char *name);
   2229 static int installed(const char *name);
   2230 
   2231 /* providers the packages asked for name themselves, like polkit-elogind-libs for polkit-elogind: these win over priority */
   2232 static struct list prefer;
   2233 
   2234 static void prefer_deps(const char *name)
   2235 {
   2236     struct pkg *p = newest(name);
   2237     struct list w;
   2238     int i;
   2239     if (!p || has(&prefer, name)) return;
   2240     push(&prefer, xstrdup(name));
   2241     if (!p->deps) return;
   2242     w = words(p->deps);
   2243     for (i = 0; i < w.n; i++) {
   2244         struct dep d;
   2245         dep_parse(w.v[i], &d);
   2246         if (!d.neg && newest(d.key)) prefer_deps(d.key);
   2247     }
   2248     list_free(&w);
   2249 }
   2250 
   2251 static struct pkg *pick(const struct dep *d)
   2252 {
   2253     struct pkg *best = NULL;
   2254     int lo = 0, hi = nprovs, i;
   2255     while (lo < hi) { int mid = (lo + hi) / 2; if (strcmp(provs[mid].key, d->key) < 0) lo = mid + 1; else hi = mid; }
   2256     for (hi = lo; hi < nprovs && !strcmp(provs[hi].key, d->key); hi++) {}
   2257     for (i = lo; i < hi; i++) {
   2258         struct pkg *p = provs[i].p;
   2259         int named, bnamed;
   2260         if (!dep_ok(d, provs[i].ver)) continue;
   2261         if (!best) { best = p; continue; }
   2262         named = !strcmp(p->name, d->key); bnamed = !strcmp(best->name, d->key);
   2263         if (named != bnamed) { if (named) best = p; continue; }
   2264         named = has(&prefer, p->name) || installed(p->name); bnamed = has(&prefer, best->name) || installed(best->name);
   2265         if (named != bnamed) { if (named) best = p; continue; }
   2266         if (p->prio != best->prio) { if (p->prio > best->prio) best = p; continue; }
   2267         /* the same name in two repos: apk takes the newest, pacman the first repo that has it */
   2268         if (!strcmp(p->name, best->name) && !alpm_order ? vercmp(p->ver, best->ver) > 0 : p->repo < best->repo) best = p;
   2269     }
   2270     return best;
   2271 }
   2272 
   2273 /* packages to build from a port tree even when a repo has them built */
   2274 static struct list from_ports;
   2275 
   2276 static struct pkg *port_of(const char *name)
   2277 {
   2278     struct pkg *best = NULL;
   2279     int i;
   2280     for (i = 0; i < npkgs; i++)
   2281         if (BUILT(kinds[pkgs[i].repo]) && !strcmp(pkgs[i].name, name) && (!best || vercmp(pkgs[i].ver, best->ver) > 0)) best = &pkgs[i];
   2282     return best;
   2283 }
   2284 
   2285 static struct pkg *newest(const char *name)
   2286 {
   2287     struct dep d;
   2288     struct pkg *p;
   2289     dep_parse(name, &d);
   2290     if (has(&from_ports, d.key) && (p = port_of(d.key))) return p;
   2291     p = pick(&d);
   2292     return p && !strcmp(p->name, d.key) ? p : NULL;
   2293 }
   2294 
   2295 /* ---- what is installed ---- */
   2296 
   2297 static char *dbdir(const char *name) { return fmt("%s/var/lib/mag/%s", root, name); }
   2298 
   2299 static char *db_get(const char *name, const char *what)
   2300 {
   2301     char *d = dbdir(name), *f = fmt("%s/%s", d, what), *v = slurp(f, NULL), *s;
   2302     free(d); free(f);
   2303     if (v) for (s = v + strlen(v); s > v && (s[-1] == '\n' || s[-1] == ' '); ) *--s = 0;
   2304     return v;
   2305 }
   2306 
   2307 static int installed(const char *name) { char *v = db_get(name, "version"); free(v); return v != NULL; }
   2308 
   2309 static struct list db_read(const char *name, const char *what)
   2310 {
   2311     struct list l = { 0 };
   2312     char *t = db_get(name, what), *line, *next;
   2313     if (!t) return l;
   2314     for (line = t; line && *line; line = next) {
   2315         next = strchr(line, '\n');
   2316         if (next) *next++ = 0;
   2317         if (*line) push(&l, xstrdup(line));
   2318     }
   2319     free(t);
   2320     return l;
   2321 }
   2322 
   2323 static void db_put(const char *name, const char *what, const char *data, size_t n, mode_t mode)
   2324 {
   2325     char *d = dbdir(name), *f = fmt("%s/%s", d, what);
   2326     int fd;
   2327     mkpath(d, 0755);
   2328     unlink(f);
   2329     fd = open(f, O_WRONLY | O_CREAT | O_TRUNC, mode);
   2330     if (fd < 0 || write(fd, data, n) != (ssize_t)n || close(fd) < 0) die("cannot write %s: %s", f, strerror(errno));
   2331     free(d); free(f);
   2332 }
   2333 
   2334 static void db_put_file(const char *f, const char *text)
   2335 {
   2336     int fd = open(f, O_WRONLY | O_CREAT | O_TRUNC, 0644);
   2337     size_t n = strlen(text);
   2338     if (fd < 0 || write(fd, text, n) != (ssize_t)n || write(fd, "\n", 1) != 1 || close(fd) < 0) die("cannot write %s: %s", f, strerror(errno));
   2339 }
   2340 
   2341 static void db_write(const char *name, const char *what, const struct list *l)
   2342 {
   2343     struct buf b = { 0 };
   2344     int i;
   2345     buf_add(&b, "", 0);
   2346     for (i = 0; i < l->n; i++) { buf_add(&b, l->v[i], strlen(l->v[i])); buf_add(&b, "\n", 1); }
   2347     db_put(name, what, (char *)b.p, b.n, 0644);
   2348     free(b.p);
   2349 }
   2350 
   2351 static struct list db_all(void)
   2352 {
   2353     struct list l = { 0 };
   2354     char *base = fmt("%s/var/lib/mag", root);
   2355     DIR *d = opendir(base);
   2356     struct dirent *e;
   2357     if (d) {
   2358         while ((e = readdir(d))) if (e->d_name[0] != '.') push(&l, xstrdup(e->d_name));
   2359         closedir(d);
   2360     }
   2361     free(base);
   2362     if (l.n) qsort(l.v, l.n, sizeof *l.v, cmp_str);
   2363     return l;
   2364 }
   2365 
   2366 struct inst { char *name, *ver, *prov; };
   2367 static struct inst *insts;
   2368 static int ninsts;
   2369 
   2370 static void load_insts(void)
   2371 {
   2372     static int done;
   2373     struct list all;
   2374     int i;
   2375     if (done++) return;
   2376     all = db_all();
   2377     insts = xmalloc((all.n + 1) * sizeof *insts);
   2378     for (i = 0; i < all.n; i++) {
   2379         insts[i].name = all.v[i];
   2380         insts[i].ver = db_get(all.v[i], "version");
   2381         insts[i].prov = db_get(all.v[i], "provides");
   2382     }
   2383     ninsts = all.n;
   2384 }
   2385 
   2386 /* the installed package that meets d, NULL if none */
   2387 static const char *installed_for(const struct dep *d)
   2388 {
   2389     int i;
   2390     load_insts();
   2391     for (i = 0; i < ninsts; i++) if (insts[i].ver && meets(d, insts[i].name, insts[i].ver, insts[i].prov)) return insts[i].name;
   2392     return NULL;
   2393 }
   2394 
   2395 static struct list rdeps(const char *name)
   2396 {
   2397     struct list all = db_all(), out = { 0 };
   2398     int i;
   2399     for (i = 0; i < all.n; i++) {
   2400         struct list d = db_read(all.v[i], "deps");
   2401         if (strcmp(all.v[i], name) && has(&d, name)) push(&out, all.v[i]);
   2402         list_free(&d);
   2403     }
   2404     return out;
   2405 }
   2406 
   2407 /* ---- putting files in place ---- */
   2408 
   2409 static void walk(const char *base, const char *rel, struct list *files, struct list *dirs)
   2410 {
   2411     char *dir = *rel ? fmt("%s/%s", base, rel) : xstrdup(base);
   2412     DIR *d = opendir(dir);
   2413     struct dirent *e;
   2414     struct list names = { 0 };
   2415     int i;
   2416     if (!d) die("cannot read %s: %s", dir, strerror(errno));
   2417     while ((e = readdir(d))) if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) push(&names, xstrdup(e->d_name));
   2418     closedir(d);
   2419     if (names.n) qsort(names.v, names.n, sizeof *names.v, cmp_str);
   2420     for (i = 0; i < names.n; i++) {
   2421         char *relp = *rel ? fmt("%s/%s", rel, names.v[i]) : xstrdup(names.v[i]), *full = fmt("%s/%s", base, relp);
   2422         struct stat st;
   2423         if (lstat(full, &st) < 0) die("cannot stat %s", full);
   2424         if (S_ISDIR(st.st_mode)) { push(dirs, relp); walk(base, relp, files, dirs); }
   2425         else push(files, relp);
   2426         free(full);
   2427     }
   2428     list_free(&names);
   2429     free(dir);
   2430 }
   2431 
   2432 static int copy_into(const char *from, const char *to, const struct stat *st)
   2433 {
   2434     int in = open(from, O_RDONLY), out;
   2435     char buf[65536], *tmp = fmt("%s.mag-new", to);
   2436     ssize_t n;
   2437     if (in < 0) { free(tmp); return -1; }
   2438     unlink(tmp);
   2439     out = open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0600);
   2440     if (out < 0) { close(in); free(tmp); return -1; }
   2441     while ((n = read(in, buf, sizeof buf)) > 0) {
   2442         char *p = buf;
   2443         while (n) { ssize_t w = write(out, p, n); if (w < 0) { close(in); close(out); unlink(tmp); free(tmp); return -1; } p += w; n -= w; }
   2444     }
   2445     close(in);
   2446     if (!geteuid()) fchown(out, st->st_uid, st->st_gid);
   2447     fchmod(out, st->st_mode & 07777);
   2448     if (close(out) < 0 || n < 0 || rename(tmp, to) < 0) { unlink(tmp); free(tmp); return -1; }
   2449     free(tmp);
   2450     return 0;
   2451 }
   2452 
   2453 struct owner { char *path; char *pkg; };
   2454 static struct owner *owners;
   2455 static int nowners, capowners;
   2456 
   2457 static int cmp_owner(const void *a, const void *b) { return strcmp(((const struct owner *)a)->path, ((const struct owner *)b)->path); }
   2458 
   2459 static void load_owners(void)
   2460 {
   2461     struct list all = db_all();
   2462     int i, j;
   2463     nowners = 0;
   2464     for (i = 0; i < all.n; i++) {
   2465         struct list f = db_read(all.v[i], "files");
   2466         for (j = 0; j < f.n; j++) {
   2467             if (nowners == capowners) { capowners = capowners ? capowners * 2 : 1024; owners = xrealloc(owners, capowners * sizeof *owners); }
   2468             owners[nowners].path = f.v[j]; owners[nowners].pkg = all.v[i]; nowners++;
   2469         }
   2470         free(f.v);
   2471     }
   2472     if (nowners) qsort(owners, nowners, sizeof *owners, cmp_owner);
   2473 }
   2474 
   2475 static const char *owner_of(const char *path)
   2476 {
   2477     int lo = 0, hi = nowners - 1;
   2478     while (lo <= hi) {
   2479         int mid = (lo + hi) / 2, c = strcmp(path, owners[mid].path);
   2480         if (!c) return owners[mid].pkg;
   2481         if (c < 0) hi = mid - 1; else lo = mid + 1;
   2482     }
   2483     return NULL;
   2484 }
   2485 
   2486 static int owned_by_other(const char *path, const char *name)
   2487 {
   2488     int i;
   2489     for (i = 0; i < nowners; i++) if (!strcmp(owners[i].path, path) && strcmp(owners[i].pkg, name)) return 1;
   2490     return 0;
   2491 }
   2492 
   2493 static void remove_empty_parents(const char *rel)
   2494 {
   2495     char *p = xstrdup(rel), *s;
   2496     while ((s = strrchr(p, '/'))) {
   2497         char *full;
   2498         *s = 0;
   2499         if (!strchr(p, '/')) break;
   2500         full = fmt("%s/%s", root, p);
   2501         if (rmdir(full) < 0) { free(full); break; }
   2502         free(full);
   2503     }
   2504     free(p);
   2505 }
   2506 
   2507 static void delete_files(const struct list *files)
   2508 {
   2509     int i;
   2510     for (i = files->n - 1; i >= 0; i--) {
   2511         char *full = fmt("%s/%s", root, files->v[i]);
   2512         unlink(full);
   2513         free(full);
   2514         remove_empty_parents(files->v[i]);
   2515     }
   2516 }
   2517 
   2518 static int same_file(const char *a, const char *b)
   2519 {
   2520     struct stat sa, sb;
   2521     char *ha, *hb;
   2522     int same;
   2523     if (lstat(a, &sa) < 0 || lstat(b, &sb) < 0) return 0;
   2524     if (S_ISLNK(sa.st_mode) || S_ISLNK(sb.st_mode)) {
   2525         char ta[PATH_MAX], tb[PATH_MAX];
   2526         ssize_t na, nb;
   2527         if (!S_ISLNK(sa.st_mode) || !S_ISLNK(sb.st_mode)) return 0;
   2528         na = readlink(a, ta, sizeof ta - 1); nb = readlink(b, tb, sizeof tb - 1);
   2529         return na >= 0 && na == nb && !memcmp(ta, tb, na);
   2530     }
   2531     if (!S_ISREG(sa.st_mode) || !S_ISREG(sb.st_mode) || sa.st_size != sb.st_size) return 0;
   2532     ha = sha256_file(a); hb = sha256_file(b);
   2533     same = ha && hb && !strcmp(ha, hb);
   2534     free(ha); free(hb);
   2535     return same;
   2536 }
   2537 
   2538 /* ---- scripts ---- */
   2539 
   2540 struct later { char *pkg, *script; struct list args; };
   2541 static struct later *waiting;
   2542 static int nwaiting;
   2543 
   2544 /* runs one of a package's scripts inside the root. 1 if it can't yet: what its #! wants is not there */
   2545 static int script(const char *pkg, const char *name, const struct list *args)
   2546 {
   2547     char *d = dbdir(pkg), *src = fmt("%s/%s", d, name), *text = slurp(src, NULL), *interp, *inside, *full, **av;
   2548     pid_t pid;
   2549     int i, rc;
   2550     free(d); free(src);
   2551     if (!text) return 0;
   2552     if (strncmp(text, "#!", 2)) interp = xstrdup("/bin/sh");
   2553     else { char *s = text + 2; while (*s == ' ') s++; interp = xstrndup(s, strcspn(s, " \t\n")); }
   2554     free(text);
   2555     full = fmt("%s%s", root, interp);
   2556     rc = exists(full);
   2557     free(full); free(interp);
   2558     if (!rc) return 1;
   2559     inside = fmt("/var/lib/mag/%s/%s", pkg, name);
   2560     av = xmalloc((args->n + 2) * sizeof *av);
   2561     av[0] = inside;
   2562     for (i = 0; i < args->n; i++) av[i + 1] = args->v[i];
   2563     av[args->n + 1] = NULL;
   2564     printf("==> %s %s\n", pkg, name);
   2565     fflush(stdout);
   2566     pid = fork();
   2567     if (pid < 0) die("cannot fork");
   2568     if (*root) {
   2569         char *dev = fmt("%s/dev", root), *null = fmt("%s/dev/null", root);
   2570         mkpath(dev, 0755);
   2571         if (!exists(null)) mknod(null, S_IFCHR | 0666, makedev(1, 3));
   2572         free(dev); free(null);
   2573     }
   2574     if (!pid) {
   2575         if (*root && (chroot(root) < 0 || chdir("/") < 0)) { fprintf(stderr, "%s: chroot %s: %s\n", prog, root, strerror(errno)); _exit(126); }
   2576         setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
   2577         execvp(av[0], av);
   2578         fprintf(stderr, "%s: %s: %s\n", prog, av[0], strerror(errno));
   2579         _exit(127);
   2580     }
   2581     rc = wait_for(pid);
   2582     if (rc) say("%s: %s exited with %d", pkg, name, rc);
   2583     free(inside); free(av);
   2584     return 0;
   2585 }
   2586 
   2587 static void script_or_later(const char *pkg, const char *name, const char *a1, const char *a2)
   2588 {
   2589     struct list args = { 0 };
   2590     if (a1) push(&args, xstrdup(a1));
   2591     if (a2) push(&args, xstrdup(a2));
   2592     if (!script(pkg, name, &args)) { list_free(&args); return; }
   2593     waiting = xrealloc(waiting, (nwaiting + 1) * sizeof *waiting);
   2594     waiting[nwaiting].pkg = xstrdup(pkg);
   2595     waiting[nwaiting].script = xstrdup(name);
   2596     waiting[nwaiting].args = args;
   2597     nwaiting++;
   2598 }
   2599 
   2600 /* scripts that waited for their interpreter, run once it is installed */
   2601 static void run_waiting(void)
   2602 {
   2603     int i, left = nwaiting, progress = 1;
   2604     while (left && progress) {
   2605         progress = 0;
   2606         for (i = 0; i < nwaiting; i++) {
   2607             if (!waiting[i].pkg || script(waiting[i].pkg, waiting[i].script, &waiting[i].args)) continue;
   2608             waiting[i].pkg = NULL;
   2609             left--;
   2610             progress = 1;
   2611         }
   2612     }
   2613     for (i = 0; i < nwaiting; i++) if (waiting[i].pkg) say("%s: %s did not run, nothing in the root can run it", waiting[i].pkg, waiting[i].script);
   2614     nwaiting = 0;
   2615 }
   2616 
   2617 static int glob_match(const char *p, const char *s)
   2618 {
   2619     if (!*p) return !*s;
   2620     if (*p == '*') return glob_match(p + 1, s) || (*s && *s != '/' && glob_match(p, s + 1));
   2621     return *s && ((*p == '?' && *s != '/') || *p == *s) && glob_match(p + 1, s + 1);
   2622 }
   2623 
   2624 /* a package with a trigger runs it with the directories that changed and that it watches */
   2625 static void triggers(const struct list *changed)
   2626 {
   2627     struct list all = db_all();
   2628     int i, j, k;
   2629     for (i = 0; i < all.n; i++) {
   2630         struct list globs, args = { 0 };
   2631         char *t = db_get(all.v[i], "triggers");
   2632         if (!t) continue;
   2633         globs = words(t);
   2634         for (j = 0; j < changed->n; j++)
   2635             for (k = 0; k < globs.n; k++)
   2636                 if (glob_match(globs.v[k], changed->v[j]) && !has(&args, changed->v[j])) push(&args, changed->v[j]);
   2637         if (args.n) script(all.v[i], "trigger", &args);
   2638         list_free(&globs);
   2639         free(args.v);
   2640         free(t);
   2641     }
   2642 }
   2643 
   2644 /* ---- alpm hooks: what pacman runs around a transaction, from /usr/share/libalpm/hooks and /etc/pacman.d/hooks ---- */
   2645 
   2646 /* what a run did, for the hooks: "I path", "U path", "R path", and the same for packages */
   2647 static struct list did_files, did_pkgs;
   2648 
   2649 static int alpm_match(const char *p, const char *s)
   2650 {
   2651     if (!*p) return !*s;
   2652     if (*p == '*') return alpm_match(p + 1, s) || (*s && alpm_match(p, s + 1));
   2653     if (*p == '[') {
   2654         const char *q = p + 1;
   2655         int neg = *q == '!' || *q == '^', ok = 0;
   2656         for (q += neg; *q && (*q != ']' || q == p + 1 + neg); q++) {
   2657             if (q[1] == '-' && q[2] && q[2] != ']') { if (*s >= *q && *s <= q[2]) ok = 1; q += 2; }
   2658             else if (*q == *s) ok = 1;
   2659         }
   2660         return *q && *s && ok != neg && alpm_match(q + 1, s + 1);
   2661     }
   2662     return *s && (*p == '?' || *p == *s) && alpm_match(p + 1, s + 1);
   2663 }
   2664 
   2665 struct trig { int ops, pkg; struct list targets; };
   2666 struct hook { char *desc, *exec; int post, needs, ntrig; struct trig trig[8]; };
   2667 
   2668 static char *htrim(char *s)
   2669 {
   2670     char *e;
   2671     while (*s == ' ' || *s == '\t') s++;
   2672     for (e = s + strlen(s); e > s && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r'); ) *--e = 0;
   2673     return s;
   2674 }
   2675 
   2676 static int hook_read(const char *file, struct hook *h)
   2677 {
   2678     char *t = slurp(file, NULL), *line, *next;
   2679     int sec = 0;
   2680     memset(h, 0, sizeof *h);
   2681     if (!t) return -1;
   2682     for (line = t; line; line = next) {
   2683         char *key, *val, *eq;
   2684         next = strchr(line, '\n');
   2685         if (next) *next++ = 0;
   2686         key = htrim(line);
   2687         if (!*key || *key == '#') continue;
   2688         if (!strcmp(key, "[Trigger]")) { sec = h->ntrig < 8 ? (h->ntrig++, 1) : 0; continue; }
   2689         if (!strcmp(key, "[Action]")) { sec = 2; continue; }
   2690         val = "";
   2691         if ((eq = strchr(key, '='))) { *eq = 0; val = htrim(eq + 1); key = htrim(key); }
   2692         if (sec == 1) {
   2693             struct trig *g = &h->trig[h->ntrig - 1];
   2694             if (!strcmp(key, "Operation")) g->ops |= !strcmp(val, "Install") ? 1 : !strcmp(val, "Upgrade") ? 2 : !strcmp(val, "Remove") ? 4 : 0;
   2695             else if (!strcmp(key, "Type")) g->pkg = !strcmp(val, "Package");
   2696             else if (!strcmp(key, "Target")) push(&g->targets, xstrdup(val));
   2697         } else if (sec == 2) {
   2698             if (!strcmp(key, "When")) h->post = !strcmp(val, "PostTransaction");
   2699             else if (!strcmp(key, "Exec")) { free(h->exec); h->exec = xstrdup(val); }
   2700             else if (!strcmp(key, "Description")) { free(h->desc); h->desc = xstrdup(val); }
   2701             else if (!strcmp(key, "NeedsTargets")) h->needs = 1;
   2702         }
   2703     }
   2704     free(t);
   2705     return h->exec && h->ntrig ? 0 : -1;
   2706 }
   2707 
   2708 static void hook_free(struct hook *h)
   2709 {
   2710     int i;
   2711     for (i = 0; i < h->ntrig; i++) list_free(&h->trig[i].targets);
   2712     free(h->desc); free(h->exec);
   2713 }
   2714 
   2715 /* the first pattern that matches decides, a ! one against */
   2716 static int hook_targets(const struct list *pats, const char *s)
   2717 {
   2718     int i;
   2719     for (i = 0; i < pats->n; i++) {
   2720         const char *p = pats->v[i];
   2721         int neg = *p == '!';
   2722         if (alpm_match(p + neg, s)) return !neg;
   2723     }
   2724     return 0;
   2725 }
   2726 
   2727 /* Exec split into words the way alpm does it: spaces, quotes and backslashes */
   2728 static char **hook_argv(const char *s)
   2729 {
   2730     char **av = xmalloc((strlen(s) / 2 + 2) * sizeof *av);
   2731     int n = 0;
   2732     while (*s) {
   2733         char *w = xmalloc(strlen(s) + 1), *o = w, q = 0;
   2734         while (*s == ' ' || *s == '\t') s++;
   2735         if (!*s) { free(w); break; }
   2736         for (; *s && (q || (*s != ' ' && *s != '\t')); s++) {
   2737             if (*s == '\\' && s[1] && q != '\'') { *o++ = *++s; continue; }
   2738             if (!q && (*s == '"' || *s == '\'')) { q = *s; continue; }
   2739             if (q && *s == q) { q = 0; continue; }
   2740             *o++ = *s;
   2741         }
   2742         *o = 0;
   2743         av[n++] = w;
   2744     }
   2745     av[n] = NULL;
   2746     return av;
   2747 }
   2748 
   2749 /* runs av inside the root, the lines of in on its standard input */
   2750 static int run_in_root(char **av, const struct list *in)
   2751 {
   2752     int fd[2] = { -1, -1 }, i;
   2753     pid_t pid;
   2754     if (in && pipe(fd) < 0) die("cannot make a pipe");
   2755     fflush(stdout);
   2756     if ((pid = fork()) < 0) die("cannot fork");
   2757     if (!pid) {
   2758         if (in) { dup2(fd[0], 0); close(fd[0]); close(fd[1]); }
   2759         /* in the root's / like pacman: glibc's hook is ldconfig -r . */
   2760         if ((*root && chroot(root) < 0) || chdir("/") < 0) { fprintf(stderr, "%s: chroot %s: %s\n", prog, root, strerror(errno)); _exit(126); }
   2761         setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
   2762         execvp(av[0], av);
   2763         fprintf(stderr, "%s: %s: %s\n", prog, av[0], strerror(errno));
   2764         _exit(127);
   2765     }
   2766     if (in) {
   2767         close(fd[0]);
   2768         for (i = 0; i < in->n; i++) if (write(fd[1], in->v[i], strlen(in->v[i])) < 0 || write(fd[1], "\n", 1) < 0) break;
   2769         close(fd[1]);
   2770     }
   2771     return wait_for(pid);
   2772 }
   2773 
   2774 static int cmp_strp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
   2775 
   2776 static void run_hooks(int post)
   2777 {
   2778     static const char *const where[] = { "/usr/share/libalpm/hooks", "/etc/pacman.d/hooks" };
   2779     struct list names = { 0 }, files = { 0 };
   2780     int i, j, k;
   2781     if (!did_files.n && !did_pkgs.n) return;
   2782     for (i = 0; i < 2; i++) {
   2783         char *d = fmt("%s%s", root, where[i]);
   2784         DIR *dir = opendir(d);
   2785         struct dirent *e;
   2786         while (dir && (e = readdir(dir))) {
   2787             size_t l = strlen(e->d_name);
   2788             char *f;
   2789             if (l < 6 || strcmp(e->d_name + l - 5, ".hook")) continue;
   2790             f = fmt("%s/%s", d, e->d_name);
   2791             for (j = 0; j < names.n && strcmp(names.v[j], e->d_name); j++) {}
   2792             if (j < names.n) { free(files.v[j]); files.v[j] = f; }
   2793             else { push(&names, xstrdup(e->d_name)); push(&files, f); }
   2794         }
   2795         if (dir) closedir(dir);
   2796         free(d);
   2797     }
   2798     for (i = 0; i < names.n; i++) {
   2799         for (j = i + 1; j < names.n; j++)
   2800             if (strcmp(names.v[j], names.v[i]) < 0) { char *t = names.v[i]; names.v[i] = names.v[j]; names.v[j] = t; t = files.v[i]; files.v[i] = files.v[j]; files.v[j] = t; }
   2801     }
   2802     for (i = 0; i < names.n; i++) {
   2803         struct hook h;
   2804         struct list hit = { 0 };
   2805         char lnk[16];
   2806         ssize_t ln = readlink(files.v[i], lnk, sizeof lnk - 1);
   2807         if (ln == 9 && !strncmp(lnk, "/dev/null", 9)) continue;
   2808         if (hook_read(files.v[i], &h)) { hook_free(&h); continue; }
   2809         if (h.post == post)
   2810             for (j = 0; j < h.ntrig; j++) {
   2811                 const struct list *did = h.trig[j].pkg ? &did_pkgs : &did_files;
   2812                 for (k = 0; k < did->n; k++) {
   2813                     const char *e = did->v[k];
   2814                     int op = *e == 'I' ? 1 : *e == 'U' ? 2 : 4;
   2815                     if (h.trig[j].ops & op && hook_targets(&h.trig[j].targets, e + 2) && !has(&hit, e + 2)) push(&hit, xstrdup(e + 2));
   2816                 }
   2817             }
   2818         if (hit.n) {
   2819             char **av = hook_argv(h.exec);
   2820             int rc;
   2821             if (hit.n > 1) qsort(hit.v, hit.n, sizeof *hit.v, cmp_strp);
   2822             printf("==> %s\n", h.desc ? h.desc : names.v[i]);
   2823             if (av[0] && (rc = run_in_root(av, h.needs ? &hit : NULL))) say("%s exited with %d", names.v[i], rc);
   2824             for (k = 0; av[k]; k++) free(av[k]);
   2825             free(av);
   2826         }
   2827         list_free(&hit);
   2828         hook_free(&h);
   2829     }
   2830     list_free(&names); list_free(&files);
   2831 }
   2832 
   2833 /* after a run on a pacman machine, its hooks */
   2834 static void after_run(void)
   2835 {
   2836     if (!alpm_order) return;
   2837     run_hooks(1);
   2838     list_free(&did_files); list_free(&did_pkgs);
   2839 }
   2840 
   2841 /* ---- port trees: CRUX ports, built here from their Pkgfile ---- */
   2842 
   2843 /* the text a signify file signs, if its signature checks out with the key its first line names */
   2844 static char *signify(const char *file)
   2845 {
   2846     char *t = slurp(file, NULL), *l2, *msg, *kname, *d, *kf = NULL, *kt = NULL, *kl, *ok = NULL;
   2847     unsigned char sig[96], pk[64];
   2848     if (!t || strncmp(t, "untrusted comment: ", 19) || !(l2 = strchr(t, '\n')) || !(msg = strchr(l2 + 1, '\n'))) { say("%s is not signed", file); goto out; }
   2849     *l2++ = 0;
   2850     *msg++ = 0;
   2851     kname = strrchr(t, '/') ? strrchr(t, '/') + 1 : strrchr(t, ' ') + 1;
   2852     d = confdir();
   2853     kf = fmt("%s/keys/%s", d, kname);
   2854     free(d);
   2855     if (!(kt = slurp(kf, NULL)) || !(kl = strchr(kt, '\n'))) say("%s is signed with %s, which is not there", file, kf);
   2856     else if (unbase64(kl + 1, pk) != 42 || unbase64(l2, sig) != 74 || memcmp(pk, "Ed", 2) || memcmp(sig, "Ed", 2) || memcmp(pk + 2, sig + 2, 8))
   2857         say("%s is not signed with %s", file, kf);
   2858     else if (!ed25519_ok(sig + 10, pk + 10, msg, strlen(msg))) say("the signature of %s does not match %s", file, kf);
   2859     else ok = xstrdup(msg);
   2860 out:
   2861     free(t); free(kt); free(kf);
   2862     return ok;
   2863 }
   2864 
   2865 static char *signed_sum(const char *msg, const char *file)
   2866 {
   2867     char *want = fmt("SHA256 (%s) = ", file), *s, *v = NULL;
   2868     for (s = strstr(msg, want); s && !v; s = strstr(s + 1, want))
   2869         if (s == msg || s[-1] == '\n') v = xstrndup(s + strlen(want), strcspn(s + strlen(want), "\n"));
   2870     free(want);
   2871     return v;
   2872 }
   2873 
   2874 static int has_line(const char *text, const char *line)
   2875 {
   2876     size_t n = strlen(line);
   2877     const char *s;
   2878     for (s = text ? strstr(text, line) : NULL; s; s = strstr(s + 1, line))
   2879         if ((s == text || s[-1] == '\n') && (s[n] == '\n' || !s[n])) return 1;
   2880     return 0;
   2881 }
   2882 
   2883 static char *trim(char *s)
   2884 {
   2885     char *e;
   2886     while (*s == ' ' || *s == '\t' || *s == '"' || *s == '\'') s++;
   2887     for (e = s + strlen(s); e > s && strchr(" \t\"'", e[-1]); ) *--e = 0;
   2888     return s;
   2889 }
   2890 
   2891 /* what the index needs of a Pkgfile: the comments on top and name, version and release */
   2892 static void port_entry(struct buf *b, const char *dir, const char *port)
   2893 {
   2894     char *f = fmt("%s/%s/Pkgfile", dir, port), *t = slurp(f, NULL), *line, *next, *ver = NULL, *rel = "1", *desc = "", *deps = "", *s, *e;
   2895     free(f);
   2896     if (!t) return;
   2897     for (line = t; line && *line; line = next) {
   2898         next = strchr(line, '\n');
   2899         if (next) *next++ = 0;
   2900         if (!strncmp(line, "# Description:", 14)) desc = trim(line + 14);
   2901         else if (!strncmp(line, "# Depends on:", 13)) deps = trim(line + 13);
   2902         else if (!strncmp(line, "version=", 8)) ver = trim(line + 8);
   2903         else if (!strncmp(line, "release=", 8)) rel = trim(line + 8);
   2904         else if (!strncmp(line, "build", 5)) break;
   2905     }
   2906     for (s = deps; *s; s++) if (*s == ',') *s = ' ';
   2907     if (ver && (e = strstr(ver, "${name}"))) { *e = 0; ver = fmt("%s%s%s", ver, port, e + 7); }
   2908     if (ver && !strchr(ver, '$')) {
   2909         s = fmt("P:%s\nV:%s-r%s\nT:%s\nD:%s\nk:-1\n\n", port, ver, rel, desc, deps);
   2910         buf_add(b, s, strlen(s));
   2911         free(s);
   2912     }
   2913     free(t);
   2914 }
   2915 
   2916 /* gets the files of the tree REPO lists that changed since the last time, as httpup does, and indexes them. a file
   2917  * that does not come is left out of the REPO kept here, so the next update tries it again */
   2918 static int sync_tree(int i)
   2919 {
   2920     char *dir = tree_dir(i), *repo = fmt("%s/REPO", dir), *tmp = fmt("%s/REPO.new", dir), *url = fmt("%s/REPO", repo_urls.v[i]), *idx = fmt("%s/INDEX", dir);
   2921     char *old = NULL, *t = NULL, *line, *next;
   2922     struct list urls = { 0 }, files = { 0 }, keep = { 0 }, have = { 0 }, dirs = { 0 };
   2923     struct buf b = { 0 }, r = { 0 };
   2924     int bad = 0, k, lost = 0;
   2925     printf("==> %s\n", url);
   2926     mkpath(dir, 0755);
   2927     if (download(url, tmp)) { say("could not fetch %s", url); bad = 1; goto out; }
   2928     old = slurp(repo, NULL);
   2929     t = slurp(tmp, NULL);
   2930     for (line = t; line && *line; line = next) {
   2931         char *path, *c, *full, *base;
   2932         next = strchr(line, '\n');
   2933         if (next) *next++ = 0;
   2934         if (strncmp(line, "f:", 2) || !(path = strchr(line + 2, ':'))) continue;
   2935         path++;
   2936         if (!(base = strchr(path, '/'))) continue;
   2937         if (*++base == '.' && strcmp(base, ".signature") && strcmp(base, ".footprint")) continue;
   2938         c = clean(path);
   2939         if (!c || strcmp(c, path) || strpbrk(path, "\"\\'")) { say("%s has a bad path in it, %s", url, path); free(c); continue; }
   2940         push(&keep, c);
   2941         full = fmt("%s/%s", dir, path);
   2942         if (!exists(full) || !has_line(old, line)) { unlink(full); push(&urls, fmt("%s/%s", repo_urls.v[i], path)); push(&files, full); }
   2943         else free(full);
   2944     }
   2945     if (urls.n) printf("==> %d files\n", urls.n);
   2946     fetch_all(&urls, &files, dir);
   2947     for (k = 0; k < files.n; k++) lost += !exists(files.v[k]);
   2948     if (lost) { say("%d files of %s did not come, mag update tries again", lost, repo_urls.v[i]); bad = 1; }
   2949     free(t);
   2950     t = slurp(tmp, NULL);
   2951     buf_add(&r, "", 0);
   2952     for (line = t; line && *line; line = next) {
   2953         char *path, *full;
   2954         next = strchr(line, '\n');
   2955         if (next) *next++ = 0;
   2956         if (!strncmp(line, "f:", 2) && (path = strchr(line + 2, ':'))) {
   2957             full = fmt("%s/%s", dir, path + 1);
   2958             k = exists(full);
   2959             free(full);
   2960             if (!k) continue;
   2961         }
   2962         buf_add(&r, line, strlen(line));
   2963         buf_add(&r, "\n", 1);
   2964     }
   2965     k = open(repo, O_WRONLY | O_CREAT | O_TRUNC, 0644);
   2966     if (k < 0 || write(k, r.p, r.n) != (ssize_t)r.n || close(k) < 0) die("cannot write %s: %s", repo, strerror(errno));
   2967     unlink(tmp);
   2968     walk(dir, "", &have, &dirs);
   2969     for (k = 0; k < have.n; k++)
   2970         if (!has(&keep, have.v[k]) && strcmp(have.v[k], "REPO") && strcmp(have.v[k], "REPO.new") && strcmp(have.v[k], "INDEX")) {
   2971             char *f = fmt("%s/%s", dir, have.v[k]);
   2972             unlink(f);
   2973             free(f);
   2974         }
   2975     buf_add(&b, "", 0);
   2976     free(t);
   2977     t = slurp(repo, NULL);
   2978     for (line = t; line && *line; line = next) {
   2979         char *pf;
   2980         next = strchr(line, '\n');
   2981         if (next) *next++ = 0;
   2982         if (strncmp(line, "d:", 2) || strchr(line + 2, '/')) continue;
   2983         pf = fmt("%s/Pkgfile", line + 2);
   2984         if (has(&keep, pf)) port_entry(&b, dir, line + 2);
   2985         free(pf);
   2986     }
   2987     db_put_file(idx, (char *)b.p);
   2988 out:
   2989     list_free(&urls); list_free(&files); list_free(&keep); list_free(&have); list_free(&dirs);
   2990     free(b.p); free(r.p); free(old); free(t); free(dir); free(repo); free(tmp); free(url); free(idx);
   2991     return bad;
   2992 }
   2993 
   2994 /* runs a shell script inside the root, with bash if it is there: Pkgfiles are written for it */
   2995 static int shell(const char *text)
   2996 {
   2997     static const char *const shs[] = { "/bin/bash", "/usr/bin/bash", "/bin/mksh", "/usr/bin/mksh" };
   2998     const char *sh = NULL;
   2999     pid_t pid;
   3000     int i;
   3001     for (i = 0; i < 4 && !sh; i++) { char *f = fmt("%s%s", root, shs[i]); if (exists(f)) sh = shs[i]; free(f); }
   3002     if (!sh) die("building a port needs bash, mag install bash");
   3003     fflush(stdout);
   3004     if ((pid = fork()) < 0) die("cannot fork");
   3005     if (!pid) {
   3006         if (*root && (chroot(root) < 0 || chdir("/") < 0)) { fprintf(stderr, "%s: chroot %s: %s\n", prog, root, strerror(errno)); _exit(126); }
   3007         setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
   3008         execl(sh, sh, "-c", text, (char *)NULL);
   3009         _exit(127);
   3010     }
   3011     return wait_for(pid);
   3012 }
   3013 
   3014 static const char *in_root(const char *path) { return path + strlen(root); }
   3015 
   3016 static int is_archive(const char *f)
   3017 {
   3018     static const char *const ext[] = { ".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar.lz", ".tar.lzma", ".tar.zst", ".zip" };
   3019     size_t n = strlen(f);
   3020     int i;
   3021     for (i = 0; i < 11; i++) if (n > strlen(ext[i]) && !strcmp(f + n - strlen(ext[i]), ext[i])) return 1 + (i == 10);
   3022     return 0;
   3023 }
   3024 
   3025 /* what pkgmk does: the sources, checked against the signed sums, unpacked into $SRC, then build() puts the package in $PKG */
   3026 static void build_port(const struct pkg *p, const char *stage)
   3027 {
   3028     char *tree = tree_dir(p->repo), *dir = fmt("%s/%s", tree, p->name), *sigf = fmt("%s/.signature", dir), *msg, *sum, *have;
   3029     char *work = fmt("%s/var/tmp/mag/build/%s", root, p->name), *src = fmt("%s/src", work), *list = fmt("%s/sources", work), *cache = fmt("%s/var/cache/mag/src", root);
   3030     char *s, *t, *line, *next;
   3031     struct list files = { 0 }, dirs = { 0 };
   3032     printf("==> building %s %s\n", p->name, p->ver);
   3033     if (!(msg = signify(sigf))) die("not building %s", p->name);
   3034     s = fmt("%s/Pkgfile", dir);
   3035     sum = signed_sum(msg, "Pkgfile");
   3036     have = sha256_file(s);
   3037     if (!sum || !have || strcmp(sum, have)) die("%s: the Pkgfile does not match its .signature", p->name);
   3038     free(s); free(sum); free(have);
   3039     rmtree(work);
   3040     rmtree(stage);
   3041     mkpath(src, 0755);
   3042     mkpath(stage, 0755);
   3043     mkpath(cache, 0755);
   3044     s = fmt("cd '%s' && . ./Pkgfile && for s in \"${source[@]}\"; do printf '%%s\\n' \"$s\"; done > '%s'", in_root(dir), in_root(list));
   3045     if (shell(s)) die("%s: cannot read the Pkgfile", p->name);
   3046     free(s);
   3047     t = slurp(list, NULL);
   3048     for (line = t; line && *line; line = next) {
   3049         char *base, *file, *cmd;
   3050         int remote = strstr(line, "://") != NULL, kind;
   3051         next = strchr(line, '\n');
   3052         if (next) *next++ = 0;
   3053         base = strrchr(line, '/') ? strrchr(line, '/') + 1 : line;
   3054         if (!*base || strpbrk(base, "'\\") || !strcmp(base, "..")) die("%s: a source with a bad name, %s", p->name, line);
   3055         file = remote ? fmt("%s/%s", cache, base) : fmt("%s/%s", dir, line);
   3056         if (!(sum = signed_sum(msg, base))) die("%s: %s is not in its .signature", p->name, base);
   3057         have = exists(file) ? sha256_file(file) : NULL;
   3058         if (remote && (!have || strcmp(have, sum))) {
   3059             printf("==> fetching %s\n", line);
   3060             free(have);
   3061             if (download(line, file)) die("could not fetch %s", line);
   3062             have = sha256_file(file);
   3063         }
   3064         if (!have || strcmp(have, sum)) die("%s: %s does not match its .signature", p->name, base);
   3065         kind = is_archive(base);
   3066         if (kind == 2) cmd = fmt("unzip -qo '%s' -d '%s'", in_root(file), in_root(src));
   3067         else if (kind) cmd = fmt("tar -C '%s' -xf '%s'", in_root(src), in_root(file));
   3068         else cmd = fmt("cp '%s' '%s/'", in_root(file), in_root(src));
   3069         if (shell(cmd)) die("%s: cannot unpack %s", p->name, base);
   3070         free(cmd); free(file); free(sum); free(have);
   3071     }
   3072     free(t);
   3073     s = fmt("set -e\n"
   3074             "[ -f /etc/mag/build.conf ] && . /etc/mag/build.conf\n"
   3075             "export CFLAGS=\"${CFLAGS:--O2 -pipe}\" CXXFLAGS=\"${CXXFLAGS:-${CFLAGS:--O2 -pipe}}\" MAKEFLAGS=\"${MAKEFLAGS:--j$(nproc)}\"\n"
   3076             "export PKG='%s' SRC='%s' PKGMK_ROOT='%s'\n"
   3077             "cd \"$PKGMK_ROOT\"\n"
   3078             ". ./Pkgfile\n"
   3079             "cd \"$SRC\"\n"
   3080             "(set -e -x; build)\n"
   3081             "cd \"$PKG\"\n"
   3082             "rm -f usr/share/info/dir\n"
   3083             "if command -v strip >/dev/null; then\n"
   3084             "  find . -type f \\( -perm -100 -o -name '*.so' -o -name '*.so.*' \\) -exec strip --strip-unneeded {} + 2>/dev/null || :\n"
   3085             "fi\n", in_root(stage), in_root(src), in_root(dir));
   3086     if (shell(s)) die("%s did not build, what it left is in %s", p->name, work);
   3087     free(s);
   3088     walk(stage, "", &files, &dirs);
   3089     if (!files.n) die("%s built nothing", p->name);
   3090     list_free(&files); list_free(&dirs);
   3091     rmtree(work);
   3092     free(tree); free(dir); free(sigf); free(msg); free(work); free(src); free(list); free(cache);
   3093 }
   3094 
   3095 /* ---- Void's srcpkgs and Exherbo's exheres: a git tree, fetched whole, built with the tree's own helpers ---- */
   3096 
   3097 static int match(const char *p, const char *s)
   3098 {
   3099     if (*p == '*') return match(p + 1, s) || (*s && match(p, s + 1));
   3100     if (!*p) return !*s;
   3101     return *s && (*p == '?' || *p == *s) && match(p + 1, s + 1);
   3102 }
   3103 
   3104 struct var { char *k, *v; };
   3105 
   3106 static const char *var_get(const struct var *vs, int n, const char *k)
   3107 {
   3108     while (n--) if (!strcmp(vs[n].k, k)) return vs[n].v;
   3109     return NULL;
   3110 }
   3111 
   3112 /* $x and ${x} of the variables set above it; anything harder stays as it is */
   3113 static char *expand(const char *v, const struct var *vs, int n)
   3114 {
   3115     struct buf b = { 0 };
   3116     buf_add(&b, "", 0);
   3117     while (*v) {
   3118         if (*v == '$') {
   3119             const char *s = v + 1 + (v[1] == '{'), *e, *val;
   3120             char *k;
   3121             for (e = s; isalnum((unsigned char)*e) || *e == '_'; e++) {}
   3122             if (e > s && (v[1] != '{' || *e == '}')) {
   3123                 k = xstrndup(s, e - s);
   3124                 val = var_get(vs, n, k);
   3125                 free(k);
   3126                 if (val) { buf_add(&b, val, strlen(val)); v = e + (v[1] == '{'); continue; }
   3127             }
   3128         }
   3129         buf_add(&b, v++, 1);
   3130     }
   3131     return (char *)b.p;
   3132 }
   3133 
   3134 /* the variables a recipe sets at the top level, outside its functions, ifs and cases */
   3135 static int top_vars(char *t, struct var **out)
   3136 {
   3137     struct var *vs = NULL;
   3138     int n = 0, infn = 0, j;
   3139     char *line, *next, *s;
   3140     for (s = t; (s = strstr(s, "\\\n")); ) s[0] = s[1] = ' ';
   3141     for (line = t; line && *line; line = next) {
   3142         char *k, *v, *val;
   3143         int add;
   3144         size_t l;
   3145         next = strchr(line, '\n');
   3146         if (next) *next++ = 0;
   3147         l = strlen(line);
   3148         if (infn) { infn = *line != '}'; continue; }
   3149         if (!isspace((unsigned char)*line) && strstr(line, "()") && l && line[l - 1] == '{') { infn = 1; continue; }
   3150         if (!strncmp(line, "require ", 8)) { vs = xrealloc(vs, (n + 1) * sizeof *vs); vs[n].k = xstrdup("require"); vs[n++].v = xstrdup(line + 8); continue; }
   3151         for (k = line; isalnum((unsigned char)*k) || *k == '_'; k++) {}
   3152         if (k == line || (*k != '=' && (k[0] != '+' || k[1] != '='))) continue;
   3153         add = *k == '+';
   3154         *k = 0;
   3155         v = k + 1 + add;
   3156         if (*v == '"' || *v == '\'') {
   3157             char q = *v++, *e;
   3158             for (;;) {
   3159                 for (e = v; *e && (*e != q || (q == '"' && e > v && e[-1] == '\\')); e++) {}
   3160                 if (*e || !next) { *e = 0; break; }
   3161                 next[-1] = '\n';
   3162                 e = strchr(next, '\n');
   3163                 next = e ? (*e = 0, e + 1) : NULL;
   3164             }
   3165         } else v[strcspn(v, " \t#;")] = 0;
   3166         val = expand(v, vs, n);
   3167         for (j = n - 1; j >= 0 && strcmp(vs[j].k, line); j--) {}
   3168         if (j >= 0 && add) { char *s = fmt("%s%s", vs[j].v, val); free(vs[j].v); free(val); vs[j].v = s; }
   3169         else if (j >= 0) { free(vs[j].v); vs[j].v = val; }
   3170         else { vs = xrealloc(vs, (n + 1) * sizeof *vs); vs[n].k = xstrdup(line); vs[n++].v = val; }
   3171     }
   3172     *out = vs;
   3173     return n;
   3174 }
   3175 
   3176 static void vars_free(struct var *vs, int n)
   3177 {
   3178     while (n--) { free(vs[n].k); free(vs[n].v); }
   3179     free(vs);
   3180 }
   3181 
   3182 static void entry(struct buf *b, const char *name, const char *ver, const char *desc, const char *deps, const char *prov, const char *path)
   3183 {
   3184     char *s = fmt("P:%s\nV:%s\nT:%s\nD:%s\np:%s\nC:%s\nk:-1\n\n", name, ver, desc ? desc : "", deps, prov ? prov : "", path ? path : "");
   3185     char *c;
   3186     for (c = s; *c; c++) if (*c == '\t') *c = ' ';
   3187     buf_add(b, s, strlen(s));
   3188     free(s);
   3189 }
   3190 
   3191 static void void_deps(struct buf *d, const char *s)
   3192 {
   3193     struct list w = words(s);
   3194     int i;
   3195     for (i = 0; i < w.n; i++) {
   3196         char *n = w.v[i], *dash;
   3197         if (!strncmp(n, "virtual?", 8)) n += 8;
   3198         n[strcspn(n, "<>=")] = 0;
   3199         if ((dash = strrchr(n, '-')) && strchr(dash, '_') && isdigit((unsigned char)dash[1])) *dash = 0;
   3200         if (*n && !strchr(n, '$')) { buf_add(d, " ", 1); buf_add(d, n, strlen(n)); }
   3201         if (!strcmp(n, "automake") || !strcmp(n, "libtool")) buf_add(d, " autoconf", 9);
   3202     }
   3203     list_free(&w);
   3204 }
   3205 
   3206 static int void_arch_ok(const char *archs)
   3207 {
   3208     const char *m = !strcmp(arch, "x86") ? "i686-musl" : !strcmp(arch, "x86_64") ? "x86_64-musl" : arch;
   3209     struct list w = words(archs);
   3210     int i, pos = 0, in = 0, out = 0;
   3211     for (i = 0; i < w.n; i++) {
   3212         if (*w.v[i] == '~') out |= match(w.v[i] + 1, m);
   3213         else { pos = 1; in |= match(w.v[i], m); }
   3214     }
   3215     list_free(&w);
   3216     return !out && (!pos || in);
   3217 }
   3218 
   3219 static void void_entry(struct buf *b, const char *dir, const char *name, const char *prov)
   3220 {
   3221     static const char *const tools[][2] = { { "cmake", "cmake" }, { "meson", "meson" }, { "perl-module", "perl" }, { "cargo", "cargo" }, { "go", "go" },
   3222                                             { "python3-module", "python3 py3-setuptools" }, { "python3-pep517", "python3 py3-build py3-installer" } };
   3223     char *f = fmt("%s/srcpkgs/%s/template", dir, name), *t = slurp(f, NULL), *ver;
   3224     const char *v, *r, *a, *bs;
   3225     struct var *vs;
   3226     struct buf d = { 0 };
   3227     int n, i;
   3228     free(f);
   3229     if (!t) return;
   3230     n = top_vars(t, &vs);
   3231     v = var_get(vs, n, "version");
   3232     r = var_get(vs, n, "revision");
   3233     a = var_get(vs, n, "archs");
   3234     if (v && !strchr(v, '$') && !var_get(vs, n, "broken") && !(a && strcmp(a, "noarch") && !void_arch_ok(a))) {
   3235         buf_add(&d, "", 0);
   3236         void_deps(&d, var_get(vs, n, "hostmakedepends") ? var_get(vs, n, "hostmakedepends") : "");
   3237         void_deps(&d, var_get(vs, n, "makedepends") ? var_get(vs, n, "makedepends") : "");
   3238         void_deps(&d, var_get(vs, n, "depends") ? var_get(vs, n, "depends") : "");
   3239         if ((bs = var_get(vs, n, "build_style")))
   3240             for (i = 0; i < 7; i++) if (!strcmp(bs, tools[i][0])) { buf_add(&d, " ", 1); buf_add(&d, tools[i][1], strlen(tools[i][1])); }
   3241         ver = fmt("%s-r%s", v, r ? r : "1");
   3242         entry(b, name, ver, var_get(vs, n, "short_desc"), (char *)d.p + (d.n > 0), prov, NULL);
   3243         free(ver);
   3244         free(d.p);
   3245     }
   3246     vars_free(vs, n);
   3247     free(t);
   3248 }
   3249 
   3250 static void void_index(struct buf *b, const char *dir)
   3251 {
   3252     char *sp = fmt("%s/srcpkgs", dir);
   3253     struct list names = { 0 }, subs = { 0 }, mains = { 0 };
   3254     DIR *d = opendir(sp);
   3255     struct dirent *e;
   3256     int i, j;
   3257     while (d && (e = readdir(d))) if (e->d_name[0] != '.') push(&names, xstrdup(e->d_name));
   3258     if (d) closedir(d);
   3259     if (names.n) qsort(names.v, names.n, sizeof *names.v, cmp_str);
   3260     for (i = 0; i < names.n; i++) {
   3261         char *f = fmt("%s/%s", sp, names.v[i]), to[256];
   3262         ssize_t k = readlink(f, to, sizeof to - 1);
   3263         if (k > 0) { to[k] = 0; push(&subs, xstrdup(names.v[i])); push(&mains, xstrdup(to)); }
   3264         free(f);
   3265     }
   3266     for (i = 0; i < names.n; i++) {
   3267         struct buf p = { 0 };
   3268         if (has(&subs, names.v[i])) continue;
   3269         buf_add(&p, "", 0);
   3270         for (j = 0; j < subs.n; j++) if (!strcmp(mains.v[j], names.v[i])) { if (p.n) buf_add(&p, " ", 1); buf_add(&p, subs.v[j], strlen(subs.v[j])); }
   3271         void_entry(b, dir, names.v[i], (char *)p.p);
   3272         free(p.p);
   3273     }
   3274     list_free(&names); list_free(&subs); list_free(&mains);
   3275     free(sp);
   3276 }
   3277 
   3278 /* the build and run dependencies of an exheres, without what an option turns on: those are off here */
   3279 static void exherbo_deps(struct buf *d, const char *s)
   3280 {
   3281     struct list w = words(s);
   3282     int i, ann = 0, use = 1, off = 0, depth = 0, offat = 0;
   3283     for (i = 0; i < w.n; i++) {
   3284         char *t = w.v[i], *n;
   3285         size_t l = strlen(t);
   3286         if (!strncmp(t, "[[", 2)) { ann++; continue; }
   3287         if (ann) { if (!strcmp(t, "]]")) ann--; continue; }
   3288         if (!strcmp(t, "(")) { depth++; continue; }
   3289         if (!strcmp(t, ")")) { if (off && depth == offat) off = 0; depth--; continue; }
   3290         if (l > 1 && t[l - 1] == '?') { if (!off) { off = 1; offat = depth + 1; } continue; }
   3291         if (l > 1 && t[l - 1] == ':' && !strchr(t, '/')) { t[l - 1] = 0; use = !strcmp(t, "build") || !strcmp(t, "run") || !strcmp(t, "build+run"); continue; }
   3292         if (!use || off || *t == '!' || !(n = strrchr(t, '/'))) continue;
   3293         n++;
   3294         n[strcspn(n, "[:")] = 0;
   3295         if (*n && !strchr(n, '$')) { buf_add(d, " ", 1); buf_add(d, n, strlen(n)); }
   3296     }
   3297     list_free(&w);
   3298 }
   3299 
   3300 static void exherbo_entry(struct buf *b, const char *dir, const char *rel, const char *pn, const char *file)
   3301 {
   3302     char *f = fmt("%s/%s", dir, rel), *t = slurp(f, NULL), *ver = xstrndup(file + strlen(pn) + 1, strlen(file) - strlen(pn) - 1 - 10);
   3303     const char *pl, *rq, *plat = !strcmp(arch, "x86") ? "x86" : "amd64";
   3304     struct var *vs;
   3305     struct buf d = { 0 };
   3306     int n, ok = 1;
   3307     free(f);
   3308     if (!t || strstr(ver, "scm")) { free(t); free(ver); return; }
   3309     n = top_vars(t, &vs);
   3310     if ((pl = var_get(vs, n, "PLATFORMS"))) {
   3311         struct list w = words(pl);
   3312         int i;
   3313         for (i = 0, ok = 0; i < w.n; i++) ok |= !strcmp(w.v[i] + (*w.v[i] == '~'), plat);
   3314         list_free(&w);
   3315     }
   3316     if (ok) {
   3317         buf_add(&d, "", 0);
   3318         exherbo_deps(&d, var_get(vs, n, "DEPENDENCIES") ? var_get(vs, n, "DEPENDENCIES") : "");
   3319         if ((rq = var_get(vs, n, "require"))) {
   3320             if (strstr(rq, "autotools")) buf_add(&d, " autoconf automake libtool", 26);
   3321             if (strstr(rq, "cmake")) buf_add(&d, " cmake", 6);
   3322             if (strstr(rq, "meson")) buf_add(&d, " meson", 6);
   3323         }
   3324         entry(b, pn, ver, var_get(vs, n, "SUMMARY"), (char *)d.p + (d.n > 0), NULL, rel);
   3325         free(d.p);
   3326     }
   3327     vars_free(vs, n);
   3328     free(t);
   3329     free(ver);
   3330 }
   3331 
   3332 static void exherbo_index(struct buf *b, const char *dir)
   3333 {
   3334     char *pd = fmt("%s/packages", dir);
   3335     struct list cats = { 0 };
   3336     DIR *d = opendir(pd), *d2, *d3;
   3337     struct dirent *e;
   3338     int i;
   3339     while (d && (e = readdir(d))) if (e->d_name[0] != '.') push(&cats, xstrdup(e->d_name));
   3340     if (d) closedir(d);
   3341     for (i = 0; i < cats.n; i++) {
   3342         char *cd = fmt("%s/%s", pd, cats.v[i]);
   3343         if ((d2 = opendir(cd))) {
   3344             while ((e = readdir(d2))) {
   3345                 char *pn = xstrdup(e->d_name), *dd = fmt("%s/%s", cd, pn);
   3346                 struct dirent *e3;
   3347                 if (*pn != '.' && (d3 = opendir(dd))) {
   3348                     while ((e3 = readdir(d3))) {
   3349                         size_t l = strlen(e3->d_name);
   3350                         if (l > strlen(pn) + 11 && !strncmp(e3->d_name, pn, strlen(pn)) && e3->d_name[strlen(pn)] == '-' && !strcmp(e3->d_name + l - 10, ".exheres-0")) {
   3351                             char *rel = fmt("packages/%s/%s/%s", cats.v[i], pn, e3->d_name);
   3352                             exherbo_entry(b, dir, rel, pn, e3->d_name);
   3353                             free(rel);
   3354                         }
   3355                     }
   3356                     closedir(d3);
   3357                 }
   3358                 free(pn); free(dd);
   3359             }
   3360             closedir(d2);
   3361         }
   3362         free(cd);
   3363     }
   3364     list_free(&cats);
   3365     free(pd);
   3366 }
   3367 
   3368 /* github and gitlab give a tarball of a branch; a line can also be the tarball itself */
   3369 static char *archive_url(const char *u)
   3370 {
   3371     size_t n = strlen(u);
   3372     const char *b = strrchr(u, '/');
   3373     if ((n > 7 && !strcmp(u + n - 7, ".tar.gz")) || (n > 4 && !strcmp(u + n - 4, ".tgz"))) return xstrdup(u);
   3374     if (strstr(u, "://github.com/")) return fmt("%s/archive/refs/heads/master.tar.gz", u);
   3375     return fmt("%s/-/archive/master/%s-master.tar.gz", u, b ? b + 1 : u);
   3376 }
   3377 
   3378 static int sync_archive(int i)
   3379 {
   3380     char *dir = tree_dir(i), *url = archive_url(repo_urls.v[i]), *tgz = fmt("%s/tree.tar.gz", dir), *tmp = fmt("%s/new", dir), *tree = fmt("%s/tree", dir), *idx = fmt("%s/INDEX", dir), *top = NULL;
   3381     struct in *r = xmalloc(sizeof *r);
   3382     struct tar t;
   3383     struct buf b = { 0 };
   3384     DIR *d;
   3385     struct dirent *e;
   3386     int fd, bad = 0;
   3387     printf("==> %s\n", url);
   3388     mkpath(dir, 0755);
   3389     if (download(url, tgz)) { say("could not fetch %s", url); bad = 1; goto out; }
   3390     rmtree(tmp);
   3391     mkpath(tmp, 0755);
   3392     memset(&t, 0, sizeof t);
   3393     t.dir = tmp;
   3394     if ((fd = open(tgz, O_RDONLY)) < 0) die("cannot read %s", tgz);
   3395     in_open(r, fd, 0);
   3396     do {
   3397         if (gunzip(r, tar_out, &t) || t.bad) { bad = 1; break; }
   3398     } while (!in_eof(r));
   3399     tar_free(&t);
   3400     close(fd);
   3401     unlink(tgz);
   3402     if (!bad && (d = opendir(tmp))) {
   3403         while ((e = readdir(d))) if (e->d_name[0] != '.') { if (top) bad = 1; else top = fmt("%s/%s", tmp, e->d_name); }
   3404         closedir(d);
   3405     }
   3406     if (bad || !top) { say("%s did not unpack into one directory", url); bad = 1; goto out; }
   3407     rmtree(tree);
   3408     if (rename(top, tree) < 0) die("cannot rename %s: %s", top, strerror(errno));
   3409     buf_add(&b, "", 0);
   3410     if (kinds[i] == VOID) void_index(&b, tree); else exherbo_index(&b, tree);
   3411     db_put_file(idx, (char *)b.p);
   3412 out:
   3413     rmtree(tmp);
   3414     free(r); free(b.p); free(dir); free(url); free(tgz); free(tmp); free(tree); free(idx); free(top);
   3415     return bad;
   3416 }
   3417 
   3418 static const char void_sh[] =
   3419     "export XBPS_COMMONDIR=$MAG_TREE/common XBPS_SRCPKGDIR=$MAG_TREE/srcpkgs XBPS_BUILDSTYLEDIR=$MAG_TREE/common/build-style\n"
   3420     "case $MAG_ARCH in x86) XBPS_MACHINE=i686-musl XBPS_WORDSIZE=32 ;; *) XBPS_MACHINE=$MAG_ARCH-musl XBPS_WORDSIZE=64 ;; esac\n"
   3421     "export XBPS_MACHINE XBPS_TARGET_MACHINE=$XBPS_MACHINE XBPS_TARGET_LIBC=musl XBPS_WORDSIZE XBPS_TARGET_WORDSIZE=\n"
   3422     "export XBPS_BUILDDIR=$MAG_WORK XBPS_SRCDISTDIR=$MAG_SRC XBPS_STATEDIR=$MAG_WORK/.xbps XBPS_MAKEJOBS=$(nproc)\n"
   3423     ". $XBPS_COMMONDIR/build-profiles/$XBPS_MACHINE.sh\n"
   3424     "export XBPS_TRIPLET XBPS_CROSS_TRIPLET= CROSS_BUILD=\n"
   3425     "msg_normal() { printf '==> %b' \"$*\"; }\n"
   3426     "msg_warn() { printf 'warning: %b' \"$*\" >&2; }\n"
   3427     "msg_red() { msg_warn \"$@\"; }\n"
   3428     "msg_verbose() { :; }\n"
   3429     "msg_error() { printf '%b' \"$*\" >&2; exit 1; }\n"
   3430     "for f in archive install misc options python replace-interpreter vsed; do . $XBPS_COMMONDIR/environment/setup/$f.sh; done\n"
   3431     ". $XBPS_SRCPKGDIR/$MAG_PORT/template\n"
   3432     "for f in $build_options_default; do eval \"build_option_$f=1\"; done\n"
   3433     "if [ -n \"$build_style\" ]; then\n"
   3434     "    [ ! -r $XBPS_COMMONDIR/environment/build-style/$build_style.sh ] || . $XBPS_COMMONDIR/environment/build-style/$build_style.sh\n"
   3435     "    . $XBPS_BUILDSTYLEDIR/$build_style.sh\n"
   3436     "fi\n"
   3437     ". $XBPS_SRCPKGDIR/$MAG_PORT/template\n"
   3438     "sourcepkg=$pkgname pkgver=$pkgname-${version}_$revision\n"
   3439     "wrksrc=$XBPS_BUILDDIR/$pkgname-$version\n"
   3440     "FILESDIR=$XBPS_SRCPKGDIR/$pkgname/files PATCHESDIR=$XBPS_SRCPKGDIR/$pkgname/patches\n"
   3441     "export XBPS_WRAPPERDIR=$XBPS_STATEDIR/wrappers XBPS_BUILDHELPERDIR=$XBPS_COMMONDIR/build-helper\n"
   3442     "if [ \"$MAG_STEP\" = list ]; then\n"
   3443     "    exec > \"$MAG_OUT\"\n"
   3444     "    set -- $checksum\n"
   3445     "    for f in $distfiles; do\n"
   3446     "        c=${f#*>} c=${c##*/}\n"
   3447     "        printf '%s\\t%s/%s\\t%s\\n' \"${f%>*}\" \"$pkgname-$version\" \"$c\" \"$1\"\n"
   3448     "        shift\n"
   3449     "    done\n"
   3450     "    exit 0\n"
   3451     "fi\n"
   3452     "[ -z \"$broken\" ] || msg_error \"$pkgver is broken in Void: $broken\\n\"\n"
   3453     "[ -f /etc/mag/build.conf ] && . /etc/mag/build.conf\n"
   3454     "export CFLAGS=\"${CFLAGS:--O2 -pipe}\" CXXFLAGS=\"${CXXFLAGS:-${CFLAGS:--O2 -pipe}}\" LDFLAGS\n"
   3455     "export CC=cc CXX=c++ CPP=cpp LD=ld AR=ar AS=as RANLIB=ranlib STRIP=strip NM=nm OBJDUMP=objdump OBJCOPY=objcopy READELF=readelf PKG_CONFIG=pkg-config\n"
   3456     "[ -z \"$disable_parallel_build\" ] || XBPS_MAKEJOBS=1\n"
   3457     "makejobs=-j$XBPS_MAKEJOBS DESTDIR=$MAG_DEST PKGDESTDIR=$MAG_DEST\n"
   3458     "mkdir -p \"$XBPS_STATEDIR\" \"$XBPS_WRAPPERDIR\" \"$DESTDIR\" || exit 1\n"
   3459     "for f in $build_helper; do . $XBPS_BUILDHELPERDIR/$f.sh || exit 1; done\n"
   3460     "cd_wrksrc() { if [ -d \"$wrksrc/$build_wrksrc\" ]; then cd \"$wrksrc/$build_wrksrc\"; elif [ -d \"$wrksrc\" ]; then cd \"$wrksrc\"; fi; }\n"
   3461     "run() { (set -E -x; trap 'exit 1' ERR; \"$@\") || msg_error \"$pkgver: $1 failed\\n\"; }\n"
   3462     "hooks() { local f; for f in \"$@\"; do [ -r $XBPS_COMMONDIR/hooks/$f.sh ] || continue; unset -f hook; . $XBPS_COMMONDIR/hooks/$f.sh; cd_wrksrc; run hook; done; }\n"
   3463     "step() {\n"
   3464     "    local s=$1\n"
   3465     "    shift\n"
   3466     "    cd_wrksrc\n"
   3467     "    hooks $(for h in \"$@\"; do echo pre-$s/$h; done)\n"
   3468     "    if declare -f pre_$s >/dev/null; then cd_wrksrc; run pre_$s; fi\n"
   3469     "    cd_wrksrc\n"
   3470     "    if declare -f do_$s >/dev/null; then run do_$s\n"
   3471     "    else hooks do-$s/00-distfiles do-$s/00-patches\n"
   3472     "    fi\n"
   3473     "    if declare -f post_$s >/dev/null; then cd_wrksrc; run post_$s; fi\n"
   3474     "}\n"
   3475     "mkdir -p \"$wrksrc\"\n"
   3476     "step extract\n"
   3477     "step patch\n"
   3478     ". $XBPS_COMMONDIR/environment/configure/gnu-configure-args.sh\n"
   3479     "step configure 01-override-config\n"
   3480     "step build\n"
   3481     "step install\n"
   3482     "cd \"$DESTDIR\" || exit 1\n"
   3483     "if [ -d usr/lib64 ] && [ ! -L usr/lib64 ]; then mkdir -p usr/lib; cp -a usr/lib64/. usr/lib/; rm -rf usr/lib64; fi\n"
   3484     "find . -name '*.la' -delete\n"
   3485     "rm -f usr/share/info/dir\n"
   3486     "if command -v strip >/dev/null; then\n"
   3487     "    find . -type f \\( -perm -100 -o -name '*.so' -o -name '*.so.*' \\) -exec strip --strip-unneeded {} + 2>/dev/null || :\n"
   3488     "fi\n"
   3489     "find . -depth -type d -empty -delete\n";
   3490 
   3491 
   3492 static const char exherbo_sh[] =
   3493     "shopt -s extglob\n"
   3494     "die() { echo \"${PNV:-mag}: $*\" >&2; exit 1; }\n"
   3495     "nonfatal() { \"$@\"; }\n"
   3496     "edo() { echo \"$*\" >&2; \"$@\" || die \"$* failed\"; }\n"
   3497     "einfo() { echo \" * $*\"; }\n"
   3498     "elog() { einfo \"$@\"; }\n"
   3499     "ewarn() { echo \" * $*\" >&2; }\n"
   3500     "eerror() { ewarn \"$@\"; }\n"
   3501     "ebegin() { einfo \"$@\"; }\n"
   3502     "eend() { return ${1:-0}; }\n"
   3503     "has() { local x=$1 i; shift; for i in \"$@\"; do [[ $i == \"$x\" ]] && return 0; done; return 1; }\n"
   3504     "hasq() { has \"$@\"; }\n"
   3505     "illegal_in_global_scope() { :; }\n"
   3506     "esandbox() { :; }\n"
   3507     "expecting_tests() { false; }\n"
   3508     "CHOST=$(cc -dumpmachine)\n"
   3509     "exhost() {\n"
   3510     "    case $1 in\n"
   3511     "    --target|--host|--build) echo \"$CHOST\" ;;\n"
   3512     "    --tool-prefix) echo ;;\n"
   3513     "    --is-native) return 0 ;;\n"
   3514     "    *) echo \"$CHOST\" ;;\n"
   3515     "    esac\n"
   3516     "}\n"
   3517     "has_version() { local p=${1##*/}; p=${p%%[:\\[]*}; [[ -d /var/lib/mag/$p ]]; }\n"
   3518     "best_version() { local p=${1##*/}; p=${p%%[:\\[]*}; [[ -f /var/lib/mag/$p/version ]] && echo \"$1-$(cat /var/lib/mag/$p/version)\"; }\n"
   3519     "\n"
   3520     "vcmp() {\n"
   3521     "    local IFS=._- a b i x y\n"
   3522     "    a=($1) b=($2)\n"
   3523     "    for ((i = 0; i < ${#a[@]} || i < ${#b[@]}; i++)); do\n"
   3524     "        x=${a[i]:-0} y=${b[i]:-0}\n"
   3525     "        [[ $x == \"$y\" ]] && continue\n"
   3526     "        if [[ $x =~ ^[0-9]+$ && $y =~ ^[0-9]+$ ]]; then (( 10#$x > 10#$y )); return; fi\n"
   3527     "        [[ $x > $y ]]; return\n"
   3528     "    done\n"
   3529     "    return 1\n"
   3530     "}\n"
   3531     "ever() {\n"
   3532     "    local c=$1 v\n"
   3533     "    shift\n"
   3534     "    case $c in\n"
   3535     "    is_scm) v=${1:-$PV}; [[ $v == scm || $v == *-scm ]] ;;\n"
   3536     "    major) v=${1:-$PV}; echo \"${v%%[._-]*}\" ;;\n"
   3537     "    range)\n"
   3538     "        local a=${1%-*} b=${1#*-} i=1 out= p\n"
   3539     "        [[ $1 == *-* ]] || b=$a\n"
   3540     "        [[ -z $b ]] && b=99\n"
   3541     "        v=${2:-$PV}\n"
   3542     "        for p in ${v//[._-]/ }; do\n"
   3543     "            if (( i >= a && i <= b )); then out+=${out:+.}$p; fi\n"
   3544     "            ((i++))\n"
   3545     "        done\n"
   3546     "        echo \"$out\" ;;\n"
   3547     "    at_least) v=${2:-$PV}; [[ $v == \"$1\" ]] || vcmp \"$v\" \"$1\" ;;\n"
   3548     "    replace) v=${3:-$PV}; local n=$1 r=$2 i=0 out= ch; for ((k=0; k<${#v}; k++)); do ch=${v:k:1}; if [[ $ch == [._-] ]]; then ((++i)); [[ $i == \"$n\" ]] && ch=$r; fi; out+=$ch; done; echo \"$out\" ;;\n"
   3549     "    replace_all) v=${2:-$PV}; echo \"${v//[._-]/$1}\" ;;\n"
   3550     "    delete) ever replace \"$1\" '' \"${2:-$PV}\" ;;\n"
   3551     "    delete_all) v=${1:-$PV}; echo \"${v//[._-]/}\" ;;\n"
   3552     "    split) v=${1:-$PV}; echo \"${v//[._-]/ }\" ;;\n"
   3553     "    split_all) v=${1:-$PV}; echo \"${v//[._-]/ }\" ;;\n"
   3554     "    remainder) v=${1:-$PV}; echo \"${v#*[._-]}\" ;;\n"
   3555     "    *) die \"ever $c is not known here\" ;;\n"
   3556     "    esac\n"
   3557     "}\n"
   3558     "\n"
   3559     "declare -A EXP\n"
   3560     "exlib_of() { local f=${BASH_SOURCE[2]##*/}; echo \"${f%.exlib}\"; }\n"
   3561     "myexparam() {\n"
   3562     "    local b= x=$(exlib_of) k v\n"
   3563     "    [[ $1 == -b ]] && shift\n"
   3564     "    k=${1%%=*} v=${1#*=}\n"
   3565     "    [[ $1 == *=* ]] || v=\n"
   3566     "    if [[ $v == '[' ]]; then\n"
   3567     "        shift; v=\n"
   3568     "        while [[ $# -gt 0 && $1 != ']' ]]; do v+=${v:+ }$1; shift; done\n"
   3569     "    fi\n"
   3570     "    k=${k%\\[\\]}\n"
   3571     "    [[ -v EXP[$x:$k] ]] || EXP[$x:$k]=$v\n"
   3572     "}\n"
   3573     "exparam() {\n"
   3574     "    local b= var= x=$(exlib_of) k\n"
   3575     "    [[ $1 == -b ]] && { b=1; shift; }\n"
   3576     "    [[ $1 == -v ]] && { var=$2; shift 2; }\n"
   3577     "    k=${1%\\[@\\]}\n"
   3578     "    if [[ -n $b ]]; then [[ ${EXP[$x:$k]} == true ]]; return; fi\n"
   3579     "    if [[ -n $var ]]; then\n"
   3580     "        if [[ $1 == *'[@]' ]]; then eval \"$var=(${EXP[$x:$k]})\"; else printf -v \"$var\" '%s' \"${EXP[$x:$k]}\"; fi\n"
   3581     "    else echo \"${EXP[$x:$k]}\"\n"
   3582     "    fi\n"
   3583     "}\n"
   3584     "declare -A LOADED\n"
   3585     "require() {\n"
   3586     "    local name f d k v\n"
   3587     "    while [[ $# -gt 0 ]]; do\n"
   3588     "        name=$1; shift\n"
   3589     "        if [[ $1 == '[' ]]; then\n"
   3590     "            shift\n"
   3591     "            while [[ $# -gt 0 && $1 != ']' ]]; do\n"
   3592     "                k=${1%%=*} v=${1#*=}\n"
   3593     "                shift\n"
   3594     "                if [[ $v == '[' ]]; then\n"
   3595     "                    v=\n"
   3596     "                    while [[ $1 != ']' ]]; do v+=${v:+ }$1; shift; done\n"
   3597     "                    shift\n"
   3598     "                fi\n"
   3599     "                EXP[$name:$k]=$v\n"
   3600     "            done\n"
   3601     "            shift\n"
   3602     "        fi\n"
   3603     "        [[ -n ${LOADED[$name]} ]] && continue\n"
   3604     "        LOADED[$name]=1\n"
   3605     "        f=\n"
   3606     "        for d in \"$PKGDIR\" \"$MAG_TREE/packages/$CATEGORY\" \"$MAG_TREE/exlibs\"; do\n"
   3607     "            [[ -f $d/$name.exlib ]] && { f=$d/$name.exlib; break; }\n"
   3608     "        done\n"
   3609     "        [[ -n $f ]] || die \"no exlib $name\"\n"
   3610     "        source \"$f\"\n"
   3611     "    done\n"
   3612     "}\n"
   3613     "export_exlib_phases() {\n"
   3614     "    local x=$(exlib_of) p\n"
   3615     "    for p in \"$@\"; do eval \"$p() { ${x}_$p \\\"\\$@\\\"; }\"; done\n"
   3616     "}\n"
   3617     "\n"
   3618     "declare -A OPT\n"
   3619     "for o in ncurses truetype crypt openssl ssl bash-completion vim-syntax parts:binaries parts:configuration parts:data parts:development parts:documentation parts:libraries libc:musl providers:eudev providers:openssl providers:libressl providers:elfutils providers:ijg-jpeg providers:jpeg-turbo providers:gtk3 providers:qt5 providers:pkgconf; do OPT[$o]=1; done\n"
   3620     "case $MAG_ARCH in x86) OPT[platform:x86]=1 ;; *) OPT[platform:amd64]=1 ;; esac\n"
   3621     "option() { local o=$1; [[ $o == '!'* ]] && { ! option \"${o#!}\"; return; }; [[ -n ${OPT[$o]} ]]; }\n"
   3622     "optionq() { option \"$@\"; }\n"
   3623     "optionv() { option \"$1\" && echo \"${1##*:}\"; }\n"
   3624     "option_enable() {\n"
   3625     "    set -- $*\n"
   3626     "    local o=$1 f=${2:-${1##*:}} v=$3\n"
   3627     "    if option \"$o\"; then echo \"--enable-$f${v:+=$v}\"; else echo \"--disable-$f\"; fi\n"
   3628     "}\n"
   3629     "option_with() {\n"
   3630     "    set -- $*\n"
   3631     "    local o=$1 f=${2:-${1##*:}} v=$3\n"
   3632     "    if option \"$o\"; then echo \"--with-$f${v:+=$v}\"; else echo \"--without-$f\"; fi\n"
   3633     "}\n"
   3634     "\n"
   3635     "into() { DESTTREE=$1; }\n"
   3636     "insinto() { INSDESTTREE=$1; }\n"
   3637     "exeinto() { EXEDESTTREE=$1; }\n"
   3638     "docinto() { DOCDESTTREE=$1; }\n"
   3639     "insopts() { :; }\n"
   3640     "exeopts() { :; }\n"
   3641     "dodir() { local d; for d; do mkdir -p \"$IMAGE/$d\"; done; }\n"
   3642     "keepdir() { dodir \"$@\"; local d; for d; do touch \"$IMAGE/$d/.keep\"; done; }\n"
   3643     "doins() {\n"
   3644     "    local r= f\n"
   3645     "    [[ $1 == -r ]] && { r=-r; shift; }\n"
   3646     "    mkdir -p \"$IMAGE/$INSDESTTREE\"\n"
   3647     "    for f; do cp -pP $r \"$f\" \"$IMAGE/$INSDESTTREE/\" || die \"doins $f\"; done\n"
   3648     "}\n"
   3649     "newins() { mkdir -p \"$IMAGE/$INSDESTTREE\"; cp -p \"$1\" \"$IMAGE/$INSDESTTREE/$2\" || die \"newins $1\"; }\n"
   3650     "doexe() { local f; mkdir -p \"$IMAGE/$EXEDESTTREE\"; for f; do install -m755 \"$f\" \"$IMAGE/$EXEDESTTREE/\" || die \"doexe $f\"; done; }\n"
   3651     "newexe() { mkdir -p \"$IMAGE/$EXEDESTTREE\"; install -m755 \"$1\" \"$IMAGE/$EXEDESTTREE/$2\" || die \"newexe $1\"; }\n"
   3652     "dobin() { local f; mkdir -p \"$IMAGE/usr/$CHOST/bin\"; for f; do install -m755 \"$f\" \"$IMAGE/usr/$CHOST/bin/\" || die \"dobin $f\"; done; }\n"
   3653     "newbin() { mkdir -p \"$IMAGE/usr/$CHOST/bin\"; install -m755 \"$1\" \"$IMAGE/usr/$CHOST/bin/$2\" || die \"newbin $1\"; }\n"
   3654     "dosbin() { dobin \"$@\"; }\n"
   3655     "newsbin() { newbin \"$@\"; }\n"
   3656     "dolib() { local f; mkdir -p \"$IMAGE/usr/$CHOST/lib\"; for f; do cp -pP \"$f\" \"$IMAGE/usr/$CHOST/lib/\" || die \"dolib $f\"; done; }\n"
   3657     "dolib.so() { dolib \"$@\"; }\n"
   3658     "dolib.a() { dolib \"$@\"; }\n"
   3659     "doheader() { local f; mkdir -p \"$IMAGE/usr/$CHOST/include\"; for f; do cp -p \"$f\" \"$IMAGE/usr/$CHOST/include/\" || die \"doheader $f\"; done; }\n"
   3660     "dodoc() {\n"
   3661     "    local r= f\n"
   3662     "    [[ $1 == -r ]] && { r=-r; shift; }\n"
   3663     "    mkdir -p \"$IMAGE/usr/share/doc/$PNVR/$DOCDESTTREE\"\n"
   3664     "    for f; do [[ -e $f ]] && cp -p $r \"$f\" \"$IMAGE/usr/share/doc/$PNVR/$DOCDESTTREE/\"; done\n"
   3665     "    return 0\n"
   3666     "}\n"
   3667     "newdoc() { mkdir -p \"$IMAGE/usr/share/doc/$PNVR\"; cp -p \"$1\" \"$IMAGE/usr/share/doc/$PNVR/$2\"; }\n"
   3668     "doman() {\n"
   3669     "    local f s\n"
   3670     "    for f; do\n"
   3671     "        s=${f##*.}\n"
   3672     "        [[ $s == [0-9n]* ]] || continue\n"
   3673     "        mkdir -p \"$IMAGE/usr/share/man/man${s:0:1}\"\n"
   3674     "        cp -p \"$f\" \"$IMAGE/usr/share/man/man${s:0:1}/\" || die \"doman $f\"\n"
   3675     "    done\n"
   3676     "}\n"
   3677     "newman() { local s=${2##*.}; mkdir -p \"$IMAGE/usr/share/man/man${s:0:1}\"; cp -p \"$1\" \"$IMAGE/usr/share/man/man${s:0:1}/$2\"; }\n"
   3678     "dosym() { mkdir -p \"$IMAGE/$(dirname \"$2\")\"; ln -sfn \"$1\" \"$IMAGE/$2\"; }\n"
   3679     "emagicdocs() {\n"
   3680     "    local f\n"
   3681     "    for f in README* AUTHORS ChangeLog NEWS THANKS TODO BUGS FAQ CHANGES* \"${DEFAULT_SRC_INSTALL_EXTRA_DOCS[@]}\"; do\n"
   3682     "        [[ -f $f && -s $f ]] && dodoc \"$f\"\n"
   3683     "    done\n"
   3684     "    return 0\n"
   3685     "}\n"
   3686     "alternatives_for() { :; }\n"
   3687     "expart() { :; }\n"
   3688     "here_to() { mkdir -p \"$IMAGE/$1\"; cat > \"$IMAGE/$1/$2\"; chmod \"$3\" \"$IMAGE/$1/$2\"; }\n"
   3689     "hereins() { here_to \"$INSDESTTREE\" \"$1\" 644; }\n"
   3690     "hereexe() { here_to \"$EXEDESTTREE\" \"$1\" 755; }\n"
   3691     "herebin() { here_to \"usr/$CHOST/bin\" \"$1\" 755; }\n"
   3692     "hereenvd() { here_to etc/env.d \"$1\" 644; }\n"
   3693     "hereconfd() { here_to etc/conf.d \"$1\" 644; }\n"
   3694     "hereinitd() { here_to etc/init.d \"$1\" 755; }\n"
   3695     "heredoc() { here_to \"usr/share/doc/$PNVR\" \"$1\" 644; }\n"
   3696     "\n"
   3697     "expatch() {\n"
   3698     "    local p f o=\n"
   3699     "    [[ $1 == -p* ]] && { o=$1; shift; }\n"
   3700     "    for p; do\n"
   3701     "        if [[ -d $p ]]; then for f in \"$p\"/*; do expatch $o \"$f\"; done; continue; fi\n"
   3702     "        [[ -f $p ]] || continue\n"
   3703     "        echo \"patching with ${p##*/}\"\n"
   3704     "        if [[ -n $o ]]; then patch $o -s -N < \"$p\" || die \"patch ${p##*/}\"\n"
   3705     "        else patch -p1 -s -N < \"$p\" || patch -p0 -s -N < \"$p\" || die \"patch ${p##*/}\"; fi\n"
   3706     "    done\n"
   3707     "}\n"
   3708     "emake() { edo make ${MAKEFLAGS:+-j$JOBS} \"$@\"; }\n"
   3709     "econf() {\n"
   3710     "    local src=${ECONF_SOURCE:-.}\n"
   3711     "    edo \"$src/configure\" --prefix=/usr/$CHOST --bindir=/usr/$CHOST/bin --sbindir=/usr/$CHOST/bin --libdir=/usr/$CHOST/lib \\\n"
   3712     "        --libexecdir=/usr/$CHOST/libexec --includedir=/usr/$CHOST/include --datarootdir=/usr/share --datadir=/usr/share \\\n"
   3713     "        --mandir=/usr/share/man --infodir=/usr/share/info --docdir=/usr/share/doc/$PNVR --sysconfdir=/etc --localstatedir=/var \\\n"
   3714     "        --build=$CHOST --host=$CHOST --disable-dependency-tracking \"$@\"\n"
   3715     "}\n"
   3716     "unpack() {\n"
   3717     "    local f\n"
   3718     "    for f; do\n"
   3719     "        [[ $f == */* ]] || f=$FETCHEDDIR/$f\n"
   3720     "        case $f in\n"
   3721     "        *.tar|*.tar.*|*.tgz|*.tbz2|*.txz) edo tar -xf \"$f\" ;;\n"
   3722     "        *.zip) edo unzip -qo \"$f\" ;;\n"
   3723     "        *.gz) gunzip -c \"$f\" > \"$(basename \"${f%.gz}\")\" ;;\n"
   3724     "        *.xz) xz -dc \"$f\" > \"$(basename \"${f%.xz}\")\" ;;\n"
   3725     "        *.bz2) bzip2 -dc \"$f\" > \"$(basename \"${f%.bz2}\")\" ;;\n"
   3726     "        *) cp \"$f\" . ;;\n"
   3727     "        esac\n"
   3728     "    done\n"
   3729     "}\n"
   3730     "\n"
   3731     "default_pkg_setup() { :; }\n"
   3732     "default_src_unpack() { cd \"$WORKBASE\"; [[ -z $A ]] || unpack $A; }\n"
   3733     "default_src_prepare() { expatch \"${DEFAULT_SRC_PREPARE_PATCHES[@]}\"; }\n"
   3734     "default_src_configure() {\n"
   3735     "    local a=() s\n"
   3736     "    [[ -x ${ECONF_SOURCE:-.}/configure ]] || return 0\n"
   3737     "    for s in \"${DEFAULT_SRC_CONFIGURE_OPTION_ENABLES[@]}\"; do a+=($(option_enable \"$s\")); done\n"
   3738     "    for s in \"${DEFAULT_SRC_CONFIGURE_OPTION_WITHS[@]}\"; do a+=($(option_with \"$s\")); done\n"
   3739     "    for s in \"${DEFAULT_SRC_CONFIGURE_OPTIONS[@]}\"; do set -- $s; option \"$1\" && shift && a+=(\"$@\"); done\n"
   3740     "    for s in \"${DEFAULT_SRC_CONFIGURE_TESTS[@]}\"; do set -- $s; [[ -n $2 ]] && a+=(\"$2\"); done\n"
   3741     "    econf \"${DEFAULT_SRC_CONFIGURE_PARAMS[@]}\" \"${a[@]}\"\n"
   3742     "}\n"
   3743     "default_src_compile() { [[ -f Makefile || -f GNUmakefile || -f makefile ]] && emake \"${DEFAULT_SRC_COMPILE_PARAMS[@]}\"; return 0; }\n"
   3744     "default_src_install() {\n"
   3745     "    if [[ -f Makefile || -f GNUmakefile || -f makefile ]]; then emake -j1 DESTDIR=\"$IMAGE\" \"${DEFAULT_SRC_INSTALL_PARAMS[@]}\" install; fi\n"
   3746     "    emagicdocs\n"
   3747     "}\n"
   3748     "for p in pkg_setup src_unpack src_prepare src_configure src_compile src_install; do eval \"$p() { default_$p \\\"\\$@\\\"; }\"; done\n"
   3749     "default() { default_$PHASE \"$@\"; }\n"
   3750     "\n"
   3751     "PKGDIR=$(dirname \"$MAG_FILE\")\n"
   3752     "CATEGORY=$(basename \"$(dirname \"$PKGDIR\")\")\n"
   3753     "PN=$(basename \"$PKGDIR\")\n"
   3754     "f=$(basename \"$MAG_FILE\" .exheres-0)\n"
   3755     "PVR=${f#$PN-} PV=${PVR%-r+([0-9])} PR=r0\n"
   3756     "[[ $PVR == *-r+([0-9]) ]] && PR=${PVR##*-}\n"
   3757     "PNV=$PN-$PV PNVR=$PN-$PVR\n"
   3758     "FILES=$PKGDIR/files WORKBASE=$MAG_WORK/work WORK=$WORKBASE/$PNV IMAGE=$MAG_DEST TEMP=$MAG_WORK/temp FETCHEDDIR=$MAG_SRC/$PN ROOT=/\n"
   3759     "export PN PV PR PVR PNV PNVR CATEGORY FILES WORKBASE IMAGE TEMP FETCHEDDIR ROOT CHOST\n"
   3760     "mkdir -p \"$WORKBASE\" \"$TEMP\" \"$IMAGE\"\n"
   3761     "mkdir -p \"$TEMP/bin\"\n"
   3762     "for t in cc c++ cpp gcc g++ ar as ld nm strip objcopy objdump readelf ranlib pkg-config; do\n"
   3763     "    command -v $t >/dev/null && ln -sf \"$(command -v $t)\" \"$TEMP/bin/$CHOST-$t\"\n"
   3764     "done\n"
   3765     "PATH=$TEMP/bin:$PATH\n"
   3766     "source \"$MAG_FILE\"\n"
   3767     "\n"
   3768     "ex_downloads() {\n"
   3769     "    local skip=0 w out=() d=() mirrors\n"
   3770     "    set -- $DOWNLOADS\n"
   3771     "    while [[ $# -gt 0 ]]; do\n"
   3772     "        w=$1; shift\n"
   3773     "        case $w in\n"
   3774     "        *'?') if option \"${w%\\?}\"; then d+=(0); else d+=(1); fi; shift ;;\n"
   3775     "        '(') d+=(0) ;;\n"
   3776     "        ')') unset 'd[${#d[@]}-1]' ;;\n"
   3777     "        '->') [[ \" ${d[*]} \" == *' 1 '* ]] || out[${#out[@]}-1]=\"${out[${#out[@]}-1]} $1\"; shift ;;\n"
   3778     "        *) [[ \" ${d[*]} \" == *' 1 '* ]] || out+=(\"$w\") ;;\n"
   3779     "        esac\n"
   3780     "    done\n"
   3781     "    for w in \"${out[@]}\"; do\n"
   3782     "        set -- $w\n"
   3783     "        local u=$1 n=${2:-${1##*/}}\n"
   3784     "        if [[ $u == mirror://* ]]; then\n"
   3785     "            local m=${u#mirror://} rest\n"
   3786     "            rest=${m#*/} m=${m%%/*}\n"
   3787     "            u=$(awk -v m=\"$m\" '$1 == m { print $2; exit }' \"$MAG_TREE/metadata/mirrors.conf\")${rest}\n"
   3788     "        fi\n"
   3789     "        printf '%s\\t%s/%s\\t\\n' \"$u\" \"$PN\" \"$n\"\n"
   3790     "    done\n"
   3791     "}\n"
   3792     "if [[ $MAG_STEP == list ]]; then ex_downloads > \"$MAG_OUT\"; exit 0; fi\n"
   3793     "A=$(ex_downloads | cut -f2 | sed 's|.*/||' | tr '\\n' ' ')\n"
   3794     "[ -f /etc/mag/build.conf ] && . /etc/mag/build.conf\n"
   3795     "export CFLAGS=\"${CFLAGS:--O2 -pipe}\" CXXFLAGS=\"${CXXFLAGS:-${CFLAGS:--O2 -pipe}}\" LDFLAGS JOBS=${MAKEFLAGS#-j}\n"
   3796     "JOBS=${JOBS:-$(nproc)}\n"
   3797     "export CC=cc CXX=c++ CPP=cpp LD=ld AR=ar AS=as RANLIB=ranlib STRIP=strip NM=nm PKG_CONFIG=pkg-config\n"
   3798     "for PHASE in pkg_setup src_unpack src_prepare src_configure src_compile src_install; do\n"
   3799     "    if [[ $PHASE == src_unpack ]]; then cd \"$WORKBASE\"; else cd \"$WORK\" 2>/dev/null || cd \"$WORKBASE\"; fi\n"
   3800     "    echo \"==> $PHASE\"\n"
   3801     "    $PHASE\n"
   3802     "done\n"
   3803     "cd \"$IMAGE\" || exit 1\n"
   3804     "if [[ -d usr/$CHOST ]]; then\n"
   3805     "    cp -a \"usr/$CHOST/.\" usr/\n"
   3806     "    rm -rf \"usr/$CHOST\"\n"
   3807     "    grep -rlI \"/$CHOST\" usr/lib usr/share 2>/dev/null | while read -r f; do sed -i -e \"s|/usr/$CHOST|/usr|g\" -e \"s|}/$CHOST|}|g\" \"$f\"; done\n"
   3808     "fi\n"
   3809     "find . -name '*.la' -delete\n"
   3810     "rm -f usr/share/info/dir\n"
   3811     "if command -v strip >/dev/null; then\n"
   3812     "    find . -type f \\( -perm -100 -o -name '*.so' -o -name '*.so.*' \\) -exec strip --strip-unneeded {} + 2>/dev/null || :\n"
   3813     "fi\n"
   3814     "find . -depth -type d -empty -delete\n";
   3815 
   3816 
   3817 /* what xbps-src or paludis would do: the sources, checked against the checksums Void has (Exherbo has none), then the
   3818  * phases, with the helpers of the tree */
   3819 static void build_tree(const struct pkg *p, const char *stage)
   3820 {
   3821     int k = kinds[p->repo], told = 0;
   3822     char *dir = tree_dir(p->repo), *tree = fmt("%s/tree", dir), *work = fmt("%s/var/tmp/mag/build/%s", root, p->name);
   3823     char *cache = fmt("%s/var/cache/mag/src", root), *list = fmt("%s/sources", work), *file = fmt("%s/%s", tree, p->csum ? p->csum : "");
   3824     const char *sh = k == VOID ? void_sh : exherbo_sh;
   3825     const char *vars[] = { "MAG_TREE", "MAG_PORT", "MAG_FILE", "MAG_ARCH", "MAG_WORK", "MAG_DEST", "MAG_SRC", "MAG_OUT", "MAG_STEP" };
   3826     char *t, *line, *next;
   3827     struct list files = { 0 }, dirs = { 0 };
   3828     int i;
   3829     printf("==> building %s %s\n", p->name, p->ver);
   3830     rmtree(work);
   3831     rmtree(stage);
   3832     mkpath(work, 0755);
   3833     mkpath(stage, 0755);
   3834     mkpath(cache, 0755);
   3835     setenv("MAG_TREE", in_root(tree), 1);
   3836     setenv("MAG_PORT", p->name, 1);
   3837     setenv("MAG_FILE", in_root(file), 1);
   3838     setenv("MAG_ARCH", arch, 1);
   3839     setenv("MAG_WORK", in_root(work), 1);
   3840     setenv("MAG_DEST", in_root(stage), 1);
   3841     setenv("MAG_SRC", in_root(cache), 1);
   3842     setenv("MAG_OUT", in_root(list), 1);
   3843     setenv("MAG_STEP", "list", 1);
   3844     if (shell(sh)) die("%s: cannot read what it is built from", p->name);
   3845     unsetenv("MAG_STEP");
   3846     t = slurp(list, NULL);
   3847     for (line = t; line && *line; line = next) {
   3848         char *rel, *sum, *c, *f, *have, *base;
   3849         next = strchr(line, '\n');
   3850         if (next) *next++ = 0;
   3851         if (!(rel = strchr(line, '\t'))) continue;
   3852         *rel++ = 0;
   3853         if ((sum = strchr(rel, '\t'))) *sum++ = 0; else sum = "";
   3854         c = clean(rel);
   3855         if (!c || strcmp(c, rel) || strpbrk(rel, "'\\")) die("%s: a source with a bad name, %s", p->name, rel);
   3856         free(c);
   3857         base = strrchr(rel, '/') ? strrchr(rel, '/') + 1 : rel;
   3858         if (*sum == '@') die("%s: the checksum of %s is of what is in it, which mag cannot check", p->name, base);
   3859         f = fmt("%s/%s", cache, rel);
   3860         have = exists(f) ? sha256_file(f) : NULL;
   3861         if (!have || (*sum && strcmp(have, sum))) {
   3862             printf("==> fetching %s\n", line);
   3863             free(have);
   3864             mkparent(f);
   3865             if (download(line, f)) die("could not fetch %s", line);
   3866             have = sha256_file(f);
   3867         }
   3868         if (*sum && (!have || strcmp(have, sum))) { unlink(f); die("%s: %s does not match the checksum in its template", p->name, base); }
   3869         if (!*sum && !told++) printf("==> Exherbo has no checksums: the sources of %s are as good as the connection they came over\n", p->name);
   3870         free(f); free(have);
   3871     }
   3872     free(t);
   3873     if (shell(sh)) die("%s did not build, what it left is in %s", p->name, work);
   3874     for (i = 0; i < 9; i++) unsetenv(vars[i]);
   3875     walk(stage, "", &files, &dirs);
   3876     if (!files.n) die("%s built nothing", p->name);
   3877     list_free(&files); list_free(&dirs);
   3878     rmtree(work);
   3879     free(dir); free(tree); free(work); free(cache); free(list); free(file);
   3880 }
   3881 
   3882 /* ---- pacman repos (Artix, Arch): the database read into mag's index, packages checked against it and their signature ---- */
   3883 
   3884 static int unpack_any(struct in *r, outfn *out, void *ctx)
   3885 {
   3886     int c = in_byte(r);
   3887     if (c < 0) return -1;
   3888     r->pos--;
   3889     return c == 0x1f ? gunzip(r, out, ctx) : c == 0x28 ? unzstd(r, out, ctx) : -1;
   3890 }
   3891 
   3892 /* the database's name: .../system/os is system.db */
   3893 static char *pac_name(int i)
   3894 {
   3895     char *u = xstrdup(repo_urls.v[i]), *s = strrchr(u, '/'), *n;
   3896     if (s && !strcmp(s + 1, "os")) { *s = 0; s = strrchr(u, '/'); }
   3897     n = xstrdup(s ? s + 1 : u);
   3898     free(u);
   3899     return n;
   3900 }
   3901 
   3902 static void field(struct buf *b, int k, const char *v)
   3903 {
   3904     char h[2] = { k, ':' };
   3905     if (!v || !*v) return;
   3906     buf_add(b, h, 2); buf_add(b, v, strlen(v)); buf_add(b, "\n", 1);
   3907 }
   3908 
   3909 static void pac_entry(struct buf *b, char *t)
   3910 {
   3911     static const char *const keys[] = { "%NAME%", "%VERSION%", "%DESC%", "%FILENAME%", "%SHA256SUM%", "%PGPSIG%", "%CSIZE%", "%BASE%", "%ISIZE%" };
   3912     char *line, *next, *key = "", *v[9] = { 0 };
   3913     struct buf deps = { 0 }, prov = { 0 };
   3914     int k;
   3915     for (line = t; line; line = next) {
   3916         next = strchr(line, '\n');
   3917         if (next) *next++ = 0;
   3918         if (*line == '%') { key = line; continue; }
   3919         if (!*line) continue;
   3920         for (k = 0; k < 9 && strcmp(key, keys[k]); k++) {}
   3921         if (k < 9) { if (!v[k]) v[k] = line; }
   3922         else if (!strcmp(key, "%DEPENDS%")) { buf_add(&deps, " ", 1); buf_add(&deps, line, strlen(line)); }
   3923         else if (!strcmp(key, "%CONFLICTS%")) { buf_add(&deps, " !", 2); buf_add(&deps, line, strlen(line)); }
   3924         else if (!strcmp(key, "%PROVIDES%")) { buf_add(&prov, " ", 1); buf_add(&prov, line, strlen(line)); }
   3925     }
   3926     if (v[0] && v[1] && v[3] && v[4]) {
   3927         field(b, 'P', v[0]); field(b, 'V', v[1]); field(b, 'T', v[2]); field(b, 'F', v[3]); field(b, 'C', v[4]);
   3928         field(b, 'G', v[5]); field(b, 'S', v[6]); field(b, 'B', v[7]); field(b, 'I', v[8]);
   3929         if (deps.n) field(b, 'D', (char *)deps.p + 1);
   3930         if (prov.n) field(b, 'p', (char *)prov.p + 1);
   3931         buf_add(b, "\n", 1);
   3932     }
   3933     free(deps.p); free(prov.p);
   3934 }
   3935 
   3936 static int sync_pacman(int i)
   3937 {
   3938     char *name = pac_name(i), *base = pac_base(i), *url = fmt("%s/%s.db", base, name), *d = tree_dir(i), *db = fmt("%s/%s.db", d, name), *ix = fmt("%s/INDEX", d), *tmp = fmt("%s.new", ix);
   3939     struct in *r = xmalloc(sizeof *r);
   3940     struct tar t;
   3941     struct buf b = { 0 };
   3942     int fd = -1, bad = 1, j;
   3943     memset(&t, 0, sizeof t);
   3944     printf("==> %s\n", url);
   3945     mkpath(d, 0755);
   3946     if (download(url, db)) say("could not fetch %s", url);
   3947     else if ((fd = open(db, O_RDONLY)) >= 0) {
   3948         in_open(r, fd, 0);
   3949         if (unpack_any(r, tar_out, &t) || t.bad) say("%s is broken", url);
   3950         else {
   3951             for (j = 0; j < t.nents; j++) {
   3952                 size_t l = strlen(t.ents[j].name);
   3953                 if (l > 5 && !strcmp(t.ents[j].name + l - 5, "/desc") && t.ents[j].data.p) pac_entry(&b, (char *)t.ents[j].data.p);
   3954             }
   3955             db_put_file(tmp, b.n ? (char *)b.p : "");
   3956             bad = rename(tmp, ix) < 0;
   3957         }
   3958         close(fd);
   3959     }
   3960     tar_free(&t);
   3961     free(r); free(b.p); free(name); free(base); free(url); free(d); free(db); free(ix); free(tmp);
   3962     return bad;
   3963 }
   3964 
   3965 static void ent_add(struct tar *t, char *name, char *data)
   3966 {
   3967     t->ents = xrealloc(t->ents, (t->nents + 1) * sizeof *t->ents);
   3968     t->ents[t->nents].name = name;
   3969     memset(&t->ents[t->nents].data, 0, sizeof t->ents[t->nents].data);
   3970     buf_add(&t->ents[t->nents].data, data, strlen(data));
   3971     t->nents++;
   3972     free(data);
   3973 }
   3974 
   3975 /* checked against the index and its signature, unpacked into stage; .INSTALL's functions become mag's scripts */
   3976 static int pac_extract(const char *name, const char *file, const char *stage, struct tar *ctl);
   3977 
   3978 static int pac_unpack(const struct pkg *p, const char *file, const char *stage, struct tar *ctl)
   3979 {
   3980     unsigned char *sig;
   3981     char *sum = sha256_file(file);
   3982     size_t n;
   3983     int v;
   3984     if (!sum || !p->csum || strcmp(sum, p->csum)) { say("%s: the package does not match the index", p->name); free(sum); return -1; }
   3985     free(sum);
   3986     if (p->sig) {
   3987         sig = xmalloc(strlen(p->sig) + 4);
   3988         n = unbase64(p->sig, sig);
   3989     } else {
   3990         /* the database left it out: the .sig next to the package */
   3991         char *base = pac_base(p->repo), *url = fmt("%s/%s.sig", base, p->file), *sf = fmt("%s.sig", file);
   3992         if (!exists(sf) && download(url, sf)) { say("%s is not signed", p->name); free(base); free(url); free(sf); return -1; }
   3993         sig = (unsigned char *)slurp(sf, &n);
   3994         free(base); free(url); free(sf);
   3995         if (!sig) return -1;
   3996     }
   3997     v = pgp_verify(file, sig, n);
   3998     free(sig);
   3999     if (v > 0) { say("%s is signed by a key mag does not have", p->name); return -1; }
   4000     if (v) { say("%s: the signature does not match", p->name); return -1; }
   4001     return pac_extract(p->name, file, stage, ctl);
   4002 }
   4003 
   4004 static int pac_extract(const char *name, const char *file, const char *stage, struct tar *ctl)
   4005 {
   4006     static const char *const fn[][2] = { { "pre-install", "pre_install" }, { "post-install", "post_install" }, { "pre-upgrade", "pre_upgrade" },
   4007         { "post-upgrade", "post_upgrade" }, { "pre-deinstall", "pre_remove" }, { "post-deinstall", "post_remove" } };
   4008     static const char *const meta[] = { ".PKGINFO", ".MTREE", ".BUILDINFO", ".INSTALL", ".CHANGELOG" };
   4009     struct in *r;
   4010     struct tar t;
   4011     char *f, *inst;
   4012     int fd, ok = -1, i;
   4013     memset(ctl, 0, sizeof *ctl);
   4014     if ((fd = open(file, O_RDONLY)) < 0) return -1;
   4015     r = xmalloc(sizeof *r);
   4016     memset(&t, 0, sizeof t);
   4017     rmtree(stage);
   4018     mkpath(stage, 0755);
   4019     t.dir = stage;
   4020     in_open(r, fd, 0);
   4021     do if (unpack_any(r, tar_out, &t) || t.bad) { say("%s: cannot unpack it", name); goto out; } while (!in_eof(r));
   4022     f = fmt("%s/.INSTALL", stage);
   4023     if ((inst = slurp(f, NULL)))
   4024         for (i = 0; i < 6; i++) ent_add(ctl, fmt(".%s", fn[i][0]), fmt("#!/bin/bash\n%s\ndeclare -F %s >/dev/null || exit 0\n%s \"$@\"\n", inst, fn[i][1], fn[i][1]));
   4025     free(inst); free(f);
   4026     for (i = 0; i < 5; i++) { f = fmt("%s/%s", stage, meta[i]); unlink(f); free(f); }
   4027     ok = 0;
   4028 out:
   4029     tar_free(&t);
   4030     free(r);
   4031     close(fd);
   4032     return ok;
   4033 }
   4034 
   4035 static long id_of(const char *file, const char *name);
   4036 
   4037 /* ---- the AUR: its metadata dump is the index, a PKGBUILD is built with makepkg as nobody ---- */
   4038 
   4039 static void to_buf(void *ctx, const unsigned char *p, size_t n) { buf_add(ctx, p, n); }
   4040 
   4041 /* a JSON string at s (on its quote) into o, without newlines; returns what follows it */
   4042 static const char *js_str(const char *s, struct buf *o)
   4043 {
   4044     o->n = 0;
   4045     buf_add(o, "", 0);
   4046     for (s++; *s && *s != '"'; s++) {
   4047         char c = *s;
   4048         if (c == '\\' && s[1]) {
   4049             c = *++s;
   4050             if (c == 'u' && isxdigit(s[1]) && isxdigit(s[2]) && isxdigit(s[3]) && isxdigit(s[4])) {
   4051                 char h[5] = { s[1], s[2], s[3], s[4], 0 }, u[3];
   4052                 unsigned v = strtoul(h, NULL, 16);
   4053                 s += 4;
   4054                 if (v < 0x80) { c = v < 0x20 ? ' ' : v; buf_add(o, &c, 1); }
   4055                 else if (v < 0x800) { u[0] = 0xc0 | v >> 6; u[1] = 0x80 | (v & 63); buf_add(o, u, 2); }
   4056                 else if (v < 0xd800 || v > 0xdfff) { u[0] = 0xe0 | v >> 12; u[1] = 0x80 | (v >> 6 & 63); u[2] = 0x80 | (v & 63); buf_add(o, u, 3); }
   4057                 continue;
   4058             }
   4059             if (c == 'n' || c == 't' || c == 'r' || c == 'b' || c == 'f') c = ' ';
   4060         }
   4061         if (c == '\n' || c == '\r') c = ' ';
   4062         buf_add(o, &c, 1);
   4063     }
   4064     return *s ? s + 1 : s;
   4065 }
   4066 
   4067 static const char *js_ws(const char *s) { while (*s == ' ' || *s == '\n' || *s == '\r' || *s == '\t' || *s == ',') s++; return s; }
   4068 
   4069 static int sync_aur(int i)
   4070 {
   4071     char *url = fmt("%s/packages-meta-ext-v1.json.gz", repo_urls.v[i]), *d = tree_dir(i), *gz = fmt("%s/meta.json.gz", d), *ix = fmt("%s/INDEX", d), *tmp = fmt("%s.new", ix);
   4072     struct in *r = xmalloc(sizeof *r);
   4073     struct buf js = { 0 }, out = { 0 }, key = { 0 }, val = { 0 }, f[4] = { { 0 } }, l[3] = { { 0 } };
   4074     int fd = -1, bad = 1, k;
   4075     printf("==> %s\n", url);
   4076     mkpath(d, 0755);
   4077     if (download(url, gz)) say("could not fetch %s", url);
   4078     else if ((fd = open(gz, O_RDONLY)) >= 0) {
   4079         const char *s;
   4080         in_open(r, fd, 0);
   4081         if (gunzip(r, to_buf, &js) || !js.p) { say("%s is broken", url); goto out; }
   4082         s = js_ws((char *)js.p);
   4083         if (*s++ != '[') { say("%s is not the list it should be", url); goto out; }
   4084         for (;;) {
   4085             s = js_ws(s);
   4086             if (*s != '{') break;
   4087             for (k = 0; k < 4; k++) { f[k].n = 0; buf_add(&f[k], "", 0); }
   4088             for (k = 0; k < 3; k++) { l[k].n = 0; buf_add(&l[k], "", 0); }
   4089             for (s++;;) {
   4090                 const char *kn;
   4091                 int which = -1, list = -1, neg = 0;
   4092                 s = js_ws(s);
   4093                 if (*s == '}') { s++; break; }
   4094                 if (*s != '"') goto out;
   4095                 s = js_ws(js_str(s, &key));
   4096                 if (*s++ != ':') goto out;
   4097                 s = js_ws(s);
   4098                 kn = (char *)key.p;
   4099                 which = !strcmp(kn, "Name") ? 0 : !strcmp(kn, "Version") ? 1 : !strcmp(kn, "Description") ? 2 : !strcmp(kn, "PackageBase") ? 3 : -1;
   4100                 list = !strcmp(kn, "Depends") ? 0 : !strcmp(kn, "Conflicts") ? (neg = 1, 0) : !strcmp(kn, "MakeDepends") || !strcmp(kn, "CheckDepends") ? 1 : !strcmp(kn, "Provides") ? 2 : -1;
   4101                 if (*s == '"') {
   4102                     s = js_str(s, &val);
   4103                     if (which >= 0) { f[which].n = 0; buf_add(&f[which], val.p, val.n); }
   4104                 } else if (*s == '[') {
   4105                     for (s++;;) {
   4106                         s = js_ws(s);
   4107                         if (*s == ']') { s++; break; }
   4108                         if (*s != '"') goto out;
   4109                         s = js_str(s, &val);
   4110                         if (list >= 0 && val.n && !strchr((char *)val.p, ' ')) {
   4111                             if (l[list].n) buf_add(&l[list], " ", 1);
   4112                             if (neg) buf_add(&l[list], "!", 1);
   4113                             buf_add(&l[list], val.p, val.n);
   4114                         }
   4115                     }
   4116                 } else while (*s && *s != ',' && *s != '}') s++;
   4117             }
   4118             if (f[0].n && f[1].n) {
   4119                 field(&out, 'P', (char *)f[0].p); field(&out, 'V', (char *)f[1].p); field(&out, 'T', (char *)f[2].p);
   4120                 field(&out, 'B', (char *)f[3].p); field(&out, 'D', (char *)l[0].p); field(&out, 'M', (char *)l[1].p); field(&out, 'p', (char *)l[2].p);
   4121                 buf_add(&out, "\n", 1);
   4122             }
   4123         }
   4124         db_put_file(tmp, out.n ? (char *)out.p : "");
   4125         bad = rename(tmp, ix) < 0;
   4126     }
   4127 out:
   4128     if (fd >= 0) close(fd);
   4129     free(r); free(js.p); free(out.p); free(key.p); free(val.p);
   4130     for (k = 0; k < 4; k++) free(f[k].p);
   4131     for (k = 0; k < 3; k++) free(l[k].p);
   4132     free(url); free(d); free(gz); free(ix); free(tmp);
   4133     return bad;
   4134 }
   4135 
   4136 /* the snapshot of the package base, built by makepkg as nobody inside the root; the package it made goes into stage */
   4137 static void build_aur(const struct pkg *p, const char *stage, struct tar *ctl)
   4138 {
   4139     const char *base = p->base ? p->base : p->name;
   4140     char *top = fmt("%s/var/cache/mag/aur", root), *dir = fmt("%s/%s", top, base), *tgz = fmt("%s/%s.tar.gz", top, base),
   4141         *url = fmt("%s/cgit/aur.git/snapshot/%s.tar.gz", repo_urls.v[p->repo], base), *in = fmt("/var/cache/mag/aur/%s", base), *outd, *built = NULL, *sh;
   4142     struct list files = { 0 }, dirs = { 0 };
   4143     struct in *r = xmalloc(sizeof *r);
   4144     struct tar t;
   4145     long uid = id_of("passwd", "nobody"), gid = id_of("group", "nobody");
   4146     int fd, i;
   4147     DIR *od;
   4148     struct dirent *e;
   4149     char *av[] = { "/usr/bin/setpriv", "--reuid=nobody", "--regid=nobody", "--clear-groups", "/bin/bash", "-c", NULL, NULL };
   4150     if (uid < 0 || gid < 0) die("%s: there is no nobody here to build as", p->name);
   4151     rmtree(dir);
   4152     mkpath(top, 0755);
   4153     printf("==> %s\n", url);
   4154     if (download(url, tgz)) die("could not fetch %s", url);
   4155     memset(&t, 0, sizeof t);
   4156     t.dir = top;
   4157     if ((fd = open(tgz, O_RDONLY)) < 0) die("cannot read %s", tgz);
   4158     in_open(r, fd, 0);
   4159     if (gunzip(r, tar_out, &t) || t.bad) die("%s: the snapshot is broken", p->name);
   4160     close(fd);
   4161     tar_free(&t);
   4162     free(r);
   4163     unlink(tgz);
   4164     walk(dir, "", &files, &dirs);
   4165     lchown(dir, uid, gid);
   4166     for (i = 0; i < files.n; i++) { char *f = fmt("%s/%s", dir, files.v[i]); lchown(f, uid, gid); free(f); }
   4167     for (i = 0; i < dirs.n; i++) { char *f = fmt("%s/%s", dir, dirs.v[i]); lchown(f, uid, gid); free(f); }
   4168     list_free(&files); list_free(&dirs);
   4169     printf("==> building %s from the AUR in %s\n", p->name, in);
   4170     sh = fmt("cd '%s' && export HOME=$PWD BUILDDIR=$PWD/build PKGDEST=$PWD/out SRCDEST=$PWD/src GNUPGHOME=$PWD/.gnupg && mkdir -p out src .gnupg && chmod 700 .gnupg && "
   4171         "for k in $(sed -n 's/^[[:space:]]*validpgpkeys = //p' .SRCINFO); do gpg --batch -q --keyserver hkps://keyserver.ubuntu.com --recv-keys \"$k\" || :; done; "
   4172         "makepkg --nodeps --noconfirm --noprogressbar -f", in);
   4173     av[6] = sh;
   4174     if (run_in_root(av, NULL)) die("%s did not build; what makepkg left is in %s", p->name, in);
   4175     free(sh);
   4176     outd = fmt("%s/out", dir);
   4177     /* NAME-VERSION-RELEASE-ARCH.pkg.tar.*: the version can be newer than the index says, a -git one sets its own */
   4178     if ((od = opendir(outd))) {
   4179         while ((e = readdir(od)) && !built) {
   4180             char *n = xstrdup(e->d_name), *x = strstr(n, ".pkg.tar"), *c;
   4181             int dashes = 0;
   4182             if (x && !strstr(n, ".sig")) {
   4183                 for (*x = 0, c = x; c > n && dashes < 3; ) if (*--c == '-') dashes++;
   4184                 if (dashes == 3) { *c = 0; if (!strcmp(n, p->name)) built = fmt("%s/%s", outd, e->d_name); }
   4185             }
   4186             free(n);
   4187         }
   4188         closedir(od);
   4189     }
   4190     if (!built) die("%s: makepkg made no package called that", p->name);
   4191     if (pac_extract(p->name, built, stage, ctl)) die("%s: cannot unpack what makepkg made", p->name);
   4192     free(built); free(outd); free(top); free(dir); free(tgz); free(url); free(in);
   4193 }
   4194 
   4195 /* ---- installing a package ---- */
   4196 
   4197 static char *pkg_file(const struct pkg *p)
   4198 {
   4199     if (kinds[p->repo] == PACMAN) return fmt("%s/var/cache/mag/pkg/%s", root, p->file);
   4200     return fmt("%s/var/cache/mag/pkg/%s-%s.apk", root, p->name, p->ver);
   4201 }
   4202 
   4203 /* the control part is checked against the index, the files against the control part, then they go into stage */
   4204 static int unpack(const struct pkg *p, const char *file, const char *stage, struct tar *ctl)
   4205 {
   4206     int fd = open(file, O_RDONLY), ok = -1, n;
   4207     struct in *r = xmalloc(sizeof *r);
   4208     struct tar t;
   4209     off_t at, data;
   4210     unsigned char dig[32], want[64];
   4211     char *datahash = NULL, *s;
   4212     struct ent *info;
   4213     memset(&t, 0, sizeof t);
   4214     memset(ctl, 0, sizeof *ctl);
   4215     if (fd < 0) goto out;
   4216     in_open(r, fd, 0);
   4217     if (gunzip(r, tar_out, &t)) goto out;
   4218     tar_free(&t);
   4219     at = in_tell(r);
   4220     if (gunzip(r, tar_out, ctl)) goto out;
   4221     data = in_tell(r);
   4222     if (!p->csum || strlen(p->csum) < 3 || p->csum[0] != 'Q' || (p->csum[1] != '1' && p->csum[1] != '2')) { say("%s has no checksum in the index", p->name); goto out; }
   4223     n = hash_range(fd, at, data, p->csum[1] == '1', dig);
   4224     if ((int)unbase64(p->csum + 2, want) != n || memcmp(dig, want, n)) { say("%s: the package does not match the index", p->name); goto out; }
   4225     if (!(info = tar_find(ctl, ".PKGINFO"))) { say("%s has no .PKGINFO", p->name); goto out; }
   4226     s = (char *)info->data.p;
   4227     if (strncmp(s, "datahash = ", 11)) s = strstr(s, "\ndatahash = ") ? strstr(s, "\ndatahash = ") + 1 : NULL;
   4228     if (s) { s += 11; datahash = xstrndup(s, strcspn(s, "\n")); }
   4229     if (!datahash) { say("%s has no datahash", p->name); goto out; }
   4230     hash_range(fd, data, -1, 0, dig);
   4231     s = hex(dig, 32);
   4232     n = strcmp(s, datahash);
   4233     free(s);
   4234     if (n) { say("%s: the files do not match the package's own hash", p->name); goto out; }
   4235     rmtree(stage);
   4236     mkpath(stage, 0755);
   4237     t.dir = stage;
   4238     in_open(r, fd, data);
   4239     do {
   4240         if (gunzip(r, tar_out, &t) || t.bad) { say("%s: cannot unpack it", p->name); tar_free(&t); goto out; }
   4241     } while (!in_eof(r));
   4242     tar_free(&t);
   4243     ok = 0;
   4244 out:
   4245     free(datahash);
   4246     free(r);
   4247     if (fd >= 0) close(fd);
   4248     return ok;
   4249 }
   4250 
   4251 static char *pkginfo(struct tar *ctl, const char *key)
   4252 {
   4253     struct ent *e = tar_find(ctl, ".PKGINFO");
   4254     char *s, *want = fmt("\n%s = ", key), *v = NULL;
   4255     if (e && (s = strstr((char *)e->data.p, want))) { s += strlen(want); v = xstrndup(s, strcspn(s, "\n")); }
   4256     free(want);
   4257     return v;
   4258 }
   4259 
   4260 static struct list changed_dirs;
   4261 
   4262 static void fetch_pkg(const struct pkg *p, const char *file)
   4263 {
   4264     char *base = pac_base(p->repo), *url = kinds[p->repo] == PACMAN ? fmt("%s/%s", base, p->file) : fmt("%s/%s-%s.apk", base, p->name, p->ver);
   4265     printf("==> fetching %s\n", url);
   4266     if (download(url, file)) die("could not fetch %s", url);
   4267     free(base); free(url);
   4268 }
   4269 
   4270 /* is the file at full still what the package put there, by the sums mag kept of its /etc files */
   4271 static int etc_untouched(const struct list *sums, const char *rel, const char *full)
   4272 {
   4273     int i, same = 0;
   4274     char *sum;
   4275     for (i = 0; i < sums->n; i++) {
   4276         const char *sp = strchr(sums->v[i], ' ');
   4277         if (!sp || strcmp(sp + 1, rel)) continue;
   4278         if ((sum = sha256_file(full))) { same = !strncmp(sums->v[i], sum, sp - sums->v[i]); free(sum); }
   4279         break;
   4280     }
   4281     return same;
   4282 }
   4283 
   4284 /* the id of NAME in the root's passwd or group file, or -1 */
   4285 static long id_of(const char *file, const char *name)
   4286 {
   4287     char *f = fmt("%s/etc/%s", root, file), *t = slurp(f, NULL), *line, *next;
   4288     long id = -1;
   4289     size_t n = strlen(name);
   4290     for (line = t; line && *line && id < 0; line = next) {
   4291         next = strchr(line, '\n');
   4292         if (next) *next++ = 0;
   4293         if (!strncmp(line, name, n) && line[n] == ':') {
   4294             char *c = strchr(line + n + 1, ':');
   4295             if (c) id = strtol(c + 1, NULL, 10);
   4296         }
   4297     }
   4298     free(t); free(f);
   4299     return id;
   4300 }
   4301 
   4302 /* the owner a file of the package gets here: by the names in the package, once its pre-install made the users */
   4303 static int owner_here(const char *rel, struct stat *st)
   4304 {
   4305     int i;
   4306     size_t n = strlen(rel);
   4307     for (i = 0; i < named.n; i++) {
   4308         char *u, *g;
   4309         long id;
   4310         if (strncmp(named.v[i], rel, n) || named.v[i][n] != '\t') continue;
   4311         u = named.v[i] + n + 1;
   4312         g = strchr(u, '\t');
   4313         if (!g) return 0;
   4314         *g = 0;
   4315         if ((id = !strcmp(u, "root") ? 0 : id_of("passwd", u)) >= 0) st->st_uid = id;
   4316         *g = '\t';
   4317         if ((id = !strcmp(g + 1, "root") ? 0 : id_of("group", g + 1)) >= 0) st->st_gid = id;
   4318         return 1;
   4319     }
   4320     return 0;
   4321 }
   4322 
   4323 /* apk: two packages giving the same versioned name (cmd:ld.lld=..) can't both be there, the new one replaces the old, as lld23 does lld22 */
   4324 static int replaces(const struct pkg *p, const char *other)
   4325 {
   4326     char *t = db_get(other, "provides");
   4327     struct list a = words(p->prov ? p->prov : ""), b = words(t ? t : "");
   4328     int i, j, hit = 0;
   4329     for (i = 0; i < a.n && !hit; i++) {
   4330         size_t n = strcspn(a.v[i], "=");
   4331         if (!a.v[i][n]) continue;
   4332         for (j = 0; j < b.n && !hit; j++) hit = !strncmp(a.v[i], b.v[j], n + 1);
   4333     }
   4334     list_free(&a); list_free(&b); free(t);
   4335     return hit;
   4336 }
   4337 
   4338 static void install_one(struct pkg *p, int explicit, const struct list *planned)
   4339 {
   4340     static const char *const scripts[] = { "pre-install", "post-install", "pre-upgrade", "post-upgrade", "pre-deinstall", "post-deinstall", "trigger" };
   4341     char *file = pkg_file(p), *stage = fmt("%s/var/tmp/mag/%s", root, p->name), *oldver = db_get(p->name, "version"), *trig;
   4342     struct list files = { 0 }, dirs = { 0 }, old, gone = { 0 }, deps = { 0 }, w, v = { 0 }, pr = { 0 }, sums, newsums = { 0 }, takes = { 0 };
   4343     struct tar ctl;
   4344     int i, bad = 0, port = BUILT(kinds[p->repo]);
   4345     int (*un)(const struct pkg *, const char *, const char *, struct tar *) = kinds[p->repo] == PACMAN ? pac_unpack : unpack;
   4346     list_free(&named);
   4347     if (port) {
   4348         memset(&ctl, 0, sizeof ctl);
   4349         if (kinds[p->repo] == AUR) build_aur(p, stage, &ctl);
   4350         else if (kinds[p->repo] == CRUX) build_port(p, stage); else build_tree(p, stage);
   4351     } else {
   4352         if (!exists(file)) fetch_pkg(p, file);
   4353         if (un(p, file, stage, &ctl)) {
   4354             /* a download that came down wrong (a flaky link, a proxy) gets one clean retry before we give up;
   4355              * the detached pacman .sig is cached next to it, so drop that too or the stale one is reused */
   4356             char *sf = fmt("%s.sig", file);
   4357             unlink(file); unlink(sf);
   4358             fetch_pkg(p, file);
   4359             if (un(p, file, stage, &ctl)) { unlink(file); unlink(sf); die("not installing %s", p->name); }
   4360             free(sf);
   4361         }
   4362     }
   4363     walk(stage, "", &files, &dirs);
   4364     load_owners();
   4365     old = db_read(p->name, "files");
   4366     for (i = 0; i < files.n; i++) {
   4367         struct stat st;
   4368         const char *o = owner_of(files.v[i]);
   4369         char *full = fmt("%s/%s", root, files.v[i]);
   4370         /* a package upgraded in the same run may be letting go of the file, as chamesle-base did of /sbin/service */
   4371         if (o && strcmp(o, p->name) && !has(planned, o) && (has(&takes, o) || (kinds[p->repo] == APK && replaces(p, o)))) { if (!has(&takes, o)) push(&takes, xstrdup(o)); }
   4372         else if (o && strcmp(o, p->name) && !has(planned, o)) { if (bad < 5) say("%s wants /%s, which %s has", p->name, files.v[i], o); bad++; }
   4373         else if (!o && exists(full) && strncmp(files.v[i], "etc/", 4) && !(lstat(full, &st) == 0 && S_ISLNK(st.st_mode))) {
   4374             char *from = fmt("%s/%s", stage, files.v[i]);
   4375             if (!same_file(from, full)) { if (bad < 5) say("%s wants /%s, which is there already and is different", p->name, files.v[i]); bad++; }
   4376             free(from);
   4377         }
   4378         free(full);
   4379     }
   4380     if (bad > 5) say("and %d more", bad - 5);
   4381     if (bad && !force) die("not installing %s, %d files are in the way, -f writes over them", p->name, bad);
   4382     bad = 0;
   4383 
   4384     for (i = 0; i < 7; i++) {
   4385         char *n = fmt(".%s", scripts[i]);
   4386         struct ent *e = tar_find(&ctl, n);
   4387         if (e) db_put(p->name, scripts[i], (char *)e->data.p, e->data.n, 0755);
   4388         else { char *d = dbdir(p->name), *f = fmt("%s/%s", d, scripts[i]); unlink(f); free(d); free(f); }
   4389         free(n);
   4390     }
   4391     for (i = 0; port && i < 2; i++) {
   4392         char *d = tree_dir(p->repo), *f = fmt("%s/%s/%s", d, p->name, scripts[i]), *t;
   4393         size_t n;
   4394         if ((t = slurp(f, &n))) db_put(p->name, scripts[i], t, n, 0755);
   4395         free(d); free(f); free(t);
   4396     }
   4397     if (oldver) script_or_later(p->name, "pre-upgrade", p->ver, oldver);
   4398     else script_or_later(p->name, "pre-install", p->ver, NULL);
   4399 
   4400     sums = db_read(p->name, "etcsums");
   4401     for (i = 0; i < dirs.n; i++) {
   4402         char *from = fmt("%s/%s", stage, dirs.v[i]), *to = fmt("%s/%s", root, dirs.v[i]);
   4403         struct stat st;
   4404         if (lstat(from, &st)) { free(from); free(to); continue; }
   4405         if (!exists(to)) {
   4406             owner_here(dirs.v[i], &st);
   4407             mkpath(to, 0755);
   4408             chmod(to, st.st_mode & 07777);
   4409             if (!geteuid()) lchown(to, st.st_uid, st.st_gid);
   4410         } else if (owner_here(dirs.v[i], &st) && !geteuid()) lchown(to, st.st_uid, st.st_gid);
   4411         free(from); free(to);
   4412     }
   4413     for (i = 0; i < files.n; i++) {
   4414         char *from = fmt("%s/%s", stage, files.v[i]), *to = fmt("%s/%s", root, files.v[i]), *slash;
   4415         struct stat st;
   4416         mkparent(to);
   4417         if (lstat(from, &st) < 0) die("cannot stat %s", from);
   4418         owner_here(files.v[i], &st);
   4419         if (S_ISLNK(st.st_mode)) {
   4420             char tgt[PATH_MAX];
   4421             ssize_t n = readlink(from, tgt, sizeof tgt - 1);
   4422             if (n < 0) die("cannot read link %s", from);
   4423             tgt[n] = 0;
   4424             unlink(to);
   4425             if (symlink(tgt, to) < 0) { say("cannot link %s: %s", to, strerror(errno)); bad = 1; }
   4426             else if (!geteuid()) lchown(to, st.st_uid, st.st_gid);
   4427         } else if (!strncmp(files.v[i], "etc/", 4) && exists(to) && !same_file(from, to) && !etc_untouched(&sums, files.v[i], to)) {
   4428             char *alt = fmt("%s.new", to);
   4429             printf("==> /%s is changed here, the new one is /%s.new\n", files.v[i], files.v[i]);
   4430             if (copy_into(from, alt, &st) < 0) { say("cannot write %s: %s", alt, strerror(errno)); bad = 1; }
   4431             free(alt);
   4432         } else if (copy_into(from, to, &st) < 0) { say("cannot write %s: %s", to, strerror(errno)); bad = 1; }
   4433         if (!strncmp(files.v[i], "etc/", 4) && S_ISREG(st.st_mode)) {
   4434             char *sum = sha256_file(from);
   4435             if (sum) { push(&newsums, fmt("%s %s", sum, files.v[i])); free(sum); }
   4436         }
   4437         /* the directory and the ones above it: shared-mime-info watches /usr/share/mime for files in packages/ */
   4438         for (slash = strchr(files.v[i], '/'); slash; slash = strchr(slash + 1, '/')) {
   4439             char *dir = fmt("/%.*s", (int)(slash - files.v[i]), files.v[i]);
   4440             if (!has(&changed_dirs, dir)) push(&changed_dirs, dir); else free(dir);
   4441         }
   4442         free(from); free(to);
   4443     }
   4444     if (bad) die("%s did not install cleanly", p->name);
   4445     for (i = 0; i < old.n; i++) if (!has(&files, old.v[i]) && !owned_by_other(old.v[i], p->name)) push(&gone, old.v[i]);
   4446     if (alpm_order) {
   4447         for (i = 0; i < files.n; i++) push(&did_files, fmt("%c %s", oldver && has(&old, files.v[i]) ? 'U' : 'I', files.v[i]));
   4448         for (i = 0; i < dirs.n; i++) push(&did_files, fmt("%c %s/", oldver ? 'U' : 'I', dirs.v[i]));
   4449         for (i = 0; i < gone.n; i++) push(&did_files, fmt("R %s", gone.v[i]));
   4450         push(&did_pkgs, fmt("%c %s", oldver ? 'U' : 'I', p->name));
   4451     }
   4452     delete_files(&gone);
   4453     rmtree(stage);
   4454 
   4455     w = words(p->deps);
   4456     for (i = 0; i < w.n; i++) {
   4457         struct dep d;
   4458         const char *who = NULL;
   4459         int j;
   4460         dep_parse(w.v[i], &d);
   4461         if (d.neg) continue;
   4462         for (j = 0; j < planned->n && !who; j++) {
   4463             struct pkg *q = newest(planned->v[j]);
   4464             if (q && meets(&d, q->name, q->ver, q->prov)) who = q->name;
   4465         }
   4466         if (!who) who = installed_for(&d);
   4467         if (who && strcmp(who, p->name) && !has(&deps, who)) push(&deps, xstrdup(who));
   4468     }
   4469     list_free(&w);
   4470     push(&v, p->ver);
   4471     push(&pr, p->prov ? p->prov : "");
   4472     db_write(p->name, "version", &v);
   4473     db_write(p->name, "deps", &deps);
   4474     db_write(p->name, "provides", &pr);
   4475     db_write(p->name, "files", &files);
   4476     db_write(p->name, "etcsums", &newsums);
   4477     if ((trig = pkginfo(&ctl, "triggers"))) db_put(p->name, "triggers", trig, strlen(trig), 0644);
   4478     if (explicit) db_put(p->name, "explicit", "", 0, 0644);
   4479     if (port) db_put(p->name, "port", repo_urls.v[p->repo], strlen(repo_urls.v[p->repo]), 0644);
   4480     else { char *d = dbdir(p->name), *f = fmt("%s/port", d); unlink(f); free(d); free(f); }
   4481     free(trig);
   4482     tar_free(&ctl);
   4483     for (i = 0; i < takes.n; i++) {
   4484         struct list qf = db_read(takes.v[i], "files"), left = { 0 };
   4485         char *d = dbdir(takes.v[i]);
   4486         int k;
   4487         for (k = 0; k < qf.n; k++) if (!has(&files, qf.v[k])) push(&left, xstrdup(qf.v[k]));
   4488         delete_files(&left);
   4489         rmtree(d);
   4490         printf("==> %s replaced %s\n", p->name, takes.v[i]);
   4491         list_free(&qf); list_free(&left); free(d);
   4492     }
   4493     list_free(&takes);
   4494     if (oldver) script_or_later(p->name, "post-upgrade", p->ver, oldver);
   4495     else script_or_later(p->name, "post-install", p->ver, NULL);
   4496     printf("==> installed %s %s%s%s\n", p->name, p->ver, oldver ? ", was " : "", oldver ? oldver : "");
   4497     list_free(&files); list_free(&dirs); list_free(&old); list_free(&sums); list_free(&newsums); free(gone.v); list_free(&deps); free(v.v); free(pr.v);
   4498     free(oldver); free(file); free(stage);
   4499 }
   4500 
   4501 /* ---- working out what to install ---- */
   4502 
   4503 static struct list wanted;
   4504 
   4505 static void plan(struct pkg *p, struct list *order, struct list *stack);
   4506 
   4507 /* a port is built with build-base, pkgconf and bash, which CRUX has in core, and the -dev of what it needs that comes built from a repo */
   4508 static void plan_tool(const char *name, struct list *order, struct list *stack)
   4509 {
   4510     struct pkg *q = newest(name);
   4511     if (q && !installed(name) && !has(order, name)) plan(q, order, stack);
   4512 }
   4513 
   4514 /* the name a Void or Exherbo dependency goes by in the repos: Void's -devel is their -dev, and what comes built wins */
   4515 static char *port_dep(int kind, const char *w)
   4516 {
   4517     static const char *const alias[][2] = { { "pkg-config", "pkgconf" }, { "liblzma", "xz" }, { "libuuid", "util-linux" }, { "gettext-tiny", "gettext" } };
   4518     char *n = xstrdup(w), *c[3] = { 0 }, *best = NULL;
   4519     size_t l = strlen(n);
   4520     int i, dev = kind == VOID && l > 6 && !strcmp(n + l - 6, "-devel");
   4521     struct pkg *q;
   4522     if (dev) n[l - 6] = 0;
   4523     for (i = 0; i < 4; i++) if (!strcmp(n, alias[i][0])) { free(n); n = xstrdup(alias[i][1]); break; }
   4524     if (dev) { c[0] = fmt("%s-dev", n); if (!strncmp(n, "lib", 3)) c[1] = fmt("%s-dev", n + 3); }
   4525     c[2] = xstrdup(n);
   4526     for (i = 0; i < 3 && !best; i++) if (c[i] && (q = newest(c[i])) && kinds[q->repo] == APK) best = c[i];
   4527     for (i = 0; i < 3 && !best; i++) if (c[i] && newest(c[i])) best = c[i];
   4528     best = xstrdup(best ? best : n);
   4529     for (i = 0; i < 3; i++) free(c[i]);
   4530     free(n);
   4531     return best;
   4532 }
   4533 
   4534 static void plan(struct pkg *p, struct list *order, struct list *stack)
   4535 {
   4536     struct list w;
   4537     int i, j, k = kinds[p->repo], port = BUILT(k), tree = k == VOID || k == EXHERBO;
   4538     char *all;
   4539     if (has(order, p->name) || has(stack, p->name)) return;
   4540     push(stack, p->name);
   4541     if (port && k != AUR) { plan_tool("build-base", order, stack); plan_tool("pkgconf", order, stack); plan_tool("bash", order, stack); }
   4542     if (tree) { plan_tool("tar", order, stack); plan_tool("xz", order, stack); }
   4543     if (k == AUR) { plan_tool("base-devel", order, stack); plan_tool("git", order, stack); }
   4544     all = fmt("%s %s", p->deps ? p->deps : "", p->mdeps ? p->mdeps : "");
   4545     w = words(all);
   4546     free(all);
   4547     for (i = 0; i < w.n; i++) {
   4548         struct dep d;
   4549         struct pkg *c;
   4550         int done = 0;
   4551         if (tree) { char *m = port_dep(k, w.v[i]); dep_parse(m, &d); free(m); }
   4552         else dep_parse(w.v[i], &d);
   4553         if (d.neg || !strcmp(d.key, p->name)) continue;
   4554         for (j = 0; j < order->n && !done; j++) {
   4555             struct pkg *q = newest(order->v[j]);
   4556             done = q && meets(&d, q->name, q->ver, q->prov);
   4557         }
   4558         if (!done && !installed_for(&d)) {
   4559             for (j = 0, c = NULL; j < wanted.n && !c; j++) {
   4560                 struct pkg *q = newest(wanted.v[j]);
   4561                 if (q && meets(&d, q->name, q->ver, q->prov)) c = q;
   4562             }
   4563             if (!c && !(c = pick(&d))) {
   4564                 if (!tree) die("%s needs %s, which no repo has", p->name, w.v[i]);
   4565                 say("%s wants %s, which no repo has, building without it", p->name, w.v[i]);
   4566                 continue;
   4567             }
   4568             plan(c, order, stack);
   4569         }
   4570         if (port && k != AUR) {
   4571             struct pkg *q = newest(d.key);
   4572             char *dev = fmt("%s-dev", d.key), *m = dbdir(d.key), *f = fmt("%s/port", m);
   4573             if (q && kinds[q->repo] == APK && !exists(f)) plan_tool(dev, order, stack);
   4574             free(dev); free(m); free(f);
   4575         }
   4576     }
   4577     list_free(&w);
   4578     stack->n--;
   4579     push(order, p->name);
   4580 }
   4581 
   4582 /* install_if: a package that comes by itself once all it names is installed or coming, like foo-openrc with openrc and foo */
   4583 static int coming(const char *tok, const struct list *order)
   4584 {
   4585     struct dep d;
   4586     int j;
   4587     dep_parse(tok, &d);
   4588     for (j = 0; j < order->n; j++) {
   4589         struct pkg *q = newest(order->v[j]);
   4590         if (q && meets(&d, q->name, q->ver, q->prov)) return !d.neg;
   4591     }
   4592     return d.neg ? !installed_for(&d) : installed_for(&d) != NULL;
   4593 }
   4594 
   4595 /* Artix keeps a daemon's OpenRC service in NAME-openrc (or BASE-openrc), which nothing depends on: it comes along */
   4596 static int plan_openrc(struct list *order, struct list *stack)
   4597 {
   4598     int i, k, more = 0;
   4599     for (i = 0; alpm_order && i < order->n; i++) {
   4600         struct pkg *p = newest(order->v[i]), *s;
   4601         const char *names[2];
   4602         if (!p) continue;
   4603         names[0] = p->name; names[1] = p->base;
   4604         for (k = 0; k < 2; k++) {
   4605             char *n;
   4606             if (!names[k] || (k && !strcmp(names[0], names[1]))) continue;
   4607             n = fmt("%s-openrc", names[k]);
   4608             if (!has(order, n) && !installed(n) && (s = newest(n))) { plan(s, order, stack); more = 1; }
   4609             free(n);
   4610         }
   4611     }
   4612     return more;
   4613 }
   4614 
   4615 static void plan_install_ifs(struct list *order, struct list *stack)
   4616 {
   4617     int i, j, ok, more = 1;
   4618     while (more) {
   4619         more = plan_openrc(order, stack);
   4620         for (i = 0; i < npkgs; i++) {
   4621             struct pkg *p = &pkgs[i];
   4622             struct list w;
   4623             if (!p->iif || has(order, p->name) || newest(p->name) != p || installed(p->name)) continue;
   4624             w = words(p->iif);
   4625             for (j = 0, ok = 1; j < w.n && ok; j++) ok = coming(w.v[j], order);
   4626             list_free(&w);
   4627             if (ok) { plan(p, order, stack); more = 1; }
   4628         }
   4629     }
   4630 }
   4631 
   4632 /* the directories changed by a run that did not get to its triggers, so the next run runs them */
   4633 static char *pending_file(void) { return fmt("%s/var/lib/mag/.triggers", root); }
   4634 
   4635 static void pending_save(void)
   4636 {
   4637     char *f = pending_file();
   4638     struct buf b = { 0 };
   4639     int i;
   4640     buf_add(&b, "", 0);
   4641     for (i = 0; i < changed_dirs.n; i++) { buf_add(&b, changed_dirs.v[i], strlen(changed_dirs.v[i])); buf_add(&b, "\n", 1); }
   4642     mkparent(f);
   4643     db_put_file(f, (char *)b.p);
   4644     free(b.p); free(f);
   4645 }
   4646 
   4647 static void pending_load(void)
   4648 {
   4649     char *f = pending_file(), *t = slurp(f, NULL), *line, *next;
   4650     for (line = t; line && *line; line = next) {
   4651         next = strchr(line, '\n');
   4652         if (next) *next++ = 0;
   4653         if (*line && !has(&changed_dirs, line)) push(&changed_dirs, xstrdup(line));
   4654     }
   4655     free(t); free(f);
   4656 }
   4657 
   4658 static const char *bold(void) { return isatty(1) ? "\033[1m" : ""; }
   4659 static const char *plain(void) { return isatty(1) ? "\033[0m" : ""; }
   4660 
   4661 static const char *hsize(double b)
   4662 {
   4663     static char s[2][32];
   4664     static int k;
   4665     const char *u[] = { "B", "KiB", "MiB", "GiB" };
   4666     int i = 0;
   4667     for (; b >= 1024 && i < 3; i++) b /= 1024;
   4668     k ^= 1;
   4669     snprintf(s[k], sizeof s[k], i ? "%.1f %s" : "%.0f %s", b, u[i]);
   4670     return s[k];
   4671 }
   4672 
   4673 static char *repo_label(int i)
   4674 {
   4675     const char *u = repo_urls.v[i], *s;
   4676     if (kinds[i] == PACMAN) return pac_name(i);
   4677     if (kinds[i] == AUR) return xstrdup("aur");
   4678     s = strrchr(u, '/');
   4679     return xstrdup(s && s[1] ? s + 1 : u);
   4680 }
   4681 
   4682 /* y/n on a terminal; -y or MAG_YES says yes without asking */
   4683 static int ask(const char *what)
   4684 {
   4685     char c[16];
   4686     ssize_t n;
   4687     const char *e = getenv("MAG_YES");
   4688     if (yes || (e && *e) || !isatty(0)) return 1;
   4689     printf("%s? [Y/n] ", what);
   4690     fflush(stdout);
   4691     if ((n = read(0, c, sizeof c - 1)) <= 0) { putchar('\n'); return 0; }
   4692     return *c == '\n' || *c == 'y' || *c == 'Y';
   4693 }
   4694 
   4695 static int apply(const struct list *order, const struct list *want)
   4696 {
   4697     int i;
   4698     if (!dry && !geteuid()) {
   4699         pending_load();
   4700         if (!order->n && changed_dirs.n) {
   4701             char *f = pending_file();
   4702             puts("running the triggers a run before this one did not get to");
   4703             triggers(&changed_dirs);
   4704             unlink(f); free(f);
   4705         }
   4706     }
   4707     if (!order->n) return 0;
   4708     {
   4709         double dl = 0, in = 0;
   4710         int w = 0, wv = 0;
   4711         for (i = 0; i < order->n; i++) {
   4712             struct pkg *p = newest(order->v[i]);
   4713             if ((int)strlen(p->name) > w) w = strlen(p->name);
   4714             if ((int)strlen(p->ver) > wv) wv = strlen(p->ver);
   4715         }
   4716         printf("%sinstall (%d)%s\n", bold(), order->n, plain());
   4717         for (i = 0; i < order->n; i++) {
   4718             struct pkg *p = newest(order->v[i]);
   4719             char *old = db_get(p->name, "version"), *from = repo_label(p->repo);
   4720             printf("  %-*s  %-*s  %s", w, p->name, wv, p->ver, from);
   4721             if (BUILT(kinds[p->repo])) printf(", built here");
   4722             if (old) printf(", was %s", old);
   4723             putchar('\n');
   4724             if (!BUILT(kinds[p->repo]) && p->size) dl += atof(p->size);
   4725             if (p->isize) in += atof(p->isize);
   4726             free(old); free(from);
   4727         }
   4728         printf("\ndownload %s", hsize(dl));
   4729         printf(", installed %s\n", hsize(in));
   4730     }
   4731     if (dry) return 0;
   4732     if (geteuid()) die("this needs root");
   4733     if (!ask("install")) return 1;
   4734     {
   4735         char *f = fmt("%s/etc/mag/arch", root);
   4736         if (!exists(f)) { mkparent(f); db_put_file(f, arch); }
   4737         free(f);
   4738     }
   4739     {
   4740         struct list urls = { 0 }, files = { 0 };
   4741         char *dir = NULL;
   4742         for (i = 0; i < order->n; i++) {
   4743             struct pkg *p = newest(order->v[i]);
   4744             char *file, *base;
   4745             if (BUILT(kinds[p->repo]) || exists(file = pkg_file(p))) continue;
   4746             base = pac_base(p->repo);
   4747             if (!dir) { dir = xstrdup(file); *strrchr(dir, '/') = 0; }
   4748             push(&urls, kinds[p->repo] == PACMAN ? fmt("%s/%s", base, p->file) : fmt("%s/%s-%s.apk", base, p->name, p->ver));
   4749             push(&files, file);
   4750             if (kinds[p->repo] == PACMAN && !p->sig) { push(&urls, fmt("%s/%s.sig", base, p->file)); push(&files, fmt("%s.sig", file)); }
   4751             free(base);
   4752         }
   4753         if (urls.n > 1) { printf("==> fetching %d files\n", urls.n); fetch_all(&urls, &files, dir); }
   4754         list_free(&urls); list_free(&files); free(dir);
   4755     }
   4756     for (i = 0; i < order->n; i++) {
   4757         struct pkg *p = newest(order->v[i]);
   4758         install_one(p, has(want, p->name), order);
   4759         pending_save();
   4760     }
   4761     run_waiting();
   4762     triggers(&changed_dirs);
   4763     after_run();
   4764     {
   4765         char *f = pending_file();
   4766         unlink(f); free(f);
   4767     }
   4768     return 0;
   4769 }
   4770 
   4771 static int cmd_install(int n, char **names)
   4772 {
   4773     struct list order = { 0 }, stack = { 0 }, want = { 0 };
   4774     int i;
   4775     load_index();
   4776     for (i = 0; i < n; i++) push(&wanted, names[i]);
   4777     for (i = 0; i < n; i++) prefer_deps(names[i]);
   4778     for (i = 0; i < n; i++) {
   4779         struct pkg *p = newest(names[i]);
   4780         if (!p) {
   4781             struct dep d;
   4782             dep_parse(names[i], &d);
   4783             if (!(p = pick(&d))) die("%s is in no repo", names[i]);
   4784         }
   4785         push(&want, p->name);
   4786         if (installed(p->name) && !force) {
   4787             char *v = db_get(p->name, "version");
   4788             int same = !strcmp(v, p->ver);
   4789             if (same) {
   4790                 printf("%s %s is installed already\n", p->name, v);
   4791                 if (!dry) db_put(p->name, "explicit", "", 0, 0644);
   4792             }
   4793             free(v);
   4794             if (same) continue;
   4795         }
   4796         plan(p, &order, &stack);
   4797     }
   4798     plan_install_ifs(&order, &stack);
   4799     return apply(&order, &want);
   4800 }
   4801 
   4802 static int cmd_upgrade(void)
   4803 {
   4804     struct list all = db_all(), order = { 0 }, stack = { 0 }, want = { 0 };
   4805     int i;
   4806     load_index();
   4807     for (i = 0; i < all.n; i++) { char *v = db_get(all.v[i], "port"); if (v) push(&from_ports, all.v[i]); free(v); }
   4808     for (i = 0; i < all.n; i++) {
   4809         struct pkg *p = newest(all.v[i]);
   4810         char *v = db_get(all.v[i], "version"), *d = dbdir(all.v[i]), *e = fmt("%s/explicit", d);
   4811         if (exists(e)) push(&want, all.v[i]);
   4812         if (p && v && vercmp(p->ver, v) > 0) plan(p, &order, &stack);
   4813         free(v); free(d); free(e);
   4814     }
   4815     plan_install_ifs(&order, &stack);
   4816     if (!order.n) { puts("everything is up to date"); return 0; }
   4817     return apply(&order, &want);
   4818 }
   4819 
   4820 static int cmd_update(void)
   4821 {
   4822     int i, bad = 0;
   4823     for (i = 0; i < repo_urls.n; i++) {
   4824         char *base, *url, *f, *tmp;
   4825         if (kinds[i] == PACMAN) { bad |= sync_pacman(i); continue; }
   4826         if (kinds[i] == AUR) { bad |= sync_aur(i); continue; }
   4827         if (kinds[i] != APK) { bad |= kinds[i] == CRUX ? sync_tree(i) : sync_archive(i); continue; }
   4828         base = repo_base(i); url = fmt("%s/APKINDEX.tar.gz", base); f = index_file(i); tmp = fmt("%s.new", f);
   4829         printf("==> %s\n", url);
   4830         if (download(url, tmp)) { say("could not fetch %s", url); bad = 1; }
   4831         else if (check_signed(tmp)) { say("%s is not signed by a key mag has, not using it", url); unlink(tmp); bad = 1; }
   4832         else rename(tmp, f);
   4833         free(base); free(url); free(f); free(tmp);
   4834     }
   4835     load_index();
   4836     printf("%d packages\n", npkgs);
   4837     return bad;
   4838 }
   4839 
   4840 static int cmd_build(int n, char **names)
   4841 {
   4842     int i;
   4843     load_index();
   4844     for (i = 0; i < n; i++) {
   4845         if (!port_of(names[i])) {
   4846             int j;
   4847             for (j = 0; j < npkgs; j++) {
   4848                 struct list pv;
   4849                 if (!BUILT(kinds[pkgs[j].repo]) || !pkgs[j].prov) continue;
   4850                 pv = words(pkgs[j].prov);
   4851                 if (has(&pv, names[i])) names[i] = pkgs[j].name;
   4852                 list_free(&pv);
   4853             }
   4854         }
   4855         if (!port_of(names[i])) die("%s is in no port tree", names[i]);
   4856         push(&from_ports, names[i]);
   4857     }
   4858     return cmd_install(n, names);
   4859 }
   4860 
   4861 static int cmd_remove(int n, char **names)
   4862 {
   4863     int i;
   4864     for (i = 0; alpm_order && !dry && i < n; i++) {
   4865         struct list files = installed(names[i]) ? db_read(names[i], "files") : (struct list){ 0 };
   4866         int k;
   4867         for (k = 0; k < files.n; k++) push(&did_files, fmt("R %s", files.v[k]));
   4868         push(&did_pkgs, fmt("R %s", names[i]));
   4869         list_free(&files);
   4870     }
   4871     if (!dry) {
   4872         printf("%sremove (%d)%s\n ", bold(), n, plain());
   4873         for (i = 0; i < n; i++) printf(" %s", names[i]);
   4874         putchar('\n');
   4875         if (!ask("remove")) return 1;
   4876     }
   4877     run_hooks(0);
   4878     for (i = 0; i < n; i++) {
   4879         struct list rd, files;
   4880         char *d, *v;
   4881         if (!installed(names[i])) die("%s is not installed", names[i]);
   4882         rd = rdeps(names[i]);
   4883         if (rd.n && !force) {
   4884             int k;
   4885             fprintf(stderr, "%s: %s is needed by", prog, names[i]);
   4886             for (k = 0; k < rd.n; k++) fprintf(stderr, " %s", rd.v[k]);
   4887             fputs(", -f removes it anyway\n", stderr);
   4888             return 1;
   4889         }
   4890         files = db_read(names[i], "files");
   4891         if (dry) { printf("would remove %s (%d files)\n", names[i], files.n); continue; }
   4892         v = db_get(names[i], "version");
   4893         script_or_later(names[i], "pre-deinstall", v, NULL);
   4894         delete_files(&files);
   4895         script_or_later(names[i], "post-deinstall", v, NULL);
   4896         nwaiting = 0;
   4897         d = dbdir(names[i]);
   4898         rmtree(d);
   4899         free(d); free(v);
   4900         list_free(&files); list_free(&rd);
   4901         printf("==> removed %s\n", names[i]);
   4902     }
   4903     if (!dry) after_run();
   4904     return 0;
   4905 }
   4906 
   4907 static struct list orphans(void)
   4908 {
   4909     struct list all = db_all(), out = { 0 };
   4910     int i;
   4911     for (i = 0; i < all.n; i++) {
   4912         char *d = dbdir(all.v[i]), *e = fmt("%s/explicit", d);
   4913         struct list rd = rdeps(all.v[i]);
   4914         if (!exists(e) && !rd.n) push(&out, all.v[i]);
   4915         free(d); free(e);
   4916         list_free(&rd);
   4917     }
   4918     return out;
   4919 }
   4920 
   4921 static int cmd_autoremove(void)
   4922 {
   4923     int total = 0;
   4924     for (;;) {
   4925         struct list o = orphans();
   4926         if (!o.n) break;
   4927         if (cmd_remove(o.n, o.v)) return 1;
   4928         total += o.n;
   4929         if (dry) break;
   4930     }
   4931     if (!total) puts("nothing to remove");
   4932     return 0;
   4933 }
   4934 
   4935 /* ---- the small commands ---- */
   4936 
   4937 static int cmd_list(void)
   4938 {
   4939     struct list all = db_all();
   4940     int i;
   4941     for (i = 0; i < all.n; i++) { char *v = db_get(all.v[i], "version"); printf("%s %s\n", all.v[i], v ? v : "?"); free(v); }
   4942     return 0;
   4943 }
   4944 
   4945 static int cmd_info(const char *name)
   4946 {
   4947     struct pkg *p;
   4948     char *v = db_get(name, "version"), *port = db_get(name, "port");
   4949     load_index();
   4950     if (port) push(&from_ports, xstrdup(name));
   4951     free(port);
   4952     p = newest(name);
   4953     if (!p && !v) die("%s is in no repo and not installed", name);
   4954     if (p) {
   4955         printf("%s %s\n", p->name, p->ver);
   4956         if (p->desc) printf("  %s\n", p->desc);
   4957         if (p->deps) printf("  needs: %s\n", p->deps);
   4958         if (p->size) printf("  size: %s bytes\n", p->size);
   4959         printf("  from: %s%s%s\n", kind_name[kinds[p->repo]], kinds[p->repo] != APK ? " " : "", repo_urls.v[p->repo]);
   4960     } else printf("%s\n", name);
   4961     if (v) printf("  installed: %s\n", v); else puts("  not installed");
   4962     free(v);
   4963     return 0;
   4964 }
   4965 
   4966 static int cmd_search(const char *word)
   4967 {
   4968     int i, found = 0;
   4969     load_index();
   4970     for (i = 0; i < npkgs; i++) {
   4971         struct pkg *p = &pkgs[i];
   4972         if (strstr(p->name, word) || (p->desc && strstr(p->desc, word))) { printf("%s %s  %s\n", p->name, p->ver, p->desc ? p->desc : ""); found = 1; }
   4973     }
   4974     return !found;
   4975 }
   4976 
   4977 static int cmd_files(const char *name)
   4978 {
   4979     struct list f;
   4980     int i;
   4981     if (!installed(name)) die("%s is not installed", name);
   4982     f = db_read(name, "files");
   4983     for (i = 0; i < f.n; i++) printf("/%s\n", f.v[i]);
   4984     return 0;
   4985 }
   4986 
   4987 static int cmd_owns(const char *path)
   4988 {
   4989     const char *o;
   4990     char *real = realpath(path, NULL), *rel;
   4991     size_t rl = strlen(root);
   4992     if (!real) die("%s: %s", path, strerror(errno));
   4993     rel = real;
   4994     if (rl && !strncmp(rel, root, rl)) rel += rl;
   4995     while (*rel == '/') rel++;
   4996     load_owners();
   4997     o = owner_of(rel);
   4998     if (!o) { printf("%s is not owned by any package\n", path); return 1; }
   4999     printf("%s is owned by %s\n", path, o);
   5000     return 0;
   5001 }
   5002 
   5003 static int cmd_deps(const char *name, int reverse)
   5004 {
   5005     struct list l;
   5006     int i;
   5007     if (reverse) l = rdeps(name);
   5008     else if (installed(name)) l = db_read(name, "deps");
   5009     else {
   5010         struct pkg *p;
   5011         load_index();
   5012         if (!(p = newest(name))) die("%s is in no repo", name);
   5013         l = words(p->deps);
   5014     }
   5015     for (i = 0; i < l.n; i++) puts(l.v[i]);
   5016     return 0;
   5017 }
   5018 
   5019 static int cmd_fetch(int n, char **names)
   5020 {
   5021     int i;
   5022     load_index();
   5023     for (i = 0; i < n; i++) {
   5024         struct pkg *p = newest(names[i]);
   5025         char *file, *base, *url;
   5026         if (!p) die("%s is in no repo", names[i]);
   5027         if (BUILT(kinds[p->repo])) { printf("%s comes from a port tree, it is built and not fetched\n", p->name); continue; }
   5028         file = pkg_file(p); base = pac_base(p->repo); url = fmt("%s/%s-%s.apk", base, p->name, p->ver);
   5029         printf("==> fetching %s\n", url);
   5030         if (download(url, file)) die("could not fetch %s", url);
   5031         free(file); free(base); free(url);
   5032     }
   5033     return 0;
   5034 }
   5035 
   5036 static void usage(void)
   5037 {
   5038     puts("Usage: mag [-nfy] COMMAND [PACKAGE]...\n"
   5039          "\n"
   5040          "  update            get the index of every repo, checked against the keys\n"
   5041          "  install PKG...    install packages and what they need\n"
   5042          "  build PKG...      build them from a port tree and install them, even if a repo has them built\n"
   5043          "  remove PKG...     take a package off\n"
   5044          "  upgrade           install what the repos have a newer version of\n"
   5045          "  autoremove        remove what was only installed as a dependency and is not needed now\n"
   5046          "  list              what is installed\n"
   5047          "  info PKG          what the repo says about it, and whether it is installed\n"
   5048          "  search WORD       packages whose name or description has WORD\n"
   5049          "  files PKG         the files a package put on the system\n"
   5050          "  owns PATH         which package a file came from\n"
   5051          "  deps PKG          what it needs, rdeps PKG for what needs it\n"
   5052          "  fetch PKG...      only download them\n"
   5053          "\n"
   5054          "  -n  only say what would happen    -f  go on when files clash or something needs the package\n"
   5055          "  -y  do not ask before installing or removing\n"
   5056          "\n"
   5057          "/etc/mag/repos has one repo url a line, /etc/mag/keys the public keys they are signed with, /etc/mag/arch\n"
   5058          "which builds to get (written on the first install, the machine's own if it is not there). A line \"crux URL\" is a\n"
   5059          "CRUX port tree, like crux https://crux.nu/ports/crux-3.8/opt; its key, opt.pub, goes in /etc/mag/keys too.\n"
   5060          "\"void https://github.com/void-linux/void-packages\" builds Void's templates, \"exherbo https://gitlab.exherbo.org/exherbo/arbor\"\n"
   5061          "Exherbo's exheres; those two come whole as a tarball on mag update and are not signed. What a\n"
   5062          "repo has built wins over a port, mag build takes the port. Ports build with bash and the CFLAGS, CXXFLAGS and\n"
   5063          "MAKEFLAGS of /etc/mag/build.conf, if it is there.\n"
   5064          "\"pacman URL\" is a pacman repo like Artix's and Arch's, pacman https://geo.mirror.pkgbuild.com/extra/os: its\n"
   5065          "packages are checked against the OpenPGP keyrings in /etc/mag/keys (*.gpg) and /usr/share/pacman/keyrings, and the\n"
   5066          "hooks in /usr/share/libalpm/hooks run after them. A name in two pacman repos comes from the first one, as in pacman.\n"
   5067          "\"aur https://aur.archlinux.org\" is the AUR: a PKGBUILD is built by makepkg as nobody in /var/cache/mag/aur.\n"
   5068          "MAG_ROOT installs somewhere else than /, MAG_ARCH overrides the arch, MAG_FETCH is the download command, which gets a file and an url (curl, else wget, else ftp; plain http:// mag fetches itself)");
   5069 }
   5070 
   5071 int main(int argc, char **argv)
   5072 {
   5073     const char *r = getenv("MAG_ROOT");
   5074     int i = 1, rc;
   5075     if (r && strcmp(r, "/")) { char *rr = xstrdup(r), *s = rr + strlen(rr); while (s > rr + 1 && s[-1] == '/') *--s = 0; root = rr; }
   5076     for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
   5077         const char *o;
   5078         if (!strcmp(argv[i], "--")) { i++; break; }
   5079         if (!strcmp(argv[i], "--help")) { usage(); return 0; }
   5080         if (!strcmp(argv[i], "--version")) { puts("mag " VERSION); return 0; }
   5081         for (o = argv[i] + 1; *o; o++) {
   5082             if (*o == 'n') dry = 1; else if (*o == 'f') force = 1; else if (*o == 'y') yes = 1;
   5083             else { say("unknown option -%c", *o); return 1; }
   5084         }
   5085     }
   5086     {
   5087         /* -y and the rest after the command too: mag install -y foo */
   5088         int j, k = i;
   5089         for (j = i; j < argc; j++) {
   5090             if (argv[j][0] == '-' && argv[j][1] && strspn(argv[j] + 1, "nfy") == strlen(argv[j] + 1) && j > i) {
   5091                 const char *o;
   5092                 for (o = argv[j] + 1; *o; o++) { if (*o == 'n') dry = 1; else if (*o == 'f') force = 1; else yes = 1; }
   5093             } else argv[k++] = argv[j];
   5094         }
   5095         argc = k;
   5096     }
   5097     if (i >= argc || !strcmp(argv[i], "help")) { usage(); return i >= argc ? 1 : 0; }
   5098     arch = machine();
   5099     {
   5100         const char *cmd = argv[i++];
   5101         int n = argc - i;
   5102         char **a = argv + i;
   5103         if (strcmp(cmd, "list") && strcmp(cmd, "files") && strcmp(cmd, "owns") && strcmp(cmd, "remove") && strcmp(cmd, "del")
   5104             && strcmp(cmd, "rdeps") && strcmp(cmd, "autoremove")) load_repos();
   5105         else {
   5106             /* remove needs to know a pacman system for its hooks */
   5107             char *d = confdir(), *f = fmt("%s/repos", d);
   5108             if (exists(f)) load_repos();
   5109             free(d); free(f);
   5110         }
   5111         if (!strcmp(cmd, "update") && !n) rc = cmd_update();
   5112         else if (!strcmp(cmd, "install") || !strcmp(cmd, "add")) rc = n ? cmd_install(n, a) : (say("install what?"), 1);
   5113         else if (!strcmp(cmd, "build")) rc = n ? cmd_build(n, a) : (say("build what?"), 1);
   5114         else if (!strcmp(cmd, "remove") || !strcmp(cmd, "del")) rc = n ? cmd_remove(n, a) : (say("remove what?"), 1);
   5115         else if (!strcmp(cmd, "upgrade") && !n) rc = cmd_upgrade();
   5116         else if (!strcmp(cmd, "autoremove") && !n) rc = cmd_autoremove();
   5117         else if (!strcmp(cmd, "list") && !n) rc = cmd_list();
   5118         else if (!strcmp(cmd, "info") && n == 1) rc = cmd_info(a[0]);
   5119         else if (!strcmp(cmd, "search") && n == 1) rc = cmd_search(a[0]);
   5120         else if (!strcmp(cmd, "files") && n == 1) rc = cmd_files(a[0]);
   5121         else if (!strcmp(cmd, "owns") && n == 1) rc = cmd_owns(a[0]);
   5122         else if (!strcmp(cmd, "deps") && n == 1) rc = cmd_deps(a[0], 0);
   5123         else if (!strcmp(cmd, "rdeps") && n == 1) rc = cmd_deps(a[0], 1);
   5124         else if (!strcmp(cmd, "fetch") && n) rc = cmd_fetch(n, a);
   5125         else { say("'%s' with %d argument%s makes no sense, mag help says what there is", cmd, n, n == 1 ? "" : "s"); return 1; }
   5126     }
   5127     fflush(stdout);
   5128     return rc;
   5129 }