Use G_DIR_SEPARATOR_S rather than "/" as a pathname separator in format
[obnox/wireshark/wip.git] / prefs.c
1 /* prefs.c
2  * Routines for handling preferences
3  *
4  * $Id: prefs.c,v 1.65 2001/10/21 21:47:57 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  * 
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  * 
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  * 
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
32
33 #ifdef HAVE_DIRECT_H
34 #include <direct.h>
35 #endif
36
37 #include <stdlib.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <errno.h>
41
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif
49
50 #include <filesystem.h>
51 #include "globals.h"
52 #include "packet.h"
53 #include "file.h"
54 #include "prefs.h"
55 #include "proto.h"
56 #include "column.h"
57 #include "print.h"
58
59 #include "prefs-int.h"
60
61 /* Internal functions */
62 static int    set_pref(gchar*, gchar*);
63 static GList *get_string_list(gchar *);
64 static gchar *put_string_list(GList *);
65 static void   clear_string_list(GList *);
66 static void   free_col_info(e_prefs *);
67
68 #define GPF_NAME        "ethereal.conf"
69 #define PF_NAME         "preferences"
70
71 static gboolean init_prefs = TRUE;
72 static gchar *gpf_path = NULL;
73 static gchar *pf_path = NULL;
74
75 /*
76  * XXX - variables to allow us to attempt to interpret the first
77  * "mgcp.{tcp,udp}.port" in a preferences file as
78  * "mgcp.{tcp,udp}.gateway_port" and the second as
79  * "mgcp.{tcp,udp}.callagent_port".
80  */
81 static int mgcp_tcp_port_count;
82 static int mgcp_udp_port_count;
83
84 e_prefs prefs;
85
86 gchar   *gui_ptree_line_style_text[] =
87         { "NONE", "SOLID", "DOTTED", "TABBED", NULL };
88
89 gchar   *gui_ptree_expander_style_text[] =
90         { "NONE", "SQUARE", "TRIANGLE", "CIRCULAR", NULL };
91
92 gchar   *gui_hex_dump_highlight_style_text[] =
93         { "BOLD", "INVERSE", NULL };
94
95 /*
96  * List of modules with preference settings.
97  */
98 static GList *modules;
99
100 static gint
101 module_compare_name(gconstpointer p1_arg, gconstpointer p2_arg)
102 {
103         const module_t *p1 = p1_arg;
104         const module_t *p2 = p2_arg;
105
106         return g_strcasecmp(p1->name, p2->name);
107 }
108
109 /*
110  * Register a module that will have preferences.
111  * Specify the name used for the module in the preferences file, the
112  * title used in the tab for it in a preferences dialog box, and a
113  * routine to call back when we apply the preferences.
114  */
115 module_t *
116 prefs_register_module(const char *name, const char *title,
117     void (*apply_cb)(void))
118 {
119         module_t *module;
120
121         module = g_malloc(sizeof (module_t));
122         module->name = name;
123         module->title = title;
124         module->apply_cb = apply_cb;
125         module->prefs = NULL;   /* no preferences, to start */
126         module->numprefs = 0;
127         module->prefs_changed = FALSE;
128
129         modules = g_list_insert_sorted(modules, module, module_compare_name);
130
131         return module;
132 }
133
134 /*
135  * Register that a protocol has preferences.
136  */
137 module_t *
138 prefs_register_protocol(int id, void (*apply_cb)(void))
139 {
140         return prefs_register_module(proto_get_protocol_filter_name(id),
141                                      proto_get_protocol_short_name(id),
142                                      apply_cb);
143 }
144
145 /*
146  * Find a module, given its name.
147  */
148 static gint
149 module_match(gconstpointer a, gconstpointer b)
150 {
151         const module_t *module = a;
152         const char *name = b;
153
154         return strcmp(name, module->name);
155 }
156
157 static module_t *
158 find_module(char *name)
159 {
160         GList *list_entry;
161
162         list_entry = g_list_find_custom(modules, name, module_match);
163         if (list_entry == NULL)
164                 return NULL;    /* no such module */
165         return (module_t *) list_entry->data;
166 }
167
168 typedef struct {
169         module_cb callback;
170         gpointer user_data;
171 } module_cb_arg_t;
172
173 static void
174 do_module_callback(gpointer data, gpointer user_data)
175 {
176         module_t *module = data;
177         module_cb_arg_t *arg = user_data;
178
179         (*arg->callback)(module, arg->user_data);
180 }
181
182 /*
183  * Call a callback function, with a specified argument, for each module.
184  */
185 void
186 prefs_module_foreach(module_cb callback, gpointer user_data)
187 {
188         module_cb_arg_t arg;
189
190         arg.callback = callback;
191         arg.user_data = user_data;
192         g_list_foreach(modules, do_module_callback, &arg);
193 }
194
195 static void
196 call_apply_cb(gpointer data, gpointer user_data)
197 {
198         module_t *module = data;
199
200         if (module->prefs_changed) {
201                 if (module->apply_cb != NULL)
202                         (*module->apply_cb)();
203                 module->prefs_changed = FALSE;
204         }
205 }
206
207 /*
208  * Call the "apply" callback function for each module if any of its
209  * preferences have changed, and then clear the flag saying its
210  * preferences have changed, as the module has been notified of that
211  * fact.
212  */
213 void
214 prefs_apply_all(void)
215 {
216         g_list_foreach(modules, call_apply_cb, NULL);
217 }
218
219 /*
220  * Register a preference in a module's list of preferences.
221  */
222 static pref_t *
223 register_preference(module_t *module, const char *name, const char *title,
224     const char *description)
225 {
226         pref_t *preference;
227
228         preference = g_malloc(sizeof (pref_t));
229         preference->name = name;
230         preference->title = title;
231         preference->description = description;
232         preference->ordinal = module->numprefs;
233
234         module->prefs = g_list_append(module->prefs, preference);
235         module->numprefs++;
236
237         return preference;
238 }
239
240 /*
241  * Find a preference in a module's list of preferences, given the module
242  * and the preference's name.
243  */
244 static gint
245 preference_match(gconstpointer a, gconstpointer b)
246 {
247         const pref_t *pref = a;
248         const char *name = b;
249
250         return strcmp(name, pref->name);
251 }
252
253 static struct preference *
254 find_preference(module_t *module, char *name)
255 {
256         GList *list_entry;
257
258         list_entry = g_list_find_custom(module->prefs, name, preference_match);
259         if (list_entry == NULL)
260                 return NULL;    /* no such preference */
261         return (struct preference *) list_entry->data;
262 }
263
264 /*
265  * Returns TRUE if the given protocol has registered preferences
266  */
267 gboolean
268 prefs_is_registered_protocol(char *name)
269 {
270         return (find_module(name) != NULL);
271 }
272
273 /*
274  * Returns the module title of a registered protocol
275  */
276 const char *
277 prefs_get_title_by_name(char *name)
278 {
279         module_t *m = find_module(name);
280         return  (m) ? m->title : NULL;
281 }
282
283 /*
284  * Register a preference with an unsigned integral value.
285  */
286 void
287 prefs_register_uint_preference(module_t *module, const char *name,
288     const char *title, const char *description, guint base, guint *var)
289 {
290         pref_t *preference;
291
292         preference = register_preference(module, name, title, description);
293         preference->type = PREF_UINT;
294         preference->varp.uint = var;
295         preference->info.base = base;
296 }
297
298 /*
299  * Register a preference with an Boolean value.
300  */
301 void
302 prefs_register_bool_preference(module_t *module, const char *name,
303     const char *title, const char *description, gboolean *var)
304 {
305         pref_t *preference;
306
307         preference = register_preference(module, name, title, description);
308         preference->type = PREF_BOOL;
309         preference->varp.bool = var;
310 }
311
312 /*
313  * Register a preference with an enumerated value.
314  */
315 void
316 prefs_register_enum_preference(module_t *module, const char *name,
317     const char *title, const char *description, gint *var,
318     const enum_val_t *enumvals, gboolean radio_buttons)
319 {
320         pref_t *preference;
321
322         preference = register_preference(module, name, title, description);
323         preference->type = PREF_ENUM;
324         preference->varp.enump = var;
325         preference->info.enum_info.enumvals = enumvals;
326         preference->info.enum_info.radio_buttons = radio_buttons;
327 }
328
329 /*
330  * Register a preference with a character-string value.
331  */
332 void
333 prefs_register_string_preference(module_t *module, const char *name,
334     const char *title, const char *description, char **var)
335 {
336         pref_t *preference;
337
338         preference = register_preference(module, name, title, description);
339         preference->type = PREF_STRING;
340         preference->varp.string = var;
341         preference->saved_val.string = NULL;
342 }
343
344 typedef struct {
345         pref_cb callback;
346         gpointer user_data;
347 } pref_cb_arg_t;
348
349 static void
350 do_pref_callback(gpointer data, gpointer user_data)
351 {
352         pref_t *pref = data;
353         pref_cb_arg_t *arg = user_data;
354
355         (*arg->callback)(pref, arg->user_data);
356 }
357
358 /*
359  * Call a callback function, with a specified argument, for each preference
360  * in a given module.
361  */
362 void
363 prefs_pref_foreach(module_t *module, pref_cb callback, gpointer user_data)
364 {
365         pref_cb_arg_t arg;
366
367         arg.callback = callback;
368         arg.user_data = user_data;
369         g_list_foreach(module->prefs, do_pref_callback, &arg);
370 }
371
372 /*
373  * Register all non-dissector modules' preferences.
374  */
375 void
376 prefs_register_modules(void)
377 {
378 }
379
380 /* Parse through a list of comma-separated, possibly quoted strings.
381    Return a list of the string data. */
382 static GList *
383 get_string_list(gchar *str)
384 {
385   enum { PRE_STRING, IN_QUOT, NOT_IN_QUOT };
386
387   gint      state = PRE_STRING, i = 0, j = 0;
388   gboolean  backslash = FALSE;
389   guchar    cur_c;
390   gchar    *slstr = NULL;
391   GList    *sl = NULL;
392
393   /* Allocate a buffer for the first string.   */
394   slstr = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
395   j = 0;
396
397   for (;;) {
398     cur_c = str[i];
399     if (cur_c == '\0') {
400       /* It's the end of the input, so it's the end of the string we
401          were working on, and there's no more input. */
402       if (state == IN_QUOT || backslash) {
403         /* We were in the middle of a quoted string or backslash escape,
404            and ran out of characters; that's an error.  */
405         g_free(slstr);
406         clear_string_list(sl);
407         return NULL;
408       }
409       slstr[j] = '\0';
410       sl = g_list_append(sl, slstr);
411       break;
412     }
413     if (cur_c == '"' && ! backslash) {
414       switch (state) {
415         case PRE_STRING:
416           /* We hadn't yet started processing a string; this starts the
417              string, and we're now quoting.  */
418           state = IN_QUOT;
419           break;
420         case IN_QUOT:
421           /* We're in the middle of a quoted string, and we saw a quotation
422              mark; we're no longer quoting.   */
423           state = NOT_IN_QUOT;
424           break;
425         case NOT_IN_QUOT:
426           /* We're working on a string, but haven't seen a quote; we're
427              now quoting.  */
428           state = IN_QUOT;
429           break;
430         default:
431           break;
432       }
433     } else if (cur_c == '\\' && ! backslash) {
434       /* We saw a backslash, and the previous character wasn't a
435          backslash; escape the next character.
436
437          This also means we've started a new string. */
438       backslash = TRUE;
439       if (state == PRE_STRING)
440         state = NOT_IN_QUOT;
441     } else if (cur_c == ',' && state != IN_QUOT && ! backslash) {
442       /* We saw a comma, and we're not in the middle of a quoted string
443          and it wasn't preceded by a backslash; it's the end of
444          the string we were working on...  */
445       slstr[j] = '\0';
446       sl = g_list_append(sl, slstr);
447
448       /* ...and the beginning of a new string.  */
449       state = PRE_STRING;
450       slstr = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
451       j = 0;
452     } else if (!isspace(cur_c) || state != PRE_STRING) {
453       /* Either this isn't a white-space character, or we've started a
454          string (i.e., already seen a non-white-space character for that
455          string and put it into the string).
456
457          The character is to be put into the string; do so if there's
458          room.  */
459       if (j < COL_MAX_LEN) {
460         slstr[j] = cur_c;
461         j++;
462       }
463
464       /* If it was backslash-escaped, we're done with the backslash escape.  */
465       backslash = FALSE;
466     }
467     i++;
468   }
469   return(sl);
470 }
471
472 #define MAX_FMT_PREF_LEN      1024
473 #define MAX_FMT_PREF_LINE_LEN   60
474 static gchar *
475 put_string_list(GList *sl)
476 {
477   static gchar  pref_str[MAX_FMT_PREF_LEN] = "";
478   GList        *clp = g_list_first(sl);
479   gchar        *str;
480   int           cur_pos = 0, cur_len = 0;
481   gchar        *quoted_str;
482   int           str_len;
483   gchar        *strp, *quoted_strp, c;
484   int           fmt_len;
485
486   while (clp) {
487     str = clp->data;
488
489     /* Allocate a buffer big enough to hold the entire string, with each
490        character quoted (that's the worst case).  */
491     str_len = strlen(str);
492     quoted_str = g_malloc(str_len*2 + 1);
493
494     /* Now quote any " or \ characters in it. */
495     strp = str;
496     quoted_strp = quoted_str;
497     while ((c = *strp++) != '\0') {
498       if (c == '"' || c == '\\') {
499         /* It has to be backslash-quoted.  */
500         *quoted_strp++ = '\\';
501       }
502       *quoted_strp++ = c;
503     }
504     *quoted_strp = '\0';
505
506     fmt_len = strlen(quoted_str) + 4;
507     if ((fmt_len + cur_len) < (MAX_FMT_PREF_LEN - 1)) {
508       if ((fmt_len + cur_pos) > MAX_FMT_PREF_LINE_LEN) {
509         /* Wrap the line.  */
510         cur_len--;
511         cur_pos = 0;
512         pref_str[cur_len] = '\n'; cur_len++;
513         pref_str[cur_len] = '\t'; cur_len++;
514       }
515       sprintf(&pref_str[cur_len], "\"%s\", ", quoted_str);
516       cur_pos += fmt_len;
517       cur_len += fmt_len;
518     }
519     g_free(quoted_str);
520     clp = clp->next;
521   }
522
523   /* If the string is at least two characters long, the last two characters
524      are ", ", and should be discarded, as there are no more items in the
525      string.  */
526   if (cur_len >= 2)
527     pref_str[cur_len - 2] = '\0';
528
529   return(pref_str);
530 }    
531
532 static void
533 clear_string_list(GList *sl)
534 {
535   GList *l = sl;
536   
537   while (l) {
538     g_free(l->data);
539     l = g_list_remove_link(l, l);
540   }
541 }
542
543 /*
544  * Takes a string, a pointer to an array of "enum_val_t"s, and a default gint
545  * value.
546  * The array must be terminated by an entry with a null "name" string.
547  * If the string matches a "name" strings in an entry, the value from that
548  * entry is returned. Otherwise, the default value that was passed as the
549  * third argument is returned.
550  */
551 gint
552 find_val_for_string(const char *needle, const enum_val_t *haystack,
553     gint default_value)
554 {
555         int i = 0;
556
557         while (haystack[i].name != NULL) {
558                 if (strcasecmp(needle, haystack[i].name) == 0) {
559                         return haystack[i].value;
560                 }
561                 i++;    
562         }
563         return default_value;
564 }
565
566 /* Takes an string and a pointer to an array of strings, and a default int value.
567  * The array must be terminated by a NULL string. If the string is found in the array
568  * of strings, the index of that string in the array is returned. Otherwise, the
569  * default value that was passed as the third argument is returned.
570  */
571 static int
572 find_index_from_string_array(char *needle, char **haystack, int default_value)
573 {
574         int i = 0;
575
576         while (haystack[i] != NULL) {
577                 if (strcmp(needle, haystack[i]) == 0) {
578                         return i;
579                 }
580                 i++;    
581         }
582         return default_value;
583 }
584
585 /* Preferences file format:
586  * - Configuration directives start at the beginning of the line, and 
587  *   are terminated with a colon.
588  * - Directives can be continued on the next line by preceding them with
589  *   whitespace.
590  *
591  * Example:
592
593 # This is a comment line
594 print.command: lpr
595 print.file: /a/very/long/path/
596         to/ethereal-out.ps
597  *
598  */
599
600 #define MAX_VAR_LEN    48
601 #define MAX_VAL_LEN  1024
602
603 #define DEF_NUM_COLS    6
604
605 static void read_prefs_file(const char *pf_path, FILE *pf);
606
607 /* Read the preferences file, fill in "prefs", and return a pointer to it.
608
609    If we got an error (other than "it doesn't exist") trying to read
610    the global preferences file, stuff the errno into "*gpf_errno_return"
611    and a pointer to the path of the file into "*gpf_path_return", and
612    return NULL.
613
614    If we got an error (other than "it doesn't exist") trying to read
615    the user's preferences file, stuff the errno into "*pf_errno_return"
616    and a pointer to the path of the file into "*pf_path_return", and
617    return NULL. */
618 e_prefs *
619 read_prefs(int *gpf_errno_return, char **gpf_path_return,
620            int *pf_errno_return, char **pf_path_return)
621 {
622   int       i;
623   FILE     *pf;
624   fmt_data *cfmt;
625   gchar    *col_fmt[] = {"No.",      "%m", "Time",        "%t",
626                          "Source",   "%s", "Destination", "%d",
627                          "Protocol", "%p", "Info",        "%i"};
628
629   
630   if (init_prefs) {
631     /* Initialize preferences to wired-in default values.
632        They may be overridded by the global preferences file or the
633        user's preferences file. */
634     init_prefs       = FALSE;
635     prefs.pr_format  = PR_FMT_TEXT;
636     prefs.pr_dest    = PR_DEST_CMD;
637     prefs.pr_file    = g_strdup("ethereal.out");
638     prefs.pr_cmd     = g_strdup("lpr");
639     prefs.col_list = NULL;
640     for (i = 0; i < DEF_NUM_COLS; i++) {
641       cfmt = (fmt_data *) g_malloc(sizeof(fmt_data));
642       cfmt->title = g_strdup(col_fmt[i * 2]);
643       cfmt->fmt   = g_strdup(col_fmt[(i * 2) + 1]);
644       prefs.col_list = g_list_append(prefs.col_list, cfmt);
645     }
646     prefs.num_cols  = DEF_NUM_COLS;
647     prefs.st_client_fg.pixel =     0;
648     prefs.st_client_fg.red   = 32767;
649     prefs.st_client_fg.green =     0;
650     prefs.st_client_fg.blue  =     0;
651     prefs.st_client_bg.pixel = 65535;
652     prefs.st_client_bg.red   = 65535;
653     prefs.st_client_bg.green = 65535;
654     prefs.st_client_bg.blue  = 65535;
655     prefs.st_server_fg.pixel =     0;
656     prefs.st_server_fg.red   =     0;
657     prefs.st_server_fg.green =     0;
658     prefs.st_server_fg.blue  = 32767;
659     prefs.st_server_bg.pixel = 65535;
660     prefs.st_server_bg.red   = 65535;
661     prefs.st_server_bg.green = 65535;
662     prefs.st_server_bg.blue  = 65535;
663     prefs.gui_scrollbar_on_right = TRUE;
664     prefs.gui_plist_sel_browse = FALSE;
665     prefs.gui_ptree_sel_browse = FALSE;
666     prefs.gui_ptree_line_style = 0;
667     prefs.gui_ptree_expander_style = 1;
668     prefs.gui_hex_dump_highlight_style = 1;
669 #ifdef WIN32
670     prefs.gui_font_name = g_strdup("-*-lucida console-medium-r-*-*-*-100-*-*-*-*-*-*");
671 #else
672     /*
673      * XXX - for now, we make the initial font name a pattern that matches
674      * only ISO 8859/1 fonts, so that we don't match 2-byte fonts such
675      * as ISO 10646 fonts.
676      *
677      * Users in locales using other one-byte fonts will have to choose
678      * a different font from the preferences dialog - or put the font
679      * selection in the global preferences file to make that font the
680      * default for all users who don't explicitly specify a different
681      * font.
682      *
683      * Making this a font set rather than a font has two problems:
684      *
685      *  1) as far as I know, you can't select font sets with the
686      *     font selection dialog;
687      *
688      *  2) if you use a font set, the text to be drawn must be a
689      *     multi-byte string in the appropriate locale, but
690      *     Ethereal does *NOT* guarantee that's the case - in
691      *     the hex-dump window, each character in the text portion
692      *     of the display must be a *single* byte, and in the
693      *     packet-list and protocol-tree windows, text extracted
694      *     from the packet is not necessarily in the right format.
695      *
696      * "Doing this right" may, for the packet-list and protocol-tree
697      * windows, require that dissectors know what the locale is
698      * *AND* know what locale and text representation is used in
699      * the packets they're dissecting, and may be impossible in
700      * the hex-dump window (except by punting and displaying only
701      * ASCII characters).
702      *
703      * GTK+ 2.0 may simplify part of the problem, as it will, as I
704      * understand it, use UTF-8-encoded Unicode as its internal
705      * character set; however, we'd still have to know whatever
706      * character set and encoding is used in the packet (which
707      * may differ for different protocols, e.g. SMB might use
708      * PC code pages for some strings and Unicode for others, whilst
709      * NFS might use some UNIX character set encoding, e.g. ISO 8859/x,
710      * or one of the EUC character sets for Asian languages, or one
711      * of the other multi-byte character sets, or UTF-8, or...).
712      *
713      * I.e., as far as I can tell, "internationalizing" the packet-list,
714      * protocol-tree, and hex-dump windows involves a lot more than, say,
715      * just using font sets rather than fonts.
716      */
717     prefs.gui_font_name = g_strdup("-*-fixed-medium-r-semicondensed-*-*-120-*-*-*-*-iso8859-1");
718 #endif
719     prefs.gui_marked_fg.pixel = 65535;
720     prefs.gui_marked_fg.red   = 65535;
721     prefs.gui_marked_fg.green = 65535;
722     prefs.gui_marked_fg.blue  = 65535;
723     prefs.gui_marked_bg.pixel =     0;
724     prefs.gui_marked_bg.red   =     0;
725     prefs.gui_marked_bg.green =     0;
726     prefs.gui_marked_bg.blue  =     0;
727
728 /* set the default values for the capture dialog box */
729     prefs.capture_prom_mode   =  TRUE;
730     prefs.capture_real_time   = FALSE;
731     prefs.capture_auto_scroll = FALSE;
732     prefs.name_resolve        = PREFS_RESOLV_ALL;
733   }
734
735   /* Construct the pathname of the global preferences file. */
736   if (! gpf_path) {
737     gpf_path = (gchar *) g_malloc(strlen(get_datafile_dir()) +
738       strlen(GPF_NAME) + 2);
739     sprintf(gpf_path, "%s" G_DIR_SEPARATOR_S "%s",
740       get_datafile_dir(), GPF_NAME);
741   }
742
743   /* Read the global preferences file, if it exists. */
744   *gpf_path_return = NULL;
745   if ((pf = fopen(gpf_path, "r")) != NULL) {
746     /* We succeeded in opening it; read it. */
747     read_prefs_file(gpf_path, pf);
748     fclose(pf);
749   } else {
750     /* We failed to open it.  If we failed for some reason other than
751        "it doesn't exist", return the errno and the pathname, so our
752        caller can report the error. */
753     if (errno != ENOENT) {
754       *gpf_errno_return = errno;
755       *gpf_path_return = gpf_path;
756     }
757   }
758
759   /* Construct the pathname of the user's preferences file. */
760   if (! pf_path) {
761     pf_path = (gchar *) g_malloc(strlen(get_home_dir()) + strlen(PF_DIR) +
762       strlen(PF_NAME) + 4);
763     sprintf(pf_path, "%s" G_DIR_SEPARATOR_S "%s" G_DIR_SEPARATOR_S "%s",
764       get_home_dir(), PF_DIR, PF_NAME);
765   }
766     
767   /* Read the user's preferences file, if it exists. */
768   *pf_path_return = NULL;
769   if ((pf = fopen(pf_path, "r")) != NULL) {
770     /* We succeeded in opening it; read it. */
771     read_prefs_file(pf_path, pf);
772     fclose(pf);
773   } else {
774     /* We failed to open it.  If we failed for some reason other than
775        "it doesn't exist", return the errno and the pathname, so our
776        caller can report the error. */
777     if (errno != ENOENT) {
778       *pf_errno_return = errno;
779       *pf_path_return = pf_path;
780     }
781   }
782   
783   return &prefs;
784 }
785
786 static void
787 read_prefs_file(const char *pf_path, FILE *pf)
788 {
789   enum { START, IN_VAR, PRE_VAL, IN_VAL, IN_SKIP };
790   gchar     cur_var[MAX_VAR_LEN], cur_val[MAX_VAL_LEN];
791   int       got_c, state = START;
792   gboolean  got_val = FALSE;
793   gint      var_len = 0, val_len = 0, fline = 1, pline = 1;
794
795   /*
796    * Start out the counters of "mgcp.{tcp,udp}.port" entries we've
797    * seen.
798    */
799   mgcp_tcp_port_count = 0;
800   mgcp_udp_port_count = 0;
801
802   while ((got_c = getc(pf)) != EOF) {
803     if (got_c == '\n') {
804       state = START;
805       fline++;
806       continue;
807     }
808     if (var_len >= MAX_VAR_LEN) {
809       g_warning ("%s line %d: Variable too long", pf_path, fline);
810       state = IN_SKIP;
811       var_len = 0;
812       continue;
813     }
814     if (val_len >= MAX_VAL_LEN) {
815       g_warning ("%s line %d: Value too long", pf_path, fline);
816       state = IN_SKIP;
817       var_len = 0;
818       continue;
819     }
820     
821     switch (state) {
822       case START:
823         if (isalnum(got_c)) {
824           if (var_len > 0) {
825             if (got_val) {
826               cur_var[var_len] = '\0';
827               cur_val[val_len] = '\0';
828               switch (set_pref(cur_var, cur_val)) {
829
830               case PREFS_SET_SYNTAX_ERR:
831                 g_warning ("%s line %d: Syntax error", pf_path, pline);
832                 break;
833
834               case PREFS_SET_NO_SUCH_PREF:
835                 g_warning ("%s line %d: No such preference \"%s\"", pf_path,
836                                 pline, cur_var);
837                 break;
838               }
839             } else {
840               g_warning ("%s line %d: Incomplete preference", pf_path, pline);
841             }
842           }
843           state      = IN_VAR;
844           got_val    = FALSE;
845           cur_var[0] = got_c;
846           var_len    = 1;
847           pline = fline;
848         } else if (isspace(got_c) && var_len > 0 && got_val) {
849           state = PRE_VAL;
850         } else if (got_c == '#') {
851           state = IN_SKIP;
852         } else {
853           g_warning ("%s line %d: Malformed line", pf_path, fline);
854         }
855         break;
856       case IN_VAR:
857         if (got_c != ':') {
858           cur_var[var_len] = got_c;
859           var_len++;
860         } else {
861           state   = PRE_VAL;
862           val_len = 0;
863           got_val = TRUE;
864         }
865         break;
866       case PRE_VAL:
867         if (!isspace(got_c)) {
868           state = IN_VAL;
869           cur_val[val_len] = got_c;
870           val_len++;
871         }
872         break;
873       case IN_VAL:
874         if (got_c != '#')  {
875           cur_val[val_len] = got_c;
876           val_len++;
877         } else {
878           while (isspace((guchar)cur_val[val_len]) && val_len > 0)
879             val_len--;
880           state = IN_SKIP;
881         }
882         break;
883     }
884   }
885   if (var_len > 0) {
886     if (got_val) {
887       cur_var[var_len] = '\0';
888       cur_val[val_len] = '\0';
889       switch (set_pref(cur_var, cur_val)) {
890
891       case PREFS_SET_SYNTAX_ERR:
892         g_warning ("%s line %d: Syntax error", pf_path, pline);
893         break;
894
895       case PREFS_SET_NO_SUCH_PREF:
896         g_warning ("%s line %d: No such preference \"%s\"", pf_path,
897                         pline, cur_var);
898         break;
899       }
900     } else {
901       g_warning ("%s line %d: Incomplete preference", pf_path, pline);
902     }
903   }
904 }
905
906 /*
907  * Given a string of the form "<pref name>:<pref value>", as might appear
908  * as an argument to a "-o" option, parse it and set the preference in
909  * question.  Return an indication of whether it succeeded or failed
910  * in some fashion.
911  */
912 int
913 prefs_set_pref(char *prefarg)
914 {
915         u_char *p, *colonp;
916         int ret;
917
918         /*
919          * Set the counters of "mgcp.{tcp,udp}.port" entries we've
920          * seen to values that keep us from trying to interpret tham
921          * as "mgcp.{tcp,udp}.gateway_port" or "mgcp.{tcp,udp}.callagent_port",
922          * as, from the command line, we have no way of guessing which
923          * the user had in mind.
924          */
925         mgcp_tcp_port_count = -1;
926         mgcp_udp_port_count = -1;
927
928         colonp = strchr(prefarg, ':');
929         if (colonp == NULL)
930                 return PREFS_SET_SYNTAX_ERR;
931
932         p = colonp;
933         *p++ = '\0';
934
935         /*
936          * Skip over any white space (there probably won't be any, but
937          * as we allow it in the preferences file, we might as well
938          * allow it here).
939          */
940         while (isspace(*p))
941                 p++;
942         if (*p == '\0') {
943                 /*
944                  * Put the colon back, so if our caller uses, in an
945                  * error message, the string they passed us, the message
946                  * looks correct.
947                  */
948                 *colonp = ':';
949                 return PREFS_SET_SYNTAX_ERR;
950         }
951
952         ret = set_pref(prefarg, p);
953         *colonp = ':';  /* put the colon back */
954         return ret;
955 }
956
957 #define PRS_PRINT_FMT    "print.format"
958 #define PRS_PRINT_DEST   "print.destination"
959 #define PRS_PRINT_FILE   "print.file"
960 #define PRS_PRINT_CMD    "print.command"
961 #define PRS_COL_FMT      "column.format"
962 #define PRS_STREAM_CL_FG "stream.client.fg"
963 #define PRS_STREAM_CL_BG "stream.client.bg"
964 #define PRS_STREAM_SR_FG "stream.server.fg"
965 #define PRS_STREAM_SR_BG "stream.server.bg"
966 #define PRS_GUI_SCROLLBAR_ON_RIGHT "gui.scrollbar_on_right"
967 #define PRS_GUI_PLIST_SEL_BROWSE "gui.packet_list_sel_browse"
968 #define PRS_GUI_PTREE_SEL_BROWSE "gui.protocol_tree_sel_browse"
969 #define PRS_GUI_PTREE_LINE_STYLE "gui.protocol_tree_line_style"
970 #define PRS_GUI_PTREE_EXPANDER_STYLE "gui.protocol_tree_expander_style"
971 #define PRS_GUI_HEX_DUMP_HIGHLIGHT_STYLE "gui.hex_dump_highlight_style"
972 #define PRS_GUI_FONT_NAME "gui.font_name"
973 #define PRS_GUI_MARKED_FG "gui.marked_frame.fg"
974 #define PRS_GUI_MARKED_BG "gui.marked_frame.bg"
975
976 /*
977  * This applies to more than just captures, so it's not "capture.name_resolve";
978  * "capture.name_resolve" is supported on input for backwards compatibility.
979  *
980  * It's not a preference for a particular part of Ethereal, it's used all
981  * over the place, so its name doesn't have two components.
982  */
983 #define PRS_NAME_RESOLVE "name_resolve"
984 #define PRS_CAP_NAME_RESOLVE "capture.name_resolve"
985
986 /*  values for the capture dialog box */
987 #define PRS_CAP_REAL_TIME "capture.real_time_update"
988 #define PRS_CAP_PROM_MODE "capture.prom_mode"
989 #define PRS_CAP_AUTO_SCROLL "capture.auto_scroll"
990
991 #define RED_COMPONENT(x)   ((((x) >> 16) & 0xff) * 65535 / 255)
992 #define GREEN_COMPONENT(x) ((((x) >>  8) & 0xff) * 65535 / 255)
993 #define BLUE_COMPONENT(x)   (((x)        & 0xff) * 65535 / 255)
994
995 static gchar *pr_formats[] = { "text", "postscript" };
996 static gchar *pr_dests[]   = { "command", "file" };
997
998 typedef struct {
999   char    letter;
1000   guint32 value;
1001 } name_resolve_opt_t;
1002
1003 static name_resolve_opt_t name_resolve_opt[] = {
1004   { 'm', PREFS_RESOLV_MAC },
1005   { 'n', PREFS_RESOLV_NETWORK },
1006   { 't', PREFS_RESOLV_TRANSPORT },
1007 };
1008
1009 #define N_NAME_RESOLVE_OPT      (sizeof name_resolve_opt / sizeof name_resolve_opt[0])
1010
1011 static char *
1012 name_resolve_to_string(guint32 name_resolve)
1013 {
1014   static char string[N_NAME_RESOLVE_OPT+1];
1015   char *p;
1016   unsigned int i;
1017   gboolean all_opts_set = TRUE;
1018
1019   if (name_resolve == PREFS_RESOLV_NONE)
1020     return "FALSE";
1021   p = &string[0];
1022   for (i = 0; i < N_NAME_RESOLVE_OPT; i++) {
1023     if (name_resolve & name_resolve_opt[i].value)
1024       *p++ =  name_resolve_opt[i].letter;
1025     else
1026       all_opts_set = FALSE;
1027   }
1028   *p = '\0';
1029   if (all_opts_set)
1030     return "TRUE";
1031   return string;
1032 }
1033
1034 char
1035 string_to_name_resolve(char *string, guint32 *name_resolve)
1036 {
1037   char c;
1038   unsigned int i;
1039
1040   *name_resolve = 0;
1041   while ((c = *string++) != '\0') {
1042     for (i = 0; i < N_NAME_RESOLVE_OPT; i++) {
1043       if (c == name_resolve_opt[i].letter) {
1044         *name_resolve |= name_resolve_opt[i].value;
1045         break;
1046       }
1047     }
1048     if (i == N_NAME_RESOLVE_OPT) {
1049       /*
1050        * Unrecognized letter.
1051        */
1052       return c;
1053     }
1054   }
1055   return '\0';
1056 }
1057
1058 static int
1059 set_pref(gchar *pref_name, gchar *value)
1060 {
1061   GList    *col_l, *col_l_elt;
1062   gint      llen;
1063   fmt_data *cfmt;
1064   unsigned long int cval;
1065   guint    uval;
1066   gboolean bval;
1067   gint     enum_val;
1068   char     *p;
1069   gchar    *dotp;
1070   module_t *module;
1071   pref_t   *pref;
1072
1073   if (strcmp(pref_name, PRS_PRINT_FMT) == 0) {
1074     if (strcmp(value, pr_formats[PR_FMT_TEXT]) == 0) {
1075       prefs.pr_format = PR_FMT_TEXT;
1076     } else if (strcmp(value, pr_formats[PR_FMT_PS]) == 0) {
1077       prefs.pr_format = PR_FMT_PS;
1078     } else {
1079       return PREFS_SET_SYNTAX_ERR;
1080     }
1081   } else if (strcmp(pref_name, PRS_PRINT_DEST) == 0) {
1082     if (strcmp(value, pr_dests[PR_DEST_CMD]) == 0) {
1083       prefs.pr_dest = PR_DEST_CMD;
1084     } else if (strcmp(value, pr_dests[PR_DEST_FILE]) == 0) {
1085       prefs.pr_dest = PR_DEST_FILE;
1086     } else {
1087       return PREFS_SET_SYNTAX_ERR;
1088     }
1089   } else if (strcmp(pref_name, PRS_PRINT_FILE) == 0) {
1090     if (prefs.pr_file) g_free(prefs.pr_file);
1091     prefs.pr_file = g_strdup(value);
1092   } else if (strcmp(pref_name, PRS_PRINT_CMD) == 0) {
1093     if (prefs.pr_cmd) g_free(prefs.pr_cmd);
1094     prefs.pr_cmd = g_strdup(value);
1095   } else if (strcmp(pref_name, PRS_COL_FMT) == 0) {
1096     col_l = get_string_list(value);
1097     if (col_l == NULL)
1098       return PREFS_SET_SYNTAX_ERR;
1099     if ((g_list_length(col_l) % 2) != 0) {
1100       /* A title didn't have a matching format.  */
1101       clear_string_list(col_l);
1102       return PREFS_SET_SYNTAX_ERR;
1103     }
1104     /* Check to make sure all column formats are valid.  */
1105     col_l_elt = g_list_first(col_l);
1106     while(col_l_elt) {
1107       /* Make sure the title isn't empty.  */
1108       if (strcmp(col_l_elt->data, "") == 0) {
1109         /* It is.  */
1110         clear_string_list(col_l);
1111         return PREFS_SET_SYNTAX_ERR;
1112       }
1113
1114       /* Go past the title.  */
1115       col_l_elt = col_l_elt->next;
1116
1117       /* Check the format.  */
1118       if (get_column_format_from_str(col_l_elt->data) == -1) {
1119         /* It's not a valid column format.  */
1120         clear_string_list(col_l);
1121         return PREFS_SET_SYNTAX_ERR;
1122       }
1123
1124       /* Go past the format.  */
1125       col_l_elt = col_l_elt->next;
1126     }
1127     free_col_info(&prefs);
1128     prefs.col_list = NULL;
1129     llen             = g_list_length(col_l);
1130     prefs.num_cols   = llen / 2;
1131     col_l_elt = g_list_first(col_l);
1132     while(col_l_elt) {
1133       cfmt = (fmt_data *) g_malloc(sizeof(fmt_data));
1134       cfmt->title    = g_strdup(col_l_elt->data);
1135       col_l_elt      = col_l_elt->next;
1136       cfmt->fmt      = g_strdup(col_l_elt->data);
1137       col_l_elt      = col_l_elt->next;
1138       prefs.col_list = g_list_append(prefs.col_list, cfmt);
1139     }
1140     clear_string_list(col_l);
1141   } else if (strcmp(pref_name, PRS_STREAM_CL_FG) == 0) {
1142     cval = strtoul(value, NULL, 16);
1143     prefs.st_client_fg.pixel = 0;
1144     prefs.st_client_fg.red   = RED_COMPONENT(cval);
1145     prefs.st_client_fg.green = GREEN_COMPONENT(cval);
1146     prefs.st_client_fg.blue  = BLUE_COMPONENT(cval);
1147   } else if (strcmp(pref_name, PRS_STREAM_CL_BG) == 0) {
1148     cval = strtoul(value, NULL, 16);
1149     prefs.st_client_bg.pixel = 0;
1150     prefs.st_client_bg.red   = RED_COMPONENT(cval);
1151     prefs.st_client_bg.green = GREEN_COMPONENT(cval);
1152     prefs.st_client_bg.blue  = BLUE_COMPONENT(cval);
1153   } else if (strcmp(pref_name, PRS_STREAM_SR_FG) == 0) {
1154     cval = strtoul(value, NULL, 16);
1155     prefs.st_server_fg.pixel = 0;
1156     prefs.st_server_fg.red   = RED_COMPONENT(cval);
1157     prefs.st_server_fg.green = GREEN_COMPONENT(cval);
1158     prefs.st_server_fg.blue  = BLUE_COMPONENT(cval);
1159   } else if (strcmp(pref_name, PRS_STREAM_SR_BG) == 0) {
1160     cval = strtoul(value, NULL, 16);
1161     prefs.st_server_bg.pixel = 0;
1162     prefs.st_server_bg.red   = RED_COMPONENT(cval);
1163     prefs.st_server_bg.green = GREEN_COMPONENT(cval);
1164     prefs.st_server_bg.blue  = BLUE_COMPONENT(cval);
1165   } else if (strcmp(pref_name, PRS_GUI_SCROLLBAR_ON_RIGHT) == 0) {
1166     if (strcasecmp(value, "true") == 0) {
1167             prefs.gui_scrollbar_on_right = TRUE;
1168     }
1169     else {
1170             prefs.gui_scrollbar_on_right = FALSE;
1171     }
1172   } else if (strcmp(pref_name, PRS_GUI_PLIST_SEL_BROWSE) == 0) {
1173     if (strcasecmp(value, "true") == 0) {
1174             prefs.gui_plist_sel_browse = TRUE;
1175     }
1176     else {
1177             prefs.gui_plist_sel_browse = FALSE;
1178     }
1179   } else if (strcmp(pref_name, PRS_GUI_PTREE_SEL_BROWSE) == 0) {
1180     if (strcasecmp(value, "true") == 0) {
1181             prefs.gui_ptree_sel_browse = TRUE;
1182     }
1183     else {
1184             prefs.gui_ptree_sel_browse = FALSE;
1185     }
1186   } else if (strcmp(pref_name, PRS_GUI_PTREE_LINE_STYLE) == 0) {
1187           prefs.gui_ptree_line_style =
1188                   find_index_from_string_array(value, gui_ptree_line_style_text, 0);
1189   } else if (strcmp(pref_name, PRS_GUI_PTREE_EXPANDER_STYLE) == 0) {
1190           prefs.gui_ptree_expander_style =
1191                   find_index_from_string_array(value, gui_ptree_expander_style_text, 1);
1192   } else if (strcmp(pref_name, PRS_GUI_HEX_DUMP_HIGHLIGHT_STYLE) == 0) {
1193           prefs.gui_hex_dump_highlight_style =
1194                   find_index_from_string_array(value, gui_hex_dump_highlight_style_text, 1);
1195   } else if (strcmp(pref_name, PRS_GUI_FONT_NAME) == 0) {
1196           if (prefs.gui_font_name != NULL)
1197                 g_free(prefs.gui_font_name);
1198           prefs.gui_font_name = g_strdup(value);
1199   } else if (strcmp(pref_name, PRS_GUI_MARKED_FG) == 0) {
1200     cval = strtoul(value, NULL, 16);
1201     prefs.gui_marked_fg.pixel = 0;
1202     prefs.gui_marked_fg.red   = RED_COMPONENT(cval);
1203     prefs.gui_marked_fg.green = GREEN_COMPONENT(cval);
1204     prefs.gui_marked_fg.blue  = BLUE_COMPONENT(cval);
1205   } else if (strcmp(pref_name, PRS_GUI_MARKED_BG) == 0) {
1206     cval = strtoul(value, NULL, 16);
1207     prefs.gui_marked_bg.pixel = 0;
1208     prefs.gui_marked_bg.red   = RED_COMPONENT(cval);
1209     prefs.gui_marked_bg.green = GREEN_COMPONENT(cval);
1210     prefs.gui_marked_bg.blue  = BLUE_COMPONENT(cval);
1211
1212 /* handle the capture options */ 
1213   } else if (strcmp(pref_name, PRS_CAP_PROM_MODE) == 0) {
1214     prefs.capture_prom_mode = ((strcasecmp(value, "true") == 0)?TRUE:FALSE); 
1215  
1216   } else if (strcmp(pref_name, PRS_CAP_REAL_TIME) == 0) {
1217     prefs.capture_real_time = ((strcasecmp(value, "true") == 0)?TRUE:FALSE); 
1218
1219   } else if (strcmp(pref_name, PRS_CAP_AUTO_SCROLL) == 0) {
1220     prefs.capture_auto_scroll = ((strcasecmp(value, "true") == 0)?TRUE:FALSE); 
1221  
1222 /* handle the global options */
1223   } else if (strcmp(pref_name, PRS_NAME_RESOLVE) == 0 ||
1224              strcmp(pref_name, PRS_CAP_NAME_RESOLVE) == 0) {
1225     /*
1226      * "TRUE" and "FALSE", for backwards compatibility, are synonyms for
1227      * PREFS_RESOLV_ALL and PREFS_RESOLV_NONE.
1228      *
1229      * Otherwise, we treat it as a list of name types we want to resolve.
1230      */
1231     if (strcasecmp(value, "true") == 0)
1232       prefs.name_resolve = PREFS_RESOLV_ALL;
1233     else if (strcasecmp(value, "false") == 0)
1234       prefs.name_resolve = PREFS_RESOLV_NONE;
1235     else {
1236       prefs.name_resolve = PREFS_RESOLV_NONE;   /* start out with none set */
1237       if (string_to_name_resolve(value, &prefs.name_resolve) != '\0')
1238         return PREFS_SET_SYNTAX_ERR;
1239     }
1240   } else {
1241     /* To which module does this preference belong? */
1242     dotp = strchr(pref_name, '.');
1243     if (dotp == NULL)
1244       return PREFS_SET_SYNTAX_ERR;      /* no ".", so no module/name separator */
1245     *dotp = '\0';               /* separate module and preference name */
1246     module = find_module(pref_name);
1247
1248     /*
1249      * XXX - "Diameter" rather than "diameter" was used in earlier
1250      * versions of Ethereal; if we didn't find the module, and its name
1251      * was "Diameter", look for "diameter" instead.
1252      */
1253     if (module == NULL && strcmp(pref_name, "Diameter") == 0)
1254       module = find_module("diameter");
1255     *dotp = '.';                /* put the preference string back */
1256     if (module == NULL)
1257       return PREFS_SET_NO_SUCH_PREF;    /* no such module */
1258     dotp++;                     /* skip past separator to preference name */
1259     pref = find_preference(module, dotp);
1260
1261     if (pref == NULL) {
1262       if (strncmp(pref_name, "mgcp.", 5) == 0) {
1263         /*
1264          * XXX - "mgcp.display raw text toggle" and "mgcp.display dissect tree"
1265          * rather than "mgcp.display_raw_text" and "mgcp.display_dissect_tree"
1266          * were used in earlier versions of Ethereal; if we didn't find the
1267          * preference, it was an MGCP preference, and its name was
1268          * "display raw text toggle" or "display dissect tree", look for
1269          * "display_raw_text" or "display_dissect_tree" instead.
1270          *
1271          * "mgcp.tcp.port" and "mgcp.udp.port" are harder to handle, as both
1272          * the gateway and callagent ports were given those names; we interpret
1273          * the first as "mgcp.{tcp,udp}.gateway_port" and the second as
1274          * "mgcp.{tcp,udp}.callagent_port", as that's the order in which
1275          * they were registered by the MCCP dissector and thus that's the
1276          * order in which they were written to the preferences file.  (If
1277          * we're not reading the preferences file, but are handling stuff
1278          * from a "-o" command-line option, we have no clue which the user
1279          * had in mind - they should have used "mgcp.{tcp,udp}.gateway_port"
1280          * or "mgcp.{tcp,udp}.callagent_port" instead.)
1281          */
1282         if (strcmp(dotp, "display raw text toggle") == 0)
1283           pref = find_preference(module, "display_raw_text");
1284         else if (strcmp(dotp, "display dissect tree") == 0)
1285           pref = find_preference(module, "display_dissect_tree");
1286         else if (strcmp(dotp, "tcp.port") == 0) {
1287           mgcp_tcp_port_count++;
1288           if (mgcp_tcp_port_count == 1) {
1289             /* It's the first one */
1290             pref = find_preference(module, "tcp.gateway_port");
1291           } else if (mgcp_tcp_port_count == 2) {
1292             /* It's the second one */
1293             pref = find_preference(module, "tcp.callagent_port");
1294           }
1295           /* Otherwise it's from the command line, and we don't bother
1296              mapping it. */
1297         } else if (strcmp(dotp, "udp.port") == 0) {
1298           mgcp_udp_port_count++;
1299           if (mgcp_udp_port_count == 1) {
1300             /* It's the first one */
1301             pref = find_preference(module, "udp.gateway_port");
1302           } else if (mgcp_udp_port_count == 2) {
1303             /* It's the second one */
1304             pref = find_preference(module, "udp.callagent_port");
1305           }
1306           /* Otherwise it's from the command line, and we don't bother
1307              mapping it. */
1308         }
1309       }
1310     }
1311     if (pref == NULL)
1312       return PREFS_SET_NO_SUCH_PREF;    /* no such preference */
1313
1314     switch (pref->type) {
1315
1316     case PREF_UINT:
1317       uval = strtoul(value, &p, pref->info.base);
1318       if (p == value || *p != '\0')
1319         return PREFS_SET_SYNTAX_ERR;    /* number was bad */
1320       if (*pref->varp.uint != uval) {
1321         module->prefs_changed = TRUE;
1322         *pref->varp.uint = uval;
1323       }
1324       break;
1325
1326     case PREF_BOOL:
1327       /* XXX - give an error if it's neither "true" nor "false"? */
1328       if (strcasecmp(value, "true") == 0)
1329         bval = TRUE;
1330       else
1331         bval = FALSE;
1332       if (*pref->varp.bool != bval) {
1333         module->prefs_changed = TRUE;
1334         *pref->varp.bool = bval;
1335       }
1336       break;
1337
1338     case PREF_ENUM:
1339       /* XXX - give an error if it doesn't match? */
1340       enum_val = find_val_for_string(value,
1341                                         pref->info.enum_info.enumvals, 1);
1342       if (*pref->varp.enump != enum_val) {
1343         module->prefs_changed = TRUE;
1344         *pref->varp.enump = enum_val;
1345       }
1346       break;
1347
1348     case PREF_STRING:
1349       if (*pref->varp.string == NULL || strcmp(*pref->varp.string, value) != 0) {
1350         module->prefs_changed = TRUE;
1351         if (*pref->varp.string != NULL)
1352           g_free(*pref->varp.string);
1353         *pref->varp.string = g_strdup(value);
1354       }
1355       break;
1356     }
1357   }
1358   
1359   return PREFS_SET_OK;
1360 }
1361
1362 typedef struct {
1363         module_t *module;
1364         FILE    *pf;
1365 } write_pref_arg_t;
1366
1367 /*
1368  * Write out a single preference.
1369  */
1370 static void
1371 write_pref(gpointer data, gpointer user_data)
1372 {
1373         pref_t *pref = data;
1374         write_pref_arg_t *arg = user_data;
1375         const enum_val_t *enum_valp;
1376         const char *val_string;
1377
1378         fprintf(arg->pf, "\n# %s\n", pref->description);
1379
1380         switch (pref->type) {
1381
1382         case PREF_UINT:
1383                 switch (pref->info.base) {
1384
1385                 case 10:
1386                         fprintf(arg->pf, "# A decimal number.\n");
1387                         fprintf(arg->pf, "%s.%s: %u\n", arg->module->name,
1388                             pref->name, *pref->varp.uint);
1389                         break;
1390
1391                 case 8:
1392                         fprintf(arg->pf, "# An octal number.\n");
1393                         fprintf(arg->pf, "%s.%s: %#o\n", arg->module->name,
1394                             pref->name, *pref->varp.uint);
1395                         break;
1396
1397                 case 16:
1398                         fprintf(arg->pf, "# A hexadecimal number.\n");
1399                         fprintf(arg->pf, "%s.%s: %#x\n", arg->module->name,
1400                             pref->name, *pref->varp.uint);
1401                         break;
1402                 }
1403                 break;
1404
1405         case PREF_BOOL:
1406                 fprintf(arg->pf, "# TRUE or FALSE (case-insensitive).\n");
1407                 fprintf(arg->pf, "%s.%s: %s\n", arg->module->name, pref->name,
1408                     *pref->varp.bool ? "TRUE" : "FALSE");
1409                 break;
1410
1411         case PREF_ENUM:
1412                 fprintf(arg->pf, "# One of: ");
1413                 enum_valp = pref->info.enum_info.enumvals;
1414                 val_string = NULL;
1415                 while (enum_valp->name != NULL) {
1416                         if (enum_valp->value == *pref->varp.enump)
1417                                 val_string = enum_valp->name;
1418                         fprintf(arg->pf, "%s", enum_valp->name);
1419                         enum_valp++;
1420                         if (enum_valp->name == NULL)
1421                                 fprintf(arg->pf, "\n");
1422                         else
1423                                 fprintf(arg->pf, ", ");
1424                 }
1425                 fprintf(arg->pf, "# (case-insensitive).\n");
1426                 fprintf(arg->pf, "%s.%s: %s\n", arg->module->name, pref->name,
1427                     val_string);
1428                 break;
1429
1430         case PREF_STRING:
1431                 fprintf(arg->pf, "# A string.\n");
1432                 fprintf(arg->pf, "%s.%s: %s\n", arg->module->name, pref->name,
1433                     *pref->varp.string);
1434                 break;
1435         }
1436 }
1437
1438 static void
1439 write_module_prefs(gpointer data, gpointer user_data)
1440 {
1441         write_pref_arg_t arg;
1442
1443         arg.module = data;
1444         arg.pf = user_data;
1445         g_list_foreach(arg.module->prefs, write_pref, &arg);
1446 }
1447
1448 /* Write out "prefs" to the user's preferences file, and return 0.
1449
1450    If we got an error, stuff a pointer to the path of the preferences file
1451    into "*pf_path_return", and return the errno. */
1452 int
1453 write_prefs(char **pf_path_return)
1454 {
1455   FILE        *pf;
1456   struct stat  s_buf;
1457   GList       *clp, *col_l;
1458   fmt_data    *cfmt;
1459
1460   /* To do:
1461    * - Split output lines longer than MAX_VAL_LEN
1462    * - Create a function for the preference directory check/creation
1463    *   so that duplication can be avoided with filter.c
1464    */
1465
1466   if (! pf_path) {
1467     pf_path = (gchar *) g_malloc(strlen(get_home_dir()) + strlen(PF_DIR) +
1468       strlen(PF_NAME) + 4);
1469   }
1470
1471   sprintf(pf_path, "%s" G_DIR_SEPARATOR_S "%s", get_home_dir(), PF_DIR);
1472   if (stat(pf_path, &s_buf) != 0)
1473 #ifdef WIN32
1474     mkdir(pf_path);
1475 #else
1476     mkdir(pf_path, 0755);
1477 #endif
1478
1479   sprintf(pf_path, "%s" G_DIR_SEPARATOR_S "%s" G_DIR_SEPARATOR_S "%s",
1480     get_home_dir(), PF_DIR, PF_NAME);
1481   if ((pf = fopen(pf_path, "w")) == NULL) {
1482     *pf_path_return = pf_path;
1483     return errno;
1484   }
1485     
1486   fputs("# Configuration file for Ethereal " VERSION ".\n"
1487     "#\n"
1488     "# This file is regenerated each time preferences are saved within\n"
1489     "# Ethereal.  Making manual changes should be safe, however.\n"
1490     "\n"
1491     "######## Printing ########\n"
1492     "\n", pf);
1493
1494   fprintf (pf, "# Can be one of \"text\" or \"postscript\".\n"
1495     "print.format: %s\n\n", pr_formats[prefs.pr_format]);
1496
1497   fprintf (pf, "# Can be one of \"command\" or \"file\".\n"
1498     "print.destination: %s\n\n", pr_dests[prefs.pr_dest]);
1499
1500   fprintf (pf, "# This is the file that gets written to when the "
1501     "destination is set to \"file\"\n"
1502     "%s: %s\n\n", PRS_PRINT_FILE, prefs.pr_file);
1503
1504   fprintf (pf, "# Output gets piped to this command when the destination "
1505     "is set to \"command\"\n"
1506     "%s: %s\n\n", PRS_PRINT_CMD, prefs.pr_cmd);
1507
1508   clp = prefs.col_list;
1509   col_l = NULL;
1510   while (clp) {
1511     cfmt = (fmt_data *) clp->data;
1512     col_l = g_list_append(col_l, cfmt->title);
1513     col_l = g_list_append(col_l, cfmt->fmt);
1514     clp = clp->next;
1515   }
1516   fprintf (pf, "# Packet list column format.  Each pair of strings consists "
1517     "of a column title \n# and its format.\n"
1518     "%s: %s\n\n", PRS_COL_FMT, put_string_list(col_l));
1519   /* This frees the list of strings, but not the strings to which it
1520      refers; that's what we want, as we haven't copied those strings,
1521      we just referred to them.  */
1522   g_list_free(col_l);
1523
1524   fprintf (pf, "# TCP stream window color preferences.  Each value is a six "
1525     "digit hexadecimal value in the form rrggbb.\n");
1526   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_CL_FG,
1527     (prefs.st_client_fg.red * 255 / 65535),
1528     (prefs.st_client_fg.green * 255 / 65535),
1529     (prefs.st_client_fg.blue * 255 / 65535));
1530   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_CL_BG,
1531     (prefs.st_client_bg.red * 255 / 65535),
1532     (prefs.st_client_bg.green * 255 / 65535),
1533     (prefs.st_client_bg.blue * 255 / 65535));
1534   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_SR_FG,
1535     (prefs.st_server_fg.red * 255 / 65535),
1536     (prefs.st_server_fg.green * 255 / 65535),
1537     (prefs.st_server_fg.blue * 255 / 65535));
1538   fprintf (pf, "%s: %02x%02x%02x\n", PRS_STREAM_SR_BG,
1539     (prefs.st_server_bg.red * 255 / 65535),
1540     (prefs.st_server_bg.green * 255 / 65535),
1541     (prefs.st_server_bg.blue * 255 / 65535));
1542
1543   fprintf(pf, "\n# Vertical scrollbars should be on right side? TRUE/FALSE\n");
1544   fprintf(pf, PRS_GUI_SCROLLBAR_ON_RIGHT ": %s\n",
1545                   prefs.gui_scrollbar_on_right == TRUE ? "TRUE" : "FALSE");
1546
1547   fprintf(pf, "\n# Packet-list selection bar can be used to browse w/o selecting? TRUE/FALSE\n");
1548   fprintf(pf, PRS_GUI_PLIST_SEL_BROWSE ": %s\n",
1549                   prefs.gui_plist_sel_browse == TRUE ? "TRUE" : "FALSE");
1550
1551   fprintf(pf, "\n# Protocol-tree selection bar can be used to browse w/o selecting? TRUE/FALSE\n");
1552   fprintf(pf, PRS_GUI_PTREE_SEL_BROWSE ": %s\n",
1553                   prefs.gui_ptree_sel_browse == TRUE ? "TRUE" : "FALSE");
1554
1555   fprintf(pf, "\n# Protocol-tree line style. One of: NONE, SOLID, DOTTED, TABBED\n");
1556   fprintf(pf, PRS_GUI_PTREE_LINE_STYLE ": %s\n",
1557                   gui_ptree_line_style_text[prefs.gui_ptree_line_style]);
1558
1559   fprintf(pf, "\n# Protocol-tree expander style. One of: NONE, SQUARE, TRIANGLE, CIRCULAR\n");
1560   fprintf(pf, PRS_GUI_PTREE_EXPANDER_STYLE ": %s\n",
1561                   gui_ptree_expander_style_text[prefs.gui_ptree_expander_style]);
1562
1563   fprintf(pf, "\n# Hex dump highlight style. One of: BOLD, INVERSE\n");
1564   fprintf(pf, PRS_GUI_HEX_DUMP_HIGHLIGHT_STYLE ": %s\n",
1565                   gui_hex_dump_highlight_style_text[prefs.gui_hex_dump_highlight_style]);
1566
1567   fprintf(pf, "\n# Font name for packet list, protocol tree, and hex dump panes.\n");
1568   fprintf(pf, PRS_GUI_FONT_NAME ": %s\n", prefs.gui_font_name);
1569
1570   fprintf (pf, "\n# Color preferences for a marked frame.  Each value is a six "
1571     "digit hexadecimal value in the form rrggbb.\n");
1572   fprintf (pf, "%s: %02x%02x%02x\n", PRS_GUI_MARKED_FG,
1573     (prefs.gui_marked_fg.red * 255 / 65535),
1574     (prefs.gui_marked_fg.green * 255 / 65535),
1575     (prefs.gui_marked_fg.blue * 255 / 65535));
1576   fprintf (pf, "%s: %02x%02x%02x\n", PRS_GUI_MARKED_BG,
1577     (prefs.gui_marked_bg.red * 255 / 65535),
1578     (prefs.gui_marked_bg.green * 255 / 65535),
1579     (prefs.gui_marked_bg.blue * 255 / 65535));
1580
1581   fprintf(pf, "\n# Resolve addresses to names? TRUE/FALSE/{list of address types to resolve}\n");
1582   fprintf(pf, PRS_NAME_RESOLVE ": %s\n",
1583                   name_resolve_to_string(prefs.name_resolve));
1584
1585 /* write the capture options */
1586   fprintf(pf, "\n# Capture in promiscuous mode? TRUE/FALSE\n");
1587   fprintf(pf, PRS_CAP_PROM_MODE ": %s\n",
1588                   prefs.capture_prom_mode == TRUE ? "TRUE" : "FALSE");
1589
1590   fprintf(pf, "\n# Update packet list in real time during capture? TRUE/FALSE\n");
1591   fprintf(pf, PRS_CAP_REAL_TIME ": %s\n",
1592                   prefs.capture_real_time == TRUE ? "TRUE" : "FALSE");
1593
1594   fprintf(pf, "\n# scroll packet list during capture? TRUE/FALSE\n");
1595   fprintf(pf, PRS_CAP_AUTO_SCROLL ": %s\n",
1596                   prefs.capture_auto_scroll == TRUE ? "TRUE" : "FALSE");
1597
1598   g_list_foreach(modules, write_module_prefs, pf);
1599
1600   fclose(pf);
1601
1602   /* XXX - catch I/O errors (e.g. "ran out of disk space") and return
1603      an error indication, or maybe write to a new preferences file and
1604      rename that file on top of the old one only if there are not I/O
1605      errors. */
1606   return 0;
1607 }
1608
1609 /* Copy a set of preferences. */
1610 void
1611 copy_prefs(e_prefs *dest, e_prefs *src)
1612 {
1613   fmt_data *src_cfmt, *dest_cfmt;
1614   GList *entry;
1615
1616   dest->pr_format = src->pr_format;
1617   dest->pr_dest = src->pr_dest;
1618   dest->pr_file = g_strdup(src->pr_file);
1619   dest->pr_cmd = g_strdup(src->pr_cmd);
1620   dest->col_list = NULL;
1621   for (entry = src->col_list; entry != NULL; entry = g_list_next(entry)) {
1622     src_cfmt = entry->data;
1623     dest_cfmt = (fmt_data *) g_malloc(sizeof(fmt_data));
1624     dest_cfmt->title = g_strdup(src_cfmt->title);
1625     dest_cfmt->fmt = g_strdup(src_cfmt->fmt);
1626     dest->col_list = g_list_append(dest->col_list, dest_cfmt);
1627   }
1628   dest->num_cols = src->num_cols;
1629   dest->st_client_fg = src->st_client_fg;
1630   dest->st_client_bg = src->st_client_bg;
1631   dest->st_server_fg = src->st_server_fg;
1632   dest->st_server_bg = src->st_server_bg;
1633   dest->gui_scrollbar_on_right = src->gui_scrollbar_on_right;
1634   dest->gui_plist_sel_browse = src->gui_plist_sel_browse;
1635   dest->gui_ptree_sel_browse = src->gui_ptree_sel_browse;
1636   dest->gui_ptree_line_style = src->gui_ptree_line_style;
1637   dest->gui_ptree_expander_style = src->gui_ptree_expander_style;
1638   dest->gui_hex_dump_highlight_style = src->gui_hex_dump_highlight_style;
1639   dest->gui_font_name = g_strdup(src->gui_font_name);
1640   dest->gui_marked_fg = src->gui_marked_fg;
1641   dest->gui_marked_bg = src->gui_marked_bg;
1642 /*  values for the capture dialog box */
1643   dest->capture_prom_mode = src->capture_prom_mode;
1644   dest->capture_real_time = src->capture_real_time;
1645   dest->capture_auto_scroll = src->capture_auto_scroll;
1646   dest->name_resolve = src->name_resolve;
1647
1648 }
1649
1650 /* Free a set of preferences. */
1651 void
1652 free_prefs(e_prefs *pr)
1653 {
1654   if (pr->pr_file != NULL) {
1655     g_free(pr->pr_file);
1656     pr->pr_file = NULL;
1657   }
1658   if (pr->pr_cmd != NULL) {
1659     g_free(pr->pr_cmd);
1660     pr->pr_cmd = NULL;
1661   }
1662   free_col_info(pr);
1663   if (pr->gui_font_name != NULL) {
1664     g_free(pr->gui_font_name);
1665     pr->gui_font_name = NULL;
1666   }
1667 }
1668
1669 static void
1670 free_col_info(e_prefs *pr)
1671 {
1672   fmt_data *cfmt;
1673
1674   while (pr->col_list != NULL) {
1675     cfmt = pr->col_list->data;
1676     g_free(cfmt->title);
1677     g_free(cfmt->fmt);
1678     g_free(cfmt);
1679     pr->col_list = g_list_remove_link(pr->col_list, pr->col_list);
1680   }
1681   g_list_free(pr->col_list);
1682   pr->col_list = NULL;
1683 }