1 #if (!defined(lint) && !defined(SABER))
2 static char rcsid_module_c[] = "$Header$";
5 /* This is the file utils.c for the MOIRA Client, which allows a nieve
6 * user to quickly and easily maintain most parts of the MOIRA database.
7 * It Contains: Many useful utility functions.
10 * By: Chris D. Peterson
16 * Copyright 1988 by the Massachusetts Institute of Technology.
18 * For further information on copyright and distribution
19 * see the file mit-copyright.h
26 #include <moira_site.h>
30 #include "mit-copyright.h"
34 #include <netdb.h> /* for gethostbyname. */
35 #include <sys/types.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
40 /* Function Name: AddQueue
41 * Description: Adds an element to a queue
42 * Arguments: elem, pred - element and its predecessor.
46 static void AddQueue(struct qelem *elem, struct qelem *pred)
55 elem->q_forw = pred->q_forw;
59 /* Function Name: RemoveQueue
60 * Description: removes an element from a queue.
65 static void RemoveQueue(struct qelem *elem)
68 elem->q_forw->q_back = elem->q_back;
70 elem->q_back->q_forw = elem->q_forw;
74 /* CopyInfo: allocates memory for a copy of a NULL terminated array of
75 * strings <and returns a pointer to the copy.
78 char **CopyInfo(char **info)
83 ret = malloc(sizeof(char *) * (CountArgs(info) + 1));
86 for (i = 0; info[i]; i++)
87 ret[i] = Strsave(info[i]);
93 /* Function Name: FreeInfo
94 * Description: Frees all elements of a NULL terminated arrary of char*'s
95 * Arguments: info - array who's elements we are to free.
99 void FreeInfo(char **info)
102 FreeAndClear(info++, TRUE);
105 /* Function Name: FreeAndClear - I couldn't resist the name.
106 * Description: Clears pointer and optionially frees it.
107 * Arguments: pointer - pointer to work with.
108 * free_it - if TRUE then free pointer.
112 void FreeAndClear(char **pointer, Bool free_it)
121 /* Function Name: QueueTop
122 * Description: returns a qelem pointer that points to the top of
124 * Arguments: elem - any element of a queue.
125 * Returns: top element of a queue.
128 struct qelem *QueueTop(struct qelem *elem)
130 if (!elem) /* NULL returns NULL. */
137 /* Function Name: FreeQueueElem
138 * Description: Frees one element of the queue.
139 * Arguments: elem - the elem to free.
143 static void FreeQueueElem(struct qelem *elem)
145 char **info = (char **) elem->q_data;
149 FreeInfo(info); /* free info fields */
150 free(elem->q_data); /* free info array itself. */
152 RemoveQueue(elem); /* remove this element from the queue */
153 free(elem); /* free its space. */
156 /* Function Name: FreeQueue
157 * Description: Cleans up the queue
158 * Arguments: elem - any element of the queue.
162 void FreeQueue(struct qelem *elem)
164 struct qelem *temp, *local = QueueTop(elem);
168 temp = local->q_forw;
169 FreeQueueElem(local);
174 /* Function Name: QueueCount
175 * Description: Counts the number of elements in a queue
176 * Arguments: elem - any element in the queue.
180 int QueueCount(struct qelem *elem)
183 elem = QueueTop(elem);
192 /* Function Name: StoreInfo
193 * Description: Stores information from an moira query into a queue.
194 * Arguments: argc, argv, - information returned from the query returned
196 * data - the previous element on the queue, this data will be
197 * stored in a qelem struct immediatly after this elem.
198 * If NULL then a new queue will be created. This value
199 * is updated to the current element at the end off the
201 * Returns: MR_CONT, or MR_ABORT if it has problems.
204 int StoreInfo(int argc, char **argv, char *data)
206 char **info = malloc(MAX_ARGS_SIZE * sizeof(char *));
207 struct qelem **old_elem = (struct qelem **) data;
208 struct qelem *new_elem = malloc(sizeof(struct qelem));
211 if (!new_elem || !info)
213 Put_message("Could Not allocate more memory.");
214 FreeQueue(*old_elem);
219 for (count = 0; count < argc; count++)
220 info[count] = Strsave(argv[count]);
221 info[count] = NULL; /* NULL terminate this sucker. */
223 new_elem->q_data = (char *) info;
224 AddQueue(new_elem, *old_elem);
226 *old_elem = new_elem;
230 /* Function Name: CountArgs
231 * Description: Retrieve the number of args in a null terminated
233 * Arguments: info - the argument list.
234 * Returns: number if args in the list.
237 int CountArgs(char **info)
250 /* Function Name: Scream
251 * Description: Bitch Loudly and exit, it is intended as a callback
252 * function for queries that should never return a value.
254 * Returns: doesn't exit.
259 com_err(program_name, 0,
260 "\nA Moira update returned a value -- programmer botch\n");
267 /* Function Name: PromptWithDefault
268 * Description: allows a user to be prompted for input, and given a
270 * Arguments: prompt - the prompt string.
271 * buf, buflen - buffer to be returned and its MAX size?
272 * default value for the answer.
273 * Returns: zero on failure
276 int PromptWithDefault(char *prompt, char *buf, int buflen, char *def)
284 strncpy(buf, parsed_argv[0], buflen);
285 sprintf(tmp, "%s: %s", prompt, buf);
291 sprintf(tmp, "%s [%s]: ", prompt, def ? def : "");
292 ans = Prompt_input(tmp, buf, buflen);
295 else if (!strcmp(buf, "\"\""))
300 /* Function Name: YesNoQuestion
301 * Description: This prompts the user for the answer to a yes-no or
302 * true-false question.
303 * Arguments: prompt - the prompt for the user.
304 * bool_def - the default value either TRUE or FALSE.
305 * Returns: TRUE or FALSE or -1 on error
308 Bool YesNoQuestion(char *prompt, int bool_def)
314 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
325 Put_message("Please answer 'y' or 'n'.");
331 /* Function Name: YesNoQuitQuestion
332 * Description: This prompts the user for the answer to a yes-no or
333 * true-false question, with a quit option.
334 * Arguments: prompt - the prompt for the user.
335 * bool_def - the default value either TRUE or FALSE.
336 * Returns: TRUE or FALSE or -1 on error or QUIT
337 * NOTE: It is not possible to have quit the default, but then I don't
338 * seem to need this functionality.
341 Bool YesNoQuitQuestion(char *prompt, int bool_def)
347 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
361 Put_message("Please answer 'y', 'n' or 'q'.");
367 /* Function Name: Confirm
368 * Description: This function asks the user to confirm the action
369 * he is about to take, used for things like deleting.
370 * Arguments: prompt - the prompt string.
371 * Returns: TRUE/FALSE - wether or not the confirmation occured.
374 Bool Confirm(char *prompt)
376 return !verbose || (YesNoQuestion(prompt, FALSE) == TRUE);
379 /* Function Name: ValidName
380 * Description: This function checks to see if we have a valid list name.
381 * Arguments: s - the list name.
382 * Returns: TRUE if Valid.
385 Bool ValidName(char *s)
388 Put_message("Please use a non-empty name.");
389 else if (strchr(s, ' '))
390 Put_message("You cannot use space (' ') in this name.");
391 else if (strchr(s, '*') || strchr(s, '?'))
392 Put_message("Wildcards not accepted here.");
398 /* Function Name: ToggleVerboseMode
399 * Description: This function toggles the verbose mode.
401 * Returns: DM_NORMAL.
404 int ToggleVerboseMode(void)
409 Put_message("Delete functions will first confirm\n");
411 Put_message("Delete functions will be silent\n");
416 /* Function Name: NullFunc
417 * Description: dummy callback routine
427 /* Function Name: SlipInNewName
428 * Description: Slips the new name into the number 2 slot of a list, and
429 * returns a pointer to the new list.
430 * Arguments: info - list that needs this name slipped into it.
431 * name - the name to slip into the list.
432 * Returns: a pointer to the new list.
433 * NOTE: This screws up the numbers of the elements of the array in a
437 void SlipInNewName(char **info, char *name)
441 /* This also pushes the NULL down. */
442 for (i = CountArgs(info); i > 0; i--)
443 info[i + 1] = info[i];
444 info[1] = name; /* now slip in the name. */
447 /* Function Name: GetValueFromUser
448 * Description: This function gets a value from a user for the field
450 * Arguments: prompt - prompt for user.
451 * pointer - pointer to default value, will be returned
453 * Returns: SUB_ERROR if break hit (^C).
456 int GetValueFromUser(char *prompt, char **pointer)
460 if (PromptWithDefault(prompt, buf, BUFSIZ, *pointer) == 0)
464 * If these are the same then there is no need to allocate a new string.
466 * a difference that makes no difference, IS no difference.
471 if (strcmp(buf, *pointer))
474 *pointer = Strsave(buf);
480 /* Function Name: GetYesNoValueFromUser
481 * Description: This function gets a value from a user for the field
483 * Arguments: prompt - prompt for user.
484 * pointer - pointer to default value, will be returned
486 * Returns: SUB_ERROR if break hit (^C).
489 int GetYesNoValueFromUser(char *prompt, char **pointer)
491 char user_prompt[BUFSIZ];
494 if (!strcmp(*pointer, DEFAULT_YES))
499 sprintf(user_prompt, "%s (y/n)", prompt);
501 switch (YesNoQuestion(user_prompt, default_val))
506 *pointer = Strsave(DEFAULT_YES);
511 *pointer = Strsave(DEFAULT_NO);
520 /* Function Name: GetFSVal
521 * Description: asks about a specific filesystem value.
522 * Arguments: name - string for this type of filesystem.
523 * mask - mask for this type of filesystem.
524 * current - current filesystem state. (for defaults).
525 * new - new filesystem state.
526 * Returns: TRUE if successful.
529 static Bool GetFSVal(char *name, int mask, int current, int *new)
531 char temp_buf[BUFSIZ];
532 sprintf(temp_buf, "Is this a %s filsystem", name);
533 switch (YesNoQuestion(temp_buf, ((mask & current) == mask)))
539 break; /* zero by default. */
546 /* Function Name: GetFSTypes
547 * Description: Allows user to specify filsystem types.
548 * Arguments: current - current value of filsystem, freed here.
549 * Returns: SUB_ERROR on ^C.
552 int GetFSTypes(char **current, int options)
554 int c_value, new_val = 0; /* current value of filesys type (int). */
555 char ret_value[BUFSIZ];
560 c_value = atoi(*current);
562 if (GetFSVal("student", MR_FS_STUDENT, c_value, &new_val) == FALSE)
564 if (GetFSVal("faculty", MR_FS_FACULTY, c_value, &new_val) == FALSE)
566 if (GetFSVal("staff", MR_FS_STAFF, c_value, &new_val) == FALSE)
568 if (GetFSVal("miscellaneous", MR_FS_MISC, c_value, &new_val) == FALSE)
572 if (GetFSVal("Group Quotas", MR_FS_GROUPQUOTA, c_value, &new_val) ==
577 FreeAndClear(current, TRUE);
578 sprintf(ret_value, "%d", new_val);
579 *current = Strsave(ret_value);
583 /* Function Name: Strsave
584 * Description: save a string.
585 * Arguments: string - the string to save.
586 * Returns: The malloced string, now safely saved, or NULL.
589 char *Strsave(char *str)
591 char *newstr = malloc(strlen(str) + 1);
596 return strcpy(newstr, str);
600 /* atot: convert ASCII integer unix time into human readable date string */
602 char *atot(char *itime)
607 time = (time_t) atoi(itime);
614 /* Function Name: Print
615 * Description: prints out all the arguments on a single line.
616 * Arguments: argc, argv - the standard MR arguments.
617 * callback - the callback function - NOT USED.
621 int Print(int argc, char **argv, char *callback)
627 strcpy(buf, argv[0]); /* no newline 'cause Put_message adds one */
628 for (i = 1; i < argc; i++)
629 sprintf(buf, "%s %s", buf, argv[i]);
635 /* Function Name: PrintByType
636 * Description: This function prints all members of the type specified
637 * by the callback arg, unless the callback is NULL, in which
638 * case it prints all members.
639 * Arguments: argc, argc - normal arguments for mr_callback function.
640 * callback - either a type of member or NULL.
641 * Returns: MR_CONT or MR_QUIT.
644 int PrintByType(int argc, char **argv, char *callback)
647 return Print(argc, argv, callback);
648 if (!strcmp(argv[0], callback))
649 return Print(argc, argv, callback);
653 /* Function Name: PrintHelp
654 * Description: Prints Help Information in a NULL terminated
656 * Arguments: message.
657 * Returns: DM_NORMAL.
660 int PrintHelp(char **message)
664 for (i = 0; i < CountArgs(message); i++)
665 Put_message(message[i]);
670 /* Function Name: Loop
671 * Description: This function goes through the entire queue, and
672 * and executes the given function on each element.
673 * Arguments: elem - top element of the queue.
674 * func - the function to execute.
678 void Loop(struct qelem *elem, FVoid func)
682 char **info = (char **) elem->q_data;
689 /* Function Name: QueryLoop
690 * Description: This functions loops through a queue containing
691 * information about some item that we want to perform
692 * an operation on, and then calls the correct routine
693 * perform that operation.
694 * Arguments: top - top of the queue of information.
695 * print_func - print function.
696 * op_function - operation to be performed.
697 * query_string - string the prompts the user whether or not
698 * to perform this operation.
701 * print_opt - should expect one arguent, the info array
703 * is expected to return the name of the item.
704 * op_func - should expect two arguments.
705 * 1) the info array of char *'s.
706 * 2) a boolean the is true if there only
707 * one item in this queue, used for delete
709 * query_string - this should be of such a form that when the
710 * name of the object and '(y/n/q) ?' are appended
711 * then it should still make sense, an example is
715 void QueryLoop(struct qelem *elem, FCharStar print_func,
716 FVoid op_func, char *query_string)
719 char temp_buf[BUFSIZ], *name;
721 elem = QueueTop(elem);
722 one_item = (QueueCount(elem) == 1);
725 char **info = (char **) elem->q_data;
728 (*op_func) (info, one_item);
731 name = (*print_func) (info); /* call print function. */
732 sprintf(temp_buf, "%s %s (y/n/q)", query_string, name);
733 switch (YesNoQuitQuestion(temp_buf, FALSE))
736 (*op_func) (info, one_item);
741 Put_message("Aborting...");
749 /* Function Name: NullPrint
750 * Description: print function that returns nothing.
751 * Arguments: info - a pointer to the info array - Not used.
755 char *NullPrint(char **info)
761 /* Function Name: GetTypeValues
762 * Description: gets legal values for a typed object, keeping a cache
763 * Arguments: type name
764 * Returns: argv of values
767 struct qelem *GetTypeValues(char *tname)
770 char *argv[3], *p, **pp, *strsave();
771 struct qelem *elem, *oelem;
772 static struct qelem *cache = NULL;
775 struct qelem *cache_data;
778 for (elem = cache; elem; elem = elem->q_forw)
780 ce = (struct cache_elem *) elem->q_data;
781 if (!strcmp(ce->cache_name, tname))
782 return ce->cache_data;
789 if ((stat = do_mr_query("get_alias", 3, argv, StoreInfo, (char *)&elem)))
791 com_err(program_name, stat, " in GetTypeValues");
795 for (elem = QueueTop(elem); elem; elem = elem->q_forw)
797 pp = (char **) elem->q_data;
802 elem = malloc(sizeof(struct qelem));
803 ce = malloc(sizeof(struct cache_elem));
804 ce->cache_name = strsave(tname);
805 ce->cache_data = QueueTop(oelem);
806 elem->q_data = (char *) ce;
807 AddQueue(elem, cache);
808 cache = QueueTop(elem);
809 return ce->cache_data;
813 /* Function Name: GetTypeFromUser
814 * Description: gets a typed value from the user
815 * Arguments: prompt string, type name, buffer pointer
816 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
819 int GetTypeFromUser(char *prompt, char *tname, char **pointer)
821 char def[BUFSIZ], buffer[BUFSIZ], *p, *argv[3];
825 strcpy(def, *pointer);
826 strcpy(buffer, prompt);
827 strcat(buffer, " (");
828 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
830 strcat(buffer, elem->q_data);
832 strcat(buffer, ", ");
835 if (strlen(buffer) > 64)
836 sprintf(buffer, "%s (? for help)", prompt);
837 if (GetValueFromUser(buffer, pointer) == SUB_ERROR)
839 if (**pointer == '?')
841 sprintf(buffer, "Type %s is one of:", tname);
843 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
844 Put_message(elem->q_data);
845 *pointer = strsave(def);
846 return GetTypeFromUser(prompt, tname, pointer);
848 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
850 if (!strcasecmp(elem->q_data, *pointer))
852 strcpy(*pointer, elem->q_data);
856 sprintf(buffer, "\"%s\" is not a legal value for %s. Use one of:",
859 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
860 Put_message(elem->q_data);
861 sprintf(buffer, "Are you sure you want \"%s\" to be a legal %s",
863 if (YesNoQuestion("Do you want this to be a new legal value", 0) == TRUE &&
864 YesNoQuestion(buffer, 0) == TRUE)
869 /* don't uppercase access flags. Do uppercase everything else */
870 if (strncmp(tname, "fs_access", 9))
872 for (p = argv[2]; *p; p++)
878 if ((stat = do_mr_query("add_alias", 3, argv, Scream, NULL)))
879 com_err(program_name, stat, " in add_alias");
882 elem = malloc(sizeof(struct qelem));
883 elem->q_data = strsave(*pointer);
884 AddQueue(elem, GetTypeValues(tname));
885 Put_message("Done.");
888 *pointer = strsave(def);
889 return GetTypeFromUser(prompt, tname, pointer);
893 /* Function Name: GetAddressFromUser
894 * Description: gets an IP address from the user
895 * Arguments: prompt string, buffer pointer
896 * buffer contains default value as long int
897 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
900 int GetAddressFromUser(char *prompt, char **pointer)
902 char *value, buf[256];
906 addr.s_addr = htonl(atoi(*pointer));
907 value = strsave(inet_ntoa(addr));
908 ret = GetValueFromUser(prompt, &value);
909 if (ret == SUB_ERROR)
911 addr.s_addr = inet_addr(value);
913 sprintf(buf, "%d", ntohl(addr.s_addr));
914 *pointer = strsave(buf);
919 int do_mr_query(char *name, int argc, char **argv, int (*proc)(), char *hint)
922 extern char *whoami, *moira_server;
925 status = mr_query(name, argc, argv, proc, hint);
926 if (status != MR_ABORTED && status != MR_NOT_CONNECTED)
928 status = mr_connect(moira_server);
931 com_err(whoami, status, " while re-connecting to server %s",
935 status = mr_auth(whoami);
938 com_err(whoami, status, " while re-authenticating to server %s",
943 status = mr_query(name, argc, argv, proc, hint);