Various tweaks to support building with excessive GCC warning flags
[pacman-ng.git] / src / pacman / pacman.c
blob73d5be94ba3976aa60eab08aa7ec2c56a4b3c2a7
1 /*
2 * pacman.c
4 * Copyright (c) 2006-2012 Pacman Development Team <pacman-dev@archlinux.org>
5 * Copyright (c) 2002-2006 by Judd Vinet <jvinet@zeroflux.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 /* special handling of package version for GIT */
22 #if defined(GIT_VERSION)
23 #undef PACKAGE_VERSION
24 #define PACKAGE_VERSION GIT_VERSION
25 #endif
27 #include <ctype.h> /* isspace */
28 #include <stdlib.h> /* atoi */
29 #include <stdio.h>
30 #include <ctype.h> /* isspace */
31 #include <limits.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <signal.h>
35 #include <unistd.h>
36 #include <sys/types.h>
37 #include <sys/utsname.h> /* uname */
38 #include <locale.h> /* setlocale */
39 #include <errno.h>
41 /* alpm */
42 #include <alpm.h>
43 #include <alpm_list.h>
45 /* pacman */
46 #include "pacman.h"
47 #include "util.h"
48 #include "conf.h"
50 /* list of targets specified on command line */
51 static alpm_list_t *pm_targets;
53 /* Used to sort the options in --help */
54 static int options_cmp(const void *p1, const void *p2)
56 const char *s1 = p1;
57 const char *s2 = p2;
59 if(s1 == s2) return 0;
60 if(!s1) return -1;
61 if(!s2) return 1;
62 /* First skip all spaces in both strings */
63 while(isspace((unsigned char)*s1)) {
64 s1++;
66 while(isspace((unsigned char)*s2)) {
67 s2++;
69 /* If we compare a long option (--abcd) and a short one (-a),
70 * the short one always wins */
71 if(*s1 == '-' && *s2 == '-') {
72 s1++;
73 s2++;
74 if(*s1 == '-' && *s2 == '-') {
75 /* two long -> strcmp */
76 s1++;
77 s2++;
78 } else if(*s2 == '-') {
79 /* s1 short, s2 long */
80 return -1;
81 } else if(*s1 == '-') {
82 /* s1 long, s2 short */
83 return 1;
85 /* two short -> strcmp */
88 return strcmp(s1, s2);
91 /** Display usage/syntax for the specified operation.
92 * @param op the operation code requested
93 * @param myname basename(argv[0])
95 static void usage(int op, const char * const myname)
97 #define addlist(s) (list = alpm_list_add(list, s))
98 alpm_list_t *list = NULL, *i;
99 /* prefetch some strings for usage below, which moves a lot of calls
100 * out of gettext. */
101 char const * const str_opt = _("options");
102 char const * const str_file = _("file(s)");
103 char const * const str_pkg = _("package(s)");
104 char const * const str_usg = _("usage");
105 char const * const str_opr = _("operation");
107 /* please limit your strings to 80 characters in width */
108 if(op == PM_OP_MAIN) {
109 printf("%s: %s <%s> [...]\n", str_usg, myname, str_opr);
110 printf(_("operations:\n"));
111 printf(" %s {-h --help}\n", myname);
112 printf(" %s {-V --version}\n", myname);
113 printf(" %s {-D --database} <%s> <%s>\n", myname, str_opt, str_pkg);
114 printf(" %s {-Q --query} [%s] [%s]\n", myname, str_opt, str_pkg);
115 printf(" %s {-R --remove} [%s] <%s>\n", myname, str_opt, str_pkg);
116 printf(" %s {-S --sync} [%s] [%s]\n", myname, str_opt, str_pkg);
117 printf(" %s {-T --deptest} [%s] [%s]\n", myname, str_opt, str_pkg);
118 printf(" %s {-U --upgrade} [%s] <%s>\n", myname, str_opt, str_file);
119 printf(_("\nuse '%s {-h --help}' with an operation for available options\n"),
120 myname);
121 } else {
122 if(op == PM_OP_REMOVE) {
123 printf("%s: %s {-R --remove} [%s] <%s>\n", str_usg, myname, str_opt, str_pkg);
124 printf("%s:\n", str_opt);
125 addlist(_(" -c, --cascade remove packages and all packages that depend on them\n"));
126 addlist(_(" -n, --nosave remove configuration files\n"));
127 addlist(_(" -s, --recursive remove unnecessary dependencies\n"
128 " (-ss includes explicitly installed dependencies)\n"));
129 addlist(_(" -u, --unneeded remove unneeded packages\n"));
130 } else if(op == PM_OP_UPGRADE) {
131 printf("%s: %s {-U --upgrade} [%s] <%s>\n", str_usg, myname, str_opt, str_file);
132 addlist(_(" --needed do not reinstall up to date packages\n"));
133 printf("%s:\n", str_opt);
134 } else if(op == PM_OP_QUERY) {
135 printf("%s: %s {-Q --query} [%s] [%s]\n", str_usg, myname, str_opt, str_pkg);
136 printf("%s:\n", str_opt);
137 addlist(_(" -c, --changelog view the changelog of a package\n"));
138 addlist(_(" -d, --deps list packages installed as dependencies [filter]\n"));
139 addlist(_(" -e, --explicit list packages explicitly installed [filter]\n"));
140 addlist(_(" -g, --groups view all members of a package group\n"));
141 addlist(_(" -i, --info view package information (-ii for backup files)\n"));
142 addlist(_(" -k, --check check that the files owned by the package(s) are present\n"));
143 addlist(_(" -l, --list list the contents of the queried package\n"));
144 addlist(_(" -m, --foreign list installed packages not found in sync db(s) [filter]\n"));
145 addlist(_(" -o, --owns <file> query the package that owns <file>\n"));
146 addlist(_(" -p, --file <package> query a package file instead of the database\n"));
147 addlist(_(" -q, --quiet show less information for query and search\n"));
148 addlist(_(" -s, --search <regex> search locally-installed packages for matching strings\n"));
149 addlist(_(" -t, --unrequired list packages not required by any package [filter]\n"));
150 addlist(_(" -u, --upgrades list outdated packages [filter]\n"));
151 } else if(op == PM_OP_SYNC) {
152 printf("%s: %s {-S --sync} [%s] [%s]\n", str_usg, myname, str_opt, str_pkg);
153 printf("%s:\n", str_opt);
154 addlist(_(" -c, --clean remove old packages from cache directory (-cc for all)\n"));
155 addlist(_(" -g, --groups view all members of a package group\n"));
156 addlist(_(" -i, --info view package information\n"));
157 addlist(_(" -l, --list <repo> view a list of packages in a repo\n"));
158 addlist(_(" -q, --quiet show less information for query and search\n"));
159 addlist(_(" -s, --search <regex> search remote repositories for matching strings\n"));
160 addlist(_(" -u, --sysupgrade upgrade installed packages (-uu allows downgrade)\n"));
161 addlist(_(" -w, --downloadonly download packages but do not install/upgrade anything\n"));
162 addlist(_(" -y, --refresh download fresh package databases from the server\n"));
163 addlist(_(" --needed do not reinstall up to date packages\n"));
164 } else if(op == PM_OP_DATABASE) {
165 printf("%s: %s {-D --database} <%s> <%s>\n", str_usg, myname, str_opt, str_pkg);
166 printf("%s:\n", str_opt);
167 addlist(_(" --asdeps mark packages as non-explicitly installed\n"));
168 addlist(_(" --asexplicit mark packages as explicitly installed\n"));
169 } else if(op == PM_OP_DEPTEST) {
170 printf("%s: %s {-T --deptest} [%s] [%s]\n", str_usg, myname, str_opt, str_pkg);
171 printf("%s:\n", str_opt);
173 switch(op) {
174 case PM_OP_SYNC:
175 case PM_OP_UPGRADE:
176 addlist(_(" --force force install, overwrite conflicting files\n"));
177 addlist(_(" --asdeps install packages as non-explicitly installed\n"));
178 addlist(_(" --asexplicit install packages as explicitly installed\n"));
179 addlist(_(" --ignore <pkg> ignore a package upgrade (can be used more than once)\n"));
180 addlist(_(" --ignoregroup <grp>\n"
181 " ignore a group upgrade (can be used more than once)\n"));
182 /* pass through */
183 case PM_OP_REMOVE:
184 addlist(_(" -d, --nodeps skip dependency version checks (-dd to skip all checks)\n"));
185 addlist(_(" --dbonly only modify database entries, not package files\n"));
186 addlist(_(" --noprogressbar do not show a progress bar when downloading files\n"));
187 addlist(_(" --noscriptlet do not execute the install scriptlet if one exists\n"));
188 addlist(_(" -p, --print print the targets instead of performing the operation\n"));
189 addlist(_(" --print-format <string>\n"
190 " specify how the targets should be printed\n"));
191 break;
194 addlist(_(" -b, --dbpath <path> set an alternate database location\n"));
195 addlist(_(" -r, --root <path> set an alternate installation root\n"));
196 addlist(_(" -v, --verbose be verbose\n"));
197 addlist(_(" --arch <arch> set an alternate architecture\n"));
198 addlist(_(" --cachedir <dir> set an alternate package cache location\n"));
199 addlist(_(" --config <path> set an alternate configuration file\n"));
200 addlist(_(" --debug display debug messages\n"));
201 addlist(_(" --gpgdir <path> set an alternate home directory for GnuPG\n"));
202 addlist(_(" --logfile <path> set an alternate log file\n"));
203 addlist(_(" --noconfirm do not ask for any confirmation\n"));
205 list = alpm_list_msort(list, alpm_list_count(list), options_cmp);
206 for(i = list; i; i = alpm_list_next(i)) {
207 fputs((const char *)i->data, stdout);
209 alpm_list_free(list);
210 #undef addlist
213 /** Output pacman version and copyright.
215 static void version(void)
217 printf("\n");
218 printf(" .--. Pacman v%s - libalpm v%s\n", PACKAGE_VERSION, alpm_version());
219 printf("/ _.-' .-. .-. .-. Copyright (C) 2006-2012 Pacman Development Team\n");
220 printf("\\ '-. '-' '-' '-' Copyright (C) 2002-2006 Judd Vinet\n");
221 printf(" '--'\n");
222 printf(_(" This program may be freely redistributed under\n"
223 " the terms of the GNU General Public License.\n"));
224 printf("\n");
227 /** Sets up gettext localization. Safe to call multiple times.
229 /* Inspired by the monotone function localize_monotone. */
230 #if defined(ENABLE_NLS)
231 static void localize(void)
233 static int init = 0;
234 if(!init) {
235 setlocale(LC_ALL, "");
236 bindtextdomain(PACKAGE, LOCALEDIR);
237 textdomain(PACKAGE);
238 init = 1;
241 #endif
243 /** Set user agent environment variable.
245 static void setuseragent(void)
247 char agent[101];
248 struct utsname un;
250 uname(&un);
251 snprintf(agent, 100, "pacman/%s (%s %s) libalpm/%s",
252 PACKAGE_VERSION, un.sysname, un.machine, alpm_version());
253 setenv("HTTP_USER_AGENT", agent, 0);
256 /** Free the resources.
258 * @param ret the return value
260 static void cleanup(int ret) {
261 /* free alpm library resources */
262 if(config->handle && alpm_release(config->handle) == -1) {
263 pm_printf(ALPM_LOG_ERROR, "error releasing alpm library\n");
266 /* free memory */
267 FREELIST(pm_targets);
268 if(config) {
269 config_free(config);
270 config = NULL;
273 exit(ret);
276 /** Write function that correctly handles EINTR.
278 static ssize_t xwrite(int fd, const void *buf, size_t count)
280 ssize_t ret;
281 do {
282 ret = write(fd, buf, count);
283 } while(ret == -1 && errno == EINTR);
284 return ret;
287 /** Catches thrown signals. Performs necessary cleanup to ensure database is
288 * in a consistant state.
289 * @param signum the thrown signal
291 static void handler(int signum)
293 int out = fileno(stdout);
294 int err = fileno(stderr);
295 const char *msg;
296 if(signum == SIGSEGV) {
297 msg = "\nerror: segmentation fault\n"
298 "Please submit a full bug report with --debug if appropriate.\n";
299 xwrite(err, msg, strlen(msg));
300 exit(signum);
301 } else if(signum == SIGINT || signum == SIGHUP) {
302 if(signum == SIGINT) {
303 msg = "\nInterrupt signal received\n";
304 } else {
305 msg = "\nHangup signal received\n";
307 xwrite(err, msg, strlen(msg));
308 if(alpm_trans_interrupt(config->handle) == 0) {
309 /* a transaction is being interrupted, don't exit pacman yet. */
310 return;
313 /* SIGINT: no commiting transaction, release it now and then exit pacman
314 * SIGHUP, SIGTERM: release no matter what */
315 alpm_trans_release(config->handle);
316 /* output a newline to be sure we clear any line we may be on */
317 xwrite(out, "\n", 1);
318 cleanup(128 + signum);
321 #define check_optarg() if(!optarg) { return 1; }
323 static int parsearg_util_addlist(alpm_list_t **list)
325 alpm_list_t *split, *item;
327 check_optarg();
328 split = strsplit(optarg, ',');
329 for(item = split; item; item = alpm_list_next(item)) {
330 *list = alpm_list_add(*list, item->data);
332 alpm_list_free(split);
333 return 0;
336 /** Helper function for parsing operation from command-line arguments.
337 * @param opt Keycode returned by getopt_long
338 * @param dryrun If nonzero, application state is NOT changed
339 * @return 0 if opt was handled, 1 if it was not handled
341 static int parsearg_op(int opt, int dryrun)
343 switch(opt) {
344 /* operations */
345 case 'D':
346 if(dryrun) break;
347 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DATABASE); break;
348 case 'Q':
349 if(dryrun) break;
350 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_QUERY); break;
351 case 'R':
352 if(dryrun) break;
353 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_REMOVE); break;
354 case 'S':
355 if(dryrun) break;
356 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_SYNC); break;
357 case 'T':
358 if(dryrun) break;
359 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DEPTEST); break;
360 case 'U':
361 if(dryrun) break;
362 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_UPGRADE); break;
363 case 'V':
364 if(dryrun) break;
365 config->version = 1; break;
366 case 'h':
367 if(dryrun) break;
368 config->help = 1; break;
369 default:
370 return 1;
372 return 0;
375 /** Helper functions for parsing command-line arguments.
376 * @param opt Keycode returned by getopt_long
377 * @return 0 on success, 1 on failure
379 static int parsearg_global(int opt)
381 switch(opt) {
382 case OP_ARCH:
383 check_optarg();
384 config_set_arch(optarg);
385 break;
386 case OP_ASK:
387 check_optarg();
388 config->noask = 1;
389 config->ask = (unsigned int)atoi(optarg);
390 break;
391 case OP_CACHEDIR:
392 check_optarg();
393 config->cachedirs = alpm_list_add(config->cachedirs, strdup(optarg));
394 break;
395 case OP_CONFIG:
396 check_optarg();
397 if(config->configfile) {
398 free(config->configfile);
400 config->configfile = strndup(optarg, PATH_MAX);
401 break;
402 case OP_DEBUG:
403 /* debug levels are made more 'human readable' than using a raw logmask
404 * here, error and warning are set in config_new, though perhaps a
405 * --quiet option will remove these later */
406 if(optarg) {
407 unsigned short debug = (unsigned short)atoi(optarg);
408 switch(debug) {
409 case 2:
410 config->logmask |= ALPM_LOG_FUNCTION; /* fall through */
411 case 1:
412 config->logmask |= ALPM_LOG_DEBUG;
413 break;
414 default:
415 pm_printf(ALPM_LOG_ERROR, _("'%s' is not a valid debug level\n"),
416 optarg);
417 return 1;
419 } else {
420 config->logmask |= ALPM_LOG_DEBUG;
422 /* progress bars get wonky with debug on, shut them off */
423 config->noprogressbar = 1;
424 break;
425 case OP_GPGDIR:
426 config->gpgdir = strdup(optarg);
427 break;
428 case OP_LOGFILE:
429 check_optarg();
430 config->logfile = strndup(optarg, PATH_MAX);
431 break;
432 case OP_NOCONFIRM: config->noconfirm = 1; break;
433 case 'b':
434 check_optarg();
435 config->dbpath = strdup(optarg);
436 break;
437 case 'r': check_optarg(); config->rootdir = strdup(optarg); break;
438 case 'v': (config->verbose)++; break;
439 default: return 1;
441 return 0;
444 static int parsearg_database(int opt)
446 switch(opt) {
447 case OP_ASDEPS: config->flags |= ALPM_TRANS_FLAG_ALLDEPS; break;
448 case OP_ASEXPLICIT: config->flags |= ALPM_TRANS_FLAG_ALLEXPLICIT; break;
449 default: return 1;
451 return 0;
454 static int parsearg_query(int opt)
456 switch(opt) {
457 case 'c': config->op_q_changelog = 1; break;
458 case 'd': config->op_q_deps = 1; break;
459 case 'e': config->op_q_explicit = 1; break;
460 case 'g': (config->group)++; break;
461 case 'i': (config->op_q_info)++; break;
462 case 'k': config->op_q_check = 1; break;
463 case 'l': config->op_q_list = 1; break;
464 case 'm': config->op_q_foreign = 1; break;
465 case 'o': config->op_q_owns = 1; break;
466 case 'p': config->op_q_isfile = 1; break;
467 case 'q': config->quiet = 1; break;
468 case 's': config->op_q_search = 1; break;
469 case 't': config->op_q_unrequired = 1; break;
470 case 'u': config->op_q_upgrade = 1; break;
471 default: return 1;
473 return 0;
476 /* options common to -S -R -U */
477 static int parsearg_trans(int opt)
479 switch(opt) {
480 case 'd':
481 if(config->flags & ALPM_TRANS_FLAG_NODEPVERSION) {
482 config->flags |= ALPM_TRANS_FLAG_NODEPS;
483 } else {
484 config->flags |= ALPM_TRANS_FLAG_NODEPVERSION;
486 break;
487 case OP_DBONLY: config->flags |= ALPM_TRANS_FLAG_DBONLY; break;
488 case OP_NOPROGRESSBAR: config->noprogressbar = 1; break;
489 case OP_NOSCRIPTLET: config->flags |= ALPM_TRANS_FLAG_NOSCRIPTLET; break;
490 case 'p': config->print = 1; break;
491 case OP_PRINTFORMAT:
492 check_optarg();
493 config->print_format = strdup(optarg);
494 break;
495 default: return 1;
497 return 0;
500 static int parsearg_remove(int opt)
502 if(parsearg_trans(opt) == 0)
503 return 0;
504 switch(opt) {
505 case 'c': config->flags |= ALPM_TRANS_FLAG_CASCADE; break;
506 case 'n': config->flags |= ALPM_TRANS_FLAG_NOSAVE; break;
507 case 's':
508 if(config->flags & ALPM_TRANS_FLAG_RECURSE) {
509 config->flags |= ALPM_TRANS_FLAG_RECURSEALL;
510 } else {
511 config->flags |= ALPM_TRANS_FLAG_RECURSE;
513 break;
514 case 'u': config->flags |= ALPM_TRANS_FLAG_UNNEEDED; break;
515 default: return 1;
517 return 0;
520 /* options common to -S -U */
521 static int parsearg_upgrade(int opt)
523 if(parsearg_trans(opt) == 0)
524 return 0;
525 switch(opt) {
526 case OP_FORCE: config->flags |= ALPM_TRANS_FLAG_FORCE; break;
527 case OP_ASDEPS: config->flags |= ALPM_TRANS_FLAG_ALLDEPS; break;
528 case OP_ASEXPLICIT: config->flags |= ALPM_TRANS_FLAG_ALLEXPLICIT; break;
529 case OP_NEEDED: config->flags |= ALPM_TRANS_FLAG_NEEDED; break;
530 case OP_IGNORE:
531 parsearg_util_addlist(&(config->ignorepkg));
532 break;
533 case OP_IGNOREGROUP:
534 parsearg_util_addlist(&(config->ignoregrp));
535 break;
536 default: return 1;
538 return 0;
541 static int parsearg_sync(int opt)
543 if(parsearg_upgrade(opt) == 0)
544 return 0;
545 switch(opt) {
546 case 'c': (config->op_s_clean)++; break;
547 case 'g': (config->group)++; break;
548 case 'i': (config->op_s_info)++; break;
549 case 'l': config->op_q_list = 1; break;
550 case 'q': config->quiet = 1; break;
551 case 's': config->op_s_search = 1; break;
552 case 'u': (config->op_s_upgrade)++; break;
553 case 'w':
554 config->op_s_downloadonly = 1;
555 config->flags |= ALPM_TRANS_FLAG_DOWNLOADONLY;
556 config->flags |= ALPM_TRANS_FLAG_NOCONFLICTS;
557 break;
558 case 'y': (config->op_s_sync)++; break;
559 default: return 1;
561 return 0;
564 /** Parse command-line arguments for each operation.
565 * @param argc argc
566 * @param argv argv
567 * @return 0 on success, 1 on error
569 static int parseargs(int argc, char *argv[])
571 int opt;
572 int option_index = 0;
573 int result;
574 const char *optstring = "DQRSTUVb:cdefghiklmnopqr:stuvwy";
575 static const struct option opts[] =
577 {"database", no_argument, 0, 'D'},
578 {"query", no_argument, 0, 'Q'},
579 {"remove", no_argument, 0, 'R'},
580 {"sync", no_argument, 0, 'S'},
581 {"deptest", no_argument, 0, 'T'}, /* used by makepkg */
582 {"upgrade", no_argument, 0, 'U'},
583 {"version", no_argument, 0, 'V'},
584 {"dbpath", required_argument, 0, 'b'},
585 {"cascade", no_argument, 0, 'c'},
586 {"changelog", no_argument, 0, 'c'},
587 {"clean", no_argument, 0, 'c'},
588 {"nodeps", no_argument, 0, 'd'},
589 {"deps", no_argument, 0, 'd'},
590 {"explicit", no_argument, 0, 'e'},
591 {"groups", no_argument, 0, 'g'},
592 {"help", no_argument, 0, 'h'},
593 {"info", no_argument, 0, 'i'},
594 {"check", no_argument, 0, 'k'},
595 {"list", no_argument, 0, 'l'},
596 {"foreign", no_argument, 0, 'm'},
597 {"nosave", no_argument, 0, 'n'},
598 {"owns", no_argument, 0, 'o'},
599 {"file", no_argument, 0, 'p'},
600 {"print", no_argument, 0, 'p'},
601 {"quiet", no_argument, 0, 'q'},
602 {"root", required_argument, 0, 'r'},
603 {"recursive", no_argument, 0, 's'},
604 {"search", no_argument, 0, 's'},
605 {"unrequired", no_argument, 0, 't'},
606 {"upgrades", no_argument, 0, 'u'},
607 {"sysupgrade", no_argument, 0, 'u'},
608 {"unneeded", no_argument, 0, 'u'},
609 {"verbose", no_argument, 0, 'v'},
610 {"downloadonly", no_argument, 0, 'w'},
611 {"refresh", no_argument, 0, 'y'},
613 {"noconfirm", no_argument, 0, OP_NOCONFIRM},
614 {"config", required_argument, 0, OP_CONFIG},
615 {"ignore", required_argument, 0, OP_IGNORE},
616 {"debug", optional_argument, 0, OP_DEBUG},
617 {"force", no_argument, 0, OP_FORCE},
618 {"noprogressbar", no_argument, 0, OP_NOPROGRESSBAR},
619 {"noscriptlet", no_argument, 0, OP_NOSCRIPTLET},
620 {"ask", required_argument, 0, OP_ASK},
621 {"cachedir", required_argument, 0, OP_CACHEDIR},
622 {"asdeps", no_argument, 0, OP_ASDEPS},
623 {"logfile", required_argument, 0, OP_LOGFILE},
624 {"ignoregroup", required_argument, 0, OP_IGNOREGROUP},
625 {"needed", no_argument, 0, OP_NEEDED},
626 {"asexplicit", no_argument, 0, OP_ASEXPLICIT},
627 {"arch", required_argument, 0, OP_ARCH},
628 {"print-format", required_argument, 0, OP_PRINTFORMAT},
629 {"gpgdir", required_argument, 0, OP_GPGDIR},
630 {"dbonly", no_argument, 0, OP_DBONLY},
631 {0, 0, 0, 0}
634 /* parse operation */
635 while((opt = getopt_long(argc, argv, optstring, opts, &option_index))) {
636 if(opt < 0) {
637 break;
638 } else if(opt == 0) {
639 continue;
640 } else if(opt == '?') {
641 /* unknown option, getopt printed an error */
642 return 1;
644 parsearg_op(opt, 0);
647 if(config->op == 0) {
648 pm_printf(ALPM_LOG_ERROR, _("only one operation may be used at a time\n"));
649 return 1;
651 if(config->help) {
652 usage(config->op, mbasename(argv[0]));
653 return 2;
655 if(config->version) {
656 version();
657 return 2;
660 /* parse all other options */
661 optind = 1;
662 while((opt = getopt_long(argc, argv, optstring, opts, &option_index))) {
663 if(opt < 0) {
664 break;
665 } else if(opt == 0) {
666 continue;
667 } else if(opt == '?') {
668 /* this should have failed during first pass already */
669 return 1;
670 } else if(parsearg_op(opt, 1) == 0) {
671 /* opt is an operation */
672 continue;
675 switch(config->op) {
676 case PM_OP_DATABASE:
677 result = parsearg_database(opt);
678 break;
679 case PM_OP_QUERY:
680 result = parsearg_query(opt);
681 break;
682 case PM_OP_REMOVE:
683 result = parsearg_remove(opt);
684 break;
685 case PM_OP_SYNC:
686 result = parsearg_sync(opt);
687 break;
688 case PM_OP_UPGRADE:
689 result = parsearg_upgrade(opt);
690 break;
691 case PM_OP_DEPTEST:
692 default:
693 result = 1;
694 break;
696 if(result == 0) {
697 continue;
700 /* fall back to global options */
701 result = parsearg_global(opt);
702 if(result != 0) {
703 /* global option parsing failed, abort */
704 pm_printf(ALPM_LOG_ERROR, _("invalid option\n"));
705 return result;
709 while(optind < argc) {
710 /* add the target to our target array */
711 pm_targets = alpm_list_add(pm_targets, strdup(argv[optind]));
712 optind++;
715 return 0;
718 /** Print command line to logfile.
719 * @param argc
720 * @param argv
722 static void cl_to_log(int argc, char* argv[])
724 size_t size = 0;
725 int i;
726 for(i = 0; i < argc; i++) {
727 size += strlen(argv[i]) + 1;
729 if(!size) {
730 return;
732 char *cl_text = malloc(size);
733 if(!cl_text) {
734 return;
736 char *p = cl_text;
737 for(i = 0; i < argc - 1; i++) {
738 strcpy(p, argv[i]);
739 p += strlen(argv[i]);
740 *p++ = ' ';
742 strcpy(p, argv[i]);
743 alpm_logaction(config->handle, "Running '%s'\n", cl_text);
744 free(cl_text);
747 /** Main function.
748 * @param argc
749 * @param argv
750 * @return A return code indicating success, failure, etc.
752 int main(int argc, char *argv[])
754 int ret = 0;
755 size_t i;
756 struct sigaction new_action, old_action;
757 const int signals[] = { SIGHUP, SIGINT, SIGTERM, SIGSEGV };
758 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
759 /* geteuid undefined in CYGWIN */
760 uid_t myuid = geteuid();
761 #endif
763 /* Set signal handlers */
764 /* Set up the structure to specify the new action. */
765 new_action.sa_handler = handler;
766 sigemptyset(&new_action.sa_mask);
767 new_action.sa_flags = 0;
769 /* assign our handler to any signals we care about */
770 for(i = 0; i < sizeof(signals) / sizeof(signals[0]); i++) {
771 int signal = signals[i];
772 sigaction(signal, NULL, &old_action);
773 if(old_action.sa_handler != SIG_IGN) {
774 sigaction(signal, &new_action, NULL);
778 /* i18n init */
779 #if defined(ENABLE_NLS)
780 localize();
781 #endif
783 /* set user agent for downloading */
784 setuseragent();
786 /* init config data */
787 config = config_new();
789 /* disable progressbar if the output is redirected */
790 if(!isatty(fileno(stdout))) {
791 config->noprogressbar = 1;
794 /* Priority of options:
795 * 1. command line
796 * 2. config file
797 * 3. compiled-in defaults
798 * However, we have to parse the command line first because a config file
799 * location can be specified here, so we need to make sure we prefer these
800 * options over the config file coming second.
803 /* parse the command line */
804 ret = parseargs(argc, argv);
805 if(ret != 0) {
806 cleanup(ret);
809 /* we support reading targets from stdin if a cmdline parameter is '-' */
810 if(!isatty(fileno(stdin)) && alpm_list_find_str(pm_targets, "-")) {
811 size_t current_size = PATH_MAX;
812 char *line = malloc(current_size);
814 /* remove the '-' from the list */
815 pm_targets = alpm_list_remove_str(pm_targets, "-", NULL);
817 i = 0;
818 while((line[i] = (char)fgetc(stdin)) != EOF) {
819 if(isspace((unsigned char)line[i])) {
820 /* avoid adding zero length arg when multiple spaces separate args */
821 if(i > 0) {
822 line[i] = '\0';
823 pm_targets = alpm_list_add(pm_targets, strdup(line));
824 i = 0;
826 } else {
827 i++;
828 /* we may be at the end of our allocated buffer now */
829 if(i >= current_size) {
830 char *new = realloc(line, current_size * 2);
831 if(new) {
832 line = new;
833 current_size *= 2;
834 } else {
835 free(line);
836 line = NULL;
837 break;
842 /* check for memory exhaustion */
843 if(!line) {
844 pm_printf(ALPM_LOG_ERROR, _("memory exhausted in argument parsing\n"));
845 cleanup(EXIT_FAILURE);
848 /* end of stream -- check for data still in line buffer */
849 if(i > 0) {
850 line[i] = '\0';
851 pm_targets = alpm_list_add(pm_targets, strdup(line));
853 free(line);
854 if(!freopen(ctermid(NULL), "r", stdin)) {
855 pm_printf(ALPM_LOG_ERROR, _("failed to reopen stdin for reading: (%s)\n"),
856 strerror(errno));
860 /* parse the config file */
861 ret = parseconfig(config->configfile);
862 if(ret != 0) {
863 cleanup(ret);
866 /* noask is meant to be non-interactive */
867 if(config->noask) {
868 config->noconfirm = 1;
871 /* set up the print operations */
872 if(config->print && !config->op_s_clean) {
873 config->noconfirm = 1;
874 config->flags |= ALPM_TRANS_FLAG_NOCONFLICTS;
875 config->flags |= ALPM_TRANS_FLAG_NOLOCK;
876 /* Display only errors */
877 config->logmask &= ~ALPM_LOG_WARNING;
880 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
881 /* check if we have sufficient permission for the requested operation */
882 if(myuid > 0 && needs_root()) {
883 pm_printf(ALPM_LOG_ERROR, _("you cannot perform this operation unless you are root.\n"));
884 cleanup(EXIT_FAILURE);
886 #endif
888 if(config->verbose > 0) {
889 alpm_list_t *j;
890 printf("Root : %s\n", alpm_option_get_root(config->handle));
891 printf("Conf File : %s\n", config->configfile);
892 printf("DB Path : %s\n", alpm_option_get_dbpath(config->handle));
893 printf("Cache Dirs: ");
894 for(j = alpm_option_get_cachedirs(config->handle); j; j = alpm_list_next(j)) {
895 printf("%s ", (const char *)j->data);
897 printf("\n");
898 printf("Lock File : %s\n", alpm_option_get_lockfile(config->handle));
899 printf("Log File : %s\n", alpm_option_get_logfile(config->handle));
900 printf("GPG Dir : %s\n", alpm_option_get_gpgdir(config->handle));
901 list_display("Targets :", pm_targets, 0);
904 /* Log command line */
905 if(needs_root()) {
906 cl_to_log(argc, argv);
909 /* start the requested operation */
910 switch(config->op) {
911 case PM_OP_DATABASE:
912 ret = pacman_database(pm_targets);
913 break;
914 case PM_OP_REMOVE:
915 ret = pacman_remove(pm_targets);
916 break;
917 case PM_OP_UPGRADE:
918 ret = pacman_upgrade(pm_targets);
919 break;
920 case PM_OP_QUERY:
921 ret = pacman_query(pm_targets);
922 break;
923 case PM_OP_SYNC:
924 ret = pacman_sync(pm_targets);
925 break;
926 case PM_OP_DEPTEST:
927 ret = pacman_deptest(pm_targets);
928 break;
929 default:
930 pm_printf(ALPM_LOG_ERROR, _("no operation specified (use -h for help)\n"));
931 ret = EXIT_FAILURE;
934 cleanup(ret);
935 /* not reached */
936 return EXIT_SUCCESS;
939 /* vim: set ts=2 sw=2 noet: */