2 * Copyright 2000, International Business Machines Corporation and others.
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
10 #include <afsconfig.h>
11 #include <afs/param.h>
20 /* declaration of private token type */
22 struct cmd_token *next;
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 */
36 /* take name and string, and return null string if name is empty, otherwise return
37 the concatenation of the two strings */
39 NName(char *a1, char *a2)
41 static char tbuffer[300];
42 if (strlen(a1) == 0) {
45 strncpy(tbuffer, a1, sizeof(tbuffer));
46 strncat(tbuffer, a2, sizeof(tbuffer));
47 tbuffer[sizeof(tbuffer)-1]='\0';
52 /* return true if asub is a substring of amain */
54 SubString(char *amain, char *asub)
58 mlen = (int) strlen(amain);
59 slen = (int) strlen(asub);
62 return 0; /* not a substring */
63 for (i = 0; i <= j; i++) {
64 if (strncmp(amain, asub, slen) == 0)
68 return 0; /* didn't find it */
72 FindType(struct cmd_syndesc *as, char *aname)
79 /* Allow --long-style options. */
80 if (aname[0] == '-' && aname[1] == '-' && aname[2] && aname[3]) {
84 cmdlen = strlen(aname);
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)
92 if (strlen(as->parms[i].name) < cmdlen)
94 /* A hidden option must be a full match (no best matches) */
95 if (as->parms[i].flags & CMD_HIDE || !enableAbbreviation)
98 if (strncmp(as->parms[i].name, aname, cmdlen) == 0) {
105 return (ambig ? -1 : best);
108 static struct cmd_syndesc *
109 FindSyntax(char *aname, int *aambig)
111 struct cmd_syndesc *ts;
112 struct cmd_syndesc *best;
116 cmdLen = strlen(aname);
117 best = (struct cmd_syndesc *)0;
120 *aambig = 0; /* initialize to unambiguous */
121 for (ts = allSyntax; ts; ts = ts->next) {
122 if (strcmp(aname, ts->name) == 0)
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)
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.
135 if (best && ts->aliasOf == best->aliasOf)
137 if (strncmp(ts->name, aname, cmdLen) == 0) {
139 ambig = 1; /* ambiguous name */
146 *aambig = ambig; /* if ambiguous and they care, tell them */
147 return (struct cmd_syndesc *)0; /* fails */
149 return best; /* otherwise its not ambiguous, and they know */
152 /* print the help for a single parameter */
154 PrintParmHelp(struct cmd_parmdesc *aparm)
156 if (aparm->type == CMD_FLAG) {
158 /* doc people don't like seeing this information */
160 printf(" (%s)", aparm->help);
162 } else if (aparm->help) {
163 printf(" <%s>", aparm->help);
164 if (aparm->type == CMD_LIST)
166 } else if (aparm->type == CMD_SINGLE)
168 else if (aparm->type == CMD_LIST)
172 extern char *AFSVersion;
175 VersionProc(struct cmd_syndesc *as, void *arock)
177 printf("%s\n", AFSVersion);
182 PrintSyntax(struct cmd_syndesc *as)
185 struct cmd_parmdesc *tp;
187 /* now print usage, from syntax table */
189 printf("Usage: %s", as->a0name);
191 if (!strcmp(as->name, initcmd_opcode))
192 printf("Usage: %s[%s]", NName(as->a0name, " "), as->name);
194 printf("Usage: %s%s", NName(as->a0name, " "), as->name);
197 for (i = 0; i < CMD_MAXPARMS; i++) {
200 continue; /* seeked over slot */
201 if (tp->flags & CMD_HIDE)
202 continue; /* skip hidden options */
204 if (tp->flags & CMD_OPTIONAL)
206 printf("%s", tp->name);
208 if (tp->flags & CMD_OPTIONAL)
214 /* must print newline in any case, to terminate preceding line */
216 PrintAliases(struct cmd_syndesc *as)
218 struct cmd_syndesc *ts;
220 if (as->flags & CMD_ALIAS) {
222 printf("(alias for %s)\n", ts->name);
226 return; /* none, print nothing */
228 for (as = as->nextAlias; as; as = as->nextAlias) {
229 printf("%s ", as->name);
236 PrintFlagHelp(struct cmd_syndesc *as)
239 struct cmd_parmdesc *tp;
243 /* find flag name length */
245 for (i = 0; i < CMD_MAXPARMS; i++) {
246 if (i == CMD_HELPPARM)
249 if (tp->type != CMD_FLAG)
251 if (tp->flags & CMD_HIDE)
252 continue; /* skip hidden options */
256 if (strlen(tp->name) > flag_width)
257 flag_width = strlen(tp->name);
260 /* print flag help */
261 flag_prefix = "Where:";
262 for (i = 0; i < CMD_MAXPARMS; i++) {
263 if (i == CMD_HELPPARM)
266 if (tp->type != CMD_FLAG)
268 if (tp->flags & CMD_HIDE)
269 continue; /* skip hidden options */
273 printf("%-7s%-*s %s\n", flag_prefix, flag_width, tp->name, tp->help);
279 AproposProc(struct cmd_syndesc *as, void *arock)
281 struct cmd_syndesc *ts;
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))
290 if (SubString(ts->help, tsub)) {
291 printf("%s: %s\n", ts->name, ts->help);
293 } else if (SubString(ts->name, tsub)) {
294 printf("%s: %s\n", ts->name, ts->help);
299 printf("Sorry, no commands found\n");
304 HelpProc(struct cmd_syndesc *as, void *arock)
306 struct cmd_syndesc *ts;
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))
316 printf("%-15s %s\n", ts->name, (ts->help ? ts->help : ""));
319 /* print out individual help topics */
320 for (ti = as->parms[0].items; ti; ti = ti->next) {
322 ts = FindSyntax(ti->data, &ambig);
323 if (ts && (ts->flags & CMD_HIDDEN))
324 ts = 0; /* no hidden commands */
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;
335 fprintf(stderr, "%sUnknown topic '%s'\n",
336 NName(as->a0name, ": "), ti->data);
338 /* ambiguous, list 'em all */
340 "%sAmbiguous topic '%s'; use 'apropos' to list\n",
341 NName(as->a0name, ": "), ti->data);
343 code = CMD_UNKNOWNCMD;
351 cmd_SetBeforeProc(int (*aproc) (struct cmd_syndesc * ts, void *beforeRock),
360 cmd_SetAfterProc(int (*aproc) (struct cmd_syndesc * ts, void *afterRock),
368 /* thread on list in alphabetical order */
370 SortSyntax(struct cmd_syndesc *as)
372 struct cmd_syndesc **ld, *ud;
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 */
379 /* thread us on the list now */
386 cmd_CreateSyntax(char *aname,
387 int (*aproc) (struct cmd_syndesc * ts, void *arock),
388 void *arock, char *ahelp)
390 struct cmd_syndesc *td;
392 /* can't have two cmds in no opcode mode */
396 td = calloc(1, sizeof(struct cmd_syndesc));
398 td->aliasOf = td; /* treat aliasOf as pointer to real command, no matter what */
400 /* copy in name, etc */
402 td->name = malloc(strlen(aname) + 1);
404 strcpy(td->name, aname);
410 /* Piggy-back the hidden option onto the help string */
411 if (ahelp == (char *)CMD_HIDDEN) {
412 td->flags |= CMD_HIDDEN;
414 td->help = malloc(strlen(ahelp) + 1);
416 strcpy(td->help, ahelp);
425 cmd_Seek(td, CMD_HELPPARM);
426 cmd_AddParm(td, "-help", CMD_FLAG, CMD_OPTIONAL, "get detailed help");
433 cmd_CreateAlias(struct cmd_syndesc *as, char *aname)
435 struct cmd_syndesc *td;
437 td = malloc(sizeof(struct cmd_syndesc));
439 memcpy(td, as, sizeof(struct cmd_syndesc));
440 td->name = malloc(strlen(aname) + 1);
442 strcpy(td->name, aname);
443 td->flags |= CMD_ALIAS;
444 /* if ever free things, make copy of help string, too */
449 /* thread on alias lists */
450 td->nextAlias = as->nextAlias;
454 return 0; /* all done */
458 cmd_DisablePositionalCommands(void)
460 enablePositional = 0;
464 cmd_DisableAbbreviations(void)
466 enableAbbreviation = 0;
470 cmd_IsAdministratorCommand(struct cmd_syndesc *as)
472 as->flags |= CMD_ADMIN;
477 cmd_Seek(struct cmd_syndesc *as, int apos)
479 if (apos >= CMD_MAXPARMS)
480 return CMD_EXCESSPARMS;
486 cmd_AddParm(struct cmd_syndesc *as, char *aname, int atype,
487 afs_int32 aflags, char *ahelp)
489 struct cmd_parmdesc *tp;
491 if (as->nParms >= CMD_MAXPARMS)
492 return CMD_EXCESSPARMS;
493 tp = &as->parms[as->nParms++];
495 tp->name = malloc(strlen(aname) + 1);
497 strcpy(tp->name, aname);
502 tp->help = malloc(strlen(ahelp) + 1);
504 strcpy(tp->help, ahelp);
510 /* add a text item to the end of the parameter list */
512 AddItem(struct cmd_parmdesc *aparm, char *aval)
514 struct cmd_item *ti, *ni;
515 ti = calloc(1, sizeof(struct cmd_item));
517 ti->data = malloc(strlen(aval) + 1);
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)
524 break; /* skip to last one */
527 aparm->items = ti; /* we're first */
531 /* skip to next non-flag item, if any */
533 AdvanceType(struct cmd_syndesc *as, afs_int32 aval)
536 struct cmd_parmdesc *tp;
538 /* first see if we should try to grab rest of line for this dude */
539 if (as->parms[aval].flags & CMD_EXPANDS)
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)
551 /* discard parameters filled in by dispatch */
553 ResetSyntax(struct cmd_syndesc *as)
556 struct cmd_parmdesc *tp;
557 struct cmd_item *ti, *ni;
560 for (i = 0; i < CMD_MAXPARMS; i++, tp++) {
564 /* free whole list in both cases, just for fun */
565 for (ti = tp->items; ti; ti = ni) {
579 /* move the expands flag to the last one in the list */
581 SetupExpandsFlag(struct cmd_syndesc *as)
583 struct cmd_parmdesc *tp;
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++) {
591 if (tp->type == CMD_LIST) {
592 if (tp->flags & CMD_EXPANDS)
593 return 0; /* done if already specified */
598 as->parms[last].flags |= CMD_EXPANDS;
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.*/
606 InsertInitOpcode(int *aargc, char **aargv)
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 */
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 *));
616 fprintf(stderr, "%s: Can't create new argv array with %d+2 slots\n",
621 /* Create space for the initial opcode & fill it in */
622 pinitopcode = malloc(sizeof(initcmd_opcode));
624 fprintf(stderr, "%s: Can't malloc initial opcode space\n", aargv[0]);
628 strcpy(pinitopcode, initcmd_opcode);
630 /* Move all the items in the old argv into the new argv, in their
632 for (i = *aargc; i > 1; i--)
633 newargv[i] = aargv[i - 1];
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;
640 newargv[*aargc] = NULL;
642 /* Return the happy news */
645 } /*InsertInitOpcode */
648 NoParmsOK(struct cmd_syndesc *as)
651 struct cmd_parmdesc *td;
653 for (i = 0; i < CMD_MAXPARMS; 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) */
664 /* Add help, apropos commands once */
668 struct cmd_syndesc *ts;
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);
676 ts = cmd_CreateSyntax("apropos", AproposProc, NULL,
677 "search by help text");
678 cmd_AddParm(ts, "-topic", CMD_SINGLE, CMD_REQUIRED, "help string");
679 ts = cmd_CreateSyntax("version", VersionProc, NULL,
681 ts = cmd_CreateSyntax("-version", VersionProc, NULL,
683 ts = cmd_CreateSyntax("-help", HelpProc, NULL,
685 ts = cmd_CreateSyntax("--version", VersionProc, NULL,
687 ts = cmd_CreateSyntax("--help", HelpProc, NULL,
692 /* Call the appropriate function, or return syntax error code. Note: if
693 * no opcode is specified, an initialization routine exists, and it has
694 * NOT been called before, we invoke the special initialization opcode
697 cmd_Parse(int argc, char **argv, struct cmd_syndesc **outsyntax)
700 struct cmd_syndesc *ts = NULL;
701 struct cmd_parmdesc *tparm;
707 static int initd = 0; /*Is this the first time this routine has been called? */
708 static int initcmdpossible = 1; /*Should be consider parsing the initial command? */
717 /*Remember the program name */
722 if (!NoParmsOK(allSyntax)) {
723 printf("%s: Type '%s -help' for help\n", pname, pname);
730 /* if there is an initcmd, don't print an error message, just
731 * setup to use the initcmd below. */
732 if (!(initcmdpossible && FindSyntax(initcmd_opcode, NULL))) {
733 printf("%s: Type '%s help' or '%s help <topic>' for help\n",
734 pname, pname, pname);
741 /* Find the syntax descriptor for this command, doing prefix matching properly */
745 ts = (argc < 2 ? 0 : FindSyntax(argv[1], &ambig));
747 /*First token doesn't match a syntax descriptor */
748 if (initcmdpossible) {
749 /*If initial command line handling hasn't been done yet,
750 * see if there is a descriptor for the initialization opcode.
751 * Only try this once. */
753 ts = FindSyntax(initcmd_opcode, NULL);
755 /*There is no initialization opcode available, so we declare
758 fprintf(stderr, "%s", NName(pname, ": "));
760 "Ambiguous operation '%s'; type '%shelp' for list\n",
761 argv[1], NName(pname, " "));
763 fprintf(stderr, "%s", NName(pname, ": "));
765 "Unrecognized operation '%s'; type '%shelp' for list\n",
766 argv[1], NName(pname, " "));
768 code = CMD_UNKNOWNCMD;
771 /*Found syntax structure for an initialization opcode. Fix
772 * up argv and argc to relect what the user
773 * ``should have'' typed */
774 if (!(argv = InsertInitOpcode(&argc, argv))) {
776 "%sCan't insert implicit init opcode into command line\n",
778 code = CMD_INTERNALERROR;
782 } /*Initial opcode not yet attempted */
784 /* init cmd already run and no syntax entry found */
786 fprintf(stderr, "%s", NName(pname, ": "));
788 "Ambiguous operation '%s'; type '%shelp' for list\n",
789 argv[1], NName(pname, " "));
791 fprintf(stderr, "%s", NName(pname, ": "));
793 "Unrecognized operation '%s'; type '%shelp' for list\n",
794 argv[1], NName(pname, " "));
796 code = CMD_UNKNOWNCMD;
799 } /*Argv[1] is not a valid opcode */
800 } /*Opcodes are defined */
802 /* Found the descriptor; start parsing. curType is the type we're
806 /* We start off parsing in "positional" mode, where tokens are put in
807 * slots positionally. If we find a name that takes args, we go
808 * out of positional mode, and from that point on, expect a switch
809 * before any particular token. */
811 positional = enablePositional; /* Accepting positional cmds ? */
812 i = noOpcodes ? 1 : 2;
813 SetupExpandsFlag(ts);
814 for (; i < argc; i++) {
815 /* Only tokens that start with a hyphen and are not followed by a digit
816 * are considered switches. This allow negative numbers. */
817 if ((argv[i][0] == '-') && !isdigit(argv[i][1])) {
819 j = FindType(ts, argv[i]);
822 "%sUnrecognized or ambiguous switch '%s'; type ",
823 NName(pname, ": "), argv[i]);
825 fprintf(stderr, "'%s -help' for detailed help\n",
828 fprintf(stderr, "'%shelp %s' for detailed help\n",
829 NName(argv[0], " "), ts->name);
830 code = CMD_UNKNOWNSWITCH;
833 if (j >= CMD_MAXPARMS) {
834 fprintf(stderr, "%sInternal parsing error\n",
836 code = CMD_INTERNALERROR;
839 if (ts->parms[j].type == CMD_FLAG) {
840 ts->parms[j].items = &dummy;
844 ts->parms[j].flags |= CMD_PROCESSED;
847 /* Try to fit in this descr */
848 if (curType >= CMD_MAXPARMS) {
849 fprintf(stderr, "%sToo many arguments\n", NName(pname, ": "));
853 tparm = &ts->parms[curType];
855 if ((tparm->type == 0) || /* No option in this slot */
856 (tparm->type == CMD_FLAG)) { /* A flag (not an argument */
857 /* skipped parm slot */
858 curType++; /* Skip this slot and reprocess this parm */
863 if (!(tparm->flags & CMD_PROCESSED) && (tparm->flags & CMD_HIDE)) {
864 curType++; /* Skip this slot and reprocess this parm */
869 if (tparm->type == CMD_SINGLE) {
871 fprintf(stderr, "%sToo many values after switch %s\n",
872 NName(pname, ": "), tparm->name);
876 AddItem(tparm, argv[i]); /* Add to end of list */
877 } else if (tparm->type == CMD_LIST) {
878 AddItem(tparm, argv[i]); /* Add to end of list */
880 /* Now, if we're in positional mode, advance to the next item */
882 curType = AdvanceType(ts, curType);
886 /* keep track of this for messages */
887 ts->a0name = argv[0];
889 /* If we make it here, all the parameters are filled in. Check to see if
890 * this is a -help version. Must do this before checking for all
891 * required parms, otherwise it is a real nuisance */
892 if (ts->parms[CMD_HELPPARM].items) {
894 /* Display full help syntax if we don't have subcommands */
901 /* Parsing done, see if we have all of our required parameters */
902 for (i = 0; i < CMD_MAXPARMS; i++) {
903 tparm = &ts->parms[i];
904 if (tparm->type == 0)
905 continue; /* Skipped parm slot */
906 if ((tparm->flags & CMD_PROCESSED) && tparm->items == 0) {
907 fprintf(stderr, "%s The field '%s' isn't completed properly\n",
908 NName(pname, ": "), tparm->name);
912 if (!(tparm->flags & CMD_OPTIONAL) && tparm->items == 0) {
913 fprintf(stderr, "%sMissing required parameter '%s'\n",
914 NName(pname, ": "), tparm->name);
918 tparm->flags &= ~CMD_PROCESSED;
923 if (code && ts != NULL)
930 cmd_Dispatch(int argc, char **argv)
932 struct cmd_syndesc *ts = NULL;
935 code = cmd_Parse(argc, argv, &ts);
940 * Before calling the beforeProc and afterProc and all the implications
941 * from those calls, check if the help procedure was called and call it
944 if ((ts->proc == HelpProc) || (ts->proc == AproposProc)) {
945 code = (*ts->proc) (ts, ts->rock);
949 /* Now, we just call the procedure and return */
951 code = (*beforeProc) (ts, beforeRock);
956 code = (*ts->proc) (ts, ts->rock);
959 (*afterProc) (ts, afterRock);
961 cmd_FreeOptions(&ts);
966 cmd_FreeOptions(struct cmd_syndesc **ts)
974 /* free token list returned by parseLine */
976 FreeTokens(struct cmd_token *alist)
978 struct cmd_token *nlist;
979 for (; alist; alist = nlist) {
987 /* free an argv list returned by parseline */
989 cmd_FreeArgv(char **argv)
992 for (tp = *argv; tp; argv++, tp = *argv)
997 /* copy back the arg list to the argv array, freeing the cmd_tokens as you go;
998 * the actual data is still malloc'd, and will be freed when the caller calls
999 * cmd_FreeArgv later on
1003 CopyBackArgs(struct cmd_token *alist, char **argv,
1004 afs_int32 * an, afs_int32 amaxn)
1006 struct cmd_token *next;
1012 *argv = (char *)malloc(strlen(INITSTR) + 1);
1014 strcpy(*argv, INITSTR);
1020 return CMD_TOOMANY; /* argv is too small for his many parms. */
1029 *(argv++) = 0; /* use last slot for terminating null */
1030 /* don't count terminating null */
1038 if (x == '"' || x == 39 /* single quote */ )
1047 if (x == 0 || x == ' ' || x == '\t' || x == '\n')
1054 cmd_ParseLine(char *aline, char **argv, afs_int32 * an, afs_int32 amaxn)
1058 int inToken, inQuote;
1059 struct cmd_token *first, *last;
1060 struct cmd_token *ttok;
1063 inToken = 0; /* not copying token chars at start */
1066 inQuote = 0; /* not in a quoted string */
1069 if (tc == 0 || (!inQuote && space(tc))) { /* terminating null gets us in here, too */
1071 inToken = 0; /* end of this token */
1073 return -1; /* should never get here */
1076 ttok = malloc(sizeof(struct cmd_token));
1079 ttok->key = malloc(strlen(tbuffer) + 1);
1081 strcpy(ttok->key, tbuffer);
1091 /* an alpha character */
1096 if (tptr - tbuffer >= sizeof(tbuffer)) {
1098 return CMD_TOOBIG; /* token too long */
1101 /* hit a quote, toggle inQuote flag but don't insert character */
1104 /* insert character */
1109 /* last token flushed 'cause space(0) --> true */
1112 return CopyBackArgs(first, argv, an, amaxn);