Debian Codegraph @

src/util/simpleparse.c

raw symbols SCIP
1 /* simpleparse.c - Minimalistic parser
2 Copyright (C) 2008 g10 Code GmbH
3
4 This file is part of Poldi.
5
6 Poldi is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 Poldi is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, see
18 <http://www.gnu.org/licenses/>. */
19
20 #include <util-local.h>
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <stdarg.h>
27 #include <assert.h>
28 #include <limits.h>
29 #include <errno.h>
30
31 #include <gpg-error.h>
32
33 #include "simplelog.h"
34 #include "simpleparse.h"
35 #include "support.h"
36
37 struct simpleparse_handle
38 {
39 unsigned flags; /* General flags. */
40 simpleparse_parse_cb_t parse_cb; /* Parser callback. */
41 void *parse_cookie; /* Cookie for parser callback. */
42 simpleparse_i18n_cb_t i18n_cb; /* Callback for i18n. */
43 void *i18n_cookie; /* Cookie for i18n callback. */
44 log_handle_t loghandle;
45 const char *program_name; /* Name of the program. */
46 const char *package_name; /* Name of the package */
47 const char *version; /* Version of the program. */
48 const char *program_description; /* General description of the program. */
49 const char *bug_address; /* Address for bugreports. */
50 const char *syntax_description; /* Description of command-line syntax. */
51 const char *copyright_info; /* Copyright information. */
52 simpleparse_opt_spec_t *specs; /* Specifications for the supported options. */
53 FILE *stream_stdout;
54 FILE *stream_stderr;
55 };
56
57 /** String list. **/
58
59 #define TOKENSIZE 512
60
61 /* For now, we use static allocation... */
62 typedef char token_t[TOKENSIZE];
63
64 /* Install the logging handle LOGHANDLE in HANDLE. */
65 void
66 simpleparse_set_loghandle (simpleparse_handle_t handle,
67 log_handle_t loghandle)
68 {
69 assert (handle);
70 handle->loghandle = loghandle;
71 }
72
73 gpg_error_t
74 simpleparse_set_specs (simpleparse_handle_t handle, simpleparse_opt_spec_t *specs)
75 {
76 assert (specs);
77 handle->specs = specs;
78 /* FIXME, necessary to check for INT_MAX overflow? */
79 return 0;
80 }
81
82 /* This function looks up the specification structure for a long
83 option by it's name in the context of HANDLE. The name is given as
84 NAME. On success the struct is stored in *SPEC. Returns proper
85 error code. The only non-zero error code returned by this function
86 is GPG_ERR_UNKNOWN_OPTION in case the option requested could not be
87 found. */
88 static gpg_error_t
89 lookup_opt_spec_long (simpleparse_handle_t handle,
90 const char *name, simpleparse_opt_spec_t *spec)
91 {
92 gpg_error_t err = 0;
93 unsigned int i;
94
95 assert (name);
96
97 for (i = 0; handle->specs[i].long_opt; i++)
98 if (!strcmp (name, handle->specs[i].long_opt))
99 break;
100
101 if (handle->specs[i].long_opt)
102 *spec = handle->specs[i];
103 else
104 err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
105
106 return err;
107 }
108
109 /* This function looks up the specification structure for a long
110 option by it's short one-letter name in the context of HANDLE. The
111 name is given as NAME. On success the struct is stored in
112 *SPEC. Returns proper error code. The only non-zero error code
113 returned by this function is GPG_ERR_UNKNOWN_OPTION in case the
114 option requested could not be found. */
115 static gpg_error_t
116 lookup_opt_spec_short (simpleparse_handle_t handle,
117 const char name, simpleparse_opt_spec_t *spec)
118 {
119 gpg_error_t err = 0;
120 unsigned int i;
121
122 assert (name);
123
124 for (i = 0; handle->specs[i].long_opt; i++)
125 if (name == handle->specs[i].short_opt)
126 break;
127
128 if (handle->specs[i].long_opt)
129 *spec = handle->specs[i];
130 else
131 err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
132
133 return err;
134 }
135
136 static const char *
137 translate (simpleparse_handle_t handle, const char *msg)
138 {
139 if (handle->i18n_cb)
140 return (*handle->i18n_cb) (handle->i18n_cookie, msg);
141 else
142 return msg;
143 }
144
145 static void
146 display_bugreports (simpleparse_handle_t handle, unsigned int flags)
147 {
148 fprintf (handle->stream_stdout,
149 translate (handle, N_("Please report bugs to <%s>.\n")),
150 handle->bug_address);
151 }
152
153 static void
154 display_usage (simpleparse_handle_t handle, unsigned int flags)
155 {
156 if (handle->syntax_description)
157 fprintf (handle->stream_stdout, "%s\n", handle->syntax_description);
158 }
159
160 static void
161 display_version (simpleparse_handle_t handle, unsigned int flags)
162 {
163 fprintf (handle->stream_stdout, "%s ", handle->program_name);
164 if (handle->package_name)
165 fprintf (handle->stream_stdout, "(%s) ", handle->package_name);
166 fprintf (handle->stream_stdout, "%s\n", handle->version);
167
168 fprintf (handle->stream_stdout, "%s\n",
169 translate (handle, handle->copyright_info));
170 }
171
172 static void
173 display_help (simpleparse_handle_t handle, unsigned int flags)
174 {
175 simpleparse_opt_spec_t *specs = handle->specs;
176 FILE *out = handle->stream_stdout;
177 const char *s;
178 int i, j, indent;
179
180 assert (handle->stream_stdout);
181
182 display_version (handle, flags);
183 display_usage (handle, flags);
184
185 putc ('\n', handle->stream_stdout);
186
187 /* Get max. length of long options */
188 for(i = indent = 0; specs[i].short_opt; i++)
189 {
190 if (specs[i].long_opt)
191 if ((j = strlen (specs[i].long_opt)) > indent && j < 35)
192 indent = j;
193 }
194
195 /* example: " -v, --verbose Viele Sachen ausgeben" */
196 indent += 10;
197
198 for (i = 0; specs[i].id; i++)
199 {
200 if (specs[i].description)
201 s = translate (handle, specs[i].description);
202 else
203 s = NULL;
204
205 j = 3;
206 if (specs[i].short_opt)
207 fprintf (out, " -%c", specs[i].short_opt);
208 else
209 fputs (" ", out);
210
211 if (specs[i].long_opt)
212 {
213 j += fprintf (out,
214 "%c --%s", specs[i].short_opt ? ',' : ' ',
215 specs[i].long_opt);
216 fputs (" ", out);
217 j += 3;
218 }
219 for(; j < indent; j++)
220 putc (' ', out);
221
222 if (s)
223 {
224 if (*s && j > indent)
225 {
226 putc ('\n', out);
227 for(j = 0; j < indent; j++)
228 putc (' ', out);
229 }
230 for(; *s; s++)
231 putc (*s, out);
232 }
233
234 putc ('\n', out);
235 }
236 putc ('\n', out);
237
238 display_bugreports (handle, flags);
239 }
240
241
242 static gpg_error_t
243 internal_parse_args (simpleparse_handle_t handle, unsigned int flags,
244 unsigned int argc, const char **argv, const char ***rest_args)
245 {
246 simpleparse_opt_spec_t spec;
247 gpg_error_t err;
248 const char **arg;
249
250 assert (argv);
251 assert (rest_args);
252
253 arg = argv;
254 err = 0;
255
256 while (1)
257 {
258 if (!argc)
259 /* No more args. */
260 break;
261
262 if (!strcmp (*arg, "--"))
263 {
264 /* This marks the end of the switches. */
265 arg++;
266 argc--;
267 break;
268 }
269
270 /* Special switches. */
271 if (!strcmp (*arg, "--help"))
272 {
273 display_help (handle, flags);
274 arg++;
275 argc--;
276 break;
277 }
278
279 /* Special switches. */
280 if (!strcmp (*arg, "--version"))
281 {
282 display_version (handle, flags);
283 arg++;
284 argc--;
285 break;
286 }
287
288 if (!strcmp (*arg, "-"))
289 /* We consider this arg to be a non-switch. */
290 break;
291
292 if ((*arg)[0] != '-')
293 /* First non-switch argument. */
294 break;
295
296 /* Next arg is either long or short option. */
297 if ((*arg)[1] == '-')
298 /* Long option. */
299 err = lookup_opt_spec_long (handle, (*arg) + 2, &spec);
300 else
301 /* Short option. */
302 err = lookup_opt_spec_short (handle, *((*arg) + 1), &spec);
303
304 if (err)
305 {
306 /* Invalid option. */
307 log_msg_error (handle->loghandle,
308 translate (handle, N_("unknown option '%s'")), *arg);
309 break;
310 }
311
312 if (spec.arg == SIMPLEPARSE_ARG_OPTIONAL)
313 {
314 if (argc >= 2 && (*(arg+1)) && (*(arg+1))[0] != '-')
315 {
316 err = (*handle->parse_cb) (handle->parse_cookie, spec, *(arg + 1));
317 if (err)
318 {
319 log_msg_error (handle->loghandle,
320 translate (handle,
321 N_("parse-callback returned error '%s' for argument '%s'")),
322 gpg_strerror (err), spec.long_opt);
323 goto out;
324 }
325 arg += 2;
326 argc -= 2;
327 }
328 else
329 {
330 err = (*handle->parse_cb) (handle->parse_cookie, spec, NULL);
331 if (err)
332 {
333 log_msg_error (handle->loghandle,
334 translate (handle,
335 N_("parse-callback returned error '%s' for argument '%s'")),
336 gpg_strerror (err), spec.long_opt);
337 goto out;
338 }
339 arg++;
340 argc--;
341 }
342 }
343 else if (spec.arg == SIMPLEPARSE_ARG_REQUIRED)
344 {
345 if (argc >= 2 && (*(arg+1)) && (*(arg+1))[0] != '-')
346 {
347 err = (*handle->parse_cb) (handle->parse_cookie, spec, *(arg + 1));
348 if (err)
349 {
350 log_msg_error (handle->loghandle,
351 translate (handle,
352 N_("parse-callback returned error '%s' for argument '%s'")),
353 gpg_strerror (err), spec.long_opt);
354 goto out;
355 }
356 arg += 2;
357 argc -= 2;
358 }
359 else
360 {
361 /* Argument missing. */
362 err = gpg_error (GPG_ERR_MISSING_VALUE);
363 log_msg_error (handle->loghandle,
364 translate (handle,
365 N_("missing required argument for '%s'")),
366 spec.long_opt);
367 goto out;
368 }
369 }
370 else if (spec.arg == SIMPLEPARSE_ARG_NONE)
371 {
372 /* No arg allowed. */
373 err = (*handle->parse_cb) (handle->parse_cookie, spec, NULL);
374 if (err)
375 {
376 log_msg_error (handle->loghandle,
377 translate (handle,
378 N_("parse-callback returned error '%s' for argument '%s'")),
379 gpg_strerror (err), spec.long_opt);
380 goto out;
381 }
382 arg++;
383 argc--;
384 }
385 }
386
387 out:
388
389 if (err || (argc == 0))
390 *rest_args = NULL;
391 else
392 *rest_args = arg;
393
394 return err;
395 }
396
397 typedef struct
398 {
399 token_t *tokens;
400 unsigned int size;
401 } token_list_t;
402
403 static gpg_error_t
404 token_list_init (token_list_t *list)
405 {
406 list->tokens = NULL;
407 list->size = 0;
408
409 return 0;
410 }
411
412 static gpg_error_t
413 token_list_add (token_list_t *list, const char *item, int length)
414 {
415 gpg_error_t err = 0;
416 int item_length;
417 token_t *tokens = NULL;
418
419 if (!item)
420 goto out;
421
422 if (list->size == UINT_MAX)
423 {
424 err = gpg_error (GPG_ERR_TOO_LARGE);
425 goto out;
426 }
427
428 if (length == -1)
429 {
430 item_length = my_strlen (item);
431 if (item_length)
432 {
433 err = gpg_error (GPG_ERR_TOO_LARGE);
434 goto out;
435 }
436 }
437 else
438 item_length = length;
439
440 if (item_length >= TOKENSIZE)
441 {
442 err = gpg_error (GPG_ERR_TOO_LARGE);
443 goto out;
444 }
445
446 tokens = xtryrealloc (list->tokens, sizeof (*list->tokens) * (list->size + 1));
447 if (!tokens)
448 {
449 err = gpg_error_from_errno (errno);
450 goto out;
451 }
452
453 list->tokens = tokens;
454 assert (item_length < TOKENSIZE);
455 memcpy (list->tokens[list->size], item, item_length);
456 list->tokens[list->size][item_length] = 0;
457 list->size++;
458
459 out:
460
461 return err;
462 }
463
464 static gpg_error_t
465 token_list_clear (token_list_t *list)
466 {
467 if (list->tokens)
468 xfree (list->tokens);
469 list->tokens = NULL;
470 list->size = 0;
471 return 0;
472 }
473
474 static gpg_error_t
475 internal_parse_line (char *line, token_list_t *tokens)
476 {
477 token_list_t token_list;
478 gpg_error_t err;
479 char *p;
480
481 err = token_list_init (&token_list);
482 if (err)
483 goto out;
484
485 /* Start. */
486 p = line;
487
488 /* Special case for comments and empty lines. */
489 while (isspace (*p))
490 p++;
491 if ((*p == '#') || (*p == '\n') || (*p == '\0'))
492 goto out;
493
494 /* This loops over the tokens contained in the line. */
495 while (1)
496 {
497 int quoting_char = 0;
498 unsigned int i = 0;
499
500 /* Skip whitespaces before tokens. */
501 while ((*p == ' ') || (*p == '\t'))
502 p++;
503
504 if (*p == '\0')
505 /* This was an empty line. */
506 break;
507
508 /* There seems to be another token. */
509
510 if ((*p == '"') || (*p == '\''))
511 {
512 /* The token is quoted; remember quoting character. */
513 quoting_char = *p;
514 p++;
515 }
516
517 /* The new token starts at P and is at least one byte long. If
518 quoting_char is positive, the current token is quoted. */
519 i = 1;
520
521 while (1)
522 {
523 if (!p[i])
524 {
525 if (quoting_char)
526 {
527 /* Quoting not properly terminated. */
528 err = gpg_error (GPG_ERR_SYNTAX);
529 goto out;
530 }
531 else
532 break;
533 }
534 else if ((p[i] == ' ') || (p[i] == '\t'))
535 {
536 /* Whitespace! */
537 if (!quoting_char)
538 /* Not inside of a quoted token, therefore this is a
539 token delimiter. */
540 break;
541 }
542
543 else if (p[i] == '\\')
544 {
545 abort ();
546 /* We do not allow escape characters yet. */
547 }
548 else if (p[i] == quoting_char)
549 {
550 /* Terminating quote characters, ends current token. */
551 i++;
552 break;
553 }
554
555 /* Move forward in current token. */
556 i++;
557 }
558
559 /* Now we have a new token in {p[0], p[1], ..., p[i-1]}; i is
560 positive. In case of quoted tokens, we must subtract one
561 byte, since the trailing quote character is not part of the
562 token. */
563
564 err = token_list_add (&token_list, p, i - !!quoting_char);
565 if (err)
566 goto out;
567
568 p += i;
569 }
570
571 out:
572
573 if (err)
574 {
575 token_list_clear (&token_list);
576 }
577 else
578 *tokens = token_list;
579
580 return err;
581 }
582
583 static gpg_error_t
584 internal_process_tokens (simpleparse_handle_t handle, token_list_t tokens)
585 {
586 simpleparse_opt_spec_t spec;
587 gpg_error_t err;
588
589 err = 0;
590
591 assert (1 <= tokens.size);
592
593 err = lookup_opt_spec_long (handle, tokens.tokens[0], &spec);
594 if (err)
595 {
596 log_msg_error (handle->loghandle,
597 translate (handle, N_("unknown option '%s'")), tokens.tokens[0]);
598 goto out;
599 }
600
601 switch (spec.arg)
602 {
603 case SIMPLEPARSE_ARG_NONE:
604 if (tokens.size > 1)
605 {
606 log_msg_error (handle->loghandle,
607 translate (handle,
608 N_("too many arguments specified for option '%s'")),
609 tokens.tokens[0]);
610 err = gpg_error (GPG_ERR_SYNTAX);
611 goto out;
612 }
613 break;
614 case SIMPLEPARSE_ARG_REQUIRED:
615 if (tokens.size < 2)
616 {
617 log_msg_error (handle->loghandle,
618 translate (handle,
619 N_("missing required argument for '%s'")),
620 tokens.tokens[0]);
621 err = gpg_error (GPG_ERR_SYNTAX);
622 goto out;
623 }
624 else if (tokens.size > 2)
625 {
626 log_msg_error (handle->loghandle,
627 translate (handle,
628 N_("too many arguments specified for option '%s'")),
629 tokens.tokens[0]);
630 err = gpg_error (GPG_ERR_SYNTAX);
631 goto out;
632 }
633 break;
634
635 case SIMPLEPARSE_ARG_OPTIONAL:
636 break;
637 }
638
639 err = (*handle->parse_cb) (handle->parse_cookie, spec,
640 (tokens.size == 2) ? tokens.tokens[1] : NULL);
641
642 out:
643
644 return err;
645 }
646
647 /* Replaces the first occurence of a newline character in the string S
648 with a NUL character. */
649 static void
650 cut_trailing_newline (char *s)
651 {
652 char *nl = strchr (s, '\n');
653 if (nl)
654 *nl = '\0';
655 }
656
657 /* Parse the stream STREAM using the state contained in HANDLE. FLAGS
658 is not used yet. Returns proper error code. */
659 static gpg_error_t
660 internal_parse_stream (simpleparse_handle_t handle, unsigned int flags, FILE *stream)
661 {
662 size_t line_size;
663 char *line;
664 int length;
665 token_list_t tokens;
666 gpg_error_t err;
667 int ret;
668
669 tokens.tokens = NULL;
670 tokens.size = 0;
671 err = 0;
672
673 while (1)
674 {
675 line = NULL;
676 line_size = 0;
677
678 ret = getline (&line, &line_size, stream);
679 if (ret == -1)
680 {
681 if (!feof (stream))
682 err = gpg_error_from_errno (errno);
683 goto out;
684 }
685
686 /* We simply ignore NUL characters in line. */
687 length = my_strlen (line);
688 if (length == -1)
689 {
690 err = GPG_ERR_TOO_LARGE;
691 goto out;
692 }
693
694 /* Ignore terminating newline character. */
695 cut_trailing_newline (line);
696
697 /* Split line into tokens. */
698
699 err = internal_parse_line (line, &tokens);
700 if (err)
701 goto out;
702
703 /* Process. */
704 if (tokens.size > 0)
705 {
706 err = internal_process_tokens (handle, tokens);
707 if (err)
708 goto out;
709 }
710
711 /* Release. */
712
713 token_list_clear (&tokens);
714 free (line);
715 line = NULL;
716 }
717
718 out:
719
720 if (line)
721 free (line); /* Allocated by getline, thus standard
722 free. */
723 return err;
724 }
725
726 /* Parse the stream STREAM using the state contained in HANDLE. FLAGS
727 is not used yet. Returns proper error code. */
728 gpg_error_t
729 simpleparse_parse_stream (simpleparse_handle_t handle, unsigned int flags,
730 FILE *stream)
731 {
732 return internal_parse_stream (handle, flags, stream);
733 }
734
735 /* Parse the file FILENAME using the state contained in HANDLE. FLAGS
736 is not used yet. Returns proper error code. */
737 gpg_error_t
738 simpleparse_parse_file (simpleparse_handle_t handle, unsigned int flags,
739 const char *filename)
740 {
741 gpg_error_t err;
742 FILE *fp;
743
744 fp = fopen (filename, "r");
745 if (!fp)
746 {
747 err = gpg_error_from_errno (errno);
748 goto out;
749 }
750
751 err = internal_parse_stream (handle, flags, fp);
752
753 out:
754
755 if (fp)
756 fclose (fp);
757
758 return err;
759 }
760
761 /* Parse the argument vector ARGC/ARGV using the state contained in
762 HANDLE. On successful parsing, a pointer to the rest arguments is
763 stored in *REST_ARGS. FLAGS is not used. Returns proper error
764 code. */
765 gpg_error_t
766 simpleparse_parse (simpleparse_handle_t handle, unsigned int flags,
767 unsigned int argc, const char **argv, const char ***rest_args)
768 {
769 gpg_error_t err;
770 const char **rest;
771
772 err = internal_parse_args (handle, flags, argc, argv, &rest);
773 if (err)
774 goto out;
775
776 if (rest && (! rest_args))
777 {
778 /* Caller does not expect rest arguments, but there are some. */
779 err = gpg_error (GPG_ERR_UNEXPECTED);
780 goto out;
781 }
782
783 if (rest_args)
784 *rest_args = rest;
785
786 out:
787
788 return err;
789 }
790
791 static struct simpleparse_handle simpleparse_handle_init;
792
793 /* Create a new, plain handle and store it in *HANDLE. Returns proper
794 error code. */
795 gpg_error_t
796 simpleparse_create (simpleparse_handle_t *handle)
797 {
798 gpg_error_t err = 0;
799
800 *handle = xtrymalloc (sizeof (**handle));
801 if (!*handle)
802 {
803 err = gpg_error_from_errno (errno);
804 goto out;
805 }
806
807 **handle = simpleparse_handle_init;
808
809 out:
810
811 return err;
812 }
813
814 static void
815 internal_release_handle (simpleparse_handle_t handle)
816 {
817 assert (handle);
818 xfree (handle);
819 }
820
821 /* Destroy the handle HANDLE. */
822 void
823 simpleparse_destroy (simpleparse_handle_t handle)
824 {
825 if (handle)
826 internal_release_handle (handle);
827 }
828
829 /* Install the parser callback and it's cookie in HANDLE. */
830 void
831 simpleparse_set_parse_cb (simpleparse_handle_t handle,
832 simpleparse_parse_cb_t parse_cb, void *cookie)
833 {
834 assert (handle);
835
836 handle->parse_cb = parse_cb;
837 handle->parse_cookie = cookie;
838 }
839
840 void
841 simpleparse_set_i18n_cb (simpleparse_handle_t handle,
842 simpleparse_i18n_cb_t i18n_cb, void *cookie)
843 {
844 assert (handle);
845
846 handle->i18n_cb = i18n_cb;
847 handle->i18n_cookie = cookie;
848 }
849
850 void
851 simpleparse_set_name (simpleparse_handle_t handle, const char *program_name)
852 {
853 handle->program_name = program_name;
854 }
855
856 void
857 simpleparse_set_package (simpleparse_handle_t handle, const char *package_name)
858 {
859 handle->package_name = package_name;
860 }
861
862 void
863 simpleparse_set_copyright (simpleparse_handle_t handle, const char *copyright_info)
864 {
865 handle->copyright_info = copyright_info;
866 }
867
868 void
869 simpleparse_set_version (simpleparse_handle_t handle, const char *program_version)
870 {
871 handle->version = program_version;
872 }
873
874 void
875 simpleparse_set_bugaddress (simpleparse_handle_t handle, const char *bug_address)
876 {
877 handle->bug_address = bug_address;
878 }
879
880 void
881 simpleparse_set_author (simpleparse_handle_t handle, const char *author)
882 {
883 /* FIXME */
884 }
885
886 void
887 simpleparse_set_license (simpleparse_handle_t handle, const char *license)
888 {
889 /* FIXME */
890 }
891
892 void
893 simpleparse_set_description (simpleparse_handle_t handle, const char *program_description)
894 {
895 handle->program_description = program_description;
896 }
897
898 void
899 simpleparse_set_syntax (simpleparse_handle_t handle, const char *syntax_description)
900 {
901 handle->syntax_description = syntax_description;
902 }
903
904 void
905 simpleparse_set_streams (simpleparse_handle_t handle, FILE *stream_stdout, FILE *stream_stderr)
906 {
907 handle->stream_stdout = stream_stdout;
908 handle->stream_stderr = stream_stderr;
909 }
910
911 /* END*/