getopt.c 9.3 KB

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