getopt.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * getopt.c
  3. */
  4. #include <linux/kernel.h>
  5. #include <linux/string.h>
  6. #include <asm/errno.h>
  7. #include "getopt.h"
  8. /**
  9. * ncp_getopt - option parser
  10. * @caller: name of the caller, for error messages
  11. * @options: the options string
  12. * @opts: an array of &struct option entries controlling parser operations
  13. * @optopt: output; will contain the current option
  14. * @optarg: output; will contain the value (if one exists)
  15. * @flag: output; may be NULL; should point to a long for or'ing flags
  16. * @value: output; may be NULL; will be overwritten with the integer value
  17. * of the current argument.
  18. *
  19. * Helper to parse options on the format used by mount ("a=b,c=d,e,f").
  20. * Returns opts->val if a matching entry in the 'opts' array is found,
  21. * 0 when no more tokens are found, -1 if an error is encountered.
  22. */
  23. int ncp_getopt(const char *caller, char **options, const struct ncp_option *opts,
  24. char **optopt, char **optarg, unsigned long *value)
  25. {
  26. char *token;
  27. char *val;
  28. do {
  29. if ((token = strsep(options, ",")) == NULL)
  30. return 0;
  31. } while (*token == '\0');
  32. if (optopt)
  33. *optopt = token;
  34. if ((val = strchr (token, '=')) != NULL) {
  35. *val++ = 0;
  36. }
  37. *optarg = val;
  38. for (; opts->name; opts++) {
  39. if (!strcmp(opts->name, token)) {
  40. if (!val) {
  41. if (opts->has_arg & OPT_NOPARAM) {
  42. return opts->val;
  43. }
  44. printk(KERN_INFO "%s: the %s option requires an argument\n",
  45. caller, token);
  46. return -EINVAL;
  47. }
  48. if (opts->has_arg & OPT_INT) {
  49. char* v;
  50. *value = simple_strtoul(val, &v, 0);
  51. if (!*v) {
  52. return opts->val;
  53. }
  54. printk(KERN_INFO "%s: invalid numeric value in %s=%s\n",
  55. caller, token, val);
  56. return -EDOM;
  57. }
  58. if (opts->has_arg & OPT_STRING) {
  59. return opts->val;
  60. }
  61. printk(KERN_INFO "%s: unexpected argument %s to the %s option\n",
  62. caller, val, token);
  63. return -EINVAL;
  64. }
  65. }
  66. printk(KERN_INFO "%s: Unrecognized mount option %s\n", caller, token);
  67. return -EOPNOTSUPP;
  68. }