getopt.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 (5.8 kb)"
  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 -l LONGOPTs"
  44. //config: default y
  45. //config: depends on GETOPT && LONG_OPTS
  46. //config: help
  47. //config: Enable support for long options (option -l).
  48. //applet:IF_GETOPT(APPLET_NOEXEC(getopt, getopt, BB_DIR_BIN, BB_SUID_DROP, getopt))
  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_FEATURE_GETOPT_LONG(
  54. //usage: " -a Allow long options starting with single -\n"
  55. //usage: " -l LOPT[,...] Long options to recognize\n"
  56. //usage: )
  57. //usage: " -n PROGNAME The name under which errors are reported"
  58. //usage: "\n -o OPTSTRING Short options to recognize"
  59. //usage: "\n -q No error messages on unrecognized options"
  60. //usage: "\n -Q No normal output"
  61. //usage: "\n -s SHELL Set shell quoting conventions"
  62. //usage: "\n -T Version test (exits with 4)"
  63. //usage: "\n -u Don't quote output"
  64. //usage: IF_FEATURE_GETOPT_LONG( /* example uses -l, needs FEATURE_GETOPT_LONG */
  65. //usage: "\n"
  66. //usage: "\nExample:"
  67. //usage: "\n"
  68. //usage: "\nO=`getopt -l bb: -- ab:c:: \"$@\"` || exit 1"
  69. //usage: "\neval set -- \"$O\""
  70. //usage: "\nwhile true; do"
  71. //usage: "\n case \"$1\" in"
  72. //usage: "\n -a) echo A; shift;;"
  73. //usage: "\n -b|--bb) echo \"B:'$2'\"; shift 2;;"
  74. //usage: "\n -c) case \"$2\" in"
  75. //usage: "\n \"\") echo C; shift 2;;"
  76. //usage: "\n *) echo \"C:'$2'\"; shift 2;;"
  77. //usage: "\n esac;;"
  78. //usage: "\n --) shift; break;;"
  79. //usage: "\n *) echo Error; exit 1;;"
  80. //usage: "\n esac"
  81. //usage: "\ndone"
  82. //usage: )
  83. //usage:
  84. //usage:#define getopt_example_usage
  85. //usage: "$ cat getopt.test\n"
  86. //usage: "#!/bin/sh\n"
  87. //usage: "GETOPT=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \\\n"
  88. //usage: " -n 'example.busybox' -- \"$@\"`\n"
  89. //usage: "if [ $? != 0 ]; then exit 1; fi\n"
  90. //usage: "eval set -- \"$GETOPT\"\n"
  91. //usage: "while true; do\n"
  92. //usage: " case $1 in\n"
  93. //usage: " -a|--a-long) echo \"Option a\"; shift;;\n"
  94. //usage: " -b|--b-long) echo \"Option b, argument '$2'\"; shift 2;;\n"
  95. //usage: " -c|--c-long)\n"
  96. //usage: " case \"$2\" in\n"
  97. //usage: " \"\") echo \"Option c, no argument\"; shift 2;;\n"
  98. //usage: " *) echo \"Option c, argument '$2'\"; shift 2;;\n"
  99. //usage: " esac;;\n"
  100. //usage: " --) shift; break;;\n"
  101. //usage: " *) echo \"Internal error!\"; exit 1;;\n"
  102. //usage: " esac\n"
  103. //usage: "done\n"
  104. #if ENABLE_FEATURE_GETOPT_LONG
  105. # include <getopt.h>
  106. #endif
  107. #include "libbb.h"
  108. /* NON_OPT is the code that is returned when a non-option is found in '+'
  109. mode */
  110. enum {
  111. NON_OPT = 1,
  112. #if ENABLE_FEATURE_GETOPT_LONG
  113. /* LONG_OPT is the code that is returned when a long option is found. */
  114. LONG_OPT = 2
  115. #endif
  116. };
  117. /* For finding activated option flags. Must match getopt32 call! */
  118. enum {
  119. OPT_o = 0x1, // -o
  120. OPT_n = 0x2, // -n
  121. OPT_q = 0x4, // -q
  122. OPT_Q = 0x8, // -Q
  123. OPT_s = 0x10, // -s
  124. OPT_T = 0x20, // -T
  125. OPT_u = 0x40, // -u
  126. #if ENABLE_FEATURE_GETOPT_LONG
  127. OPT_a = 0x80, // -a
  128. OPT_l = 0x100, // -l
  129. #endif
  130. SHELL_IS_TCSH = 0x8000, /* hijack this bit for other purposes */
  131. };
  132. /* 0 is getopt_long, 1 is getopt_long_only */
  133. #define alternative (option_mask32 & OPT_a)
  134. #define quiet_errors (option_mask32 & OPT_q)
  135. #define quiet_output (option_mask32 & OPT_Q)
  136. #define quote (!(option_mask32 & OPT_u))
  137. #define shell_TCSH (option_mask32 & SHELL_IS_TCSH)
  138. /*
  139. * This function 'normalizes' a single argument: it puts single quotes around
  140. * it and escapes other special characters. If quote is false, it just
  141. * returns its argument.
  142. * Bash only needs special treatment for single quotes; tcsh also recognizes
  143. * exclamation marks within single quotes, and nukes whitespace.
  144. * This function returns a pointer to a buffer that is overwritten by
  145. * each call.
  146. */
  147. static const char *normalize(const char *arg)
  148. {
  149. char *bufptr;
  150. #if ENABLE_FEATURE_CLEAN_UP
  151. static char *BUFFER = NULL;
  152. free(BUFFER);
  153. #else
  154. char *BUFFER;
  155. #endif
  156. if (!quote) { /* Just copy arg */
  157. BUFFER = xstrdup(arg);
  158. return BUFFER;
  159. }
  160. /* Each character in arg may take up to four characters in the result:
  161. For a quote we need a closing quote, a backslash, a quote and an
  162. opening quote! We need also the global opening and closing quote,
  163. and one extra character for '\0'. */
  164. BUFFER = xmalloc(strlen(arg)*4 + 3);
  165. bufptr = BUFFER;
  166. *bufptr ++= '\'';
  167. while (*arg) {
  168. if (*arg == '\'') {
  169. /* Quote: replace it with: '\'' */
  170. *bufptr ++= '\'';
  171. *bufptr ++= '\\';
  172. *bufptr ++= '\'';
  173. *bufptr ++= '\'';
  174. } else if (shell_TCSH && *arg == '!') {
  175. /* Exclamation mark: replace it with: \! */
  176. *bufptr ++= '\'';
  177. *bufptr ++= '\\';
  178. *bufptr ++= '!';
  179. *bufptr ++= '\'';
  180. } else if (shell_TCSH && *arg == '\n') {
  181. /* Newline: replace it with: \n */
  182. *bufptr ++= '\\';
  183. *bufptr ++= 'n';
  184. } else if (shell_TCSH && isspace(*arg)) {
  185. /* Non-newline whitespace: replace it with \<ws> */
  186. *bufptr ++= '\'';
  187. *bufptr ++= '\\';
  188. *bufptr ++= *arg;
  189. *bufptr ++= '\'';
  190. } else
  191. /* Just copy */
  192. *bufptr ++= *arg;
  193. arg++;
  194. }
  195. *bufptr ++= '\'';
  196. *bufptr ++= '\0';
  197. return BUFFER;
  198. }
  199. /*
  200. * Generate the output. argv[0] is the program name (used for reporting errors).
  201. * argv[1..] contains the options to be parsed. argc must be the number of
  202. * elements in argv (ie. 1 if there are no options, only the program name),
  203. * optstr must contain the short options, and longopts the long options.
  204. * Other settings are found in global variables.
  205. */
  206. #if !ENABLE_FEATURE_GETOPT_LONG
  207. #define generate_output(argv,argc,optstr,longopts) \
  208. generate_output(argv,argc,optstr)
  209. #endif
  210. static int generate_output(char **argv, int argc, const char *optstr, const struct option *longopts)
  211. {
  212. int exit_code = 0; /* We assume everything will be OK */
  213. if (quiet_errors) /* No error reporting from getopt(3) */
  214. opterr = 0;
  215. /* We used it already in main() in getopt32(),
  216. * we *must* reset getopt(3): */
  217. GETOPT_RESET();
  218. while (1) {
  219. #if ENABLE_FEATURE_GETOPT_LONG
  220. int longindex;
  221. int opt = alternative
  222. ? getopt_long_only(argc, argv, optstr, longopts, &longindex)
  223. : getopt_long(argc, argv, optstr, longopts, &longindex)
  224. ;
  225. #else
  226. int opt = getopt(argc, argv, optstr);
  227. #endif
  228. if (opt == -1)
  229. break;
  230. if (opt == '?' || opt == ':' )
  231. exit_code = 1;
  232. else if (!quiet_output) {
  233. #if ENABLE_FEATURE_GETOPT_LONG
  234. if (opt == LONG_OPT) {
  235. printf(" --%s", longopts[longindex].name);
  236. if (longopts[longindex].has_arg)
  237. printf(" %s",
  238. normalize(optarg ? optarg : ""));
  239. } else
  240. #endif
  241. if (opt == NON_OPT)
  242. printf(" %s", normalize(optarg));
  243. else {
  244. const char *charptr;
  245. printf(" -%c", opt);
  246. charptr = strchr(optstr, opt);
  247. if (charptr && *++charptr == ':')
  248. printf(" %s",
  249. normalize(optarg ? optarg : ""));
  250. }
  251. }
  252. }
  253. if (!quiet_output) {
  254. unsigned idx;
  255. printf(" --");
  256. idx = optind;
  257. while (argv[idx])
  258. printf(" %s", normalize(argv[idx++]));
  259. bb_putchar('\n');
  260. }
  261. return exit_code;
  262. }
  263. #if ENABLE_FEATURE_GETOPT_LONG
  264. /*
  265. * Register several long options. options is a string of long options,
  266. * separated by commas or whitespace.
  267. * This nukes options!
  268. */
  269. static struct option *add_long_options(struct option *long_options, char *options)
  270. {
  271. int long_nr = 0;
  272. int arg_opt, tlen;
  273. char *tokptr;
  274. if (long_options)
  275. while (long_options[long_nr].name)
  276. long_nr++;
  277. tokptr = strtok_r(options, ", \t\n", &options);
  278. while (tokptr) {
  279. arg_opt = no_argument;
  280. tlen = strlen(tokptr);
  281. if (tlen) {
  282. tlen--;
  283. if (tokptr[tlen] == ':') {
  284. arg_opt = required_argument;
  285. if (tlen && tokptr[tlen-1] == ':') {
  286. tlen--;
  287. arg_opt = optional_argument;
  288. }
  289. tokptr[tlen] = '\0';
  290. if (tlen == 0)
  291. bb_simple_error_msg_and_die("empty long option specified");
  292. }
  293. long_options = xrealloc_vector(long_options, 4, long_nr);
  294. long_options[long_nr].has_arg = arg_opt;
  295. /*long_options[long_nr].flag = NULL; - xrealloc_vector did it */
  296. long_options[long_nr].val = LONG_OPT;
  297. long_options[long_nr].name = xstrdup(tokptr);
  298. long_nr++;
  299. /*memset(&long_options[long_nr], 0, sizeof(long_options[0])); - xrealloc_vector did it */
  300. }
  301. tokptr = strtok_r(NULL, ", \t\n", &options);
  302. }
  303. return long_options;
  304. }
  305. #endif
  306. static void set_shell(const char *new_shell)
  307. {
  308. if (strcmp(new_shell, "bash") == 0 || strcmp(new_shell, "sh") == 0)
  309. return;
  310. if (strcmp(new_shell, "tcsh") == 0 || strcmp(new_shell, "csh") == 0)
  311. option_mask32 |= SHELL_IS_TCSH;
  312. else
  313. bb_error_msg("unknown shell '%s', assuming bash", new_shell);
  314. }
  315. /* Exit codes:
  316. * 0) No errors, successful operation.
  317. * 1) getopt(3) returned an error.
  318. * 2) A problem with parameter parsing for getopt(1).
  319. * 3) Internal error, out of memory
  320. * 4) Returned for -T
  321. */
  322. #if ENABLE_FEATURE_GETOPT_LONG
  323. static const char getopt_longopts[] ALIGN1 =
  324. "options\0" Required_argument "o"
  325. "longoptions\0" Required_argument "l"
  326. "quiet\0" No_argument "q"
  327. "quiet-output\0" No_argument "Q"
  328. "shell\0" Required_argument "s"
  329. "test\0" No_argument "T"
  330. "unquoted\0" No_argument "u"
  331. "alternative\0" No_argument "a"
  332. "name\0" Required_argument "n"
  333. ;
  334. #endif
  335. int getopt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  336. int getopt_main(int argc, char **argv)
  337. {
  338. int n;
  339. char *optstr = NULL;
  340. char *name = NULL;
  341. unsigned opt;
  342. const char *compatible;
  343. char *s_arg;
  344. #if ENABLE_FEATURE_GETOPT_LONG
  345. struct option *long_options = NULL;
  346. llist_t *l_arg = NULL;
  347. #endif
  348. compatible = getenv("GETOPT_COMPATIBLE"); /* used as yes/no flag */
  349. if (!argv[1]) {
  350. if (compatible) {
  351. /* For some reason, the original getopt gave no error
  352. * when there were no arguments. */
  353. puts(" --");
  354. return 0;
  355. }
  356. bb_simple_error_msg_and_die("missing optstring argument");
  357. }
  358. if (argv[1][0] != '-' || compatible) {
  359. char *s = argv[1];
  360. option_mask32 |= OPT_u; /* quoting off */
  361. s = xstrdup(s + strspn(s, "-+"));
  362. argv[1] = argv[0];
  363. return generate_output(argv+1, argc-1, s, long_options);
  364. }
  365. #if !ENABLE_FEATURE_GETOPT_LONG
  366. opt = getopt32(argv, "+o:n:qQs:Tu", &optstr, &name, &s_arg);
  367. #else
  368. opt = getopt32long(argv, "+o:n:qQs:Tual:*", getopt_longopts,
  369. &optstr, &name, &s_arg, &l_arg);
  370. /* Effectuate the read options for the applet itself */
  371. while (l_arg) {
  372. long_options = add_long_options(long_options, llist_pop(&l_arg));
  373. }
  374. #endif
  375. if (opt & OPT_s) {
  376. set_shell(s_arg);
  377. }
  378. if (opt & OPT_T) {
  379. return 4;
  380. }
  381. /* All options controlling the applet have now been parsed */
  382. n = optind - 1;
  383. if (!optstr) {
  384. optstr = argv[++n];
  385. if (!optstr)
  386. bb_simple_error_msg_and_die("missing optstring argument");
  387. }
  388. argv[n] = name ? name : argv[0];
  389. return generate_output(argv + n, argc - n, optstr, long_options);
  390. }