Improve pkghash_remove algorithm
[pacman-ng.git] / src / pacman / pacman.c
blob984bd1b75deb256f46d3fb8b13a2690dcb6a91fe
1 /*
2 * pacman.c
4 * Copyright (c) 2006-2011 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 #include "config.h"
23 /* special handling of package version for GIT */
24 #if defined(GIT_VERSION)
25 #undef PACKAGE_VERSION
26 #define PACKAGE_VERSION GIT_VERSION
27 #endif
29 #include <ctype.h> /* isspace */
30 #include <stdlib.h> /* atoi */
31 #include <stdio.h>
32 #include <ctype.h> /* isspace */
33 #include <limits.h>
34 #include <getopt.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <unistd.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/utsname.h> /* uname */
41 #include <locale.h> /* setlocale */
42 #include <time.h> /* time_t */
43 #include <errno.h>
44 #include <glob.h>
45 #if defined(PACMAN_DEBUG) && defined(HAVE_MCHECK_H)
46 #include <mcheck.h> /* debug tracing (mtrace) */
47 #endif
49 /* alpm */
50 #include <alpm.h>
51 #include <alpm_list.h>
53 /* pacman */
54 #include "pacman.h"
55 #include "util.h"
56 #include "callback.h"
57 #include "conf.h"
58 #include "package.h"
60 /* list of targets specified on command line */
61 static alpm_list_t *pm_targets;
63 /* Used to sort the options in --help */
64 static int options_cmp(const void *p1, const void *p2)
66 const char *s1 = p1;
67 const char *s2 = p2;
69 if(s1 == s2) return(0);
70 if(!s1) return(-1);
71 if(!s2) return(1);
72 /* First skip all spaces in both strings */
73 while(isspace((unsigned char)*s1)) {
74 s1++;
76 while(isspace((unsigned char)*s2)) {
77 s2++;
79 /* If we compare a long option (--abcd) and a short one (-a),
80 * the short one always wins */
81 if(*s1 == '-' && *s2 == '-') {
82 s1++;
83 s2++;
84 if(*s1 == '-' && *s2 == '-') {
85 /* two long -> strcmp */
86 s1++;
87 s2++;
88 } else if(*s2 == '-') {
89 /* s1 short, s2 long */
90 return(-1);
91 } else if(*s1 == '-') {
92 /* s1 long, s2 short */
93 return(1);
95 /* two short -> strcmp */
98 return(strcmp(s1, s2));
101 /** Display usage/syntax for the specified operation.
102 * @param op the operation code requested
103 * @param myname basename(argv[0])
105 static void usage(int op, const char * const myname)
107 #define addlist(s) (list = alpm_list_add(list, s))
108 alpm_list_t *list = NULL, *i;
109 /* prefetch some strings for usage below, which moves a lot of calls
110 * out of gettext. */
111 char const * const str_opt = _("options");
112 char const * const str_file = _("file(s)");
113 char const * const str_pkg = _("package(s)");
114 char const * const str_usg = _("usage");
115 char const * const str_opr = _("operation");
117 if(op == PM_OP_MAIN) {
118 printf("%s: %s <%s> [...]\n", str_usg, myname, str_opr);
119 printf(_("operations:\n"));
120 printf(" %s {-h --help}\n", myname);
121 printf(" %s {-V --version}\n", myname);
122 printf(" %s {-D --database} <%s> <%s>\n", myname, str_opt, str_pkg);
123 printf(" %s {-Q --query} [%s] [%s]\n", myname, str_opt, str_pkg);
124 printf(" %s {-R --remove} [%s] <%s>\n", myname, str_opt, str_pkg);
125 printf(" %s {-S --sync} [%s] [%s]\n", myname, str_opt, str_pkg);
126 printf(" %s {-U --upgrade} [%s] <%s>\n", myname, str_opt, str_file);
127 printf(_("\nuse '%s {-h --help}' with an operation for available options\n"),
128 myname);
129 } else {
130 if(op == PM_OP_REMOVE) {
131 printf("%s: %s {-R --remove} [%s] <%s>\n", str_usg, myname, str_opt, str_pkg);
132 printf("%s:\n", str_opt);
133 addlist(_(" -c, --cascade remove packages and all packages that depend on them\n"));
134 addlist(_(" -n, --nosave remove configuration files as well\n"));
135 addlist(_(" -s, --recursive remove dependencies also (that won't break packages)\n"
136 " (-ss includes explicitly installed dependencies too)\n"));
137 addlist(_(" -u, --unneeded remove unneeded packages (that won't break packages)\n"));
138 } else if(op == PM_OP_UPGRADE) {
139 printf("%s: %s {-U --upgrade} [%s] <%s>\n", str_usg, myname, str_opt, str_file);
140 printf("%s:\n", str_opt);
141 } else if(op == PM_OP_QUERY) {
142 printf("%s: %s {-Q --query} [%s] [%s]\n", str_usg, myname, str_opt, str_pkg);
143 printf("%s:\n", str_opt);
144 addlist(_(" -c, --changelog view the changelog of a package\n"));
145 addlist(_(" -d, --deps list packages installed as dependencies [filter]\n"));
146 addlist(_(" -e, --explicit list packages explicitly installed [filter]\n"));
147 addlist(_(" -g, --groups view all members of a package group\n"));
148 addlist(_(" -i, --info view package information (-ii for backup files)\n"));
149 addlist(_(" -k, --check check that the files owned by the package(s) are present\n"));
150 addlist(_(" -l, --list list the contents of the queried package\n"));
151 addlist(_(" -m, --foreign list installed packages not found in sync db(s) [filter]\n"));
152 addlist(_(" -o, --owns <file> query the package that owns <file>\n"));
153 addlist(_(" -p, --file <package> query a package file instead of the database\n"));
154 addlist(_(" -q, --quiet show less information for query and search\n"));
155 addlist(_(" -s, --search <regex> search locally-installed packages for matching strings\n"));
156 addlist(_(" -t, --unrequired list packages not required by any package [filter]\n"));
157 addlist(_(" -u, --upgrades list outdated packages [filter]\n"));
158 } else if(op == PM_OP_SYNC) {
159 printf("%s: %s {-S --sync} [%s] [%s]\n", str_usg, myname, str_opt, str_pkg);
160 printf("%s:\n", str_opt);
161 addlist(_(" -c, --clean remove old packages from cache directory (-cc for all)\n"));
162 addlist(_(" -g, --groups view all members of a package group\n"));
163 addlist(_(" -i, --info view package information\n"));
164 addlist(_(" -l, --list <repo> view a list of packages in a repo\n"));
165 addlist(_(" -q, --quiet show less information for query and search\n"));
166 addlist(_(" -s, --search <regex> search remote repositories for matching strings\n"));
167 addlist(_(" -u, --sysupgrade upgrade installed packages (-uu allows downgrade)\n"));
168 addlist(_(" -w, --downloadonly download packages but do not install/upgrade anything\n"));
169 addlist(_(" -y, --refresh download fresh package databases from the server\n"));
170 addlist(_(" --needed don't reinstall up to date packages\n"));
171 } else if (op == PM_OP_DATABASE) {
172 printf("%s: %s {-D --database} <%s> <%s>\n", str_usg, myname, str_opt, str_pkg);
173 printf("%s:\n", str_opt);
174 addlist(_(" --asdeps mark packages as non-explicitly installed\n"));
175 addlist(_(" --asexplicit mark packages as explicitly installed\n"));
177 switch(op) {
178 case PM_OP_SYNC:
179 case PM_OP_UPGRADE:
180 addlist(_(" -f, --force force install, overwrite conflicting files\n"));
181 addlist(_(" --asdeps install packages as non-explicitly installed\n"));
182 addlist(_(" --asexplicit install packages as explicitly installed\n"));
183 addlist(_(" --ignore <pkg> ignore a package upgrade (can be used more than once)\n"));
184 addlist(_(" --ignoregroup <grp>\n"
185 " ignore a group upgrade (can be used more than once)\n"));
186 /* pass through */
187 case PM_OP_REMOVE:
188 addlist(_(" -d, --nodeps skip dependency checks\n"));
189 addlist(_(" -k, --dbonly only modify database entries, not package files\n"));
190 addlist(_(" --noprogressbar do not show a progress bar when downloading files\n"));
191 addlist(_(" --noscriptlet do not execute the install scriptlet if one exists\n"));
192 addlist(_(" --print only print the targets instead of performing the operation\n"));
193 addlist(_(" --print-format <string>\n"
194 " specify how the targets should be printed\n"));
195 break;
198 addlist(_(" -b, --dbpath <path> set an alternate database location\n"));
199 addlist(_(" -r, --root <path> set an alternate installation root\n"));
200 addlist(_(" -v, --verbose be verbose\n"));
201 addlist(_(" --arch <arch> set an alternate architecture\n"));
202 addlist(_(" --cachedir <dir> set an alternate package cache location\n"));
203 addlist(_(" --config <path> set an alternate configuration file\n"));
204 addlist(_(" --debug display debug messages\n"));
205 addlist(_(" --logfile <path> set an alternate log file\n"));
206 addlist(_(" --noconfirm do not ask for any confirmation\n"));
208 list = alpm_list_msort(list, alpm_list_count(list), options_cmp);
209 for (i = list; i; i = alpm_list_next(i)) {
210 printf("%s", (char *)alpm_list_getdata(i));
212 alpm_list_free(list);
213 #undef addlist
216 /** Output pacman version and copyright.
218 static void version(void)
220 printf("\n");
221 printf(" .--. Pacman v%s - libalpm v%s\n", PACKAGE_VERSION, alpm_version());
222 printf("/ _.-' .-. .-. .-. Copyright (C) 2006-2011 Pacman Development Team\n");
223 printf("\\ '-. '-' '-' '-' Copyright (C) 2002-2006 Judd Vinet\n");
224 printf(" '--'\n");
225 printf(_(" This program may be freely redistributed under\n"
226 " the terms of the GNU General Public License.\n"));
227 printf("\n");
230 /** Sets up gettext localization. Safe to call multiple times.
232 /* Inspired by the monotone function localize_monotone. */
233 #if defined(ENABLE_NLS)
234 static void localize(void)
236 static int init = 0;
237 if (!init) {
238 setlocale(LC_ALL, "");
239 bindtextdomain(PACKAGE, LOCALEDIR);
240 textdomain(PACKAGE);
241 init = 1;
244 #endif
246 /** Set user agent environment variable.
248 static void setuseragent(void)
250 char agent[101];
251 struct utsname un;
253 uname(&un);
254 snprintf(agent, 100, "pacman/%s (%s %s) libalpm/%s",
255 PACKAGE_VERSION, un.sysname, un.machine, alpm_version());
256 setenv("HTTP_USER_AGENT", agent, 0);
259 static void setarch(const char *arch)
261 if (strcmp(arch, "auto") == 0) {
262 struct utsname un;
263 uname(&un);
264 pm_printf(PM_LOG_DEBUG, "config: Architecture: %s\n", un.machine);
265 alpm_option_set_arch(un.machine);
266 } else {
267 pm_printf(PM_LOG_DEBUG, "config: Architecture: %s\n", arch);
268 alpm_option_set_arch(arch);
272 /** Free the resources.
274 * @param ret the return value
276 static void cleanup(int ret) {
277 /* free alpm library resources */
278 if(alpm_release() == -1) {
279 pm_printf(PM_LOG_ERROR, "%s\n", alpm_strerrorlast());
282 /* free memory */
283 FREELIST(pm_targets);
284 if(config) {
285 config_free(config);
286 config = NULL;
289 exit(ret);
292 /** Write function that correctly handles EINTR.
294 static ssize_t xwrite(int fd, const void *buf, size_t count)
296 ssize_t ret;
297 do {
298 ret = write(fd, buf, count);
299 } while(ret == -1 && errno == EINTR);
300 return(ret);
303 /** Catches thrown signals. Performs necessary cleanup to ensure database is
304 * in a consistant state.
305 * @param signum the thrown signal
307 static void handler(int signum)
309 int out = fileno(stdout);
310 int err = fileno(stderr);
311 if(signum == SIGSEGV) {
312 const char *msg1 = "error: segmentation fault\n";
313 const char *msg2 = "Internal pacman error: Segmentation fault.\n"
314 "Please submit a full bug report with --debug if appropriate.\n";
315 /* write a error message to out, the rest to err */
316 xwrite(out, msg1, strlen(msg1));
317 xwrite(err, msg2, strlen(msg2));
318 exit(signum);
319 } else if((signum == SIGINT)) {
320 const char *msg = "\nInterrupt signal received\n";
321 xwrite(err, msg, strlen(msg));
322 if(alpm_trans_interrupt() == 0) {
323 /* a transaction is being interrupted, don't exit pacman yet. */
324 return;
326 /* no commiting transaction, we can release it now and then exit pacman */
327 alpm_trans_release();
328 /* output a newline to be sure we clear any line we may be on */
329 xwrite(out, "\n", 1);
331 cleanup(signum);
334 /** Sets all libalpm required paths in one go. Called after the command line
335 * and inital config file parsing. Once this is complete, we can see if any
336 * paths were defined. If a rootdir was defined and nothing else, we want all
337 * of our paths to live under the rootdir that was specified. Safe to call
338 * multiple times (will only do anything the first time).
340 static void setlibpaths(void)
342 static int init = 0;
343 if (!init) {
344 int ret = 0;
346 pm_printf(PM_LOG_DEBUG, "setlibpaths() called\n");
347 /* Configure root path first. If it is set and dbpath/logfile were not
348 * set, then set those as well to reside under the root. */
349 if(config->rootdir) {
350 char path[PATH_MAX];
351 ret = alpm_option_set_root(config->rootdir);
352 if(ret != 0) {
353 pm_printf(PM_LOG_ERROR, _("problem setting rootdir '%s' (%s)\n"),
354 config->rootdir, alpm_strerrorlast());
355 cleanup(ret);
357 if(!config->dbpath) {
358 /* omit leading slash from our static DBPATH, root handles it */
359 snprintf(path, PATH_MAX, "%s%s", alpm_option_get_root(), DBPATH + 1);
360 config->dbpath = strdup(path);
362 if(!config->logfile) {
363 /* omit leading slash from our static LOGFILE path, root handles it */
364 snprintf(path, PATH_MAX, "%s%s", alpm_option_get_root(), LOGFILE + 1);
365 config->logfile = strdup(path);
368 /* Set other paths if they were configured. Note that unless rootdir
369 * was left undefined, these two paths (dbpath and logfile) will have
370 * been set locally above, so the if cases below will now trigger. */
371 if(config->dbpath) {
372 ret = alpm_option_set_dbpath(config->dbpath);
373 if(ret != 0) {
374 pm_printf(PM_LOG_ERROR, _("problem setting dbpath '%s' (%s)\n"),
375 config->dbpath, alpm_strerrorlast());
376 cleanup(ret);
379 if(config->logfile) {
380 ret = alpm_option_set_logfile(config->logfile);
381 if(ret != 0) {
382 pm_printf(PM_LOG_ERROR, _("problem setting logfile '%s' (%s)\n"),
383 config->logfile, alpm_strerrorlast());
384 cleanup(ret);
388 /* add a default cachedir if one wasn't specified */
389 if(alpm_option_get_cachedirs() == NULL) {
390 alpm_option_add_cachedir(CACHEDIR);
392 init = 1;
396 #define check_optarg() if(!optarg) { return(1); }
398 typedef void (*fn_add) (const char *s);
400 static int parsearg_util_addlist(fn_add fn)
402 alpm_list_t *list = NULL, *item = NULL; /* lists for splitting strings */
404 check_optarg();
405 list = strsplit(optarg, ',');
406 for(item = list; item; item = alpm_list_next(item)) {
407 fn((char *)alpm_list_getdata(item));
409 FREELIST(list);
410 return(0);
413 /** Helper function for parsing operation from command-line arguments.
414 * @param opt Keycode returned by getopt_long
415 * @param dryrun If nonzero, application state is NOT changed
416 * @return 0 if opt was handled, 1 if it was not handled
418 static int parsearg_op(int opt, int dryrun)
420 switch(opt) {
421 /* operations */
422 case 'D':
423 if(dryrun) break;
424 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DATABASE); break;
425 case 'Q':
426 if(dryrun) break;
427 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_QUERY); break;
428 case 'R':
429 if(dryrun) break;
430 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_REMOVE); break;
431 case 'S':
432 if(dryrun) break;
433 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_SYNC); break;
434 case 'T':
435 if(dryrun) break;
436 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DEPTEST); break;
437 case 'U':
438 if(dryrun) break;
439 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_UPGRADE); break;
440 case 'V':
441 if(dryrun) break;
442 config->version = 1; break;
443 case 'h':
444 if(dryrun) break;
445 config->help = 1; break;
446 default:
447 return(1);
449 return(0);
452 /** Helper functions for parsing command-line arguments.
453 * @param opt Keycode returned by getopt_long
454 * @return 0 on success, 1 on failure
456 static int parsearg_global(int opt)
458 switch(opt) {
459 case OP_ARCH: check_optarg(); setarch(optarg); break;
460 case OP_ASK:
461 check_optarg();
462 config->noask = 1;
463 config->ask = (unsigned int)atoi(optarg);
464 break;
465 case OP_CACHEDIR:
466 check_optarg();
467 if(alpm_option_add_cachedir(optarg) != 0) {
468 pm_printf(PM_LOG_ERROR, _("problem adding cachedir '%s' (%s)\n"),
469 optarg, alpm_strerrorlast());
470 return(1);
472 break;
473 case OP_CONFIG:
474 check_optarg();
475 if(config->configfile) {
476 free(config->configfile);
478 config->configfile = strndup(optarg, PATH_MAX);
479 break;
480 case OP_DEBUG:
481 /* debug levels are made more 'human readable' than using a raw logmask
482 * here, error and warning are set in config_new, though perhaps a
483 * --quiet option will remove these later */
484 if(optarg) {
485 unsigned short debug = (unsigned short)atoi(optarg);
486 switch(debug) {
487 case 2:
488 config->logmask |= PM_LOG_FUNCTION; /* fall through */
489 case 1:
490 config->logmask |= PM_LOG_DEBUG;
491 break;
492 default:
493 pm_printf(PM_LOG_ERROR, _("'%s' is not a valid debug level\n"),
494 optarg);
495 return(1);
497 } else {
498 config->logmask |= PM_LOG_DEBUG;
500 /* progress bars get wonky with debug on, shut them off */
501 config->noprogressbar = 1;
502 break;
503 case OP_LOGFILE:
504 check_optarg();
505 config->logfile = strndup(optarg, PATH_MAX);
506 break;
507 case OP_NOCONFIRM: config->noconfirm = 1; break;
508 case 'b':
509 check_optarg();
510 config->dbpath = strdup(optarg);
511 break;
512 case 'r': check_optarg(); config->rootdir = strdup(optarg); break;
513 case 'v': (config->verbose)++; break;
514 default: return(1);
516 return(0);
519 static int parsearg_database(int opt)
521 switch(opt) {
522 case OP_ASDEPS: config->flags |= PM_TRANS_FLAG_ALLDEPS; break;
523 case OP_ASEXPLICIT: config->flags |= PM_TRANS_FLAG_ALLEXPLICIT; break;
524 default: return(1);
526 return(0);
529 static int parsearg_query(int opt)
531 switch(opt) {
532 case 'c': config->op_q_changelog = 1; break;
533 case 'd': config->op_q_deps = 1; break;
534 case 'e': config->op_q_explicit = 1; break;
535 case 'g': (config->group)++; break;
536 case 'i': (config->op_q_info)++; break;
537 case 'k': config->op_q_check = 1; break;
538 case 'l': config->op_q_list = 1; break;
539 case 'm': config->op_q_foreign = 1; break;
540 case 'o': config->op_q_owns = 1; break;
541 case 'p': config->op_q_isfile = 1; break;
542 case 'q': config->quiet = 1; break;
543 case 's': config->op_q_search = 1; break;
544 case 't': config->op_q_unrequired = 1; break;
545 case 'u': config->op_q_upgrade = 1; break;
546 default: return(1);
548 return(0);
551 /* options common to -S -R -U */
552 static int parsearg_trans(int opt)
554 switch(opt) {
555 case 'd':
556 if(config->flags & PM_TRANS_FLAG_NODEPVERSION) {
557 config->flags |= PM_TRANS_FLAG_NODEPS;
558 } else {
559 config->flags |= PM_TRANS_FLAG_NODEPVERSION;
561 break;
562 case 'k': config->flags |= PM_TRANS_FLAG_DBONLY; break;
563 case OP_NOPROGRESSBAR: config->noprogressbar = 1; break;
564 case OP_NOSCRIPTLET: config->flags |= PM_TRANS_FLAG_NOSCRIPTLET; break;
565 case 'p': config->print = 1; break;
566 case OP_PRINTFORMAT:
567 check_optarg();
568 config->print_format = strdup(optarg);
569 break;
570 default: return(1);
572 return(0);
575 static int parsearg_remove(int opt)
577 if (parsearg_trans(opt) == 0)
578 return(0);
579 switch(opt) {
580 case 'c': config->flags |= PM_TRANS_FLAG_CASCADE; break;
581 case 'n': config->flags |= PM_TRANS_FLAG_NOSAVE; break;
582 case 's':
583 if(config->flags & PM_TRANS_FLAG_RECURSE) {
584 config->flags |= PM_TRANS_FLAG_RECURSEALL;
585 } else {
586 config->flags |= PM_TRANS_FLAG_RECURSE;
588 break;
589 case 'u': config->flags |= PM_TRANS_FLAG_UNNEEDED; break;
590 default: return(1);
592 return(0);
595 /* options common to -S -U */
596 static int parsearg_upgrade(int opt)
598 if (parsearg_trans(opt) == 0)
599 return(0);
600 switch(opt) {
601 case 'f': config->flags |= PM_TRANS_FLAG_FORCE; break;
602 case OP_ASDEPS: config->flags |= PM_TRANS_FLAG_ALLDEPS; break;
603 case OP_ASEXPLICIT: config->flags |= PM_TRANS_FLAG_ALLEXPLICIT; break;
604 case OP_IGNORE:
605 parsearg_util_addlist(alpm_option_add_ignorepkg);
606 break;
607 case OP_IGNOREGROUP:
608 parsearg_util_addlist(alpm_option_add_ignoregrp);
609 break;
610 default: return(1);
612 return(0);
615 static int parsearg_sync(int opt)
617 if (parsearg_upgrade(opt) == 0)
618 return(0);
619 switch(opt) {
620 case OP_NEEDED: config->flags |= PM_TRANS_FLAG_NEEDED; break;
621 case 'c': (config->op_s_clean)++; break;
622 case 'g': (config->group)++; break;
623 case 'i': (config->op_s_info)++; break;
624 case 'l': config->op_q_list = 1; break;
625 case 'q': config->quiet = 1; break;
626 case 's': config->op_s_search = 1; break;
627 case 'u': (config->op_s_upgrade)++; break;
628 case 'w':
629 config->op_s_downloadonly = 1;
630 config->flags |= PM_TRANS_FLAG_DOWNLOADONLY;
631 config->flags |= PM_TRANS_FLAG_NOCONFLICTS;
632 break;
633 case 'y': (config->op_s_sync)++; break;
634 default: return(1);
636 return(0);
639 /** Parse command-line arguments for each operation.
640 * @param argc argc
641 * @param argv argv
642 * @return 0 on success, 1 on error
644 static int parseargs(int argc, char *argv[])
646 int opt;
647 int option_index = 0;
648 int result;
649 const char *optstring = "DQRSTUVb:cdefghiklmnopqr:stuvwy";
650 static struct option opts[] =
652 {"database", no_argument, 0, 'D'},
653 {"query", no_argument, 0, 'Q'},
654 {"remove", no_argument, 0, 'R'},
655 {"sync", no_argument, 0, 'S'},
656 {"deptest", no_argument, 0, 'T'}, /* used by makepkg */
657 {"upgrade", no_argument, 0, 'U'},
658 {"version", no_argument, 0, 'V'},
659 {"dbpath", required_argument, 0, 'b'},
660 {"cascade", no_argument, 0, 'c'},
661 {"changelog", no_argument, 0, 'c'},
662 {"clean", no_argument, 0, 'c'},
663 {"nodeps", no_argument, 0, 'd'},
664 {"deps", no_argument, 0, 'd'},
665 {"explicit", no_argument, 0, 'e'},
666 {"force", no_argument, 0, 'f'},
667 {"groups", no_argument, 0, 'g'},
668 {"help", no_argument, 0, 'h'},
669 {"info", no_argument, 0, 'i'},
670 {"dbonly", no_argument, 0, 'k'},
671 {"check", no_argument, 0, 'k'},
672 {"list", no_argument, 0, 'l'},
673 {"foreign", no_argument, 0, 'm'},
674 {"nosave", no_argument, 0, 'n'},
675 {"owns", no_argument, 0, 'o'},
676 {"file", no_argument, 0, 'p'},
677 {"print", no_argument, 0, 'p'},
678 {"quiet", no_argument, 0, 'q'},
679 {"root", required_argument, 0, 'r'},
680 {"recursive", no_argument, 0, 's'},
681 {"search", no_argument, 0, 's'},
682 {"unrequired", no_argument, 0, 't'},
683 {"upgrades", no_argument, 0, 'u'},
684 {"sysupgrade", no_argument, 0, 'u'},
685 {"unneeded", no_argument, 0, 'u'},
686 {"verbose", no_argument, 0, 'v'},
687 {"downloadonly", no_argument, 0, 'w'},
688 {"refresh", no_argument, 0, 'y'},
689 {"noconfirm", no_argument, 0, OP_NOCONFIRM},
690 {"config", required_argument, 0, OP_CONFIG},
691 {"ignore", required_argument, 0, OP_IGNORE},
692 {"debug", optional_argument, 0, OP_DEBUG},
693 {"noprogressbar", no_argument, 0, OP_NOPROGRESSBAR},
694 {"noscriptlet", no_argument, 0, OP_NOSCRIPTLET},
695 {"ask", required_argument, 0, OP_ASK},
696 {"cachedir", required_argument, 0, OP_CACHEDIR},
697 {"asdeps", no_argument, 0, OP_ASDEPS},
698 {"logfile", required_argument, 0, OP_LOGFILE},
699 {"ignoregroup", required_argument, 0, OP_IGNOREGROUP},
700 {"needed", no_argument, 0, OP_NEEDED},
701 {"asexplicit", no_argument, 0, OP_ASEXPLICIT},
702 {"arch", required_argument, 0, OP_ARCH},
703 {"print-format", required_argument, 0, OP_PRINTFORMAT},
704 {0, 0, 0, 0}
707 /* parse operation */
708 while((opt = getopt_long(argc, argv, optstring, opts, &option_index))) {
709 if(opt < 0) {
710 break;
711 } else if(opt == 0) {
712 continue;
713 } else if(opt == '?') {
714 /* unknown option, getopt printed an error */
715 return(1);
717 parsearg_op(opt, 0);
720 if(config->op == 0) {
721 pm_printf(PM_LOG_ERROR, _("only one operation may be used at a time\n"));
722 return(1);
724 if(config->help) {
725 usage(config->op, mbasename(argv[0]));
726 return(2);
728 if(config->version) {
729 version();
730 return(2);
733 /* parse all other options */
734 optind = 1;
735 while((opt = getopt_long(argc, argv, optstring, opts, &option_index))) {
736 if(opt < 0) {
737 break;
738 } else if(opt == 0) {
739 continue;
740 } else if(opt == '?') {
741 /* this should have failed during first pass already */
742 return(1);
743 } else if(parsearg_op(opt, 1) == 0) { /* opt is an operation */
744 continue;
747 switch(config->op) {
748 case PM_OP_DATABASE:
749 result = parsearg_database(opt);
750 break;
751 case PM_OP_QUERY:
752 result = parsearg_query(opt);
753 break;
754 case PM_OP_REMOVE:
755 result = parsearg_remove(opt);
756 break;
757 case PM_OP_SYNC:
758 result = parsearg_sync(opt);
759 break;
760 case PM_OP_DEPTEST:
761 result = 1;
762 break;
763 case PM_OP_UPGRADE:
764 result = parsearg_upgrade(opt);
765 break;
766 default:
767 pm_printf(PM_LOG_ERROR, _("no operation specified (use -h for help)\n"));
768 return(1);
770 if (result == 0)
771 continue;
773 /* fall back to global options */
774 result = parsearg_global(opt);
775 if(result != 0) {
776 /* global option parsing failed, abort */
777 pm_printf(PM_LOG_ERROR, _("invalid option\n"));
778 return(result);
782 while(optind < argc) {
783 /* add the target to our target array */
784 pm_targets = alpm_list_add(pm_targets, strdup(argv[optind]));
785 optind++;
788 return(0);
791 /* helper for being used with setrepeatingoption */
792 static void option_add_holdpkg(const char *name) {
793 config->holdpkg = alpm_list_add(config->holdpkg, strdup(name));
796 /* helper for being used with setrepeatingoption */
797 static void option_add_syncfirst(const char *name) {
798 config->syncfirst = alpm_list_add(config->syncfirst, strdup(name));
801 /* helper for being used with setrepeatingoption */
802 static void option_add_cleanmethod(const char *value) {
803 if (strcmp(value, "KeepInstalled") == 0) {
804 config->cleanmethod |= PM_CLEAN_KEEPINST;
805 } else if (strcmp(value, "KeepCurrent") == 0) {
806 config->cleanmethod |= PM_CLEAN_KEEPCUR;
807 } else {
808 pm_printf(PM_LOG_ERROR, _("invalid value for 'CleanMethod' : '%s'\n"),
809 value);
813 /** Add repeating options such as NoExtract, NoUpgrade, etc to libalpm
814 * settings. Refactored out of the parseconfig code since all of them did
815 * the exact same thing and duplicated code.
816 * @param ptr a pointer to the start of the multiple options
817 * @param option the string (friendly) name of the option, used for messages
818 * @param optionfunc a function pointer to an alpm_option_add_* function
820 static void setrepeatingoption(const char *ptr, const char *option,
821 void (*optionfunc)(const char*))
823 char *p = (char*)ptr;
824 char *q;
826 while((q = strchr(p, ' '))) {
827 *q = '\0';
828 (*optionfunc)(p);
829 pm_printf(PM_LOG_DEBUG, "config: %s: %s\n", option, p);
830 p = q;
831 p++;
833 (*optionfunc)(p);
834 pm_printf(PM_LOG_DEBUG, "config: %s: %s\n", option, p);
837 static char *get_filename(const char *url) {
838 char *filename = strrchr(url, '/');
839 if(filename != NULL) {
840 filename++;
842 return(filename);
845 static char *get_destfile(const char *path, const char *filename) {
846 char *destfile;
847 /* len = localpath len + filename len + null */
848 size_t len = strlen(path) + strlen(filename) + 1;
849 destfile = calloc(len, sizeof(char));
850 snprintf(destfile, len, "%s%s", path, filename);
852 return(destfile);
855 static char *get_tempfile(const char *path, const char *filename) {
856 char *tempfile;
857 /* len = localpath len + filename len + '.part' len + null */
858 size_t len = strlen(path) + strlen(filename) + 6;
859 tempfile = calloc(len, sizeof(char));
860 snprintf(tempfile, len, "%s%s.part", path, filename);
862 return(tempfile);
865 /** External fetch callback */
866 static int download_with_xfercommand(const char *url, const char *localpath,
867 int force) {
868 int ret = 0;
869 int retval;
870 int usepart = 0;
871 struct stat st;
872 char *parsedcmd,*tempcmd;
873 char cwd[PATH_MAX];
874 int restore_cwd = 0;
875 char *destfile, *tempfile, *filename;
877 if(!config->xfercommand) {
878 return -1;
881 filename = get_filename(url);
882 if(!filename) {
883 return -1;
885 destfile = get_destfile(localpath, filename);
886 tempfile = get_tempfile(localpath, filename);
888 if(force && stat(tempfile, &st) == 0) {
889 unlink(tempfile);
891 if(force && stat(destfile, &st) == 0) {
892 unlink(destfile);
895 tempcmd = strdup(config->xfercommand);
896 /* replace all occurrences of %o with fn.part */
897 if(strstr(tempcmd, "%o")) {
898 usepart = 1;
899 parsedcmd = strreplace(tempcmd, "%o", tempfile);
900 free(tempcmd);
901 tempcmd = parsedcmd;
903 /* replace all occurrences of %u with the download URL */
904 parsedcmd = strreplace(tempcmd, "%u", url);
905 free(tempcmd);
907 /* save the cwd so we can restore it later */
908 if(getcwd(cwd, PATH_MAX) == NULL) {
909 pm_printf(PM_LOG_ERROR, _("could not get current working directory\n"));
910 } else {
911 restore_cwd = 1;
914 /* cwd to the download directory */
915 if(chdir(localpath)) {
916 pm_printf(PM_LOG_WARNING, _("could not chdir to download directory %s\n"), localpath);
917 ret = -1;
918 goto cleanup;
920 /* execute the parsed command via /bin/sh -c */
921 pm_printf(PM_LOG_DEBUG, "running command: %s\n", parsedcmd);
922 retval = system(parsedcmd);
924 if(retval == -1) {
925 pm_printf(PM_LOG_WARNING, _("running XferCommand: fork failed!\n"));
926 ret = -1;
927 } else if(retval != 0) {
928 /* download failed */
929 pm_printf(PM_LOG_DEBUG, "XferCommand command returned non-zero status "
930 "code (%d)\n", retval);
931 ret = -1;
932 } else {
933 /* download was successful */
934 if(usepart) {
935 rename(tempfile, destfile);
937 ret = 0;
940 cleanup:
941 /* restore the old cwd if we have it */
942 if(restore_cwd && chdir(cwd) != 0) {
943 pm_printf(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), cwd, strerror(errno));
946 if(ret == -1) {
947 /* hack to let an user the time to cancel a download */
948 sleep(2);
950 free(destfile);
951 free(tempfile);
952 free(parsedcmd);
954 return(ret);
957 static int _parse_options(char *key, char *value)
959 if(value == NULL) {
960 /* options without settings */
961 if(strcmp(key, "UseSyslog") == 0) {
962 alpm_option_set_usesyslog(1);
963 pm_printf(PM_LOG_DEBUG, "config: usesyslog\n");
964 } else if(strcmp(key, "ILoveCandy") == 0) {
965 config->chomp = 1;
966 pm_printf(PM_LOG_DEBUG, "config: chomp\n");
967 } else if(strcmp(key, "ShowSize") == 0) {
968 config->showsize = 1;
969 pm_printf(PM_LOG_DEBUG, "config: showsize\n");
970 } else if(strcmp(key, "UseDelta") == 0) {
971 alpm_option_set_usedelta(1);
972 pm_printf(PM_LOG_DEBUG, "config: usedelta\n");
973 } else if(strcmp(key, "TotalDownload") == 0) {
974 config->totaldownload = 1;
975 pm_printf(PM_LOG_DEBUG, "config: totaldownload\n");
976 } else if(strcmp(key, "CheckSpace") == 0) {
977 alpm_option_set_checkspace(1);
978 } else {
979 pm_printf(PM_LOG_ERROR, _("directive '%s' without value not recognized\n"), key);
980 return(1);
982 } else {
983 /* options with settings */
984 if(strcmp(key, "NoUpgrade") == 0) {
985 setrepeatingoption(value, "NoUpgrade", alpm_option_add_noupgrade);
986 } else if(strcmp(key, "NoExtract") == 0) {
987 setrepeatingoption(value, "NoExtract", alpm_option_add_noextract);
988 } else if(strcmp(key, "IgnorePkg") == 0) {
989 setrepeatingoption(value, "IgnorePkg", alpm_option_add_ignorepkg);
990 } else if(strcmp(key, "IgnoreGroup") == 0) {
991 setrepeatingoption(value, "IgnoreGroup", alpm_option_add_ignoregrp);
992 } else if(strcmp(key, "HoldPkg") == 0) {
993 setrepeatingoption(value, "HoldPkg", option_add_holdpkg);
994 } else if(strcmp(key, "SyncFirst") == 0) {
995 setrepeatingoption(value, "SyncFirst", option_add_syncfirst);
996 } else if(strcmp(key, "Architecture") == 0) {
997 if(!alpm_option_get_arch()) {
998 setarch(value);
1000 } else if(strcmp(key, "DBPath") == 0) {
1001 /* don't overwrite a path specified on the command line */
1002 if(!config->dbpath) {
1003 config->dbpath = strdup(value);
1004 pm_printf(PM_LOG_DEBUG, "config: dbpath: %s\n", value);
1006 } else if(strcmp(key, "CacheDir") == 0) {
1007 if(alpm_option_add_cachedir(value) != 0) {
1008 pm_printf(PM_LOG_ERROR, _("problem adding cachedir '%s' (%s)\n"),
1009 value, alpm_strerrorlast());
1010 return(1);
1012 pm_printf(PM_LOG_DEBUG, "config: cachedir: %s\n", value);
1013 } else if(strcmp(key, "RootDir") == 0) {
1014 /* don't overwrite a path specified on the command line */
1015 if(!config->rootdir) {
1016 config->rootdir = strdup(value);
1017 pm_printf(PM_LOG_DEBUG, "config: rootdir: %s\n", value);
1019 } else if (strcmp(key, "LogFile") == 0) {
1020 if(!config->logfile) {
1021 config->logfile = strdup(value);
1022 pm_printf(PM_LOG_DEBUG, "config: logfile: %s\n", value);
1024 } else if (strcmp(key, "XferCommand") == 0) {
1025 config->xfercommand = strdup(value);
1026 alpm_option_set_fetchcb(download_with_xfercommand);
1027 pm_printf(PM_LOG_DEBUG, "config: xfercommand: %s\n", value);
1028 } else if (strcmp(key, "CleanMethod") == 0) {
1029 setrepeatingoption(value, "CleanMethod", option_add_cleanmethod);
1030 } else {
1031 pm_printf(PM_LOG_ERROR, _("directive '%s' with a value not recognized\n"), key);
1032 return(1);
1036 return(0);
1039 static int _add_mirror(pmdb_t *db, char *value)
1041 const char *dbname = alpm_db_get_name(db);
1042 /* let's attempt a replacement for the current repo */
1043 char *temp = strreplace(value, "$repo", dbname);
1044 /* let's attempt a replacement for the arch */
1045 const char *arch = alpm_option_get_arch();
1046 char *server;
1047 if(arch) {
1048 server = strreplace(temp, "$arch", arch);
1049 free(temp);
1050 } else {
1051 if(strstr(temp, "$arch")) {
1052 free(temp);
1053 pm_printf(PM_LOG_ERROR, _("The mirror '%s' contains the $arch"
1054 " variable, but no Architecture is defined.\n"), value);
1055 return(1);
1057 server = temp;
1060 if(alpm_db_setserver(db, server) != 0) {
1061 /* pm_errno is set by alpm_db_setserver */
1062 pm_printf(PM_LOG_ERROR, _("could not add server URL to database '%s': %s (%s)\n"),
1063 dbname, server, alpm_strerrorlast());
1064 free(server);
1065 return(1);
1068 free(server);
1069 return(0);
1072 /* The real parseconfig. Called with a null section argument by the publicly
1073 * visible parseconfig so we can recall from within ourself on an include */
1074 static int _parseconfig(const char *file, const char *givensection,
1075 pmdb_t * const givendb)
1077 FILE *fp = NULL;
1078 char line[PATH_MAX+1];
1079 int linenum = 0;
1080 char *ptr, *section = NULL;
1081 pmdb_t *db = NULL;
1082 int ret = 0;
1084 pm_printf(PM_LOG_DEBUG, "config: attempting to read file %s\n", file);
1085 fp = fopen(file, "r");
1086 if(fp == NULL) {
1087 pm_printf(PM_LOG_ERROR, _("config file %s could not be read.\n"), file);
1088 return(1);
1091 /* if we are passed a section, use it as our starting point */
1092 if(givensection != NULL) {
1093 section = strdup(givensection);
1095 /* if we are passed a db, use it as our starting point */
1096 if(givendb != NULL) {
1097 db = givendb;
1100 while(fgets(line, PATH_MAX, fp)) {
1101 linenum++;
1102 strtrim(line);
1104 /* ignore whole line and end of line comments */
1105 if(strlen(line) == 0 || line[0] == '#') {
1106 continue;
1108 if((ptr = strchr(line, '#'))) {
1109 *ptr = '\0';
1112 if(line[0] == '[' && line[strlen(line)-1] == ']') {
1113 /* new config section, skip the '[' */
1114 ptr = line;
1115 ptr++;
1116 if(section) {
1117 free(section);
1119 section = strdup(ptr);
1120 section[strlen(section)-1] = '\0';
1121 pm_printf(PM_LOG_DEBUG, "config: new section '%s'\n", section);
1122 if(!strlen(section)) {
1123 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: bad section name.\n"),
1124 file, linenum);
1125 ret = 1;
1126 goto cleanup;
1128 /* if we are not looking at the options section, register a db */
1129 if(strcmp(section, "options") != 0) {
1130 db = alpm_db_register_sync(section);
1131 if(db == NULL) {
1132 pm_printf(PM_LOG_ERROR, _("could not register '%s' database (%s)\n"),
1133 section, alpm_strerrorlast());
1134 ret = 1;
1135 goto cleanup;
1138 continue;
1141 /* directive */
1142 char *key, *value;
1143 /* strsep modifies the 'line' string: 'key \0 value' */
1144 key = line;
1145 value = line;
1146 strsep(&value, "=");
1147 strtrim(key);
1148 strtrim(value);
1150 if(key == NULL) {
1151 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: syntax error in config file- missing key.\n"),
1152 file, linenum);
1153 ret = 1;
1154 goto cleanup;
1156 /* For each directive, compare to the camelcase string. */
1157 if(section == NULL) {
1158 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: All directives must belong to a section.\n"),
1159 file, linenum);
1160 ret = 1;
1161 goto cleanup;
1163 /* Include is allowed in both options and repo sections */
1164 if(strcmp(key, "Include") == 0) {
1165 if(value == NULL) {
1166 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive %s needs a value\n"),
1167 file, linenum, key);
1168 ret = 1;
1169 goto cleanup;
1171 /* Ignore include failures... assume non-critical */
1172 int globret;
1173 glob_t globbuf;
1174 globret = glob(value, GLOB_NOCHECK, NULL, &globbuf);
1175 switch(globret) {
1176 case GLOB_NOSPACE:
1177 pm_printf(PM_LOG_DEBUG,
1178 "config file %s, line %d: include globing out of space\n",
1179 file, linenum);
1180 break;
1181 case GLOB_ABORTED:
1182 pm_printf(PM_LOG_DEBUG,
1183 "config file %s, line %d: include globing read error for %s\n",
1184 file, linenum, value);
1185 break;
1186 case GLOB_NOMATCH:
1187 pm_printf(PM_LOG_DEBUG,
1188 "config file %s, line %d: no include found for %s\n",
1189 file, linenum, value);
1190 break;
1191 default:
1192 for(size_t gindex = 0; gindex < globbuf.gl_pathc; gindex++) {
1193 pm_printf(PM_LOG_DEBUG, "config file %s, line %d: including %s\n",
1194 file, linenum, globbuf.gl_pathv[gindex]);
1195 _parseconfig(globbuf.gl_pathv[gindex], section, db);
1197 break;
1199 globfree(&globbuf);
1200 continue;
1202 if(strcmp(section, "options") == 0) {
1203 /* we are either in options ... */
1204 if((ret = _parse_options(key, value)) != 0) {
1205 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: problem in options section\n"),
1206 file, linenum);
1207 ret = 1;
1208 goto cleanup;
1210 continue;
1211 } else {
1212 /* ... or in a repo section */
1213 if(strcmp(key, "Server") == 0) {
1214 if(value == NULL) {
1215 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive %s needs a value\n"),
1216 file, linenum, key);
1217 ret = 1;
1218 goto cleanup;
1220 if(_add_mirror(db, value) != 0) {
1221 ret = 1;
1222 goto cleanup;
1224 } else {
1225 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive '%s' in repository section '%s' not recognized.\n"),
1226 file, linenum, key, section);
1227 ret = 1;
1228 goto cleanup;
1234 cleanup:
1235 if(fp) {
1236 fclose(fp);
1238 if(section){
1239 free(section);
1241 /* call setlibpaths here to ensure we have called it at least once */
1242 setlibpaths();
1243 pm_printf(PM_LOG_DEBUG, "config: finished parsing %s\n", file);
1244 return(ret);
1247 /** Parse a configuration file.
1248 * @param file path to the config file.
1249 * @return 0 on success, non-zero on error
1251 static int parseconfig(const char *file)
1253 /* call the real parseconfig function with a null section & db argument */
1254 return(_parseconfig(file, NULL, NULL));
1257 /** print commandline to logfile
1259 static void cl_to_log(int argc, char* argv[])
1261 size_t size = 0;
1262 int i;
1263 for(i = 0; i<argc; i++) {
1264 size += strlen(argv[i]) + 1;
1266 char *cl_text = malloc(size);
1267 if(!cl_text)
1268 return;
1269 char *p = cl_text;
1270 for(i = 0; i<argc-1; i++) {
1271 strcpy(p, argv[i]);
1272 p += strlen(argv[i]);
1273 *p++ = ' ';
1275 strcpy(p, argv[i]);
1276 alpm_logaction("Running '%s'\n", cl_text);
1277 free(cl_text);
1280 /** Main function.
1281 * @param argc argc
1282 * @param argv argv
1283 * @return A return code indicating success, failure, etc.
1285 int main(int argc, char *argv[])
1287 int ret = 0;
1288 struct sigaction new_action, old_action;
1289 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
1290 /* geteuid undefined in CYGWIN */
1291 uid_t myuid = geteuid();
1292 #endif
1294 #if defined(PACMAN_DEBUG) && defined(HAVE_MCHECK_H)
1295 /*setenv("MALLOC_TRACE","pacman.mtrace", 0);*/
1296 mtrace();
1297 #endif
1299 /* Set signal handlers */
1300 /* Set up the structure to specify the new action. */
1301 new_action.sa_handler = handler;
1302 sigemptyset(&new_action.sa_mask);
1303 new_action.sa_flags = 0;
1305 sigaction(SIGINT, NULL, &old_action);
1306 if(old_action.sa_handler != SIG_IGN) {
1307 sigaction(SIGINT, &new_action, NULL);
1309 sigaction(SIGTERM, NULL, &old_action);
1310 if(old_action.sa_handler != SIG_IGN) {
1311 sigaction(SIGTERM, &new_action, NULL);
1313 sigaction(SIGSEGV, NULL, &old_action);
1314 if(old_action.sa_handler != SIG_IGN) {
1315 sigaction(SIGSEGV, &new_action, NULL);
1318 /* i18n init */
1319 #if defined(ENABLE_NLS)
1320 localize();
1321 #endif
1323 /* set user agent for downloading */
1324 setuseragent();
1326 /* init config data */
1327 config = config_new();
1329 /* disable progressbar if the output is redirected */
1330 if(!isatty(1)) {
1331 config->noprogressbar = 1;
1334 /* initialize library */
1335 if(alpm_initialize() == -1) {
1336 pm_printf(PM_LOG_ERROR, _("failed to initialize alpm library (%s)\n"),
1337 alpm_strerrorlast());
1338 cleanup(EXIT_FAILURE);
1341 /* Setup logging as soon as possible, to print out maximum debugging info */
1342 alpm_option_set_logcb(cb_log);
1343 alpm_option_set_dlcb(cb_dl_progress);
1344 /* define paths to reasonable defaults */
1345 alpm_option_set_root(ROOTDIR);
1346 alpm_option_set_dbpath(DBPATH);
1347 alpm_option_set_logfile(LOGFILE);
1349 /* Priority of options:
1350 * 1. command line
1351 * 2. config file
1352 * 3. compiled-in defaults
1353 * However, we have to parse the command line first because a config file
1354 * location can be specified here, so we need to make sure we prefer these
1355 * options over the config file coming second.
1358 /* parse the command line */
1359 ret = parseargs(argc, argv);
1360 if(ret != 0) {
1361 cleanup(ret);
1364 /* we also support reading targets from stdin */
1365 if(!isatty(fileno(stdin))) {
1366 char line[PATH_MAX];
1367 int i = 0;
1368 while(i < PATH_MAX && (line[i] = (char)fgetc(stdin)) != EOF) {
1369 if(isspace((unsigned char)line[i])) {
1370 /* avoid adding zero length arg when multiple spaces separate args */
1371 if(i > 0) {
1372 line[i] = '\0';
1373 pm_targets = alpm_list_add(pm_targets, strdup(line));
1374 i = 0;
1376 } else {
1377 i++;
1380 /* check for buffer overflow */
1381 if (i >= PATH_MAX) {
1382 pm_printf(PM_LOG_ERROR, _("buffer overflow detected in arg parsing\n"));
1383 cleanup(EXIT_FAILURE);
1386 /* end of stream -- check for data still in line buffer */
1387 if(i > 0) {
1388 line[i] = '\0';
1389 pm_targets = alpm_list_add(pm_targets, strdup(line));
1391 if (!freopen(ctermid(NULL), "r", stdin)) {
1392 pm_printf(PM_LOG_ERROR, _("failed to reopen stdin for reading: (%s)\n"),
1393 strerror(errno));
1397 /* parse the config file */
1398 ret = parseconfig(config->configfile);
1399 if(ret != 0) {
1400 cleanup(ret);
1403 /* set TotalDownload callback if option enabled */
1404 if(config->totaldownload) {
1405 alpm_option_set_totaldlcb(cb_dl_total);
1408 /* noask is meant to be non-interactive */
1409 if(config->noask) {
1410 config->noconfirm = 1;
1413 /* set up the print operations */
1414 if(config->print) {
1415 config->noconfirm = 1;
1416 config->flags |= PM_TRANS_FLAG_NOCONFLICTS;
1417 config->flags |= PM_TRANS_FLAG_NOLOCK;
1418 /* Display only errors */
1419 config->logmask &= ~PM_LOG_WARNING;
1422 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
1423 /* check if we have sufficient permission for the requested operation */
1424 if(myuid > 0 && needs_root()) {
1425 pm_printf(PM_LOG_ERROR, _("you cannot perform this operation unless you are root.\n"));
1426 cleanup(EXIT_FAILURE);
1428 #endif
1430 if(config->verbose > 0) {
1431 alpm_list_t *i;
1432 printf("Root : %s\n", alpm_option_get_root());
1433 printf("Conf File : %s\n", config->configfile);
1434 printf("DB Path : %s\n", alpm_option_get_dbpath());
1435 printf("Cache Dirs: ");
1436 for(i = alpm_option_get_cachedirs(); i; i = alpm_list_next(i)) {
1437 printf("%s ", (char*)alpm_list_getdata(i));
1439 printf("\n");
1440 printf("Lock File : %s\n", alpm_option_get_lockfile());
1441 printf("Log File : %s\n", alpm_option_get_logfile());
1442 list_display("Targets :", pm_targets);
1445 /* Log commandline */
1446 if(needs_root()) {
1447 cl_to_log(argc, argv);
1450 /* start the requested operation */
1451 switch(config->op) {
1452 case PM_OP_DATABASE:
1453 ret = pacman_database(pm_targets);
1454 break;
1455 case PM_OP_REMOVE:
1456 ret = pacman_remove(pm_targets);
1457 break;
1458 case PM_OP_UPGRADE:
1459 ret = pacman_upgrade(pm_targets);
1460 break;
1461 case PM_OP_QUERY:
1462 ret = pacman_query(pm_targets);
1463 break;
1464 case PM_OP_SYNC:
1465 ret = pacman_sync(pm_targets);
1466 break;
1467 case PM_OP_DEPTEST:
1468 ret = pacman_deptest(pm_targets);
1469 break;
1470 default:
1471 pm_printf(PM_LOG_ERROR, _("no operation specified (use -h for help)\n"));
1472 ret = EXIT_FAILURE;
1475 cleanup(ret);
1476 /* not reached */
1477 return(EXIT_SUCCESS);
1480 /* vim: set ts=2 sw=2 noet: */