getopt.c 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 Mi<B6>kiewicz
  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) generate_output(argv,argc,optstr)
  134. #endif
  135. static int generate_output(char **argv, int argc, const char *optstr, const struct option *longopts)
  136. {
  137. int exit_code = 0; /* We assume everything will be OK */
  138. unsigned opt;
  139. #if ENABLE_GETOPT_LONG
  140. int longindex;
  141. #endif
  142. const char *charptr;
  143. if (quiet_errors) /* No error reporting from getopt(3) */
  144. opterr = 0;
  145. optind = 0; /* Reset getopt(3) */
  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 == EOF)
  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(long_options,
  217. sizeof(long_options[0]) * (long_nr+2));
  218. long_options[long_nr].has_arg = arg_opt;
  219. long_options[long_nr].flag = NULL;
  220. long_options[long_nr].val = LONG_OPT;
  221. long_options[long_nr].name = xstrdup(tokptr);
  222. long_nr++;
  223. memset(&long_options[long_nr], 0, sizeof(long_options[0]));
  224. }
  225. tokptr = strtok(NULL, ", \t\n");
  226. }
  227. return long_options;
  228. }
  229. #endif
  230. static void set_shell(const char *new_shell)
  231. {
  232. if (!strcmp(new_shell,"bash") || !strcmp(new_shell,"sh"))
  233. return;
  234. if (!strcmp(new_shell,"tcsh") || !strcmp(new_shell,"csh"))
  235. option_mask32 |= SHELL_IS_TCSH;
  236. else
  237. bb_error_msg("unknown shell '%s', assuming bash", new_shell);
  238. }
  239. /* Exit codes:
  240. * 0) No errors, successful operation.
  241. * 1) getopt(3) returned an error.
  242. * 2) A problem with parameter parsing for getopt(1).
  243. * 3) Internal error, out of memory
  244. * 4) Returned for -T
  245. */
  246. #if ENABLE_GETOPT_LONG
  247. static const char getopt_longopts[] ALIGN1 =
  248. "options\0" Required_argument "o"
  249. "longoptions\0" Required_argument "l"
  250. "quiet\0" No_argument "q"
  251. "quiet-output\0" No_argument "Q"
  252. "shell\0" Required_argument "s"
  253. "test\0" No_argument "T"
  254. "unquoted\0" No_argument "u"
  255. "alternative\0" No_argument "a"
  256. "name\0" Required_argument "n"
  257. ;
  258. #endif
  259. int getopt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  260. int getopt_main(int argc, char **argv)
  261. {
  262. char *optstr = NULL;
  263. char *name = NULL;
  264. unsigned opt;
  265. const char *compatible;
  266. char *s_arg;
  267. #if ENABLE_GETOPT_LONG
  268. struct option *long_options = NULL;
  269. llist_t *l_arg = NULL;
  270. #endif
  271. compatible = getenv("GETOPT_COMPATIBLE"); /* used as yes/no flag */
  272. if (argc == 1) {
  273. if (compatible) {
  274. /* For some reason, the original getopt gave no error
  275. when there were no arguments. */
  276. printf(" --\n");
  277. return 0;
  278. }
  279. bb_error_msg_and_die("missing optstring argument");
  280. }
  281. if (argv[1][0] != '-' || compatible) {
  282. char *s;
  283. option_mask32 |= OPT_u; /* quoting off */
  284. s = xstrdup(argv[1] + strspn(argv[1], "-+"));
  285. argv[1] = argv[0];
  286. return generate_output(argv+1, argc-1, s, long_options);
  287. }
  288. #if !ENABLE_GETOPT_LONG
  289. opt = getopt32(argv, "+o:n:qQs:Tu", &optstr, &name, &s_arg);
  290. #else
  291. applet_long_options = getopt_longopts;
  292. opt_complementary = "l::";
  293. opt = getopt32(argv, "+o:n:qQs:Tual:",
  294. &optstr, &name, &s_arg, &l_arg);
  295. /* Effectuate the read options for the applet itself */
  296. while (l_arg) {
  297. long_options = add_long_options(long_options, l_arg->data);
  298. l_arg = l_arg->link;
  299. }
  300. #endif
  301. if (opt & OPT_s) {
  302. set_shell(s_arg);
  303. }
  304. if (opt & OPT_T) {
  305. return 4;
  306. }
  307. /* All options controlling the applet have now been parsed */
  308. if (!optstr) {
  309. if (optind >= argc)
  310. bb_error_msg_and_die("missing optstring argument");
  311. optstr = argv[optind++];
  312. }
  313. argv[optind-1] = name ? name : argv[0];
  314. return generate_output(argv+optind-1, argc-optind+1, optstr, long_options);
  315. }