cmd: Add parameter aliasing
[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:
605         case CMD_LIST:
606             /* free whole list in both cases, just for fun */
607             for (ti = tp->items; ti; ti = ni) {
608                 ni = ti->next;
609                 free(ti->data);
610                 free(ti);
611             }
612             break;
613
614         default:
615             break;
616         }
617         tp->items = NULL;
618     }
619 }
620
621 /* move the expands flag to the last one in the list */
622 static int
623 SetupExpandsFlag(struct cmd_syndesc *as)
624 {
625     struct cmd_parmdesc *tp;
626     int last, i;
627
628     last = -1;
629     /* find last CMD_LIST type parameter, optional or not, and make it expandable
630      * if no other dude is expandable */
631     for (i = 0; i < CMD_MAXPARMS; i++) {
632         tp = &as->parms[i];
633         if (tp->type == CMD_LIST) {
634             if (tp->flags & CMD_EXPANDS)
635                 return 0;       /* done if already specified */
636             last = i;
637         }
638     }
639     if (last >= 0)
640         as->parms[last].flags |= CMD_EXPANDS;
641     return 0;
642 }
643
644 /* Take the current argv & argc and alter them so that the initialization
645  * opcode is made to appear.  This is used in cases where the initialization
646  * opcode is implicitly invoked.*/
647 static char **
648 InsertInitOpcode(int *aargc, char **aargv)
649 {
650     char **newargv;             /*Ptr to new, expanded argv space */
651     char *pinitopcode;          /*Ptr to space for name of init opcode */
652     int i;                      /*Loop counter */
653
654     /* Allocate the new argv array, plus one for the new opcode, plus one
655      * more for the trailing null pointer */
656     newargv = malloc(((*aargc) + 2) * sizeof(char *));
657     if (!newargv) {
658         fprintf(stderr, "%s: Can't create new argv array with %d+2 slots\n",
659                 aargv[0], *aargc);
660         return (NULL);
661     }
662
663     /* Create space for the initial opcode & fill it in */
664     pinitopcode = malloc(sizeof(initcmd_opcode));
665     if (!pinitopcode) {
666         fprintf(stderr, "%s: Can't malloc initial opcode space\n", aargv[0]);
667         free(newargv);
668         return (NULL);
669     }
670     strcpy(pinitopcode, initcmd_opcode);
671
672     /* Move all the items in the old argv into the new argv, in their
673      * proper places */
674     for (i = *aargc; i > 1; i--)
675         newargv[i] = aargv[i - 1];
676
677     /* Slip in the opcode and the trailing null pointer, and bump the
678      * argument count up by one for the new opcode */
679     newargv[0] = aargv[0];
680     newargv[1] = pinitopcode;
681     (*aargc)++;
682     newargv[*aargc] = NULL;
683
684     /* Return the happy news */
685     return (newargv);
686
687 }                               /*InsertInitOpcode */
688
689 static int
690 NoParmsOK(struct cmd_syndesc *as)
691 {
692     int i;
693     struct cmd_parmdesc *td;
694
695     for (i = 0; i < CMD_MAXPARMS; i++) {
696         td = &as->parms[i];
697         if (td->type != 0 && !(td->flags & CMD_OPTIONAL)) {
698             /* found a non-optional (e.g. required) parm, so NoParmsOK
699              * is false (some parms are required) */
700             return 0;
701         }
702     }
703     return 1;
704 }
705
706 /* Add help, apropos commands once */
707 static void
708 initSyntax(void)
709 {
710     struct cmd_syndesc *ts;
711
712     if (!noOpcodes) {
713         ts = cmd_CreateSyntax("help", HelpProc, NULL,
714                               "get help on commands");
715         cmd_AddParm(ts, "-topic", CMD_LIST, CMD_OPTIONAL, "help string");
716         cmd_AddParm(ts, "-admin", CMD_FLAG, CMD_OPTIONAL, NULL);
717
718         ts = cmd_CreateSyntax("apropos", AproposProc, NULL,
719                               "search by help text");
720         cmd_AddParm(ts, "-topic", CMD_SINGLE, CMD_REQUIRED, "help string");
721         ts = cmd_CreateSyntax("version", VersionProc, NULL,
722                               (char *)CMD_HIDDEN);
723         ts = cmd_CreateSyntax("-version", VersionProc, NULL,
724                               (char *)CMD_HIDDEN);
725         ts = cmd_CreateSyntax("-help", HelpProc, 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     }
732 }
733
734 /* Call the appropriate function, or return syntax error code.  Note: if
735  * no opcode is specified, an initialization routine exists, and it has
736  * NOT been called before, we invoke the special initialization opcode
737  */
738 int
739 cmd_Parse(int argc, char **argv, struct cmd_syndesc **outsyntax)
740 {
741     char *pname;
742     struct cmd_syndesc *ts = NULL;
743     struct cmd_parmdesc *tparm;
744     afs_int32 i, j;
745     int curType;
746     int positional;
747     int ambig;
748     int code = 0;
749     static int initd = 0;       /*Is this the first time this routine has been called? */
750     static int initcmdpossible = 1;     /*Should be consider parsing the initial command? */
751
752     *outsyntax = NULL;
753
754     if (!initd) {
755         initd = 1;
756         initSyntax();
757     }
758
759     /*Remember the program name */
760     pname = argv[0];
761
762     if (noOpcodes) {
763         if (argc == 1) {
764             if (!NoParmsOK(allSyntax)) {
765                 printf("%s: Type '%s -help' for help\n", pname, pname);
766                 code = CMD_USAGE;
767                 goto out;
768             }
769         }
770     } else {
771         if (argc < 2) {
772             /* if there is an initcmd, don't print an error message, just
773              * setup to use the initcmd below. */
774             if (!(initcmdpossible && FindSyntax(initcmd_opcode, NULL))) {
775                 printf("%s: Type '%s help' or '%s help <topic>' for help\n",
776                        pname, pname, pname);
777                 code = CMD_USAGE;
778                 goto out;
779             }
780         }
781     }
782
783     /* Find the syntax descriptor for this command, doing prefix matching properly */
784     if (noOpcodes) {
785         ts = allSyntax;
786     } else {
787         ts = (argc < 2 ? 0 : FindSyntax(argv[1], &ambig));
788         if (!ts) {
789             /*First token doesn't match a syntax descriptor */
790             if (initcmdpossible) {
791                 /*If initial command line handling hasn't been done yet,
792                  * see if there is a descriptor for the initialization opcode.
793                  * Only try this once. */
794                 initcmdpossible = 0;
795                 ts = FindSyntax(initcmd_opcode, NULL);
796                 if (!ts) {
797                     /*There is no initialization opcode available, so we declare
798                      * an error */
799                     if (ambig) {
800                         fprintf(stderr, "%s", NName(pname, ": "));
801                         fprintf(stderr,
802                                 "Ambiguous operation '%s'; type '%shelp' for list\n",
803                                 argv[1], NName(pname, " "));
804                     } else {
805                         fprintf(stderr, "%s", NName(pname, ": "));
806                         fprintf(stderr,
807                                 "Unrecognized operation '%s'; type '%shelp' for list\n",
808                                 argv[1], NName(pname, " "));
809                     }
810                     code = CMD_UNKNOWNCMD;
811                     goto out;
812                 } else {
813                     /*Found syntax structure for an initialization opcode.  Fix
814                      * up argv and argc to relect what the user
815                      * ``should have'' typed */
816                     if (!(argv = InsertInitOpcode(&argc, argv))) {
817                         fprintf(stderr,
818                                 "%sCan't insert implicit init opcode into command line\n",
819                                 NName(pname, ": "));
820                         code = CMD_INTERNALERROR;
821                         goto out;
822                     }
823                 }
824             } /*Initial opcode not yet attempted */
825             else {
826                 /* init cmd already run and no syntax entry found */
827                 if (ambig) {
828                     fprintf(stderr, "%s", NName(pname, ": "));
829                     fprintf(stderr,
830                             "Ambiguous operation '%s'; type '%shelp' for list\n",
831                             argv[1], NName(pname, " "));
832                 } else {
833                     fprintf(stderr, "%s", NName(pname, ": "));
834                     fprintf(stderr,
835                             "Unrecognized operation '%s'; type '%shelp' for list\n",
836                             argv[1], NName(pname, " "));
837                 }
838                 code = CMD_UNKNOWNCMD;
839                 goto out;
840             }
841         }                       /*Argv[1] is not a valid opcode */
842     }                           /*Opcodes are defined */
843
844     /* Found the descriptor; start parsing.  curType is the type we're
845      * trying to parse */
846     curType = 0;
847
848     /* We start off parsing in "positional" mode, where tokens are put in
849      * slots positionally.  If we find a name that takes args, we go
850      * out of positional mode, and from that point on, expect a switch
851      * before any particular token. */
852
853     positional = enablePositional;      /* Accepting positional cmds ? */
854     i = noOpcodes ? 1 : 2;
855     SetupExpandsFlag(ts);
856     for (; i < argc; i++) {
857         /* Only tokens that start with a hyphen and are not followed by a digit
858          * are considered switches.  This allow negative numbers. */
859         if ((argv[i][0] == '-') && !isdigit(argv[i][1])) {
860             /* Find switch */
861             j = FindType(ts, argv[i]);
862             if (j < 0) {
863                 fprintf(stderr,
864                         "%sUnrecognized or ambiguous switch '%s'; type ",
865                         NName(pname, ": "), argv[i]);
866                 if (noOpcodes)
867                     fprintf(stderr, "'%s -help' for detailed help\n",
868                             argv[0]);
869                 else
870                     fprintf(stderr, "'%shelp %s' for detailed help\n",
871                             NName(argv[0], " "), ts->name);
872                 code = CMD_UNKNOWNSWITCH;
873                 goto out;
874             }
875             if (j >= CMD_MAXPARMS) {
876                 fprintf(stderr, "%sInternal parsing error\n",
877                         NName(pname, ": "));
878                 code = CMD_INTERNALERROR;
879                 goto out;
880             }
881             if (ts->parms[j].type == CMD_FLAG) {
882                 ts->parms[j].items = &dummy;
883             } else {
884                 positional = 0;
885                 curType = j;
886                 ts->parms[j].flags |= CMD_PROCESSED;
887             }
888         } else {
889             /* Try to fit in this descr */
890             if (curType >= CMD_MAXPARMS) {
891                 fprintf(stderr, "%sToo many arguments\n", NName(pname, ": "));
892                 code = CMD_TOOMANY;
893                 goto out;
894             }
895             tparm = &ts->parms[curType];
896
897             if ((tparm->type == 0) ||   /* No option in this slot */
898                 (tparm->type == CMD_FLAG)) {    /* A flag (not an argument */
899                 /* skipped parm slot */
900                 curType++;      /* Skip this slot and reprocess this parm */
901                 i--;
902                 continue;
903             }
904
905             if (!(tparm->flags & CMD_PROCESSED) && (tparm->flags & CMD_HIDE)) {
906                 curType++;      /* Skip this slot and reprocess this parm */
907                 i--;
908                 continue;
909             }
910
911             if (tparm->type == CMD_SINGLE) {
912                 if (tparm->items) {
913                     fprintf(stderr, "%sToo many values after switch %s\n",
914                             NName(pname, ": "), tparm->name);
915                     code = CMD_NOTLIST;
916                     goto out;
917                 }
918                 AddItem(tparm, argv[i]);        /* Add to end of list */
919             } else if (tparm->type == CMD_LIST) {
920                 AddItem(tparm, argv[i]);        /* Add to end of list */
921             }
922             /* Now, if we're in positional mode, advance to the next item */
923             if (positional)
924                 curType = AdvanceType(ts, curType);
925         }
926     }
927
928     /* keep track of this for messages */
929     ts->a0name = argv[0];
930
931     /* If we make it here, all the parameters are filled in.  Check to see if
932      * this is a -help version.  Must do this before checking for all
933      * required parms, otherwise it is a real nuisance */
934     if (ts->parms[CMD_HELPPARM].items) {
935         PrintSyntax(ts);
936         /* Display full help syntax if we don't have subcommands */
937         if (noOpcodes)
938             PrintFlagHelp(ts);
939         code = CMD_USAGE;
940         goto out;
941     }
942
943     /* Parsing done, see if we have all of our required parameters */
944     for (i = 0; i < CMD_MAXPARMS; i++) {
945         tparm = &ts->parms[i];
946         if (tparm->type == 0)
947             continue;           /* Skipped parm slot */
948         if ((tparm->flags & CMD_PROCESSED) && tparm->items == 0) {
949             fprintf(stderr, "%s The field '%s' isn't completed properly\n",
950                     NName(pname, ": "), tparm->name);
951             code = CMD_TOOFEW;
952             goto out;
953         }
954         if (!(tparm->flags & CMD_OPTIONAL) && tparm->items == 0) {
955             fprintf(stderr, "%sMissing required parameter '%s'\n",
956                     NName(pname, ": "), tparm->name);
957             code = CMD_TOOFEW;
958             goto out;
959         }
960         tparm->flags &= ~CMD_PROCESSED;
961     }
962     *outsyntax = ts;
963
964 out:
965     if (code && ts != NULL)
966         ResetSyntax(ts);
967
968     return code;
969 }
970
971 int
972 cmd_Dispatch(int argc, char **argv)
973 {
974     struct cmd_syndesc *ts = NULL;
975     int code;
976
977     code = cmd_Parse(argc, argv, &ts);
978     if (code)
979         return code;
980
981     /*
982      * Before calling the beforeProc and afterProc and all the implications
983      * from those calls, check if the help procedure was called and call it
984      * now.
985      */
986     if ((ts->proc == HelpProc) || (ts->proc == AproposProc)) {
987         code = (*ts->proc) (ts, ts->rock);
988         goto out;
989     }
990
991     /* Now, we just call the procedure and return */
992     if (beforeProc)
993         code = (*beforeProc) (ts, beforeRock);
994
995     if (code)
996         goto out;
997
998     code = (*ts->proc) (ts, ts->rock);
999
1000     if (afterProc)
1001         (*afterProc) (ts, afterRock);
1002 out:
1003     cmd_FreeOptions(&ts);
1004     return code;
1005 }
1006
1007 void
1008 cmd_FreeOptions(struct cmd_syndesc **ts)
1009 {
1010     if (*ts != NULL) {
1011         ResetSyntax(*ts);
1012         *ts = NULL;
1013     }
1014 }
1015
1016 /* free token list returned by parseLine */
1017 static int
1018 FreeTokens(struct cmd_token *alist)
1019 {
1020     struct cmd_token *nlist;
1021     for (; alist; alist = nlist) {
1022         nlist = alist->next;
1023         free(alist->key);
1024         free(alist);
1025     }
1026     return 0;
1027 }
1028
1029 /* free an argv list returned by parseline */
1030 int
1031 cmd_FreeArgv(char **argv)
1032 {
1033     char *tp;
1034     for (tp = *argv; tp; argv++, tp = *argv)
1035         free(tp);
1036     return 0;
1037 }
1038
1039 /* copy back the arg list to the argv array, freeing the cmd_tokens as you go;
1040  * the actual data is still malloc'd, and will be freed when the caller calls
1041  * cmd_FreeArgv later on
1042  */
1043 #define INITSTR ""
1044 static int
1045 CopyBackArgs(struct cmd_token *alist, char **argv,
1046              afs_int32 * an, afs_int32 amaxn)
1047 {
1048     struct cmd_token *next;
1049     afs_int32 count;
1050
1051     count = 0;
1052     if (amaxn <= 1)
1053         return CMD_TOOMANY;
1054     *argv = (char *)malloc(strlen(INITSTR) + 1);
1055     assert(*argv);
1056     strcpy(*argv, INITSTR);
1057     amaxn--;
1058     argv++;
1059     count++;
1060     while (alist) {
1061         if (amaxn <= 1)
1062             return CMD_TOOMANY; /* argv is too small for his many parms. */
1063         *argv = alist->key;
1064         next = alist->next;
1065         free(alist);
1066         alist = next;
1067         amaxn--;
1068         argv++;
1069         count++;
1070     }
1071     *(argv++) = 0;              /* use last slot for terminating null */
1072     /* don't count terminating null */
1073     *an = count;
1074     return 0;
1075 }
1076
1077 static int
1078 quote(int x)
1079 {
1080     if (x == '"' || x == 39 /* single quote */ )
1081         return 1;
1082     else
1083         return 0;
1084 }
1085
1086 static int
1087 space(int x)
1088 {
1089     if (x == 0 || x == ' ' || x == '\t' || x == '\n')
1090         return 1;
1091     else
1092         return 0;
1093 }
1094
1095 int
1096 cmd_ParseLine(char *aline, char **argv, afs_int32 * an, afs_int32 amaxn)
1097 {
1098     char tbuffer[256];
1099     char *tptr = 0;
1100     int inToken, inQuote;
1101     struct cmd_token *first, *last;
1102     struct cmd_token *ttok;
1103     int tc;
1104
1105     inToken = 0;                /* not copying token chars at start */
1106     first = NULL;
1107     last = NULL;
1108     inQuote = 0;                /* not in a quoted string */
1109     while (1) {
1110         tc = *aline++;
1111         if (tc == 0 || (!inQuote && space(tc))) {       /* terminating null gets us in here, too */
1112             if (inToken) {
1113                 inToken = 0;    /* end of this token */
1114                 if (!tptr)
1115                     return -1;  /* should never get here */
1116                 else
1117                     *tptr++ = 0;
1118                 ttok = malloc(sizeof(struct cmd_token));
1119                 assert(ttok);
1120                 ttok->next = NULL;
1121                 ttok->key = malloc(strlen(tbuffer) + 1);
1122                 assert(ttok->key);
1123                 strcpy(ttok->key, tbuffer);
1124                 if (last) {
1125                     last->next = ttok;
1126                     last = ttok;
1127                 } else
1128                     last = ttok;
1129                 if (!first)
1130                     first = ttok;
1131             }
1132         } else {
1133             /* an alpha character */
1134             if (!inToken) {
1135                 tptr = tbuffer;
1136                 inToken = 1;
1137             }
1138             if (tptr - tbuffer >= sizeof(tbuffer)) {
1139                 FreeTokens(first);
1140                 return CMD_TOOBIG;      /* token too long */
1141             }
1142             if (quote(tc)) {
1143                 /* hit a quote, toggle inQuote flag but don't insert character */
1144                 inQuote = !inQuote;
1145             } else {
1146                 /* insert character */
1147                 *tptr++ = tc;
1148             }
1149         }
1150         if (tc == 0) {
1151             /* last token flushed 'cause space(0) --> true */
1152             if (last)
1153                 last->next = NULL;
1154             return CopyBackArgs(first, argv, an, amaxn);
1155         }
1156     }
1157 }
1158
1159 int
1160 cmd_OptionAsInt(struct cmd_syndesc *syn, int pos, int *value)
1161 {
1162     if (pos > syn->nParms)
1163         return CMD_EXCESSPARMS;
1164     if (syn->parms[pos].items == NULL ||
1165         syn->parms[pos].items->data == NULL)
1166         return CMD_MISSING;
1167     *value = strtol(syn->parms[pos].items->data, NULL, 10);
1168
1169     return 0;
1170 }
1171
1172 int
1173 cmd_OptionAsString(struct cmd_syndesc *syn, int pos, char **value)
1174 {
1175     if (pos > syn->nParms)
1176         return CMD_EXCESSPARMS;
1177     if (syn->parms[pos].items == NULL || syn->parms[pos].items->data == NULL)
1178         return CMD_MISSING;
1179
1180     if (*value)
1181         free(*value);
1182     *value = strdup(syn->parms[pos].items->data);
1183
1184     return 0;
1185 }
1186
1187 int
1188 cmd_OptionAsList(struct cmd_syndesc *syn, int pos, struct cmd_item **value)
1189 {
1190     if (pos > syn->nParms)
1191         return CMD_EXCESSPARMS;
1192     if (syn->parms[pos].items == NULL)
1193         return CMD_MISSING;
1194
1195     *value = syn->parms[pos].items;
1196     return 0;
1197 }
1198
1199 int
1200 cmd_OptionAsFlag(struct cmd_syndesc *syn, int pos, int *value)
1201 {
1202     if (pos > syn->nParms)
1203         return CMD_EXCESSPARMS;
1204     if (syn->parms[pos].items == NULL)
1205         return CMD_MISSING;
1206
1207     *value = 1;
1208     return 0;
1209 }
1210
1211 int
1212 cmd_OptionPresent(struct cmd_syndesc *syn, int pos)
1213 {
1214     if (pos > syn->nParms || syn->parms[pos].items == NULL)
1215         return 0;
1216
1217     return 1;
1218 }