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