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/>.
23 /* special handling of package version for GIT */
24 #if defined(GIT_VERSION)
25 #undef PACKAGE_VERSION
26 #define PACKAGE_VERSION GIT_VERSION
29 #include <ctype.h> /* isspace */
30 #include <stdlib.h> /* atoi */
32 #include <ctype.h> /* isspace */
38 #include <sys/types.h>
40 #include <sys/utsname.h> /* uname */
41 #include <locale.h> /* setlocale */
42 #include <time.h> /* time_t */
45 #if defined(PACMAN_DEBUG) && defined(HAVE_MCHECK_H)
46 #include <mcheck.h> /* debug tracing (mtrace) */
51 #include <alpm_list.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
)
69 if(s1
== s2
) return(0);
72 /* First skip all spaces in both strings */
73 while(isspace((unsigned char)*s1
)) {
76 while(isspace((unsigned char)*s2
)) {
79 /* If we compare a long option (--abcd) and a short one (-a),
80 * the short one always wins */
81 if(*s1
== '-' && *s2
== '-') {
84 if(*s1
== '-' && *s2
== '-') {
85 /* two long -> strcmp */
88 } else if(*s2
== '-') {
89 /* s1 short, s2 long */
91 } else if(*s1
== '-') {
92 /* s1 long, s2 short */
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
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"),
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"));
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"));
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"));
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
);
216 /** Output pacman version and copyright.
218 static void version(void)
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");
225 printf(_(" This program may be freely redistributed under\n"
226 " the terms of the GNU General Public License.\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)
238 setlocale(LC_ALL
, "");
239 bindtextdomain(PACKAGE
, LOCALEDIR
);
246 /** Set user agent environment variable.
248 static void setuseragent(void)
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) {
264 pm_printf(PM_LOG_DEBUG
, "config: Architecture: %s\n", un
.machine
);
265 alpm_option_set_arch(un
.machine
);
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());
283 FREELIST(pm_targets
);
292 /** Write function that correctly handles EINTR.
294 static ssize_t
xwrite(int fd
, const void *buf
, size_t count
)
298 ret
= write(fd
, buf
, count
);
299 } while(ret
== -1 && errno
== EINTR
);
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
));
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. */
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);
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)
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
) {
351 ret
= alpm_option_set_root(config
->rootdir
);
353 pm_printf(PM_LOG_ERROR
, _("problem setting rootdir '%s' (%s)\n"),
354 config
->rootdir
, alpm_strerrorlast());
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. */
372 ret
= alpm_option_set_dbpath(config
->dbpath
);
374 pm_printf(PM_LOG_ERROR
, _("problem setting dbpath '%s' (%s)\n"),
375 config
->dbpath
, alpm_strerrorlast());
379 if(config
->logfile
) {
380 ret
= alpm_option_set_logfile(config
->logfile
);
382 pm_printf(PM_LOG_ERROR
, _("problem setting logfile '%s' (%s)\n"),
383 config
->logfile
, alpm_strerrorlast());
388 /* add a default cachedir if one wasn't specified */
389 if(alpm_option_get_cachedirs() == NULL
) {
390 alpm_option_add_cachedir(CACHEDIR
);
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 */
405 list
= strsplit(optarg
, ',');
406 for(item
= list
; item
; item
= alpm_list_next(item
)) {
407 fn((char *)alpm_list_getdata(item
));
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
)
424 config
->op
= (config
->op
!= PM_OP_MAIN
? 0 : PM_OP_DATABASE
); break;
427 config
->op
= (config
->op
!= PM_OP_MAIN
? 0 : PM_OP_QUERY
); break;
430 config
->op
= (config
->op
!= PM_OP_MAIN
? 0 : PM_OP_REMOVE
); break;
433 config
->op
= (config
->op
!= PM_OP_MAIN
? 0 : PM_OP_SYNC
); break;
436 config
->op
= (config
->op
!= PM_OP_MAIN
? 0 : PM_OP_DEPTEST
); break;
439 config
->op
= (config
->op
!= PM_OP_MAIN
? 0 : PM_OP_UPGRADE
); break;
442 config
->version
= 1; break;
445 config
->help
= 1; break;
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
)
459 case OP_ARCH
: check_optarg(); setarch(optarg
); break;
463 config
->ask
= (unsigned int)atoi(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());
475 if(config
->configfile
) {
476 free(config
->configfile
);
478 config
->configfile
= strndup(optarg
, PATH_MAX
);
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 */
485 unsigned short debug
= (unsigned short)atoi(optarg
);
488 config
->logmask
|= PM_LOG_FUNCTION
; /* fall through */
490 config
->logmask
|= PM_LOG_DEBUG
;
493 pm_printf(PM_LOG_ERROR
, _("'%s' is not a valid debug level\n"),
498 config
->logmask
|= PM_LOG_DEBUG
;
500 /* progress bars get wonky with debug on, shut them off */
501 config
->noprogressbar
= 1;
505 config
->logfile
= strndup(optarg
, PATH_MAX
);
507 case OP_NOCONFIRM
: config
->noconfirm
= 1; break;
510 config
->dbpath
= strdup(optarg
);
512 case 'r': check_optarg(); config
->rootdir
= strdup(optarg
); break;
513 case 'v': (config
->verbose
)++; break;
519 static int parsearg_database(int opt
)
522 case OP_ASDEPS
: config
->flags
|= PM_TRANS_FLAG_ALLDEPS
; break;
523 case OP_ASEXPLICIT
: config
->flags
|= PM_TRANS_FLAG_ALLEXPLICIT
; break;
529 static int parsearg_query(int 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;
551 /* options common to -S -R -U */
552 static int parsearg_trans(int opt
)
556 if(config
->flags
& PM_TRANS_FLAG_NODEPVERSION
) {
557 config
->flags
|= PM_TRANS_FLAG_NODEPS
;
559 config
->flags
|= PM_TRANS_FLAG_NODEPVERSION
;
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;
568 config
->print_format
= strdup(optarg
);
575 static int parsearg_remove(int opt
)
577 if (parsearg_trans(opt
) == 0)
580 case 'c': config
->flags
|= PM_TRANS_FLAG_CASCADE
; break;
581 case 'n': config
->flags
|= PM_TRANS_FLAG_NOSAVE
; break;
583 if(config
->flags
& PM_TRANS_FLAG_RECURSE
) {
584 config
->flags
|= PM_TRANS_FLAG_RECURSEALL
;
586 config
->flags
|= PM_TRANS_FLAG_RECURSE
;
589 case 'u': config
->flags
|= PM_TRANS_FLAG_UNNEEDED
; break;
595 /* options common to -S -U */
596 static int parsearg_upgrade(int opt
)
598 if (parsearg_trans(opt
) == 0)
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;
605 parsearg_util_addlist(alpm_option_add_ignorepkg
);
608 parsearg_util_addlist(alpm_option_add_ignoregrp
);
615 static int parsearg_sync(int opt
)
617 if (parsearg_upgrade(opt
) == 0)
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;
629 config
->op_s_downloadonly
= 1;
630 config
->flags
|= PM_TRANS_FLAG_DOWNLOADONLY
;
631 config
->flags
|= PM_TRANS_FLAG_NOCONFLICTS
;
633 case 'y': (config
->op_s_sync
)++; break;
639 /** Parse command-line arguments for each operation.
642 * @return 0 on success, 1 on error
644 static int parseargs(int argc
, char *argv
[])
647 int option_index
= 0;
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
},
707 /* parse operation */
708 while((opt
= getopt_long(argc
, argv
, optstring
, opts
, &option_index
))) {
711 } else if(opt
== 0) {
713 } else if(opt
== '?') {
714 /* unknown option, getopt printed an error */
720 if(config
->op
== 0) {
721 pm_printf(PM_LOG_ERROR
, _("only one operation may be used at a time\n"));
725 usage(config
->op
, mbasename(argv
[0]));
728 if(config
->version
) {
733 /* parse all other options */
735 while((opt
= getopt_long(argc
, argv
, optstring
, opts
, &option_index
))) {
738 } else if(opt
== 0) {
740 } else if(opt
== '?') {
741 /* this should have failed during first pass already */
743 } else if(parsearg_op(opt
, 1) == 0) { /* opt is an operation */
749 result
= parsearg_database(opt
);
752 result
= parsearg_query(opt
);
755 result
= parsearg_remove(opt
);
758 result
= parsearg_sync(opt
);
764 result
= parsearg_upgrade(opt
);
767 pm_printf(PM_LOG_ERROR
, _("no operation specified (use -h for help)\n"));
773 /* fall back to global options */
774 result
= parsearg_global(opt
);
776 /* global option parsing failed, abort */
777 pm_printf(PM_LOG_ERROR
, _("invalid option\n"));
782 while(optind
< argc
) {
783 /* add the target to our target array */
784 pm_targets
= alpm_list_add(pm_targets
, strdup(argv
[optind
]));
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
;
808 pm_printf(PM_LOG_ERROR
, _("invalid value for 'CleanMethod' : '%s'\n"),
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
;
826 while((q
= strchr(p
, ' '))) {
829 pm_printf(PM_LOG_DEBUG
, "config: %s: %s\n", option
, 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
) {
845 static char *get_destfile(const char *path
, const char *filename
) {
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
);
855 static char *get_tempfile(const char *path
, const char *filename
) {
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
);
865 /** External fetch callback */
866 static int download_with_xfercommand(const char *url
, const char *localpath
,
872 char *parsedcmd
,*tempcmd
;
875 char *destfile
, *tempfile
, *filename
;
877 if(!config
->xfercommand
) {
881 filename
= get_filename(url
);
885 destfile
= get_destfile(localpath
, filename
);
886 tempfile
= get_tempfile(localpath
, filename
);
888 if(force
&& stat(tempfile
, &st
) == 0) {
891 if(force
&& stat(destfile
, &st
) == 0) {
895 tempcmd
= strdup(config
->xfercommand
);
896 /* replace all occurrences of %o with fn.part */
897 if(strstr(tempcmd
, "%o")) {
899 parsedcmd
= strreplace(tempcmd
, "%o", tempfile
);
903 /* replace all occurrences of %u with the download URL */
904 parsedcmd
= strreplace(tempcmd
, "%u", url
);
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"));
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
);
920 /* execute the parsed command via /bin/sh -c */
921 pm_printf(PM_LOG_DEBUG
, "running command: %s\n", parsedcmd
);
922 retval
= system(parsedcmd
);
925 pm_printf(PM_LOG_WARNING
, _("running XferCommand: fork failed!\n"));
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
);
933 /* download was successful */
935 rename(tempfile
, destfile
);
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
));
947 /* hack to let an user the time to cancel a download */
957 static int _parse_options(char *key
, char *value
)
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) {
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);
979 pm_printf(PM_LOG_ERROR
, _("directive '%s' without value not recognized\n"), key
);
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()) {
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());
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
);
1031 pm_printf(PM_LOG_ERROR
, _("directive '%s' with a value not recognized\n"), key
);
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();
1048 server
= strreplace(temp
, "$arch", arch
);
1051 if(strstr(temp
, "$arch")) {
1053 pm_printf(PM_LOG_ERROR
, _("The mirror '%s' contains the $arch"
1054 " variable, but no Architecture is defined.\n"), value
);
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());
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
)
1078 char line
[PATH_MAX
+1];
1080 char *ptr
, *section
= NULL
;
1084 pm_printf(PM_LOG_DEBUG
, "config: attempting to read file %s\n", file
);
1085 fp
= fopen(file
, "r");
1087 pm_printf(PM_LOG_ERROR
, _("config file %s could not be read.\n"), file
);
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
) {
1100 while(fgets(line
, PATH_MAX
, fp
)) {
1104 /* ignore whole line and end of line comments */
1105 if(strlen(line
) == 0 || line
[0] == '#') {
1108 if((ptr
= strchr(line
, '#'))) {
1112 if(line
[0] == '[' && line
[strlen(line
)-1] == ']') {
1113 /* new config section, skip the '[' */
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"),
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
);
1132 pm_printf(PM_LOG_ERROR
, _("could not register '%s' database (%s)\n"),
1133 section
, alpm_strerrorlast());
1143 /* strsep modifies the 'line' string: 'key \0 value' */
1146 strsep(&value
, "=");
1151 pm_printf(PM_LOG_ERROR
, _("config file %s, line %d: syntax error in config file- missing key.\n"),
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"),
1163 /* Include is allowed in both options and repo sections */
1164 if(strcmp(key
, "Include") == 0) {
1166 pm_printf(PM_LOG_ERROR
, _("config file %s, line %d: directive %s needs a value\n"),
1167 file
, linenum
, key
);
1171 /* Ignore include failures... assume non-critical */
1174 globret
= glob(value
, GLOB_NOCHECK
, NULL
, &globbuf
);
1177 pm_printf(PM_LOG_DEBUG
,
1178 "config file %s, line %d: include globing out of space\n",
1182 pm_printf(PM_LOG_DEBUG
,
1183 "config file %s, line %d: include globing read error for %s\n",
1184 file
, linenum
, value
);
1187 pm_printf(PM_LOG_DEBUG
,
1188 "config file %s, line %d: no include found for %s\n",
1189 file
, linenum
, value
);
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
);
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"),
1212 /* ... or in a repo section */
1213 if(strcmp(key
, "Server") == 0) {
1215 pm_printf(PM_LOG_ERROR
, _("config file %s, line %d: directive %s needs a value\n"),
1216 file
, linenum
, key
);
1220 if(_add_mirror(db
, value
) != 0) {
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
);
1241 /* call setlibpaths here to ensure we have called it at least once */
1243 pm_printf(PM_LOG_DEBUG
, "config: finished parsing %s\n", file
);
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
[])
1263 for(i
= 0; i
<argc
; i
++) {
1264 size
+= strlen(argv
[i
]) + 1;
1266 char *cl_text
= malloc(size
);
1270 for(i
= 0; i
<argc
-1; i
++) {
1272 p
+= strlen(argv
[i
]);
1276 alpm_logaction("Running '%s'\n", cl_text
);
1283 * @return A return code indicating success, failure, etc.
1285 int main(int argc
, char *argv
[])
1288 struct sigaction new_action
, old_action
;
1289 #if defined(HAVE_GETEUID) && !defined(CYGWIN)
1290 /* geteuid undefined in CYGWIN */
1291 uid_t myuid
= geteuid();
1294 #if defined(PACMAN_DEBUG) && defined(HAVE_MCHECK_H)
1295 /*setenv("MALLOC_TRACE","pacman.mtrace", 0);*/
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
);
1319 #if defined(ENABLE_NLS)
1323 /* set user agent for downloading */
1326 /* init config data */
1327 config
= config_new();
1329 /* disable progressbar if the output is redirected */
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:
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
);
1364 /* we also support reading targets from stdin */
1365 if(!isatty(fileno(stdin
))) {
1366 char line
[PATH_MAX
];
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 */
1373 pm_targets
= alpm_list_add(pm_targets
, strdup(line
));
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 */
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"),
1397 /* parse the config file */
1398 ret
= parseconfig(config
->configfile
);
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 */
1410 config
->noconfirm
= 1;
1413 /* set up the print operations */
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
);
1430 if(config
->verbose
> 0) {
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
));
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 */
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
);
1456 ret
= pacman_remove(pm_targets
);
1459 ret
= pacman_upgrade(pm_targets
);
1462 ret
= pacman_query(pm_targets
);
1465 ret
= pacman_sync(pm_targets
);
1468 ret
= pacman_deptest(pm_targets
);
1471 pm_printf(PM_LOG_ERROR
, _("no operation specified (use -h for help)\n"));
1477 return(EXIT_SUCCESS
);
1480 /* vim: set ts=2 sw=2 noet: */