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