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