getopt.c 12 KB

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