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 <netinet/in.h>
23 #include <arpa/inet.h>
24 #include <netdb.h> /* for gethostbyname. */
34 /* Function Name: AddQueue
35 * Description: Adds an element to a queue
36 * Arguments: elem, pred - element and its predecessor.
40 static void AddQueue(struct qelem *elem, struct qelem *pred)
49 elem->q_forw = pred->q_forw;
53 /* Function Name: RemoveQueue
54 * Description: removes an element from a queue.
59 static void RemoveQueue(struct qelem *elem)
62 elem->q_forw->q_back = elem->q_back;
64 elem->q_back->q_forw = elem->q_forw;
68 /* CopyInfo: allocates memory for a copy of a NULL terminated array of
69 * strings <and returns a pointer to the copy.
72 char **CopyInfo(char **info)
77 ret = malloc(sizeof(char *) * (CountArgs(info) + 1));
80 for (i = 0; info[i]; i++)
81 ret[i] = strdup(info[i]);
87 /* Function Name: FreeInfo
88 * Description: Frees all elements of a NULL terminated arrary of char*'s
89 * Arguments: info - array who's elements we are to free.
93 void FreeInfo(char **info)
96 FreeAndClear(info++, TRUE);
99 /* Function Name: FreeAndClear - I couldn't resist the name.
100 * Description: Clears pointer and optionially frees it.
101 * Arguments: pointer - pointer to work with.
102 * free_it - if TRUE then free pointer.
106 void FreeAndClear(char **pointer, Bool free_it)
115 /* Function Name: QueueTop
116 * Description: returns a qelem pointer that points to the top of
118 * Arguments: elem - any element of a queue.
119 * Returns: top element of a queue.
122 struct qelem *QueueTop(struct qelem *elem)
124 if (!elem) /* NULL returns NULL. */
131 /* Function Name: FreeQueueElem
132 * Description: Frees one element of the queue.
133 * Arguments: elem - the elem to free.
137 static void FreeQueueElem(struct qelem *elem)
139 char **info = elem->q_data;
143 FreeInfo(info); /* free info fields */
144 free(elem->q_data); /* free info array itself. */
146 RemoveQueue(elem); /* remove this element from the queue */
147 free(elem); /* free its space. */
150 /* Function Name: FreeQueue
151 * Description: Cleans up the queue
152 * Arguments: elem - any element of the queue.
156 void FreeQueue(struct qelem *elem)
158 struct qelem *temp, *local = QueueTop(elem);
162 temp = local->q_forw;
163 FreeQueueElem(local);
168 /* Function Name: QueueCount
169 * Description: Counts the number of elements in a queue
170 * Arguments: elem - any element in the queue.
174 int QueueCount(struct qelem *elem)
177 elem = QueueTop(elem);
186 /* Function Name: StoreInfo
187 * Description: Stores information from a moira query into a queue.
188 * Arguments: argc, argv, - information returned from the query returned
190 * data - the previous element on the queue, this data will be
191 * stored in a qelem struct immediatly after this elem.
192 * If NULL then a new queue will be created. This value
193 * is updated to the current element at the end off the
195 * Returns: MR_CONT, or MR_ABORT if it has problems.
198 int StoreInfo(int argc, char **argv, void *data)
200 char **info = malloc(MAX_ARGS_SIZE * sizeof(char *));
201 struct qelem **old_elem = data;
202 struct qelem *new_elem = malloc(sizeof(struct qelem));
205 if (!new_elem || !info)
207 Put_message("Could Not allocate more memory.");
208 FreeQueue(*old_elem);
213 for (count = 0; count < argc; count++)
214 info[count] = strdup(argv[count]);
215 info[count] = NULL; /* NULL terminate this sucker. */
217 new_elem->q_data = info;
218 AddQueue(new_elem, *old_elem);
220 *old_elem = new_elem;
224 /* Function Name: CountArgs
225 * Description: Retrieve the number of args in a null terminated
227 * Arguments: info - the argument list.
228 * Returns: number if args in the list.
231 int CountArgs(char **info)
244 /* Function Name: PromptWithDefault
245 * Description: allows a user to be prompted for input, and given a
247 * Arguments: prompt - the prompt string.
248 * buf, buflen - buffer to be returned and its MAX size?
249 * default value for the answer.
250 * Returns: zero on failure
253 int PromptWithDefault(char *prompt, char *buf, int buflen, char *def)
261 strncpy(buf, parsed_argv[0], buflen);
262 sprintf(tmp, "%s: %s", prompt, buf);
268 sprintf(tmp, "%s [%s]: ", prompt, def ? def : "");
269 ans = Prompt_input(tmp, buf, buflen);
272 else if (!strcmp(buf, "\"\""))
277 /* Function Name: YesNoQuestion
278 * Description: This prompts the user for the answer to a yes-no or
279 * true-false question.
280 * Arguments: prompt - the prompt for the user.
281 * bool_def - the default value either TRUE or FALSE.
282 * Returns: TRUE or FALSE or -1 on error
285 Bool YesNoQuestion(char *prompt, int bool_def)
291 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
302 Put_message("Please answer 'y' or 'n'.");
308 /* Function Name: YesNoQuitQuestion
309 * Description: This prompts the user for the answer to a yes-no or
310 * true-false question, with a quit option.
311 * Arguments: prompt - the prompt for the user.
312 * bool_def - the default value either TRUE or FALSE.
313 * Returns: TRUE or FALSE or -1 on error or QUIT
314 * NOTE: It is not possible to have quit the default, but then I don't
315 * seem to need this functionality.
318 Bool YesNoQuitQuestion(char *prompt, int bool_def)
324 if (!PromptWithDefault(prompt, ans, 2, bool_def ? "y" : "n"))
338 Put_message("Please answer 'y', 'n' or 'q'.");
344 /* Function Name: Confirm
345 * Description: This function asks the user to confirm the action
346 * he is about to take, used for things like deleting.
347 * Arguments: prompt - the prompt string.
348 * Returns: TRUE/FALSE - wether or not the confirmation occured.
351 Bool Confirm(char *prompt)
353 return !verbose || (YesNoQuestion(prompt, FALSE) == TRUE);
356 /* Function Name: ValidName
357 * Description: This function checks to see if we have a valid list name.
358 * Arguments: s - the list name.
359 * Returns: TRUE if Valid.
362 Bool ValidName(char *s)
365 Put_message("Please use a non-empty name.");
366 else if (strchr(s, ' '))
367 Put_message("You cannot use space (' ') in this name.");
368 else if (strchr(s, '*') || strchr(s, '?'))
369 Put_message("Wildcards not accepted here.");
375 /* Function Name: ToggleVerboseMode
376 * Description: This function toggles the verbose mode.
378 * Returns: DM_NORMAL.
381 int ToggleVerboseMode(int argc, char **argv)
386 Put_message("Delete functions will first confirm\n");
388 Put_message("Delete functions will be silent\n");
393 /* Function Name: SlipInNewName
394 * Description: Slips the new name into the number 2 slot of a list, and
395 * returns a pointer to the new list.
396 * Arguments: info - list that needs this name slipped into it.
397 * name - the name to slip into the list.
398 * Returns: a pointer to the new list.
399 * NOTE: This screws up the numbers of the elements of the array in a
403 void SlipInNewName(char **info, char *name)
407 /* This also pushes the NULL down. */
408 for (i = CountArgs(info); i > 0; i--)
409 info[i + 1] = info[i];
410 info[1] = name; /* now slip in the name. */
413 /* Function Name: GetValueFromUser
414 * Description: This function gets a value from a user for the field
416 * Arguments: prompt - prompt for user.
417 * pointer - pointer to default value, will be returned
419 * Returns: SUB_ERROR if break hit (^C).
422 int GetValueFromUser(char *prompt, char **pointer)
426 if (PromptWithDefault(prompt, buf, BUFSIZ, *pointer) == 0)
430 * If these are the same then there is no need to allocate a new string.
432 * a difference that makes no difference, IS no difference.
437 if (strcmp(buf, *pointer))
440 *pointer = strdup(buf);
446 /* Function Name: GetYesNoValueFromUser
447 * Description: This function gets a value from a user for the field
449 * Arguments: prompt - prompt for user.
450 * pointer - pointer to default value, will be returned
452 * Returns: SUB_ERROR if break hit (^C).
455 int GetYesNoValueFromUser(char *prompt, char **pointer)
457 char user_prompt[BUFSIZ];
460 if (!strcmp(*pointer, DEFAULT_YES))
465 sprintf(user_prompt, "%s (y/n)", prompt);
467 switch (YesNoQuestion(user_prompt, default_val))
472 *pointer = strdup(DEFAULT_YES);
477 *pointer = strdup(DEFAULT_NO);
486 /* Function Name: GetFSVal
487 * Description: asks about a specific filesystem value.
488 * Arguments: name - string for this type of filesystem.
489 * mask - mask for this type of filesystem.
490 * current - current filesystem state. (for defaults).
491 * new - new filesystem state.
492 * Returns: TRUE if successful.
495 static Bool GetFSVal(char *name, int mask, int current, int *new)
497 char temp_buf[BUFSIZ];
498 sprintf(temp_buf, "Is this a %s filsystem", name);
499 switch (YesNoQuestion(temp_buf, ((mask & current) == mask)))
505 break; /* zero by default. */
512 /* Function Name: GetFSTypes
513 * Description: Allows user to specify filsystem types.
514 * Arguments: current - current value of filsystem, freed here.
515 * Returns: SUB_ERROR on ^C.
518 int GetFSTypes(char **current, int options)
520 int c_value, new_val = 0; /* current value of filesys type (int). */
521 char ret_value[BUFSIZ];
526 c_value = atoi(*current);
528 if (GetFSVal("student", MR_FS_STUDENT, c_value, &new_val) == FALSE)
530 if (GetFSVal("faculty", MR_FS_FACULTY, c_value, &new_val) == FALSE)
532 if (GetFSVal("staff", MR_FS_STAFF, c_value, &new_val) == FALSE)
534 if (GetFSVal("miscellaneous", MR_FS_MISC, c_value, &new_val) == FALSE)
538 if (GetFSVal("Group Quotas", MR_FS_GROUPQUOTA, c_value, &new_val) ==
543 FreeAndClear(current, TRUE);
544 sprintf(ret_value, "%d", new_val);
545 *current = strdup(ret_value);
549 /* atot: convert ASCII integer unix time into human readable date string */
551 char *atot(char *itime)
556 time = (time_t) atoi(itime);
563 /* Function Name: Print
564 * Description: prints out all the arguments on a single line.
565 * Arguments: argc, argv - the standard Moira arguments.
566 * callback - the callback function - NOT USED.
570 int Print(int argc, char **argv, void *callback)
576 strcpy(buf, argv[0]); /* no newline 'cause Put_message adds one */
577 for (i = 1; i < argc; i++)
578 sprintf(buf, "%s %s", buf, argv[i]);
584 /* Function Name: PrintByType
585 * Description: This function prints all members of the type specified
586 * by the callback arg, unless the callback is NULL, in which
587 * case it prints all members.
588 * Arguments: argc, argc - normal arguments for mr_callback function.
589 * callback - either a type of member or NULL.
590 * Returns: MR_CONT or MR_QUIT.
593 int PrintByType(int argc, char **argv, void *callback)
596 return Print(argc, argv, callback);
597 if (!strcmp(argv[0], callback))
598 return Print(argc, argv, callback);
602 /* Function Name: PrintHelp
603 * Description: Prints Help Information in a NULL terminated
605 * Arguments: message.
606 * Returns: DM_NORMAL.
609 int PrintHelp(char **message)
613 for (i = 0; i < CountArgs(message); i++)
614 Put_message(message[i]);
619 /* Function Name: Loop
620 * Description: This function goes through the entire queue, and
621 * and executes the given function on each element.
622 * Arguments: elem - top element of the queue.
623 * func - the function to execute.
627 void Loop(struct qelem *elem, void (*func)(char **))
631 (*func) (elem->q_data);
637 /* Function Name: QueryLoop
638 * Description: This functions loops through a queue containing
639 * information about some item that we want to perform
640 * an operation on, and then calls the correct routine
641 * perform that operation.
642 * Arguments: top - top of the queue of information.
643 * print_func - print function.
644 * op_function - operation to be performed.
645 * query_string - string the prompts the user whether or not
646 * to perform this operation.
649 * print_opt - should expect one arguent, the info array
651 * is expected to return the name of the item.
652 * op_func - should expect two arguments.
653 * 1) the info array of char *'s.
654 * 2) a boolean the is true if there only
655 * one item in this queue, used for delete
657 * query_string - this should be of such a form that when the
658 * name of the object and '(y/n/q) ?' are appended
659 * then it should still make sense, an example is
663 void QueryLoop(struct qelem *elem, char * (*print_func)(char **),
664 void (*op_func)(char **, Bool), char *query_string)
667 char temp_buf[BUFSIZ], *name;
669 elem = QueueTop(elem);
670 one_item = (QueueCount(elem) == 1);
673 char **info = elem->q_data;
676 (*op_func) (info, one_item);
679 name = (*print_func) (info); /* call print function. */
680 sprintf(temp_buf, "%s %s (y/n/q)", query_string, name);
681 switch (YesNoQuitQuestion(temp_buf, FALSE))
684 (*op_func) (info, one_item);
689 Put_message("Aborting...");
697 /* Function Name: NullPrint
698 * Description: print function that returns nothing.
699 * Arguments: info - a pointer to the info array - Not used.
703 char *NullPrint(char **info)
709 /* Function Name: GetTypeValues
710 * Description: gets legal values for a typed object, keeping a cache
711 * Arguments: type name
712 * Returns: argv of values
715 struct qelem *GetTypeValues(char *tname)
718 char *argv[3], *p, **pp;
719 struct qelem *elem, *oelem;
720 static struct qelem *cache = NULL;
723 struct qelem *cache_data;
726 for (elem = cache; elem; elem = elem->q_forw)
729 if (!strcmp(ce->cache_name, tname))
730 return ce->cache_data;
737 if ((stat = do_mr_query("get_alias", 3, argv, StoreInfo, &elem)))
739 com_err(program_name, stat, " in GetTypeValues");
743 for (elem = QueueTop(elem); elem; elem = elem->q_forw)
750 elem = malloc(sizeof(struct qelem));
751 ce = malloc(sizeof(struct cache_elem));
752 ce->cache_name = strdup(tname);
753 ce->cache_data = QueueTop(oelem);
755 AddQueue(elem, cache);
756 cache = QueueTop(elem);
757 return ce->cache_data;
761 /* Function Name: GetTypeFromUser
762 * Description: gets a typed value from the user
763 * Arguments: prompt string, type name, buffer pointer
764 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
767 int GetTypeFromUser(char *prompt, char *tname, char **pointer)
769 char def[BUFSIZ], buffer[BUFSIZ], *p, *argv[3];
773 strcpy(def, *pointer);
774 strcpy(buffer, prompt);
775 strcat(buffer, " (");
776 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
778 strcat(buffer, elem->q_data);
780 strcat(buffer, ", ");
783 if (strlen(buffer) > 64)
784 sprintf(buffer, "%s (? for help)", prompt);
785 if (GetValueFromUser(buffer, pointer) == SUB_ERROR)
787 if (**pointer == '?')
789 sprintf(buffer, "Type %s is one of:", tname);
791 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
792 Put_message(elem->q_data);
793 *pointer = strdup(def);
794 return GetTypeFromUser(prompt, tname, pointer);
796 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
798 if (!strcasecmp(elem->q_data, *pointer))
800 strcpy(*pointer, elem->q_data);
804 sprintf(buffer, "\"%s\" is not a legal value for %s. Use one of:",
807 for (elem = GetTypeValues(tname); elem; elem = elem->q_forw)
808 Put_message(elem->q_data);
809 sprintf(buffer, "Are you sure you want \"%s\" to be a legal %s",
811 if (YesNoQuestion("Do you want this to be a new legal value", 0) == TRUE &&
812 YesNoQuestion(buffer, 0) == TRUE)
817 /* don't uppercase access flags. Do uppercase everything else */
818 if (strncmp(tname, "fs_access", 9))
820 for (p = argv[2]; *p; p++)
826 if ((stat = do_mr_query("add_alias", 3, argv, NULL, NULL)))
827 com_err(program_name, stat, " in add_alias");
830 elem = malloc(sizeof(struct qelem));
831 elem->q_data = strdup(*pointer);
832 AddQueue(elem, GetTypeValues(tname));
833 Put_message("Done.");
836 *pointer = strdup(def);
837 return GetTypeFromUser(prompt, tname, pointer);
841 /* Function Name: GetAddressFromUser
842 * Description: gets an IP address from the user
843 * Arguments: prompt string, buffer pointer
844 * buffer contains default value as long int
845 * Returns: SUB_ERROR if ^C, SUB_NORMAL otherwise
848 int GetAddressFromUser(char *prompt, char **pointer)
850 char *value, buf[256];
854 addr.s_addr = htonl(atoi(*pointer));
855 value = strdup(inet_ntoa(addr));
856 ret = GetValueFromUser(prompt, &value);
857 if (ret == SUB_ERROR)
859 addr.s_addr = inet_addr(value);
861 sprintf(buf, "%ld", ntohl(addr.s_addr));
862 *pointer = strdup(buf);
867 int do_mr_query(char *name, int argc, char **argv,
868 int (*proc)(int, char **, void *), void *hint)
871 extern char *whoami, *moira_server;
874 status = mr_query(name, argc, argv, proc, hint);
875 if (status != MR_ABORTED && status != MR_NOT_CONNECTED)
877 status = mr_connect(moira_server);
880 com_err(whoami, status, " while re-connecting to server %s",
884 status = mr_auth(whoami);
887 com_err(whoami, status, " while re-authenticating to server %s",
892 status = mr_query(name, argc, argv, proc, hint);