getopt.c 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 tarball for details.
  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_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_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_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_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. while (1) {
  147. opt =
  148. #if ENABLE_GETOPT_LONG
  149. alternative ?
  150. getopt_long_only(argc, argv, optstr, longopts, &longindex) :
  151. getopt_long(argc, argv, optstr, longopts, &longindex);
  152. #else
  153. getopt(argc, argv, optstr);
  154. #endif
  155. if (opt == -1)
  156. break;
  157. if (opt == '?' || opt == ':' )
  158. exit_code = 1;
  159. else if (!quiet_output) {
  160. #if ENABLE_GETOPT_LONG
  161. if (opt == LONG_OPT) {
  162. printf(" --%s", longopts[longindex].name);
  163. if (longopts[longindex].has_arg)
  164. printf(" %s",
  165. normalize(optarg ? optarg : ""));
  166. } else
  167. #endif
  168. if (opt == NON_OPT)
  169. printf(" %s", normalize(optarg));
  170. else {
  171. printf(" -%c", opt);
  172. charptr = strchr(optstr, opt);
  173. if (charptr != NULL && *++charptr == ':')
  174. printf(" %s",
  175. normalize(optarg ? optarg : ""));
  176. }
  177. }
  178. }
  179. if (!quiet_output) {
  180. printf(" --");
  181. while (optind < argc)
  182. printf(" %s", normalize(argv[optind++]));
  183. bb_putchar('\n');
  184. }
  185. return exit_code;
  186. }
  187. #if ENABLE_GETOPT_LONG
  188. /*
  189. * Register several long options. options is a string of long options,
  190. * separated by commas or whitespace.
  191. * This nukes options!
  192. */
  193. static struct option *add_long_options(struct option *long_options, char *options)
  194. {
  195. int long_nr = 0;
  196. int arg_opt, tlen;
  197. char *tokptr = strtok(options, ", \t\n");
  198. if (long_options)
  199. while (long_options[long_nr].name)
  200. long_nr++;
  201. while (tokptr) {
  202. arg_opt = no_argument;
  203. tlen = strlen(tokptr);
  204. if (tlen) {
  205. tlen--;
  206. if (tokptr[tlen] == ':') {
  207. arg_opt = required_argument;
  208. if (tlen && tokptr[tlen-1] == ':') {
  209. tlen--;
  210. arg_opt = optional_argument;
  211. }
  212. tokptr[tlen] = '\0';
  213. if (tlen == 0)
  214. bb_error_msg_and_die("empty long option specified");
  215. }
  216. long_options = xrealloc_vector(long_options, 4, long_nr);
  217. long_options[long_nr].has_arg = arg_opt;
  218. /*long_options[long_nr].flag = NULL; - xrealloc_vector did it */
  219. long_options[long_nr].val = LONG_OPT;
  220. long_options[long_nr].name = xstrdup(tokptr);
  221. long_nr++;
  222. /*memset(&long_options[long_nr], 0, sizeof(long_options[0])); - xrealloc_vector did it */
  223. }
  224. tokptr = strtok(NULL, ", \t\n");
  225. }
  226. return long_options;
  227. }
  228. #endif
  229. static void set_shell(const char *new_shell)
  230. {
  231. if (!strcmp(new_shell, "bash") || !strcmp(new_shell, "sh"))
  232. return;
  233. if (!strcmp(new_shell, "tcsh") || !strcmp(new_shell, "csh"))
  234. option_mask32 |= SHELL_IS_TCSH;
  235. else
  236. bb_error_msg("unknown shell '%s', assuming bash", new_shell);
  237. }
  238. /* Exit codes:
  239. * 0) No errors, successful operation.
  240. * 1) getopt(3) returned an error.
  241. * 2) A problem with parameter parsing for getopt(1).
  242. * 3) Internal error, out of memory
  243. * 4) Returned for -T
  244. */
  245. #if ENABLE_GETOPT_LONG
  246. static const char getopt_longopts[] ALIGN1 =
  247. "options\0" Required_argument "o"
  248. "longoptions\0" Required_argument "l"
  249. "quiet\0" No_argument "q"
  250. "quiet-output\0" No_argument "Q"
  251. "shell\0" Required_argument "s"
  252. "test\0" No_argument "T"
  253. "unquoted\0" No_argument "u"
  254. "alternative\0" No_argument "a"
  255. "name\0" Required_argument "n"
  256. ;
  257. #endif
  258. int getopt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  259. int getopt_main(int argc, char **argv)
  260. {
  261. char *optstr = NULL;
  262. char *name = NULL;
  263. unsigned opt;
  264. const char *compatible;
  265. char *s_arg;
  266. #if ENABLE_GETOPT_LONG
  267. struct option *long_options = NULL;
  268. llist_t *l_arg = NULL;
  269. #endif
  270. compatible = getenv("GETOPT_COMPATIBLE"); /* used as yes/no flag */
  271. if (argc == 1) {
  272. if (compatible) {
  273. /* For some reason, the original getopt gave no error
  274. when there were no arguments. */
  275. printf(" --\n");
  276. return 0;
  277. }
  278. bb_error_msg_and_die("missing optstring argument");
  279. }
  280. if (argv[1][0] != '-' || compatible) {
  281. char *s;
  282. option_mask32 |= OPT_u; /* quoting off */
  283. s = xstrdup(argv[1] + strspn(argv[1], "-+"));
  284. argv[1] = argv[0];
  285. return generate_output(argv+1, argc-1, s, long_options);
  286. }
  287. #if !ENABLE_GETOPT_LONG
  288. opt = getopt32(argv, "+o:n:qQs:Tu", &optstr, &name, &s_arg);
  289. #else
  290. applet_long_options = getopt_longopts;
  291. opt_complementary = "l::";
  292. opt = getopt32(argv, "+o:n:qQs:Tual:",
  293. &optstr, &name, &s_arg, &l_arg);
  294. /* Effectuate the read options for the applet itself */
  295. while (l_arg) {
  296. long_options = add_long_options(long_options, llist_pop(&l_arg));
  297. }
  298. #endif
  299. if (opt & OPT_s) {
  300. set_shell(s_arg);
  301. }
  302. if (opt & OPT_T) {
  303. return 4;
  304. }
  305. /* All options controlling the applet have now been parsed */
  306. if (!optstr) {
  307. if (optind >= argc)
  308. bb_error_msg_and_die("missing optstring argument");
  309. optstr = argv[optind++];
  310. }
  311. argv[optind-1] = name ? name : argv[0];
  312. return generate_output(argv+optind-1, argc-optind+1, optstr, long_options);
  313. }