Whamcloud - gitweb
89a8d237a0d9103c9be90085dbdce689b2919513
[tools/e2fsprogs.git] / e2fsck / profile.c
1 /*
2  * profile.c -- A simple configuration file parsing "library in a file"
3  * 
4  * The profile library was originally written by Theodore Ts'o in 1995
5  * for use in the MIT Kerberos v5 library.  It has been
6  * modified/enhanced/bug-fixed over time by other members of the MIT
7  * Kerberos team.  This version was originally taken from the Kerberos
8  * v5 distribution, version 1.4.2, and radically simplified for use in
9  * e2fsprogs.  (Support for locking for multi-threaded operations,
10  * being able to modify and update the configuration file
11  * programmatically, and Mac/Windows portability have been removed.
12  * It has been folded into a single C source file to make it easier to
13  * fold into an application program.)
14  *
15  * Copyright (C) 2005, 2006 by Theodore Ts'o.
16  *
17  * %Begin-Header%
18  * This file may be redistributed under the terms of the GNU Public
19  * License.
20  * %End-Header%
21  * 
22  * Copyright (C) 1985-2005 by the Massachusetts Institute of Technology.
23  * 
24  * All rights reserved.
25  * 
26  * Export of this software from the United States of America may require
27  * a specific license from the United States Government.  It is the
28  * responsibility of any person or organization contemplating export to
29  * obtain such a license before exporting.
30  * 
31  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
32  * distribute this software and its documentation for any purpose and
33  * without fee is hereby granted, provided that the above copyright
34  * notice appear in all copies and that both that copyright notice and
35  * this permission notice appear in supporting documentation, and that
36  * the name of M.I.T. not be used in advertising or publicity pertaining
37  * to distribution of the software without specific, written prior
38  * permission.  Furthermore if you modify this software you must label
39  * your software as modified software and not distribute it in such a
40  * fashion that it might be confused with the original MIT software.
41  * M.I.T. makes no representations about the suitability of this software
42  * for any purpose.  It is provided "as is" without express or implied
43  * warranty.
44  * 
45  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
46  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
47  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
48  * 
49  */
50
51 #ifdef HAVE_UNISTD_H
52 #include <unistd.h>
53 #endif
54 #include <stdio.h>
55 #ifdef HAVE_STDLIB_H
56 #include <stdlib.h>
57 #endif
58 #include <time.h>
59 #include <string.h>
60 #include <errno.h>
61 #include <ctype.h>
62 #include <limits.h>
63 #include <stddef.h>
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <dirent.h>
67 #ifdef HAVE_PWD_H
68 #include <pwd.h>
69 #endif
70
71 #include <et/com_err.h>
72 #include "profile.h"
73 #include "prof_err.h"
74
75 #undef STAT_ONCE_PER_SECOND
76 #undef HAVE_STAT
77
78 /*
79  * prof_int.h
80  */
81
82 typedef long prf_magic_t;
83
84 /*
85  * This is the structure which stores the profile information for a
86  * particular configuration file.
87  */
88 struct _prf_file_t {
89         prf_magic_t     magic;
90         char            *filespec;
91 #ifdef STAT_ONCE_PER_SECOND
92         time_t          last_stat;
93 #endif
94         time_t          timestamp; /* time tree was last updated from file */
95         int             flags;  /* r/w, dirty */
96         int             upd_serial; /* incremented when data changes */
97         struct profile_node *root;
98         struct _prf_file_t *next;
99 };
100
101 typedef struct _prf_file_t *prf_file_t;
102
103 /*
104  * The profile flags
105  */
106 #define PROFILE_FILE_RW         0x0001
107 #define PROFILE_FILE_DIRTY      0x0002
108
109 /*
110  * This structure defines the high-level, user visible profile_t
111  * object, which is used as a handle by users who need to query some
112  * configuration file(s)
113  */
114 struct _profile_t {
115         prf_magic_t     magic;
116         prf_file_t      first_file;
117 };
118
119 /*
120  * Used by the profile iterator in prof_get.c
121  */
122 #define PROFILE_ITER_LIST_SECTION       0x0001
123 #define PROFILE_ITER_SECTIONS_ONLY      0x0002
124 #define PROFILE_ITER_RELATIONS_ONLY     0x0004
125
126 #define PROFILE_ITER_FINAL_SEEN         0x0100
127
128 /*
129  * Check if a filespec is last in a list (NULL on UNIX, invalid FSSpec on MacOS
130  */
131
132 #define PROFILE_LAST_FILESPEC(x) (((x) == NULL) || ((x)[0] == '\0'))
133
134 struct profile_node {
135         errcode_t       magic;
136         char *name;
137         char *value;
138         int group_level;
139         int final:1;            /* Indicate don't search next file */
140         int deleted:1;
141         struct profile_node *first_child;
142         struct profile_node *parent;
143         struct profile_node *next, *prev;
144 };
145
146 #define CHECK_MAGIC(node) \
147           if ((node)->magic != PROF_MAGIC_NODE) \
148                   return PROF_MAGIC_NODE;
149
150 static errcode_t profile_parse_file
151         (FILE *f, prf_file_t prf);
152
153 #ifdef DEBUG_PROGRAM
154 static errcode_t profile_write_tree_file
155         (struct profile_node *root, FILE *dstfile);
156
157 static errcode_t profile_write_tree_to_buffer
158         (struct profile_node *root, char **buf);
159 #endif
160
161
162 static void profile_free_node
163         (struct profile_node *relation);
164
165 static errcode_t profile_create_node
166         (const char *name, const char *value,
167                    struct profile_node **ret_node);
168
169 #ifdef DEBUG_PROGRAM
170 static errcode_t profile_verify_node
171         (struct profile_node *node);
172 #endif
173
174 static errcode_t profile_add_node
175         (struct profile_node *section,
176                     const char *name, const char *value,
177                     struct profile_node **ret_node);
178
179 static errcode_t profile_find_node
180         (struct profile_node *section,
181                     const char *name, const char *value,
182                     int section_flag, void **state,
183                     struct profile_node **node);
184
185 static errcode_t profile_node_iterator
186         (void   **iter_p, struct profile_node **ret_node,
187                    char **ret_name, char **ret_value);
188
189 static errcode_t profile_open_file
190         (const char * file, prf_file_t *ret_prof);
191
192 static errcode_t profile_update_file
193         (prf_file_t prf);
194
195 static void profile_free_file
196         (prf_file_t profile);
197
198 static errcode_t profile_get_value(profile_t profile, const char *name,
199                                    const char *subname, const char *subsubname,
200                                    const char **ret_value);
201
202
203 /*
204  * prof_init.c --- routines that manipulate the user-visible profile_t
205  *      object.
206  */
207
208 static int compstr(const void *m1, const void *m2) 
209 {
210         const char *s1 = *((const char **) m1);
211         const char *s2 = *((const char **) m2);
212
213         return strcmp(s1, s2); 
214 }
215
216 static void free_list(char **list)
217 {
218     char        **cp;
219
220     if (list == 0)
221             return;
222     
223     for (cp = list; *cp; cp++)
224         free(*cp);
225     free(list);
226 }
227
228 static errcode_t get_dirlist(const char *dirname, char***ret_array)
229 {
230         DIR *dir;
231         struct dirent *de;
232         struct stat st;
233         errcode_t retval;
234         char *fn, *cp;
235         char **array = 0, **new_array;
236         int max = 0, num = 0;
237
238         dir = opendir(dirname);
239         if (!dir)
240                 return errno;
241
242         while ((de = readdir(dir)) != NULL) {
243                 for (cp = de->d_name; *cp; cp++) {
244                         if (!isalnum(*cp) &&
245                             (*cp != '-') &&
246                             (*cp != '_'))
247                                 break;
248                 }
249                 if (*cp)
250                         continue;
251                 fn = malloc(strlen(dirname) + strlen(de->d_name) + 2);
252                 if (!fn) {
253                         retval = ENOMEM;
254                         goto errout;
255                 }
256                 sprintf(fn, "%s/%s", dirname, de->d_name);
257                 if ((stat(fn, &st) < 0) || !S_ISREG(st.st_mode)) {
258                         free(fn);
259                         continue;
260                 }
261                 if (num >= max) {
262                         max += 10;
263                         new_array = realloc(array, sizeof(char *) * (max+1));
264                         if (!new_array) {
265                                 retval = ENOMEM;
266                                 goto errout;
267                         }
268                         array = new_array;
269                 }
270                 array[num++] = fn;
271         }
272         qsort(array, num, sizeof(char *), compstr);
273         array[num++] = 0;
274         *ret_array = array;
275         closedir(dir);
276         return 0;
277 errout:
278         closedir(dir);
279         free_list(array);
280         return retval;
281 }
282
283 errcode_t 
284 profile_init(const char **files, profile_t *ret_profile)
285 {
286         const char **fs;
287         profile_t profile;
288         prf_file_t  new_file, *last;
289         errcode_t retval = 0;
290         char **cpp, *cp, **array = 0;
291
292         profile = malloc(sizeof(struct _profile_t));
293         if (!profile)
294                 return ENOMEM;
295         memset(profile, 0, sizeof(struct _profile_t));
296         profile->magic = PROF_MAGIC_PROFILE;
297         last = &profile->first_file;
298
299         /* if the filenames list is not specified return an empty profile */
300         if ( files ) {
301             for (fs = files; !PROFILE_LAST_FILESPEC(*fs); fs++) {
302                 retval = get_dirlist(*fs, &array);
303                 if (retval == 0) {
304                         for (cpp = array; (cp = *cpp); cpp++) {
305                                 retval = profile_open_file(cp, &new_file);
306                                 if (retval == EACCES)
307                                         continue;
308                                 if (retval)
309                                         goto errout;
310                                 *last = new_file;
311                                 last = &new_file->next;
312                         }
313                 } else if (retval != ENOTDIR)
314                         goto errout;
315
316                 retval = profile_open_file(*fs, &new_file);
317                 /* if this file is missing, skip to the next */
318                 if (retval == ENOENT || retval == EACCES) {
319                         continue;
320                 }
321                 if (retval)
322                         goto errout;
323                 *last = new_file;
324                 last = &new_file->next;
325             }
326             /*
327              * If all the files were not found, return the appropriate error.
328              */
329             if (!profile->first_file) {
330                 profile_release(profile);
331                 return ENOENT;
332             }
333         }
334
335         free_list(array);
336         *ret_profile = profile;
337         return 0;
338 errout:
339         free_list(array);
340         profile_release(profile);
341         return retval;
342 }
343
344 void 
345 profile_release(profile_t profile)
346 {
347         prf_file_t      p, next;
348
349         if (!profile || profile->magic != PROF_MAGIC_PROFILE)
350                 return;
351
352         for (p = profile->first_file; p; p = next) {
353                 next = p->next;
354                 profile_free_file(p);
355         }
356         profile->magic = 0;
357         free(profile);
358 }
359
360
361 /*
362  * prof_file.c ---- routines that manipulate an individual profile file.
363  */
364
365 errcode_t profile_open_file(const char * filespec,
366                             prf_file_t *ret_prof)
367 {
368         prf_file_t      prf;
369         errcode_t       retval;
370         char            *home_env = 0;
371         unsigned int    len;
372         char            *expanded_filename;
373
374         prf = malloc(sizeof(struct _prf_file_t));
375         if (!prf)
376                 return ENOMEM;
377         memset(prf, 0, sizeof(struct _prf_file_t));
378         prf->magic = PROF_MAGIC_FILE;
379
380         len = strlen(filespec)+1;
381         if (filespec[0] == '~' && filespec[1] == '/') {
382                 home_env = getenv("HOME");
383 #ifdef HAVE_PWD_H
384                 if (home_env == NULL) {
385 #ifdef HAVE_GETWUID_R
386                     struct passwd *pw, pwx;
387                     uid_t uid;
388                     char pwbuf[BUFSIZ];
389
390                     uid = getuid();
391                     if (!getpwuid_r(uid, &pwx, pwbuf, sizeof(pwbuf), &pw)
392                         && pw != NULL && pw->pw_dir[0] != 0)
393                         home_env = pw->pw_dir;
394 #else
395                     struct passwd *pw;
396
397                     pw = getpwuid(getuid());
398                     home_env = pw->pw_dir;
399 #endif
400                 }
401 #endif
402                 if (home_env)
403                         len += strlen(home_env);
404         }
405         expanded_filename = malloc(len);
406         if (expanded_filename == 0)
407             return errno;
408         if (home_env) {
409             strcpy(expanded_filename, home_env);
410             strcat(expanded_filename, filespec+1);
411         } else
412             memcpy(expanded_filename, filespec, len);
413
414         prf->filespec = expanded_filename;
415
416         retval = profile_update_file(prf);
417         if (retval) {
418                 profile_free_file(prf);
419                 return retval;
420         }
421
422         *ret_prof = prf;
423         return 0;
424 }
425
426 errcode_t profile_update_file(prf_file_t prf)
427 {
428         errcode_t retval;
429 #ifdef HAVE_STAT
430         struct stat st;
431 #ifdef STAT_ONCE_PER_SECOND
432         time_t now;
433 #endif
434 #endif
435         FILE *f;
436
437 #ifdef HAVE_STAT
438 #ifdef STAT_ONCE_PER_SECOND
439         now = time(0);
440         if (now == prf->last_stat && prf->root != NULL) {
441             return 0;
442         }
443 #endif
444         if (stat(prf->filespec, &st)) {
445             retval = errno;
446             return retval;
447         }
448 #ifdef STAT_ONCE_PER_SECOND
449         prf->last_stat = now;
450 #endif
451         if (st.st_mtime == prf->timestamp && prf->root != NULL) {
452             return 0;
453         }
454         if (prf->root) {
455                 profile_free_node(prf->root);
456                 prf->root = 0;
457         }
458 #else
459         /*
460          * If we don't have the stat() call, assume that our in-core
461          * memory image is correct.  That is, we won't reread the
462          * profile file if it changes.
463          */
464         if (prf->root) {
465             return 0;
466         }
467 #endif
468         errno = 0;
469         f = fopen(prf->filespec, "r");
470         if (f == NULL) {
471                 retval = errno;
472                 if (retval == 0)
473                         retval = ENOENT;
474                 return retval;
475         }
476         prf->upd_serial++;
477         retval = profile_parse_file(f, prf);
478         fclose(f);
479         if (retval) {
480             return retval;
481         }
482 #ifdef HAVE_STAT
483         prf->timestamp = st.st_mtime;
484 #endif
485         return 0;
486 }
487
488 void profile_free_file(prf_file_t prf)
489 {
490     if (prf->root)
491         profile_free_node(prf->root);
492     if (prf->filespec)
493             free(prf->filespec);
494     free(prf);
495 }
496
497 /* Begin the profile parser */
498
499 static profile_syntax_err_cb_t  syntax_err_cb;
500
501 profile_syntax_err_cb_t profile_set_syntax_err_cb(profile_syntax_err_cb_t hook)
502 {
503         profile_syntax_err_cb_t old;
504
505         old = syntax_err_cb;
506         syntax_err_cb = hook;
507         return(old);
508 }
509
510 #define STATE_INIT_COMMENT      0
511 #define STATE_STD_LINE          1
512 #define STATE_GET_OBRACE        2
513
514 struct parse_state {
515         int     state;
516         int     group_level;
517         int     line_num;
518         struct profile_node *root_section;
519         struct profile_node *current_section;
520 };
521
522 static char *skip_over_blanks(char *cp)
523 {
524         while (*cp && isspace((int) (*cp)))
525                 cp++;
526         return cp;
527 }
528
529 static int end_or_comment(char ch)
530 {
531         return (ch == 0 || ch == '#' || ch == ';');
532 }
533
534 static char *skip_over_nonblanks(char *cp)
535 {
536         while (!end_or_comment(*cp) && !isspace(*cp))
537                 cp++;
538         return cp;
539 }
540
541 static void strip_line(char *line)
542 {
543         char *p = line + strlen(line);
544         while (p > line && (p[-1] == '\n' || p[-1] == '\r'))
545             *p-- = 0;
546 }
547
548 static void parse_quoted_string(char *str)
549 {
550         char *to, *from;
551
552         to = from = str;
553
554         for (to = from = str; *from && *from != '"'; to++, from++) {
555                 if (*from == '\\') {
556                         from++;
557                         switch (*from) {
558                         case 'n':
559                                 *to = '\n';
560                                 break;
561                         case 't':
562                                 *to = '\t';
563                                 break;
564                         case 'b':
565                                 *to = '\b';
566                                 break;
567                         default:
568                                 *to = *from;
569                         }
570                         continue;
571                 }
572                 *to = *from;
573         }
574         *to = '\0';
575 }
576
577
578 static errcode_t parse_std_line(char *line, struct parse_state *state)
579 {
580         char    *cp, ch, *tag, *value;
581         char    *p;
582         errcode_t retval;
583         struct profile_node     *node;
584         int do_subsection = 0;
585         void *iter = 0;
586         
587         if (*line == 0)
588                 return 0;
589         strip_line(line);
590         cp = skip_over_blanks(line);
591         ch = *cp;
592         if (end_or_comment(ch))
593                 return 0;
594         if (ch == '[') {
595                 if (state->group_level > 0)
596                         return PROF_SECTION_NOTOP;
597                 cp++;
598                 cp = skip_over_blanks(cp);
599                 p = strchr(cp, ']');
600                 if (p == NULL)
601                         return PROF_SECTION_SYNTAX;
602                 if (*cp == '"') {
603                         cp++;
604                         parse_quoted_string(cp);
605                 } else {
606                         *p-- = '\0';
607                         while (isspace(*p) && (p > cp))
608                                 *p-- = '\0';
609                         if (*cp == 0)
610                                 return PROF_SECTION_SYNTAX;
611                 }
612                 retval = profile_find_node(state->root_section, cp, 0, 1, 
613                                            &iter, &state->current_section);
614                 if (retval == PROF_NO_SECTION) {
615                         retval = profile_add_node(state->root_section,
616                                                   cp, 0,
617                                                   &state->current_section);
618                         if (retval)
619                                 return retval;
620                 } else if (retval)
621                         return retval;
622
623                 /*
624                  * Finish off the rest of the line.
625                  */
626                 cp = p+1;
627                 if (*cp == '*') {
628                         state->current_section->final = 1;
629                         cp++;
630                 }
631                 /*
632                  * Spaces or comments after ']' should not be fatal 
633                  */
634                 cp = skip_over_blanks(cp);
635                 if (!end_or_comment(*cp))
636                         return PROF_SECTION_SYNTAX;
637                 return 0;
638         }
639         if (ch == '}') {
640                 if (state->group_level == 0)
641                         return PROF_EXTRA_CBRACE;
642                 if (*(cp+1) == '*')
643                         state->current_section->final = 1;
644                 state->current_section = state->current_section->parent;
645                 state->group_level--;
646                 return 0;
647         }
648         /*
649          * Parse the relations
650          */
651         tag = cp;
652         cp = strchr(cp, '=');
653         if (!cp)
654                 return PROF_RELATION_SYNTAX;
655         if (cp == tag)
656             return PROF_RELATION_SYNTAX;
657         *cp = '\0';
658         if (*tag == '"') {
659                 tag++;
660                 parse_quoted_string(tag);
661         } else {
662                 /* Look for whitespace on left-hand side.  */
663                 p = skip_over_nonblanks(tag);
664                 if (*p)
665                         *p++ = 0;
666                 p = skip_over_blanks(p);
667                 /* If we have more non-whitespace, it's an error.  */
668                 if (*p)
669                         return PROF_RELATION_SYNTAX;
670         }
671
672         cp = skip_over_blanks(cp+1);
673         value = cp;
674         ch = value[0];
675         if (ch == '"') {
676                 value++;
677                 parse_quoted_string(value);
678         } else if (end_or_comment(ch)) {
679                 do_subsection++;
680                 state->state = STATE_GET_OBRACE;
681         } else if (value[0] == '{') {
682                 cp = skip_over_blanks(value+1);
683                 ch = *cp;
684                 if (end_or_comment(ch))
685                         do_subsection++;
686                 else
687                         return PROF_RELATION_SYNTAX;
688         } else {
689                 cp = skip_over_nonblanks(value);
690                 p = skip_over_blanks(cp);
691                 ch = *p;
692                 *cp = 0;
693                 if (!end_or_comment(ch))
694                         return PROF_RELATION_SYNTAX;
695         }
696         if (do_subsection) {
697                 p = strchr(tag, '*');
698                 if (p)
699                         *p = '\0';
700                 retval = profile_add_node(state->current_section,
701                                           tag, 0, &state->current_section);
702                 if (retval)
703                         return retval;
704                 if (p)
705                         state->current_section->final = 1;
706                 state->group_level++;
707                 return 0;
708         }
709         p = strchr(tag, '*');
710         if (p)
711                 *p = '\0';
712         profile_add_node(state->current_section, tag, value, &node);
713         if (p)
714                 node->final = 1;
715         return 0;
716 }
717
718 static errcode_t parse_line(char *line, struct parse_state *state)
719 {
720         char    *cp;
721         
722         state->line_num++;
723         switch (state->state) {
724         case STATE_INIT_COMMENT:
725                 if (line[0] != '[')
726                         return 0;
727                 state->state = STATE_STD_LINE;
728         case STATE_STD_LINE:
729                 return parse_std_line(line, state);
730         case STATE_GET_OBRACE:
731                 cp = skip_over_blanks(line);
732                 if (*cp != '{')
733                         return PROF_MISSING_OBRACE;
734                 state->state = STATE_STD_LINE;
735         }
736         return 0;
737 }
738
739 errcode_t profile_parse_file(FILE *f, prf_file_t file)
740 {
741         char buf[2048];
742         errcode_t retval;
743         struct parse_state state;
744
745         memset(&state, 0, sizeof(struct parse_state));
746
747         retval = profile_create_node("(root)", 0, &state.root_section);
748         if (retval)
749                 return retval;
750
751         while (!feof(f)) {
752                 if (fgets(buf, sizeof(buf), f) == NULL)
753                         break;
754                 retval = parse_line(buf, &state);
755                 if (retval) {
756                         if (syntax_err_cb)
757                                 (syntax_err_cb)(file->filespec, retval, 
758                                                 state.line_num);
759                         return retval;
760                 }
761         }
762         file->root = state.root_section;
763
764         return 0;
765 }
766
767
768 #ifdef DEBUG_PROGRAM
769 /*
770  * Return TRUE if the string begins or ends with whitespace
771  */
772 static int need_double_quotes(char *str)
773 {
774         if (!str || !*str)
775                 return 0;
776         if (isspace((int) (*str)) ||isspace((int) (*(str + strlen(str) - 1))))
777                 return 1;
778         if (strchr(str, '\n') || strchr(str, '\t') || strchr(str, '\b') ||
779             strchr(str, ' ') || strchr(str, '#') || strchr(str, ';'))
780                 return 1;
781         return 0;
782 }
783
784 /*
785  * Output a string with double quotes, doing appropriate backquoting
786  * of characters as necessary.
787  */
788 static void output_quoted_string(char *str, void (*cb)(const char *,void *),
789                                  void *data)
790 {
791         char    ch;
792         char buf[2];
793
794         cb("\"", data);
795         if (!str) {
796                 cb("\"", data);
797                 return;
798         }
799         buf[1] = 0;
800         while ((ch = *str++)) {
801                 switch (ch) {
802                 case '\\':
803                         cb("\\\\", data);
804                         break;
805                 case '\n':
806                         cb("\\n", data);
807                         break;
808                 case '\t':
809                         cb("\\t", data);
810                         break;
811                 case '\b':
812                         cb("\\b", data);
813                         break;
814                 default:
815                         /* This would be a lot faster if we scanned
816                            forward for the next "interesting"
817                            character.  */
818                         buf[0] = ch;
819                         cb(buf, data);
820                         break;
821                 }
822         }
823         cb("\"", data);
824 }
825
826 #ifndef EOL
827 #define EOL "\n"
828 #endif
829
830 /* Errors should be returned, not ignored!  */
831 static void dump_profile(struct profile_node *root, int level,
832                          void (*cb)(const char *, void *), void *data)
833 {
834         int i;
835         struct profile_node *p;
836         void *iter;
837         long retval;
838         
839         iter = 0;
840         do {
841                 retval = profile_find_node(root, 0, 0, 0, &iter, &p);
842                 if (retval)
843                         break;
844                 for (i=0; i < level; i++)
845                         cb("\t", data);
846                 if (need_double_quotes(p->name))
847                         output_quoted_string(p->name, cb, data);
848                 else
849                         cb(p->name, data);
850                 cb(" = ", data);
851                 if (need_double_quotes(p->value))
852                         output_quoted_string(p->value, cb, data);
853                 else
854                         cb(p->value, data);
855                 cb(EOL, data);
856         } while (iter != 0);
857
858         iter = 0;
859         do {
860                 retval = profile_find_node(root, 0, 0, 1, &iter, &p);
861                 if (retval)
862                         break;
863                 if (level == 0) { /* [xxx] */
864                         cb("[", data);
865                         if (need_double_quotes(p->name))
866                                 output_quoted_string(p->name, cb, data);
867                         else
868                                 cb(p->name, data);
869                         cb("]", data);
870                         cb(p->final ? "*" : "", data);
871                         cb(EOL, data);
872                         dump_profile(p, level+1, cb, data);
873                         cb(EOL, data);
874                 } else {        /* xxx = { ... } */
875                         for (i=0; i < level; i++)
876                                 cb("\t", data);
877                         if (need_double_quotes(p->name))
878                                 output_quoted_string(p->name, cb, data);
879                         else
880                                 cb(p->name, data);
881                         cb(" = {", data);
882                         cb(EOL, data);
883                         dump_profile(p, level+1, cb, data);
884                         for (i=0; i < level; i++)
885                                 cb("\t", data);
886                         cb("}", data);
887                         cb(p->final ? "*" : "", data);
888                         cb(EOL, data);
889                 }
890         } while (iter != 0);
891 }
892
893 static void dump_profile_to_file_cb(const char *str, void *data)
894 {
895         fputs(str, data);
896 }
897
898 errcode_t profile_write_tree_file(struct profile_node *root, FILE *dstfile)
899 {
900         dump_profile(root, 0, dump_profile_to_file_cb, dstfile);
901         return 0;
902 }
903
904 struct prof_buf {
905         char *base;
906         size_t cur, max;
907         int err;
908 };
909
910 static void add_data_to_buffer(struct prof_buf *b, const void *d, size_t len)
911 {
912         if (b->err)
913                 return;
914         if (b->max - b->cur < len) {
915                 size_t newsize;
916                 char *newptr;
917
918                 newsize = b->max + (b->max >> 1) + len + 1024;
919                 newptr = realloc(b->base, newsize);
920                 if (newptr == NULL) {
921                         b->err = 1;
922                         return;
923                 }
924                 b->base = newptr;
925                 b->max = newsize;
926         }
927         memcpy(b->base + b->cur, d, len);
928         b->cur += len;          /* ignore overflow */
929 }
930
931 static void dump_profile_to_buffer_cb(const char *str, void *data)
932 {
933         add_data_to_buffer((struct prof_buf *)data, str, strlen(str));
934 }
935
936 errcode_t profile_write_tree_to_buffer(struct profile_node *root,
937                                        char **buf)
938 {
939         struct prof_buf prof_buf = { 0, 0, 0, 0 };
940
941         dump_profile(root, 0, dump_profile_to_buffer_cb, &prof_buf);
942         if (prof_buf.err) {
943                 *buf = NULL;
944                 return ENOMEM;
945         }
946         add_data_to_buffer(&prof_buf, "", 1); /* append nul */
947         if (prof_buf.max - prof_buf.cur > (prof_buf.max >> 3)) {
948                 char *newptr = realloc(prof_buf.base, prof_buf.cur);
949                 if (newptr)
950                         prof_buf.base = newptr;
951         }
952         *buf = prof_buf.base;
953         return 0;
954 }
955 #endif
956
957 /*
958  * prof_tree.c --- these routines maintain the parse tree of the
959  *      config file.
960  * 
961  * All of the details of how the tree is stored is abstracted away in
962  * this file; all of the other profile routines build, access, and
963  * modify the tree via the accessor functions found in this file.
964  *
965  * Each node may represent either a relation or a section header.
966  * 
967  * A section header must have its value field set to 0, and may a one
968  * or more child nodes, pointed to by first_child.
969  * 
970  * A relation has as its value a pointer to allocated memory
971  * containing a string.  Its first_child pointer must be null.
972  *
973  */
974
975 /*
976  * Free a node, and any children
977  */
978 void profile_free_node(struct profile_node *node)
979 {
980         struct profile_node *child, *next;
981
982         if (node->magic != PROF_MAGIC_NODE)
983                 return;
984         
985         if (node->name)
986                 free(node->name);
987         if (node->value)
988                 free(node->value);
989
990         for (child=node->first_child; child; child = next) {
991                 next = child->next;
992                 profile_free_node(child);
993         }
994         node->magic = 0;
995         
996         free(node);
997 }
998
999 #ifndef HAVE_STRDUP
1000 #undef strdup
1001 #define strdup MYstrdup
1002 static char *MYstrdup (const char *s)
1003 {
1004     size_t sz = strlen(s) + 1;
1005     char *p = malloc(sz);
1006     if (p != 0)
1007         memcpy(p, s, sz);
1008     return p;
1009 }
1010 #endif
1011
1012 /*
1013  * Create a node
1014  */
1015 errcode_t profile_create_node(const char *name, const char *value,
1016                               struct profile_node **ret_node)
1017 {
1018         struct profile_node *new;
1019
1020         new = malloc(sizeof(struct profile_node));
1021         if (!new)
1022                 return ENOMEM;
1023         memset(new, 0, sizeof(struct profile_node));
1024         new->name = strdup(name);
1025         if (new->name == 0) {
1026             profile_free_node(new);
1027             return ENOMEM;
1028         }
1029         if (value) {
1030                 new->value = strdup(value);
1031                 if (new->value == 0) {
1032                     profile_free_node(new);
1033                     return ENOMEM;
1034                 }
1035         }
1036         new->magic = PROF_MAGIC_NODE;
1037
1038         *ret_node = new;
1039         return 0;
1040 }
1041
1042 /*
1043  * This function verifies that all of the representation invarients of
1044  * the profile are true.  If not, we have a programming bug somewhere,
1045  * probably in this file.
1046  */
1047 #ifdef DEBUG_PROGRAM
1048 errcode_t profile_verify_node(struct profile_node *node)
1049 {
1050         struct profile_node *p, *last;
1051         errcode_t       retval;
1052
1053         CHECK_MAGIC(node);
1054
1055         if (node->value && node->first_child)
1056                 return PROF_SECTION_WITH_VALUE;
1057
1058         last = 0;
1059         for (p = node->first_child; p; last = p, p = p->next) {
1060                 if (p->prev != last)
1061                         return PROF_BAD_LINK_LIST;
1062                 if (last && (last->next != p))
1063                         return PROF_BAD_LINK_LIST;
1064                 if (node->group_level+1 != p->group_level)
1065                         return PROF_BAD_GROUP_LVL;
1066                 if (p->parent != node)
1067                         return PROF_BAD_PARENT_PTR;
1068                 retval = profile_verify_node(p);
1069                 if (retval)
1070                         return retval;
1071         }
1072         return 0;
1073 }
1074 #endif
1075
1076 /*
1077  * Add a node to a particular section
1078  */
1079 errcode_t profile_add_node(struct profile_node *section, const char *name,
1080                            const char *value, struct profile_node **ret_node)
1081 {
1082         errcode_t retval;
1083         struct profile_node *p, *last, *new;
1084
1085         CHECK_MAGIC(section);
1086
1087         if (section->value)
1088                 return PROF_ADD_NOT_SECTION;
1089
1090         /*
1091          * Find the place to insert the new node.  We look for the
1092          * place *after* the last match of the node name, since 
1093          * order matters.
1094          */
1095         for (p=section->first_child, last = 0; p; last = p, p = p->next) {
1096                 int cmp;
1097                 cmp = strcmp(p->name, name);
1098                 if (cmp > 0)
1099                         break;
1100         }
1101         retval = profile_create_node(name, value, &new);
1102         if (retval)
1103                 return retval;
1104         new->group_level = section->group_level+1;
1105         new->deleted = 0;
1106         new->parent = section;
1107         new->prev = last;
1108         new->next = p;
1109         if (p)
1110                 p->prev = new;
1111         if (last)
1112                 last->next = new;
1113         else
1114                 section->first_child = new;
1115         if (ret_node)
1116                 *ret_node = new;
1117         return 0;
1118 }
1119
1120 /*
1121  * Iterate through the section, returning the nodes which match
1122  * the given name.  If name is NULL, then interate through all the
1123  * nodes in the section.  If section_flag is non-zero, only return the
1124  * section which matches the name; don't return relations.  If value
1125  * is non-NULL, then only return relations which match the requested
1126  * value.  (The value argument is ignored if section_flag is non-zero.)
1127  * 
1128  * The first time this routine is called, the state pointer must be
1129  * null.  When this profile_find_node_relation() returns, if the state
1130  * pointer is non-NULL, then this routine should be called again.
1131  * (This won't happen if section_flag is non-zero, obviously.)
1132  *
1133  */
1134 errcode_t profile_find_node(struct profile_node *section, const char *name,
1135                             const char *value, int section_flag, void **state,
1136                             struct profile_node **node)
1137 {
1138         struct profile_node *p;
1139
1140         CHECK_MAGIC(section);
1141         p = *state;
1142         if (p) {
1143                 CHECK_MAGIC(p);
1144         } else
1145                 p = section->first_child;
1146         
1147         for (; p; p = p->next) {
1148                 if (name && (strcmp(p->name, name)))
1149                         continue;
1150                 if (section_flag) {
1151                         if (p->value)
1152                                 continue;
1153                 } else {
1154                         if (!p->value)
1155                                 continue;
1156                         if (value && (strcmp(p->value, value)))
1157                                 continue;
1158                 }
1159                 if (p->deleted)
1160                     continue;
1161                 /* A match! */
1162                 if (node)
1163                         *node = p;
1164                 break;
1165         }
1166         if (p == 0) {
1167                 *state = 0;
1168                 return section_flag ? PROF_NO_SECTION : PROF_NO_RELATION;
1169         }
1170         /*
1171          * OK, we've found one match; now let's try to find another
1172          * one.  This way, if we return a non-zero state pointer,
1173          * there's guaranteed to be another match that's returned.
1174          */
1175         for (p = p->next; p; p = p->next) {
1176                 if (name && (strcmp(p->name, name)))
1177                         continue;
1178                 if (section_flag) {
1179                         if (p->value)
1180                                 continue;
1181                 } else {
1182                         if (!p->value)
1183                                 continue;
1184                         if (value && (strcmp(p->value, value)))
1185                                 continue;
1186                 }
1187                 /* A match! */
1188                 break;
1189         }
1190         *state = p;
1191         return 0;
1192 }
1193
1194 /*
1195  * This is a general-purpose iterator for returning all nodes that
1196  * match the specified name array.  
1197  */
1198 struct profile_iterator {
1199         prf_magic_t             magic;
1200         profile_t               profile;
1201         int                     flags;
1202         const char              *const *names;
1203         const char              *name;
1204         prf_file_t              file;
1205         int                     file_serial;
1206         int                     done_idx;
1207         struct profile_node     *node;
1208         int                     num;
1209 };
1210
1211 errcode_t 
1212 profile_iterator_create(profile_t profile, const char *const *names, int flags,
1213                         void **ret_iter)
1214 {
1215         struct profile_iterator *iter;
1216         int     done_idx = 0;
1217
1218         if (profile == 0)
1219                 return PROF_NO_PROFILE;
1220         if (profile->magic != PROF_MAGIC_PROFILE)
1221                 return PROF_MAGIC_PROFILE;
1222         if (!names)
1223                 return PROF_BAD_NAMESET;
1224         if (!(flags & PROFILE_ITER_LIST_SECTION)) {
1225                 if (!names[0])
1226                         return PROF_BAD_NAMESET;
1227                 done_idx = 1;
1228         }
1229
1230         if ((iter = malloc(sizeof(struct profile_iterator))) == NULL)
1231                 return ENOMEM;
1232
1233         iter->magic = PROF_MAGIC_ITERATOR;
1234         iter->profile = profile;
1235         iter->names = names;
1236         iter->flags = flags;
1237         iter->file = profile->first_file;
1238         iter->done_idx = done_idx;
1239         iter->node = 0;
1240         iter->num = 0;
1241         *ret_iter = iter;
1242         return 0;
1243 }
1244
1245 void profile_iterator_free(void **iter_p)
1246 {
1247         struct profile_iterator *iter;
1248
1249         if (!iter_p)
1250                 return;
1251         iter = *iter_p;
1252         if (!iter || iter->magic != PROF_MAGIC_ITERATOR)
1253                 return;
1254         free(iter);
1255         *iter_p = 0;
1256 }
1257
1258 /*
1259  * Note: the returned character strings in ret_name and ret_value
1260  * points to the stored character string in the parse string.  Before
1261  * this string value is returned to a calling application
1262  * (profile_node_iterator is not an exported interface), it should be
1263  * strdup()'ed.
1264  */
1265 errcode_t profile_node_iterator(void **iter_p, struct profile_node **ret_node,
1266                                 char **ret_name, char **ret_value)
1267 {
1268         struct profile_iterator         *iter = *iter_p;
1269         struct profile_node             *section, *p;
1270         const char                      *const *cpp;
1271         errcode_t                       retval;
1272         int                             skip_num = 0;
1273
1274         if (!iter || iter->magic != PROF_MAGIC_ITERATOR)
1275                 return PROF_MAGIC_ITERATOR;
1276         if (iter->file && iter->file->magic != PROF_MAGIC_FILE)
1277             return PROF_MAGIC_FILE;
1278         /*
1279          * If the file has changed, then the node pointer is invalid,
1280          * so we'll have search the file again looking for it.
1281          */
1282         if (iter->node && (iter->file->upd_serial != iter->file_serial)) {
1283                 iter->flags &= ~PROFILE_ITER_FINAL_SEEN;
1284                 skip_num = iter->num;
1285                 iter->node = 0;
1286         }
1287         if (iter->node && iter->node->magic != PROF_MAGIC_NODE) {
1288             return PROF_MAGIC_NODE;
1289         }
1290 get_new_file:
1291         if (iter->node == 0) {
1292                 if (iter->file == 0 ||
1293                     (iter->flags & PROFILE_ITER_FINAL_SEEN)) {
1294                         profile_iterator_free(iter_p);
1295                         if (ret_node)
1296                                 *ret_node = 0;
1297                         if (ret_name)
1298                                 *ret_name = 0;
1299                         if (ret_value)
1300                                 *ret_value =0;
1301                         return 0;
1302                 }
1303                 if ((retval = profile_update_file(iter->file))) {
1304                     if (retval == ENOENT || retval == EACCES) {
1305                         /* XXX memory leak? */
1306                         iter->file = iter->file->next;
1307                         skip_num = 0;
1308                         retval = 0;
1309                         goto get_new_file;
1310                     } else {
1311                         profile_iterator_free(iter_p);
1312                         return retval;
1313                     }
1314                 }
1315                 iter->file_serial = iter->file->upd_serial;
1316                 /*
1317                  * Find the section to list if we are a LIST_SECTION,
1318                  * or find the containing section if not.
1319                  */
1320                 section = iter->file->root;
1321                 for (cpp = iter->names; cpp[iter->done_idx]; cpp++) {
1322                         for (p=section->first_child; p; p = p->next) {
1323                                 if (!strcmp(p->name, *cpp) && !p->value)
1324                                         break;
1325                         }
1326                         if (!p) {
1327                                 section = 0;
1328                                 break;
1329                         }
1330                         section = p;
1331                         if (p->final)
1332                                 iter->flags |= PROFILE_ITER_FINAL_SEEN;
1333                 }
1334                 if (!section) {
1335                         iter->file = iter->file->next;
1336                         skip_num = 0;
1337                         goto get_new_file;
1338                 }
1339                 iter->name = *cpp;
1340                 iter->node = section->first_child;
1341         }
1342         /*
1343          * OK, now we know iter->node is set up correctly.  Let's do
1344          * the search.
1345          */
1346         for (p = iter->node; p; p = p->next) {
1347                 if (iter->name && strcmp(p->name, iter->name))
1348                         continue;
1349                 if ((iter->flags & PROFILE_ITER_SECTIONS_ONLY) &&
1350                     p->value)
1351                         continue;
1352                 if ((iter->flags & PROFILE_ITER_RELATIONS_ONLY) &&
1353                     !p->value)
1354                         continue;
1355                 if (skip_num > 0) {
1356                         skip_num--;
1357                         continue;
1358                 }
1359                 if (p->deleted)
1360                         continue;
1361                 break;
1362         }
1363         iter->num++;
1364         if (!p) {
1365                 iter->file = iter->file->next;
1366                 if (iter->file) {
1367                 }
1368                 iter->node = 0;
1369                 skip_num = 0;
1370                 goto get_new_file;
1371         }
1372         if ((iter->node = p->next) == NULL)
1373                 iter->file = iter->file->next;
1374         if (ret_node)
1375                 *ret_node = p;
1376         if (ret_name)
1377                 *ret_name = p->name;
1378         if (ret_value)
1379                 *ret_value = p->value;
1380         return 0;
1381 }
1382
1383
1384 /*
1385  * prof_get.c --- routines that expose the public interfaces for
1386  *      querying items from the profile.
1387  *
1388  */
1389
1390 /*
1391  * This function only gets the first value from the file; it is a
1392  * helper function for profile_get_string, profile_get_integer, etc.
1393  */
1394 errcode_t profile_get_value(profile_t profile, const char *name,
1395                             const char *subname, const char *subsubname,
1396                             const char **ret_value)
1397 {
1398         errcode_t               retval;
1399         void                    *state;
1400         char                    *value;
1401         const char              *names[4];
1402
1403         names[0] = name;
1404         names[1] = subname;
1405         names[2] = subsubname;
1406         names[3] = 0;
1407
1408         if ((retval = profile_iterator_create(profile, names,
1409                                               PROFILE_ITER_RELATIONS_ONLY,
1410                                               &state)))
1411                 return retval;
1412
1413         if ((retval = profile_node_iterator(&state, 0, 0, &value)))
1414                 goto cleanup;
1415
1416         if (value)
1417                 *ret_value = value;
1418         else
1419                 retval = PROF_NO_RELATION;
1420         
1421 cleanup:
1422         profile_iterator_free(&state);
1423         return retval;
1424 }
1425
1426 errcode_t 
1427 profile_get_string(profile_t profile, const char *name, const char *subname,
1428                    const char *subsubname, const char *def_val,
1429                    char **ret_string)
1430 {
1431         const char      *value;
1432         errcode_t       retval;
1433
1434         if (profile) {
1435                 retval = profile_get_value(profile, name, subname, 
1436                                            subsubname, &value);
1437                 if (retval == PROF_NO_SECTION || retval == PROF_NO_RELATION)
1438                         value = def_val;
1439                 else if (retval)
1440                         return retval;
1441         } else
1442                 value = def_val;
1443     
1444         if (value) {
1445                 *ret_string = malloc(strlen(value)+1);
1446                 if (*ret_string == 0)
1447                         return ENOMEM;
1448                 strcpy(*ret_string, value);
1449         } else
1450                 *ret_string = 0;
1451         return 0;
1452 }
1453
1454 errcode_t 
1455 profile_get_integer(profile_t profile, const char *name, const char *subname,
1456                     const char *subsubname, int def_val, int *ret_int)
1457 {
1458         const char      *value;
1459         errcode_t       retval;
1460         char            *end_value;
1461         long            ret_long;
1462
1463         *ret_int = def_val;
1464         if (profile == 0)
1465                 return 0;
1466
1467         retval = profile_get_value(profile, name, subname, subsubname, &value);
1468         if (retval == PROF_NO_SECTION || retval == PROF_NO_RELATION) {
1469                 *ret_int = def_val;
1470                 return 0;
1471         } else if (retval)
1472                 return retval;
1473
1474         if (value[0] == 0)
1475             /* Empty string is no good.  */
1476             return PROF_BAD_INTEGER;
1477         errno = 0;
1478         ret_long = strtol (value, &end_value, 10);
1479
1480         /* Overflow or underflow.  */
1481         if ((ret_long == LONG_MIN || ret_long == LONG_MAX) && errno != 0)
1482             return PROF_BAD_INTEGER;
1483         /* Value outside "int" range.  */
1484         if ((long) (int) ret_long != ret_long)
1485             return PROF_BAD_INTEGER;
1486         /* Garbage in string.  */
1487         if (end_value != value + strlen (value))
1488             return PROF_BAD_INTEGER;
1489         
1490    
1491         *ret_int = ret_long;
1492         return 0;
1493 }
1494
1495 static const char *const conf_yes[] = {
1496     "y", "yes", "true", "t", "1", "on",
1497     0,
1498 };
1499
1500 static const char *const conf_no[] = {
1501     "n", "no", "false", "nil", "0", "off",
1502     0,
1503 };
1504
1505 static errcode_t
1506 profile_parse_boolean(const char *s, int *ret_boolean)
1507 {
1508     const char *const *p;
1509     
1510     if (ret_boolean == NULL)
1511         return PROF_EINVAL;
1512
1513     for(p=conf_yes; *p; p++) {
1514                 if (!strcasecmp(*p,s)) {
1515                         *ret_boolean = 1;
1516                 return 0;
1517                 }
1518     }
1519
1520     for(p=conf_no; *p; p++) {
1521                 if (!strcasecmp(*p,s)) {
1522                         *ret_boolean = 0;
1523                         return 0;
1524                 }
1525     }
1526         
1527         return PROF_BAD_BOOLEAN;
1528 }
1529
1530 errcode_t 
1531 profile_get_boolean(profile_t profile, const char *name, const char *subname,
1532                     const char *subsubname, int def_val, int *ret_boolean)
1533 {
1534         const char      *value;
1535         errcode_t       retval;
1536
1537         if (profile == 0) {
1538                 *ret_boolean = def_val;
1539                 return 0;
1540         }
1541
1542         retval = profile_get_value(profile, name, subname, subsubname, &value);
1543         if (retval == PROF_NO_SECTION || retval == PROF_NO_RELATION) {
1544                 *ret_boolean = def_val;
1545                 return 0;
1546         } else if (retval)
1547                 return retval;
1548    
1549         return profile_parse_boolean (value, ret_boolean);
1550 }
1551
1552 errcode_t 
1553 profile_iterator(void **iter_p, char **ret_name, char **ret_value)
1554 {
1555         char *name, *value;
1556         errcode_t       retval;
1557         
1558         retval = profile_node_iterator(iter_p, 0, &name, &value);
1559         if (retval)
1560                 return retval;
1561
1562         if (ret_name) {
1563                 if (name) {
1564                         *ret_name = malloc(strlen(name)+1);
1565                         if (!*ret_name)
1566                                 return ENOMEM;
1567                         strcpy(*ret_name, name);
1568                 } else
1569                         *ret_name = 0;
1570         }
1571         if (ret_value) {
1572                 if (value) {
1573                         *ret_value = malloc(strlen(value)+1);
1574                         if (!*ret_value) {
1575                                 if (ret_name) {
1576                                         free(*ret_name);
1577                                         *ret_name = 0;
1578                                 }
1579                                 return ENOMEM;
1580                         }
1581                         strcpy(*ret_value, value);
1582                 } else
1583                         *ret_value = 0;
1584         }
1585         return 0;
1586 }
1587
1588 #ifdef DEBUG_PROGRAM
1589
1590 /*
1591  * test_profile.c --- testing program for the profile routine
1592  */
1593
1594 #include "argv_parse.h"
1595 #include "profile_helpers.h"
1596
1597 const char *program_name = "test_profile";
1598
1599 #define PRINT_VALUE     1
1600 #define PRINT_VALUES    2
1601
1602 static void do_cmd(profile_t profile, char **argv)
1603 {
1604         errcode_t       retval;
1605         const char      **names, *value;
1606         char            **values, **cpp;
1607         char    *cmd;
1608         int             print_status;
1609
1610         cmd = *(argv);
1611         names = (const char **) argv + 1;
1612         print_status = 0;
1613         retval = 0;
1614         if (cmd == 0)
1615                 return;
1616         if (!strcmp(cmd, "query")) {
1617                 retval = profile_get_values(profile, names, &values);
1618                 print_status = PRINT_VALUES;
1619         } else if (!strcmp(cmd, "query1")) {
1620                 const char *name = 0;
1621                 const char *subname = 0;
1622                 const char *subsubname = 0;
1623
1624                 name = names[0];
1625                 if (name)
1626                         subname = names[1];
1627                 if (subname)
1628                         subsubname = names[2];
1629                 if (subsubname && names[3]) {
1630                         fprintf(stderr, 
1631                                 "Only 3 levels are allowed with query1\n");
1632                         retval = EINVAL;
1633                 } else
1634                         retval = profile_get_value(profile, name, subname, 
1635                                                    subsubname, &value);
1636                 print_status = PRINT_VALUE;
1637         } else if (!strcmp(cmd, "list_sections")) {
1638                 retval = profile_get_subsection_names(profile, names, 
1639                                                       &values);
1640                 print_status = PRINT_VALUES;
1641         } else if (!strcmp(cmd, "list_relations")) {
1642                 retval = profile_get_relation_names(profile, names, 
1643                                                     &values);
1644                 print_status = PRINT_VALUES;
1645         } else if (!strcmp(cmd, "dump")) {
1646                 retval = profile_write_tree_file
1647                         (profile->first_file->root, stdout);
1648 #if 0
1649         } else if (!strcmp(cmd, "clear")) {
1650                 retval = profile_clear_relation(profile, names);
1651         } else if (!strcmp(cmd, "update")) {
1652                 retval = profile_update_relation(profile, names+2,
1653                                                  *names, *(names+1));
1654 #endif
1655         } else if (!strcmp(cmd, "verify")) {
1656                 retval = profile_verify_node
1657                         (profile->first_file->root);
1658 #if 0
1659         } else if (!strcmp(cmd, "rename_section")) {
1660                 retval = profile_rename_section(profile, names+1, *names);
1661         } else if (!strcmp(cmd, "add")) {
1662                 value = *names;
1663                 if (strcmp(value, "NULL") == 0)
1664                         value = NULL;
1665                 retval = profile_add_relation(profile, names+1, value);
1666         } else if (!strcmp(cmd, "flush")) {
1667                 retval = profile_flush(profile);
1668 #endif
1669         } else {
1670                 printf("Invalid command.\n");
1671         }
1672         if (retval) {
1673                 com_err(cmd, retval, "");
1674                 print_status = 0;
1675         }
1676         switch (print_status) {
1677         case PRINT_VALUE:
1678                 printf("%s\n", value);
1679                 break;
1680         case PRINT_VALUES:
1681                 for (cpp = values; *cpp; cpp++)
1682                         printf("%s\n", *cpp);
1683                 profile_free_list(values);
1684                 break;
1685         }
1686 }
1687
1688 static void do_batchmode(profile_t profile)
1689 {
1690         int             argc, ret;
1691         char            **argv;
1692         char            buf[256];
1693
1694         while (!feof(stdin)) {
1695                 if (fgets(buf, sizeof(buf), stdin) == NULL)
1696                         break;
1697                 printf(">%s", buf);
1698                 ret = argv_parse(buf, &argc, &argv);
1699                 if (ret != 0) {
1700                         printf("Argv_parse returned %d!\n", ret);
1701                         continue;
1702                 }
1703                 do_cmd(profile, argv);
1704                 printf("\n");
1705                 argv_free(argv);
1706         }
1707         profile_release(profile);
1708         exit(0);
1709         
1710 }
1711
1712 void syntax_err_report(const char *filename, long err, int line_num)
1713 {
1714         fprintf(stderr, "Syntax error in %s, line number %d: %s\n",
1715                 filename, line_num, error_message(err));
1716         exit(1);
1717 }
1718
1719 int main(int argc, char **argv)
1720 {
1721     profile_t   profile;
1722     long        retval;
1723     char        *cmd;
1724     
1725     if (argc < 2) {
1726             fprintf(stderr, "Usage: %s filename [cmd argset]\n", program_name);
1727             exit(1);
1728     }
1729
1730     initialize_prof_error_table();
1731
1732     profile_set_syntax_err_cb(syntax_err_report);
1733     
1734     retval = profile_init_path(argv[1], &profile);
1735     if (retval) {
1736         com_err(program_name, retval, "while initializing profile");
1737         exit(1);
1738     }
1739     cmd = *(argv+2);
1740     if (!cmd || !strcmp(cmd, "batch"))
1741             do_batchmode(profile);
1742     else
1743             do_cmd(profile, argv+2);
1744     profile_release(profile);
1745
1746     return 0;
1747 }
1748
1749 #endif