Add support for a global "ethereal.conf" preferences file, stored in the
[obnox/wireshark/wip.git] / prefs.c
1 /* prefs.c
2  * Routines for handling preferences
3  *
4  * $Id: prefs.c,v 1.31 2000/07/05 09:40:41 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@zing.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * 
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  * 
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  * 
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33
34 #ifdef HAVE_DIRECT_H
35 #include <direct.h>
36 #endif
37
38 #include <stdlib.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include <errno.h>
42
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46
47 #include <sys/stat.h>
48
49 #include "globals.h"
50 #include "packet.h"
51 #include "file.h"
52 #include "prefs.h"
53 #include "column.h"
54 #include "print.h"
55 #include "util.h"
56
57 #include "prefs-int.h"
58
59 /* Internal functions */
60 static int    set_pref(gchar*, gchar*);
61 static GList *get_string_list(gchar *);
62 static void   clear_string_list(GList *);
63
64 #define PF_NAME "preferences"
65
66 #define GPF_PATH        DATAFILE_DIR "/ethereal.conf"
67
68 static gboolean init_prefs = TRUE;
69 static gchar *pf_path = NULL;
70
71 e_prefs prefs;
72
73 gchar   *gui_ptree_line_style_text[] =
74         { "NONE", "SOLID", "DOTTED", "TABBED", NULL };
75
76 gchar   *gui_ptree_expander_style_text[] =
77         { "NONE", "SQUARE", "TRIANGLE", "CIRCULAR", NULL };
78
79
80 /*
81  * List of modules with preference settings.
82  */
83 static GList *modules;
84
85 /*
86  * Register a module that will have preferences.
87  * Specify the name used for the module in the preferences file, the
88  * title used in the tab for it in a preferences dialog box, and a
89  * routine to call back when we apply the preferences.
90  */
91 module_t *
92 prefs_register_module(const char *name, const char *title,
93     void (*apply_cb)(void))
94 {
95         module_t *module;
96
97         module = g_malloc(sizeof (module_t));
98         module->name = name;
99         module->title = title;
100         module->apply_cb = apply_cb;
101         module->prefs = NULL;   /* no preferences, to start */
102         module->numprefs = 0;
103
104         modules = g_list_append(modules, module);
105
106         return module;
107 }
108
109 /*
110  * Find a module, given its name.
111  */
112 static gint
113 module_match(gconstpointer a, gconstpointer b)
114 {
115         const module_t *module = a;
116         const char *name = b;
117
118         return strcmp(name, module->name);
119 }
120
121 static module_t *
122 find_module(char *name)
123 {
124         GList *list_entry;
125
126         list_entry = g_list_find_custom(modules, name, module_match);
127         if (list_entry == NULL)
128                 return NULL;    /* no such module */
129         return (module_t *) list_entry->data;
130 }
131
132 typedef struct {
133         module_cb callback;
134         gpointer user_data;
135 } module_cb_arg_t;
136
137 static void
138 do_module_callback(gpointer data, gpointer user_data)
139 {
140         module_t *module = data;
141         module_cb_arg_t *arg = user_data;
142
143         (*arg->callback)(module, arg->user_data);
144 }
145
146 /*
147  * Call a callback function, with a specified argument, for each module.
148  */
149 void
150 prefs_module_foreach(module_cb callback, gpointer user_data)
151 {
152         module_cb_arg_t arg;
153
154         arg.callback = callback;
155         arg.user_data = user_data;
156         g_list_foreach(modules, do_module_callback, &arg);
157 }
158
159 static void
160 call_apply_cb(gpointer data, gpointer user_data)
161 {
162         module_t *module = data;
163
164         (*module->apply_cb)();
165 }
166
167 /*
168  * Call the "apply" callback function for each module.
169  */
170 void
171 prefs_apply_all(void)
172 {
173         g_list_foreach(modules, call_apply_cb, NULL);
174 }
175
176 /*
177  * Register a preference in a module's list of preferences.
178  */
179 static pref_t *
180 register_preference(module_t *module, const char *name, const char *title,
181     const char *description)
182 {
183         pref_t *preference;
184
185         preference = g_malloc(sizeof (pref_t));
186         preference->name = name;
187         preference->title = title;
188         preference->description = description;
189         preference->ordinal = module->numprefs;
190
191         module->prefs = g_list_append(module->prefs, preference);
192         module->numprefs++;
193
194         return preference;
195 }
196
197 /*
198  * Find a preference in a module's list of preferences, given the module
199  * and the preference's name.
200  */
201 static gint
202 preference_match(gconstpointer a, gconstpointer b)
203 {
204         const pref_t *pref = a;
205         const char *name = b;
206
207         return strcmp(name, pref->name);
208 }
209
210 static struct preference *
211 find_preference(module_t *module, char *name)
212 {
213         GList *list_entry;
214
215         list_entry = g_list_find_custom(module->prefs, name, preference_match);
216         if (list_entry == NULL)
217                 return NULL;    /* no such preference */
218         return (struct preference *) list_entry->data;
219 }
220
221 /*
222  * Register a preference with an unsigned integral value.
223  */
224 void
225 prefs_register_uint_preference(module_t *module, const char *name,
226     const char *title, const char *description, guint base, guint *var)
227 {
228         pref_t *preference;
229
230         preference = register_preference(module, name, title, description);
231         preference->type = PREF_UINT;
232         preference->varp.uint = var;
233         preference->info.base = base;
234 }
235
236 /*
237  * Register a preference with an Boolean value.
238  */
239 void
240 prefs_register_bool_preference(module_t *module, const char *name,
241     const char *title, const char *description, gboolean *var)
242 {
243         pref_t *preference;
244
245         preference = register_preference(module, name, title, description);
246         preference->type = PREF_BOOL;
247         preference->varp.bool = var;
248 }
249
250 /*
251  * Register a preference with an enumerated value.
252  */
253 void
254 prefs_register_enum_preference(module_t *module, const char *name,
255     const char *title, const char *description, gint *var,
256     const enum_val *enumvals, gboolean radio_buttons)
257 {
258         pref_t *preference;
259
260         preference = register_preference(module, name, title, description);
261         preference->type = PREF_ENUM;
262         preference->varp.enump = var;
263         preference->info.enum_info.enumvals = enumvals;
264         preference->info.enum_info.radio_buttons = radio_buttons;
265 }
266
267 /*
268  * Register a preference with a character-string value.
269  */
270 void
271 prefs_register_string_preference(module_t *module, const char *name,
272     const char *title, const char *description, char **var)
273 {
274         pref_t *preference;
275
276         preference = register_preference(module, name, title, description);
277         preference->type = PREF_STRING;
278         preference->varp.string = var;
279         preference->saved_val.string = NULL;
280 }
281
282 typedef struct {
283         pref_cb callback;
284         gpointer user_data;
285 } pref_cb_arg_t;
286
287 static void
288 do_pref_callback(gpointer data, gpointer user_data)
289 {
290         pref_t *pref = data;
291         pref_cb_arg_t *arg = user_data;
292
293         (*arg->callback)(pref, arg->user_data);
294 }
295
296 /*
297  * Call a callback function, with a specified argument, for each preference
298  * in a given module.
299  */
300 void
301 prefs_pref_foreach(module_t *module, pref_cb callback, gpointer user_data)
302 {
303         pref_cb_arg_t arg;
304
305         arg.callback = callback;
306         arg.user_data = user_data;
307         g_list_foreach(module->prefs, do_pref_callback, &arg);
308 }
309
310 /*
311  * Register all non-dissector modules' preferences.
312  */
313 void
314 prefs_register_modules(void)
315 {
316 }
317
318 /* Parse through a list of comma-separated, quoted strings.  Return a
319    list of the string data */
320 static GList *
321 get_string_list(gchar *str) {
322   enum { PRE_QUOT, IN_QUOT, POST_QUOT };
323
324   gint      state = PRE_QUOT, i = 0, j = 0;
325   gboolean  backslash = FALSE;
326   gchar     cur_c, *slstr = NULL;
327   GList    *sl = NULL;
328   
329   while ((cur_c = str[i]) != '\0') {
330     if (cur_c == '"' && ! backslash) {
331       switch (state) {
332         case PRE_QUOT:
333           state = IN_QUOT;
334           slstr = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
335           j = 0;
336           break;
337         case IN_QUOT:
338           state  = POST_QUOT;
339           slstr[j] = '\0';
340           sl = g_list_append(sl, slstr);
341           break;
342         case POST_QUOT:
343           clear_string_list(sl);
344           return NULL;
345           break;
346         default:
347           break;
348       }
349     } else if (cur_c == '\\' && ! backslash) {
350       backslash = TRUE;
351     } else if (cur_c == ',' && state == POST_QUOT) {
352       state = PRE_QUOT;
353     } else if (state == IN_QUOT && j < COL_MAX_LEN) {
354       slstr[j] = str[i];
355       j++;
356     }
357     i++;
358   }
359   if (state != POST_QUOT) {
360     clear_string_list(sl);
361   }
362   return(sl);
363 }
364
365 void
366 clear_string_list(GList *sl) {
367   GList *l = sl;
368   
369   while (l) {
370     g_free(l->data);
371     l = g_list_remove_link(l, l);
372   }
373 }
374
375 /*
376  * Takes a string, a pointer to an array of "enum_val"s, and a default gint
377  * value.
378  * The array must be terminated by an entry with a null "name" string.
379  * If the string matches a "name" strings in an entry, the value from that
380  * entry is returned. Otherwise, the default value that was passed as the
381  * third argument is returned.
382  */
383 gint
384 find_val_for_string(const char *needle, const enum_val *haystack,
385     gint default_value)
386 {
387         int i = 0;
388
389         while (haystack[i].name != NULL) {
390                 if (strcasecmp(needle, haystack[i].name) == 0) {
391                         return haystack[i].value;
392                 }
393                 i++;    
394         }
395         return default_value;
396 }
397
398 /* Takes an string and a pointer to an array of strings, and a default int value.
399  * The array must be terminated by a NULL string. If the string is found in the array
400  * of strings, the index of that string in the array is returned. Otherwise, the
401  * default value that was passed as the third argument is returned.
402  */
403 static int
404 find_index_from_string_array(char *needle, char **haystack, int default_value)
405 {
406         int i = 0;
407
408         while (haystack[i] != NULL) {
409                 if (strcmp(needle, haystack[i]) == 0) {
410                         return i;
411                 }
412                 i++;    
413         }
414         return default_value;
415 }
416
417 /* Preferences file format:
418  * - Configuration directives start at the beginning of the line, and 
419  *   are terminated with a colon.
420  * - Directives can be continued on the next line by preceding them with
421  *   whitespace.
422  *
423  * Example:
424
425 # This is a comment line
426 print.command: lpr
427 print.file: /a/very/long/path/
428         to/ethereal-out.ps
429  *
430  */
431
432 #define MAX_VAR_LEN    48
433 #define MAX_VAL_LEN  1024
434
435 #define DEF_NUM_COLS    6
436
437 static void read_prefs_file(const char *pf_path, FILE *pf);
438
439 e_prefs *
440 read_prefs(int *gpf_errno_return, char **gpf_path_return,
441            int *pf_errno_return, char **pf_path_return)
442 {
443   int       i;
444   FILE     *pf;
445   fmt_data *cfmt;
446   gchar    *col_fmt[] = {"No.",      "%m", "Time",        "%t",
447                          "Source",   "%s", "Destination", "%d",
448                          "Protocol", "%p", "Info",        "%i"};
449
450   
451   if (init_prefs) {
452     /* Initialize preferences to wired-in default values.
453        They may be overridded by the global preferences file or the
454        user's preferences file. */
455     init_prefs       = FALSE;
456     prefs.pr_format  = PR_FMT_TEXT;
457     prefs.pr_dest    = PR_DEST_CMD;
458     prefs.pr_file    = g_strdup("ethereal.out");
459     prefs.pr_cmd     = g_strdup("lpr");
460     prefs.col_list = NULL;
461     for (i = 0; i < DEF_NUM_COLS; i++) {
462       cfmt = (fmt_data *) g_malloc(sizeof(fmt_data));
463       cfmt->title = g_strdup(col_fmt[i * 2]);
464       cfmt->fmt   = g_strdup(col_fmt[(i * 2) + 1]);
465       prefs.col_list = g_list_append(prefs.col_list, cfmt);
466     }
467     prefs.num_cols  = DEF_NUM_COLS;
468     prefs.st_client_fg.pixel =     0;
469     prefs.st_client_fg.red   = 32767;
470     prefs.st_client_fg.green =     0;
471     prefs.st_client_fg.blue  =     0;
472     prefs.st_client_bg.pixel = 65535;
473     prefs.st_client_bg.red   = 65535;
474     prefs.st_client_bg.green = 65535;
475     prefs.st_client_bg.blue  = 65535;
476     prefs.st_server_fg.pixel =     0;
477     prefs.st_server_fg.red   =     0;
478     prefs.st_server_fg.green =     0;
479     prefs.st_server_fg.blue  = 32767;
480     prefs.st_server_bg.pixel = 65535;
481     prefs.st_server_bg.red   = 65535;
482     prefs.st_server_bg.green = 65535;
483     prefs.st_server_bg.blue  = 65535;
484     prefs.gui_scrollbar_on_right = TRUE;
485     prefs.gui_plist_sel_browse = FALSE;
486     prefs.gui_ptree_sel_browse = FALSE;
487     prefs.gui_ptree_line_style = 0;
488     prefs.gui_ptree_expander_style = 1;
489   }
490
491   /* Read the global preferences file, if it exists. */
492   *gpf_path_return = NULL;
493   if ((pf = fopen(GPF_PATH, "r")) != NULL) {
494     /* We succeeded in opening it; read it. */
495     read_prefs_file(GPF_PATH, pf);
496     fclose(pf);
497   } else {
498     /* We failed to open it.  If we failed for some reason other than
499        "it doesn't exist", return the errno and the pathname, so our
500        caller can report the error. */
501     if (errno != ENOENT) {
502       *gpf_errno_return = errno;
503       *gpf_path_return = GPF_PATH;
504     }
505   }
506
507   /* Construct the pathname of the user's preferences file. */
508   if (! pf_path) {
509     pf_path = (gchar *) g_malloc(strlen(get_home_dir()) + strlen(PF_DIR) +
510       strlen(PF_NAME) + 4);
511     sprintf(pf_path, "%s/%s/%s", get_home_dir(), PF_DIR, PF_NAME);
512   }
513     
514   /* Read the user's preferences file, if it exists. */
515   *pf_path_return = NULL;
516   if ((pf = fopen(pf_path, "r")) != NULL) {
517     /* We succeeded in opening it; read it. */
518     read_prefs_file(pf_path, pf);
519     fclose(pf);
520   } else {
521     /* We failed to open it.  If we failed for some reason other than
522        "it doesn't exist", return the errno and the pathname, so our
523        caller can report the error. */
524     if (errno != ENOENT) {
525       *pf_errno_return = errno;
526       *pf_path_return = pf_path;
527     }
528   }
529   
530   return &prefs;
531 }
532
533 static void
534 read_prefs_file(const char *pf_path, FILE *pf)
535 {
536   enum { START, IN_VAR, PRE_VAL, IN_VAL, IN_SKIP };
537   gchar     cur_var[MAX_VAR_LEN], cur_val[MAX_VAL_LEN];
538   int       got_c, state = START;
539   gboolean  got_val = FALSE;
540   gint      var_len = 0, val_len = 0, fline = 1, pline = 1;
541
542   while ((got_c = getc(pf)) != EOF) {
543     if (got_c == '\n') {
544       state = START;
545       fline++;
546       continue;
547     }
548     if (var_len >= MAX_VAR_LEN) {
549       g_warning ("%s line %d: Variable too long", pf_path, fline);
550       state = IN_SKIP;
551       var_len = 0;
552       continue;
553     }
554     if (val_len >= MAX_VAL_LEN) {
555       g_warning ("%s line %d: Value too long", pf_path, fline);
556       state = IN_SKIP;
557       var_len = 0;
558       continue;
559     }
560     
561     switch (state) {
562       case START:
563         if (isalnum(got_c)) {
564           if (var_len > 0) {
565             if (got_val) {
566               cur_var[var_len] = '\0';
567               cur_val[val_len] = '\0';
568               switch (set_pref(cur_var, cur_val)) {
569
570               case PREFS_SET_SYNTAX_ERR:
571                 g_warning ("%s line %d: Syntax error", pf_path, pline);
572                 break;
573
574               case PREFS_SET_NO_SUCH_PREF:
575                 g_warning ("%s line %d: No such preference \"%s\"", pf_path,
576                                 pline, cur_var);
577                 break;
578               }
579             } else {
580               g_warning ("%s line %d: Incomplete preference", pf_path, pline);
581             }
582           }
583           state      = IN_VAR;
584           got_val    = FALSE;
585           cur_var[0] = got_c;
586           var_len    = 1;
587           pline = fline;
588         } else if (isspace(got_c) && var_len > 0 && got_val) {
589           state = PRE_VAL;
590         } else if (got_c == '#') {
591           state = IN_SKIP;
592         } else {
593           g_warning ("%s line %d: Malformed line", pf_path, fline);
594         }
595         break;
596       case IN_VAR:
597         if (got_c != ':') {
598           cur_var[var_len] = got_c;
599           var_len++;
600         } else {
601           state   = PRE_VAL;
602           val_len = 0;
603           got_val = TRUE;
604         }
605         break;
606       case PRE_VAL:
607         if (!isspace(got_c)) {
608           state = IN_VAL;
609           cur_val[val_len] = got_c;
610           val_len++;
611         }
612         break;
613       case IN_VAL:
614         if (got_c != '#')  {
615           cur_val[val_len] = got_c;
616           val_len++;
617         } else {
618           while (isspace(cur_val[val_len]) && val_len > 0)
619             val_len--;
620           state = IN_SKIP;
621         }
622         break;
623     }
624   }
625   if (var_len > 0) {
626     if (got_val) {
627       cur_var[var_len] = '\0';
628       cur_val[val_len] = '\0';
629       switch (set_pref(cur_var, cur_val)) {
630
631       case PREFS_SET_SYNTAX_ERR:
632         g_warning ("%s line %d: Syntax error", pf_path, pline);
633         break;
634
635       case PREFS_SET_NO_SUCH_PREF:
636         g_warning ("%s line %d: No such preference \"%s\"", pf_path,
637                         pline, cur_var);
638         break;
639       }
640     } else {
641       g_warning ("%s line %d: Incomplete preference", pf_path, pline);
642     }
643   }
644 }
645
646 /*
647  * Given a string of the form "<pref name>:<pref value>", as might appear
648  * as an argument to a "-o" option, parse it and set the preference in
649  * question.  Return an indication of whether it succeeded or failed
650  * in some fashion.
651  */
652 int
653 prefs_set_pref(char *prefarg)
654 {
655         u_char *p, *colonp;
656         int ret;
657
658         colonp = strchr(prefarg, ':');
659         if (colonp == NULL)
660                 return PREFS_SET_SYNTAX_ERR;
661
662         p = colonp;
663         *p++ = '\0';
664
665         /*
666          * Skip over any white space (there probably won't be any, but
667          * as we allow it in the preferences file, we might as well
668          * allow it here).
669          */
670         while (isspace(*p))
671                 p++;
672         if (*p == '\0') {
673                 /*
674                  * Put the colon back, so if our caller uses, in an
675                  * error message, the string they passed us, the message
676                  * looks correct.
677                  */
678                 *colonp = ':';
679                 return PREFS_SET_SYNTAX_ERR;
680         }
681
682         ret = set_pref(prefarg, p);
683         *colonp = ':';  /* put the colon back */
684         return ret;
685 }
686
687 #define PRS_PRINT_FMT    "print.format"
688 #define PRS_PRINT_DEST   "print.destination"
689 #define PRS_PRINT_FILE   "print.file"
690 #define PRS_PRINT_CMD    "print.command"
691 #define PRS_COL_FMT      "column.format"
692 #define PRS_STREAM_CL_FG "stream.client.fg"
693 #define PRS_STREAM_CL_BG "stream.client.bg"
694 #define PRS_STREAM_SR_FG "stream.server.fg"
695 #define PRS_STREAM_SR_BG "stream.server.bg"
696 #define PRS_GUI_SCROLLBAR_ON_RIGHT "gui.scrollbar_on_right"
697 #define PRS_GUI_PLIST_SEL_BROWSE "gui.packet_list_sel_browse"
698 #define PRS_GUI_PTREE_SEL_BROWSE "gui.protocol_tree_sel_browse"
699 #define PRS_GUI_PTREE_LINE_STYLE "gui.protocol_tree_line_style"
700 #define PRS_GUI_PTREE_EXPANDER_STYLE "gui.protocol_tree_expander_style"
701
702 #define RED_COMPONENT(x)   ((((x) >> 16) & 0xff) * 65535 / 255)
703 #define GREEN_COMPONENT(x) ((((x) >>  8) & 0xff) * 65535 / 255)
704 #define BLUE_COMPONENT(x)   (((x)        & 0xff) * 65535 / 255)
705
706 static gchar *pr_formats[] = { "text", "postscript" };
707 static gchar *pr_dests[]   = { "command", "file" };
708
709 static int
710 set_pref(gchar *pref_name, gchar *value)
711 {
712   GList    *col_l;
713   gint      llen;
714   fmt_data *cfmt;
715   unsigned long int cval;
716   guint    uval;
717   char     *p;
718   gchar    *dotp;
719   module_t *module;
720   pref_t   *pref;
721
722   if (strcmp(pref_name, PRS_PRINT_FMT) == 0) {
723     if (strcmp(value, pr_formats[PR_FMT_TEXT]) == 0) {
724       prefs.pr_format = PR_FMT_TEXT;
725     } else if (strcmp(value, pr_formats[PR_FMT_PS]) == 0) {
726       prefs.pr_format = PR_FMT_PS;
727     } else {
728       return PREFS_SET_SYNTAX_ERR;
729     }
730   } else if (strcmp(pref_name, PRS_PRINT_DEST) == 0) {
731     if (strcmp(value, pr_dests[PR_DEST_CMD]) == 0) {
732       prefs.pr_dest = PR_DEST_CMD;
733     } else if (strcmp(value, pr_dests[PR_DEST_FILE]) == 0) {
734       prefs.pr_dest = PR_DEST_FILE;
735     } else {
736       return PREFS_SET_SYNTAX_ERR;
737     }
738   } else if (strcmp(pref_name, PRS_PRINT_FILE) == 0) {
739     if (prefs.pr_file) g_free(prefs.pr_file);
740     prefs.pr_file = g_strdup(value);
741   } else if (strcmp(pref_name, PRS_PRINT_CMD) == 0) {
742     if (prefs.pr_cmd) g_free(prefs.pr_cmd);
743     prefs.pr_cmd = g_strdup(value);
744   } else if (strcmp(pref_name, PRS_COL_FMT) == 0) {
745     if ((col_l = get_string_list(value)) && (g_list_length(col_l) % 2) == 0) {
746       while (prefs.col_list) {
747         cfmt = prefs.col_list->data;
748         g_free(cfmt->title);
749         g_free(cfmt->fmt);
750         g_free(cfmt);
751         prefs.col_list = g_list_remove_link(prefs.col_list, prefs.col_list);
752       }
753       llen             = g_list_length(col_l);
754       prefs.num_cols   = llen / 2;
755       col_l = g_list_first(col_l);
756       while(col_l) {
757         cfmt = (fmt_data *) g_malloc(sizeof(fmt_data));
758         cfmt->title    = g_strdup(col_l->data);
759         col_l          = col_l->next;
760         cfmt->fmt      = g_strdup(col_l->data);
761         col_l          = col_l->next;
762         prefs.col_list = g_list_append(prefs.col_list, cfmt);
763       }
764       /* To do: else print some sort of error? */
765     }
766     clear_string_list(col_l);
767   } else if (strcmp(pref_name, PRS_STREAM_CL_FG) == 0) {
768     cval = strtoul(value, NULL, 16);
769     prefs.st_client_fg.pixel = 0;
770     prefs.st_client_fg.red   = RED_COMPONENT(cval);
771     prefs.st_client_fg.green = GREEN_COMPONENT(cval);
772     prefs.st_client_fg.blue  = BLUE_COMPONENT(cval);
773   } else if (strcmp(pref_name, PRS_STREAM_CL_BG) == 0) {
774     cval = strtoul(value, NULL, 16);
775     prefs.st_client_bg.pixel = 0;
776     prefs.st_client_bg.red   = RED_COMPONENT(cval);
777     prefs.st_client_bg.green = GREEN_COMPONENT(cval);
778     prefs.st_client_bg.blue  = BLUE_COMPONENT(cval);
779   } else if (strcmp(pref_name, PRS_STREAM_SR_FG) == 0) {
780     cval = strtoul(value, NULL, 16);
781     prefs.st_server_fg.pixel = 0;
782     prefs.st_server_fg.red   = RED_COMPONENT(cval);
783     prefs.st_server_fg.green = GREEN_COMPONENT(cval);
784     prefs.st_server_fg.blue  = BLUE_COMPONENT(cval);
785   } else if (strcmp(pref_name, PRS_STREAM_SR_BG) == 0) {
786     cval = strtoul(value, NULL, 16);
787     prefs.st_server_bg.pixel = 0;
788     prefs.st_server_bg.red   = RED_COMPONENT(cval);
789     prefs.st_server_bg.green = GREEN_COMPONENT(cval);
790     prefs.st_server_bg.blue  = BLUE_COMPONENT(cval);
791   } else if (strcmp(pref_name, PRS_GUI_SCROLLBAR_ON_RIGHT) == 0) {
792     if (strcmp(value, "TRUE") == 0) {
793             prefs.gui_scrollbar_on_right = TRUE;
794     }
795     else {
796             prefs.gui_scrollbar_on_right = FALSE;
797     }
798   } else if (strcmp(pref_name, PRS_GUI_PLIST_SEL_BROWSE) == 0) {
799     if (strcmp(value, "TRUE") == 0) {
800             prefs.gui_plist_sel_browse = TRUE;
801     }
802     else {
803             prefs.gui_plist_sel_browse = FALSE;
804     }
805   } else if (strcmp(pref_name, PRS_GUI_PTREE_SEL_BROWSE) == 0) {
806     if (strcmp(value, "TRUE") == 0) {
807             prefs.gui_ptree_sel_browse = TRUE;
808     }
809     else {
810             prefs.gui_ptree_sel_browse = FALSE;
811     }
812   } else if (strcmp(pref_name, PRS_GUI_PTREE_LINE_STYLE) == 0) {
813           prefs.gui_ptree_line_style =
814                   find_index_from_string_array(value, gui_ptree_line_style_text, 0);
815   } else if (strcmp(pref_name, PRS_GUI_PTREE_EXPANDER_STYLE) == 0) {
816           prefs.gui_ptree_expander_style =
817                   find_index_from_string_array(value, gui_ptree_expander_style_text, 1);
818   } else {
819     /* To which module does this preference belong? */
820     dotp = strchr(pref_name, '.');
821     if (dotp == NULL)
822       return PREFS_SET_SYNTAX_ERR;      /* no ".", so no module/name separator */
823     *dotp = '\0';               /* separate module and preference name */
824     module = find_module(pref_name);
825     *dotp = '.';                /* put the preference string back */
826     if (module == NULL)
827       return PREFS_SET_NO_SUCH_PREF;    /* no such module */
828     dotp++;                     /* skip past separator to preference name */
829     pref = find_preference(module, dotp);
830     if (pref == NULL)
831       return PREFS_SET_NO_SUCH_PREF;    /* no such preference */
832
833     switch (pref->type) {
834
835     case PREF_UINT:
836       uval = strtoul(value, &p, pref->info.base);
837       if (p == value || *p != '\0')
838         return PREFS_SET_SYNTAX_ERR;    /* number was bad */
839       *pref->varp.uint = uval;
840       break;
841
842     case PREF_BOOL:
843       /* XXX - give an error if it's neither "true" nor "false"? */
844       if (strcasecmp(value, "true") == 0)
845         *pref->varp.bool = TRUE;
846       else
847         *pref->varp.bool = FALSE;
848       break;
849
850     case PREF_ENUM:
851       /* XXX - give an error if it doesn't match? */
852       *pref->varp.enump = find_val_for_string(value,
853                                         pref->info.enum_info.enumvals, 1);
854       break;
855
856     case PREF_STRING:
857       if (*pref->varp.string != NULL)
858         g_free(*pref->varp.string);
859       *pref->varp.string = g_strdup(value);
860       break;
861     }
862   }
863   
864   return PREFS_SET_OK;
865 }
866
867 typedef struct {
868         module_t *module;
869         FILE    *pf;
870 } write_pref_arg_t;
871
872 /*
873  * Write out a single preference.
874  */
875 static void
876 write_pref(gpointer data, gpointer user_data)
877 {
878         pref_t *pref = data;
879         write_pref_arg_t *arg = user_data;
880         const enum_val *enum_valp;
881         const char *val_string;
882
883         fprintf(arg->pf, "\n# %s\n", pref->description);
884
885         switch (pref->type) {
886
887         case PREF_UINT:
888                 switch (pref->info.base) {
889
890                 case 10:
891                         fprintf(arg->pf, "# A decimal number.\n");
892                         fprintf(arg->pf, "%s.%s: %u\n", arg->module->name,
893                             pref->name, *pref->varp.uint);
894                         break;
895
896                 case 8:
897                         fprintf(arg->pf, "# An octal number.\n");
898                         fprintf(arg->pf, "%s.%s: %#o\n", arg->module->name,
899                             pref->name, *pref->varp.uint);
900                         break;
901
902                 case 16:
903                         fprintf(arg->pf, "# A hexadecimal number.\n");
904                         fprintf(arg->pf, "%s.%s: %#x\n", arg->module->name,
905                             pref->name, *pref->varp.uint);
906                         break;
907                 }
908                 break;
909
910         case PREF_BOOL:
911                 fprintf(arg->pf, "# TRUE or FALSE (case-insensitive).\n");
912                 fprintf(arg->pf, "%s.%s: %s\n", arg->module->name, pref->name,
913                     *pref->varp.bool ? "TRUE" : "FALSE");
914                 break;
915
916         case PREF_ENUM:
917                 fprintf(arg->pf, "# One of: ");
918                 enum_valp = pref->info.enum_info.enumvals;
919                 val_string = NULL;
920                 while (enum_valp->name != NULL) {
921                         if (enum_valp->value == *pref->varp.enump)
922                                 val_string = enum_valp->name;
923                         fprintf(arg->pf, "%s", enum_valp->name);
924                         enum_valp++;
925                         if (enum_valp->name == NULL)
926                                 fprintf(arg->pf, "\n");
927                         else
928                                 fprintf(arg->pf, ", ");
929                 }
930                 fprintf(arg->pf, "# (case-insensitive).\n");
931                 fprintf(arg->pf, "%s.%s: %s\n", arg->module->name, pref->name,
932                     val_string);
933                 break;
934
935         case PREF_STRING:
936                 fprintf(arg->pf, "# A string.\n");
937                 fprintf(arg->pf, "%s.%s: %s\n", arg->module->name, pref->name,
938                     *pref->varp.string);
939                 break;
940         }
941 }
942
943 static void
944 write_module_prefs(gpointer data, gpointer user_data)
945 {
946         write_pref_arg_t arg;
947
948         arg.module = data;
949         arg.pf = user_data;
950         g_list_foreach(arg.module->prefs, write_pref, &arg);
951 }
952
953 int
954 write_prefs(char **pf_path_return)
955 {
956   FILE        *pf;
957   struct stat  s_buf;
958   
959   /* To do:
960    * - Split output lines longer than MAX_VAL_LEN
961    * - Create a function for the preference directory check/creation
962    *   so that duplication can be avoided with filter.c
963    */
964
965   if (! pf_path) {
966     pf_path = (gchar *) g_malloc(strlen(get_home_dir()) + strlen(PF_DIR) +
967       strlen(PF_NAME) + 4);
968   }
969
970   sprintf(pf_path, "%s/%s", get_home_dir(), PF_DIR);
971   if (stat(pf_path, &s_buf) != 0)
972 #ifdef WIN32
973     mkdir(pf_path);
974 #else
975     mkdir(pf_path, 0755);
976 #endif
977
978   sprintf(pf_path, "%s/%s/%s", get_home_dir(), PF_DIR, PF_NAME);
979   if ((pf = fopen(pf_path, "w")) == NULL) {
980     *pf_path_return = pf_path;
981     return errno;
982   }
983     
984   fputs("# Configuration file for Ethereal " VERSION ".\n"
985     "#\n"
986     "# This file is regenerated each time preferences are saved within\n"
987     "# Ethereal.  Making manual changes should be safe, however.\n"
988     "\n"
989     "######## Printing ########\n"
990     "\n", pf);
991
992   fprintf (pf, "# Can be one of \"text\" or \"postscript\".\n"
993     "print.format: %s\n\n", pr_formats[prefs.pr_format]);
994
995   fprintf (pf, "# Can be one of \"command\" or \"file\".\n"
996     "print.destination: %s\n\n", pr_dests[prefs.pr_dest]);
997
998   fprintf (pf, "# This is the file that gets written to when the "
999     "destination is set to \"file\"\n"
1000     "%s: %s\n\n", PRS_PRINT_FILE, prefs.pr_file);
1001
1002   fprintf (pf, "# Output gets piped to this command when the destination "
1003     "is set to \"command\"\n"
1004     "%s: %s\n\n", PRS_PRINT_CMD, prefs.pr_cmd);
1005
1006   fprintf (pf, "# Packet list column format.  Each pair of strings consists "
1007     "of a column title \n# and its format.\n"
1008     "%s: %s\n\n", PRS_COL_FMT, col_format_to_pref_str());
1009
1010   fprintf (pf, "# TCP stream window color preferences.  Each value is a six "
1011     "digit hexadecimal value in the form rrggbb.\n");
1012   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_CL_FG,
1013     (prefs.st_client_fg.red * 255 / 65535),
1014     (prefs.st_client_fg.green * 255 / 65535),
1015     (prefs.st_client_fg.blue * 255 / 65535));
1016   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_CL_BG,
1017     (prefs.st_client_bg.red * 255 / 65535),
1018     (prefs.st_client_bg.green * 255 / 65535),
1019     (prefs.st_client_bg.blue * 255 / 65535));
1020   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_SR_FG,
1021     (prefs.st_server_fg.red * 255 / 65535),
1022     (prefs.st_server_fg.green * 255 / 65535),
1023     (prefs.st_server_fg.blue * 255 / 65535));
1024   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_SR_BG,
1025     (prefs.st_server_bg.red * 255 / 65535),
1026     (prefs.st_server_bg.green * 255 / 65535),
1027     (prefs.st_server_bg.blue * 255 / 65535));
1028
1029   fprintf(pf, "\n# Vertical scrollbars should be on right side? TRUE/FALSE\n");
1030   fprintf(pf, PRS_GUI_SCROLLBAR_ON_RIGHT ": %s\n",
1031                   prefs.gui_scrollbar_on_right == TRUE ? "TRUE" : "FALSE");
1032
1033   fprintf(pf, "\n# Packet-list selection bar can be used to browse w/o selecting? TRUE/FALSE\n");
1034   fprintf(pf, PRS_GUI_PLIST_SEL_BROWSE ": %s\n",
1035                   prefs.gui_plist_sel_browse == TRUE ? "TRUE" : "FALSE");
1036
1037   fprintf(pf, "\n# Protocol-tree selection bar can be used to browse w/o selecting? TRUE/FALSE\n");
1038   fprintf(pf, PRS_GUI_PTREE_SEL_BROWSE ": %s\n",
1039                   prefs.gui_ptree_sel_browse == TRUE ? "TRUE" : "FALSE");
1040
1041   fprintf(pf, "\n# Protocol-tree line style. One of: NONE, SOLID, DOTTED, TABBED\n");
1042   fprintf(pf, PRS_GUI_PTREE_LINE_STYLE ": %s\n",
1043                   gui_ptree_line_style_text[prefs.gui_ptree_line_style]);
1044
1045   fprintf(pf, "\n# Protocol-tree expander style. One of: NONE, SQUARE, TRIANGLE, CIRCULAR\n");
1046   fprintf(pf, PRS_GUI_PTREE_EXPANDER_STYLE ": %s\n",
1047                   gui_ptree_expander_style_text[prefs.gui_ptree_expander_style]);
1048
1049   g_list_foreach(modules, write_module_prefs, pf);
1050
1051   fclose(pf);
1052
1053   /* XXX - catch I/O errors (e.g. "ran out of disk space") and return
1054      an error indication, or maybe write to a new preferences file and
1055      rename that file on top of the old one only if there are not I/O
1056      errors. */
1057   return 0;
1058 }