Make debug config messages consistent in capitalization
[pacman-ng.git] / src / pacman / pacman.c
blob2cd99cbb4d035fa8dee17f99821daf4aa716da65
1 /*
2 * pacman.c
4 * Copyright (c) 2006-2010 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 <stdlib.h> /* atoi */
30 #include <stdio.h>
31 #include <limits.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <signal.h>
35 #include <unistd.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/utsname.h> /* uname */
39 #include <locale.h> /* setlocale */
40 #include <time.h> /* time_t */
41 #include <errno.h>
42 #include <glob.h>
43 #if defined(PACMAN_DEBUG) && defined(HAVE_MCHECK_H)
44 #include <mcheck.h> /* debug tracing (mtrace) */
45 #endif
47 /* alpm */
48 #include <alpm.h>
49 #include <alpm_list.h>
51 /* pacman */
52 #include "pacman.h"
53 #include "util.h"
54 #include "callback.h"
55 #include "conf.h"
56 #include "package.h"
58 pmdb_t *db_local;
59 /* list of targets specified on command line */
60 static alpm_list_t *pm_targets;
62 /** Display usage/syntax for the specified operation.
63 * @param op the operation code requested
64 * @param myname basename(argv[0])
66 static void usage(int op, const char * const myname)
68 /* prefetch some strings for usage below, which moves a lot of calls
69 * out of gettext. */
70 char const * const str_opt = _("options");
71 char const * const str_file = _("file(s)");
72 char const * const str_pkg = _("package(s)");
73 char const * const str_usg = _("usage");
74 char const * const str_opr = _("operation");
76 if(op == PM_OP_MAIN) {
77 printf("%s: %s <%s> [...]\n", str_usg, myname, str_opr);
78 printf(_("operations:\n"));
79 printf(" %s {-h --help}\n", myname);
80 printf(" %s {-V --version}\n", myname);
81 printf(" %s {-D --database} <%s> <%s>\n", myname, str_opt, str_pkg);
82 printf(" %s {-Q --query} [%s] [%s]\n", myname, str_opt, str_pkg);
83 printf(" %s {-R --remove} [%s] <%s>\n", myname, str_opt, str_pkg);
84 printf(" %s {-S --sync} [%s] [%s]\n", myname, str_opt, str_pkg);
85 printf(" %s {-U --upgrade} [%s] <%s>\n", myname, str_opt, str_file);
86 printf(_("\nuse '%s {-h --help}' with an operation for available options\n"),
87 myname);
88 } else {
89 if(op == PM_OP_REMOVE) {
90 printf("%s: %s {-R --remove} [%s] <%s>\n", str_usg, myname, str_opt, str_pkg);
91 printf("%s:\n", str_opt);
92 printf(_(" -c, --cascade remove packages and all packages that depend on them\n"));
93 printf(_(" -d, --nodeps skip dependency checks\n"));
94 printf(_(" -k, --dbonly only remove database entries, do not remove files\n"));
95 printf(_(" -n, --nosave remove configuration files as well\n"));
96 printf(_(" -s, --recursive remove dependencies also (that won't break packages)\n"
97 " (-ss includes explicitly installed dependencies too)\n"));
98 printf(_(" -u, --unneeded remove unneeded packages (that won't break packages)\n"));
99 printf(_(" --print only print the targets instead of performing the operation\n"));
100 printf(_(" --print-format <string>\n"
101 " specify how the targets should be printed\n"));
102 } else if(op == PM_OP_UPGRADE) {
103 printf("%s: %s {-U --upgrade} [%s] <%s>\n", str_usg, myname, str_opt, str_file);
104 printf("%s:\n", str_opt);
105 printf(_(" --asdeps install packages as non-explicitly installed\n"));
106 printf(_(" --asexplicit install packages as explicitly installed\n"));
107 printf(_(" -d, --nodeps skip dependency checks\n"));
108 printf(_(" -f, --force force install, overwrite conflicting files\n"));
109 printf(_(" -k, --dbonly add database entries, do not install or keep existing files\n"));
110 printf(_(" --print only print the targets instead of performing the operation\n"));
111 printf(_(" --print-format <string>\n"
112 " specify how the targets should be printed\n"));
113 } else if(op == PM_OP_QUERY) {
114 printf("%s: %s {-Q --query} [%s] [%s]\n", str_usg, myname, str_opt, str_pkg);
115 printf("%s:\n", str_opt);
116 printf(_(" -c, --changelog view the changelog of a package\n"));
117 printf(_(" -d, --deps list packages installed as dependencies [filter]\n"));
118 printf(_(" -e, --explicit list packages explicitly installed [filter]\n"));
119 printf(_(" -g, --groups view all members of a package group\n"));
120 printf(_(" -i, --info view package information (-ii for backup files)\n"));
121 printf(_(" -k, --check check that the files owned by the package(s) are present\n"));
122 printf(_(" -l, --list list the contents of the queried package\n"));
123 printf(_(" -m, --foreign list installed packages not found in sync db(s) [filter]\n"));
124 printf(_(" -o, --owns <file> query the package that owns <file>\n"));
125 printf(_(" -p, --file <package> query a package file instead of the database\n"));
126 printf(_(" -s, --search <regex> search locally-installed packages for matching strings\n"));
127 printf(_(" -t, --unrequired list packages not required by any package [filter]\n"));
128 printf(_(" -u, --upgrades list outdated packages [filter]\n"));
129 printf(_(" -q, --quiet show less information for query and search\n"));
130 } else if(op == PM_OP_SYNC) {
131 printf("%s: %s {-S --sync} [%s] [%s]\n", str_usg, myname, str_opt, str_pkg);
132 printf("%s:\n", str_opt);
133 printf(_(" --asdeps install packages as non-explicitly installed\n"));
134 printf(_(" --asexplicit install packages as explicitly installed\n"));
135 printf(_(" -c, --clean remove old packages from cache directory (-cc for all)\n"));
136 printf(_(" -d, --nodeps skip dependency checks\n"));
137 printf(_(" -f, --force force install, overwrite conflicting files\n"));
138 printf(_(" -g, --groups view all members of a package group\n"));
139 printf(_(" -i, --info view package information\n"));
140 printf(_(" -l, --list <repo> view a list of packages in a repo\n"));
141 printf(_(" -s, --search <regex> search remote repositories for matching strings\n"));
142 printf(_(" -u, --sysupgrade upgrade installed packages (-uu allows downgrade)\n"));
143 printf(_(" -w, --downloadonly download packages but do not install/upgrade anything\n"));
144 printf(_(" -y, --refresh download fresh package databases from the server\n"));
145 printf(_(" --needed don't reinstall up to date packages\n"));
146 printf(_(" --ignore <pkg> ignore a package upgrade (can be used more than once)\n"));
147 printf(_(" --ignoregroup <grp>\n"
148 " ignore a group upgrade (can be used more than once)\n"));
149 printf(_(" --print only print the targets instead of performing the operation\n"));
150 printf(_(" --print-format <string>\n"
151 " specify how the targets should be printed\n"));
152 printf(_(" -q, --quiet show less information for query and search\n"));
153 } else if (op == PM_OP_DATABASE) {
154 printf("%s: %s {-D --database} <%s> <%s>\n", str_usg, myname, str_opt, str_pkg);
155 printf("%s:\n", str_opt);
156 printf(_(" --asdeps mark packages as non-explicitly installed\n"));
157 printf(_(" --asexplicit mark packages as explicitly installed\n"));
159 printf(_(" --config <path> set an alternate configuration file\n"));
160 printf(_(" --logfile <path> set an alternate log file\n"));
161 printf(_(" --noconfirm do not ask for any confirmation\n"));
162 printf(_(" --noprogressbar do not show a progress bar when downloading files\n"));
163 printf(_(" --noscriptlet do not execute the install scriptlet if one exists\n"));
164 printf(_(" -v, --verbose be verbose\n"));
165 printf(_(" --debug display debug messages\n"));
166 printf(_(" -r, --root <path> set an alternate installation root\n"));
167 printf(_(" -b, --dbpath <path> set an alternate database location\n"));
168 printf(_(" --cachedir <dir> set an alternate package cache location\n"));
169 printf(_(" --arch <arch> set an alternate architecture\n"));
173 /** Output pacman version and copyright.
175 static void version(void)
177 printf("\n");
178 printf(" .--. Pacman v%s - libalpm v%s\n", PACKAGE_VERSION, alpm_version());
179 printf("/ _.-' .-. .-. .-. Copyright (C) 2006-2010 Pacman Development Team\n");
180 printf("\\ '-. '-' '-' '-' Copyright (C) 2002-2006 Judd Vinet\n");
181 printf(" '--'\n");
182 printf(_(" This program may be freely redistributed under\n"
183 " the terms of the GNU General Public License.\n"));
184 printf("\n");
187 /** Sets up gettext localization. Safe to call multiple times.
189 /* Inspired by the monotone function localize_monotone. */
190 #if defined(ENABLE_NLS)
191 static void localize(void)
193 static int init = 0;
194 if (!init) {
195 setlocale(LC_ALL, "");
196 bindtextdomain(PACKAGE, LOCALEDIR);
197 textdomain(PACKAGE);
198 init = 1;
201 #endif
203 /** Set user agent environment variable.
205 static void setuseragent(void)
207 char agent[101];
208 struct utsname un;
210 uname(&un);
211 snprintf(agent, 100, "pacman/%s (%s %s) libalpm/%s",
212 PACKAGE_VERSION, un.sysname, un.machine, alpm_version());
213 setenv("HTTP_USER_AGENT", agent, 0);
216 static void setarch(const char *arch)
218 if (strcmp(arch, "auto") == 0) {
219 struct utsname un;
220 uname(&un);
221 pm_printf(PM_LOG_DEBUG, "config: Architecture: %s\n", un.machine);
222 alpm_option_set_arch(un.machine);
223 } else {
224 pm_printf(PM_LOG_DEBUG, "config: Architecture: %s\n", arch);
225 alpm_option_set_arch(arch);
229 /** Free the resources.
231 * @param ret the return value
233 static void cleanup(int ret) {
234 /* free alpm library resources */
235 if(alpm_release() == -1) {
236 pm_printf(PM_LOG_ERROR, "%s\n", alpm_strerrorlast());
239 /* free memory */
240 FREELIST(pm_targets);
241 if(config) {
242 config_free(config);
243 config = NULL;
246 exit(ret);
249 /** Write function that correctly handles EINTR.
251 static ssize_t xwrite(int fd, const void *buf, size_t count)
253 ssize_t ret;
254 do {
255 ret = write(fd, buf, count);
256 } while(ret == -1 && errno == EINTR);
257 return(ret);
260 /** Catches thrown signals. Performs necessary cleanup to ensure database is
261 * in a consistant state.
262 * @param signum the thrown signal
264 static RETSIGTYPE handler(int signum)
266 int out = fileno(stdout);
267 int err = fileno(stderr);
268 if(signum == SIGSEGV) {
269 const char *msg1 = "error: segmentation fault\n";
270 const char *msg2 = "Internal pacman error: Segmentation fault.\n"
271 "Please submit a full bug report with --debug if appropriate.\n";
272 /* write a error message to out, the rest to err */
273 xwrite(out, msg1, strlen(msg1));
274 xwrite(err, msg2, strlen(msg2));
275 exit(signum);
276 } else if((signum == SIGINT)) {
277 const char *msg = "\nInterrupt signal received\n";
278 xwrite(err, msg, strlen(msg));
279 if(alpm_trans_interrupt() == 0) {
280 /* a transaction is being interrupted, don't exit pacman yet. */
281 return;
283 /* no commiting transaction, we can release it now and then exit pacman */
284 alpm_trans_release();
285 /* output a newline to be sure we clear any line we may be on */
286 xwrite(out, "\n", 1);
288 cleanup(signum);
291 /** Sets all libalpm required paths in one go. Called after the command line
292 * and inital config file parsing. Once this is complete, we can see if any
293 * paths were defined. If a rootdir was defined and nothing else, we want all
294 * of our paths to live under the rootdir that was specified. Safe to call
295 * multiple times (will only do anything the first time).
297 static void setlibpaths(void)
299 static int init = 0;
300 if (!init) {
301 int ret = 0;
303 pm_printf(PM_LOG_DEBUG, "setlibpaths() called\n");
304 /* Configure root path first. If it is set and dbpath/logfile were not
305 * set, then set those as well to reside under the root. */
306 if(config->rootdir) {
307 char path[PATH_MAX];
308 ret = alpm_option_set_root(config->rootdir);
309 if(ret != 0) {
310 pm_printf(PM_LOG_ERROR, _("problem setting rootdir '%s' (%s)\n"),
311 config->rootdir, alpm_strerrorlast());
312 cleanup(ret);
314 if(!config->dbpath) {
315 /* omit leading slash from our static DBPATH, root handles it */
316 snprintf(path, PATH_MAX, "%s%s", alpm_option_get_root(), DBPATH + 1);
317 config->dbpath = strdup(path);
319 if(!config->logfile) {
320 /* omit leading slash from our static LOGFILE path, root handles it */
321 snprintf(path, PATH_MAX, "%s%s", alpm_option_get_root(), LOGFILE + 1);
322 config->logfile = strdup(path);
325 /* Set other paths if they were configured. Note that unless rootdir
326 * was left undefined, these two paths (dbpath and logfile) will have
327 * been set locally above, so the if cases below will now trigger. */
328 if(config->dbpath) {
329 ret = alpm_option_set_dbpath(config->dbpath);
330 if(ret != 0) {
331 pm_printf(PM_LOG_ERROR, _("problem setting dbpath '%s' (%s)\n"),
332 config->dbpath, alpm_strerrorlast());
333 cleanup(ret);
336 if(config->logfile) {
337 ret = alpm_option_set_logfile(config->logfile);
338 if(ret != 0) {
339 pm_printf(PM_LOG_ERROR, _("problem setting logfile '%s' (%s)\n"),
340 config->logfile, alpm_strerrorlast());
341 cleanup(ret);
345 /* add a default cachedir if one wasn't specified */
346 if(alpm_option_get_cachedirs() == NULL) {
347 alpm_option_add_cachedir(CACHEDIR);
349 init = 1;
353 #define check_optarg() if(!optarg) { return(1); }
355 /** Parse command-line arguments for each operation.
356 * @param argc argc
357 * @param argv argv
358 * @return 0 on success, 1 on error
360 static int parseargs(int argc, char *argv[])
362 int opt;
363 int option_index = 0;
364 static struct option opts[] =
366 {"database", no_argument, 0, 'D'},
367 {"query", no_argument, 0, 'Q'},
368 {"remove", no_argument, 0, 'R'},
369 {"sync", no_argument, 0, 'S'},
370 {"deptest", no_argument, 0, 'T'}, /* used by makepkg */
371 {"upgrade", no_argument, 0, 'U'},
372 {"version", no_argument, 0, 'V'},
373 {"dbpath", required_argument, 0, 'b'},
374 {"cascade", no_argument, 0, 'c'},
375 {"changelog", no_argument, 0, 'c'},
376 {"clean", no_argument, 0, 'c'},
377 {"nodeps", no_argument, 0, 'd'},
378 {"deps", no_argument, 0, 'd'},
379 {"explicit", no_argument, 0, 'e'},
380 {"force", no_argument, 0, 'f'},
381 {"groups", no_argument, 0, 'g'},
382 {"help", no_argument, 0, 'h'},
383 {"info", no_argument, 0, 'i'},
384 {"dbonly", no_argument, 0, 'k'},
385 {"check", no_argument, 0, 'k'},
386 {"list", no_argument, 0, 'l'},
387 {"foreign", no_argument, 0, 'm'},
388 {"nosave", no_argument, 0, 'n'},
389 {"owns", no_argument, 0, 'o'},
390 {"file", no_argument, 0, 'p'},
391 {"print", no_argument, 0, 'p'},
392 {"quiet", no_argument, 0, 'q'},
393 {"root", required_argument, 0, 'r'},
394 {"recursive", no_argument, 0, 's'},
395 {"search", no_argument, 0, 's'},
396 {"unrequired", no_argument, 0, 't'},
397 {"upgrades", no_argument, 0, 'u'},
398 {"sysupgrade", no_argument, 0, 'u'},
399 {"unneeded", no_argument, 0, 'u'},
400 {"verbose", no_argument, 0, 'v'},
401 {"downloadonly", no_argument, 0, 'w'},
402 {"refresh", no_argument, 0, 'y'},
403 {"noconfirm", no_argument, 0, OP_NOCONFIRM},
404 {"config", required_argument, 0, OP_CONFIG},
405 {"ignore", required_argument, 0, OP_IGNORE},
406 {"debug", optional_argument, 0, OP_DEBUG},
407 {"noprogressbar", no_argument, 0, OP_NOPROGRESSBAR},
408 {"noscriptlet", no_argument, 0, OP_NOSCRIPTLET},
409 {"ask", required_argument, 0, OP_ASK},
410 {"cachedir", required_argument, 0, OP_CACHEDIR},
411 {"asdeps", no_argument, 0, OP_ASDEPS},
412 {"logfile", required_argument, 0, OP_LOGFILE},
413 {"ignoregroup", required_argument, 0, OP_IGNOREGROUP},
414 {"needed", no_argument, 0, OP_NEEDED},
415 {"asexplicit", no_argument, 0, OP_ASEXPLICIT},
416 {"arch", required_argument, 0, OP_ARCH},
417 {"print-format", required_argument, 0, OP_PRINTFORMAT},
418 {0, 0, 0, 0}
421 while((opt = getopt_long(argc, argv, "DQRSTUVb:cdefghiklmnopqr:stuvwy", opts, &option_index))) {
422 alpm_list_t *list = NULL, *item = NULL; /* lists for splitting strings */
424 if(opt < 0) {
425 break;
427 switch(opt) {
428 case 0: break;
429 case OP_NOCONFIRM: config->noconfirm = 1; break;
430 case OP_CONFIG:
431 check_optarg();
432 if(config->configfile) {
433 free(config->configfile);
435 config->configfile = strndup(optarg, PATH_MAX);
436 break;
437 case OP_IGNORE:
438 check_optarg();
439 list = strsplit(optarg, ',');
440 for(item = list; item; item = alpm_list_next(item)) {
441 alpm_option_add_ignorepkg((char *)alpm_list_getdata(item));
443 FREELIST(list);
444 break;
445 case OP_DEBUG:
446 /* debug levels are made more 'human readable' than using a raw logmask
447 * here, error and warning are set in config_new, though perhaps a
448 * --quiet option will remove these later */
449 if(optarg) {
450 unsigned short debug = atoi(optarg);
451 switch(debug) {
452 case 2:
453 config->logmask |= PM_LOG_FUNCTION; /* fall through */
454 case 1:
455 config->logmask |= PM_LOG_DEBUG;
456 break;
457 default:
458 pm_printf(PM_LOG_ERROR, _("'%s' is not a valid debug level\n"),
459 optarg);
460 return(1);
462 } else {
463 config->logmask |= PM_LOG_DEBUG;
465 /* progress bars get wonky with debug on, shut them off */
466 config->noprogressbar = 1;
467 break;
468 case OP_NOPROGRESSBAR: config->noprogressbar = 1; break;
469 case OP_NOSCRIPTLET: config->flags |= PM_TRANS_FLAG_NOSCRIPTLET; break;
470 case OP_ASK:
471 check_optarg();
472 config->noask = 1;
473 config->ask = atoi(optarg);
474 break;
475 case OP_CACHEDIR:
476 check_optarg();
477 if(alpm_option_add_cachedir(optarg) != 0) {
478 pm_printf(PM_LOG_ERROR, _("problem adding cachedir '%s' (%s)\n"),
479 optarg, alpm_strerrorlast());
480 return(1);
482 break;
483 case OP_ASDEPS:
484 config->flags |= PM_TRANS_FLAG_ALLDEPS;
485 break;
486 case OP_LOGFILE:
487 check_optarg();
488 config->logfile = strndup(optarg, PATH_MAX);
489 break;
490 case OP_IGNOREGROUP:
491 check_optarg();
492 list = strsplit(optarg, ',');
493 for(item = list; item; item = alpm_list_next(item)) {
494 alpm_option_add_ignoregrp((char *)alpm_list_getdata(item));
496 FREELIST(list);
497 break;
498 case OP_NEEDED: config->flags |= PM_TRANS_FLAG_NEEDED; break;
499 case OP_ASEXPLICIT:
500 config->flags |= PM_TRANS_FLAG_ALLEXPLICIT;
501 break;
502 case OP_ARCH:
503 check_optarg();
504 setarch(optarg);
505 break;
506 case OP_PRINTFORMAT:
507 check_optarg();
508 config->print_format = strdup(optarg);
509 break;
510 case 'D': config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DATABASE); break;
511 case 'Q': config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_QUERY); break;
512 case 'R': config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_REMOVE); break;
513 case 'S': config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_SYNC); break;
514 case 'T': config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_DEPTEST); break;
515 case 'U': config->op = (config->op != PM_OP_MAIN ? 0 : PM_OP_UPGRADE); break;
516 case 'V': config->version = 1; break;
517 case 'b':
518 check_optarg();
519 config->dbpath = strdup(optarg);
520 break;
521 case 'c':
522 (config->op_s_clean)++;
523 config->flags |= PM_TRANS_FLAG_CASCADE;
524 config->op_q_changelog = 1;
525 break;
526 case 'd':
527 config->op_q_deps = 1;
528 config->flags |= PM_TRANS_FLAG_NODEPS;
529 break;
530 case 'e':
531 config->op_q_explicit = 1;
532 break;
533 case 'f': config->flags |= PM_TRANS_FLAG_FORCE; break;
534 case 'g': (config->group)++; break;
535 case 'h': config->help = 1; break;
536 case 'i': (config->op_q_info)++; (config->op_s_info)++; break;
537 case 'k':
538 config->flags |= PM_TRANS_FLAG_DBONLY;
539 config->op_q_check = 1;
540 break;
541 case 'l': config->op_q_list = 1; break;
542 case 'm': config->op_q_foreign = 1; break;
543 case 'n': config->flags |= PM_TRANS_FLAG_NOSAVE; break;
544 case 'o': config->op_q_owns = 1; break;
545 case 'p':
546 config->op_q_isfile = 1;
547 config->print = 1;
548 break;
549 case 'q':
550 config->quiet = 1;
551 break;
552 case 'r':
553 check_optarg();
554 config->rootdir = strdup(optarg);
555 break;
556 case 's':
557 config->op_s_search = 1;
558 config->op_q_search = 1;
559 if(config->flags & PM_TRANS_FLAG_RECURSE) {
560 config->flags |= PM_TRANS_FLAG_RECURSEALL;
561 } else {
562 config->flags |= PM_TRANS_FLAG_RECURSE;
564 break;
565 case 't':
566 config->op_q_unrequired = 1;
567 break;
568 case 'u':
569 (config->op_s_upgrade)++;
570 config->op_q_upgrade = 1;
571 config->flags |= PM_TRANS_FLAG_UNNEEDED;
572 break;
573 case 'v': (config->verbose)++; break;
574 case 'w':
575 config->op_s_downloadonly = 1;
576 config->flags |= PM_TRANS_FLAG_DOWNLOADONLY;
577 config->flags |= PM_TRANS_FLAG_NOCONFLICTS;
578 break;
579 case 'y': (config->op_s_sync)++; break;
580 case '?': return(1);
581 default: return(1);
585 if(config->op == 0) {
586 pm_printf(PM_LOG_ERROR, _("only one operation may be used at a time\n"));
587 return(1);
590 if(config->help) {
591 usage(config->op, mbasename(argv[0]));
592 return(2);
594 if(config->version) {
595 version();
596 return(2);
599 while(optind < argc) {
600 /* add the target to our target array */
601 pm_targets = alpm_list_add(pm_targets, strdup(argv[optind]));
602 optind++;
605 return(0);
608 /* helper for being used with setrepeatingoption */
609 static void option_add_holdpkg(const char *name) {
610 config->holdpkg = alpm_list_add(config->holdpkg, strdup(name));
613 /* helper for being used with setrepeatingoption */
614 static void option_add_syncfirst(const char *name) {
615 config->syncfirst = alpm_list_add(config->syncfirst, strdup(name));
618 /** Add repeating options such as NoExtract, NoUpgrade, etc to libalpm
619 * settings. Refactored out of the parseconfig code since all of them did
620 * the exact same thing and duplicated code.
621 * @param ptr a pointer to the start of the multiple options
622 * @param option the string (friendly) name of the option, used for messages
623 * @param optionfunc a function pointer to an alpm_option_add_* function
625 static void setrepeatingoption(const char *ptr, const char *option,
626 void (*optionfunc)(const char*))
628 char *p = (char*)ptr;
629 char *q;
631 while((q = strchr(p, ' '))) {
632 *q = '\0';
633 (*optionfunc)(p);
634 pm_printf(PM_LOG_DEBUG, "config: %s: %s\n", option, p);
635 p = q;
636 p++;
638 (*optionfunc)(p);
639 pm_printf(PM_LOG_DEBUG, "config: %s: %s\n", option, p);
642 static char *get_filename(const char *url) {
643 char *filename = strrchr(url, '/');
644 if(filename != NULL) {
645 filename++;
647 return(filename);
650 static char *get_destfile(const char *path, const char *filename) {
651 char *destfile;
652 /* len = localpath len + filename len + null */
653 size_t len = strlen(path) + strlen(filename) + 1;
654 destfile = calloc(len, sizeof(char));
655 snprintf(destfile, len, "%s%s", path, filename);
657 return(destfile);
660 static char *get_tempfile(const char *path, const char *filename) {
661 char *tempfile;
662 /* len = localpath len + filename len + '.part' len + null */
663 size_t len = strlen(path) + strlen(filename) + 6;
664 tempfile = calloc(len, sizeof(char));
665 snprintf(tempfile, len, "%s%s.part", path, filename);
667 return(tempfile);
670 /** External fetch callback */
671 int download_with_xfercommand(const char *url, const char *localpath,
672 int force) {
673 int ret = 0;
674 int retval;
675 int usepart = 0;
676 struct stat st;
677 char *parsedcmd,*tempcmd;
678 char cwd[PATH_MAX];
679 char *destfile, *tempfile, *filename;
681 if(!config->xfercommand) {
682 return -1;
685 filename = get_filename(url);
686 if(!filename) {
687 return -1;
689 destfile = get_destfile(localpath, filename);
690 tempfile = get_tempfile(localpath, filename);
692 if(force && stat(tempfile, &st) == 0) {
693 unlink(tempfile);
695 if(force && stat(destfile, &st) == 0) {
696 unlink(destfile);
699 tempcmd = strdup(config->xfercommand);
700 /* replace all occurrences of %o with fn.part */
701 if(strstr(tempcmd, "%o")) {
702 usepart = 1;
703 parsedcmd = strreplace(tempcmd, "%o", tempfile);
704 free(tempcmd);
705 tempcmd = parsedcmd;
707 /* replace all occurrences of %u with the download URL */
708 parsedcmd = strreplace(tempcmd, "%u", url);
709 free(tempcmd);
711 /* cwd to the download directory */
712 getcwd(cwd, PATH_MAX);
713 if(chdir(localpath)) {
714 pm_printf(PM_LOG_WARNING, _("could not chdir to download directory %s\n"), localpath);
715 ret = -1;
716 goto cleanup;
718 /* execute the parsed command via /bin/sh -c */
719 pm_printf(PM_LOG_DEBUG, "running command: %s\n", parsedcmd);
720 retval = system(parsedcmd);
722 if(retval == -1) {
723 pm_printf(PM_LOG_WARNING, _("running XferCommand: fork failed!\n"));
724 ret = -1;
725 } else if(retval != 0) {
726 /* download failed */
727 pm_printf(PM_LOG_DEBUG, "XferCommand command returned non-zero status "
728 "code (%d)\n", retval);
729 ret = -1;
730 } else {
731 /* download was successful */
732 if(usepart) {
733 rename(tempfile, destfile);
735 ret = 0;
738 cleanup:
739 chdir(cwd);
740 if(ret == -1) {
741 /* hack to let an user the time to cancel a download */
742 sleep(2);
744 free(destfile);
745 free(tempfile);
746 free(parsedcmd);
748 return(ret);
751 static int _parse_options(char *key, char *value)
753 if(value == NULL) {
754 /* options without settings */
755 if(strcmp(key, "UseSyslog") == 0) {
756 alpm_option_set_usesyslog(1);
757 pm_printf(PM_LOG_DEBUG, "config: usesyslog\n");
758 } else if(strcmp(key, "ILoveCandy") == 0) {
759 config->chomp = 1;
760 pm_printf(PM_LOG_DEBUG, "config: chomp\n");
761 } else if(strcmp(key, "ShowSize") == 0) {
762 config->showsize = 1;
763 pm_printf(PM_LOG_DEBUG, "config: showsize\n");
764 } else if(strcmp(key, "UseDelta") == 0) {
765 alpm_option_set_usedelta(1);
766 pm_printf(PM_LOG_DEBUG, "config: usedelta\n");
767 } else if(strcmp(key, "TotalDownload") == 0) {
768 config->totaldownload = 1;
769 pm_printf(PM_LOG_DEBUG, "config: totaldownload\n");
770 } else {
771 pm_printf(PM_LOG_ERROR, _("directive '%s' without value not recognized\n"), key);
772 return(1);
774 } else {
775 /* options with settings */
776 if(strcmp(key, "NoUpgrade") == 0) {
777 setrepeatingoption(value, "NoUpgrade", alpm_option_add_noupgrade);
778 } else if(strcmp(key, "NoExtract") == 0) {
779 setrepeatingoption(value, "NoExtract", alpm_option_add_noextract);
780 } else if(strcmp(key, "IgnorePkg") == 0) {
781 setrepeatingoption(value, "IgnorePkg", alpm_option_add_ignorepkg);
782 } else if(strcmp(key, "IgnoreGroup") == 0) {
783 setrepeatingoption(value, "IgnoreGroup", alpm_option_add_ignoregrp);
784 } else if(strcmp(key, "HoldPkg") == 0) {
785 setrepeatingoption(value, "HoldPkg", option_add_holdpkg);
786 } else if(strcmp(key, "SyncFirst") == 0) {
787 setrepeatingoption(value, "SyncFirst", option_add_syncfirst);
788 } else if(strcmp(key, "Architecture") == 0) {
789 if(!alpm_option_get_arch()) {
790 setarch(value);
792 } else if(strcmp(key, "DBPath") == 0) {
793 /* don't overwrite a path specified on the command line */
794 if(!config->dbpath) {
795 config->dbpath = strdup(value);
796 pm_printf(PM_LOG_DEBUG, "config: dbpath: %s\n", value);
798 } else if(strcmp(key, "CacheDir") == 0) {
799 if(alpm_option_add_cachedir(value) != 0) {
800 pm_printf(PM_LOG_ERROR, _("problem adding cachedir '%s' (%s)\n"),
801 value, alpm_strerrorlast());
802 return(1);
804 pm_printf(PM_LOG_DEBUG, "config: cachedir: %s\n", value);
805 } else if(strcmp(key, "RootDir") == 0) {
806 /* don't overwrite a path specified on the command line */
807 if(!config->rootdir) {
808 config->rootdir = strdup(value);
809 pm_printf(PM_LOG_DEBUG, "config: rootdir: %s\n", value);
811 } else if (strcmp(key, "LogFile") == 0) {
812 if(!config->logfile) {
813 config->logfile = strdup(value);
814 pm_printf(PM_LOG_DEBUG, "config: logfile: %s\n", value);
816 } else if (strcmp(key, "XferCommand") == 0) {
817 config->xfercommand = strdup(value);
818 alpm_option_set_fetchcb(download_with_xfercommand);
819 pm_printf(PM_LOG_DEBUG, "config: xfercommand: %s\n", value);
820 } else if (strcmp(key, "CleanMethod") == 0) {
821 if (strcmp(value, "KeepInstalled") == 0) {
822 config->cleanmethod = PM_CLEAN_KEEPINST;
823 } else if (strcmp(value, "KeepCurrent") == 0) {
824 config->cleanmethod = PM_CLEAN_KEEPCUR;
825 } else {
826 pm_printf(PM_LOG_ERROR, _("invalid value for 'CleanMethod' : '%s'\n"), value);
827 return(1);
829 pm_printf(PM_LOG_DEBUG, "config: cleanmethod: %s\n", value);
830 } else {
831 pm_printf(PM_LOG_ERROR, _("directive '%s' with a value not recognized\n"), key);
832 return(1);
836 return(0);
839 static int _add_mirror(pmdb_t *db, char *value)
841 const char *dbname = alpm_db_get_name(db);
842 /* let's attempt a replacement for the current repo */
843 char *temp = strreplace(value, "$repo", dbname);
844 /* let's attempt a replacement for the arch */
845 const char *arch = alpm_option_get_arch();
846 char *server;
847 if(arch) {
848 server = strreplace(temp, "$arch", arch);
849 free(temp);
850 } else {
851 if(strstr(temp, "$arch")) {
852 free(temp);
853 pm_printf(PM_LOG_ERROR, _("The mirror '%s' contains the $arch"
854 " variable, but no Architecture is defined.\n"), value);
855 return(1);
857 server = temp;
860 if(alpm_db_setserver(db, server) != 0) {
861 /* pm_errno is set by alpm_db_setserver */
862 pm_printf(PM_LOG_ERROR, _("could not add server URL to database '%s': %s (%s)\n"),
863 dbname, server, alpm_strerrorlast());
864 free(server);
865 return(1);
868 free(server);
869 return(0);
872 /* The real parseconfig. Called with a null section argument by the publicly
873 * visible parseconfig so we can recall from within ourself on an include */
874 static int _parseconfig(const char *file, const char *givensection,
875 pmdb_t * const givendb)
877 FILE *fp = NULL;
878 char line[PATH_MAX+1];
879 int linenum = 0;
880 char *ptr, *section = NULL;
881 pmdb_t *db = NULL;
882 int ret = 0;
884 pm_printf(PM_LOG_DEBUG, "config: attempting to read file %s\n", file);
885 fp = fopen(file, "r");
886 if(fp == NULL) {
887 pm_printf(PM_LOG_ERROR, _("config file %s could not be read.\n"), file);
888 return(1);
891 /* if we are passed a section, use it as our starting point */
892 if(givensection != NULL) {
893 section = strdup(givensection);
895 /* if we are passed a db, use it as our starting point */
896 if(givendb != NULL) {
897 db = givendb;
900 while(fgets(line, PATH_MAX, fp)) {
901 linenum++;
902 strtrim(line);
904 /* ignore whole line and end of line comments */
905 if(strlen(line) == 0 || line[0] == '#') {
906 continue;
908 if((ptr = strchr(line, '#'))) {
909 *ptr = '\0';
912 if(line[0] == '[' && line[strlen(line)-1] == ']') {
913 /* new config section, skip the '[' */
914 ptr = line;
915 ptr++;
916 if(section) {
917 free(section);
919 section = strdup(ptr);
920 section[strlen(section)-1] = '\0';
921 pm_printf(PM_LOG_DEBUG, "config: new section '%s'\n", section);
922 if(!strlen(section)) {
923 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: bad section name.\n"),
924 file, linenum);
925 ret = 1;
926 goto cleanup;
928 /* if we are not looking at the options section, register a db */
929 if(strcmp(section, "options") != 0) {
930 db = alpm_db_register_sync(section);
931 if(db == NULL) {
932 pm_printf(PM_LOG_ERROR, _("could not register '%s' database (%s)\n"),
933 section, alpm_strerrorlast());
934 ret = 1;
935 goto cleanup;
938 continue;
941 /* directive */
942 char *key, *value;
943 /* strsep modifies the 'line' string: 'key \0 value' */
944 key = line;
945 value = line;
946 strsep(&value, "=");
947 strtrim(key);
948 strtrim(value);
950 if(key == NULL) {
951 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: syntax error in config file- missing key.\n"),
952 file, linenum);
953 ret = 1;
954 goto cleanup;
956 /* For each directive, compare to the camelcase string. */
957 if(section == NULL) {
958 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: All directives must belong to a section.\n"),
959 file, linenum);
960 ret = 1;
961 goto cleanup;
963 /* Include is allowed in both options and repo sections */
964 if(strcmp(key, "Include") == 0) {
965 if(value == NULL) {
966 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive %s needs a value\n"),
967 file, linenum, key);
968 ret = 1;
969 goto cleanup;
971 /* Ignore include failures... assume non-critical */
972 int globret;
973 glob_t globbuf;
974 globret = glob(value, GLOB_NOCHECK, NULL, &globbuf);
975 switch(globret) {
976 case GLOB_NOSPACE:
977 pm_printf(PM_LOG_DEBUG,
978 "config file %s, line %d: include globing out of space\n",
979 file, linenum);
980 break;
981 case GLOB_ABORTED:
982 pm_printf(PM_LOG_DEBUG,
983 "config file %s, line %d: include globing read error for %s\n",
984 file, linenum, value);
985 break;
986 case GLOB_NOMATCH:
987 pm_printf(PM_LOG_DEBUG,
988 "config file %s, line %d: no include found for %s\n",
989 file, linenum, value);
990 break;
991 default:
992 for(int gindex = 0; gindex < globbuf.gl_pathc; gindex++) {
993 pm_printf(PM_LOG_DEBUG, "config file %s, line %d: including %s\n",
994 file, linenum, globbuf.gl_pathv[gindex]);
995 _parseconfig(globbuf.gl_pathv[gindex], section, db);
997 break;
999 globfree(&globbuf);
1000 continue;
1002 if(strcmp(section, "options") == 0) {
1003 /* we are either in options ... */
1004 if((ret = _parse_options(key, value)) != 0) {
1005 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: problem in options section\n"),
1006 file, linenum);
1007 ret = 1;
1008 goto cleanup;
1010 continue;
1011 } else {
1012 /* ... or in a repo section */
1013 if(strcmp(key, "Server") == 0) {
1014 if(value == NULL) {
1015 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive %s needs a value\n"),
1016 file, linenum, key);
1017 ret = 1;
1018 goto cleanup;
1020 if(_add_mirror(db, value) != 0) {
1021 ret = 1;
1022 goto cleanup;
1024 } else {
1025 pm_printf(PM_LOG_ERROR, _("config file %s, line %d: directive '%s' in repository section '%s' not recognized.\n"),
1026 file, linenum, key, section);
1027 ret = 1;
1028 goto cleanup;
1034 cleanup:
1035 if(fp) {
1036 fclose(fp);
1038 if(section){
1039 free(section);
1041 /* call setlibpaths here to ensure we have called it at least once */
1042 setlibpaths();
1043 pm_printf(PM_LOG_DEBUG, "config: finished parsing %s\n", file);
1044 return(ret);
1047 /** Parse a configuration file.
1048 * @param file path to the config file.
1049 * @return 0 on success, non-zero on error
1051 static int parseconfig(const char *file)
1053 /* call the real parseconfig function with a null section & db argument */
1054 return(_parseconfig(file, NULL, NULL));
1057 /** print commandline to logfile
1059 static void cl_to_log(int argc, char* argv[])
1061 size_t size = 0;
1062 int i;
1063 for(i = 0; i<argc; i++) {
1064 size += strlen(argv[i]) + 1;
1066 char *cl_text = malloc(size);
1067 if(!cl_text)
1068 return;
1069 char *p = cl_text;
1070 for(i = 0; i<argc-1; i++) {
1071 strcpy(p, argv[i]);
1072 p += strlen(argv[i]);
1073 *p++ = ' ';
1075 strcpy(p, argv[i]);
1076 alpm_logaction("Running '%s'\n", cl_text);
1077 free(cl_text);
1080 /** Main function.
1081 * @param argc argc
1082 * @param argv argv
1083 * @return A return code indicating success, failure, etc.
1085 int main(int argc, char *argv[])
1087 int ret = 0;
1088 struct sigaction new_action, old_action;
1089 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
1090 /* geteuid undefined in CYGWIN */
1091 uid_t myuid = geteuid();
1092 #endif
1094 #if defined(PACMAN_DEBUG) && defined(HAVE_MCHECK_H)
1095 /*setenv("MALLOC_TRACE","pacman.mtrace", 0);*/
1096 mtrace();
1097 #endif
1099 /* Set signal handlers */
1100 /* Set up the structure to specify the new action. */
1101 new_action.sa_handler = handler;
1102 sigemptyset(&new_action.sa_mask);
1103 new_action.sa_flags = 0;
1105 sigaction(SIGINT, NULL, &old_action);
1106 if(old_action.sa_handler != SIG_IGN) {
1107 sigaction(SIGINT, &new_action, NULL);
1109 sigaction(SIGTERM, NULL, &old_action);
1110 if(old_action.sa_handler != SIG_IGN) {
1111 sigaction(SIGTERM, &new_action, NULL);
1113 sigaction(SIGSEGV, NULL, &old_action);
1114 if(old_action.sa_handler != SIG_IGN) {
1115 sigaction(SIGSEGV, &new_action, NULL);
1118 /* i18n init */
1119 #if defined(ENABLE_NLS)
1120 localize();
1121 #endif
1123 /* set user agent for downloading */
1124 setuseragent();
1126 /* init config data */
1127 config = config_new();
1129 /* disable progressbar if the output is redirected */
1130 if(!isatty(1)) {
1131 config->noprogressbar = 1;
1134 /* initialize library */
1135 if(alpm_initialize() == -1) {
1136 pm_printf(PM_LOG_ERROR, _("failed to initialize alpm library (%s)\n"),
1137 alpm_strerrorlast());
1138 cleanup(EXIT_FAILURE);
1141 /* Setup logging as soon as possible, to print out maximum debugging info */
1142 alpm_option_set_logcb(cb_log);
1143 alpm_option_set_dlcb(cb_dl_progress);
1144 /* define paths to reasonable defaults */
1145 alpm_option_set_root(ROOTDIR);
1146 alpm_option_set_dbpath(DBPATH);
1147 alpm_option_set_logfile(LOGFILE);
1149 /* Priority of options:
1150 * 1. command line
1151 * 2. config file
1152 * 3. compiled-in defaults
1153 * However, we have to parse the command line first because a config file
1154 * location can be specified here, so we need to make sure we prefer these
1155 * options over the config file coming second.
1158 /* parse the command line */
1159 ret = parseargs(argc, argv);
1160 if(ret != 0) {
1161 cleanup(ret);
1164 /* parse the config file */
1165 ret = parseconfig(config->configfile);
1166 if(ret != 0) {
1167 cleanup(ret);
1170 /* set TotalDownload callback if option enabled */
1171 if(config->totaldownload) {
1172 alpm_option_set_totaldlcb(cb_dl_total);
1175 /* noask is meant to be non-interactive */
1176 if(config->noask) {
1177 config->noconfirm = 1;
1180 /* set up the print operations */
1181 if(config->print) {
1182 config->noconfirm = 1;
1183 config->flags |= PM_TRANS_FLAG_NOCONFLICTS;
1184 config->flags |= PM_TRANS_FLAG_NOLOCK;
1185 /* Display only errors */
1186 config->logmask &= ~PM_LOG_WARNING;
1189 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
1190 /* check if we have sufficient permission for the requested operation */
1191 if(myuid > 0 && needs_root()) {
1192 pm_printf(PM_LOG_ERROR, _("you cannot perform this operation unless you are root.\n"));
1193 cleanup(EXIT_FAILURE);
1195 #endif
1197 if(config->verbose > 0) {
1198 alpm_list_t *i;
1199 printf("Root : %s\n", alpm_option_get_root());
1200 printf("Conf File : %s\n", config->configfile);
1201 printf("DB Path : %s\n", alpm_option_get_dbpath());
1202 printf("Cache Dirs: ");
1203 for(i = alpm_option_get_cachedirs(); i; i = alpm_list_next(i)) {
1204 printf("%s ", (char*)alpm_list_getdata(i));
1206 printf("\n");
1207 printf("Lock File : %s\n", alpm_option_get_lockfile());
1208 printf("Log File : %s\n", alpm_option_get_logfile());
1209 list_display("Targets :", pm_targets);
1212 /* Opening local database */
1213 db_local = alpm_db_register_local();
1214 if(db_local == NULL) {
1215 pm_printf(PM_LOG_ERROR, _("could not register 'local' database (%s)\n"),
1216 alpm_strerrorlast());
1217 cleanup(EXIT_FAILURE);
1220 /* Log commandline */
1221 if(needs_root()) {
1222 cl_to_log(argc, argv);
1225 /* start the requested operation */
1226 switch(config->op) {
1227 case PM_OP_DATABASE:
1228 ret = pacman_database(pm_targets);
1229 break;
1230 case PM_OP_REMOVE:
1231 ret = pacman_remove(pm_targets);
1232 break;
1233 case PM_OP_UPGRADE:
1234 ret = pacman_upgrade(pm_targets);
1235 break;
1236 case PM_OP_QUERY:
1237 ret = pacman_query(pm_targets);
1238 break;
1239 case PM_OP_SYNC:
1240 ret = pacman_sync(pm_targets);
1241 break;
1242 case PM_OP_DEPTEST:
1243 ret = pacman_deptest(pm_targets);
1244 break;
1245 default:
1246 pm_printf(PM_LOG_ERROR, _("no operation specified (use -h for help)\n"));
1247 ret = EXIT_FAILURE;
1250 cleanup(ret);
1251 /* not reached */
1252 return(EXIT_SUCCESS);
1255 /* vim: set ts=2 sw=2 noet: */