xref: /freebsd/crypto/heimdal/lib/roken/getarg.c (revision f126890a)
1 /*
2  * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <config.h>
35 
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include "roken.h"
40 #include "getarg.h"
41 
42 #define ISFLAG(X) ((X).type == arg_flag || (X).type == arg_negative_flag)
43 
44 static size_t
45 print_arg (char *string,
46 	   size_t len,
47 	   int mdoc,
48 	   int longp,
49 	   struct getargs *arg,
50 	   char *(i18n)(const char *))
51 {
52     const char *s;
53 
54     *string = '\0';
55 
56     if (ISFLAG(*arg) || (!longp && arg->type == arg_counter))
57 	return 0;
58 
59     if(mdoc){
60 	if(longp)
61 	    strlcat(string, "= Ns", len);
62 	strlcat(string, " Ar ", len);
63     } else {
64 	if (longp)
65 	    strlcat (string, "=", len);
66 	else
67 	    strlcat (string, " ", len);
68     }
69 
70     if (arg->arg_help)
71 	s = (*i18n)(arg->arg_help);
72     else if (arg->type == arg_integer || arg->type == arg_counter)
73 	s = "integer";
74     else if (arg->type == arg_string)
75 	s = "string";
76     else if (arg->type == arg_strings)
77 	s = "strings";
78     else if (arg->type == arg_double)
79 	s = "float";
80     else
81 	s = "<undefined>";
82 
83     strlcat(string, s, len);
84     return 1 + strlen(s);
85 }
86 
87 static void
88 mandoc_template(struct getargs *args,
89 		size_t num_args,
90 		const char *progname,
91 		const char *extra_string,
92 		char *(i18n)(const char *))
93 {
94     size_t i;
95     char timestr[64], cmd[64];
96     char buf[128];
97     const char *p;
98     time_t t;
99 
100     printf(".\\\" Things to fix:\n");
101     printf(".\\\"   * correct section, and operating system\n");
102     printf(".\\\"   * remove Op from mandatory flags\n");
103     printf(".\\\"   * use better macros for arguments (like .Pa for files)\n");
104     printf(".\\\"\n");
105     t = time(NULL);
106     strftime(timestr, sizeof(timestr), "%B %e, %Y", localtime(&t));
107     printf(".Dd %s\n", timestr);
108     p = strrchr(progname, '/');
109     if(p) p++; else p = progname;
110     strlcpy(cmd, p, sizeof(cmd));
111     strupr(cmd);
112 
113     printf(".Dt %s SECTION\n", cmd);
114     printf(".Os OPERATING_SYSTEM\n");
115     printf(".Sh NAME\n");
116     printf(".Nm %s\n", p);
117     printf(".Nd in search of a description\n");
118     printf(".Sh SYNOPSIS\n");
119     printf(".Nm\n");
120     for(i = 0; i < num_args; i++){
121 	/* we seem to hit a limit on number of arguments if doing
122            short and long flags with arguments -- split on two lines */
123 	if(ISFLAG(args[i]) ||
124 	   args[i].short_name == 0 || args[i].long_name == NULL) {
125 	    printf(".Op ");
126 
127 	    if(args[i].short_name) {
128 		print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
129 		printf("Fl %c%s", args[i].short_name, buf);
130 		if(args[i].long_name)
131 		    printf(" | ");
132 	    }
133 	    if(args[i].long_name) {
134 		print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
135 		printf("Fl Fl %s%s%s",
136 		       args[i].type == arg_negative_flag ? "no-" : "",
137 		       args[i].long_name, buf);
138 	    }
139 	    printf("\n");
140 	} else {
141 	    print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
142 	    printf(".Oo Fl %c%s \\*(Ba Xo\n", args[i].short_name, buf);
143 	    print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
144 	    printf(".Fl Fl %s%s\n.Xc\n.Oc\n", args[i].long_name, buf);
145 	}
146     /*
147 	    if(args[i].type == arg_strings)
148 		fprintf (stderr, "...");
149 		*/
150     }
151     if (extra_string && *extra_string)
152 	printf (".Ar %s\n", extra_string);
153     printf(".Sh DESCRIPTION\n");
154     printf("Supported options:\n");
155     printf(".Bl -tag -width Ds\n");
156     for(i = 0; i < num_args; i++){
157 	printf(".It Xo\n");
158 	if(args[i].short_name){
159 	    printf(".Fl %c", args[i].short_name);
160 	    print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
161 	    printf("%s", buf);
162 	    if(args[i].long_name)
163 		printf(" ,");
164 	    printf("\n");
165 	}
166 	if(args[i].long_name){
167 	    printf(".Fl Fl %s%s",
168 		   args[i].type == arg_negative_flag ? "no-" : "",
169 		   args[i].long_name);
170 	    print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
171 	    printf("%s\n", buf);
172 	}
173 	printf(".Xc\n");
174 	if(args[i].help)
175 	    printf("%s\n", args[i].help);
176     /*
177 	    if(args[i].type == arg_strings)
178 		fprintf (stderr, "...");
179 		*/
180     }
181     printf(".El\n");
182     printf(".\\\".Sh ENVIRONMENT\n");
183     printf(".\\\".Sh FILES\n");
184     printf(".\\\".Sh EXAMPLES\n");
185     printf(".\\\".Sh DIAGNOSTICS\n");
186     printf(".\\\".Sh SEE ALSO\n");
187     printf(".\\\".Sh STANDARDS\n");
188     printf(".\\\".Sh HISTORY\n");
189     printf(".\\\".Sh AUTHORS\n");
190     printf(".\\\".Sh BUGS\n");
191 }
192 
193 static int
194 check_column(FILE *f, int col, int len, int columns)
195 {
196     if(col + len > columns) {
197 	fprintf(f, "\n");
198 	col = fprintf(f, "  ");
199     }
200     return col;
201 }
202 
203 static char *
204 builtin_i18n(const char *str)
205 {
206     return rk_UNCONST(str);
207 }
208 
209 ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
210 arg_printusage (struct getargs *args,
211 		size_t num_args,
212 		const char *progname,
213 		const char *extra_string)
214 {
215     arg_printusage_i18n(args, num_args, "Usage",
216 			progname, extra_string, builtin_i18n);
217 }
218 
219 ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
220 arg_printusage_i18n (struct getargs *args,
221 		     size_t num_args,
222 		     const char *usage,
223 		     const char *progname,
224 		     const char *extra_string,
225 		     char *(*i18n)(const char *))
226 {
227     size_t i, max_len = 0;
228     char buf[128];
229     int col = 0, columns;
230 
231     if (progname == NULL)
232 	progname = getprogname();
233 
234     if (i18n == NULL)
235 	i18n = builtin_i18n;
236 
237     if(getenv("GETARGMANDOC")){
238 	mandoc_template(args, num_args, progname, extra_string, i18n);
239 	return;
240     }
241     if(get_window_size(2, NULL, &columns) == -1)
242 	columns = 80;
243     col = 0;
244     col += fprintf (stderr, "%s: %s", usage, progname);
245     buf[0] = '\0';
246     for (i = 0; i < num_args; ++i) {
247 	if(args[i].short_name && ISFLAG(args[i])) {
248 	    char s[2];
249 	    if(buf[0] == '\0')
250 		strlcpy(buf, "[-", sizeof(buf));
251 	    s[0] = args[i].short_name;
252 	    s[1] = '\0';
253 	    strlcat(buf, s, sizeof(buf));
254 	}
255     }
256     if(buf[0] != '\0') {
257 	strlcat(buf, "]", sizeof(buf));
258 	col = check_column(stderr, col, strlen(buf) + 1, columns);
259 	col += fprintf(stderr, " %s", buf);
260     }
261 
262     for (i = 0; i < num_args; ++i) {
263 	size_t len = 0;
264 
265 	if (args[i].long_name) {
266 	    buf[0] = '\0';
267 	    strlcat(buf, "[--", sizeof(buf));
268 	    len += 2;
269 	    if(args[i].type == arg_negative_flag) {
270 		strlcat(buf, "no-", sizeof(buf));
271 		len += 3;
272 	    }
273 	    strlcat(buf, args[i].long_name, sizeof(buf));
274 	    len += strlen(args[i].long_name);
275 	    len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
276 			     0, 1, &args[i], i18n);
277 	    strlcat(buf, "]", sizeof(buf));
278 	    if(args[i].type == arg_strings)
279 		strlcat(buf, "...", sizeof(buf));
280 	    col = check_column(stderr, col, strlen(buf) + 1, columns);
281 	    col += fprintf(stderr, " %s", buf);
282 	}
283 	if (args[i].short_name && !ISFLAG(args[i])) {
284 	    snprintf(buf, sizeof(buf), "[-%c", args[i].short_name);
285 	    len += 2;
286 	    len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
287 			     0, 0, &args[i], i18n);
288 	    strlcat(buf, "]", sizeof(buf));
289 	    if(args[i].type == arg_strings)
290 		strlcat(buf, "...", sizeof(buf));
291 	    col = check_column(stderr, col, strlen(buf) + 1, columns);
292 	    col += fprintf(stderr, " %s", buf);
293 	}
294 	if (args[i].long_name && args[i].short_name)
295 	    len += 2; /* ", " */
296 	max_len = max(max_len, len);
297     }
298     if (extra_string) {
299 	check_column(stderr, col, strlen(extra_string) + 1, columns);
300 	fprintf (stderr, " %s\n", extra_string);
301     } else
302 	fprintf (stderr, "\n");
303     for (i = 0; i < num_args; ++i) {
304 	if (args[i].help) {
305 	    size_t count = 0;
306 
307 	    if (args[i].short_name) {
308 		count += fprintf (stderr, "-%c", args[i].short_name);
309 		print_arg (buf, sizeof(buf), 0, 0, &args[i], i18n);
310 		count += fprintf(stderr, "%s", buf);
311 	    }
312 	    if (args[i].short_name && args[i].long_name)
313 		count += fprintf (stderr, ", ");
314 	    if (args[i].long_name) {
315 		count += fprintf (stderr, "--");
316 		if (args[i].type == arg_negative_flag)
317 		    count += fprintf (stderr, "no-");
318 		count += fprintf (stderr, "%s", args[i].long_name);
319 		print_arg (buf, sizeof(buf), 0, 1, &args[i], i18n);
320 		count += fprintf(stderr, "%s", buf);
321 	    }
322 	    while(count++ <= max_len)
323 		putc (' ', stderr);
324 	    fprintf (stderr, "%s\n", (*i18n)(args[i].help));
325 	}
326     }
327 }
328 
329 static int
330 add_string(getarg_strings *s, char *value)
331 {
332     char **strings;
333 
334     strings = realloc(s->strings, (s->num_strings + 1) * sizeof(*s->strings));
335     if (strings == NULL) {
336 	free(s->strings);
337 	s->strings = NULL;
338 	s->num_strings = 0;
339 	return ENOMEM;
340     }
341     s->strings = strings;
342     s->strings[s->num_strings] = value;
343     s->num_strings++;
344     return 0;
345 }
346 
347 static int
348 arg_match_long(struct getargs *args, size_t num_args,
349 	       char *argv, int argc, char **rargv, int *goptind)
350 {
351     size_t i;
352     char *goptarg = NULL;
353     int negate = 0;
354     int partial_match = 0;
355     struct getargs *partial = NULL;
356     struct getargs *current = NULL;
357     int argv_len;
358     char *p;
359     int p_len;
360 
361     argv_len = strlen(argv);
362     p = strchr (argv, '=');
363     if (p != NULL)
364 	argv_len = p - argv;
365 
366     for (i = 0; i < num_args; ++i) {
367 	if(args[i].long_name) {
368 	    int len = strlen(args[i].long_name);
369 	    p = argv;
370 	    p_len = argv_len;
371 	    negate = 0;
372 
373 	    for (;;) {
374 		if (strncmp (args[i].long_name, p, p_len) == 0) {
375 		    if(p_len == len)
376 			current = &args[i];
377 		    else {
378 			++partial_match;
379 			partial = &args[i];
380 		    }
381 		    goptarg  = p + p_len;
382 		} else if (ISFLAG(args[i]) && strncmp (p, "no-", 3) == 0) {
383 		    negate = !negate;
384 		    p += 3;
385 		    p_len -= 3;
386 		    continue;
387 		}
388 		break;
389 	    }
390 	    if (current)
391 		break;
392 	}
393     }
394     if (current == NULL) {
395 	if (partial_match == 1)
396 	    current = partial;
397 	else
398 	    return ARG_ERR_NO_MATCH;
399     }
400 
401     if(*goptarg == '\0'
402        && !ISFLAG(*current)
403        && current->type != arg_collect
404        && current->type != arg_counter)
405 	return ARG_ERR_NO_MATCH;
406     switch(current->type){
407     case arg_integer:
408     {
409 	int tmp;
410 	if(sscanf(goptarg + 1, "%d", &tmp) != 1)
411 	    return ARG_ERR_BAD_ARG;
412 	*(int*)current->value = tmp;
413 	return 0;
414     }
415     case arg_string:
416     {
417 	*(char**)current->value = goptarg + 1;
418 	return 0;
419     }
420     case arg_strings:
421     {
422 	return add_string((getarg_strings*)current->value, goptarg + 1);
423     }
424     case arg_flag:
425     case arg_negative_flag:
426     {
427 	int *flag = current->value;
428 	if(*goptarg == '\0' ||
429 	   strcmp(goptarg + 1, "yes") == 0 ||
430 	   strcmp(goptarg + 1, "true") == 0){
431 	    *flag = !negate;
432 	    return 0;
433 	} else if (*goptarg && strcmp(goptarg + 1, "maybe") == 0) {
434 	    *flag = rk_random() & 1;
435 	} else {
436 	    *flag = negate;
437 	    return 0;
438 	}
439 	return ARG_ERR_BAD_ARG;
440     }
441     case arg_counter :
442     {
443 	int val;
444 
445 	if (*goptarg == '\0')
446 	    val = 1;
447 	else if(sscanf(goptarg + 1, "%d", &val) != 1)
448 	    return ARG_ERR_BAD_ARG;
449 	*(int *)current->value += val;
450 	return 0;
451     }
452     case arg_double:
453     {
454 	double tmp;
455 	if(sscanf(goptarg + 1, "%lf", &tmp) != 1)
456 	    return ARG_ERR_BAD_ARG;
457 	*(double*)current->value = tmp;
458 	return 0;
459     }
460     case arg_collect:{
461 	struct getarg_collect_info *c = current->value;
462 	int o = argv - rargv[*goptind];
463 	return (*c->func)(FALSE, argc, rargv, goptind, &o, c->data);
464     }
465 
466     default:
467 	abort ();
468 	UNREACHABLE(return 0);
469     }
470 }
471 
472 static int
473 arg_match_short (struct getargs *args, size_t num_args,
474 		 char *argv, int argc, char **rargv, int *goptind)
475 {
476     size_t j, k;
477 
478     for(j = 1; j > 0 && j < strlen(rargv[*goptind]); j++) {
479 	for(k = 0; k < num_args; k++) {
480 	    char *goptarg;
481 
482 	    if(args[k].short_name == 0)
483 		continue;
484 	    if(argv[j] == args[k].short_name) {
485 		if(args[k].type == arg_flag) {
486 		    *(int*)args[k].value = 1;
487 		    break;
488 		}
489 		if(args[k].type == arg_negative_flag) {
490 		    *(int*)args[k].value = 0;
491 		    break;
492 		}
493 		if(args[k].type == arg_counter) {
494 		    ++*(int *)args[k].value;
495 		    break;
496 		}
497 		if(args[k].type == arg_collect) {
498 		    struct getarg_collect_info *c = args[k].value;
499 		    int a = (int)j;
500 
501 		    if((*c->func)(TRUE, argc, rargv, goptind, &a, c->data))
502 			return ARG_ERR_BAD_ARG;
503 		    j = a;
504 		    break;
505 		}
506 
507 		if(argv[j + 1])
508 		    goptarg = &argv[j + 1];
509 		else {
510 		    ++*goptind;
511 		    goptarg = rargv[*goptind];
512 		}
513 		if(goptarg == NULL) {
514 		    --*goptind;
515 		    return ARG_ERR_NO_ARG;
516 		}
517 		if(args[k].type == arg_integer) {
518 		    int tmp;
519 		    if(sscanf(goptarg, "%d", &tmp) != 1)
520 			return ARG_ERR_BAD_ARG;
521 		    *(int*)args[k].value = tmp;
522 		    return 0;
523 		} else if(args[k].type == arg_string) {
524 		    *(char**)args[k].value = goptarg;
525 		    return 0;
526 		} else if(args[k].type == arg_strings) {
527 		    return add_string((getarg_strings*)args[k].value, goptarg);
528 		} else if(args[k].type == arg_double) {
529 		    double tmp;
530 		    if(sscanf(goptarg, "%lf", &tmp) != 1)
531 			return ARG_ERR_BAD_ARG;
532 		    *(double*)args[k].value = tmp;
533 		    return 0;
534 		}
535 		return ARG_ERR_BAD_ARG;
536 	    }
537 	}
538 	if (k == num_args)
539 	    return ARG_ERR_NO_MATCH;
540     }
541     return 0;
542 }
543 
544 ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
545 getarg(struct getargs *args, size_t num_args,
546        int argc, char **argv, int *goptind)
547 {
548     int i;
549     int ret = 0;
550 
551     rk_random_init();
552     (*goptind)++;
553     for(i = *goptind; i < argc; i++) {
554 	if(argv[i][0] != '-')
555 	    break;
556 	if(argv[i][1] == '-'){
557 	    if(argv[i][2] == 0){
558 		i++;
559 		break;
560 	    }
561 	    ret = arg_match_long (args, num_args, argv[i] + 2,
562 				  argc, argv, &i);
563 	} else {
564 	    ret = arg_match_short (args, num_args, argv[i],
565 				   argc, argv, &i);
566 	}
567 	if(ret)
568 	    break;
569     }
570     *goptind = i;
571     return ret;
572 }
573 
574 ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
575 free_getarg_strings (getarg_strings *s)
576 {
577     free (s->strings);
578 }
579 
580 #if TEST
581 int foo_flag = 2;
582 int flag1 = 0;
583 int flag2 = 0;
584 int bar_int;
585 char *baz_string;
586 
587 struct getargs args[] = {
588     { NULL, '1', arg_flag, &flag1, "one", NULL },
589     { NULL, '2', arg_flag, &flag2, "two", NULL },
590     { "foo", 'f', arg_negative_flag, &foo_flag, "foo", NULL },
591     { "bar", 'b', arg_integer, &bar_int, "bar", "seconds"},
592     { "baz", 'x', arg_string, &baz_string, "baz", "name" },
593 };
594 
595 int main(int argc, char **argv)
596 {
597     int goptind = 0;
598     while(getarg(args, 5, argc, argv, &goptind))
599 	printf("Bad arg: %s\n", argv[goptind]);
600     printf("flag1 = %d\n", flag1);
601     printf("flag2 = %d\n", flag2);
602     printf("foo_flag = %d\n", foo_flag);
603     printf("bar_int = %d\n", bar_int);
604     printf("baz_flag = %s\n", baz_string);
605     arg_printusage (args, 5, argv[0], "nothing here");
606 }
607 #endif
608