summaryrefslogtreecommitdiffstats
path: root/expac.c
blob: db6ed6b44edab96b70a1da1e3115c9f0b442ae31 (plain)
1
2
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/* Copyright (c) 2010-2011 Dave Reisner
 *
 * expac.c
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#define _GNU_SOURCE
#include <alpm.h>
#include <ctype.h>
#include <getopt.h>
/* #include <limits.h> */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define DEFAULT_DELIM        "\n"
#define DEFAULT_LISTDELIM    "  "
#define DEFAULT_TIMEFMT      "%c"
#define FORMAT_TOKENS        "BCDEGLNOPRSabdhmnprsuvw%"
#define FORMAT_TOKENS_LOCAL  "ilFw"
#define FORMAT_TOKENS_SYNC   "fgk"
#define ESCAPE_TOKENS        "\"\\abefnrtv"
#define SIZE_TOKENS          "BKMGTPEZY\0"

#ifndef PATH_MAX
#define PATH_MAX  4096
#endif

static char const digits[] = "0123456789";
static char const printf_flags[] = "'-+ #0I";

alpm_db_t *db_local = NULL;
alpm_list_t *dblist = NULL;
alpm_list_t *targets = NULL;
bool readone = false;
bool verbose = false;
bool search = false;
bool local = false;
bool groups = false;
bool localpkg = false;
char humansize = 'B';
const char *format = NULL;
const char *timefmt = NULL;
const char *listdelim = NULL;
const char *delim = NULL;
int pkgcounter = 0;

typedef const char *(*extractfn)(void*);

static double humanize_size(off_t bytes, const char target_unit, const char **label)
{
	static const char *labels[] = {"B", "KiB", "MiB", "GiB",
		"TiB", "PiB", "EiB", "ZiB", "YiB"};
	static const int unitcount = sizeof(labels) / sizeof(labels[0]);

	double val = (double)bytes;
	int index;

	for(index = 0; index < unitcount - 1; index++) {
		if(target_unit != '\0' && labels[index][0] == target_unit) {
			break;
		} else if(target_unit == '\0' && val <= 2048.0 && val >= -2048.0) {
			break;
		}
		val /= 1024.0;
	}

	if(label) {
		*label = labels[index];
	}

	return val;
}

static char *size_to_string(off_t pkgsize)
{
	static char out[64];

	if(humansize == 'B') {
		snprintf(out, sizeof(out), "%jd", (intmax_t)pkgsize);
	} else {
		snprintf(out, sizeof(out), "%.2f %ciB", humanize_size(pkgsize, humansize, NULL), humansize);
	}

	return out;
}

static char *strtrim(char *str) {
  char *pch = str;

  if (!str || *str == '\0') {
    return str;
  }

  while (isspace((unsigned char)*pch)) {
    pch++;
  }
  if (pch != str) {
    memmove(str, pch, (strlen(pch) + 1));
  }

  if (*str == '\0') {
    return str;
  }

  pch = (str + (strlen(str) - 1));
  while (isspace((unsigned char)*pch)) {
    pch--;
  }
  *++pch = '\0';

  return str;
}

static char *trim_optdep(char *optdep) {
  char *colon;

  colon = strchr(optdep, ':');
  if (colon) {
    *colon = '\0';
  }

  return optdep;
}

static alpm_handle_t *alpm_init(void) {
  alpm_handle_t *handle = NULL;
  enum _alpm_errno_t alpm_errno = 0;
  FILE *fp;
  char line[PATH_MAX];
  char *ptr, *section = NULL;

  handle = alpm_initialize("/", "/var/lib/pacman", &alpm_errno);
  if (!handle) {
    alpm_strerror(alpm_errno);
    return NULL;
  }

  db_local = alpm_option_get_localdb(handle);

  fp = fopen("/etc/pacman.conf", "r");
  if (!fp) {
    perror("fopen: /etc/pacman.conf");
    return handle;
  }

  while (fgets(line, PATH_MAX, fp)) {
    strtrim(line);

    if (strlen(line) == 0 || line[0] == '#') {
      continue;
    }
    if ((ptr = strchr(line, '#'))) {
      *ptr = '\0';
    }

    if (line[0] == '[' && line[strlen(line) - 1] == ']') {
      ptr = &line[1];
      if (section) {
        free(section);
      }

      section = strdup(ptr);
      section[strlen(section) - 1] = '\0';

      if (strcmp(section, "options") != 0) {
        alpm_db_register_sync(handle, section,
            ALPM_SIG_DATABASE | ALPM_SIG_DATABASE_OPTIONAL);
      }
    }
  }

  free(section);
  fclose(fp);
  return handle;
}

static const char *alpm_dep_get_name(void *dep) {
  return ((alpm_depend_t*)dep)->name;
}

static void usage(void) {
  fprintf(stderr, "expac %s\n"
      "Usage: expac [options] <format> target...\n\n", VERSION);
  fprintf(stderr,
      " Options:\n"
      "  -Q, --local               search local DB (default)\n"
      "  -S, --sync                search sync DBs\n"
      "  -s, --search              search for matching regex\n"
      "  -g, --group               return packages matching targets as groups\n"
      "  -H, --humansize <size>    format package sizes in SI units (default: bytes)\n"
      "  -1, --readone             return only the first result of a sync search\n\n"
      "  -d, --delim <string>      separator used between packages (default: \"\\n\")\n"
      "  -l, --listdelim <string>  separator used between list elements (default: \"  \")\n"
      "  -p, --file                query local files instead of the DB\n"
      "  -t, --timefmt <fmt>       date format passed to strftime (default: \"%%c\")\n\n"
      "  -v, --verbose             be more verbose\n\n"
      "  -h, --help                display this help and exit\n\n");
}

static int parse_options(int argc, char *argv[], alpm_handle_t *handle) {
  int opt, option_index = 0;
  const char *i;

  static struct option opts[] = {
    {"readone",   no_argument,        0, '1'},
    {"delim",     required_argument,  0, 'd'},
    {"listdelim", required_argument,  0, 'l'},
    {"group",     required_argument,  0, 'g'},
    {"help",      no_argument,        0, 'h'},
    {"file",      no_argument,        0, 'p'},
    {"humansize", required_argument,  0, 'H'},
    {"query",     no_argument,        0, 'Q'},
    {"sync",      no_argument,        0, 'S'},
    {"search",    no_argument,        0, 's'},
    {"timefmt",   required_argument,  0, 't'},
    {"verbose",   no_argument,        0, 'v'},
    {0, 0, 0, 0}
  };

  while (-1 != (opt = getopt_long(argc, argv, "1l:d:gH:hf:pQSst:v", opts, &option_index))) {
    switch (opt) {
      case 'S':
        if (dblist) {
          fprintf(stderr, "error: can only select one repo option (use -h for help)\n");
          return 1;
        }
        dblist = alpm_list_copy(alpm_option_get_syncdbs(handle));
        break;
      case 'Q':
        if (dblist) {
          fprintf(stderr, "error: can only select one repo option (use -h for help)\n");
          return 1;
        }
        dblist = alpm_list_add(dblist, db_local);
        local = true;
        break;
      case '1':
        readone = true;
        break;
      case 'd':
        delim = optarg;
        break;
      case 'g':
        groups = true;
        break;
      case 'l':
        listdelim = optarg;
        break;
      case 'H':
        for(i = SIZE_TOKENS; *i; i++) {
          if(*i == *optarg) {
            humansize = *optarg;
            break;
          }
        }
        if(*i == '\0') {
          fprintf(stderr, "error: invalid SI size formatter: %c\n", *optarg);
          return 1;
        }
        break;
      case 'h':
        usage();
        return 1;
      case 'p':
        localpkg = true;
        break;
      case 's':
        search = true;
        break;
      case 't':
        timefmt = optarg;
        break;
      case 'v':
        verbose = true;
        break;

      case '?':
        return 1;
      default:
        return 1;
    }
  }

  if (optind < argc) {
    format = argv[optind++];
  } else {
    fprintf(stderr, "error: missing format string (use -h for help)\n");
    return 1;
  }

  while (optind < argc) {
    targets = alpm_list_add(targets, argv[optind++]);
  }

  return 0;
}

static int print_escaped(const char *delim) {
  const char *f;
  int out = 0;

  for (f = delim; *f != '\0'; f++) {
    if (*f == '\\') {
      switch (*++f) {
        case '\\':
          putchar('\\');
          break;
        case '"':
          putchar('\"');
          break;
        case 'a':
          putchar('\a');
          break;
        case 'b':
          putchar('\b');
          break;
        case 'e': /* \e is nonstandard */
          putchar('\033');
          break;
        case 'n':
          putchar('\n');
          break;
        case 'r':
          putchar('\r');
          break;
        case 't':
          putchar('\t');
          break;
        case 'v':
          putchar('\v');
          break;
        case '0':
          putchar('\0');
          break;
        ++out;
      }
    } else {
      putchar(*f);
      ++out;
    }
  }

  return out;
}

static int print_list(alpm_list_t *list, extractfn fn, bool shortdeps) {
  alpm_list_t *i;
  int out = 0;

  if (!list) {
    if (verbose) {
      out += printf("None");
    }
    return out;
  }

  i = list;
  while (1) {
    char *item;

    item = (char*)(fn ? fn(i->data) : i->data);

    if (shortdeps) {
      *(item + strcspn(item, "<>=")) = '\0';
    }

    out += printf("%s", item);

    if ((i = alpm_list_next(i))) {
      out += print_escaped(listdelim);
    } else {
      break;
    }
  }

  return out;
}

static int print_time(time_t timestamp) {
  char buffer[64];
  int out = 0;

  if (!timestamp) {
    if (verbose) {
      out += printf("None");
    }
    return out;
  }

  /* no overflow here, strftime prints a max of 64 including null */
  strftime(&buffer[0], 64, timefmt, localtime(&timestamp));
  out += printf("%s", buffer);

  return out;
}

static int print_filelist(alpm_filelist_t *filelist) {
  int out = 0;
  size_t i;

  for (i = 0; i < filelist->count; i++) {
    out += printf("%s", (filelist->files + i)->name);
    out += print_escaped(listdelim);
  }

  return out;
}

static int print_pkg(alpm_pkg_t *pkg, const char *format) {
  const char *f, *end;
  char fmt[64], buf[64];
  int len, out = 0;

  end = rawmemchr(format, '\0');

  for (f = format; f < end; f++) {
    bool shortdeps = false;
    len = 0;
    if (*f == '%') {
      len = strspn(f + 1 + len, printf_flags);
      len += strspn(f + 1 + len, digits);
      snprintf(fmt, len + 3, "%ss", f);
      fmt[len + 1] = 's';
      f += len + 1;
      switch (*f) {
        /* simple attributes */
        case 'f': /* filename */
          out += printf(fmt, alpm_pkg_get_filename(pkg));
          break;
        case 'n': /* package name */
          out += printf(fmt, alpm_pkg_get_name(pkg));
          break;
        case 'v': /* version */
          out += printf(fmt, alpm_pkg_get_version(pkg));
          break;
        case 'd': /* description */
          out += printf(fmt, alpm_pkg_get_desc(pkg));
          break;
        case 'u': /* project url */
          out += printf(fmt, alpm_pkg_get_url(pkg));
          break;
        case 'p': /* packager name */
          out += printf(fmt, alpm_pkg_get_packager(pkg));
          break;
        case 's': /* md5sum */
          out += printf(fmt, alpm_pkg_get_md5sum(pkg));
          break;
        case 'a': /* architecutre */
          out += printf(fmt, alpm_pkg_get_arch(pkg));
          break;
        case 'i': /* has install scriptlet? */
          out += printf(fmt, alpm_pkg_has_scriptlet(pkg) ? "yes" : "no");
          break;
        case 'r': /* repo */
          out += printf(fmt, alpm_db_get_name(alpm_pkg_get_db(pkg)));
          break;
        case 'w': /* install reason */
          out += printf(fmt, alpm_pkg_get_reason(pkg) ? "dependency" : "explicit");
          break;
        case '!': /* result number */
          snprintf(buf, sizeof(buf), "%d", pkgcounter++);
          out += printf(fmt, buf);
          break;
        case 'g': /* base64 gpg sig */
          out += printf(fmt, alpm_pkg_get_base64_sig(pkg));
          break;
        case 'h': /* sha256sum */
          out += printf(fmt, alpm_pkg_get_sha256sum(pkg));
          break;

        /* times */
        case 'b': /* build date */
          out += print_time(alpm_pkg_get_builddate(pkg));
          break;
        case 'l': /* install date */
          out += print_time(alpm_pkg_get_installdate(pkg));
          break;

        /* sizes */
        case 'k': /* download size */
          out += printf(fmt, size_to_string(alpm_pkg_get_size(pkg)));
          break;
        case 'm': /* install size */
          out += printf(fmt, size_to_string(alpm_pkg_get_isize(pkg)));
          break;

        /* lists */
        case 'F': /* files */
          out += print_filelist(alpm_pkg_get_files(pkg));
          break;
        case 'N': /* requiredby */
          out += print_list(alpm_pkg_compute_requiredby(pkg), NULL, shortdeps);
          break;
        case 'L': /* licenses */
          out += print_list(alpm_pkg_get_licenses(pkg), NULL, shortdeps);
          break;
        case 'G': /* groups */
          out += print_list(alpm_pkg_get_groups(pkg), NULL, shortdeps);
          break;
        case 'E': /* depends (shortdeps) */
          out += print_list(alpm_pkg_get_depends(pkg), (extractfn)alpm_dep_get_name, shortdeps);
          break;
        case 'D': /* depends */
          out += print_list(alpm_pkg_get_depends(pkg), (extractfn)alpm_dep_compute_string, shortdeps);
          break;
        case 'O': /* optdepends */
          out += print_list(alpm_pkg_get_optdepends(pkg), NULL, shortdeps);
          break;
        case 'o': /* optdepends (shortdeps) */
          out += print_list(alpm_pkg_get_optdepends(pkg), (extractfn)trim_optdep, shortdeps);
          break;
        case 'C': /* conflicts */
          out += print_list(alpm_pkg_get_conflicts(pkg), NULL, shortdeps);
          break;
        case 'S': /* provides (shortdeps) */
          shortdeps = true;
        case 'P': /* provides */
          out += print_list(alpm_pkg_get_provides(pkg), NULL, shortdeps);
          break;
        case 'R': /* replaces */
          out += print_list(alpm_pkg_get_replaces(pkg), NULL, shortdeps);
          break;
        case 'B': /* backup */
          out += print_list(alpm_pkg_get_backup(pkg), NULL, shortdeps);
          break;
        case '%':
          putchar('%');
          out++;
          break;
        default:
          putchar('?');
          out++;
          break;
      }
    } else if (*f == '\\') {
      char buf[3]; /* its not safe to do this in a single sprintf */
      buf[0] = *f;
      buf[1] = *++f;
      buf[2] = '\0';
      out += print_escaped(buf);
    } else {
      putchar(*f);
      out++;
    }
  }

  /* only print a delimeter if any package data was outputted */
  if (out > 0) {
    print_escaped(delim);
  }

  return !out;
}

static alpm_list_t *resolve_pkg(alpm_list_t *targets) {
  char *pkgname, *reponame;
  alpm_list_t *t, *r, *ret = NULL;

  if (!targets) {
    for (r = dblist; r; r = alpm_list_next(r)) {
      /* joining causes corruption on alpm_release(), so we copy */
      ret = alpm_list_join(ret, alpm_list_copy(alpm_db_get_pkgcache(r->data)));
    }
  } else if (search) {
    for (r = dblist; r; r = alpm_list_next(r)) {
      ret = alpm_list_join(ret, alpm_db_search(r->data, targets));
    }
  } else if (groups) {
    for (t = targets; t; t = alpm_list_next(t)) {
      for (r = dblist; r; r = alpm_list_next(r)) {
        alpm_group_t *grp = alpm_db_readgroup(r->data, t->data);
        if (grp) {
          ret = alpm_list_join(ret, alpm_list_copy(grp->packages));
        }
      }
    }
  } else {
    for (t = targets; t; t = alpm_list_next(t)) {
      alpm_pkg_t *pkg = NULL;
      int found = 0;

      pkgname = reponame = t->data;
      if (strchr(pkgname, '/')) {
        strsep(&pkgname, "/");
      } else {
        reponame = NULL;
      }

      for (r = dblist; r; r = alpm_list_next(r)) {
        alpm_db_t *repo = r->data;

        if (reponame && strcmp(reponame, alpm_db_get_name(repo)) != 0) {
          continue;
        }

        if (!(pkg = alpm_db_get_pkg(repo, pkgname)) &&
            !(pkg = alpm_find_satisfier(alpm_db_get_pkgcache(repo), pkgname))) {
          continue;
        }

        found = 1;
        ret = alpm_list_add(ret, pkg);
        if (readone) {
          break;
        }
      }
      if (!found && verbose) {
        fprintf(stderr, "error: package `%s' not found\n", pkgname);
      }
    }
  }

  return ret;
}

int main(int argc, char *argv[]) {
  int ret = 1;
  alpm_handle_t *handle;
  alpm_list_t *results = NULL, *i;

  handle = alpm_init();
  if (!handle) {
    return ret;
  }

  ret = parse_options(argc, argv, handle);
  if (ret != 0) {
    goto finish;
  }

  /* ensure sane defaults */
  if (!dblist && !localpkg) {
    local = true;
    dblist = alpm_list_add(dblist, db_local);
  }

  delim = delim ? delim : DEFAULT_DELIM;
  listdelim = listdelim ? listdelim : DEFAULT_LISTDELIM;
  timefmt = timefmt ? timefmt : DEFAULT_TIMEFMT;

  if (localpkg) {
    /* load each target as a package */
    for (i = targets; i; i = alpm_list_next(i)) {
      alpm_pkg_t *pkg;
      int err;

      err = alpm_pkg_load(handle, i->data, 0,
          ALPM_SIG_PACKAGE|ALPM_SIG_PACKAGE_OPTIONAL, &pkg);
      if (err) {
        fprintf(stderr, "error: %s: %s\n", (const char*)i->data,
            alpm_strerror(alpm_errno(handle)));
        continue;
      }
      results = alpm_list_add(results, pkg);
    }
  } else {
    results = resolve_pkg(targets);
    if (!results) {
      ret = 1;
      goto finish;
    }
  }

  for (i = results; i; i = alpm_list_next(i)) {
    alpm_pkg_t *pkg = i->data;
    ret += print_pkg(pkg, format);
  }
  ret = !!ret; /* clamp to zero/one */

  if(localpkg) {
    alpm_list_free_inner(results, (alpm_list_fn_free)alpm_pkg_free);
  }
  alpm_list_free(results);

finish:
  alpm_list_free(dblist);
  alpm_list_free(targets);
  alpm_release(handle);
  return ret;
}