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. * @value: output; may be NULL; will be overwritten with the integer value
  16. * of the current argument.
  17. *
  18. * Helper to parse options on the format used by mount ("a=b,c=d,e,f").
  19. * Returns opts->val if a matching entry in the 'opts' array is found,
  20. * 0 when no more tokens are found, -1 if an error is encountered.
  21. */
  22. int ncp_getopt(const char *caller, char **options, const struct ncp_option *opts,
  23. char **optopt, char **optarg, unsigned long *value)
  24. {
  25. char *token;
  26. char *val;
  27. do {
  28. if ((token = strsep(options, ",")) == NULL)
  29. return 0;
  30. } while (*token == '\0');
  31. if (optopt)
  32. *optopt = token;
  33. if ((val = strchr (token, '=')) != NULL) {
  34. *val++ = 0;
  35. }
  36. *optarg = val;
  37. for (; opts->name; opts++) {
  38. if (!strcmp(opts->name, token)) {
  39. if (!val) {
  40. if (opts->has_arg & OPT_NOPARAM) {
  41. return opts->val;
  42. }
  43. printk(KERN_INFO "%s: the %s option requires an argument\n",
  44. caller, token);
  45. return -EINVAL;
  46. }
  47. if (opts->has_arg & OPT_INT) {
  48. char* v;
  49. *value = simple_strtoul(val, &v, 0);
  50. if (!*v) {
  51. return opts->val;
  52. }
  53. printk(KERN_INFO "%s: invalid numeric value in %s=%s\n",
  54. caller, token, val);
  55. return -EDOM;
  56. }
  57. if (opts->has_arg & OPT_STRING) {
  58. return opts->val;
  59. }
  60. printk(KERN_INFO "%s: unexpected argument %s to the %s option\n",
  61. caller, val, token);
  62. return -EINVAL;
  63. }
  64. }
  65. printk(KERN_INFO "%s: Unrecognized mount option %s\n", caller, token);
  66. return -EOPNOTSUPP;
  67. }