cmd: Add support for params with optional values
[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
36 /* take name and string, and return null string if name is empty, otherwise return
37    the concatenation of the two strings */
38 static char *
39 NName(char *a1, char *a2)
40 {
41     static char tbuffer[300];
42     if (strlen(a1) == 0) {
43         return "";
44     } else {
45         strncpy(tbuffer, a1, sizeof(tbuffer));
46         strncat(tbuffer, a2, sizeof(tbuffer));
47         tbuffer[sizeof(tbuffer)-1]='\0';
48         return tbuffer;
49     }
50 }
51
52 /* return true if asub is a substring of amain */
53 static int
54 SubString(char *amain, char *asub)
55 {
56     int mlen, slen;
57     int i, j;
58     mlen = (int) strlen(amain);
59     slen = (int) strlen(asub);
60     j = mlen - slen;
61     if (j < 0)
62         return 0;               /* not a substring */
63     for (i = 0; i <= j; i++) {
64         if (strncmp(amain, asub, slen) == 0)
65             return 1;
66         amain++;
67     }
68     return 0;                   /* didn't find it */
69 }
70
71 static int
72 FindType(struct cmd_syndesc *as, char *aname)
73 {
74     int i;
75     size_t cmdlen;
76     int ambig;
77     int best;
78     struct cmd_item *alias;
79
80     /* Allow --long-style options. */
81     if (aname[0] == '-' && aname[1] == '-' && aname[2] && aname[3]) {
82         aname++;
83     }
84
85     cmdlen = strlen(aname);
86     ambig = 0;
87     best = -1;
88     for (i = 0; i < CMD_MAXPARMS; i++) {
89         if (as->parms[i].type == 0)
90             continue;           /* this slot not set (seeked over) */
91         if (strcmp(as->parms[i].name, aname) == 0)
92             return i;
93         if (strlen(as->parms[i].name) < cmdlen)
94             continue;
95
96         /* Check for aliases, which must be full matches */
97         alias = as->parms[i].aliases;
98         while (alias != NULL) {
99             if (strcmp(alias->data, aname) == 0)
100                 return i;
101             alias = alias->next;
102         }
103
104         /* A hidden option must be a full match (no best matches) */
105         if (as->parms[i].flags & CMD_HIDE || !enableAbbreviation)
106             continue;
107
108         if (strncmp(as->parms[i].name, aname, cmdlen) == 0) {
109             if (best != -1)
110                 ambig = 1;
111             else
112                 best = i;
113         }
114     }
115     return (ambig ? -1 : best);
116 }
117
118 static struct cmd_syndesc *
119 FindSyntax(char *aname, int *aambig)
120 {
121     struct cmd_syndesc *ts;
122     struct cmd_syndesc *best;
123     size_t cmdLen;
124     int ambig;
125
126     cmdLen = strlen(aname);
127     best = (struct cmd_syndesc *)0;
128     ambig = 0;
129     if (aambig)
130         *aambig = 0;            /* initialize to unambiguous */
131     for (ts = allSyntax; ts; ts = ts->next) {
132         if (strcmp(aname, ts->name) == 0)
133             return (ts);
134         if (strlen(ts->name) < cmdLen)
135             continue;           /* we typed more than item has */
136         /* A hidden command must be a full match (no best matches) */
137         if (ts->flags & CMD_HIDDEN)
138             continue;
139
140         /* This is just an alias for *best, or *best is just an alias for us.
141          * If we don't make this check explicitly, then an alias which is just a
142          * short prefix of the real command's name might make things ambiguous
143          * for no apparent reason.
144          */
145         if (best && ts->aliasOf == best->aliasOf)
146             continue;
147         if (strncmp(ts->name, aname, cmdLen) == 0) {
148             if (best)
149                 ambig = 1;      /* ambiguous name */
150             else
151                 best = ts;
152         }
153     }
154     if (ambig) {
155         if (aambig)
156             *aambig = ambig;    /* if ambiguous and they care, tell them */
157         return (struct cmd_syndesc *)0; /* fails */
158     } else
159         return best;            /* otherwise its not ambiguous, and they know */
160 }
161
162 /* print the help for a single parameter */
163 static void
164 PrintParmHelp(struct cmd_parmdesc *aparm)
165 {
166     if (aparm->type == CMD_FLAG) {
167 #ifdef notdef
168         /* doc people don't like seeing this information */
169         if (aparm->help)
170             printf(" (%s)", aparm->help);
171 #endif
172     } else if (aparm->help) {
173         printf(" <%s>", aparm->help);
174         if (aparm->type == CMD_LIST)
175             printf("+");
176     } else if (aparm->type == CMD_SINGLE)
177         printf(" <arg>");
178     else if (aparm->type == CMD_LIST)
179         printf(" <arg>+");
180 }
181
182 extern char *AFSVersion;
183
184 static int
185 VersionProc(struct cmd_syndesc *as, void *arock)
186 {
187     printf("%s\n", AFSVersion);
188     return 0;
189 }
190
191 void
192 PrintSyntax(struct cmd_syndesc *as)
193 {
194     int i;
195     struct cmd_parmdesc *tp;
196
197     /* now print usage, from syntax table */
198     if (noOpcodes)
199         printf("Usage: %s", as->a0name);
200     else {
201         if (!strcmp(as->name, initcmd_opcode))
202             printf("Usage: %s[%s]", NName(as->a0name, " "), as->name);
203         else
204             printf("Usage: %s%s", NName(as->a0name, " "), as->name);
205     }
206
207     for (i = 0; i < CMD_MAXPARMS; i++) {
208         tp = &as->parms[i];
209         if (tp->type == 0)
210             continue;           /* seeked over slot */
211         if (tp->flags & CMD_HIDE)
212             continue;           /* skip hidden options */
213         printf(" ");
214         if (tp->flags & CMD_OPTIONAL)
215             printf("[");
216         printf("%s", tp->name);
217         PrintParmHelp(tp);
218         if (tp->flags & CMD_OPTIONAL)
219             printf("]");
220     }
221     printf("\n");
222 }
223
224 /* must print newline in any case, to terminate preceding line */
225 static void
226 PrintAliases(struct cmd_syndesc *as)
227 {
228     struct cmd_syndesc *ts;
229
230     if (as->flags & CMD_ALIAS) {
231         ts = as->aliasOf;
232         printf("(alias for %s)\n", ts->name);
233     } else {
234         printf("\n");
235         if (!as->nextAlias)
236             return;             /* none, print nothing */
237         printf("aliases: ");
238         for (as = as->nextAlias; as; as = as->nextAlias) {
239             printf("%s ", as->name);
240         }
241         printf("\n");
242     }
243 }
244
245 void
246 PrintFlagHelp(struct cmd_syndesc *as)
247 {
248     int i;
249     struct cmd_parmdesc *tp;
250     int flag_width;
251     char *flag_prefix;
252
253     /* find flag name length */
254     flag_width = 0;
255     for (i = 0; i < CMD_MAXPARMS; i++) {
256         if (i == CMD_HELPPARM)
257             continue;
258         tp = &as->parms[i];
259         if (tp->type != CMD_FLAG)
260             continue;
261         if (tp->flags & CMD_HIDE)
262             continue;           /* skip hidden options */
263         if (!tp->help)
264             continue;
265
266         if (strlen(tp->name) > flag_width)
267             flag_width = strlen(tp->name);
268     }
269
270     /* print flag help */
271     flag_prefix = "Where:";
272     for (i = 0; i < CMD_MAXPARMS; i++) {
273         if (i == CMD_HELPPARM)
274             continue;
275         tp = &as->parms[i];
276         if (tp->type != CMD_FLAG)
277             continue;
278         if (tp->flags & CMD_HIDE)
279             continue;           /* skip hidden options */
280         if (!tp->help)
281             continue;
282
283         printf("%-7s%-*s  %s\n", flag_prefix, flag_width, tp->name, tp->help);
284         flag_prefix = "";
285     }
286 }
287
288 static int
289 AproposProc(struct cmd_syndesc *as, void *arock)
290 {
291     struct cmd_syndesc *ts;
292     char *tsub;
293     int didAny;
294
295     didAny = 0;
296     tsub = as->parms[0].items->data;
297     for (ts = allSyntax; ts; ts = ts->next) {
298         if ((ts->flags & CMD_ALIAS) || (ts->flags & CMD_HIDDEN))
299             continue;
300         if (SubString(ts->help, tsub)) {
301             printf("%s: %s\n", ts->name, ts->help);
302             didAny = 1;
303         } else if (SubString(ts->name, tsub)) {
304             printf("%s: %s\n", ts->name, ts->help);
305             didAny = 1;
306         }
307     }
308     if (!didAny)
309         printf("Sorry, no commands found\n");
310     return 0;
311 }
312
313 static int
314 HelpProc(struct cmd_syndesc *as, void *arock)
315 {
316     struct cmd_syndesc *ts;
317     struct cmd_item *ti;
318     int ambig;
319     int code = 0;
320
321     if (as->parms[0].items == 0) {
322         printf("%sCommands are:\n", NName(as->a0name, ": "));
323         for (ts = allSyntax; ts; ts = ts->next) {
324             if ((ts->flags & CMD_ALIAS) || (ts->flags & CMD_HIDDEN))
325                 continue;
326             printf("%-15s %s\n", ts->name, (ts->help ? ts->help : ""));
327         }
328     } else {
329         /* print out individual help topics */
330         for (ti = as->parms[0].items; ti; ti = ti->next) {
331             code = 0;
332             ts = FindSyntax(ti->data, &ambig);
333             if (ts && (ts->flags & CMD_HIDDEN))
334                 ts = 0;         /* no hidden commands */
335             if (ts) {
336                 /* print out command name and help */
337                 printf("%s%s: %s ", NName(as->a0name, " "), ts->name,
338                        (ts->help ? ts->help : ""));
339                 ts->a0name = as->a0name;
340                 PrintAliases(ts);
341                 PrintSyntax(ts);
342                 PrintFlagHelp(ts);
343             } else {
344                 if (!ambig)
345                     fprintf(stderr, "%sUnknown topic '%s'\n",
346                             NName(as->a0name, ": "), ti->data);
347                 else {
348                     /* ambiguous, list 'em all */
349                     fprintf(stderr,
350                             "%sAmbiguous topic '%s'; use 'apropos' to list\n",
351                             NName(as->a0name, ": "), ti->data);
352                 }
353                 code = CMD_UNKNOWNCMD;
354             }
355         }
356     }
357     return (code);
358 }
359
360 int
361 cmd_SetBeforeProc(int (*aproc) (struct cmd_syndesc * ts, void *beforeRock),
362                   void *arock)
363 {
364     beforeProc = aproc;
365     beforeRock = arock;
366     return 0;
367 }
368
369 int
370 cmd_SetAfterProc(int (*aproc) (struct cmd_syndesc * ts, void *afterRock),
371                  void *arock)
372 {
373     afterProc = aproc;
374     afterRock = arock;
375     return 0;
376 }
377
378 /* thread on list in alphabetical order */
379 static int
380 SortSyntax(struct cmd_syndesc *as)
381 {
382     struct cmd_syndesc **ld, *ud;
383
384     for (ld = &allSyntax, ud = *ld; ud; ld = &ud->next, ud = *ld) {
385         if (strcmp(ud->name, as->name) > 0) {   /* next guy is bigger than us */
386             break;
387         }
388     }
389     /* thread us on the list now */
390     *ld = as;
391     as->next = ud;
392     return 0;
393 }
394
395 struct cmd_syndesc *
396 cmd_CreateSyntax(char *aname,
397                  int (*aproc) (struct cmd_syndesc * ts, void *arock),
398                  void *arock, char *ahelp)
399 {
400     struct cmd_syndesc *td;
401
402     /* can't have two cmds in no opcode mode */
403     if (noOpcodes)
404         return NULL;
405
406     td = calloc(1, sizeof(struct cmd_syndesc));
407     assert(td);
408     td->aliasOf = td;           /* treat aliasOf as pointer to real command, no matter what */
409
410     /* copy in name, etc */
411     if (aname) {
412         td->name = malloc(strlen(aname) + 1);
413         assert(td->name);
414         strcpy(td->name, aname);
415     } else {
416         td->name = NULL;
417         noOpcodes = 1;
418     }
419     if (ahelp) {
420         /* Piggy-back the hidden option onto the help string */
421         if (ahelp == (char *)CMD_HIDDEN) {
422             td->flags |= CMD_HIDDEN;
423         } else {
424             td->help = malloc(strlen(ahelp) + 1);
425             assert(td->help);
426             strcpy(td->help, ahelp);
427         }
428     } else
429         td->help = NULL;
430     td->proc = aproc;
431     td->rock = arock;
432
433     SortSyntax(td);
434
435     cmd_Seek(td, CMD_HELPPARM);
436     cmd_AddParm(td, "-help", CMD_FLAG, CMD_OPTIONAL, "get detailed help");
437     cmd_Seek(td, 0);
438
439     return td;
440 }
441
442 int
443 cmd_CreateAlias(struct cmd_syndesc *as, char *aname)
444 {
445     struct cmd_syndesc *td;
446
447     td = malloc(sizeof(struct cmd_syndesc));
448     assert(td);
449     memcpy(td, as, sizeof(struct cmd_syndesc));
450     td->name = malloc(strlen(aname) + 1);
451     assert(td->name);
452     strcpy(td->name, aname);
453     td->flags |= CMD_ALIAS;
454     /* if ever free things, make copy of help string, too */
455
456     /* thread on list */
457     SortSyntax(td);
458
459     /* thread on alias lists */
460     td->nextAlias = as->nextAlias;
461     as->nextAlias = td;
462     td->aliasOf = as;
463
464     return 0;                   /* all done */
465 }
466
467 void
468 cmd_DisablePositionalCommands(void)
469 {
470     enablePositional = 0;
471 }
472
473 void
474 cmd_DisableAbbreviations(void)
475 {
476     enableAbbreviation = 0;
477 }
478
479 int
480 cmd_IsAdministratorCommand(struct cmd_syndesc *as)
481 {
482     as->flags |= CMD_ADMIN;
483     return 0;
484 }
485
486 int
487 cmd_Seek(struct cmd_syndesc *as, int apos)
488 {
489     if (apos >= CMD_MAXPARMS)
490         return CMD_EXCESSPARMS;
491     as->nParms = apos;
492     return 0;
493 }
494
495 int
496 cmd_AddParmAtOffset(struct cmd_syndesc *as, char *aname, int atype,
497                     afs_int32 aflags, char *ahelp, int ref)
498 {
499     struct cmd_parmdesc *tp;
500
501     if (ref >= CMD_MAXPARMS)
502         return CMD_EXCESSPARMS;
503     tp = &as->parms[ref];
504
505     tp->name = malloc(strlen(aname) + 1);
506     assert(tp->name);
507     strcpy(tp->name, aname);
508     tp->type = atype;
509     tp->flags = aflags;
510     tp->items = NULL;
511     if (ahelp) {
512         tp->help = malloc(strlen(ahelp) + 1);
513         assert(tp->help);
514         strcpy(tp->help, ahelp);
515     } else
516         tp->help = NULL;
517
518     tp->aliases = NULL;
519
520     if (as->nParms <= ref)
521         as->nParms = ref+1;
522
523     return 0;
524 }
525
526 int
527 cmd_AddParm(struct cmd_syndesc *as, char *aname, int atype,
528             afs_int32 aflags, char *ahelp)
529 {
530     if (as->nParms >= CMD_MAXPARMS)
531         return CMD_EXCESSPARMS;
532
533     return cmd_AddParmAtOffset(as, aname, atype, aflags, ahelp, as->nParms++);
534 }
535
536 int
537 cmd_AddParmAlias(struct cmd_syndesc *as, int pos, char *alias)
538 {
539     struct cmd_item *item;
540
541     if (pos > as->nParms)
542         return CMD_EXCESSPARMS;
543
544     item = calloc(1, sizeof(struct cmd_item));
545     item->data = strdup(alias);
546     item->next = as->parms[pos].aliases;
547     as->parms[pos].aliases = item;
548
549     return 0;
550 }
551
552 /* add a text item to the end of the parameter list */
553 static int
554 AddItem(struct cmd_parmdesc *aparm, char *aval)
555 {
556     struct cmd_item *ti, *ni;
557     ti = calloc(1, sizeof(struct cmd_item));
558     assert(ti);
559     ti->data = malloc(strlen(aval) + 1);
560     assert(ti->data);
561     strcpy(ti->data, aval);
562     /* now put ti at the *end* of the list */
563     if ((ni = aparm->items)) {
564         for (; ni; ni = ni->next)
565             if (ni->next == 0)
566                 break;          /* skip to last one */
567         ni->next = ti;
568     } else
569         aparm->items = ti;      /* we're first */
570     return 0;
571 }
572
573 /* skip to next non-flag item, if any */
574 static int
575 AdvanceType(struct cmd_syndesc *as, afs_int32 aval)
576 {
577     afs_int32 next;
578     struct cmd_parmdesc *tp;
579
580     /* first see if we should try to grab rest of line for this dude */
581     if (as->parms[aval].flags & CMD_EXPANDS)
582         return aval;
583
584     /* if not, find next non-flag used slot */
585     for (next = aval + 1; next < CMD_MAXPARMS; next++) {
586         tp = &as->parms[next];
587         if (tp->type != 0 && tp->type != CMD_FLAG)
588             return next;
589     }
590     return aval;
591 }
592
593 /* discard parameters filled in by dispatch */
594 static void
595 ResetSyntax(struct cmd_syndesc *as)
596 {
597     int i;
598     struct cmd_parmdesc *tp;
599     struct cmd_item *ti, *ni;
600
601     tp = as->parms;
602     for (i = 0; i < CMD_MAXPARMS; i++, tp++) {
603         switch (tp->type) {
604         case CMD_SINGLE_OR_FLAG:
605             if (tp->items == &dummy)
606                 break;
607             /* Deliberately fall through here */
608         case CMD_SINGLE:
609         case CMD_LIST:
610             /* free whole list in both cases, just for fun */
611             for (ti = tp->items; ti; ti = ni) {
612                 ni = ti->next;
613                 free(ti->data);
614                 free(ti);
615             }
616             break;
617
618         default:
619             break;
620         }
621         tp->items = NULL;
622     }
623 }
624
625 /* move the expands flag to the last one in the list */
626 static int
627 SetupExpandsFlag(struct cmd_syndesc *as)
628 {
629     struct cmd_parmdesc *tp;
630     int last, i;
631
632     last = -1;
633     /* find last CMD_LIST type parameter, optional or not, and make it expandable
634      * if no other dude is expandable */
635     for (i = 0; i < CMD_MAXPARMS; i++) {
636         tp = &as->parms[i];
637         if (tp->type == CMD_LIST) {
638             if (tp->flags & CMD_EXPANDS)
639                 return 0;       /* done if already specified */
640             last = i;
641         }
642     }
643     if (last >= 0)
644         as->parms[last].flags |= CMD_EXPANDS;
645     return 0;
646 }
647
648 /* Take the current argv & argc and alter them so that the initialization
649  * opcode is made to appear.  This is used in cases where the initialization
650  * opcode is implicitly invoked.*/
651 static char **
652 InsertInitOpcode(int *aargc, char **aargv)
653 {
654     char **newargv;             /*Ptr to new, expanded argv space */
655     char *pinitopcode;          /*Ptr to space for name of init opcode */
656     int i;                      /*Loop counter */
657
658     /* Allocate the new argv array, plus one for the new opcode, plus one
659      * more for the trailing null pointer */
660     newargv = malloc(((*aargc) + 2) * sizeof(char *));
661     if (!newargv) {
662         fprintf(stderr, "%s: Can't create new argv array with %d+2 slots\n",
663                 aargv[0], *aargc);
664         return (NULL);
665     }
666
667     /* Create space for the initial opcode & fill it in */
668     pinitopcode = malloc(sizeof(initcmd_opcode));
669     if (!pinitopcode) {
670         fprintf(stderr, "%s: Can't malloc initial opcode space\n", aargv[0]);
671         free(newargv);
672         return (NULL);
673     }
674     strcpy(pinitopcode, initcmd_opcode);
675
676     /* Move all the items in the old argv into the new argv, in their
677      * proper places */
678     for (i = *aargc; i > 1; i--)
679         newargv[i] = aargv[i - 1];
680
681     /* Slip in the opcode and the trailing null pointer, and bump the
682      * argument count up by one for the new opcode */
683     newargv[0] = aargv[0];
684     newargv[1] = pinitopcode;
685     (*aargc)++;
686     newargv[*aargc] = NULL;
687
688     /* Return the happy news */
689     return (newargv);
690
691 }                               /*InsertInitOpcode */
692
693 static int
694 NoParmsOK(struct cmd_syndesc *as)
695 {
696     int i;
697     struct cmd_parmdesc *td;
698
699     for (i = 0; i < CMD_MAXPARMS; i++) {
700         td = &as->parms[i];
701         if (td->type != 0 && !(td->flags & CMD_OPTIONAL)) {
702             /* found a non-optional (e.g. required) parm, so NoParmsOK
703              * is false (some parms are required) */
704             return 0;
705         }
706     }
707     return 1;
708 }
709
710 /* Add help, apropos commands once */
711 static void
712 initSyntax(void)
713 {
714     struct cmd_syndesc *ts;
715
716     if (!noOpcodes) {
717         ts = cmd_CreateSyntax("help", HelpProc, NULL,
718                               "get help on commands");
719         cmd_AddParm(ts, "-topic", CMD_LIST, CMD_OPTIONAL, "help string");
720         cmd_AddParm(ts, "-admin", CMD_FLAG, CMD_OPTIONAL, NULL);
721
722         ts = cmd_CreateSyntax("apropos", AproposProc, NULL,
723                               "search by help text");
724         cmd_AddParm(ts, "-topic", CMD_SINGLE, CMD_REQUIRED, "help string");
725         ts = cmd_CreateSyntax("version", VersionProc, NULL,
726                               (char *)CMD_HIDDEN);
727         ts = cmd_CreateSyntax("-version", VersionProc, NULL,
728                               (char *)CMD_HIDDEN);
729         ts = cmd_CreateSyntax("-help", HelpProc, NULL,
730                               (char *)CMD_HIDDEN);
731         ts = cmd_CreateSyntax("--version", VersionProc, NULL,
732                               (char *)CMD_HIDDEN);
733         ts = cmd_CreateSyntax("--help", HelpProc, NULL,
734                               (char *)CMD_HIDDEN);
735     }
736 }
737
738 /* Call the appropriate function, or return syntax error code.  Note: if
739  * no opcode is specified, an initialization routine exists, and it has
740  * NOT been called before, we invoke the special initialization opcode
741  */
742 int
743 cmd_Parse(int argc, char **argv, struct cmd_syndesc **outsyntax)
744 {
745     char *pname;
746     struct cmd_syndesc *ts = NULL;
747     struct cmd_parmdesc *tparm;
748     afs_int32 i, j;
749     int curType;
750     int positional;
751     int ambig;
752     int code = 0;
753     static int initd = 0;       /*Is this the first time this routine has been called? */
754     static int initcmdpossible = 1;     /*Should be consider parsing the initial command? */
755
756     *outsyntax = NULL;
757
758     if (!initd) {
759         initd = 1;
760         initSyntax();
761     }
762
763     /*Remember the program name */
764     pname = argv[0];
765
766     if (noOpcodes) {
767         if (argc == 1) {
768             if (!NoParmsOK(allSyntax)) {
769                 printf("%s: Type '%s -help' for help\n", pname, pname);
770                 code = CMD_USAGE;
771                 goto out;
772             }
773         }
774     } else {
775         if (argc < 2) {
776             /* if there is an initcmd, don't print an error message, just
777              * setup to use the initcmd below. */
778             if (!(initcmdpossible && FindSyntax(initcmd_opcode, NULL))) {
779                 printf("%s: Type '%s help' or '%s help <topic>' for help\n",
780                        pname, pname, pname);
781                 code = CMD_USAGE;
782                 goto out;
783             }
784         }
785     }
786
787     /* Find the syntax descriptor for this command, doing prefix matching properly */
788     if (noOpcodes) {
789         ts = allSyntax;
790     } else {
791         ts = (argc < 2 ? 0 : FindSyntax(argv[1], &ambig));
792         if (!ts) {
793             /*First token doesn't match a syntax descriptor */
794             if (initcmdpossible) {
795                 /*If initial command line handling hasn't been done yet,
796                  * see if there is a descriptor for the initialization opcode.
797                  * Only try this once. */
798                 initcmdpossible = 0;
799                 ts = FindSyntax(initcmd_opcode, NULL);
800                 if (!ts) {
801                     /*There is no initialization opcode available, so we declare
802                      * an error */
803                     if (ambig) {
804                         fprintf(stderr, "%s", NName(pname, ": "));
805                         fprintf(stderr,
806                                 "Ambiguous operation '%s'; type '%shelp' for list\n",
807                                 argv[1], NName(pname, " "));
808                     } else {
809                         fprintf(stderr, "%s", NName(pname, ": "));
810                         fprintf(stderr,
811                                 "Unrecognized operation '%s'; type '%shelp' for list\n",
812                                 argv[1], NName(pname, " "));
813                     }
814                     code = CMD_UNKNOWNCMD;
815                     goto out;
816                 } else {
817                     /*Found syntax structure for an initialization opcode.  Fix
818                      * up argv and argc to relect what the user
819                      * ``should have'' typed */
820                     if (!(argv = InsertInitOpcode(&argc, argv))) {
821                         fprintf(stderr,
822                                 "%sCan't insert implicit init opcode into command line\n",
823                                 NName(pname, ": "));
824                         code = CMD_INTERNALERROR;
825                         goto out;
826                     }
827                 }
828             } /*Initial opcode not yet attempted */
829             else {
830                 /* init cmd already run and no syntax entry found */
831                 if (ambig) {
832                     fprintf(stderr, "%s", NName(pname, ": "));
833                     fprintf(stderr,
834                             "Ambiguous operation '%s'; type '%shelp' for list\n",
835                             argv[1], NName(pname, " "));
836                 } else {
837                     fprintf(stderr, "%s", NName(pname, ": "));
838                     fprintf(stderr,
839                             "Unrecognized operation '%s'; type '%shelp' for list\n",
840                             argv[1], NName(pname, " "));
841                 }
842                 code = CMD_UNKNOWNCMD;
843                 goto out;
844             }
845         }                       /*Argv[1] is not a valid opcode */
846     }                           /*Opcodes are defined */
847
848     /* Found the descriptor; start parsing.  curType is the type we're
849      * trying to parse */
850     curType = 0;
851
852     /* We start off parsing in "positional" mode, where tokens are put in
853      * slots positionally.  If we find a name that takes args, we go
854      * out of positional mode, and from that point on, expect a switch
855      * before any particular token. */
856
857     positional = enablePositional;      /* Accepting positional cmds ? */
858     i = noOpcodes ? 1 : 2;
859     SetupExpandsFlag(ts);
860     for (; i < argc; i++) {
861         /* Only tokens that start with a hyphen and are not followed by a digit
862          * are considered switches.  This allow negative numbers. */
863         if ((argv[i][0] == '-') && !isdigit(argv[i][1])) {
864             /* Find switch */
865             j = FindType(ts, argv[i]);
866             if (j < 0) {
867                 fprintf(stderr,
868                         "%sUnrecognized or ambiguous switch '%s'; type ",
869                         NName(pname, ": "), argv[i]);
870                 if (noOpcodes)
871                     fprintf(stderr, "'%s -help' for detailed help\n",
872                             argv[0]);
873                 else
874                     fprintf(stderr, "'%shelp %s' for detailed help\n",
875                             NName(argv[0], " "), ts->name);
876                 code = CMD_UNKNOWNSWITCH;
877                 goto out;
878             }
879             if (j >= CMD_MAXPARMS) {
880                 fprintf(stderr, "%sInternal parsing error\n",
881                         NName(pname, ": "));
882                 code = CMD_INTERNALERROR;
883                 goto out;
884             }
885             if (ts->parms[j].type == CMD_FLAG) {
886                 ts->parms[j].items = &dummy;
887             } else {
888                 positional = 0;
889                 curType = j;
890                 ts->parms[j].flags |= CMD_PROCESSED;
891             }
892         } else {
893             /* Try to fit in this descr */
894             if (curType >= CMD_MAXPARMS) {
895                 fprintf(stderr, "%sToo many arguments\n", NName(pname, ": "));
896                 code = CMD_TOOMANY;
897                 goto out;
898             }
899             tparm = &ts->parms[curType];
900
901             if ((tparm->type == 0) ||   /* No option in this slot */
902                 (tparm->type == CMD_FLAG)) {    /* A flag (not an argument */
903                 /* skipped parm slot */
904                 curType++;      /* Skip this slot and reprocess this parm */
905                 i--;
906                 continue;
907             }
908
909             if (!(tparm->flags & CMD_PROCESSED) && (tparm->flags & CMD_HIDE)) {
910                 curType++;      /* Skip this slot and reprocess this parm */
911                 i--;
912                 continue;
913             }
914
915             if (tparm->type == CMD_SINGLE ||
916                 tparm->type == CMD_SINGLE_OR_FLAG) {
917                 if (tparm->items) {
918                     fprintf(stderr, "%sToo many values after switch %s\n",
919                             NName(pname, ": "), tparm->name);
920                     code = CMD_NOTLIST;
921                     goto out;
922                 }
923                 AddItem(tparm, argv[i]);        /* Add to end of list */
924             } else if (tparm->type == CMD_LIST) {
925                 AddItem(tparm, argv[i]);        /* Add to end of list */
926             }
927             /* Now, if we're in positional mode, advance to the next item */
928             if (positional)
929                 curType = AdvanceType(ts, curType);
930         }
931     }
932
933     /* keep track of this for messages */
934     ts->a0name = argv[0];
935
936     /* If we make it here, all the parameters are filled in.  Check to see if
937      * this is a -help version.  Must do this before checking for all
938      * required parms, otherwise it is a real nuisance */
939     if (ts->parms[CMD_HELPPARM].items) {
940         PrintSyntax(ts);
941         /* Display full help syntax if we don't have subcommands */
942         if (noOpcodes)
943             PrintFlagHelp(ts);
944         code = CMD_USAGE;
945         goto out;
946     }
947
948     /* Parsing done, see if we have all of our required parameters */
949     for (i = 0; i < CMD_MAXPARMS; i++) {
950         tparm = &ts->parms[i];
951         if (tparm->type == 0)
952             continue;           /* Skipped parm slot */
953         if ((tparm->flags & CMD_PROCESSED) && tparm->items == 0) {
954             if (tparm->type == CMD_SINGLE_OR_FLAG) {
955                 tparm->items = &dummy;
956             } else {
957                 fprintf(stderr, "%s The field '%s' isn't completed properly\n",
958                     NName(pname, ": "), tparm->name);
959                 code = CMD_TOOFEW;
960                 goto out;
961             }
962         }
963         if (!(tparm->flags & CMD_OPTIONAL) && tparm->items == 0) {
964             fprintf(stderr, "%sMissing required parameter '%s'\n",
965                     NName(pname, ": "), tparm->name);
966             code = CMD_TOOFEW;
967             goto out;
968         }
969         tparm->flags &= ~CMD_PROCESSED;
970     }
971     *outsyntax = ts;
972
973 out:
974     if (code && ts != NULL)
975         ResetSyntax(ts);
976
977     return code;
978 }
979
980 int
981 cmd_Dispatch(int argc, char **argv)
982 {
983     struct cmd_syndesc *ts = NULL;
984     int code;
985
986     code = cmd_Parse(argc, argv, &ts);
987     if (code)
988         return code;
989
990     /*
991      * Before calling the beforeProc and afterProc and all the implications
992      * from those calls, check if the help procedure was called and call it
993      * now.
994      */
995     if ((ts->proc == HelpProc) || (ts->proc == AproposProc)) {
996         code = (*ts->proc) (ts, ts->rock);
997         goto out;
998     }
999
1000     /* Now, we just call the procedure and return */
1001     if (beforeProc)
1002         code = (*beforeProc) (ts, beforeRock);
1003
1004     if (code)
1005         goto out;
1006
1007     code = (*ts->proc) (ts, ts->rock);
1008
1009     if (afterProc)
1010         (*afterProc) (ts, afterRock);
1011 out:
1012     cmd_FreeOptions(&ts);
1013     return code;
1014 }
1015
1016 void
1017 cmd_FreeOptions(struct cmd_syndesc **ts)
1018 {
1019     if (*ts != NULL) {
1020         ResetSyntax(*ts);
1021         *ts = NULL;
1022     }
1023 }
1024
1025 /* free token list returned by parseLine */
1026 static int
1027 FreeTokens(struct cmd_token *alist)
1028 {
1029     struct cmd_token *nlist;
1030     for (; alist; alist = nlist) {
1031         nlist = alist->next;
1032         free(alist->key);
1033         free(alist);
1034     }
1035     return 0;
1036 }
1037
1038 /* free an argv list returned by parseline */
1039 int
1040 cmd_FreeArgv(char **argv)
1041 {
1042     char *tp;
1043     for (tp = *argv; tp; argv++, tp = *argv)
1044         free(tp);
1045     return 0;
1046 }
1047
1048 /* copy back the arg list to the argv array, freeing the cmd_tokens as you go;
1049  * the actual data is still malloc'd, and will be freed when the caller calls
1050  * cmd_FreeArgv later on
1051  */
1052 #define INITSTR ""
1053 static int
1054 CopyBackArgs(struct cmd_token *alist, char **argv,
1055              afs_int32 * an, afs_int32 amaxn)
1056 {
1057     struct cmd_token *next;
1058     afs_int32 count;
1059
1060     count = 0;
1061     if (amaxn <= 1)
1062         return CMD_TOOMANY;
1063     *argv = (char *)malloc(strlen(INITSTR) + 1);
1064     assert(*argv);
1065     strcpy(*argv, INITSTR);
1066     amaxn--;
1067     argv++;
1068     count++;
1069     while (alist) {
1070         if (amaxn <= 1)
1071             return CMD_TOOMANY; /* argv is too small for his many parms. */
1072         *argv = alist->key;
1073         next = alist->next;
1074         free(alist);
1075         alist = next;
1076         amaxn--;
1077         argv++;
1078         count++;
1079     }
1080     *(argv++) = 0;              /* use last slot for terminating null */
1081     /* don't count terminating null */
1082     *an = count;
1083     return 0;
1084 }
1085
1086 static int
1087 quote(int x)
1088 {
1089     if (x == '"' || x == 39 /* single quote */ )
1090         return 1;
1091     else
1092         return 0;
1093 }
1094
1095 static int
1096 space(int x)
1097 {
1098     if (x == 0 || x == ' ' || x == '\t' || x == '\n')
1099         return 1;
1100     else
1101         return 0;
1102 }
1103
1104 int
1105 cmd_ParseLine(char *aline, char **argv, afs_int32 * an, afs_int32 amaxn)
1106 {
1107     char tbuffer[256];
1108     char *tptr = 0;
1109     int inToken, inQuote;
1110     struct cmd_token *first, *last;
1111     struct cmd_token *ttok;
1112     int tc;
1113
1114     inToken = 0;                /* not copying token chars at start */
1115     first = NULL;
1116     last = NULL;
1117     inQuote = 0;                /* not in a quoted string */
1118     while (1) {
1119         tc = *aline++;
1120         if (tc == 0 || (!inQuote && space(tc))) {       /* terminating null gets us in here, too */
1121             if (inToken) {
1122                 inToken = 0;    /* end of this token */
1123                 if (!tptr)
1124                     return -1;  /* should never get here */
1125                 else
1126                     *tptr++ = 0;
1127                 ttok = malloc(sizeof(struct cmd_token));
1128                 assert(ttok);
1129                 ttok->next = NULL;
1130                 ttok->key = malloc(strlen(tbuffer) + 1);
1131                 assert(ttok->key);
1132                 strcpy(ttok->key, tbuffer);
1133                 if (last) {
1134                     last->next = ttok;
1135                     last = ttok;
1136                 } else
1137                     last = ttok;
1138                 if (!first)
1139                     first = ttok;
1140             }
1141         } else {
1142             /* an alpha character */
1143             if (!inToken) {
1144                 tptr = tbuffer;
1145                 inToken = 1;
1146             }
1147             if (tptr - tbuffer >= sizeof(tbuffer)) {
1148                 FreeTokens(first);
1149                 return CMD_TOOBIG;      /* token too long */
1150             }
1151             if (quote(tc)) {
1152                 /* hit a quote, toggle inQuote flag but don't insert character */
1153                 inQuote = !inQuote;
1154             } else {
1155                 /* insert character */
1156                 *tptr++ = tc;
1157             }
1158         }
1159         if (tc == 0) {
1160             /* last token flushed 'cause space(0) --> true */
1161             if (last)
1162                 last->next = NULL;
1163             return CopyBackArgs(first, argv, an, amaxn);
1164         }
1165     }
1166 }
1167
1168 int
1169 cmd_OptionAsInt(struct cmd_syndesc *syn, int pos, int *value)
1170 {
1171     if (pos > syn->nParms)
1172         return CMD_EXCESSPARMS;
1173     if (syn->parms[pos].items == NULL ||
1174         syn->parms[pos].items->data == NULL)
1175         return CMD_MISSING;
1176     if (syn->parms[pos].items == &dummy)
1177         return 0;
1178
1179     *value = strtol(syn->parms[pos].items->data, NULL, 10);
1180
1181     return 0;
1182 }
1183
1184 int
1185 cmd_OptionAsString(struct cmd_syndesc *syn, int pos, char **value)
1186 {
1187     if (pos > syn->nParms)
1188         return CMD_EXCESSPARMS;
1189     if (syn->parms[pos].items == NULL || syn->parms[pos].items->data == NULL)
1190         return CMD_MISSING;
1191     if (syn->parms[pos].items == &dummy)
1192         return 0;
1193
1194     if (*value)
1195         free(*value);
1196
1197     *value = strdup(syn->parms[pos].items->data);
1198
1199     return 0;
1200 }
1201
1202 int
1203 cmd_OptionAsList(struct cmd_syndesc *syn, int pos, struct cmd_item **value)
1204 {
1205     if (pos > syn->nParms)
1206         return CMD_EXCESSPARMS;
1207     if (syn->parms[pos].items == NULL)
1208         return CMD_MISSING;
1209
1210     *value = syn->parms[pos].items;
1211     return 0;
1212 }
1213
1214 int
1215 cmd_OptionAsFlag(struct cmd_syndesc *syn, int pos, int *value)
1216 {
1217     if (pos > syn->nParms)
1218         return CMD_EXCESSPARMS;
1219     if (syn->parms[pos].items == NULL)
1220         return CMD_MISSING;
1221
1222     *value = 1;
1223     return 0;
1224 }
1225
1226 int
1227 cmd_OptionPresent(struct cmd_syndesc *syn, int pos)
1228 {
1229     if (pos > syn->nParms || syn->parms[pos].items == NULL)
1230         return 0;
1231
1232     return 1;
1233 }