Import Upstream version 1.8.5
[hcoop/debian/openafs.git] / src / cmd / cmd.c
1 /*
2 * Copyright 2000, International Business Machines Corporation and others.
3 * All Rights Reserved.
4 *
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
8 */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 #include <roken.h>
14
15 #include <ctype.h>
16 #include <assert.h>
17
18 #include "cmd.h"
19
20 /* declaration of private token type */
21 struct cmd_token {
22 struct cmd_token *next;
23 char *key;
24 };
25
26 static struct cmd_item dummy; /* non-null ptr used for flag existence */
27 static struct cmd_syndesc *allSyntax = 0;
28 static int noOpcodes = 0;
29 static int (*beforeProc) (struct cmd_syndesc * ts, void *beforeRock) = NULL;
30 static int (*afterProc) (struct cmd_syndesc * ts, void *afterRock) = NULL;
31 static int enablePositional = 1;
32 static int enableAbbreviation = 1;
33 static void *beforeRock, *afterRock;
34 static char initcmd_opcode[] = "initcmd"; /*Name of initcmd opcode */
35 static cmd_config_section *globalConfig = NULL;
36 static const char *commandName = NULL;
37
38 /* take name and string, and return null string if name is empty, otherwise return
39 the concatenation of the two strings */
40 static char *
41 NName(char *a1, char *a2)
42 {
43 static char tbuffer[300];
44 if (strlen(a1) == 0) {
45 return "";
46 } else {
47 strlcpy(tbuffer, a1, sizeof(tbuffer));
48 strlcat(tbuffer, a2, sizeof(tbuffer));
49 return tbuffer;
50 }
51 }
52
53 /* return true if asub is a substring of amain */
54 static int
55 SubString(char *amain, char *asub)
56 {
57 int mlen, slen;
58 int i, j;
59 mlen = (int) strlen(amain);
60 slen = (int) strlen(asub);
61 j = mlen - slen;
62 if (j < 0)
63 return 0; /* not a substring */
64 for (i = 0; i <= j; i++) {
65 if (strncmp(amain, asub, slen) == 0)
66 return 1;
67 amain++;
68 }
69 return 0; /* didn't find it */
70 }
71
72 static int
73 FindType(struct cmd_syndesc *as, char *aname)
74 {
75 int i;
76 size_t cmdlen;
77 int ambig;
78 int best;
79 struct cmd_item *alias;
80
81 /* Allow --long-style options. */
82 if (aname[0] == '-' && aname[1] == '-' && aname[2] && aname[3]) {
83 aname++;
84 }
85
86 cmdlen = strlen(aname);
87 ambig = 0;
88 best = -1;
89 for (i = 0; i < CMD_MAXPARMS; i++) {
90 if (as->parms[i].type == 0)
91 continue; /* this slot not set (seeked over) */
92 if (strcmp(as->parms[i].name, aname) == 0)
93 return i;
94 if (strlen(as->parms[i].name) < cmdlen)
95 continue;
96
97 /* Check for aliases, which must be full matches */
98 alias = as->parms[i].aliases;
99 while (alias != NULL) {
100 if (strcmp(alias->data, aname) == 0)
101 return i;
102 alias = alias->next;
103 }
104
105 /* A hidden option, or one which cannot be abbreviated,
106 * must be a full match (no best matches) */
107 if (as->parms[i].flags & CMD_HIDE ||
108 as->parms[i].flags & CMD_NOABBRV ||
109 !enableAbbreviation)
110 continue;
111
112 if (strncmp(as->parms[i].name, aname, cmdlen) == 0) {
113 if (best != -1)
114 ambig = 1;
115 else
116 best = i;
117 }
118 }
119 return (ambig ? -1 : best);
120 }
121
122 static struct cmd_syndesc *
123 FindSyntax(char *aname, int *aambig)
124 {
125 struct cmd_syndesc *ts;
126 struct cmd_syndesc *best;
127 size_t cmdLen;
128 int ambig;
129
130 cmdLen = strlen(aname);
131 best = (struct cmd_syndesc *)0;
132 ambig = 0;
133 if (aambig)
134 *aambig = 0; /* initialize to unambiguous */
135 for (ts = allSyntax; ts; ts = ts->next) {
136 if (strcmp(aname, ts->name) == 0)
137 return (ts);
138 if (strlen(ts->name) < cmdLen)
139 continue; /* we typed more than item has */
140 /* A hidden command must be a full match (no best matches) */
141 if (ts->flags & CMD_HIDDEN)
142 continue;
143
144 /* This is just an alias for *best, or *best is just an alias for us.
145 * If we don't make this check explicitly, then an alias which is just a
146 * short prefix of the real command's name might make things ambiguous
147 * for no apparent reason.
148 */
149 if (best && ts->aliasOf == best->aliasOf)
150 continue;
151 if (strncmp(ts->name, aname, cmdLen) == 0) {
152 if (best)
153 ambig = 1; /* ambiguous name */
154 else
155 best = ts;
156 }
157 }
158 if (ambig) {
159 if (aambig)
160 *aambig = ambig; /* if ambiguous and they care, tell them */
161 return (struct cmd_syndesc *)0; /* fails */
162 } else
163 return best; /* otherwise its not ambiguous, and they know */
164 }
165
166 /* print the help for a single parameter */
167 static char *
168 ParmHelpString(struct cmd_parmdesc *aparm)
169 {
170 char *str;
171 if (aparm->type == CMD_FLAG) {
172 return strdup("");
173 } else {
174 if (asprintf(&str, " %s<%s>%s%s",
175 aparm->type == CMD_SINGLE_OR_FLAG?"[":"",
176 aparm->help?aparm->help:"arg",
177 aparm->type == CMD_LIST?"+":"",
178 aparm->type == CMD_SINGLE_OR_FLAG?"]":"") < 0)
179 return "<< OUT OF MEMORY >>";
180 return str;
181 }
182 }
183
184 extern char *AFSVersion;
185
186 static int
187 VersionProc(struct cmd_syndesc *as, void *arock)
188 {
189 printf("%s\n", AFSVersion);
190 return 0;
191 }
192
193 void
194 PrintSyntax(struct cmd_syndesc *as)
195 {
196 int i;
197 struct cmd_parmdesc *tp;
198 char *str;
199 char *name;
200 size_t len;
201 size_t xtralen;
202
203 /* now print usage, from syntax table */
204 if (noOpcodes)
205 len = printf("Usage: %s", as->a0name);
206 else {
207 if (!strcmp(as->name, initcmd_opcode))
208 len = printf("Usage: %s[%s]", NName(as->a0name, " "), as->name);
209 else
210 len = printf("Usage: %s%s", NName(as->a0name, " "), as->name);
211 }
212
213 for (i = 0; i < CMD_MAXPARMS; i++) {
214 tp = &as->parms[i];
215 if (tp->type == 0)
216 continue; /* seeked over slot */
217 if (tp->flags & CMD_HIDE)
218 continue; /* skip hidden options */
219
220 /* The parameter name is the real name, plus any aliases */
221 if (!tp->aliases) {
222 name = strdup(tp->name);
223 } else {
224 size_t namelen;
225 struct cmd_item *alias;
226 namelen = strlen(tp->name) + 1;
227 for (alias = tp->aliases; alias != NULL; alias = alias->next)
228 namelen+=strlen(alias->data) + 3;
229
230 name = malloc(namelen);
231 strlcpy(name, tp->name, namelen);
232
233 for (alias = tp->aliases; alias != NULL; alias = alias->next) {
234 strlcat(name, " | ", namelen);
235 strlcat(name, alias->data, namelen);
236 }
237 }
238
239 /* Work out if we can fit what we want to on this line, or if we need to
240 * start a new one */
241 str = ParmHelpString(tp);
242 xtralen = 1 + strlen(name) + strlen(str) +
243 ((tp->flags & CMD_OPTIONAL)? 2: 0);
244
245 if (len + xtralen > 78) {
246 printf("\n ");
247 len = 8;
248 }
249
250 printf(" %s%s%s%s",
251 tp->flags & CMD_OPTIONAL?"[":"",
252 name,
253 str,
254 tp->flags & CMD_OPTIONAL?"]":"");
255 free(str);
256 free(name);
257 len+=xtralen;
258 }
259 printf("\n");
260 }
261
262 /* must print newline in any case, to terminate preceding line */
263 static void
264 PrintAliases(struct cmd_syndesc *as)
265 {
266 struct cmd_syndesc *ts;
267
268 if (as->flags & CMD_ALIAS) {
269 ts = as->aliasOf;
270 printf("(alias for %s)\n", ts->name);
271 } else {
272 printf("\n");
273 if (!as->nextAlias)
274 return; /* none, print nothing */
275 printf("aliases: ");
276 for (as = as->nextAlias; as; as = as->nextAlias) {
277 printf("%s ", as->name);
278 }
279 printf("\n");
280 }
281 }
282
283 void
284 PrintFlagHelp(struct cmd_syndesc *as)
285 {
286 int i;
287 struct cmd_parmdesc *tp;
288 int flag_width;
289 char *flag_prefix;
290
291 /* find flag name length */
292 flag_width = 0;
293 for (i = 0; i < CMD_MAXPARMS; i++) {
294 if (i == CMD_HELPPARM)
295 continue;
296 tp = &as->parms[i];
297 if (tp->type != CMD_FLAG)
298 continue;
299 if (tp->flags & CMD_HIDE)
300 continue; /* skip hidden options */
301 if (!tp->help)
302 continue;
303
304 if (strlen(tp->name) > flag_width)
305 flag_width = strlen(tp->name);
306 }
307
308 /* print flag help */
309 flag_prefix = "Where:";
310 for (i = 0; i < CMD_MAXPARMS; i++) {
311 if (i == CMD_HELPPARM)
312 continue;
313 tp = &as->parms[i];
314 if (tp->type != CMD_FLAG)
315 continue;
316 if (tp->flags & CMD_HIDE)
317 continue; /* skip hidden options */
318 if (!tp->help)
319 continue;
320
321 printf("%-7s%-*s %s\n", flag_prefix, flag_width, tp->name, tp->help);
322 flag_prefix = "";
323 }
324 }
325
326 static int
327 AproposProc(struct cmd_syndesc *as, void *arock)
328 {
329 struct cmd_syndesc *ts;
330 char *tsub;
331 int didAny;
332
333 didAny = 0;
334 tsub = as->parms[0].items->data;
335 for (ts = allSyntax; ts; ts = ts->next) {
336 if ((ts->flags & CMD_ALIAS) || (ts->flags & CMD_HIDDEN))
337 continue;
338 if (SubString(ts->help, tsub)) {
339 printf("%s: %s\n", ts->name, ts->help);
340 didAny = 1;
341 } else if (SubString(ts->name, tsub)) {
342 printf("%s: %s\n", ts->name, ts->help);
343 didAny = 1;
344 }
345 }
346 if (!didAny)
347 printf("Sorry, no commands found\n");
348 return 0;
349 }
350
351 static int
352 HelpProc(struct cmd_syndesc *as, void *arock)
353 {
354 struct cmd_syndesc *ts;
355 struct cmd_item *ti;
356 int ambig;
357 int code = 0;
358
359 if (as->parms[0].items == 0) {
360 printf("%sCommands are:\n", NName(as->a0name, ": "));
361 for (ts = allSyntax; ts; ts = ts->next) {
362 if ((ts->flags & CMD_ALIAS) || (ts->flags & CMD_HIDDEN))
363 continue;
364 printf("%-15s %s\n", ts->name, (ts->help ? ts->help : ""));
365 }
366 } else {
367 /* print out individual help topics */
368 for (ti = as->parms[0].items; ti; ti = ti->next) {
369 code = 0;
370 ts = FindSyntax(ti->data, &ambig);
371 if (ts && (ts->flags & CMD_HIDDEN))
372 ts = 0; /* no hidden commands */
373 if (ts) {
374 /* print out command name and help */
375 printf("%s%s: %s ", NName(as->a0name, " "), ts->name,
376 (ts->help ? ts->help : ""));
377 ts->a0name = as->a0name;
378 PrintAliases(ts);
379 PrintSyntax(ts);
380 PrintFlagHelp(ts);
381 } else {
382 if (!ambig)
383 fprintf(stderr, "%sUnknown topic '%s'\n",
384 NName(as->a0name, ": "), ti->data);
385 else {
386 /* ambiguous, list 'em all */
387 fprintf(stderr,
388 "%sAmbiguous topic '%s'; use 'apropos' to list\n",
389 NName(as->a0name, ": "), ti->data);
390 }
391 code = CMD_UNKNOWNCMD;
392 }
393 }
394 }
395 return (code);
396 }
397
398 int
399 cmd_SetBeforeProc(int (*aproc) (struct cmd_syndesc * ts, void *beforeRock),
400 void *arock)
401 {
402 beforeProc = aproc;
403 beforeRock = arock;
404 return 0;
405 }
406
407 int
408 cmd_SetAfterProc(int (*aproc) (struct cmd_syndesc * ts, void *afterRock),
409 void *arock)
410 {
411 afterProc = aproc;
412 afterRock = arock;
413 return 0;
414 }
415
416 /* thread on list in alphabetical order */
417 static int
418 SortSyntax(struct cmd_syndesc *as)
419 {
420 struct cmd_syndesc **ld, *ud;
421
422 for (ld = &allSyntax, ud = *ld; ud; ld = &ud->next, ud = *ld) {
423 if (strcmp(ud->name, as->name) > 0) { /* next guy is bigger than us */
424 break;
425 }
426 }
427 /* thread us on the list now */
428 *ld = as;
429 as->next = ud;
430 return 0;
431 }
432
433 /*!
434 * Create a command syntax.
435 *
436 * \note Use cmd_AddParm() or cmd_AddParmAtOffset() to set the
437 * parameters for the new command.
438 *
439 * \param[in] aname name used to invoke the command
440 * \param[in] aproc procedure to be called when command is invoked
441 * \param[in] arock opaque data pointer to be passed to aproc
442 * \param[in] aflags command option flags (CMD_HIDDEN)
443 * \param[in] ahelp help string to display for this command
444 *
445 * \return a pointer to the cmd_syndesc or NULL if error.
446 */
447 struct cmd_syndesc *
448 cmd_CreateSyntax(char *aname,
449 int (*aproc) (struct cmd_syndesc * ts, void *arock),
450 void *arock, afs_uint32 aflags, char *ahelp)
451 {
452 struct cmd_syndesc *td;
453
454 /* can't have two cmds in no opcode mode */
455 if (noOpcodes)
456 return NULL;
457
458 /* Allow only valid cmd flags. */
459 if (aflags & ~CMD_HIDDEN) {
460 return NULL;
461 }
462
463 td = calloc(1, sizeof(struct cmd_syndesc));
464 assert(td);
465 td->aliasOf = td; /* treat aliasOf as pointer to real command, no matter what */
466 td->flags = aflags;
467
468 /* copy in name, etc */
469 if (aname) {
470 td->name = strdup(aname);
471 assert(td->name);
472 } else {
473 td->name = NULL;
474 noOpcodes = 1;
475 }
476 if (ahelp) {
477 td->help = strdup(ahelp);
478 assert(td->help);
479 } else
480 td->help = NULL;
481 td->proc = aproc;
482 td->rock = arock;
483
484 SortSyntax(td);
485
486 cmd_Seek(td, CMD_HELPPARM);
487 cmd_AddParm(td, "-help", CMD_FLAG, CMD_OPTIONAL, "get detailed help");
488 cmd_Seek(td, 0);
489
490 return td;
491 }
492
493 int
494 cmd_CreateAlias(struct cmd_syndesc *as, char *aname)
495 {
496 struct cmd_syndesc *td;
497
498 td = malloc(sizeof(struct cmd_syndesc));
499 assert(td);
500 memcpy(td, as, sizeof(struct cmd_syndesc));
501 td->name = strdup(aname);
502 assert(td->name);
503 td->flags |= CMD_ALIAS;
504 /* if ever free things, make copy of help string, too */
505
506 /* thread on list */
507 SortSyntax(td);
508
509 /* thread on alias lists */
510 td->nextAlias = as->nextAlias;
511 as->nextAlias = td;
512 td->aliasOf = as;
513
514 return 0; /* all done */
515 }
516
517 void
518 cmd_DisablePositionalCommands(void)
519 {
520 enablePositional = 0;
521 }
522
523 void
524 cmd_DisableAbbreviations(void)
525 {
526 enableAbbreviation = 0;
527 }
528
529 int
530 cmd_Seek(struct cmd_syndesc *as, int apos)
531 {
532 if (apos >= CMD_MAXPARMS)
533 return CMD_EXCESSPARMS;
534 as->nParms = apos;
535 return 0;
536 }
537
538 int
539 cmd_AddParmAtOffset(struct cmd_syndesc *as, int ref, char *aname, int atype,
540 afs_int32 aflags, char *ahelp)
541 {
542 struct cmd_parmdesc *tp;
543
544 if (ref >= CMD_MAXPARMS)
545 return CMD_EXCESSPARMS;
546 tp = &as->parms[ref];
547
548 tp->name = strdup(aname);
549 assert(tp->name);
550 tp->type = atype;
551 tp->flags = aflags;
552 tp->items = NULL;
553 if (ahelp) {
554 tp->help = strdup(ahelp);
555 assert(tp->help);
556 } else
557 tp->help = NULL;
558
559 tp->aliases = NULL;
560
561 if (as->nParms <= ref)
562 as->nParms = ref+1;
563
564 return 0;
565 }
566
567 int
568 cmd_AddParm(struct cmd_syndesc *as, char *aname, int atype,
569 afs_int32 aflags, char *ahelp)
570 {
571 if (as->nParms >= CMD_MAXPARMS)
572 return CMD_EXCESSPARMS;
573
574 return cmd_AddParmAtOffset(as, as->nParms++, aname, atype, aflags, ahelp);
575 }
576
577 int
578 cmd_AddParmAlias(struct cmd_syndesc *as, int pos, char *alias)
579 {
580 struct cmd_item *item;
581
582 if (pos > as->nParms)
583 return CMD_EXCESSPARMS;
584
585 item = calloc(1, sizeof(struct cmd_item));
586 item->data = strdup(alias);
587 item->next = as->parms[pos].aliases;
588 as->parms[pos].aliases = item;
589
590 return 0;
591 }
592
593 /* add a text item to the end of the parameter list */
594 static int
595 AddItem(struct cmd_parmdesc *aparm, char *aval, char *pname)
596 {
597 struct cmd_item *ti, *ni;
598
599 if (aparm->type == CMD_SINGLE ||
600 aparm->type == CMD_SINGLE_OR_FLAG) {
601 if (aparm->items) {
602 fprintf(stderr, "%sToo many values after switch %s\n",
603 NName(pname, ": "), aparm->name);
604 return CMD_NOTLIST;
605 }
606 }
607
608 ti = calloc(1, sizeof(struct cmd_item));
609 assert(ti);
610 ti->data = strdup(aval);
611 assert(ti->data);
612 /* now put ti at the *end* of the list */
613 if ((ni = aparm->items)) {
614 for (; ni; ni = ni->next)
615 if (ni->next == 0)
616 break; /* skip to last one */
617 ni->next = ti;
618 } else
619 aparm->items = ti; /* we're first */
620 return 0;
621 }
622
623 /* skip to next non-flag item, if any */
624 static int
625 AdvanceType(struct cmd_syndesc *as, afs_int32 aval)
626 {
627 afs_int32 next;
628 struct cmd_parmdesc *tp;
629
630 /* first see if we should try to grab rest of line for this dude */
631 if (as->parms[aval].flags & CMD_EXPANDS)
632 return aval;
633
634 /* if not, find next non-flag used slot */
635 for (next = aval + 1; next < CMD_MAXPARMS; next++) {
636 tp = &as->parms[next];
637 if (tp->type != 0 && tp->type != CMD_FLAG)
638 return next;
639 }
640 return aval;
641 }
642
643 /* discard parameters filled in by dispatch */
644 static void
645 ResetSyntax(struct cmd_syndesc *as)
646 {
647 int i;
648 struct cmd_parmdesc *tp;
649 struct cmd_item *ti, *ni;
650
651 tp = as->parms;
652 for (i = 0; i < CMD_MAXPARMS; i++, tp++) {
653 switch (tp->type) {
654 case CMD_SINGLE_OR_FLAG:
655 if (tp->items == &dummy)
656 break;
657 /* Deliberately fall through here */
658 case CMD_SINGLE:
659 case CMD_LIST:
660 /* free whole list in both cases, just for fun */
661 for (ti = tp->items; ti; ti = ni) {
662 ni = ti->next;
663 free(ti->data);
664 free(ti);
665 }
666 break;
667
668 default:
669 break;
670 }
671 tp->items = NULL;
672 }
673 }
674
675 /* move the expands flag to the last one in the list */
676 static int
677 SetupExpandsFlag(struct cmd_syndesc *as)
678 {
679 struct cmd_parmdesc *tp;
680 int last, i;
681
682 last = -1;
683 /* find last CMD_LIST type parameter, optional or not, and make it expandable
684 * if no other dude is expandable */
685 for (i = 0; i < CMD_MAXPARMS; i++) {
686 tp = &as->parms[i];
687 if (tp->type == CMD_LIST) {
688 if (tp->flags & CMD_EXPANDS)
689 return 0; /* done if already specified */
690 last = i;
691 }
692 }
693 if (last >= 0)
694 as->parms[last].flags |= CMD_EXPANDS;
695 return 0;
696 }
697
698 /* Take the current argv & argc and alter them so that the initialization
699 * opcode is made to appear. This is used in cases where the initialization
700 * opcode is implicitly invoked.*/
701 static char **
702 InsertInitOpcode(int *aargc, char **aargv)
703 {
704 char **newargv; /*Ptr to new, expanded argv space */
705 char *pinitopcode; /*Ptr to space for name of init opcode */
706 int i; /*Loop counter */
707
708 /* Allocate the new argv array, plus one for the new opcode, plus one
709 * more for the trailing null pointer */
710 newargv = malloc(((*aargc) + 2) * sizeof(char *));
711 if (!newargv) {
712 fprintf(stderr, "%s: Can't create new argv array with %d+2 slots\n",
713 aargv[0], *aargc);
714 return (NULL);
715 }
716
717 /* Create space for the initial opcode & fill it in */
718 pinitopcode = strdup(initcmd_opcode);
719 if (!pinitopcode) {
720 fprintf(stderr, "%s: Can't malloc initial opcode space\n", aargv[0]);
721 free(newargv);
722 return (NULL);
723 }
724
725 /* Move all the items in the old argv into the new argv, in their
726 * proper places */
727 for (i = *aargc; i > 1; i--)
728 newargv[i] = aargv[i - 1];
729
730 /* Slip in the opcode and the trailing null pointer, and bump the
731 * argument count up by one for the new opcode */
732 newargv[0] = aargv[0];
733 newargv[1] = pinitopcode;
734 (*aargc)++;
735 newargv[*aargc] = NULL;
736
737 /* Return the happy news */
738 return (newargv);
739
740 } /*InsertInitOpcode */
741
742 static int
743 NoParmsOK(struct cmd_syndesc *as)
744 {
745 int i;
746 struct cmd_parmdesc *td;
747
748 for (i = 0; i < CMD_MAXPARMS; i++) {
749 td = &as->parms[i];
750 if (td->type != 0 && !(td->flags & CMD_OPTIONAL)) {
751 /* found a non-optional (e.g. required) parm, so NoParmsOK
752 * is false (some parms are required) */
753 return 0;
754 }
755 }
756 return 1;
757 }
758
759 /* Add help, apropos commands once */
760 static void
761 initSyntax(void)
762 {
763 struct cmd_syndesc *ts;
764
765 if (!noOpcodes) {
766 ts = cmd_CreateSyntax("help", HelpProc, NULL, 0,
767 "get help on commands");
768 cmd_AddParm(ts, "-topic", CMD_LIST, CMD_OPTIONAL, "help string");
769
770 ts = cmd_CreateSyntax("apropos", AproposProc, NULL, 0,
771 "search by help text");
772 cmd_AddParm(ts, "-topic", CMD_SINGLE, CMD_REQUIRED, "help string");
773
774 cmd_CreateSyntax("version", VersionProc, NULL, 0,
775 "show version");
776 cmd_CreateSyntax("-version", VersionProc, NULL, CMD_HIDDEN, NULL);
777 cmd_CreateSyntax("-help", HelpProc, NULL, CMD_HIDDEN, NULL);
778 cmd_CreateSyntax("--version", VersionProc, NULL, CMD_HIDDEN, NULL);
779 cmd_CreateSyntax("--help", HelpProc, NULL, CMD_HIDDEN, NULL);
780 }
781 }
782
783 /* Call the appropriate function, or return syntax error code. Note: if
784 * no opcode is specified, an initialization routine exists, and it has
785 * NOT been called before, we invoke the special initialization opcode
786 */
787 int
788 cmd_Parse(int argc, char **argv, struct cmd_syndesc **outsyntax)
789 {
790 char *pname;
791 struct cmd_syndesc *ts = NULL;
792 struct cmd_parmdesc *tparm;
793 int i;
794 int curType;
795 int positional;
796 int ambig;
797 int code = 0;
798 char *param = NULL;
799 char *embeddedvalue = NULL;
800 static int initd = 0; /*Is this the first time this routine has been called? */
801 static int initcmdpossible = 1; /*Should be consider parsing the initial command? */
802
803 *outsyntax = NULL;
804
805 if (!initd) {
806 initd = 1;
807 initSyntax();
808 }
809
810 /*Remember the program name */
811 pname = argv[0];
812
813 if (noOpcodes) {
814 if (argc == 1) {
815 if (!NoParmsOK(allSyntax)) {
816 printf("%s: Type '%s -help' for help\n", pname, pname);
817 code = CMD_USAGE;
818 goto out;
819 }
820 }
821 } else {
822 if (argc < 2) {
823 /* if there is an initcmd, don't print an error message, just
824 * setup to use the initcmd below. */
825 if (!(initcmdpossible && FindSyntax(initcmd_opcode, NULL))) {
826 printf("%s: Type '%s help' or '%s help <topic>' for help\n",
827 pname, pname, pname);
828 code = CMD_USAGE;
829 goto out;
830 }
831 }
832 }
833
834 /* Find the syntax descriptor for this command, doing prefix matching properly */
835 if (noOpcodes) {
836 ts = allSyntax;
837 } else {
838 ts = (argc < 2 ? 0 : FindSyntax(argv[1], &ambig));
839 if (!ts) {
840 /*First token doesn't match a syntax descriptor */
841 if (initcmdpossible) {
842 /*If initial command line handling hasn't been done yet,
843 * see if there is a descriptor for the initialization opcode.
844 * Only try this once. */
845 initcmdpossible = 0;
846 ts = FindSyntax(initcmd_opcode, NULL);
847 if (!ts) {
848 /*There is no initialization opcode available, so we declare
849 * an error */
850 if (ambig) {
851 fprintf(stderr, "%s", NName(pname, ": "));
852 fprintf(stderr,
853 "Ambiguous operation '%s'; type '%shelp' for list\n",
854 argv[1], NName(pname, " "));
855 } else {
856 fprintf(stderr, "%s", NName(pname, ": "));
857 fprintf(stderr,
858 "Unrecognized operation '%s'; type '%shelp' for list\n",
859 argv[1], NName(pname, " "));
860 }
861 code = CMD_UNKNOWNCMD;
862 goto out;
863 } else {
864 /*Found syntax structure for an initialization opcode. Fix
865 * up argv and argc to relect what the user
866 * ``should have'' typed */
867 if (!(argv = InsertInitOpcode(&argc, argv))) {
868 fprintf(stderr,
869 "%sCan't insert implicit init opcode into command line\n",
870 NName(pname, ": "));
871 code = CMD_INTERNALERROR;
872 goto out;
873 }
874 }
875 } /*Initial opcode not yet attempted */
876 else {
877 /* init cmd already run and no syntax entry found */
878 if (ambig) {
879 fprintf(stderr, "%s", NName(pname, ": "));
880 fprintf(stderr,
881 "Ambiguous operation '%s'; type '%shelp' for list\n",
882 argv[1], NName(pname, " "));
883 } else {
884 fprintf(stderr, "%s", NName(pname, ": "));
885 fprintf(stderr,
886 "Unrecognized operation '%s'; type '%shelp' for list\n",
887 argv[1], NName(pname, " "));
888 }
889 code = CMD_UNKNOWNCMD;
890 goto out;
891 }
892 } /*Argv[1] is not a valid opcode */
893 } /*Opcodes are defined */
894
895 /* Found the descriptor; start parsing. curType is the type we're
896 * trying to parse */
897 curType = 0;
898
899 /* We start off parsing in "positional" mode, where tokens are put in
900 * slots positionally. If we find a name that takes args, we go
901 * out of positional mode, and from that point on, expect a switch
902 * before any particular token. */
903
904 positional = enablePositional; /* Accepting positional cmds ? */
905 i = noOpcodes ? 1 : 2;
906 SetupExpandsFlag(ts);
907 for (; i < argc; i++) {
908 if (param) {
909 free(param);
910 param = NULL;
911 embeddedvalue = NULL;
912 }
913
914 /* Only tokens that start with a hyphen and are not followed by a digit
915 * are considered switches. This allow negative numbers. */
916
917 if ((argv[i][0] == '-') && !isdigit(argv[i][1])) {
918 int j;
919
920 /* Find switch */
921 if (strrchr(argv[i], '=') != NULL) {
922 param = strdup(argv[i]);
923 embeddedvalue = strrchr(param, '=');
924 *embeddedvalue = '\0';
925 embeddedvalue ++;
926 j = FindType(ts, param);
927 } else {
928 j = FindType(ts, argv[i]);
929 }
930
931 if (j < 0) {
932 fprintf(stderr,
933 "%sUnrecognized or ambiguous switch '%s'; type ",
934 NName(pname, ": "), argv[i]);
935 if (noOpcodes)
936 fprintf(stderr, "'%s -help' for detailed help\n",
937 argv[0]);
938 else
939 fprintf(stderr, "'%shelp %s' for detailed help\n",
940 NName(argv[0], " "), ts->name);
941 code = CMD_UNKNOWNSWITCH;
942 goto out;
943 }
944 if (j >= CMD_MAXPARMS) {
945 fprintf(stderr, "%sInternal parsing error\n",
946 NName(pname, ": "));
947 code = CMD_INTERNALERROR;
948 goto out;
949 }
950 if (ts->parms[j].type == CMD_FLAG) {
951 ts->parms[j].items = &dummy;
952
953 if (embeddedvalue) {
954 fprintf(stderr, "%sSwitch '%s' doesn't take an argument\n",
955 NName(pname, ": "), ts->parms[j].name);
956 code = CMD_TOOMANY;
957 goto out;
958 }
959 } else {
960 positional = 0;
961 curType = j;
962 ts->parms[j].flags |= CMD_PROCESSED;
963
964 if (embeddedvalue) {
965 AddItem(&ts->parms[curType], embeddedvalue, pname);
966 }
967 }
968 } else {
969 /* Try to fit in this descr */
970 if (curType >= CMD_MAXPARMS) {
971 fprintf(stderr, "%sToo many arguments\n", NName(pname, ": "));
972 code = CMD_TOOMANY;
973 goto out;
974 }
975 tparm = &ts->parms[curType];
976
977 if ((tparm->type == 0) || /* No option in this slot */
978 (tparm->type == CMD_FLAG)) { /* A flag (not an argument */
979 /* skipped parm slot */
980 curType++; /* Skip this slot and reprocess this parm */
981 i--;
982 continue;
983 }
984
985 if (!(tparm->flags & CMD_PROCESSED) && (tparm->flags & CMD_HIDE)) {
986 curType++; /* Skip this slot and reprocess this parm */
987 i--;
988 continue;
989 }
990
991 if (tparm->type == CMD_SINGLE ||
992 tparm->type == CMD_SINGLE_OR_FLAG) {
993 if (tparm->items) {
994 fprintf(stderr, "%sToo many values after switch %s\n",
995 NName(pname, ": "), tparm->name);
996 code = CMD_NOTLIST;
997 goto out;
998 }
999 AddItem(tparm, argv[i], pname); /* Add to end of list */
1000 } else if (tparm->type == CMD_LIST) {
1001 AddItem(tparm, argv[i], pname); /* Add to end of list */
1002 }
1003
1004 /* Now, if we're in positional mode, advance to the next item */
1005 if (positional)
1006 curType = AdvanceType(ts, curType);
1007 }
1008 }
1009
1010 /* keep track of this for messages */
1011 ts->a0name = argv[0];
1012
1013 /* If we make it here, all the parameters are filled in. Check to see if
1014 * this is a -help version. Must do this before checking for all
1015 * required parms, otherwise it is a real nuisance */
1016 if (ts->parms[CMD_HELPPARM].items) {
1017 PrintSyntax(ts);
1018 /* Display full help syntax if we don't have subcommands */
1019 if (noOpcodes)
1020 PrintFlagHelp(ts);
1021 code = CMD_HELP;
1022 goto out;
1023 }
1024
1025 /* Parsing done, see if we have all of our required parameters */
1026 for (i = 0; i < CMD_MAXPARMS; i++) {
1027 tparm = &ts->parms[i];
1028 if (tparm->type == 0)
1029 continue; /* Skipped parm slot */
1030 if ((tparm->flags & CMD_PROCESSED) && tparm->items == 0) {
1031 if (tparm->type == CMD_SINGLE_OR_FLAG) {
1032 tparm->items = &dummy;
1033 } else {
1034 fprintf(stderr, "%s The field '%s' isn't completed properly\n",
1035 NName(pname, ": "), tparm->name);
1036 code = CMD_TOOFEW;
1037 goto out;
1038 }
1039 }
1040 if (!(tparm->flags & CMD_OPTIONAL) && tparm->items == 0) {
1041 fprintf(stderr, "%sMissing required parameter '%s'\n",
1042 NName(pname, ": "), tparm->name);
1043 code = CMD_TOOFEW;
1044 goto out;
1045 }
1046 tparm->flags &= ~CMD_PROCESSED;
1047 }
1048 *outsyntax = ts;
1049
1050 out:
1051 if (code && ts != NULL)
1052 ResetSyntax(ts);
1053
1054 return code;
1055 }
1056
1057 int
1058 cmd_Dispatch(int argc, char **argv)
1059 {
1060 struct cmd_syndesc *ts = NULL;
1061 int code;
1062
1063 code = cmd_Parse(argc, argv, &ts);
1064 if (code) {
1065 if (code == CMD_HELP) {
1066 code = 0; /* displaying help is not an error */
1067 }
1068 return code;
1069 }
1070
1071 /*
1072 * Before calling the beforeProc and afterProc and all the implications
1073 * from those calls, check if the help procedure was called and call it
1074 * now.
1075 */
1076 if ((ts->proc == HelpProc) || (ts->proc == AproposProc)) {
1077 code = (*ts->proc) (ts, ts->rock);
1078 goto out;
1079 }
1080
1081 /* Now, we just call the procedure and return */
1082 if (beforeProc)
1083 code = (*beforeProc) (ts, beforeRock);
1084
1085 if (code)
1086 goto out;
1087
1088 code = (*ts->proc) (ts, ts->rock);
1089
1090 if (afterProc)
1091 (*afterProc) (ts, afterRock);
1092 out:
1093 cmd_FreeOptions(&ts);
1094 return code;
1095 }
1096
1097 void
1098 cmd_FreeOptions(struct cmd_syndesc **ts)
1099 {
1100 if (*ts != NULL) {
1101 ResetSyntax(*ts);
1102 *ts = NULL;
1103 }
1104 }
1105
1106 /* free token list returned by parseLine */
1107 static int
1108 FreeTokens(struct cmd_token *alist)
1109 {
1110 struct cmd_token *nlist;
1111 for (; alist; alist = nlist) {
1112 nlist = alist->next;
1113 free(alist->key);
1114 free(alist);
1115 }
1116 return 0;
1117 }
1118
1119 /* free an argv list returned by parseline */
1120 int
1121 cmd_FreeArgv(char **argv)
1122 {
1123 char *tp;
1124 for (tp = *argv; tp; argv++, tp = *argv)
1125 free(tp);
1126 return 0;
1127 }
1128
1129 /* copy back the arg list to the argv array, freeing the cmd_tokens as you go;
1130 * the actual data is still malloc'd, and will be freed when the caller calls
1131 * cmd_FreeArgv later on
1132 */
1133 #define INITSTR ""
1134 static int
1135 CopyBackArgs(struct cmd_token *alist, char **argv,
1136 afs_int32 * an, afs_int32 amaxn)
1137 {
1138 struct cmd_token *next;
1139 afs_int32 count;
1140
1141 count = 0;
1142 if (amaxn <= 1)
1143 return CMD_TOOMANY;
1144 *argv = strdup(INITSTR);
1145 assert(*argv);
1146 amaxn--;
1147 argv++;
1148 count++;
1149 while (alist) {
1150 if (amaxn <= 1)
1151 return CMD_TOOMANY; /* argv is too small for his many parms. */
1152 *argv = alist->key;
1153 next = alist->next;
1154 free(alist);
1155 alist = next;
1156 amaxn--;
1157 argv++;
1158 count++;
1159 }
1160 *argv = NULL; /* use last slot for terminating null */
1161 /* don't count terminating null */
1162 *an = count;
1163 return 0;
1164 }
1165
1166 static int
1167 quote(int x)
1168 {
1169 if (x == '"' || x == 39 /* single quote */ )
1170 return 1;
1171 else
1172 return 0;
1173 }
1174
1175 static int
1176 space(int x)
1177 {
1178 if (x == 0 || x == ' ' || x == '\t' || x == '\n')
1179 return 1;
1180 else
1181 return 0;
1182 }
1183
1184 int
1185 cmd_ParseLine(char *aline, char **argv, afs_int32 * an, afs_int32 amaxn)
1186 {
1187 char tbuffer[256];
1188 char *tptr = 0;
1189 int inToken, inQuote;
1190 struct cmd_token *first, *last;
1191 struct cmd_token *ttok;
1192 int tc;
1193
1194 inToken = 0; /* not copying token chars at start */
1195 first = NULL;
1196 last = NULL;
1197 inQuote = 0; /* not in a quoted string */
1198 while (1) {
1199 tc = *aline++;
1200 if (tc == 0 || (!inQuote && space(tc))) { /* terminating null gets us in here, too */
1201 if (inToken) {
1202 inToken = 0; /* end of this token */
1203 if (!tptr)
1204 return -1; /* should never get here */
1205 else
1206 *tptr++ = 0;
1207 ttok = malloc(sizeof(struct cmd_token));
1208 assert(ttok);
1209 ttok->next = NULL;
1210 ttok->key = strdup(tbuffer);
1211 assert(ttok->key);
1212 if (last) {
1213 last->next = ttok;
1214 last = ttok;
1215 } else
1216 last = ttok;
1217 if (!first)
1218 first = ttok;
1219 }
1220 } else {
1221 /* an alpha character */
1222 if (!inToken) {
1223 tptr = tbuffer;
1224 inToken = 1;
1225 }
1226 if (tptr - tbuffer >= sizeof(tbuffer)) {
1227 FreeTokens(first);
1228 return CMD_TOOBIG; /* token too long */
1229 }
1230 if (quote(tc)) {
1231 /* hit a quote, toggle inQuote flag but don't insert character */
1232 inQuote = !inQuote;
1233 } else {
1234 /* insert character */
1235 *tptr++ = tc;
1236 }
1237 }
1238 if (tc == 0) {
1239 /* last token flushed 'cause space(0) --> true */
1240 if (last)
1241 last->next = NULL;
1242 return CopyBackArgs(first, argv, an, amaxn);
1243 }
1244 }
1245 }
1246
1247 /* Read a string in from our configuration file. This checks in
1248 * multiple places within this file - firstly in the section
1249 * [command_subcommand], then in [command], then in [subcommand]
1250 *
1251 * Returns CMD_MISSING if there is no configuration file configured,
1252 * or if the file doesn't contain information for the specified option
1253 * in any of these sections.
1254 */
1255
1256 static int
1257 _get_file_string(struct cmd_syndesc *syn, int pos, const char **str)
1258 {
1259 char *section;
1260 char *optionName;
1261
1262 /* Nothing on the command line, try the config file if we have one */
1263 if (globalConfig == NULL)
1264 return CMD_MISSING;
1265
1266 /* March past any leading -'s */
1267 for (optionName = syn->parms[pos].name;
1268 *optionName == '-'; optionName++);
1269
1270 /* First, try the command_subcommand form */
1271 if (syn->name != NULL && commandName != NULL) {
1272 if (asprintf(&section, "%s_%s", commandName, syn->name) < 0)
1273 return ENOMEM;
1274 *str = cmd_RawConfigGetString(globalConfig, NULL, section,
1275 optionName, NULL);
1276 free(section);
1277 if (*str)
1278 return 0;
1279 }
1280
1281 /* Then, try the command form */
1282 if (commandName != NULL) {
1283 *str = cmd_RawConfigGetString(globalConfig, NULL, commandName,
1284 optionName, NULL);
1285 if (*str)
1286 return 0;
1287 }
1288
1289 /* Then, the defaults section */
1290 *str = cmd_RawConfigGetString(globalConfig, NULL, "defaults",
1291 optionName, NULL);
1292 if (*str)
1293 return 0;
1294
1295 /* Nothing there, return MISSING */
1296 return CMD_MISSING;
1297 }
1298
1299 static int
1300 _get_config_string(struct cmd_syndesc *syn, int pos, const char **str)
1301 {
1302 *str = NULL;
1303
1304 if (pos > syn->nParms)
1305 return CMD_EXCESSPARMS;
1306
1307 /* It's a flag, they probably shouldn't be using this interface to access
1308 * it, but don't blow up for now */
1309 if (syn->parms[pos].items == &dummy)
1310 return 0;
1311
1312 /* We have a value on the command line - this overrides anything in the
1313 * configuration file */
1314 if (syn->parms[pos].items != NULL &&
1315 syn->parms[pos].items->data != NULL) {
1316 *str = syn->parms[pos].items->data;
1317 return 0;
1318 }
1319
1320 return _get_file_string(syn, pos, str);
1321 }
1322
1323 int
1324 cmd_OptionAsInt(struct cmd_syndesc *syn, int pos, int *value)
1325 {
1326 const char *str;
1327 int code;
1328
1329 code =_get_config_string(syn, pos, &str);
1330 if (code)
1331 return code;
1332
1333 if (str == NULL)
1334 return CMD_MISSING;
1335
1336 *value = strtol(str, NULL, 10);
1337
1338 return 0;
1339 }
1340
1341 int
1342 cmd_OptionAsUint(struct cmd_syndesc *syn, int pos,
1343 unsigned int *value)
1344 {
1345 const char *str;
1346 int code;
1347
1348 code = _get_config_string(syn, pos, &str);
1349 if (code)
1350 return code;
1351
1352 if (str == NULL)
1353 return CMD_MISSING;
1354
1355 *value = strtoul(str, NULL, 10);
1356
1357 return 0;
1358 }
1359
1360 int
1361 cmd_OptionAsString(struct cmd_syndesc *syn, int pos, char **value)
1362 {
1363 const char *str;
1364 int code;
1365
1366 code = _get_config_string(syn, pos, &str);
1367 if (code)
1368 return code;
1369
1370 if (str == NULL)
1371 return CMD_MISSING;
1372
1373 if (*value)
1374 free(*value);
1375 *value = strdup(str);
1376
1377 return 0;
1378 }
1379
1380 int
1381 cmd_OptionAsList(struct cmd_syndesc *syn, int pos, struct cmd_item **value)
1382 {
1383 const char *str;
1384 struct cmd_item *item, **last;
1385 const char *start, *end;
1386 size_t len;
1387 int code;
1388
1389 if (pos > syn->nParms)
1390 return CMD_EXCESSPARMS;
1391
1392 /* If we have a list already, just return the existing list */
1393 if (syn->parms[pos].items != NULL) {
1394 *value = syn->parms[pos].items;
1395 return 0;
1396 }
1397
1398 code = _get_file_string(syn, pos, &str);
1399 if (code)
1400 return code;
1401
1402 /* Use strchr to split str into elements, and build a recursive list
1403 * from them. Hang this list off the configuration structure, so that
1404 * it is returned by any future calls to this function, and is freed
1405 * along with everything else when the syntax description is freed
1406 */
1407 last = &syn->parms[pos].items;
1408 start = str;
1409 while ((end = strchr(start, ' '))) {
1410 item = calloc(1, sizeof(struct cmd_item));
1411 len = end - start + 1;
1412 item->data = malloc(len);
1413 strlcpy(item->data, start, len);
1414 *last = item;
1415 last = &item->next;
1416 for (start = end; *start == ' '; start++); /* skip any whitespace */
1417 }
1418
1419 /* Catch the final element */
1420 if (*start != '\0') {
1421 item = calloc(1, sizeof(struct cmd_item));
1422 len = strlen(start) + 1;
1423 item->data = malloc(len);
1424 strlcpy(item->data, start, len);
1425 *last = item;
1426 }
1427
1428 *value = syn->parms[pos].items;
1429
1430 return 0;
1431 }
1432
1433 int
1434 cmd_OptionAsFlag(struct cmd_syndesc *syn, int pos, int *value)
1435 {
1436 const char *str = NULL;
1437 int code;
1438
1439 code = _get_config_string(syn, pos, &str);
1440 if (code)
1441 return code;
1442
1443 if (str == NULL ||
1444 strcasecmp(str, "yes") == 0 ||
1445 strcasecmp(str, "true") == 0 ||
1446 atoi(str))
1447 *value = 1;
1448 else
1449 *value = 0;
1450
1451 return 0;
1452 }
1453
1454 int
1455 cmd_OptionPresent(struct cmd_syndesc *syn, int pos)
1456 {
1457 const char *str;
1458 int code;
1459
1460 code = _get_config_string(syn, pos, &str);
1461 if (code == 0)
1462 return 1;
1463
1464 return 0;
1465 }
1466
1467 int
1468 cmd_OpenConfigFile(const char *file)
1469 {
1470 if (globalConfig) {
1471 cmd_RawConfigFileFree(globalConfig);
1472 globalConfig = NULL;
1473 }
1474
1475 return cmd_RawConfigParseFile(file, &globalConfig);
1476 }
1477
1478 void
1479 cmd_SetCommandName(const char *command)
1480 {
1481 commandName = command;
1482 }
1483
1484 const cmd_config_section *
1485 cmd_RawFile(void)
1486 {
1487 return globalConfig;
1488 }
1489
1490 const cmd_config_section *
1491 cmd_RawSection(void)
1492 {
1493 if (globalConfig == NULL || commandName == NULL)
1494 return NULL;
1495
1496 return cmd_RawConfigGetList(globalConfig, commandName, NULL);
1497 }