3
0

getopt.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. char *BUFFER;
  151. if (!quote) { /* Just return arg */
  152. return arg;
  153. }
  154. /* Each character in arg may take up to four characters in the result:
  155. For a quote we need a closing quote, a backslash, a quote and an
  156. opening quote! We need also the global opening and closing quote,
  157. and one extra character for '\0'. */
  158. BUFFER = auto_string(xmalloc(strlen(arg)*4 + 3));
  159. bufptr = BUFFER;
  160. *bufptr ++= '\'';
  161. while (*arg) {
  162. if (shell_TCSH && *arg == '\n') {
  163. /* Newline: replace it with: \n */
  164. *bufptr++ = '\\';
  165. *bufptr++ = 'n';
  166. } else
  167. if ((shell_TCSH && (*arg == '!' || isspace(*arg)))
  168. || *arg == '\''
  169. ) {
  170. /* Quote exclamation marks, non-NL whitespace and quotes */
  171. *bufptr++ = '\'';
  172. *bufptr++ = '\\';
  173. *bufptr++ = *arg;
  174. *bufptr++ = '\'';
  175. } else {
  176. /* Just copy */
  177. *bufptr ++= *arg;
  178. }
  179. arg++;
  180. }
  181. *bufptr++ = '\'';
  182. *bufptr++ = '\0';
  183. return BUFFER;
  184. }
  185. /*
  186. * Generate the output. argv[0] is the program name (used for reporting errors).
  187. * argv[1..] contains the options to be parsed. argc must be the number of
  188. * elements in argv (ie. 1 if there are no options, only the program name),
  189. * optstr must contain the short options, and longopts the long options.
  190. * Other settings are found in global variables.
  191. */
  192. #if !ENABLE_FEATURE_GETOPT_LONG
  193. #define generate_output(argv,argc,optstr,longopts) \
  194. generate_output(argv,argc,optstr)
  195. #endif
  196. static int generate_output(char **argv, int argc, const char *optstr, const struct option *longopts)
  197. {
  198. int exit_code = 0; /* We assume everything will be OK */
  199. if (quiet_errors) /* No error reporting from getopt(3) */
  200. opterr = 0;
  201. /* We used it already in main() in getopt32(),
  202. * we *must* reset getopt(3): */
  203. GETOPT_RESET();
  204. while (1) {
  205. #if ENABLE_FEATURE_GETOPT_LONG
  206. int longindex;
  207. int opt = alternative
  208. ? getopt_long_only(argc, argv, optstr, longopts, &longindex)
  209. : getopt_long(argc, argv, optstr, longopts, &longindex)
  210. ;
  211. #else
  212. int opt = getopt(argc, argv, optstr);
  213. #endif
  214. if (opt == -1)
  215. break;
  216. if (opt == '?' || opt == ':' )
  217. exit_code = 1;
  218. else if (!quiet_output) {
  219. #if ENABLE_FEATURE_GETOPT_LONG
  220. if (opt == LONG_OPT) {
  221. printf(" --%s", longopts[longindex].name);
  222. if (longopts[longindex].has_arg)
  223. printf(" %s",
  224. normalize(optarg ? optarg : ""));
  225. } else
  226. #endif
  227. if (opt == NON_OPT)
  228. printf(" %s", normalize(optarg));
  229. else {
  230. const char *charptr;
  231. printf(" -%c", opt);
  232. charptr = strchr(optstr, opt);
  233. if (charptr && *++charptr == ':')
  234. printf(" %s",
  235. normalize(optarg ? optarg : ""));
  236. }
  237. }
  238. }
  239. if (!quiet_output) {
  240. unsigned idx;
  241. printf(" --");
  242. idx = optind;
  243. while (argv[idx])
  244. printf(" %s", normalize(argv[idx++]));
  245. bb_putchar('\n');
  246. }
  247. return exit_code;
  248. }
  249. #if ENABLE_FEATURE_GETOPT_LONG
  250. /*
  251. * Register several long options. options is a string of long options,
  252. * separated by commas or whitespace.
  253. * This nukes options!
  254. */
  255. static struct option *add_long_options(struct option *long_options, char *options)
  256. {
  257. int long_nr = 0;
  258. int arg_opt, tlen;
  259. char *tokptr;
  260. if (long_options)
  261. while (long_options[long_nr].name)
  262. long_nr++;
  263. tokptr = strtok_r(options, ", \t\n", &options);
  264. while (tokptr) {
  265. arg_opt = no_argument;
  266. tlen = strlen(tokptr);
  267. if (tlen) {
  268. tlen--;
  269. if (tokptr[tlen] == ':') {
  270. arg_opt = required_argument;
  271. if (tlen && tokptr[tlen-1] == ':') {
  272. tlen--;
  273. arg_opt = optional_argument;
  274. }
  275. tokptr[tlen] = '\0';
  276. if (tlen == 0)
  277. bb_simple_error_msg_and_die("empty long option specified");
  278. }
  279. long_options = xrealloc_vector(long_options, 4, long_nr);
  280. long_options[long_nr].has_arg = arg_opt;
  281. /*long_options[long_nr].flag = NULL; - xrealloc_vector did it */
  282. long_options[long_nr].val = LONG_OPT;
  283. long_options[long_nr].name = xstrdup(tokptr);
  284. long_nr++;
  285. /*memset(&long_options[long_nr], 0, sizeof(long_options[0])); - xrealloc_vector did it */
  286. }
  287. tokptr = strtok_r(NULL, ", \t\n", &options);
  288. }
  289. return long_options;
  290. }
  291. #endif
  292. static void set_shell(const char *new_shell)
  293. {
  294. switch (index_in_strings("bash\0sh\0tcsh\0csh\0", new_shell)) {
  295. case 0:
  296. case 1:
  297. break;
  298. case 2:
  299. case 3:
  300. option_mask32 |= SHELL_IS_TCSH;
  301. break;
  302. default:
  303. bb_error_msg("unknown shell '%s', assuming bash", new_shell);
  304. break;
  305. }
  306. }
  307. /* Exit codes:
  308. * 0) No errors, successful operation.
  309. * 1) getopt(3) returned an error.
  310. * 2) A problem with parameter parsing for getopt(1).
  311. * 3) Internal error, out of memory
  312. * 4) Returned for -T
  313. */
  314. #if ENABLE_FEATURE_GETOPT_LONG
  315. static const char getopt_longopts[] ALIGN1 =
  316. "options\0" Required_argument "o"
  317. "longoptions\0" Required_argument "l"
  318. "quiet\0" No_argument "q"
  319. "quiet-output\0" No_argument "Q"
  320. "shell\0" Required_argument "s"
  321. "test\0" No_argument "T"
  322. "unquoted\0" No_argument "u"
  323. "alternative\0" No_argument "a"
  324. "name\0" Required_argument "n"
  325. ;
  326. #endif
  327. int getopt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  328. int getopt_main(int argc, char **argv)
  329. {
  330. int n;
  331. char *optstr = NULL;
  332. char *name = NULL;
  333. unsigned opt;
  334. const char *compatible;
  335. char *s_arg;
  336. #if ENABLE_FEATURE_GETOPT_LONG
  337. struct option *long_options = NULL;
  338. llist_t *l_arg = NULL;
  339. #endif
  340. compatible = getenv("GETOPT_COMPATIBLE"); /* used as yes/no flag */
  341. if (!argv[1]) {
  342. if (compatible) {
  343. /* For some reason, the original getopt gave no error
  344. * when there were no arguments. */
  345. puts(" --");
  346. return 0;
  347. }
  348. bb_simple_error_msg_and_die("missing optstring argument");
  349. }
  350. if (argv[1][0] != '-' || compatible) {
  351. char *s = argv[1];
  352. option_mask32 |= OPT_u; /* quoting off */
  353. s = xstrdup(s + strspn(s, "-+"));
  354. argv[1] = argv[0];
  355. return generate_output(argv+1, argc-1, s, long_options);
  356. }
  357. #if !ENABLE_FEATURE_GETOPT_LONG
  358. opt = getopt32(argv, "+o:n:qQs:Tu", &optstr, &name, &s_arg);
  359. #else
  360. opt = getopt32long(argv, "+o:n:qQs:Tual:*", getopt_longopts,
  361. &optstr, &name, &s_arg, &l_arg);
  362. /* Effectuate the read options for the applet itself */
  363. while (l_arg) {
  364. long_options = add_long_options(long_options, llist_pop(&l_arg));
  365. }
  366. #endif
  367. if (opt & OPT_s) {
  368. set_shell(s_arg);
  369. }
  370. if (opt & OPT_T) {
  371. return 4;
  372. }
  373. /* All options controlling the applet have now been parsed */
  374. n = optind - 1;
  375. if (!optstr) {
  376. optstr = argv[++n];
  377. if (!optstr)
  378. bb_simple_error_msg_and_die("missing optstring argument");
  379. }
  380. argv[n] = name ? name : argv[0];
  381. return generate_output(argv + n, argc - n, optstr, long_options);
  382. }