Added gpg verification options per repo to the config file.
[pacman-ng.git] / src / pacman / pacman.c
blob0487ee87bc3c4fb34262f36c6858fe50a0d64285
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(_(" --gpgdir <path> set an alternate home directory for GnuPG\n"));
206 addlist(_(" --logfile <path> set an alternate log file\n"));
207 addlist(_(" --noconfirm do not ask for any confirmation\n"));
209 list = alpm_list_msort(list, alpm_list_count(list), options_cmp);
210 for (i = list; i; i = alpm_list_next(i)) {
211 printf("%s", (char *)alpm_list_getdata(i));
213 alpm_list_free(list);
214 #undef addlist
217 /** Output pacman version and copyright.
219 static void version(void)
221 printf("\n");
222 printf(" .--. Pacman v%s - libalpm v%s\n", PACKAGE_VERSION, alpm_version());
223 printf("/ _.-' .-. .-. .-. Copyright (C) 2006-2011 Pacman Development Team\n");
224 printf("\\ '-. '-' '-' '-' Copyright (C) 2002-2006 Judd Vinet\n");
225 printf(" '--'\n");
226 printf(_(" This program may be freely redistributed under\n"
227 " the terms of the GNU General Public License.\n"));
228 printf("\n");
231 /** Sets up gettext localization. Safe to call multiple times.
233 /* Inspired by the monotone function localize_monotone. */
234 #if defined(ENABLE_NLS)
235 static void localize(void)
237 static int init = 0;
238 if (!init) {
239 setlocale(LC_ALL, "");
240 bindtextdomain(PACKAGE, LOCALEDIR);
241 textdomain(PACKAGE);
242 init = 1;
245 #endif
247 /** Set user agent environment variable.
249 static void setuseragent(void)
251 char agent[101];
252 struct utsname un;
254 uname(&un);
255 snprintf(agent, 100, "pacman/%s (%s %s) libalpm/%s",
256 PACKAGE_VERSION, un.sysname, un.machine, alpm_version());
257 setenv("HTTP_USER_AGENT", agent, 0);
260 static void setarch(const char *arch)
262 if (strcmp(arch, "auto") == 0) {
263 struct utsname un;
264 uname(&un);
265 pm_printf(PM_LOG_DEBUG, "config: Architecture: %s\n", un.machine);
266 alpm_option_set_arch(un.machine);
267 } else {
268 pm_printf(PM_LOG_DEBUG, "config: Architecture: %s\n", arch);
269 alpm_option_set_arch(arch);
273 /** Free the resources.
275 * @param ret the return value
277 static void cleanup(int ret) {
278 /* free alpm library resources */
279 if(alpm_release() == -1) {
280 pm_printf(PM_LOG_ERROR, "%s\n", alpm_strerrorlast());
283 /* free memory */
284 FREELIST(pm_targets);
285 if(config) {
286 config_free(config);
287 config = NULL;
290 exit(ret);
293 /** Write function that correctly handles EINTR.
295 static ssize_t xwrite(int fd, const void *buf, size_t count)
297 ssize_t ret;
298 do {
299 ret = write(fd, buf, count);
300 } while(ret == -1 && errno == EINTR);
301 return ret;
304 /** Catches thrown signals. Performs necessary cleanup to ensure database is
305 * in a consistant state.
306 * @param signum the thrown signal
308 static void handler(int signum)
310 int out = fileno(stdout);
311 int err = fileno(stderr);
312 if(signum == SIGSEGV) {
313 const char *msg1 = "error: segmentation fault\n";
314 const char *msg2 = "Internal pacman error: Segmentation fault.\n"
315 "Please submit a full bug report with --debug if appropriate.\n";
316 /* write a error message to out, the rest to err */
317 xwrite(out, msg1, strlen(msg1));
318 xwrite(err, msg2, strlen(msg2));
319 exit(signum);
320 } else if((signum == SIGINT)) {
321 const char *msg = "\nInterrupt signal received\n";
322 xwrite(err, msg, strlen(msg));
323 if(alpm_trans_interrupt() == 0) {
324 /* a transaction is being interrupted, don't exit pacman yet. */
325 return;
327 /* no commiting transaction, we can release it now and then exit pacman */
328 alpm_trans_release();
329 /* output a newline to be sure we clear any line we may be on */
330 xwrite(out, "\n", 1);
332 cleanup(signum);
335 /** Sets all libalpm required paths in one go. Called after the command line
336 * and inital config file parsing. Once this is complete, we can see if any
337 * paths were defined. If a rootdir was defined and nothing else, we want all
338 * of our paths to live under the rootdir that was specified. Safe to call
339 * multiple times (will only do anything the first time).
341 static void setlibpaths(void)
343 static int init = 0;
344 if (!init) {
345 int ret = 0;
347 pm_printf(PM_LOG_DEBUG, "setlibpaths() called\n");
348 /* Configure root path first. If it is set and dbpath/logfile were not
349 * set, then set those as well to reside under the root. */
350 if(config->rootdir) {
351 char path[PATH_MAX];
352 ret = alpm_option_set_root(config->rootdir);
353 if(ret != 0) {
354 pm_printf(PM_LOG_ERROR, _("problem setting rootdir '%s' (%s)\n"),
355 config->rootdir, alpm_strerrorlast());
356 cleanup(ret);
358 if(!config->dbpath) {
359 /* omit leading slash from our static DBPATH, root handles it */
360 snprintf(path, PATH_MAX, "%s%s", alpm_option_get_root(), DBPATH + 1);
361 config->dbpath = strdup(path);
363 if(!config->logfile) {
364 /* omit leading slash from our static LOGFILE path, root handles it */
365 snprintf(path, PATH_MAX, "%s%s", alpm_option_get_root(), LOGFILE + 1);
366 config->logfile = strdup(path);
369 /* Set other paths if they were configured. Note that unless rootdir
370 * was left undefined, these two paths (dbpath and logfile) will have
371 * been set locally above, so the if cases below will now trigger. */
372 if(config->dbpath) {
373 ret = alpm_option_set_dbpath(config->dbpath);
374 if(ret != 0) {
375 pm_printf(PM_LOG_ERROR, _("problem setting dbpath '%s' (%s)\n"),
376 config->dbpath, alpm_strerrorlast());
377 cleanup(ret);
380 if(config->logfile) {
381 ret = alpm_option_set_logfile(config->logfile);
382 if(ret != 0) {
383 pm_printf(PM_LOG_ERROR, _("problem setting logfile '%s' (%s)\n"),
384 config->logfile, alpm_strerrorlast());
385 cleanup(ret);
389 /* Set GnuPG's home directory. This is not relative to rootdir, even if
390 * rootdir is defined. Reasoning: gpgdir contains configuration data. */
391 if(config->gpgdir) {
392 ret = alpm_option_set_signaturedir(config->gpgdir);
393 if(ret != 0) {
394 pm_printf(PM_LOG_ERROR, _("problem setting gpgdir '%s' (%s)\n"),
395 config->gpgdir, alpm_strerrorlast());
396 cleanup(ret);
400 /* add a default cachedir if one wasn't specified */
401 if(alpm_option_get_cachedirs() == NULL) {
402 alpm_option_add_cachedir(CACHEDIR);
404 init = 1;
408 #define check_optarg() if(!optarg) { return 1; }
410 typedef void (*fn_add) (const char *s);
412 static int parsearg_util_addlist(fn_add fn)
414 alpm_list_t *list = NULL, *item = NULL; /* lists for splitting strings */
416 check_optarg();
417 list = strsplit(optarg, ',');
418 for(item = list; item; item = alpm_list_next(item)) {
419 fn((char *)alpm_list_getdata(item));
421 FREELIST(list);
422 return 0;
425 /** Helper function for parsing operation from command-line arguments.
426 * @param opt Keycode returned by getopt_long
427 * @param dryrun If nonzero, application state is NOT changed
428 * @return 0 if opt was handled, 1 if it was not handled
430 static int parsearg_op(int opt, int dryrun)
432 switch(opt) {
433 /* operations */
434 case 'D':
435 if(dryrun) break;
436 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DATABASE); break;
437 case 'Q':
438 if(dryrun) break;
439 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_QUERY); break;
440 case 'R':
441 if(dryrun) break;
442 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_REMOVE); break;
443 case 'S':
444 if(dryrun) break;
445 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_SYNC); break;
446 case 'T':
447 if(dryrun) break;
448 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DEPTEST); break;
449 case 'U':
450 if(dryrun) break;
451 config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_UPGRADE); break;
452 case 'V':
453 if(dryrun) break;
454 config->version = 1; break;
455 case 'h':
456 if(dryrun) break;
457 config->help = 1; break;
458 default:
459 return 1;
461 return 0;
464 /** Helper functions for parsing command-line arguments.
465 * @param opt Keycode returned by getopt_long
466 * @return 0 on success, 1 on failure
468 static int parsearg_global(int opt)
470 switch(opt) {
471 case OP_ARCH: check_optarg(); setarch(optarg); break;
472 case OP_ASK:
473 check_optarg();
474 config->noask = 1;
475 config->ask = (unsigned int)atoi(optarg);
476 break;
477 case OP_CACHEDIR:
478 check_optarg();
479 if(alpm_option_add_cachedir(optarg) != 0) {
480 pm_printf(PM_LOG_ERROR, _("problem adding cachedir '%s' (%s)\n"),
481 optarg, alpm_strerrorlast());
482 return 1;
484 break;
485 case OP_CONFIG:
486 check_optarg();
487 if(config->configfile) {
488 free(config->configfile);
490 config->configfile = strndup(optarg, PATH_MAX);
491 break;
492 case OP_DEBUG:
493 /* debug levels are made more 'human readable' than using a raw logmask
494 * here, error and warning are set in config_new, though perhaps a
495 * --quiet option will remove these later */
496 if(optarg) {
497 unsigned short debug = (unsigned short)atoi(optarg);
498 switch(debug) {
499 case 2:
500 config->logmask |= PM_LOG_FUNCTION; /* fall through */
501 case 1:
502 config->logmask |= PM_LOG_DEBUG;
503 break;
504 default:
505 pm_printf(PM_LOG_ERROR, _("'%s' is not a valid debug level\n"),
506 optarg);
507 return 1;
509 } else {
510 config->logmask |= PM_LOG_DEBUG;
512 /* progress bars get wonky with debug on, shut them off */
513 config->noprogressbar = 1;
514 break;
515 case OP_GPGDIR:
516 config->gpgdir = strdup(optarg);
517 break;
518 case OP_LOGFILE:
519 check_optarg();
520 config->logfile = strndup(optarg, PATH_MAX);
521 break;
522 case OP_NOCONFIRM: config->noconfirm = 1; break;
523 case 'b':
524 check_optarg();
525 config->dbpath = strdup(optarg);
526 break;
527 case 'r': check_optarg(); config->rootdir = strdup(optarg); break;
528 case 'v': (config->verbose)++; break;
529 default: return 1;
531 return 0;
534 static int parsearg_database(int opt)
536 switch(opt) {
537 case OP_ASDEPS: config->flags |= PM_TRANS_FLAG_ALLDEPS; break;
538 case OP_ASEXPLICIT: config->flags |= PM_TRANS_FLAG_ALLEXPLICIT; break;
539 default: return 1;
541 return 0;
544 static int parsearg_query(int opt)
546 switch(opt) {
547 case 'c': config->op_q_changelog = 1; break;
548 case 'd': config->op_q_deps = 1; break;
549 case 'e': config->op_q_explicit = 1; break;
550 case 'g': (config->group)++; break;
551 case 'i': (config->op_q_info)++; break;
552 case 'k': config->op_q_check = 1; break;
553 case 'l': config->op_q_list = 1; break;
554 case 'm': config->op_q_foreign = 1; break;
555 case 'o': config->op_q_owns = 1; break;
556 case 'p': config->op_q_isfile = 1; break;
557 case 'q': config->quiet = 1; break;
558 case 's': config->op_q_search = 1; break;
559 case 't': config->op_q_unrequired = 1; break;
560 case 'u': config->op_q_upgrade = 1; break;
561 default: return 1;
563 return 0;
566 /* options common to -S -R -U */
567 static int parsearg_trans(int opt)
569 switch(opt) {
570 case 'd':
571 if(config->flags & PM_TRANS_FLAG_NODEPVERSION) {
572 config->flags |= PM_TRANS_FLAG_NODEPS;
573 } else {
574 config->flags |= PM_TRANS_FLAG_NODEPVERSION;
576 break;
577 case 'k': config->flags |= PM_TRANS_FLAG_DBONLY; break;
578 case OP_NOPROGRESSBAR: config->noprogressbar = 1; break;
579 case OP_NOSCRIPTLET: config->flags |= PM_TRANS_FLAG_NOSCRIPTLET; break;
580 case 'p': config->print = 1; break;
581 case OP_PRINTFORMAT:
582 check_optarg();
583 config->print_format = strdup(optarg);
584 break;
585 default: return 1;
587 return 0;
590 static int parsearg_remove(int opt)
592 if (parsearg_trans(opt) == 0)
593 return 0;
594 switch(opt) {
595 case 'c': config->flags |= PM_TRANS_FLAG_CASCADE; break;
596 case 'n': config->flags |= PM_TRANS_FLAG_NOSAVE; break;
597 case 's':
598 if(config->flags & PM_TRANS_FLAG_RECURSE) {
599 config->flags |= PM_TRANS_FLAG_RECURSEALL;
600 } else {
601 config->flags |= PM_TRANS_FLAG_RECURSE;
603 break;
604 case 'u': config->flags |= PM_TRANS_FLAG_UNNEEDED; break;
605 default: return 1;
607 return 0;
610 /* options common to -S -U */
611 static int parsearg_upgrade(int opt)
613 if (parsearg_trans(opt) == 0)
614 return 0;
615 switch(opt) {
616 case 'f': config->flags |= PM_TRANS_FLAG_FORCE; break;
617 case OP_ASDEPS: config->flags |= PM_TRANS_FLAG_ALLDEPS; break;
618 case OP_ASEXPLICIT: config->flags |= PM_TRANS_FLAG_ALLEXPLICIT; break;
619 case OP_IGNORE:
620 parsearg_util_addlist(alpm_option_add_ignorepkg);
621 break;
622 case OP_IGNOREGROUP:
623 parsearg_util_addlist(alpm_option_add_ignoregrp);
624 break;
625 default: return 1;
627 return 0;
630 static int parsearg_sync(int opt)
632 if (parsearg_upgrade(opt) == 0)
633 return 0;
634 switch(opt) {
635 case OP_NEEDED: config->flags |= PM_TRANS_FLAG_NEEDED; break;
636 case 'c': (config->op_s_clean)++; break;
637 case 'g': (config->group)++; break;
638 case 'i': (config->op_s_info)++; break;
639 case 'l': config->op_q_list = 1; break;
640 case 'q': config->quiet = 1; break;
641 case 's': config->op_s_search = 1; break;
642 case 'u': (config->op_s_upgrade)++; break;
643 case 'w':
644 config->op_s_downloadonly = 1;
645 config->flags |= PM_TRANS_FLAG_DOWNLOADONLY;
646 config->flags |= PM_TRANS_FLAG_NOCONFLICTS;
647 break;
648 case 'y': (config->op_s_sync)++; break;
649 default: return 1;
651 return 0;
654 /** Parse command-line arguments for each operation.
655 * @param argc argc
656 * @param argv argv
657 * @return 0 on success, 1 on error
659 static int parseargs(int argc, char *argv[])
661 int opt;
662 int option_index = 0;
663 int result;
664 const char *optstring = "DQRSTUVb:cdefghiklmnopqr:stuvwy";
665 static struct option opts[] =
667 {"database", no_argument, 0, 'D'},
668 {"query", no_argument, 0, 'Q'},
669 {"remove", no_argument, 0, 'R'},
670 {"sync", no_argument, 0, 'S'},
671 {"deptest", no_argument, 0, 'T'}, /* used by makepkg */
672 {"upgrade", no_argument, 0, 'U'},
673 {"version", no_argument, 0, 'V'},
674 {"dbpath", required_argument, 0, 'b'},
675 {"cascade", no_argument, 0, 'c'},
676 {"changelog", no_argument, 0, 'c'},
677 {"clean", no_argument, 0, 'c'},
678 {"nodeps", no_argument, 0, 'd'},
679 {"deps", no_argument, 0, 'd'},
680 {"explicit", no_argument, 0, 'e'},
681 {"force", no_argument, 0, 'f'},
682 {"groups", no_argument, 0, 'g'},
683 {"help", no_argument, 0, 'h'},
684 {"info", no_argument, 0, 'i'},
685 {"dbonly", no_argument, 0, 'k'},
686 {"check", no_argument, 0, 'k'},
687 {"list", no_argument, 0, 'l'},
688 {"foreign", no_argument, 0, 'm'},
689 {"nosave", no_argument, 0, 'n'},
690 {"owns", no_argument, 0, 'o'},
691 {"file", no_argument, 0, 'p'},
692 {"print", no_argument, 0, 'p'},
693 {"quiet", no_argument, 0, 'q'},
694 {"root", required_argument, 0, 'r'},
695 {"recursive", no_argument, 0, 's'},
696 {"search", no_argument, 0, 's'},
697 {"unrequired", no_argument, 0, 't'},
698 {"upgrades", no_argument, 0, 'u'},
699 {"sysupgrade", no_argument, 0, 'u'},
700 {"unneeded", no_argument, 0, 'u'},
701 {"verbose", no_argument, 0, 'v'},
702 {"downloadonly", no_argument, 0, 'w'},
703 {"refresh", no_argument, 0, 'y'},
704 {"noconfirm", no_argument, 0, OP_NOCONFIRM},
705 {"config", required_argument, 0, OP_CONFIG},
706 {"ignore", required_argument, 0, OP_IGNORE},
707 {"debug", optional_argument, 0, OP_DEBUG},
708 {"noprogressbar", no_argument, 0, OP_NOPROGRESSBAR},
709 {"noscriptlet", no_argument, 0, OP_NOSCRIPTLET},
710 {"ask", required_argument, 0, OP_ASK},
711 {"cachedir", required_argument, 0, OP_CACHEDIR},
712 {"asdeps", no_argument, 0, OP_ASDEPS},
713 {"logfile", required_argument, 0, OP_LOGFILE},
714 {"ignoregroup", required_argument, 0, OP_IGNOREGROUP},
715 {"needed", no_argument, 0, OP_NEEDED},
716 {"asexplicit", no_argument, 0, OP_ASEXPLICIT},
717 {"arch", required_argument, 0, OP_ARCH},
718 {"print-format", required_argument, 0, OP_PRINTFORMAT},
719 {"gpgdir", required_argument, 0, OP_GPGDIR},
720 {0, 0, 0, 0}
723 /* parse operation */
724 while((opt = getopt_long(argc, argv, optstring, opts, &option_index))) {
725 if(opt < 0) {
726 break;
727 } else if(opt == 0) {
728 continue;
729 } else if(opt == '?') {
730 /* unknown option, getopt printed an error */
731 return 1;
733 parsearg_op(opt, 0);
736 if(config->op == 0) {
737 pm_printf(PM_LOG_ERROR, _("only one operation may be used at a time\n"));
738 return 1;
740 if(config->help) {
741 usage(config->op, mbasename(argv[0]));
742 return 2;
744 if(config->version) {
745 version();
746 return 2;
749 /* parse all other options */
750 optind = 1;
751 while((opt = getopt_long(argc, argv, optstring, opts, &option_index))) {
752 if(opt < 0) {
753 break;
754 } else if(opt == 0) {
755 continue;
756 } else if(opt == '?') {
757 /* this should have failed during first pass already */
758 return 1;
759 } else if(parsearg_op(opt, 1) == 0) {
760 /* opt is an operation */
761 continue;
764 switch(config->op) {
765 case PM_OP_DATABASE:
766 result = parsearg_database(opt);
767 break;
768 case PM_OP_QUERY:
769 result = parsearg_query(opt);
770 break;
771 case PM_OP_REMOVE:
772 result = parsearg_remove(opt);
773 break;
774 case PM_OP_SYNC:
775 result = parsearg_sync(opt);
776 break;
777 case PM_OP_UPGRADE:
778 result = parsearg_upgrade(opt);
779 break;
780 case PM_OP_DEPTEST:
781 default:
782 result = 1;
783 break;
785 if (result == 0) {
786 continue;
789 /* fall back to global options */
790 result = parsearg_global(opt);
791 if(result != 0) {
792 /* global option parsing failed, abort */
793 pm_printf(PM_LOG_ERROR, _("invalid option\n"));
794 return result;
798 while(optind < argc) {
799 /* add the target to our target array */
800 pm_targets = alpm_list_add(pm_targets, strdup(argv[optind]));
801 optind++;
804 return 0;
807 /* helper for being used with setrepeatingoption */
808 static void option_add_holdpkg(const char *name) {
809 config->holdpkg = alpm_list_add(config->holdpkg, strdup(name));
812 /* helper for being used with setrepeatingoption */
813 static void option_add_syncfirst(const char *name) {
814 config->syncfirst = alpm_list_add(config->syncfirst, strdup(name));
817 /* helper for being used with setrepeatingoption */
818 static void option_add_cleanmethod(const char *value) {
819 if (strcmp(value, "KeepInstalled") == 0) {
820 config->cleanmethod |= PM_CLEAN_KEEPINST;
821 } else if (strcmp(value, "KeepCurrent") == 0) {
822 config->cleanmethod |= PM_CLEAN_KEEPCUR;
823 } else {
824 pm_printf(PM_LOG_ERROR, _("invalid value for 'CleanMethod' : '%s'\n"),
825 value);
829 /** Add repeating options such as NoExtract, NoUpgrade, etc to libalpm
830 * settings. Refactored out of the parseconfig code since all of them did
831 * the exact same thing and duplicated code.
832 * @param ptr a pointer to the start of the multiple options
833 * @param option the string (friendly) name of the option, used for messages
834 * @param optionfunc a function pointer to an alpm_option_add_* function
836 static void setrepeatingoption(char *ptr, const char *option,
837 void (*optionfunc)(const char*))
839 char *q;
841 while((q = strchr(ptr, ' '))) {
842 *q = '\0';
843 (*optionfunc)(ptr);
844 pm_printf(PM_LOG_DEBUG, "config: %s: %s\n", option, ptr);
845 ptr = q;
846 ptr++;
848 (*optionfunc)(ptr);
849 pm_printf(PM_LOG_DEBUG, "config: %s: %s\n", option, ptr);
852 static char *get_filename(const char *url) {
853 char *filename = strrchr(url, '/');
854 if(filename != NULL) {
855 filename++;
857 return filename;
860 static char *get_destfile(const char *path, const char *filename) {
861 char *destfile;
862 /* len = localpath len + filename len + null */
863 size_t len = strlen(path) + strlen(filename) + 1;
864 destfile = calloc(len, sizeof(char));
865 snprintf(destfile, len, "%s%s", path, filename);
867 return destfile;
870 static char *get_tempfile(const char *path, const char *filename) {
871 char *tempfile;
872 /* len = localpath len + filename len + '.part' len + null */
873 size_t len = strlen(path) + strlen(filename) + 6;
874 tempfile = calloc(len, sizeof(char));
875 snprintf(tempfile, len, "%s%s.part", path, filename);
877 return tempfile;
880 /** External fetch callback */
881 static int download_with_xfercommand(const char *url, const char *localpath,
882 int force) {
883 int ret = 0;
884 int retval;
885 int usepart = 0;
886 struct stat st;
887 char *parsedcmd,*tempcmd;
888 char cwd[PATH_MAX];
889 int restore_cwd = 0;
890 char *destfile, *tempfile, *filename;
892 if(!config->xfercommand) {
893 return -1;
896 filename = get_filename(url);
897 if(!filename) {
898 return -1;
900 destfile = get_destfile(localpath, filename);
901 tempfile = get_tempfile(localpath, filename);
903 if(force && stat(tempfile, &st) == 0) {
904 unlink(tempfile);
906 if(force && stat(destfile, &st) == 0) {
907 unlink(destfile);
910 tempcmd = strdup(config->xfercommand);
911 /* replace all occurrences of %o with fn.part */
912 if(strstr(tempcmd, "%o")) {
913 usepart = 1;
914 parsedcmd = strreplace(tempcmd, "%o", tempfile);
915 free(tempcmd);
916 tempcmd = parsedcmd;
918 /* replace all occurrences of %u with the download URL */
919 parsedcmd = strreplace(tempcmd, "%u", url);
920 free(tempcmd);
922 /* save the cwd so we can restore it later */
923 if(getcwd(cwd, PATH_MAX) == NULL) {
924 pm_printf(PM_LOG_ERROR, _("could not get current working directory\n"));
925 } else {
926 restore_cwd = 1;
929 /* cwd to the download directory */
930 if(chdir(localpath)) {
931 pm_printf(PM_LOG_WARNING, _("could not chdir to download directory %s\n"), localpath);
932 ret = -1;
933 goto cleanup;
935 /* execute the parsed command via /bin/sh -c */
936 pm_printf(PM_LOG_DEBUG, "running command: %s\n", parsedcmd);
937 retval = system(parsedcmd);
939 if(retval == -1) {
940 pm_printf(PM_LOG_WARNING, _("running XferCommand: fork failed!\n"));
941 ret = -1;
942 } else if(retval != 0) {
943 /* download failed */
944 pm_printf(PM_LOG_DEBUG, "XferCommand command returned non-zero status "
945 "code (%d)\n", retval);
946 ret = -1;
947 } else {
948 /* download was successful */
949 if(usepart) {
950 rename(tempfile, destfile);
952 ret = 0;
955 cleanup:
956 /* restore the old cwd if we have it */
957 if(restore_cwd && chdir(cwd) != 0) {
958 pm_printf(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), cwd, strerror(errno));
961 if(ret == -1) {
962 /* hack to let an user the time to cancel a download */
963 sleep(2);
965 free(destfile);
966 free(tempfile);
967 free(parsedcmd);
969 return ret;
972 static int _parse_options(const char *key, char *value,
973 const char *file, int linenum)
975 if(value == NULL) {
976 /* options without settings */
977 if(strcmp(key, "UseSyslog") == 0) {
978 alpm_option_set_usesyslog(1);
979 pm_printf(PM_LOG_DEBUG, "config: usesyslog\n");
980 } else if(strcmp(key, "ILoveCandy") == 0) {
981 config->chomp = 1;
982 pm_printf(PM_LOG_DEBUG, "config: chomp\n");
983 } else if(strcmp(key, "ShowSize") == 0) {
984 config->showsize = 1;
985 pm_printf(PM_LOG_DEBUG, "config: showsize\n");
986 } else if(strcmp(key, "UseDelta") == 0) {
987 alpm_option_set_usedelta(1);
988 pm_printf(PM_LOG_DEBUG, "config: usedelta\n");
989 } else if(strcmp(key, "TotalDownload") == 0) {
990 config->totaldownload = 1;
991 pm_printf(PM_LOG_DEBUG, "config: totaldownload\n");
992 } else if(strcmp(key, "CheckSpace") == 0) {
993 alpm_option_set_checkspace(1);
994 } else {
995 pm_printf(PM_LOG_WARNING,
996 _("config file %s, line %d: directive '%s' in section '%s' not recognized.\n"),
997 file, linenum, key, "options");
999 } else {
1000 /* options with settings */
1001 if(strcmp(key, "NoUpgrade") == 0) {
1002 setrepeatingoption(value, "NoUpgrade", alpm_option_add_noupgrade);
1003 } else if(strcmp(key, "NoExtract") == 0) {
1004 setrepeatingoption(value, "NoExtract", alpm_option_add_noextract);
1005 } else if(strcmp(key, "IgnorePkg") == 0) {
1006 setrepeatingoption(value, "IgnorePkg", alpm_option_add_ignorepkg);
1007 } else if(strcmp(key, "IgnoreGroup") == 0) {
1008 setrepeatingoption(value, "IgnoreGroup", alpm_option_add_ignoregrp);
1009 } else if(strcmp(key, "HoldPkg") == 0) {
1010 setrepeatingoption(value, "HoldPkg", option_add_holdpkg);
1011 } else if(strcmp(key, "SyncFirst") == 0) {
1012 setrepeatingoption(value, "SyncFirst", option_add_syncfirst);
1013 } else if(strcmp(key, "Architecture") == 0) {
1014 if(!alpm_option_get_arch()) {
1015 setarch(value);
1017 } else if(strcmp(key, "DBPath") == 0) {
1018 /* don't overwrite a path specified on the command line */
1019 if(!config->dbpath) {
1020 config->dbpath = strdup(value);
1021 pm_printf(PM_LOG_DEBUG, "config: dbpath: %s\n", value);
1023 } else if(strcmp(key, "CacheDir") == 0) {
1024 if(alpm_option_add_cachedir(value) != 0) {
1025 pm_printf(PM_LOG_ERROR, _("problem adding cachedir '%s' (%s)\n"),
1026 value, alpm_strerrorlast());
1027 return 1;
1029 pm_printf(PM_LOG_DEBUG, "config: cachedir: %s\n", value);
1030 } else if(strcmp(key, "RootDir") == 0) {
1031 /* don't overwrite a path specified on the command line */
1032 if(!config->rootdir) {
1033 config->rootdir = strdup(value);
1034 pm_printf(PM_LOG_DEBUG, "config: rootdir: %s\n", value);
1036 } else if (strcmp(key, "GPGDir") == 0) {
1037 if(!config->gpgdir) {
1038 config->gpgdir = strdup(value);
1039 pm_printf(PM_LOG_DEBUG, "config: gpgdir: %s\n", value);
1041 } else if (strcmp(key, "LogFile") == 0) {
1042 if(!config->logfile) {
1043 config->logfile = strdup(value);
1044 pm_printf(PM_LOG_DEBUG, "config: logfile: %s\n", value);
1046 } else if (strcmp(key, "XferCommand") == 0) {
1047 config->xfercommand = strdup(value);
1048 alpm_option_set_fetchcb(download_with_xfercommand);
1049 pm_printf(PM_LOG_DEBUG, "config: xfercommand: %s\n", value);
1050 } else if (strcmp(key, "CleanMethod") == 0) {
1051 setrepeatingoption(value, "CleanMethod", option_add_cleanmethod);
1052 } else {
1054 pm_printf(PM_LOG_WARNING,
1055 _("config file %s, line %d: directive '%s' in section '%s' not recognized.\n"),
1056 file, linenum, key, "options");
1060 return 0;
1063 static int _add_mirror(pmdb_t *db, char *value)
1065 const char *dbname = alpm_db_get_name(db);
1066 /* let's attempt a replacement for the current repo */
1067 char *temp = strreplace(value, "$repo", dbname);
1068 /* let's attempt a replacement for the arch */
1069 const char *arch = alpm_option_get_arch();
1070 char *server;
1071 if(arch) {
1072 server = strreplace(temp, "$arch", arch);
1073 free(temp);
1074 } else {
1075 if(strstr(temp, "$arch")) {
1076 free(temp);
1077 pm_printf(PM_LOG_ERROR, _("The mirror '%s' contains the $arch"
1078 " variable, but no Architecture is defined.\n"), value);
1079 return 1;
1081 server = temp;
1084 if(alpm_db_setserver(db, server) != 0) {
1085 /* pm_errno is set by alpm_db_setserver */
1086 pm_printf(PM_LOG_ERROR, _("could not add server URL to database '%s': %s (%s)\n"),
1087 dbname, server, alpm_strerrorlast());
1088 free(server);
1089 return 1;
1092 free(server);
1093 return 0;
1096 /* The real parseconfig. Called with a null section argument by the publicly
1097 * visible parseconfig so we can recall from within ourself on an include */
1098 static int _parseconfig(const char *file, const char *givensection,
1099 pmdb_t * const givendb)
1101 FILE *fp = NULL;
1102 char line[PATH_MAX+1];
1103 int linenum = 0;
1104 char *ptr, *section = NULL;
1105 pmdb_t *db = NULL;
1106 int ret = 0;
1108 pm_printf(PM_LOG_DEBUG, "config: attempting to read file %s\n", file);
1109 fp = fopen(file, "r");
1110 if(fp == NULL) {
1111 pm_printf(PM_LOG_ERROR, _("config file %s could not be read.\n"), file);
1112 return 1;
1115 /* if we are passed a section, use it as our starting point */
1116 if(givensection != NULL) {
1117 section = strdup(givensection);
1119 /* if we are passed a db, use it as our starting point */
1120 if(givendb != NULL) {
1121 db = givendb;
1124 while(fgets(line, PATH_MAX, fp)) {
1125 linenum++;
1126 strtrim(line);
1128 /* ignore whole line and end of line comments */
1129 if(strlen(line) == 0 || line[0] == '#') {
1130 continue;
1132 if((ptr = strchr(line, '#'))) {
1133 *ptr = '\0';
1136 if(line[0] == '[' && line[strlen(line)-1] == ']') {
1137 /* new config section, skip the '[' */
1138 ptr = line;
1139 ptr++;
1140 if(section) {
1141 free(section);
1143 section = strdup(ptr);
1144 section[strlen(section)-1] = '\0';
1145 pm_printf(PM_LOG_DEBUG, "config: new section '%s'\n", section);
1146 if(!strlen(section)) {
1147 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: bad section name.\n"),
1148 file, linenum);
1149 ret = 1;
1150 goto cleanup;
1152 /* if we are not looking at the options section, register a db */
1153 if(strcmp(section, "options") != 0) {
1154 db = alpm_db_register_sync(section);
1155 if(db == NULL) {
1156 pm_printf(PM_LOG_ERROR, _("could not register '%s' database (%s)\n"),
1157 section, alpm_strerrorlast());
1158 ret = 1;
1159 goto cleanup;
1162 continue;
1165 /* directive */
1166 char *key, *value;
1167 /* strsep modifies the 'line' string: 'key \0 value' */
1168 key = line;
1169 value = line;
1170 strsep(&value, "=");
1171 strtrim(key);
1172 strtrim(value);
1174 if(key == NULL) {
1175 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: syntax error in config file- missing key.\n"),
1176 file, linenum);
1177 ret = 1;
1178 goto cleanup;
1180 /* For each directive, compare to the camelcase string. */
1181 if(section == NULL) {
1182 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: All directives must belong to a section.\n"),
1183 file, linenum);
1184 ret = 1;
1185 goto cleanup;
1187 /* Include is allowed in both options and repo sections */
1188 if(strcmp(key, "Include") == 0) {
1189 if(value == NULL) {
1190 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive '%s' needs a value\n"),
1191 file, linenum, key);
1192 ret = 1;
1193 goto cleanup;
1195 /* Ignore include failures... assume non-critical */
1196 int globret;
1197 glob_t globbuf;
1198 globret = glob(value, GLOB_NOCHECK, NULL, &globbuf);
1199 switch(globret) {
1200 case GLOB_NOSPACE:
1201 pm_printf(PM_LOG_DEBUG,
1202 "config file %s, line %d: include globbing out of space\n",
1203 file, linenum);
1204 break;
1205 case GLOB_ABORTED:
1206 pm_printf(PM_LOG_DEBUG,
1207 "config file %s, line %d: include globbing read error for %s\n",
1208 file, linenum, value);
1209 break;
1210 case GLOB_NOMATCH:
1211 pm_printf(PM_LOG_DEBUG,
1212 "config file %s, line %d: no include found for %s\n",
1213 file, linenum, value);
1214 break;
1215 default:
1216 for(size_t gindex = 0; gindex < globbuf.gl_pathc; gindex++) {
1217 pm_printf(PM_LOG_DEBUG, "config file %s, line %d: including %s\n",
1218 file, linenum, globbuf.gl_pathv[gindex]);
1219 _parseconfig(globbuf.gl_pathv[gindex], section, db);
1221 break;
1223 globfree(&globbuf);
1224 continue;
1226 if(strcmp(section, "options") == 0) {
1227 /* we are either in options ... */
1228 if((ret = _parse_options(key, value, file, linenum)) != 0) {
1229 goto cleanup;
1231 } else {
1232 /* ... or in a repo section */
1233 if(strcmp(key, "Server") == 0) {
1234 if(value == NULL) {
1235 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive '%s' needs a value\n"),
1236 file, linenum, key);
1237 ret = 1;
1238 goto cleanup;
1240 if(_add_mirror(db, value) != 0) {
1241 ret = 1;
1242 goto cleanup;
1244 } else if(strcmp(key, "VerifySig") == 0) {
1245 if (strcmp(value, "Always") == 0) {
1246 ret = alpm_db_set_pgp_verify(db,PM_PGP_VERIFY_ALWAYS);
1247 } else if (strcmp(value, "Optional") == 0) {
1248 ret = alpm_db_set_pgp_verify(db,PM_PGP_VERIFY_OPTIONAL);
1249 } else if (strcmp(value, "Never") == 0) {
1250 ret = alpm_db_set_pgp_verify(db,PM_PGP_VERIFY_NEVER);
1251 } else {
1252 pm_printf(PM_LOG_ERROR, _("invalid value for 'VerifySig' : '%s'\n"), value);
1253 ret = 1;
1254 goto cleanup;
1256 if (ret != 0) {
1257 pm_printf(PM_LOG_ERROR, _("could not add pgp verify option to database '%s': %s (%s)\n"),
1258 alpm_db_get_name(db), value, alpm_strerrorlast());
1259 goto cleanup;
1261 pm_printf(PM_LOG_DEBUG, "config: VerifySig for %s: %s\n",alpm_db_get_name(db), value);
1262 } else {
1263 pm_printf(PM_LOG_WARNING,
1264 _("config file %s, line %d: directive '%s' in section '%s' not recognized.\n"),
1265 file, linenum, key, section);
1271 cleanup:
1272 fclose(fp);
1273 if(section){
1274 free(section);
1276 /* call setlibpaths here to ensure we have called it at least once */
1277 setlibpaths();
1278 pm_printf(PM_LOG_DEBUG, "config: finished parsing %s\n", file);
1279 return ret;
1282 /** Parse a configuration file.
1283 * @param file path to the config file.
1284 * @return 0 on success, non-zero on error
1286 static int parseconfig(const char *file)
1288 /* call the real parseconfig function with a null section & db argument */
1289 return _parseconfig(file, NULL, NULL);
1292 /** print commandline to logfile
1294 static void cl_to_log(int argc, char* argv[])
1296 size_t size = 0;
1297 int i;
1298 for(i = 0; i<argc; i++) {
1299 size += strlen(argv[i]) + 1;
1301 char *cl_text = malloc(size);
1302 if(!cl_text)
1303 return;
1304 char *p = cl_text;
1305 for(i = 0; i<argc-1; i++) {
1306 strcpy(p, argv[i]);
1307 p += strlen(argv[i]);
1308 *p++ = ' ';
1310 strcpy(p, argv[i]);
1311 alpm_logaction("Running '%s'\n", cl_text);
1312 free(cl_text);
1315 /** Main function.
1316 * @param argc argc
1317 * @param argv argv
1318 * @return A return code indicating success, failure, etc.
1320 int main(int argc, char *argv[])
1322 int ret = 0;
1323 struct sigaction new_action, old_action;
1324 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
1325 /* geteuid undefined in CYGWIN */
1326 uid_t myuid = geteuid();
1327 #endif
1329 #if defined(PACMAN_DEBUG) && defined(HAVE_MCHECK_H)
1330 /*setenv("MALLOC_TRACE","pacman.mtrace", 0);*/
1331 mtrace();
1332 #endif
1334 /* Set signal handlers */
1335 /* Set up the structure to specify the new action. */
1336 new_action.sa_handler = handler;
1337 sigemptyset(&new_action.sa_mask);
1338 new_action.sa_flags = 0;
1340 sigaction(SIGINT, NULL, &old_action);
1341 if(old_action.sa_handler != SIG_IGN) {
1342 sigaction(SIGINT, &new_action, NULL);
1344 sigaction(SIGTERM, NULL, &old_action);
1345 if(old_action.sa_handler != SIG_IGN) {
1346 sigaction(SIGTERM, &new_action, NULL);
1348 sigaction(SIGSEGV, NULL, &old_action);
1349 if(old_action.sa_handler != SIG_IGN) {
1350 sigaction(SIGSEGV, &new_action, NULL);
1353 /* i18n init */
1354 #if defined(ENABLE_NLS)
1355 localize();
1356 #endif
1358 /* set user agent for downloading */
1359 setuseragent();
1361 /* init config data */
1362 config = config_new();
1364 /* disable progressbar if the output is redirected */
1365 if(!isatty(1)) {
1366 config->noprogressbar = 1;
1369 /* initialize library */
1370 if(alpm_initialize() == -1) {
1371 pm_printf(PM_LOG_ERROR, _("failed to initialize alpm library (%s)\n"),
1372 alpm_strerrorlast());
1373 cleanup(EXIT_FAILURE);
1376 /* Setup logging as soon as possible, to print out maximum debugging info */
1377 alpm_option_set_logcb(cb_log);
1378 alpm_option_set_dlcb(cb_dl_progress);
1379 /* define paths to reasonable defaults */
1380 alpm_option_set_root(ROOTDIR);
1381 alpm_option_set_dbpath(DBPATH);
1382 alpm_option_set_signaturedir(GPGDIR);
1383 alpm_option_set_logfile(LOGFILE);
1385 /* Priority of options:
1386 * 1. command line
1387 * 2. config file
1388 * 3. compiled-in defaults
1389 * However, we have to parse the command line first because a config file
1390 * location can be specified here, so we need to make sure we prefer these
1391 * options over the config file coming second.
1394 /* parse the command line */
1395 ret = parseargs(argc, argv);
1396 if(ret != 0) {
1397 cleanup(ret);
1400 /* we support reading targets from stdin if a cmdline parameter is '-' */
1401 if(!isatty(fileno(stdin)) && alpm_list_find_str(pm_targets, "-")) {
1402 char line[PATH_MAX];
1403 int i = 0;
1405 /* remove the '-' from the list */
1406 pm_targets = alpm_list_remove_str(pm_targets, "-", NULL);
1408 while(i < PATH_MAX && (line[i] = (char)fgetc(stdin)) != EOF) {
1409 if(isspace((unsigned char)line[i])) {
1410 /* avoid adding zero length arg when multiple spaces separate args */
1411 if(i > 0) {
1412 line[i] = '\0';
1413 pm_targets = alpm_list_add(pm_targets, strdup(line));
1414 i = 0;
1416 } else {
1417 i++;
1420 /* check for buffer overflow */
1421 if (i >= PATH_MAX) {
1422 pm_printf(PM_LOG_ERROR, _("buffer overflow detected in arg parsing\n"));
1423 cleanup(EXIT_FAILURE);
1426 /* end of stream -- check for data still in line buffer */
1427 if(i > 0) {
1428 line[i] = '\0';
1429 pm_targets = alpm_list_add(pm_targets, strdup(line));
1431 if (!freopen(ctermid(NULL), "r", stdin)) {
1432 pm_printf(PM_LOG_ERROR, _("failed to reopen stdin for reading: (%s)\n"),
1433 strerror(errno));
1437 /* parse the config file */
1438 ret = parseconfig(config->configfile);
1439 if(ret != 0) {
1440 cleanup(ret);
1443 /* set TotalDownload callback if option enabled */
1444 if(config->totaldownload) {
1445 alpm_option_set_totaldlcb(cb_dl_total);
1448 /* noask is meant to be non-interactive */
1449 if(config->noask) {
1450 config->noconfirm = 1;
1453 /* set up the print operations */
1454 if(config->print) {
1455 config->noconfirm = 1;
1456 config->flags |= PM_TRANS_FLAG_NOCONFLICTS;
1457 config->flags |= PM_TRANS_FLAG_NOLOCK;
1458 /* Display only errors */
1459 config->logmask &= ~PM_LOG_WARNING;
1462 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
1463 /* check if we have sufficient permission for the requested operation */
1464 if(myuid > 0 && needs_root()) {
1465 pm_printf(PM_LOG_ERROR, _("you cannot perform this operation unless you are root.\n"));
1466 cleanup(EXIT_FAILURE);
1468 #endif
1470 if(config->verbose > 0) {
1471 alpm_list_t *i;
1472 printf("Root : %s\n", alpm_option_get_root());
1473 printf("Conf File : %s\n", config->configfile);
1474 printf("DB Path : %s\n", alpm_option_get_dbpath());
1475 printf("Cache Dirs: ");
1476 for(i = alpm_option_get_cachedirs(); i; i = alpm_list_next(i)) {
1477 printf("%s ", (char*)alpm_list_getdata(i));
1479 printf("\n");
1480 printf("Lock File : %s\n", alpm_option_get_lockfile());
1481 printf("Log File : %s\n", alpm_option_get_logfile());
1482 list_display("Targets :", pm_targets);
1485 /* Log commandline */
1486 if(needs_root()) {
1487 cl_to_log(argc, argv);
1490 /* start the requested operation */
1491 switch(config->op) {
1492 case PM_OP_DATABASE:
1493 ret = pacman_database(pm_targets);
1494 break;
1495 case PM_OP_REMOVE:
1496 ret = pacman_remove(pm_targets);
1497 break;
1498 case PM_OP_UPGRADE:
1499 ret = pacman_upgrade(pm_targets);
1500 break;
1501 case PM_OP_QUERY:
1502 ret = pacman_query(pm_targets);
1503 break;
1504 case PM_OP_SYNC:
1505 ret = pacman_sync(pm_targets);
1506 break;
1507 case PM_OP_DEPTEST:
1508 ret = pacman_deptest(pm_targets);
1509 break;
1510 default:
1511 pm_printf(PM_LOG_ERROR, _("no operation specified (use -h for help)\n"));
1512 ret = EXIT_FAILURE;
1515 cleanup(ret);
1516 /* not reached */
1517 return EXIT_SUCCESS;
1520 /* vim: set ts=2 sw=2 noet: */