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