cmd: Make the original test suite build
[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 NULL;
393
394     td = 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 = 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 = 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 = malloc(sizeof(struct cmd_syndesc));
436     assert(td);
437     memcpy(td, as, sizeof(struct cmd_syndesc));
438     td->name = 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 = 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 = 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 = calloc(1, sizeof(struct cmd_item));
502     assert(ti);
503     ti->data = 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
589  * opcode is made to appear.  This is used in cases where the initialization
590  * 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
599      * more for the trailing null pointer */
600     newargv = malloc(((*aargc) + 2) * sizeof(char *));
601     if (!newargv) {
602         fprintf(stderr, "%s: Can't create new argv array with %d+2 slots\n",
603                 aargv[0], *aargc);
604         return (NULL);
605     }
606
607     /* Create space for the initial opcode & fill it in */
608     pinitopcode = malloc(sizeof(initcmd_opcode));
609     if (!pinitopcode) {
610         fprintf(stderr, "%s: Can't malloc initial opcode space\n", aargv[0]);
611         free(newargv);
612         return (NULL);
613     }
614     strcpy(pinitopcode, initcmd_opcode);
615
616     /* Move all the items in the old argv into the new argv, in their
617      * proper places */
618     for (i = *aargc; i > 1; i--)
619         newargv[i] = aargv[i - 1];
620
621     /* Slip in the opcode and the trailing null pointer, and bump the
622      * argument count up by one for the new opcode */
623     newargv[0] = aargv[0];
624     newargv[1] = pinitopcode;
625     (*aargc)++;
626     newargv[*aargc] = NULL;
627
628     /* Return the happy news */
629     return (newargv);
630
631 }                               /*InsertInitOpcode */
632
633 static int
634 NoParmsOK(struct cmd_syndesc *as)
635 {
636     int i;
637     struct cmd_parmdesc *td;
638
639     for (i = 0; i < CMD_MAXPARMS; i++) {
640         td = &as->parms[i];
641         if (td->type != 0 && !(td->flags & CMD_OPTIONAL)) {
642             /* found a non-optional (e.g. required) parm, so NoParmsOK
643              * is false (some parms are required) */
644             return 0;
645         }
646     }
647     return 1;
648 }
649
650 /* Call the appropriate function, or return syntax error code.  Note: if
651  * no opcode is specified, an initialization routine exists, and it has
652  * NOT been called before, we invoke the special initialization opcode
653  */
654 int
655 cmd_Dispatch(int argc, char **argv)
656 {
657     char *pname;
658     struct cmd_syndesc *ts;
659     struct cmd_parmdesc *tparm;
660     afs_int32 i, j;
661     int curType;
662     int positional;
663     int ambig;
664     static int initd = 0;       /*Is this the first time this routine has been called? */
665     static int initcmdpossible = 1;     /*Should be consider parsing the initial command? */
666
667     if (!initd) {
668         initd = 1;
669         /* Add help, apropos commands once */
670         if (!noOpcodes) {
671             ts = cmd_CreateSyntax("help", HelpProc, NULL,
672                                   "get help on commands");
673             cmd_AddParm(ts, "-topic", CMD_LIST, CMD_OPTIONAL, "help string");
674             cmd_AddParm(ts, "-admin", CMD_FLAG, CMD_OPTIONAL, NULL);
675
676             ts = cmd_CreateSyntax("apropos", AproposProc, NULL,
677                                   "search by help text");
678             cmd_AddParm(ts, "-topic", CMD_SINGLE, CMD_REQUIRED,
679                         "help string");
680             ts = cmd_CreateSyntax("version", VersionProc, NULL,
681                                   (char *)CMD_HIDDEN);
682             ts = cmd_CreateSyntax("-version", VersionProc, NULL,
683                                   (char *)CMD_HIDDEN);
684             ts = cmd_CreateSyntax("-help", HelpProc, NULL,
685                                   (char *)CMD_HIDDEN);
686             ts = cmd_CreateSyntax("--version", VersionProc, NULL,
687                                   (char *)CMD_HIDDEN);
688             ts = cmd_CreateSyntax("--help", HelpProc, NULL,
689                                   (char *)CMD_HIDDEN);
690         }
691     }
692
693     /*Remember the program name */
694     pname = argv[0];
695
696     if (noOpcodes) {
697         if (argc == 1) {
698             if (!NoParmsOK(allSyntax)) {
699                 printf("%s: Type '%s -help' for help\n", pname, pname);
700                 return (CMD_USAGE);
701             }
702         }
703     } else {
704         if (argc < 2) {
705             /* if there is an initcmd, don't print an error message, just
706              * setup to use the initcmd below. */
707             if (!(initcmdpossible && FindSyntax(initcmd_opcode, (int *)0))) {
708                 printf("%s: Type '%s help' or '%s help <topic>' for help\n",
709                        pname, pname, pname);
710                 return (CMD_USAGE);
711             }
712         }
713     }
714
715     /* Find the syntax descriptor for this command, doing prefix matching properly */
716     if (noOpcodes) {
717         ts = allSyntax;
718     } else {
719         ts = (argc < 2 ? 0 : FindSyntax(argv[1], &ambig));
720         if (!ts) {
721             /*First token doesn't match a syntax descriptor */
722             if (initcmdpossible) {
723                 /*If initial command line handling hasn't been done yet,
724                  * see if there is a descriptor for the initialization opcode.
725                  * Only try this once. */
726                 initcmdpossible = 0;
727                 ts = FindSyntax(initcmd_opcode, (int *)0);
728                 if (!ts) {
729                     /*There is no initialization opcode available, so we declare
730                      * an error */
731                     if (ambig) {
732                         fprintf(stderr, "%s", NName(pname, ": "));
733                         fprintf(stderr,
734                                 "Ambiguous operation '%s'; type '%shelp' for list\n",
735                                 argv[1], NName(pname, " "));
736                     } else {
737                         fprintf(stderr, "%s", NName(pname, ": "));
738                         fprintf(stderr,
739                                 "Unrecognized operation '%s'; type '%shelp' for list\n",
740                                 argv[1], NName(pname, " "));
741                     }
742                     return (CMD_UNKNOWNCMD);
743                 } else {
744                     /*Found syntax structure for an initialization opcode.  Fix
745                      * up argv and argc to relect what the user
746                      * ``should have'' typed */
747                     if (!(argv = InsertInitOpcode(&argc, argv))) {
748                         fprintf(stderr,
749                                 "%sCan't insert implicit init opcode into command line\n",
750                                 NName(pname, ": "));
751                         return (CMD_INTERNALERROR);
752                     }
753                 }
754             } /*Initial opcode not yet attempted */
755             else {
756                 /* init cmd already run and no syntax entry found */
757                 if (ambig) {
758                     fprintf(stderr, "%s", NName(pname, ": "));
759                     fprintf(stderr,
760                             "Ambiguous operation '%s'; type '%shelp' for list\n",
761                             argv[1], NName(pname, " "));
762                 } else {
763                     fprintf(stderr, "%s", NName(pname, ": "));
764                     fprintf(stderr,
765                             "Unrecognized operation '%s'; type '%shelp' for list\n",
766                             argv[1], NName(pname, " "));
767                 }
768                 return CMD_UNKNOWNCMD;
769             }
770         }                       /*Argv[1] is not a valid opcode */
771     }                           /*Opcodes are defined */
772
773     /* Found the descriptor; start parsing.  curType is the type we're
774      * trying to parse */
775     curType = 0;
776
777     /* We start off parsing in "positional" mode, where tokens are put in
778      * slots positionally.  If we find a name that takes args, we go
779      * out of positional mode, and from that point on, expect a switch
780      * before any particular token. */
781
782     positional = 1;             /* Are we still in the positional region of the cmd line? */
783     i = noOpcodes ? 1 : 2;
784     SetupExpandsFlag(ts);
785     for (; i < argc; i++) {
786         /* Only tokens that start with a hyphen and are not followed by a digit
787          * are considered switches.  This allow negative numbers. */
788         if ((argv[i][0] == '-') && !isdigit(argv[i][1])) {
789             /* Find switch */
790             j = FindType(ts, argv[i]);
791             if (j < 0) {
792                 fprintf(stderr,
793                         "%sUnrecognized or ambiguous switch '%s'; type ",
794                         NName(pname, ": "), argv[i]);
795                 if (noOpcodes)
796                     fprintf(stderr, "'%s -help' for detailed help\n",
797                             argv[0]);
798                 else
799                     fprintf(stderr, "'%shelp %s' for detailed help\n",
800                             NName(argv[0], " "), ts->name);
801                 ResetSyntax(ts);
802                 return (CMD_UNKNOWNSWITCH);
803             }
804             if (j >= CMD_MAXPARMS) {
805                 fprintf(stderr, "%sInternal parsing error\n",
806                         NName(pname, ": "));
807                 ResetSyntax(ts);
808                 return (CMD_INTERNALERROR);
809             }
810             if (ts->parms[j].type == CMD_FLAG) {
811                 ts->parms[j].items = &dummy;
812             } else {
813                 positional = 0;
814                 curType = j;
815                 ts->parms[j].flags |= CMD_PROCESSED;
816             }
817         } else {
818             /* Try to fit in this descr */
819             if (curType >= CMD_MAXPARMS) {
820                 fprintf(stderr, "%sToo many arguments\n", NName(pname, ": "));
821                 ResetSyntax(ts);
822                 return (CMD_TOOMANY);
823             }
824             tparm = &ts->parms[curType];
825
826             if ((tparm->type == 0) ||   /* No option in this slot */
827                 (tparm->type == CMD_FLAG)) {    /* A flag (not an argument */
828                 /* skipped parm slot */
829                 curType++;      /* Skip this slot and reprocess this parm */
830                 i--;
831                 continue;
832             }
833
834             if (!(tparm->flags & CMD_PROCESSED) && (tparm->flags & CMD_HIDE)) {
835                 curType++;      /* Skip this slot and reprocess this parm */
836                 i--;
837                 continue;
838             }
839
840             if (tparm->type == CMD_SINGLE) {
841                 if (tparm->items) {
842                     fprintf(stderr, "%sToo many values after switch %s\n",
843                             NName(pname, ": "), tparm->name);
844                     ResetSyntax(ts);
845                     return (CMD_NOTLIST);
846                 }
847                 AddItem(tparm, argv[i]);        /* Add to end of list */
848             } else if (tparm->type == CMD_LIST) {
849                 AddItem(tparm, argv[i]);        /* Add to end of list */
850             }
851             /* Now, if we're in positional mode, advance to the next item */
852             if (positional)
853                 curType = AdvanceType(ts, curType);
854         }
855     }
856
857     /* keep track of this for messages */
858     ts->a0name = argv[0];
859
860     /* If we make it here, all the parameters are filled in.  Check to see if
861      * this is a -help version.  Must do this before checking for all
862      * required parms, otherwise it is a real nuisance */
863     if (ts->parms[CMD_HELPPARM].items) {
864         PrintSyntax(ts);
865         /* Display full help syntax if we don't have subcommands */
866         if (noOpcodes)
867             PrintFlagHelp(ts);
868         ResetSyntax(ts);
869         return 0;
870     }
871
872     /* Parsing done, see if we have all of our required parameters */
873     for (i = 0; i < CMD_MAXPARMS; i++) {
874         tparm = &ts->parms[i];
875         if (tparm->type == 0)
876             continue;           /* Skipped parm slot */
877         if ((tparm->flags & CMD_PROCESSED) && tparm->items == 0) {
878             fprintf(stderr, "%s The field '%s' isn't completed properly\n",
879                     NName(pname, ": "), tparm->name);
880             ResetSyntax(ts);
881             tparm->flags &= ~CMD_PROCESSED;
882             return (CMD_TOOFEW);
883         }
884         if (!(tparm->flags & CMD_OPTIONAL) && tparm->items == 0) {
885             fprintf(stderr, "%sMissing required parameter '%s'\n",
886                     NName(pname, ": "), tparm->name);
887             ResetSyntax(ts);
888             tparm->flags &= ~CMD_PROCESSED;
889             return (CMD_TOOFEW);
890         }
891         tparm->flags &= ~CMD_PROCESSED;
892     }
893
894     /*
895      * Before calling the beforeProc and afterProc and all the implications
896      * from those calls, check if the help procedure was called and call it
897      * now.
898      */
899     if ((ts->proc == HelpProc) || (ts->proc == AproposProc)) {
900         i = (*ts->proc) (ts, ts->rock);
901         ResetSyntax(ts);
902         return (i);
903     }
904
905     /* Now, we just call the procedure and return */
906     if (beforeProc)
907         i = (*beforeProc) (ts, beforeRock);
908     else
909         i = 0;
910     if (i) {
911         ResetSyntax(ts);
912         return (i);
913     }
914     i = (*ts->proc) (ts, ts->rock);
915     if (afterProc)
916         (*afterProc) (ts, afterRock);
917     ResetSyntax(ts);            /* Reset and free things */
918     return (i);
919 }
920
921 /* free token list returned by parseLine */
922 static int
923 FreeTokens(struct cmd_token *alist)
924 {
925     struct cmd_token *nlist;
926     for (; alist; alist = nlist) {
927         nlist = alist->next;
928         free(alist->key);
929         free(alist);
930     }
931     return 0;
932 }
933
934 /* free an argv list returned by parseline */
935 int
936 cmd_FreeArgv(char **argv)
937 {
938     char *tp;
939     for (tp = *argv; tp; argv++, tp = *argv)
940         free(tp);
941     return 0;
942 }
943
944 /* copy back the arg list to the argv array, freeing the cmd_tokens as you go;
945  * the actual data is still malloc'd, and will be freed when the caller calls
946  * cmd_FreeArgv later on
947  */
948 #define INITSTR ""
949 static int
950 CopyBackArgs(struct cmd_token *alist, char **argv,
951              afs_int32 * an, afs_int32 amaxn)
952 {
953     struct cmd_token *next;
954     afs_int32 count;
955
956     count = 0;
957     if (amaxn <= 1)
958         return CMD_TOOMANY;
959     *argv = (char *)malloc(strlen(INITSTR) + 1);
960     assert(*argv);
961     strcpy(*argv, INITSTR);
962     amaxn--;
963     argv++;
964     count++;
965     while (alist) {
966         if (amaxn <= 1)
967             return CMD_TOOMANY; /* argv is too small for his many parms. */
968         *argv = alist->key;
969         next = alist->next;
970         free(alist);
971         alist = next;
972         amaxn--;
973         argv++;
974         count++;
975     }
976     *(argv++) = 0;              /* use last slot for terminating null */
977     /* don't count terminating null */
978     *an = count;
979     return 0;
980 }
981
982 static int
983 quote(int x)
984 {
985     if (x == '"' || x == 39 /* single quote */ )
986         return 1;
987     else
988         return 0;
989 }
990
991 static int
992 space(int x)
993 {
994     if (x == 0 || x == ' ' || x == '\t' || x == '\n')
995         return 1;
996     else
997         return 0;
998 }
999
1000 int
1001 cmd_ParseLine(char *aline, char **argv, afs_int32 * an, afs_int32 amaxn)
1002 {
1003     char tbuffer[256];
1004     char *tptr = 0;
1005     int inToken, inQuote;
1006     struct cmd_token *first, *last;
1007     struct cmd_token *ttok;
1008     int tc;
1009
1010     inToken = 0;                /* not copying token chars at start */
1011     first = NULL;
1012     last = NULL;
1013     inQuote = 0;                /* not in a quoted string */
1014     while (1) {
1015         tc = *aline++;
1016         if (tc == 0 || (!inQuote && space(tc))) {       /* terminating null gets us in here, too */
1017             if (inToken) {
1018                 inToken = 0;    /* end of this token */
1019                 if (!tptr)
1020                     return -1;  /* should never get here */
1021                 else
1022                     *tptr++ = 0;
1023                 ttok = malloc(sizeof(struct cmd_token));
1024                 assert(ttok);
1025                 ttok->next = NULL;
1026                 ttok->key = malloc(strlen(tbuffer) + 1);
1027                 assert(ttok->key);
1028                 strcpy(ttok->key, tbuffer);
1029                 if (last) {
1030                     last->next = ttok;
1031                     last = ttok;
1032                 } else
1033                     last = ttok;
1034                 if (!first)
1035                     first = ttok;
1036             }
1037         } else {
1038             /* an alpha character */
1039             if (!inToken) {
1040                 tptr = tbuffer;
1041                 inToken = 1;
1042             }
1043             if (tptr - tbuffer >= sizeof(tbuffer)) {
1044                 FreeTokens(first);
1045                 return CMD_TOOBIG;      /* token too long */
1046             }
1047             if (quote(tc)) {
1048                 /* hit a quote, toggle inQuote flag but don't insert character */
1049                 inQuote = !inQuote;
1050             } else {
1051                 /* insert character */
1052                 *tptr++ = tc;
1053             }
1054         }
1055         if (tc == 0) {
1056             /* last token flushed 'cause space(0) --> true */
1057             if (last)
1058                 last->next = NULL;
1059             return CopyBackArgs(first, argv, an, amaxn);
1060         }
1061     }
1062 }