Make UAT record update callbacks return a success/failure indication.
[metze/wireshark/wip.git] / epan / expert.c
1 /* expert.c
2  * Collecting Expert information.
3  *
4  * Implemented as a tap named "expert".
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include "config.h"
26
27 #include <stdio.h>
28 #include <stdlib.h>
29
30 #include "packet.h"
31 #include "expert.h"
32 #include "uat.h"
33 #include "prefs.h"
34 #include "wmem/wmem.h"
35 #include "tap.h"
36
37 /* proto_expert cannot be static because it's referenced in the
38  * print routines
39  */
40 int proto_expert              = -1;
41
42 static int proto_malformed    = -1;
43
44 static int expert_tap         = -1;
45 static int highest_severity   =  0;
46
47 static int ett_expert         = -1;
48 static int ett_subexpert      = -1;
49
50 static int hf_expert_msg      = -1;
51 static int hf_expert_group    = -1;
52 static int hf_expert_severity = -1;
53
54 struct expert_module
55 {
56         const char *proto_name;
57         int         proto_id;      /* Cache this for registering hfs */
58 };
59
60 /* List which stores protocols and expert_info that have been registered */
61 typedef struct _gpa_expertinfo_t {
62         guint32             len;
63         guint32             allocated_len;
64         expert_field_info **ei;
65 } gpa_expertinfo_t;
66 static gpa_expertinfo_t gpa_expertinfo;
67
68 /* Hash table of abbreviations and IDs */
69 static GHashTable *gpa_name_map = NULL;
70
71 const value_string expert_group_vals[] = {
72         { PI_CHECKSUM,          "Checksum" },
73         { PI_SEQUENCE,          "Sequence" },
74         { PI_RESPONSE_CODE,     "Response" },
75         { PI_REQUEST_CODE,      "Request" },
76         { PI_UNDECODED,         "Undecoded" },
77         { PI_REASSEMBLE,        "Reassemble" },
78         { PI_MALFORMED,         "Malformed" },
79         { PI_DEBUG,             "Debug" },
80         { PI_PROTOCOL,          "Protocol" },
81         { PI_SECURITY,          "Security" },
82         { PI_COMMENTS_GROUP,    "Comment" },
83         { 0, NULL }
84 };
85
86 const value_string expert_severity_vals[] = {
87         { PI_ERROR,             "Error" },
88         { PI_WARN,              "Warn" },
89         { PI_NOTE,              "Note" },
90         { PI_CHAT,              "Chat" },
91         { PI_COMMENT,           "Comment" },
92         { 1,                    "Ok" },
93         { 0, NULL }
94 };
95
96 /* Possible values for a checksum evaluation */
97 const value_string expert_checksum_vals[] = {
98         { EXPERT_CHECKSUM_DISABLED,   "Disabled"  },
99         { EXPERT_CHECKSUM_UNKNOWN,    "Unknown"  },
100         { EXPERT_CHECKSUM_GOOD,       "Good"  },
101         { EXPERT_CHECKSUM_BAD,        "Bad" },
102         { 0,        NULL }
103 };
104
105 static expert_field_info *expert_registrar_get_byname(const char *field_name);
106
107 /*----------------------------------------------------------------------------*/
108 /* UAT for customizing severity levels.                                       */
109 /*----------------------------------------------------------------------------*/
110 typedef struct
111 {
112         char    *field;
113         guint32  severity;
114 } expert_level_entry_t;
115
116 static expert_level_entry_t *uat_expert_entries = NULL;
117 static guint expert_level_entry_count = 0;
118 /* Array of field names currently in UAT */
119 static GArray *uat_saved_fields = NULL;
120
121 UAT_CSTRING_CB_DEF(uat_expert_entries, field, expert_level_entry_t)
122 UAT_VS_DEF(uat_expert_entries, severity, expert_level_entry_t, guint32, PI_ERROR, "Error")
123
124 static gboolean uat_expert_update_cb(void *r, char **err)
125 {
126         expert_level_entry_t *rec = (expert_level_entry_t *)r;
127
128         if (expert_registrar_get_byname(rec->field) == NULL) {
129                 *err = g_strdup_printf("Expert Info field doesn't exist");
130                 return FALSE;
131         }
132         return TRUE;
133 }
134
135 static void *uat_expert_copy_cb(void *n, const void *o, size_t siz _U_)
136 {
137         expert_level_entry_t       *new_record = (expert_level_entry_t*)n;
138         const expert_level_entry_t *old_record = (const expert_level_entry_t *)o;
139
140         if (old_record->field) {
141                 new_record->field = g_strdup(old_record->field);
142         } else {
143                 new_record->field = NULL;
144         }
145
146         new_record->severity = old_record->severity;
147
148         return new_record;
149 }
150
151 static void uat_expert_free_cb(void*r)
152 {
153         expert_level_entry_t *rec = (expert_level_entry_t *)r;
154
155         if (rec->field)
156                 g_free(rec->field);
157 }
158
159 static void uat_expert_post_update_cb(void)
160 {
161         guint              i;
162         expert_field_info *field;
163
164         /* Reset any of the previous list of expert info fields to their original severity */
165         for ( i = 0 ; i < uat_saved_fields->len; i++ ) {
166                 field = g_array_index(uat_saved_fields, expert_field_info*, i);
167                 if (field != NULL) {
168                         field->severity = field->orig_severity;
169                 }
170         }
171
172         g_array_set_size(uat_saved_fields, 0);
173
174         for (i = 0; i < expert_level_entry_count; i++)
175         {
176                 field = expert_registrar_get_byname(uat_expert_entries[i].field);
177                 if (field != NULL)
178                 {
179                         field->severity = uat_expert_entries[i].severity;
180                         g_array_append_val(uat_saved_fields, field);
181                 }
182         }
183 }
184
185 #define EXPERT_REGISTRAR_GET_NTH(eiindex, expinfo)                                               \
186         if((guint)eiindex >= gpa_expertinfo.len && getenv("WIRESHARK_ABORT_ON_DISSECTOR_BUG"))   \
187                 g_error("Unregistered expert info! index=%d", eiindex);                          \
188         DISSECTOR_ASSERT_HINT((guint)eiindex < gpa_expertinfo.len, "Unregistered expert info!"); \
189         expinfo = gpa_expertinfo.ei[eiindex];
190
191 void
192 expert_packet_init(void)
193 {
194         module_t *module_expert;
195         uat_t    *expert_uat;
196
197         static hf_register_info hf[] = {
198                 { &hf_expert_msg,
199                         { "Message", "_ws.expert.message", FT_STRING, BASE_NONE, NULL, 0, "Wireshark expert information", HFILL }
200                 },
201                 { &hf_expert_group,
202                         { "Group", "_ws.expert.group", FT_UINT32, BASE_HEX, VALS(expert_group_vals), 0, "Wireshark expert group", HFILL }
203                 },
204                 { &hf_expert_severity,
205                         { "Severity level", "_ws.expert.severity", FT_UINT32, BASE_HEX, VALS(expert_severity_vals), 0, "Wireshark expert severity level", HFILL }
206                 }
207         };
208         static gint *ett[] = {
209                 &ett_expert,
210                 &ett_subexpert
211         };
212
213         /* UAT for overriding severity levels */
214         static uat_field_t custom_expert_fields[] = {
215                 UAT_FLD_CSTRING(uat_expert_entries, field, "Field name", "Expert Info filter name"),
216                 UAT_FLD_VS(uat_expert_entries, severity, "Severity", expert_severity_vals, "Custom severity level"),
217                 UAT_END_FIELDS
218         };
219
220         if (expert_tap == -1) {
221                 expert_tap = register_tap("expert");
222         }
223
224         if (proto_expert == -1) {
225                 proto_expert = proto_register_protocol("Expert Info", "Expert", "_ws.expert");
226                 proto_register_field_array(proto_expert, hf, array_length(hf));
227                 proto_register_subtree_array(ett, array_length(ett));
228                 proto_set_cant_toggle(proto_expert);
229
230                 module_expert = prefs_register_protocol(proto_expert, NULL);
231
232                 expert_uat = uat_new("Expert Info Severity Level Configuration",
233                         sizeof(expert_level_entry_t),
234                         "expert_severity",
235                         TRUE,
236                         (void **)&uat_expert_entries,
237                         &expert_level_entry_count,
238                         UAT_AFFECTS_DISSECTION,
239                         NULL,
240                         uat_expert_copy_cb,
241                         uat_expert_update_cb,
242                         uat_expert_free_cb,
243                         uat_expert_post_update_cb,
244                         custom_expert_fields);
245
246                 prefs_register_uat_preference(module_expert,
247                         "expert_severity_levels",
248                         "Severity Level Configuration",
249                         "A table that overrides Expert Info field severity levels to user configured levels",
250                         expert_uat);
251
252         }
253
254         highest_severity = 0;
255
256         proto_malformed = proto_get_id_by_filter_name("_ws.malformed");
257 }
258
259 void
260 expert_init(void)
261 {
262         gpa_expertinfo.len           = 0;
263         gpa_expertinfo.allocated_len = 0;
264         gpa_expertinfo.ei            = NULL;
265         gpa_name_map                 = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, NULL);
266         uat_saved_fields             = g_array_new(FALSE, FALSE, sizeof(expert_field_info*));
267 }
268
269 void
270 expert_packet_cleanup(void)
271 {
272 }
273
274 void
275 expert_cleanup(void)
276 {
277         if (gpa_expertinfo.allocated_len) {
278                 gpa_expertinfo.len           = 0;
279                 gpa_expertinfo.allocated_len = 0;
280                 g_free(gpa_expertinfo.ei);
281                 gpa_expertinfo.ei          = NULL;
282         }
283
284         /* Free the abbrev/ID GTree */
285         if (gpa_name_map) {
286                 g_hash_table_destroy(gpa_name_map);
287                 gpa_name_map = NULL;
288         }
289
290         /* Free the UAT saved fields */
291         if (uat_saved_fields) {
292                 g_array_free(uat_saved_fields, TRUE);
293                 uat_saved_fields = NULL;
294         }
295 }
296
297
298 int
299 expert_get_highest_severity(void)
300 {
301         return highest_severity;
302 }
303
304 void
305 expert_update_comment_count(guint64 count)
306 {
307         if (count==0 && highest_severity==PI_COMMENT)
308                 highest_severity = 0;
309 }
310
311 expert_module_t *expert_register_protocol(int id)
312 {
313         expert_module_t *module;
314         protocol_t      *protocol;
315
316         protocol = find_protocol_by_id(id);
317
318         module = wmem_new(wmem_epan_scope(), expert_module_t);
319         module->proto_id = id;
320         module->proto_name = proto_get_protocol_short_name(protocol);
321
322         return module;
323 }
324
325 static int
326 expert_register_field_init(expert_field_info *expinfo, expert_module_t *module)
327 {
328         expinfo->protocol      = module->proto_name;
329
330         /* if we always add and never delete, then id == len - 1 is correct */
331         if (gpa_expertinfo.len >= gpa_expertinfo.allocated_len) {
332                 if (!gpa_expertinfo.ei) {
333                         gpa_expertinfo.allocated_len = PRE_ALLOC_EXPERT_FIELDS_MEM;
334                         gpa_expertinfo.ei = (expert_field_info **)g_malloc(sizeof(expert_field_info *)*PRE_ALLOC_EXPERT_FIELDS_MEM);
335                 } else {
336                         gpa_expertinfo.allocated_len += 1000;
337                         gpa_expertinfo.ei = (expert_field_info **)g_realloc(gpa_expertinfo.ei,
338                                                    sizeof(expert_field_info *)*gpa_expertinfo.allocated_len);
339                 }
340         }
341         gpa_expertinfo.ei[gpa_expertinfo.len] = expinfo;
342         gpa_expertinfo.len++;
343         expinfo->id = gpa_expertinfo.len - 1;
344         /* Save the original severity so it can be restored by the UAT */
345         expinfo->orig_severity = expinfo->severity;
346
347         /* save field name for lookup */
348         g_hash_table_insert(gpa_name_map, (gpointer) (expinfo->name), expinfo);
349
350         return expinfo->id;
351 }
352
353
354 /* for use with static arrays only, since we don't allocate our own copies
355 of the expert_field_info struct contained within the exp_register_info struct */
356 void
357 expert_register_field_array(expert_module_t *module, ei_register_info *exp, const int num_records)
358 {
359         int               i;
360         ei_register_info *ptr = exp;
361
362         for (i = 0; i < num_records; i++, ptr++) {
363                 /*
364                  * Make sure we haven't registered this yet.
365                  * Most fields have variables associated with them
366                  * that are initialized to -1; some have array elements,
367                  * or possibly uninitialized variables, so we also allow
368                  * 0 (which is unlikely to be the field ID we get back
369                  * from "expert_register_field_init()").
370                  */
371                 if (ptr->ids->ei != -1 && ptr->ids->ei != 0) {
372                         fprintf(stderr,
373                                 "Duplicate field detected in call to expert_register_field_array: '%s' is already registered\n",
374                                 ptr->eiinfo.summary);
375                         return;
376                 }
377
378                 /* Register the field with the experts */
379                 ptr->ids->ei = expert_register_field_init(&ptr->eiinfo, module);
380
381                 /* Register with the header field info, so it's display filterable */
382                 ptr->eiinfo.hf_info.p_id = &ptr->ids->hf;
383                 ptr->eiinfo.hf_info.hfinfo.abbrev = ptr->eiinfo.name;
384                 ptr->eiinfo.hf_info.hfinfo.blurb = ptr->eiinfo.summary;
385
386                 proto_register_field_array(module->proto_id, &ptr->eiinfo.hf_info, 1);
387         }
388 }
389
390 /* Finds a record in the expert array by name.
391  * For the moment, this function is only used "internally"
392  * but may find a reason to be exported
393  */
394 static expert_field_info *
395 expert_registrar_get_byname(const char *field_name)
396 {
397         expert_field_info *hfinfo;
398
399         if (!field_name)
400                 return NULL;
401
402         hfinfo = (expert_field_info*)g_hash_table_lookup(gpa_name_map, field_name);
403
404         return hfinfo;
405 }
406
407
408 /** clear flags according to the mask and set new flag values */
409 #define FI_REPLACE_FLAGS(fi, mask, flags_in) { \
410         (fi->flags = (fi)->flags & ~(mask)); \
411         (fi->flags = (fi)->flags | (flags_in)); \
412 }
413
414 /* set's the PI_ flags to a protocol item
415  * (and its parent items till the toplevel) */
416 static void
417 expert_set_item_flags(proto_item *pi, const int group, const guint severity)
418 {
419         if (pi != NULL && PITEM_FINFO(pi) != NULL && (severity >= FI_GET_FLAG(PITEM_FINFO(pi), PI_SEVERITY_MASK))) {
420                 FI_REPLACE_FLAGS(PITEM_FINFO(pi), PI_GROUP_MASK, group);
421                 FI_REPLACE_FLAGS(PITEM_FINFO(pi), PI_SEVERITY_MASK, severity);
422
423                 /* propagate till toplevel item */
424                 pi = proto_item_get_parent(pi);
425                 expert_set_item_flags(pi, group, severity);
426         }
427 }
428
429 static proto_tree*
430 expert_create_tree(proto_item *pi, int group, int severity, const char *msg)
431 {
432         proto_tree *tree;
433         proto_item *ti;
434
435         tree = proto_item_add_subtree(pi, ett_expert);
436         ti = proto_tree_add_protocol_format(tree, proto_expert, NULL, 0, 0, "Expert Info (%s/%s): %s",
437                                             val_to_str(severity, expert_severity_vals, "Unknown (%u)"),
438                                             val_to_str(group, expert_group_vals, "Unknown (%u)"),
439                                             msg);
440         PROTO_ITEM_SET_GENERATED(ti);
441
442         if (group == PI_MALFORMED) {
443                 /* Add hidden malformed protocol filter */
444                 proto_item *malformed_ti = proto_tree_add_item(tree, proto_malformed, NULL, 0, 0, ENC_NA);
445                 PROTO_ITEM_SET_HIDDEN(malformed_ti);
446         }
447
448         return proto_item_add_subtree(ti, ett_subexpert);
449 }
450
451 static void
452 expert_set_info_vformat(packet_info *pinfo, proto_item *pi, int group, int severity, int hf_index, gboolean use_vaformat,
453                         const char *format, va_list ap)
454 {
455         char           formatted[ITEM_LABEL_LENGTH];
456         int            tap;
457         expert_info_t *ei;
458         proto_tree    *tree;
459         proto_item    *ti;
460
461         if (pinfo == NULL && pi && pi->tree_data) {
462                 pinfo = PTREE_DATA(pi)->pinfo;
463         }
464
465         /* if this packet isn't loaded because of a read filter, don't output anything */
466         if (pinfo == NULL || PINFO_FD_NUM(pinfo) == 0) {
467                 return;
468         }
469
470         if (severity > highest_severity) {
471                 highest_severity = severity;
472         }
473
474         /* XXX: can we get rid of these checks and make them programming errors instead now? */
475         if (pi != NULL && PITEM_FINFO(pi) != NULL) {
476                 expert_set_item_flags(pi, group, severity);
477         }
478
479         if ((pi == NULL) || (PITEM_FINFO(pi) == NULL) ||
480                 ((guint)severity >= FI_GET_FLAG(PITEM_FINFO(pi), PI_SEVERITY_MASK))) {
481                 col_add_str(pinfo->cinfo, COL_EXPERT, val_to_str(severity, expert_severity_vals, "Unknown (%u)"));
482         }
483
484         if (use_vaformat) {
485                 g_vsnprintf(formatted, ITEM_LABEL_LENGTH, format, ap);
486         } else {
487                 g_strlcpy(formatted, format, ITEM_LABEL_LENGTH);
488         }
489
490         tree = expert_create_tree(pi, group, severity, formatted);
491
492         if (hf_index == -1) {
493                 /* If no filterable expert info, just add the message */
494                 ti = proto_tree_add_string(tree, hf_expert_msg, NULL, 0, 0, formatted);
495                 PROTO_ITEM_SET_GENERATED(ti);
496         } else {
497                 /* If filterable expert info, hide the "generic" form of the message,
498                    and generate the formatted filterable expert info */
499                 ti = proto_tree_add_none_format(tree, hf_index, NULL, 0, 0, "%s", formatted);
500                 PROTO_ITEM_SET_GENERATED(ti);
501                 ti = proto_tree_add_string(tree, hf_expert_msg, NULL, 0, 0, formatted);
502                 PROTO_ITEM_SET_HIDDEN(ti);
503         }
504
505         ti = proto_tree_add_uint_format_value(tree, hf_expert_severity, NULL, 0, 0, severity,
506                                               "%s", val_to_str_const(severity, expert_severity_vals, "Unknown"));
507         PROTO_ITEM_SET_GENERATED(ti);
508         ti = proto_tree_add_uint_format_value(tree, hf_expert_group, NULL, 0, 0, group,
509                                               "%s", val_to_str_const(group, expert_group_vals, "Unknown"));
510         PROTO_ITEM_SET_GENERATED(ti);
511
512         tap = have_tap_listener(expert_tap);
513
514         if (!tap)
515                 return;
516
517         ei = wmem_new(wmem_packet_scope(), expert_info_t);
518
519         ei->packet_num  = PINFO_FD_NUM(pinfo);
520         ei->group       = group;
521         ei->severity    = severity;
522         ei->protocol    = pinfo->current_proto;
523         ei->summary     = wmem_strdup(wmem_packet_scope(), formatted);
524
525         /* if we have a proto_item (not a faked item), set expert attributes to it */
526         if (pi != NULL && PITEM_FINFO(pi) != NULL) {
527                 ei->pitem = pi;
528         }
529         /* XXX: remove this because we don't have an internal-only function now? */
530         else {
531                 ei->pitem = NULL;
532         }
533
534         tap_queue_packet(expert_tap, pinfo, ei);
535 }
536
537 /* Helper function for expert_add_info() to work around compiler's special needs on ARM */
538 static inline void
539 expert_add_info_internal(packet_info *pinfo, proto_item *pi, expert_field *expindex, ...)
540 {
541         /* the va_list is ignored */
542         va_list            unused;
543         expert_field_info *eiinfo;
544
545         /* Look up the item */
546         EXPERT_REGISTRAR_GET_NTH(expindex->ei, eiinfo);
547
548         va_start(unused, expindex);
549         expert_set_info_vformat(pinfo, pi, eiinfo->group, eiinfo->severity, *eiinfo->hf_info.p_id, FALSE, eiinfo->summary, unused);
550         va_end(unused);
551 }
552
553 void
554 expert_add_info(packet_info *pinfo, proto_item *pi, expert_field *expindex)
555 {
556         expert_add_info_internal(pinfo, pi, expindex);
557 }
558
559 void
560 expert_add_info_format(packet_info *pinfo, proto_item *pi, expert_field *expindex, const char *format, ...)
561 {
562         va_list            ap;
563         expert_field_info *eiinfo;
564
565         /* Look up the item */
566         EXPERT_REGISTRAR_GET_NTH(expindex->ei, eiinfo);
567
568         va_start(ap, format);
569         expert_set_info_vformat(pinfo, pi, eiinfo->group, eiinfo->severity, *eiinfo->hf_info.p_id, TRUE, format, ap);
570         va_end(ap);
571 }
572
573 /* Helper function for expert_add_expert() to work around compiler's special needs on ARM */
574 static inline proto_item *
575 proto_tree_add_expert_internal(proto_tree *tree, packet_info *pinfo, expert_field *expindex,
576                 tvbuff_t *tvb, gint start, gint length, ...)
577 {
578         expert_field_info *eiinfo;
579         proto_item        *ti;
580         va_list            unused;
581
582         /* Look up the item */
583         EXPERT_REGISTRAR_GET_NTH(expindex->ei, eiinfo);
584
585         ti = proto_tree_add_text(tree, tvb, start, length, "%s", eiinfo->summary);
586         va_start(unused, length);
587         expert_set_info_vformat(pinfo, ti, eiinfo->group, eiinfo->severity, *eiinfo->hf_info.p_id, FALSE, eiinfo->summary, unused);
588         va_end(unused);
589         return ti;
590 }
591
592 proto_item *
593 proto_tree_add_expert(proto_tree *tree, packet_info *pinfo, expert_field *expindex,
594                 tvbuff_t *tvb, gint start, gint length)
595 {
596         return proto_tree_add_expert_internal(tree, pinfo, expindex, tvb, start, length);
597 }
598
599 proto_item *
600 proto_tree_add_expert_format(proto_tree *tree, packet_info *pinfo, expert_field *expindex,
601                 tvbuff_t *tvb, gint start, gint length, const char *format, ...)
602 {
603         va_list            ap;
604         expert_field_info *eiinfo;
605         proto_item        *ti;
606
607         /* Look up the item */
608         EXPERT_REGISTRAR_GET_NTH(expindex->ei, eiinfo);
609
610         va_start(ap, format);
611         ti = proto_tree_add_text_valist(tree, tvb, start, length, format, ap);
612         va_end(ap);
613
614         va_start(ap, format);
615         expert_set_info_vformat(pinfo, ti, eiinfo->group, eiinfo->severity, *eiinfo->hf_info.p_id, TRUE, format, ap);
616         va_end(ap);
617
618         return ti;
619 }
620
621 /*
622  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
623  *
624  * Local variables:
625  * c-basic-offset: 8
626  * tab-width: 8
627  * indent-tabs-mode: t
628  * End:
629  *
630  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
631  * :indentSize=8:tabSize=8:noTabs=false:
632  */