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