getopt.c 12 KB

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