getopt.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * getopt.c - Enhanced implementation of BSD getopt(1)
  4. * Copyright (c) 1997, 1998, 1999, 2000 Frodo Looijaard <frodol@dds.nl>
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. /*
  9. * Version 1.0-b4: Tue Sep 23 1997. First public release.
  10. * Version 1.0: Wed Nov 19 1997.
  11. * Bumped up the version number to 1.0
  12. * Fixed minor typo (CSH instead of TCSH)
  13. * Version 1.0.1: Tue Jun 3 1998
  14. * Fixed sizeof instead of strlen bug
  15. * Bumped up the version number to 1.0.1
  16. * Version 1.0.2: Thu Jun 11 1998 (not present)
  17. * Fixed gcc-2.8.1 warnings
  18. * Fixed --version/-V option (not present)
  19. * Version 1.0.5: Tue Jun 22 1999
  20. * Make -u option work (not present)
  21. * Version 1.0.6: Tue Jun 27 2000
  22. * No important changes
  23. * Version 1.1.0: Tue Jun 30 2000
  24. * Added NLS support (partly written by Arkadiusz Mickiewicz
  25. * <misiek@misiek.eu.org>)
  26. * Ported to Busybox - Alfred M. Szmidt <ams@trillian.itslinux.org>
  27. * Removed --version/-V and --help/-h
  28. * Removed parse_error(), using bb_error_msg() from Busybox instead
  29. * Replaced our_malloc with xmalloc and our_realloc with xrealloc
  30. */
  31. //config:config GETOPT
  32. //config: bool "getopt"
  33. //config: default y
  34. //config: help
  35. //config: The getopt utility is used to break up (parse) options in command
  36. //config: lines to make it easy to write complex shell scripts that also check
  37. //config: for legal (and illegal) options. If you want to write horribly
  38. //config: complex shell scripts, or use some horribly complex shell script
  39. //config: written by others, this utility may be for you. Most people will
  40. //config: wisely leave this disabled.
  41. //config:
  42. //config:config FEATURE_GETOPT_LONG
  43. //config: bool "Support option -l"
  44. //config: default y if LONG_OPTS
  45. //config: depends on GETOPT
  46. //config: help
  47. //config: Enable support for long options (option -l).
  48. //applet:IF_GETOPT(APPLET(getopt, BB_DIR_BIN, BB_SUID_DROP))
  49. //kbuild:lib-$(CONFIG_GETOPT) += getopt.o
  50. //usage:#define getopt_trivial_usage
  51. //usage: "[OPTIONS] [--] OPTSTRING PARAMS"
  52. //usage:#define getopt_full_usage "\n\n"
  53. //usage: IF_LONG_OPTS(
  54. //usage: IF_FEATURE_GETOPT_LONG(
  55. //usage: " -a,--alternative Allow long options starting with single -\n"
  56. //usage: " -l,--longoptions=LOPT[,...] Long options to recognize\n"
  57. //usage: )
  58. //usage: " -n,--name=PROGNAME The name under which errors are reported"
  59. //usage: "\n -o,--options=OPTSTRING Short options to recognize"
  60. //usage: "\n -q,--quiet No error messages on unrecognized options"
  61. //usage: "\n -Q,--quiet-output No normal output"
  62. //usage: "\n -s,--shell=SHELL Set shell quoting conventions"
  63. //usage: "\n -T,--test Version test (exits with 4)"
  64. //usage: "\n -u,--unquoted Don't quote output"
  65. //usage: )
  66. //usage: IF_NOT_LONG_OPTS(
  67. //usage: IF_FEATURE_GETOPT_LONG(
  68. //usage: " -a Allow long options starting with single -\n"
  69. //usage: " -l LOPT[,...] Long options to recognize\n"
  70. //usage: )
  71. //usage: " -n PROGNAME The name under which errors are reported"
  72. //usage: "\n -o OPTSTRING Short options to recognize"
  73. //usage: "\n -q No error messages on unrecognized options"
  74. //usage: "\n -Q No normal output"
  75. //usage: "\n -s SHELL Set shell quoting conventions"
  76. //usage: "\n -T Version test (exits with 4)"
  77. //usage: "\n -u Don't quote output"
  78. //usage: )
  79. //usage: IF_FEATURE_GETOPT_LONG( /* example uses -l, needs FEATURE_GETOPT_LONG */
  80. //usage: "\n"
  81. //usage: "\nExample:"
  82. //usage: "\n"
  83. //usage: "\nO=`getopt -l bb: -- ab:c:: \"$@\"` || exit 1"
  84. //usage: "\neval set -- \"$O\""
  85. //usage: "\nwhile true; do"
  86. //usage: "\n case \"$1\" in"
  87. //usage: "\n -a) echo A; shift;;"
  88. //usage: "\n -b|--bb) echo \"B:'$2'\"; shift 2;;"
  89. //usage: "\n -c) case \"$2\" in"
  90. //usage: "\n \"\") echo C; shift 2;;"
  91. //usage: "\n *) echo \"C:'$2'\"; shift 2;;"
  92. //usage: "\n esac;;"
  93. //usage: "\n --) shift; break;;"
  94. //usage: "\n *) echo Error; exit 1;;"
  95. //usage: "\n esac"
  96. //usage: "\ndone"
  97. //usage: )
  98. //usage:
  99. //usage:#define getopt_example_usage
  100. //usage: "$ cat getopt.test\n"
  101. //usage: "#!/bin/sh\n"
  102. //usage: "GETOPT=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \\\n"
  103. //usage: " -n 'example.busybox' -- \"$@\"`\n"
  104. //usage: "if [ $? != 0 ]; then exit 1; fi\n"
  105. //usage: "eval set -- \"$GETOPT\"\n"
  106. //usage: "while true; do\n"
  107. //usage: " case $1 in\n"
  108. //usage: " -a|--a-long) echo \"Option a\"; shift;;\n"
  109. //usage: " -b|--b-long) echo \"Option b, argument '$2'\"; shift 2;;\n"
  110. //usage: " -c|--c-long)\n"
  111. //usage: " case \"$2\" in\n"
  112. //usage: " \"\") echo \"Option c, no argument\"; shift 2;;\n"
  113. //usage: " *) echo \"Option c, argument '$2'\"; shift 2;;\n"
  114. //usage: " esac;;\n"
  115. //usage: " --) shift; break;;\n"
  116. //usage: " *) echo \"Internal error!\"; exit 1;;\n"
  117. //usage: " esac\n"
  118. //usage: "done\n"
  119. #if ENABLE_FEATURE_GETOPT_LONG
  120. # include <getopt.h>
  121. #endif
  122. #include "libbb.h"
  123. /* NON_OPT is the code that is returned when a non-option is found in '+'
  124. mode */
  125. enum {
  126. NON_OPT = 1,
  127. #if ENABLE_FEATURE_GETOPT_LONG
  128. /* LONG_OPT is the code that is returned when a long option is found. */
  129. LONG_OPT = 2
  130. #endif
  131. };
  132. /* For finding activated option flags. Must match getopt32 call! */
  133. enum {
  134. OPT_o = 0x1, // -o
  135. OPT_n = 0x2, // -n
  136. OPT_q = 0x4, // -q
  137. OPT_Q = 0x8, // -Q
  138. OPT_s = 0x10, // -s
  139. OPT_T = 0x20, // -T
  140. OPT_u = 0x40, // -u
  141. #if ENABLE_FEATURE_GETOPT_LONG
  142. OPT_a = 0x80, // -a
  143. OPT_l = 0x100, // -l
  144. #endif
  145. SHELL_IS_TCSH = 0x8000, /* hijack this bit for other purposes */
  146. };
  147. /* 0 is getopt_long, 1 is getopt_long_only */
  148. #define alternative (option_mask32 & OPT_a)
  149. #define quiet_errors (option_mask32 & OPT_q)
  150. #define quiet_output (option_mask32 & OPT_Q)
  151. #define quote (!(option_mask32 & OPT_u))
  152. #define shell_TCSH (option_mask32 & SHELL_IS_TCSH)
  153. /*
  154. * This function 'normalizes' a single argument: it puts single quotes around
  155. * it and escapes other special characters. If quote is false, it just
  156. * returns its argument.
  157. * Bash only needs special treatment for single quotes; tcsh also recognizes
  158. * exclamation marks within single quotes, and nukes whitespace.
  159. * This function returns a pointer to a buffer that is overwritten by
  160. * each call.
  161. */
  162. static const char *normalize(const char *arg)
  163. {
  164. char *bufptr;
  165. #if ENABLE_FEATURE_CLEAN_UP
  166. static char *BUFFER = NULL;
  167. free(BUFFER);
  168. #else
  169. char *BUFFER;
  170. #endif
  171. if (!quote) { /* Just copy arg */
  172. BUFFER = xstrdup(arg);
  173. return BUFFER;
  174. }
  175. /* Each character in arg may take up to four characters in the result:
  176. For a quote we need a closing quote, a backslash, a quote and an
  177. opening quote! We need also the global opening and closing quote,
  178. and one extra character for '\0'. */
  179. BUFFER = xmalloc(strlen(arg)*4 + 3);
  180. bufptr = BUFFER;
  181. *bufptr ++= '\'';
  182. while (*arg) {
  183. if (*arg == '\'') {
  184. /* Quote: replace it with: '\'' */
  185. *bufptr ++= '\'';
  186. *bufptr ++= '\\';
  187. *bufptr ++= '\'';
  188. *bufptr ++= '\'';
  189. } else if (shell_TCSH && *arg == '!') {
  190. /* Exclamation mark: replace it with: \! */
  191. *bufptr ++= '\'';
  192. *bufptr ++= '\\';
  193. *bufptr ++= '!';
  194. *bufptr ++= '\'';
  195. } else if (shell_TCSH && *arg == '\n') {
  196. /* Newline: replace it with: \n */
  197. *bufptr ++= '\\';
  198. *bufptr ++= 'n';
  199. } else if (shell_TCSH && isspace(*arg)) {
  200. /* Non-newline whitespace: replace it with \<ws> */
  201. *bufptr ++= '\'';
  202. *bufptr ++= '\\';
  203. *bufptr ++= *arg;
  204. *bufptr ++= '\'';
  205. } else
  206. /* Just copy */
  207. *bufptr ++= *arg;
  208. arg++;
  209. }
  210. *bufptr ++= '\'';
  211. *bufptr ++= '\0';
  212. return BUFFER;
  213. }
  214. /*
  215. * Generate the output. argv[0] is the program name (used for reporting errors).
  216. * argv[1..] contains the options to be parsed. argc must be the number of
  217. * elements in argv (ie. 1 if there are no options, only the program name),
  218. * optstr must contain the short options, and longopts the long options.
  219. * Other settings are found in global variables.
  220. */
  221. #if !ENABLE_FEATURE_GETOPT_LONG
  222. #define generate_output(argv,argc,optstr,longopts) \
  223. generate_output(argv,argc,optstr)
  224. #endif
  225. static int generate_output(char **argv, int argc, const char *optstr, const struct option *longopts)
  226. {
  227. int exit_code = 0; /* We assume everything will be OK */
  228. if (quiet_errors) /* No error reporting from getopt(3) */
  229. opterr = 0;
  230. /* We used it already in main() in getopt32(),
  231. * we *must* reset getopt(3): */
  232. #ifdef __GLIBC__
  233. optind = 0;
  234. #else /* BSD style */
  235. optind = 1;
  236. /* optreset = 1; */
  237. #endif
  238. while (1) {
  239. #if ENABLE_FEATURE_GETOPT_LONG
  240. int longindex;
  241. int opt = alternative
  242. ? getopt_long_only(argc, argv, optstr, longopts, &longindex)
  243. : getopt_long(argc, argv, optstr, longopts, &longindex)
  244. ;
  245. #else
  246. int opt = getopt(argc, argv, optstr);
  247. #endif
  248. if (opt == -1)
  249. break;
  250. if (opt == '?' || opt == ':' )
  251. exit_code = 1;
  252. else if (!quiet_output) {
  253. #if ENABLE_FEATURE_GETOPT_LONG
  254. if (opt == LONG_OPT) {
  255. printf(" --%s", longopts[longindex].name);
  256. if (longopts[longindex].has_arg)
  257. printf(" %s",
  258. normalize(optarg ? optarg : ""));
  259. } else
  260. #endif
  261. if (opt == NON_OPT)
  262. printf(" %s", normalize(optarg));
  263. else {
  264. const char *charptr;
  265. printf(" -%c", opt);
  266. charptr = strchr(optstr, opt);
  267. if (charptr && *++charptr == ':')
  268. printf(" %s",
  269. normalize(optarg ? optarg : ""));
  270. }
  271. }
  272. }
  273. if (!quiet_output) {
  274. unsigned idx;
  275. printf(" --");
  276. idx = optind;
  277. while (argv[idx])
  278. printf(" %s", normalize(argv[idx++]));
  279. bb_putchar('\n');
  280. }
  281. return exit_code;
  282. }
  283. #if ENABLE_FEATURE_GETOPT_LONG
  284. /*
  285. * Register several long options. options is a string of long options,
  286. * separated by commas or whitespace.
  287. * This nukes options!
  288. */
  289. static struct option *add_long_options(struct option *long_options, char *options)
  290. {
  291. int long_nr = 0;
  292. int arg_opt, tlen;
  293. char *tokptr = strtok(options, ", \t\n");
  294. if (long_options)
  295. while (long_options[long_nr].name)
  296. long_nr++;
  297. while (tokptr) {
  298. arg_opt = no_argument;
  299. tlen = strlen(tokptr);
  300. if (tlen) {
  301. tlen--;
  302. if (tokptr[tlen] == ':') {
  303. arg_opt = required_argument;
  304. if (tlen && tokptr[tlen-1] == ':') {
  305. tlen--;
  306. arg_opt = optional_argument;
  307. }
  308. tokptr[tlen] = '\0';
  309. if (tlen == 0)
  310. bb_error_msg_and_die("empty long option specified");
  311. }
  312. long_options = xrealloc_vector(long_options, 4, long_nr);
  313. long_options[long_nr].has_arg = arg_opt;
  314. /*long_options[long_nr].flag = NULL; - xrealloc_vector did it */
  315. long_options[long_nr].val = LONG_OPT;
  316. long_options[long_nr].name = xstrdup(tokptr);
  317. long_nr++;
  318. /*memset(&long_options[long_nr], 0, sizeof(long_options[0])); - xrealloc_vector did it */
  319. }
  320. tokptr = strtok(NULL, ", \t\n");
  321. }
  322. return long_options;
  323. }
  324. #endif
  325. static void set_shell(const char *new_shell)
  326. {
  327. if (strcmp(new_shell, "bash") == 0 || strcmp(new_shell, "sh") == 0)
  328. return;
  329. if (strcmp(new_shell, "tcsh") == 0 || strcmp(new_shell, "csh") == 0)
  330. option_mask32 |= SHELL_IS_TCSH;
  331. else
  332. bb_error_msg("unknown shell '%s', assuming bash", new_shell);
  333. }
  334. /* Exit codes:
  335. * 0) No errors, successful operation.
  336. * 1) getopt(3) returned an error.
  337. * 2) A problem with parameter parsing for getopt(1).
  338. * 3) Internal error, out of memory
  339. * 4) Returned for -T
  340. */
  341. #if ENABLE_FEATURE_GETOPT_LONG
  342. static const char getopt_longopts[] ALIGN1 =
  343. "options\0" Required_argument "o"
  344. "longoptions\0" Required_argument "l"
  345. "quiet\0" No_argument "q"
  346. "quiet-output\0" No_argument "Q"
  347. "shell\0" Required_argument "s"
  348. "test\0" No_argument "T"
  349. "unquoted\0" No_argument "u"
  350. "alternative\0" No_argument "a"
  351. "name\0" Required_argument "n"
  352. ;
  353. #endif
  354. int getopt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  355. int getopt_main(int argc, char **argv)
  356. {
  357. int n;
  358. char *optstr = NULL;
  359. char *name = NULL;
  360. unsigned opt;
  361. const char *compatible;
  362. char *s_arg;
  363. #if ENABLE_FEATURE_GETOPT_LONG
  364. struct option *long_options = NULL;
  365. llist_t *l_arg = NULL;
  366. #endif
  367. compatible = getenv("GETOPT_COMPATIBLE"); /* used as yes/no flag */
  368. if (!argv[1]) {
  369. if (compatible) {
  370. /* For some reason, the original getopt gave no error
  371. * when there were no arguments. */
  372. puts(" --");
  373. return 0;
  374. }
  375. bb_error_msg_and_die("missing optstring argument");
  376. }
  377. if (argv[1][0] != '-' || compatible) {
  378. char *s = argv[1];
  379. option_mask32 |= OPT_u; /* quoting off */
  380. s = xstrdup(s + strspn(s, "-+"));
  381. argv[1] = argv[0];
  382. return generate_output(argv+1, argc-1, s, long_options);
  383. }
  384. #if !ENABLE_FEATURE_GETOPT_LONG
  385. opt = getopt32(argv, "+o:n:qQs:Tu", &optstr, &name, &s_arg);
  386. #else
  387. applet_long_options = getopt_longopts;
  388. opt = getopt32(argv, "+o:n:qQs:Tual:*",
  389. &optstr, &name, &s_arg, &l_arg);
  390. /* Effectuate the read options for the applet itself */
  391. while (l_arg) {
  392. long_options = add_long_options(long_options, llist_pop(&l_arg));
  393. }
  394. #endif
  395. if (opt & OPT_s) {
  396. set_shell(s_arg);
  397. }
  398. if (opt & OPT_T) {
  399. return 4;
  400. }
  401. /* All options controlling the applet have now been parsed */
  402. n = optind - 1;
  403. if (!optstr) {
  404. optstr = argv[++n];
  405. if (!optstr)
  406. bb_error_msg_and_die("missing optstring argument");
  407. }
  408. argv[n] = name ? name : argv[0];
  409. return generate_output(argv + n, argc - n, optstr, long_options);
  410. }