3 * This is the file utils.c for the Moira Client, which allows users
4 * to quickly and easily maintain most parts of the Moira database.
5 * It Contains: Many useful utility functions.
8 * By: Chris D. Peterson
10 * Copyright (C) 1988-1998 by the Massachusetts Institute of Technology.
11 * For copying and distribution information, please see the file
15 #include <mit-copyright.h>
17 #include <moira_site.h>
22 #include <sys/types.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
27 #include <netdb.h> /* for gethostbyname. */
38 /* Function Name: AddQueue
39 * Description: Adds an element to a queue
40 * Arguments: elem, pred - element and its predecessor.
44 void AddQueue(struct mqelem *elem, struct mqelem *pred)
53 elem->q_forw = pred->q_forw;
57 /* Function Name: RemoveQueue
58 * Description: removes an element from a queue.
63 static void RemoveQueue(struct mqelem *elem)
66 elem->q_forw->q_back = elem->q_back;
68 elem->q_back->q_forw = elem->q_forw;
72 /* CopyInfo: allocates memory for a copy of a NULL terminated array of
73 * strings <and returns a pointer to the copy.
76 char **CopyInfo(char **info)
81 ret = malloc(sizeof(char *) * (CountArgs(info) + 1));
84 for (i = 0; info[i]; i++)
85 ret[i] = strdup(info[i]);
91 /* Function Name: FreeInfo
92 * Description: Frees all elements of a NULL terminated arrary of char*'s
93 * Arguments: info - array who's elements we are to free.
97 void FreeInfo(char **info)
100 FreeAndClear(info++, TRUE);
103 /* Function Name: FreeAndClear - I couldn't resist the name.
104 * Description: Clears pointer and optionially frees it.
105 * Arguments: pointer - pointer to work with.
106 * free_it - if TRUE then free pointer.
110 void FreeAndClear(char **pointer, Bool free_it)
119 /* Function Name: QueueTop
120 * Description: returns a mqelem pointer that points to the top of
122 * Arguments: elem - any element of a queue.
123 * Returns: top element of a queue.
126 struct mqelem *QueueTop(struct mqelem *elem)
128 if (!elem) /* NULL returns NULL. */
135 /* Function Name: FreeQueueElem
136 * Description: Frees one element of the queue.
137 * Arguments: elem - the elem to free.
141 static void FreeQueueElem(struct mqelem *elem)
143 char **info = elem->q_data;
147 FreeInfo(info); /* free info fields */
148 free(elem->q_data); /* free info array itself. */
150 RemoveQueue(elem); /* remove this element from the queue */
151 free(elem); /* free its space. */
154 /* Function Name: FreeQueue
155 * Description: Cleans up the queue
156 * Arguments: elem - any element of the queue.
160 void FreeQueue(struct mqelem *elem)
162 struct mqelem *temp, *local = QueueTop(elem);
166 temp = local->q_forw;
167 FreeQueueElem(local);
172 /* Function Name: QueueCount
173 * Description: Counts the number of elements in a queue
174 * Arguments: elem - any element in the queue.
178 int QueueCount(struct mqelem *elem)
181 elem = QueueTop(elem);
190 /* Function Name: StoreInfo
191 * Description: Stores information from a moira query into a queue.
192 * Arguments: argc, argv, - information returned from the query returned
194 * data - the previous element on the queue, this data will be
195 * stored in a mqelem struct immediatly after this elem.
196 * If NULL then a new queue will be created. This value
197 * is updated to the current element at the end off the
199 * Returns: MR_CONT, or MR_ABORT if it has problems.
202 int StoreInfo(int argc, char **argv, void *data)
204 char **info = malloc(MAX_ARGS_SIZE * sizeof(char *));
205 struct mqelem **old_elem = data;
206 struct mqelem *new_elem = malloc(sizeof(struct mqelem));
209 if (!new_elem || !info)
211 Put_message("Could Not allocate more memory.");
212 FreeQueue(*old_elem);
217 for (count = 0; count < argc; count++)
218 info[count] = strdup(argv[count]);
219 info[count] = NULL; /* NULL terminate this sucker. */
221 new_elem->q_data = info;
222 AddQueue(new_elem, *old_elem);
224 *old_elem = new_elem;
228 /* Function Name: CountArgs
229 * Description: Retrieve the number of args in a null terminated
231 * Arguments: info - the argument list.
232 * Returns: number if args in the list.
235 int CountArgs(char **info)
248 /* Function Name: PromptWithDefault
249 * Description: allows a user to be prompted for input, and given a
251 * Arguments: prompt - the prompt string.
252 * buf, buflen - buffer to be returned and its MAX size?
253 * default value for the answer.
254 * Returns: zero on failure
257 int PromptWithDefault(char *prompt, char *buf, int buflen, char *def)
265 strncpy(buf, parsed_argv[0], buflen);
266 sprintf(tmp, "%s: %s", prompt, buf);
272 sprintf(tmp, "%s [%s]: ", prompt, def ? def : "");
273 ans = Prompt_input(tmp, buf, buflen);
276 else if (!strcmp(buf, "\"\""))
281 /* Function Name: YesNoQuestion
282 * Description: This prompts the user for the answer to a yes-no or
283 * true-false question.
284 * Arguments: prompt - the prompt for the user.
285 * bool_def - the default value either TRUE or FALSE.
286 * Returns: TRUE or FALSE or -1 on error
289 Bool YesNoQuestion(char *prompt, int bool_def)
295 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
306 Put_message("Please answer 'y' or 'n'.");
312 /* Function Name: YesNoQuitQuestion
313 * Description: This prompts the user for the answer to a yes-no or
314 * true-false question, with a quit option.
315 * Arguments: prompt - the prompt for the user.
316 * bool_def - the default value either TRUE or FALSE.
317 * Returns: TRUE or FALSE or -1 on error or QUIT
318 * NOTE: It is not possible to have quit the default, but then I don't
319 * seem to need this functionality.
322 Bool YesNoQuitQuestion(char *prompt, int bool_def)
328 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
342 Put_message("Please answer 'y', 'n' or 'q'.");
348 /* Function Name: Confirm
349 * Description: This function asks the user to confirm the action
350 * he is about to take, used for things like deleting.
351 * Arguments: prompt - the prompt string.
352 * Returns: TRUE/FALSE - wether or not the confirmation occured.
355 Bool Confirm(char *prompt)
357 return !verbose || (YesNoQuestion(prompt, FALSE) == TRUE);
360 /* Function Name: ValidName
361 * Description: This function checks to see if we have a valid list name.
362 * Arguments: s - the list name.
363 * Returns: TRUE if Valid.
366 Bool ValidName(char *s)
369 Put_message("Please use a non-empty name.");
370 else if (strchr(s, ' '))
371 Put_message("You cannot use space (' ') in this name.");
372 else if (strchr(s, '*') || strchr(s, '?'))
373 Put_message("Wildcards not accepted here.");
379 /* Function Name: ToggleVerboseMode
380 * Description: This function toggles the verbose mode.
382 * Returns: DM_NORMAL.
385 int ToggleVerboseMode(int argc, char **argv)
390 Put_message("Delete functions will first confirm");
392 Put_message("Delete functions will be silent");
397 /* Function Name: SlipInNewName
398 * Description: Slips the new name into the number 2 slot of a list, and
399 * returns a pointer to the new list.
400 * Arguments: info - list that needs this name slipped into it.
401 * name - the name to slip into the list.
402 * Returns: a pointer to the new list.
403 * NOTE: This screws up the numbers of the elements of the array in a
407 void SlipInNewName(char **info, char *name)
411 /* This also pushes the NULL down. */
412 for (i = CountArgs(info); i > 0; i--)
413 info[i + 1] = info[i];
414 info[1] = name; /* now slip in the name. */
417 /* Function Name: GetValueFromUser
418 * Description: This function gets a value from a user for the field
420 * Arguments: prompt - prompt for user.
421 * pointer - pointer to default value, will be returned
423 * Returns: SUB_ERROR if break hit (^C).
426 int GetValueFromUser(char *prompt, char **pointer)
430 if (PromptWithDefault(prompt, buf, BUFSIZ, *pointer) == 0)
434 * If these are the same then there is no need to allocate a new string.
436 * a difference that makes no difference, IS no difference.
441 if (strcmp(buf, *pointer))
444 *pointer = strdup(buf);
450 /* Function Name: GetYesNoValueFromUser
451 * Description: This function gets a value from a user for the field
453 * Arguments: prompt - prompt for user.
454 * pointer - pointer to default value, will be returned
456 * Returns: SUB_ERROR if break hit (^C).
459 int GetYesNoValueFromUser(char *prompt, char **pointer)
461 char user_prompt[BUFSIZ];
464 if (!strcmp(*pointer, DEFAULT_YES))
469 sprintf(user_prompt, "%s (y/n)", prompt);
471 switch (YesNoQuestion(user_prompt, default_val))
476 *pointer = strdup(DEFAULT_YES);
481 *pointer = strdup(DEFAULT_NO);
490 /* Function Name: GetFSVal
491 * Description: asks about a specific filesystem value.
492 * Arguments: name - string for this type of filesystem.
493 * mask - mask for this type of filesystem.
494 * current - current filesystem state. (for defaults).
495 * new - new filesystem state.
496 * Returns: TRUE if successful.
499 static Bool GetFSVal(char *name, int mask, int current, int *new)
501 char temp_buf[BUFSIZ];
502 sprintf(temp_buf, "Is this a %s filsystem", name);
503 switch (YesNoQuestion(temp_buf, ((mask & current) == mask)))
509 break; /* zero by default. */
516 /* Function Name: GetFSTypes
517 * Description: Allows user to specify filsystem types.
518 * Arguments: current - current value of filsystem, freed here.
519 * Returns: SUB_ERROR on ^C.
522 int GetFSTypes(char **current, int options)
524 int c_value, new_val = 0; /* current value of filesys type (int). */
525 char ret_value[BUFSIZ];
530 c_value = atoi(*current);
532 if (GetFSVal("student", MR_FS_STUDENT, c_value, &new_val) == FALSE)
534 if (GetFSVal("faculty", MR_FS_FACULTY, c_value, &new_val) == FALSE)
536 if (GetFSVal("staff", MR_FS_STAFF, c_value, &new_val) == FALSE)
538 if (GetFSVal("miscellaneous", MR_FS_MISC, c_value, &new_val) == FALSE)
542 if (GetFSVal("Group Quotas", MR_FS_GROUPQUOTA, c_value, &new_val) ==
547 FreeAndClear(current, TRUE);
548 sprintf(ret_value, "%d", new_val);
549 *current = strdup(ret_value);
553 /* atot: convert ASCII integer unix time into human readable date string */
555 char *atot(char *itime)
560 time = (time_t) atoi(itime);
567 /* Function Name: Print
568 * Description: prints out all the arguments on a single line.
569 * Arguments: argc, argv - the standard Moira arguments.
570 * callback - the callback function - NOT USED.
574 int Print(int argc, char **argv, void *callback)
580 strcpy(buf, argv[0]); /* no newline 'cause Put_message adds one */
581 for (i = 1; i < argc; i++)
582 sprintf(buf, "%s %s", buf, argv[i]);
588 /* Function Name: PrintByType
589 * Description: This function prints all members of the type specified
590 * by the callback arg, unless the callback is NULL, in which
591 * case it prints all members.
592 * Arguments: argc, argc - normal arguments for mr_callback function.
593 * callback - either a type of member or NULL.
594 * Returns: MR_CONT or MR_QUIT.
597 int PrintByType(int argc, char **argv, void *callback)
600 return Print(argc, argv, callback);
601 if (!strcmp(argv[0], callback))
602 return Print(argc, argv, callback);
606 /* Function Name: PrintHelp
607 * Description: Prints Help Information in a NULL terminated
609 * Arguments: message.
610 * Returns: DM_NORMAL.
613 int PrintHelp(char **message)
617 for (i = 0; i < CountArgs(message); i++)
618 Put_message(message[i]);
623 /* Function Name: Loop
624 * Description: This function goes through the entire queue, and
625 * and executes the given function on each element.
626 * Arguments: elem - top element of the queue.
627 * func - the function to execute.
631 void Loop(struct mqelem *elem, void (*func)(char **))
635 (*func) (elem->q_data);
641 /* Function Name: QueryLoop
642 * Description: This functions loops through a queue containing
643 * information about some item that we want to perform
644 * an operation on, and then calls the correct routine
645 * perform that operation.
646 * Arguments: top - top of the queue of information.
647 * print_func - print function.
648 * op_function - operation to be performed.
649 * query_string - string the prompts the user whether or not
650 * to perform this operation.
653 * print_opt - should expect one arguent, the info array
655 * is expected to return the name of the item.
656 * op_func - should expect two arguments.
657 * 1) the info array of char *'s.
658 * 2) a boolean the is true if there only
659 * one item in this queue, used for delete
661 * query_string - this should be of such a form that when the
662 * name of the object and '(y/n/q) ?' are appended
663 * then it should still make sense, an example is
667 void QueryLoop(struct mqelem *elem, char * (*print_func)(char **),
668 void (*op_func)(char **, Bool), char *query_string)
671 char temp_buf[BUFSIZ], *name;
673 elem = QueueTop(elem);
674 one_item = (QueueCount(elem) == 1);
677 char **info = elem->q_data;
680 (*op_func) (info, one_item);
683 name = (*print_func) (info); /* call print function. */
684 sprintf(temp_buf, "%s %s (y/n/q)", query_string, name);
685 switch (YesNoQuitQuestion(temp_buf, FALSE))
688 (*op_func) (info, one_item);
693 Put_message("Aborting...");
701 /* Function Name: NullPrint
702 * Description: print function that returns nothing.
703 * Arguments: info - a pointer to the info array - Not used.
707 char *NullPrint(char **info)
713 /* Function Name: GetTypeValues
714 * Description: gets legal values for a typed object, keeping a cache
715 * Arguments: type name
716 * Returns: argv of values
719 struct mqelem *GetTypeValues(char *tname)
722 char *argv[3], *p, **pp;
723 struct mqelem *elem, *oelem;
724 static struct mqelem *cache = NULL;
727 struct mqelem *cache_data;
730 for (elem = cache; elem; elem = elem->q_forw)
733 if (!strcmp(ce->cache_name, tname))
734 return ce->cache_data;
741 if ((stat = do_mr_query("get_alias", 3, argv, StoreInfo, &elem)))
743 com_err(program_name, stat, " in GetTypeValues");
747 for (elem = QueueTop(elem); elem; elem = elem->q_forw)
754 elem = malloc(sizeof(struct mqelem));
755 ce = malloc(sizeof(struct cache_elem));
756 ce->cache_name = strdup(tname);
757 ce->cache_data = QueueTop(oelem);
759 AddQueue(elem, cache);
760 cache = QueueTop(elem);
761 return ce->cache_data;
765 /* Function Name: GetTypeFromUser
766 * Description: gets a typed value from the user
767 * Arguments: prompt string, type name, buffer pointer
768 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
771 int GetTypeFromUser(char *prompt, char *tname, char **pointer)
773 char def[BUFSIZ], buffer[BUFSIZ], *p, *argv[3];
777 strcpy(def, *pointer);
778 strcpy(buffer, prompt);
779 strcat(buffer, " (");
780 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
782 /* Make sure we don't blow up and get too long a prompt */
783 if (strlen(buffer) > 64)
785 strcat(buffer, elem->q_data);
787 strcat(buffer, ", ");
790 /* Trim the prompt if it is too long */
791 if (strlen(buffer) > 64)
792 sprintf(buffer, "%s (? for help)", prompt);
793 if (GetValueFromUser(buffer, pointer) == SUB_ERROR)
795 if (**pointer == '?')
797 sprintf(buffer, "Type %s is one of:", tname);
799 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
800 Put_message(elem->q_data);
801 *pointer = strdup(def);
802 return GetTypeFromUser(prompt, tname, pointer);
804 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
806 if (!strcasecmp(elem->q_data, *pointer))
808 strcpy(*pointer, elem->q_data);
812 sprintf(buffer, "\"%s\" is not a legal value for %s. Use one of:",
815 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
816 Put_message(elem->q_data);
817 sprintf(buffer, "Are you sure you want \"%s\" to be a legal %s",
819 if (YesNoQuestion("Do you want this to be a new legal value", 0) == TRUE &&
820 YesNoQuestion(buffer, 0) == TRUE)
825 /* don't uppercase access flags. Do uppercase everything else */
826 if (strncmp(tname, "fs_access", 9))
828 for (p = argv[2]; *p; p++)
834 if ((stat = do_mr_query("add_alias", 3, argv, NULL, NULL)))
835 com_err(program_name, stat, " in add_alias");
838 elem = malloc(sizeof(struct mqelem));
839 elem->q_data = strdup(*pointer);
840 AddQueue(elem, GetTypeValues(tname));
841 Put_message("Done.");
844 *pointer = strdup(def);
845 return GetTypeFromUser(prompt, tname, pointer);
849 /* Function Name: GetAddressFromUser
850 * Description: gets an IP address from the user
851 * Arguments: prompt string, buffer pointer
852 * buffer contains default value as long int
853 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
856 int GetAddressFromUser(char *prompt, char **pointer)
858 char *value, buf[256];
862 addr.s_addr = htonl(atoi(*pointer));
863 value = strdup(inet_ntoa(addr));
864 ret = GetValueFromUser(prompt, &value);
865 if (ret == SUB_ERROR)
867 addr.s_addr = inet_addr(value);
869 sprintf(buf, "%ld", ntohl(addr.s_addr));
870 *pointer = strdup(buf);
875 int do_mr_query(char *name, int argc, char **argv,
876 int (*proc)(int, char **, void *), void *hint)
879 extern char *whoami, *moira_server;
882 status = mr_query(name, argc, argv, proc, hint);
883 if (status != MR_ABORTED && status != MR_NOT_CONNECTED)
885 status = mr_connect(moira_server);
888 com_err(whoami, status, " while re-connecting to server %s",
892 status = mr_auth(whoami);
895 com_err(whoami, status, " while re-authenticating to server %s",
900 status = mr_query(name, argc, argv, proc, hint);