getopt.c 9.2 KB

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