3
0

getopt.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. GETOPT_RESET();
  233. while (1) {
  234. #if ENABLE_FEATURE_GETOPT_LONG
  235. int longindex;
  236. int opt = alternative
  237. ? getopt_long_only(argc, argv, optstr, longopts, &longindex)
  238. : getopt_long(argc, argv, optstr, longopts, &longindex)
  239. ;
  240. #else
  241. int opt = getopt(argc, argv, optstr);
  242. #endif
  243. if (opt == -1)
  244. break;
  245. if (opt == '?' || opt == ':' )
  246. exit_code = 1;
  247. else if (!quiet_output) {
  248. #if ENABLE_FEATURE_GETOPT_LONG
  249. if (opt == LONG_OPT) {
  250. printf(" --%s", longopts[longindex].name);
  251. if (longopts[longindex].has_arg)
  252. printf(" %s",
  253. normalize(optarg ? optarg : ""));
  254. } else
  255. #endif
  256. if (opt == NON_OPT)
  257. printf(" %s", normalize(optarg));
  258. else {
  259. const char *charptr;
  260. printf(" -%c", opt);
  261. charptr = strchr(optstr, opt);
  262. if (charptr && *++charptr == ':')
  263. printf(" %s",
  264. normalize(optarg ? optarg : ""));
  265. }
  266. }
  267. }
  268. if (!quiet_output) {
  269. unsigned idx;
  270. printf(" --");
  271. idx = optind;
  272. while (argv[idx])
  273. printf(" %s", normalize(argv[idx++]));
  274. bb_putchar('\n');
  275. }
  276. return exit_code;
  277. }
  278. #if ENABLE_FEATURE_GETOPT_LONG
  279. /*
  280. * Register several long options. options is a string of long options,
  281. * separated by commas or whitespace.
  282. * This nukes options!
  283. */
  284. static struct option *add_long_options(struct option *long_options, char *options)
  285. {
  286. int long_nr = 0;
  287. int arg_opt, tlen;
  288. char *tokptr = strtok(options, ", \t\n");
  289. if (long_options)
  290. while (long_options[long_nr].name)
  291. long_nr++;
  292. while (tokptr) {
  293. arg_opt = no_argument;
  294. tlen = strlen(tokptr);
  295. if (tlen) {
  296. tlen--;
  297. if (tokptr[tlen] == ':') {
  298. arg_opt = required_argument;
  299. if (tlen && tokptr[tlen-1] == ':') {
  300. tlen--;
  301. arg_opt = optional_argument;
  302. }
  303. tokptr[tlen] = '\0';
  304. if (tlen == 0)
  305. bb_error_msg_and_die("empty long option specified");
  306. }
  307. long_options = xrealloc_vector(long_options, 4, long_nr);
  308. long_options[long_nr].has_arg = arg_opt;
  309. /*long_options[long_nr].flag = NULL; - xrealloc_vector did it */
  310. long_options[long_nr].val = LONG_OPT;
  311. long_options[long_nr].name = xstrdup(tokptr);
  312. long_nr++;
  313. /*memset(&long_options[long_nr], 0, sizeof(long_options[0])); - xrealloc_vector did it */
  314. }
  315. tokptr = strtok(NULL, ", \t\n");
  316. }
  317. return long_options;
  318. }
  319. #endif
  320. static void set_shell(const char *new_shell)
  321. {
  322. if (strcmp(new_shell, "bash") == 0 || strcmp(new_shell, "sh") == 0)
  323. return;
  324. if (strcmp(new_shell, "tcsh") == 0 || strcmp(new_shell, "csh") == 0)
  325. option_mask32 |= SHELL_IS_TCSH;
  326. else
  327. bb_error_msg("unknown shell '%s', assuming bash", new_shell);
  328. }
  329. /* Exit codes:
  330. * 0) No errors, successful operation.
  331. * 1) getopt(3) returned an error.
  332. * 2) A problem with parameter parsing for getopt(1).
  333. * 3) Internal error, out of memory
  334. * 4) Returned for -T
  335. */
  336. #if ENABLE_FEATURE_GETOPT_LONG
  337. static const char getopt_longopts[] ALIGN1 =
  338. "options\0" Required_argument "o"
  339. "longoptions\0" Required_argument "l"
  340. "quiet\0" No_argument "q"
  341. "quiet-output\0" No_argument "Q"
  342. "shell\0" Required_argument "s"
  343. "test\0" No_argument "T"
  344. "unquoted\0" No_argument "u"
  345. "alternative\0" No_argument "a"
  346. "name\0" Required_argument "n"
  347. ;
  348. #endif
  349. int getopt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  350. int getopt_main(int argc, char **argv)
  351. {
  352. int n;
  353. char *optstr = NULL;
  354. char *name = NULL;
  355. unsigned opt;
  356. const char *compatible;
  357. char *s_arg;
  358. #if ENABLE_FEATURE_GETOPT_LONG
  359. struct option *long_options = NULL;
  360. llist_t *l_arg = NULL;
  361. #endif
  362. compatible = getenv("GETOPT_COMPATIBLE"); /* used as yes/no flag */
  363. if (!argv[1]) {
  364. if (compatible) {
  365. /* For some reason, the original getopt gave no error
  366. * when there were no arguments. */
  367. puts(" --");
  368. return 0;
  369. }
  370. bb_error_msg_and_die("missing optstring argument");
  371. }
  372. if (argv[1][0] != '-' || compatible) {
  373. char *s = argv[1];
  374. option_mask32 |= OPT_u; /* quoting off */
  375. s = xstrdup(s + strspn(s, "-+"));
  376. argv[1] = argv[0];
  377. return generate_output(argv+1, argc-1, s, long_options);
  378. }
  379. #if !ENABLE_FEATURE_GETOPT_LONG
  380. opt = getopt32(argv, "+o:n:qQs:Tu", &optstr, &name, &s_arg);
  381. #else
  382. applet_long_options = getopt_longopts;
  383. opt = getopt32(argv, "+o:n:qQs:Tual:*",
  384. &optstr, &name, &s_arg, &l_arg);
  385. /* Effectuate the read options for the applet itself */
  386. while (l_arg) {
  387. long_options = add_long_options(long_options, llist_pop(&l_arg));
  388. }
  389. #endif
  390. if (opt & OPT_s) {
  391. set_shell(s_arg);
  392. }
  393. if (opt & OPT_T) {
  394. return 4;
  395. }
  396. /* All options controlling the applet have now been parsed */
  397. n = optind - 1;
  398. if (!optstr) {
  399. optstr = argv[++n];
  400. if (!optstr)
  401. bb_error_msg_and_die("missing optstring argument");
  402. }
  403. argv[n] = name ? name : argv[0];
  404. return generate_output(argv + n, argc - n, optstr, long_options);
  405. }