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