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