3
0

getopt.c 12 KB

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