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