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