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