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>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <netdb.h> /* for gethostbyname. */
36 /* Function Name: AddQueue
37 * Description: Adds an element to a queue
38 * Arguments: elem, pred - element and its predecessor.
42 static void AddQueue(struct mqelem *elem, struct mqelem *pred)
51 elem->q_forw = pred->q_forw;
55 /* Function Name: RemoveQueue
56 * Description: removes an element from a queue.
61 static void RemoveQueue(struct mqelem *elem)
64 elem->q_forw->q_back = elem->q_back;
66 elem->q_back->q_forw = elem->q_forw;
70 /* CopyInfo: allocates memory for a copy of a NULL terminated array of
71 * strings <and returns a pointer to the copy.
74 char **CopyInfo(char **info)
79 ret = malloc(sizeof(char *) * (CountArgs(info) + 1));
82 for (i = 0; info[i]; i++)
83 ret[i] = strdup(info[i]);
89 /* Function Name: FreeInfo
90 * Description: Frees all elements of a NULL terminated arrary of char*'s
91 * Arguments: info - array who's elements we are to free.
95 void FreeInfo(char **info)
98 FreeAndClear(info++, TRUE);
101 /* Function Name: FreeAndClear - I couldn't resist the name.
102 * Description: Clears pointer and optionially frees it.
103 * Arguments: pointer - pointer to work with.
104 * free_it - if TRUE then free pointer.
108 void FreeAndClear(char **pointer, Bool free_it)
117 /* Function Name: QueueTop
118 * Description: returns a mqelem pointer that points to the top of
120 * Arguments: elem - any element of a queue.
121 * Returns: top element of a queue.
124 struct mqelem *QueueTop(struct mqelem *elem)
126 if (!elem) /* NULL returns NULL. */
133 /* Function Name: FreeQueueElem
134 * Description: Frees one element of the queue.
135 * Arguments: elem - the elem to free.
139 static void FreeQueueElem(struct mqelem *elem)
141 char **info = elem->q_data;
145 FreeInfo(info); /* free info fields */
146 free(elem->q_data); /* free info array itself. */
148 RemoveQueue(elem); /* remove this element from the queue */
149 free(elem); /* free its space. */
152 /* Function Name: FreeQueue
153 * Description: Cleans up the queue
154 * Arguments: elem - any element of the queue.
158 void FreeQueue(struct mqelem *elem)
160 struct mqelem *temp, *local = QueueTop(elem);
164 temp = local->q_forw;
165 FreeQueueElem(local);
170 /* Function Name: QueueCount
171 * Description: Counts the number of elements in a queue
172 * Arguments: elem - any element in the queue.
176 int QueueCount(struct mqelem *elem)
179 elem = QueueTop(elem);
188 /* Function Name: StoreInfo
189 * Description: Stores information from a moira query into a queue.
190 * Arguments: argc, argv, - information returned from the query returned
192 * data - the previous element on the queue, this data will be
193 * stored in a mqelem struct immediatly after this elem.
194 * If NULL then a new queue will be created. This value
195 * is updated to the current element at the end off the
197 * Returns: MR_CONT, or MR_ABORT if it has problems.
200 int StoreInfo(int argc, char **argv, void *data)
202 char **info = malloc(MAX_ARGS_SIZE * sizeof(char *));
203 struct mqelem **old_elem = data;
204 struct mqelem *new_elem = malloc(sizeof(struct mqelem));
207 if (!new_elem || !info)
209 Put_message("Could Not allocate more memory.");
210 FreeQueue(*old_elem);
215 for (count = 0; count < argc; count++)
216 info[count] = strdup(argv[count]);
217 info[count] = NULL; /* NULL terminate this sucker. */
219 new_elem->q_data = info;
220 AddQueue(new_elem, *old_elem);
222 *old_elem = new_elem;
226 /* Function Name: CountArgs
227 * Description: Retrieve the number of args in a null terminated
229 * Arguments: info - the argument list.
230 * Returns: number if args in the list.
233 int CountArgs(char **info)
246 /* Function Name: PromptWithDefault
247 * Description: allows a user to be prompted for input, and given a
249 * Arguments: prompt - the prompt string.
250 * buf, buflen - buffer to be returned and its MAX size?
251 * default value for the answer.
252 * Returns: zero on failure
255 int PromptWithDefault(char *prompt, char *buf, int buflen, char *def)
263 strncpy(buf, parsed_argv[0], buflen);
264 sprintf(tmp, "%s: %s", prompt, buf);
270 sprintf(tmp, "%s [%s]: ", prompt, def ? def : "");
271 ans = Prompt_input(tmp, buf, buflen);
274 else if (!strcmp(buf, "\"\""))
279 /* Function Name: YesNoQuestion
280 * Description: This prompts the user for the answer to a yes-no or
281 * true-false question.
282 * Arguments: prompt - the prompt for the user.
283 * bool_def - the default value either TRUE or FALSE.
284 * Returns: TRUE or FALSE or -1 on error
287 Bool YesNoQuestion(char *prompt, int bool_def)
293 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
304 Put_message("Please answer 'y' or 'n'.");
310 /* Function Name: YesNoQuitQuestion
311 * Description: This prompts the user for the answer to a yes-no or
312 * true-false question, with a quit option.
313 * Arguments: prompt - the prompt for the user.
314 * bool_def - the default value either TRUE or FALSE.
315 * Returns: TRUE or FALSE or -1 on error or QUIT
316 * NOTE: It is not possible to have quit the default, but then I don't
317 * seem to need this functionality.
320 Bool YesNoQuitQuestion(char *prompt, int bool_def)
326 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
340 Put_message("Please answer 'y', 'n' or 'q'.");
346 /* Function Name: Confirm
347 * Description: This function asks the user to confirm the action
348 * he is about to take, used for things like deleting.
349 * Arguments: prompt - the prompt string.
350 * Returns: TRUE/FALSE - wether or not the confirmation occured.
353 Bool Confirm(char *prompt)
355 return !verbose || (YesNoQuestion(prompt, FALSE) == TRUE);
358 /* Function Name: ValidName
359 * Description: This function checks to see if we have a valid list name.
360 * Arguments: s - the list name.
361 * Returns: TRUE if Valid.
364 Bool ValidName(char *s)
367 Put_message("Please use a non-empty name.");
368 else if (strchr(s, ' '))
369 Put_message("You cannot use space (' ') in this name.");
370 else if (strchr(s, '*') || strchr(s, '?'))
371 Put_message("Wildcards not accepted here.");
377 /* Function Name: ToggleVerboseMode
378 * Description: This function toggles the verbose mode.
380 * Returns: DM_NORMAL.
383 int ToggleVerboseMode(int argc, char **argv)
388 Put_message("Delete functions will first confirm");
390 Put_message("Delete functions will be silent");
395 /* Function Name: SlipInNewName
396 * Description: Slips the new name into the number 2 slot of a list, and
397 * returns a pointer to the new list.
398 * Arguments: info - list that needs this name slipped into it.
399 * name - the name to slip into the list.
400 * Returns: a pointer to the new list.
401 * NOTE: This screws up the numbers of the elements of the array in a
405 void SlipInNewName(char **info, char *name)
409 /* This also pushes the NULL down. */
410 for (i = CountArgs(info); i > 0; i--)
411 info[i + 1] = info[i];
412 info[1] = name; /* now slip in the name. */
415 /* Function Name: GetValueFromUser
416 * Description: This function gets a value from a user for the field
418 * Arguments: prompt - prompt for user.
419 * pointer - pointer to default value, will be returned
421 * Returns: SUB_ERROR if break hit (^C).
424 int GetValueFromUser(char *prompt, char **pointer)
428 if (PromptWithDefault(prompt, buf, BUFSIZ, *pointer) == 0)
432 * If these are the same then there is no need to allocate a new string.
434 * a difference that makes no difference, IS no difference.
439 if (strcmp(buf, *pointer))
442 *pointer = strdup(buf);
448 /* Function Name: GetYesNoValueFromUser
449 * Description: This function gets a value from a user for the field
451 * Arguments: prompt - prompt for user.
452 * pointer - pointer to default value, will be returned
454 * Returns: SUB_ERROR if break hit (^C).
457 int GetYesNoValueFromUser(char *prompt, char **pointer)
459 char user_prompt[BUFSIZ];
462 if (!strcmp(*pointer, DEFAULT_YES))
467 sprintf(user_prompt, "%s (y/n)", prompt);
469 switch (YesNoQuestion(user_prompt, default_val))
474 *pointer = strdup(DEFAULT_YES);
479 *pointer = strdup(DEFAULT_NO);
488 /* Function Name: GetFSVal
489 * Description: asks about a specific filesystem value.
490 * Arguments: name - string for this type of filesystem.
491 * mask - mask for this type of filesystem.
492 * current - current filesystem state. (for defaults).
493 * new - new filesystem state.
494 * Returns: TRUE if successful.
497 static Bool GetFSVal(char *name, int mask, int current, int *new)
499 char temp_buf[BUFSIZ];
500 sprintf(temp_buf, "Is this a %s filsystem", name);
501 switch (YesNoQuestion(temp_buf, ((mask & current) == mask)))
507 break; /* zero by default. */
514 /* Function Name: GetFSTypes
515 * Description: Allows user to specify filsystem types.
516 * Arguments: current - current value of filsystem, freed here.
517 * Returns: SUB_ERROR on ^C.
520 int GetFSTypes(char **current, int options)
522 int c_value, new_val = 0; /* current value of filesys type (int). */
523 char ret_value[BUFSIZ];
528 c_value = atoi(*current);
530 if (GetFSVal("student", MR_FS_STUDENT, c_value, &new_val) == FALSE)
532 if (GetFSVal("faculty", MR_FS_FACULTY, c_value, &new_val) == FALSE)
534 if (GetFSVal("staff", MR_FS_STAFF, c_value, &new_val) == FALSE)
536 if (GetFSVal("miscellaneous", MR_FS_MISC, c_value, &new_val) == FALSE)
540 if (GetFSVal("Group Quotas", MR_FS_GROUPQUOTA, c_value, &new_val) ==
545 FreeAndClear(current, TRUE);
546 sprintf(ret_value, "%d", new_val);
547 *current = strdup(ret_value);
551 /* atot: convert ASCII integer unix time into human readable date string */
553 char *atot(char *itime)
558 time = (time_t) atoi(itime);
565 /* Function Name: Print
566 * Description: prints out all the arguments on a single line.
567 * Arguments: argc, argv - the standard Moira arguments.
568 * callback - the callback function - NOT USED.
572 int Print(int argc, char **argv, void *callback)
578 strcpy(buf, argv[0]); /* no newline 'cause Put_message adds one */
579 for (i = 1; i < argc; i++)
580 sprintf(buf, "%s %s", buf, argv[i]);
586 /* Function Name: PrintByType
587 * Description: This function prints all members of the type specified
588 * by the callback arg, unless the callback is NULL, in which
589 * case it prints all members.
590 * Arguments: argc, argc - normal arguments for mr_callback function.
591 * callback - either a type of member or NULL.
592 * Returns: MR_CONT or MR_QUIT.
595 int PrintByType(int argc, char **argv, void *callback)
598 return Print(argc, argv, callback);
599 if (!strcmp(argv[0], callback))
600 return Print(argc, argv, callback);
604 /* Function Name: PrintHelp
605 * Description: Prints Help Information in a NULL terminated
607 * Arguments: message.
608 * Returns: DM_NORMAL.
611 int PrintHelp(char **message)
615 for (i = 0; i < CountArgs(message); i++)
616 Put_message(message[i]);
621 /* Function Name: Loop
622 * Description: This function goes through the entire queue, and
623 * and executes the given function on each element.
624 * Arguments: elem - top element of the queue.
625 * func - the function to execute.
629 void Loop(struct mqelem *elem, void (*func)(char **))
633 (*func) (elem->q_data);
639 /* Function Name: QueryLoop
640 * Description: This functions loops through a queue containing
641 * information about some item that we want to perform
642 * an operation on, and then calls the correct routine
643 * perform that operation.
644 * Arguments: top - top of the queue of information.
645 * print_func - print function.
646 * op_function - operation to be performed.
647 * query_string - string the prompts the user whether or not
648 * to perform this operation.
651 * print_opt - should expect one arguent, the info array
653 * is expected to return the name of the item.
654 * op_func - should expect two arguments.
655 * 1) the info array of char *'s.
656 * 2) a boolean the is true if there only
657 * one item in this queue, used for delete
659 * query_string - this should be of such a form that when the
660 * name of the object and '(y/n/q) ?' are appended
661 * then it should still make sense, an example is
665 void QueryLoop(struct mqelem *elem, char * (*print_func)(char **),
666 void (*op_func)(char **, Bool), char *query_string)
669 char temp_buf[BUFSIZ], *name;
671 elem = QueueTop(elem);
672 one_item = (QueueCount(elem) == 1);
675 char **info = elem->q_data;
678 (*op_func) (info, one_item);
681 name = (*print_func) (info); /* call print function. */
682 sprintf(temp_buf, "%s %s (y/n/q)", query_string, name);
683 switch (YesNoQuitQuestion(temp_buf, FALSE))
686 (*op_func) (info, one_item);
691 Put_message("Aborting...");
699 /* Function Name: NullPrint
700 * Description: print function that returns nothing.
701 * Arguments: info - a pointer to the info array - Not used.
705 char *NullPrint(char **info)
711 /* Function Name: GetTypeValues
712 * Description: gets legal values for a typed object, keeping a cache
713 * Arguments: type name
714 * Returns: argv of values
717 struct mqelem *GetTypeValues(char *tname)
720 char *argv[3], *p, **pp;
721 struct mqelem *elem, *oelem;
722 static struct mqelem *cache = NULL;
725 struct mqelem *cache_data;
728 for (elem = cache; elem; elem = elem->q_forw)
731 if (!strcmp(ce->cache_name, tname))
732 return ce->cache_data;
739 if ((stat = do_mr_query("get_alias", 3, argv, StoreInfo, &elem)))
741 com_err(program_name, stat, " in GetTypeValues");
745 for (elem = QueueTop(elem); elem; elem = elem->q_forw)
752 elem = malloc(sizeof(struct mqelem));
753 ce = malloc(sizeof(struct cache_elem));
754 ce->cache_name = strdup(tname);
755 ce->cache_data = QueueTop(oelem);
757 AddQueue(elem, cache);
758 cache = QueueTop(elem);
759 return ce->cache_data;
763 /* Function Name: GetTypeFromUser
764 * Description: gets a typed value from the user
765 * Arguments: prompt string, type name, buffer pointer
766 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
769 int GetTypeFromUser(char *prompt, char *tname, char **pointer)
771 char def[BUFSIZ], buffer[BUFSIZ], *p, *argv[3];
775 strcpy(def, *pointer);
776 strcpy(buffer, prompt);
777 strcat(buffer, " (");
778 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
780 strcat(buffer, elem->q_data);
782 strcat(buffer, ", ");
785 if (strlen(buffer) > 64)
786 sprintf(buffer, "%s (? for help)", prompt);
787 if (GetValueFromUser(buffer, pointer) == SUB_ERROR)
789 if (**pointer == '?')
791 sprintf(buffer, "Type %s is one of:", tname);
793 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
794 Put_message(elem->q_data);
795 *pointer = strdup(def);
796 return GetTypeFromUser(prompt, tname, pointer);
798 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
800 if (!strcasecmp(elem->q_data, *pointer))
802 strcpy(*pointer, elem->q_data);
806 sprintf(buffer, "\"%s\" is not a legal value for %s. Use one of:",
809 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
810 Put_message(elem->q_data);
811 sprintf(buffer, "Are you sure you want \"%s\" to be a legal %s",
813 if (YesNoQuestion("Do you want this to be a new legal value", 0) == TRUE &&
814 YesNoQuestion(buffer, 0) == TRUE)
819 /* don't uppercase access flags. Do uppercase everything else */
820 if (strncmp(tname, "fs_access", 9))
822 for (p = argv[2]; *p; p++)
828 if ((stat = do_mr_query("add_alias", 3, argv, NULL, NULL)))
829 com_err(program_name, stat, " in add_alias");
832 elem = malloc(sizeof(struct mqelem));
833 elem->q_data = strdup(*pointer);
834 AddQueue(elem, GetTypeValues(tname));
835 Put_message("Done.");
838 *pointer = strdup(def);
839 return GetTypeFromUser(prompt, tname, pointer);
843 /* Function Name: GetAddressFromUser
844 * Description: gets an IP address from the user
845 * Arguments: prompt string, buffer pointer
846 * buffer contains default value as long int
847 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
850 int GetAddressFromUser(char *prompt, char **pointer)
852 char *value, buf[256];
856 addr.s_addr = htonl(atoi(*pointer));
857 value = strdup(inet_ntoa(addr));
858 ret = GetValueFromUser(prompt, &value);
859 if (ret == SUB_ERROR)
861 addr.s_addr = inet_addr(value);
863 sprintf(buf, "%ld", ntohl(addr.s_addr));
864 *pointer = strdup(buf);
869 int do_mr_query(char *name, int argc, char **argv,
870 int (*proc)(int, char **, void *), void *hint)
873 extern char *whoami, *moira_server;
876 status = mr_query(name, argc, argv, proc, hint);
877 if (status != MR_ABORTED && status != MR_NOT_CONNECTED)
879 status = mr_connect(moira_server);
882 com_err(whoami, status, " while re-connecting to server %s",
886 status = mr_auth(whoami);
889 com_err(whoami, status, " while re-authenticating to server %s",
894 status = mr_query(name, argc, argv, proc, hint);