Update the "Following Conversations" section to use se_alloc() instead of GMemChunks.
[obnox/wireshark/wip.git] / doc / README.developer
1 $Revision$
2 $Date$
3 $Author$
4 Tabsize: 4
5
6 This file is a HOWTO for Wireshark developers. It describes how to start coding
7 a Wireshark protocol dissector and the use of some of the important functions
8 and variables.
9
10 This file is compiled to give in depth information on Wireshark.
11 It is by no means all inclusive and complete. Please feel free to send
12 remarks and patches to the developer mailing list.
13
14 0. Prerequisites.
15
16 Before starting to develop a new dissector, a "running" Wireshark build
17 environment is required - there's no such thing as a standalone "dissector
18 build toolkit".
19
20 How to setup such an environment is platform dependent; detailed information
21 about these steps can be found in the "Developer's Guide" (available from:
22 http://www.wireshark.org) and in the INSTALL and README files of the sources
23 root dir.
24
25 0.1. General README files.
26
27 You'll find additional information in the following README files:
28
29 - README.capture        - the capture engine internals
30 - README.design         - Wireshark software design - incomplete
31 - README.developer      - this file
32 - README.display_filter - Display Filter Engine
33 - README.idl2wrs        - CORBA IDL converter
34 - README.packaging      - how to distribute a software package containing WS
35 - README.regression     - regression testing of WS and TS
36 - README.stats_tree     - a tree statistics counting specific packets
37 - README.tapping        - "tap" a dissector to get protocol specific events
38 - README.xml-output     - how to work with the PDML exported output
39 - wiretap/README.developer - how to add additional capture file types to
40   Wiretap
41
42 0.2. Dissector related README files.
43
44 You'll find additional dissector related information in the following README
45 files:
46
47 - README.binarytrees    - fast access to large data collections
48 - README.heuristic      - what are heuristic dissectors and how to write them
49 - README.malloc         - how to obtain "memory leak free" memory
50 - README.plugins        - how to "pluginize" a dissector
51 - README.python         - writing a dissector in PYTHON.
52 - README.request_response_tracking - how to track req./resp. times and such
53
54 0.3 Contributors
55
56 James Coe <jammer[AT]cin.net>
57 Gilbert Ramirez <gram[AT]alumni.rice.edu>
58 Jeff Foster <jfoste[AT]woodward.com>
59 Olivier Abad <oabad[AT]cybercable.fr>
60 Laurent Deniel <laurent.deniel[AT]free.fr>
61 Gerald Combs <gerald[AT]wireshark.org>
62 Guy Harris <guy[AT]alum.mit.edu>
63 Ulf Lamping <ulf.lamping[AT]web.de>
64
65 1. Setting up your protocol dissector code.
66
67 This section provides skeleton code for a protocol dissector. It also explains
68 the basic functions needed to enter values in the traffic summary columns,
69 add to the protocol tree, and work with registered header fields.
70
71 1.1 Code style.
72
73 1.1.1 Portability.
74
75 Wireshark runs on many platforms, and can be compiled with a number of
76 different compilers; here are some rules for writing code that will work
77 on multiple platforms.
78
79 Don't use C++-style comments (comments beginning with "//" and running
80 to the end of the line); Wireshark's dissectors are written in C, and
81 thus run through C rather than C++ compilers, and not all C compilers
82 support C++-style comments (GCC does, but IBM's C compiler for AIX, for
83 example, doesn't do so by default).
84
85 In general, don't use C99 features since some C compilers used to compile
86 Wireshark don't support C99 (E.G. Microsoft C).
87
88 Don't initialize variables in their declaration with non-constant
89 values. Not all compilers support this. E.g. don't use
90         guint32 i = somearray[2];
91 use
92         guint32 i;
93         i = somearray[2];
94 instead.
95
96 Don't use zero-length arrays; not all compilers support them.  If an
97 array would have no members, just leave it out.
98
99 Don't declare variables in the middle of executable code; not all C
100 compilers support that.  Variables should be declared outside a
101 function, or at the beginning of a function or compound statement.
102
103 Don't use anonymous unions; not all compilers support them.
104 Example:
105
106         typedef struct foo {
107           guint32 foo;
108           union {
109             guint32 foo_l;
110             guint16 foo_s;
111           } u;  /* have a name here */
112         } foo_t;
113
114 Don't use "uchar", "u_char", "ushort", "u_short", "uint", "u_int",
115 "ulong", "u_long" or "boolean"; they aren't defined on all platforms.
116 If you want an 8-bit unsigned quantity, use "guint8"; if you want an
117 8-bit character value with the 8th bit not interpreted as a sign bit,
118 use "guchar"; if you want a 16-bit unsigned quantity, use "guint16";
119 if you want a 32-bit unsigned quantity, use "guint32"; and if you want
120 an "int-sized" unsigned quantity, use "guint"; if you want a boolean,
121 use "gboolean".  Use "%d", "%u", "%x", and "%o" to print those types;
122 don't use "%ld", "%lu", "%lx", or "%lo", as longs are 64 bits long on
123 many platforms, but "guint32" is 32 bits long.
124
125 Don't use "long" to mean "signed 32-bit integer", and don't use
126 "unsigned long" to mean "unsigned 32-bit integer"; "long"s are 64 bits
127 long on many platforms.  Use "gint32" for signed 32-bit integers and use
128 "guint32" for unsigned 32-bit integers.
129
130 Don't use "long" to mean "signed 64-bit integer" and don't use "unsigned
131 long" to mean "unsigned 64-bit integer"; "long"s are 32 bits long on
132 many other platforms.  Don't use "long long" or "unsigned long long",
133 either, as not all platforms support them; use "gint64" or "guint64",
134 which will be defined as the appropriate types for 64-bit signed and
135 unsigned integers.
136
137 On LLP64 data model systems (notably 64-bit Windows), "int" and "long"
138 are 32 bits while "size_t" and "ptrdiff_t" are 64 bits. This means that
139 the following will generate a compiler warning:
140
141         int i;
142         i = strlen("hello, sailor");  /* Compiler warning */
143
144 Normally, you'd just make "i" a size_t. However, many GLib and Wireshark
145 functions won't accept a size_t on LLP64:
146
147         size_t i;
148         char greeting[] = "hello, sailor";
149         guint byte_after_greet;
150
151         i = strlen(greeting);
152         byte_after_greet = tvb_get_guint8(tvb, i); /* Compiler warning */
153
154 Try to use the appropriate data type when you can. When you can't, you
155 will have to cast to a compatible data type, e.g.
156
157         size_t i;
158         char greeting[] = "hello, sailor";
159         guint byte_after_greet;
160
161         i = strlen(greeting);
162         byte_after_greet = tvb_get_guint8(tvb, (gint) i); /* OK */
163
164 or
165
166         gint i;
167         char greeting[] = "hello, sailor";
168         guint byte_after_greet;
169
170         i = (gint) strlen(greeting);
171         byte_after_greet = tvb_get_guint8(tvb, i); /* OK */
172
173 See http://www.unix.org/version2/whatsnew/lp64_wp.html for more
174 information on the sizes of common types in different data models.
175
176 When printing or displaying the values of 64-bit integral data types,
177 don't use "%lld", "%llu", "%llx", or "%llo" - not all platforms
178 support "%ll" for printing 64-bit integral data types.  Instead, for
179 GLib routines, and routines that use them, such as all the routines in
180 Wireshark that take format arguments, use G_GINT64_MODIFIER, for example:
181
182     proto_tree_add_text(tree, tvb, offset, 8,
183                         "Sequence Number: %" G_GINT64_MODIFIER "u",
184                         sequence_number);
185
186 When specifying an integral constant that doesn't fit in 32 bits, don't
187 use "LL" at the end of the constant - not all compilers use "LL" for
188 that.  Instead, put the constant in a call to the "G_GINT64_CONSTANT()"
189 macro, e.g.
190
191         G_GINT64_CONSTANT(11644473600U)
192
193 rather than
194
195         11644473600ULL
196
197 Don't assume that you can scan through a va_list initialized by va_start
198 more than once without closing it with va_end and re-initalizing it with
199 va_start.  This applies even if you're not scanning through it yourself,
200 but are calling a routine that scans through it, such as vfprintf() or
201 one of the routines in Wireshark that takes a format and a va_list as an
202 argument.  You must do
203
204         va_start(ap, format);
205         call_routine1(xxx, format, ap);
206         va_end(ap);
207         va_start(ap, format);
208         call_routine2(xxx, format, ap);
209         va_end(ap);
210
211 rather
212         va_start(ap, format);
213         call_routine1(xxx, format, ap);
214         call_routine2(xxx, format, ap);
215         va_end(ap);
216
217 Don't use a label without a statement following it.  For example,
218 something such as
219
220         if (...) {
221
222                 ...
223
224         done:
225         }
226
227 will not work with all compilers - you have to do
228
229         if (...) {
230
231                 ...
232
233         done:
234                 ;
235         }
236
237 with some statement, even if it's a null statement, after the label.
238
239 Don't use "bzero()", "bcopy()", or "bcmp()"; instead, use the ANSI C
240 routines
241
242         "memset()" (with zero as the second argument, so that it sets
243         all the bytes to zero);
244
245         "memcpy()" or "memmove()" (note that the first and second
246         arguments to "memcpy()" are in the reverse order to the
247         arguments to "bcopy()"; note also that "bcopy()" is typically
248         guaranteed to work on overlapping memory regions, while
249         "memcpy()" isn't, so if you may be copying from one region to a
250         region that overlaps it, use "memmove()", not "memcpy()" - but
251         "memcpy()" might be faster as a result of not guaranteeing
252         correct operation on overlapping memory regions);
253
254         and "memcmp()" (note that "memcmp()" returns 0, 1, or -1, doing
255         an ordered comparison, rather than just returning 0 for "equal"
256         and 1 for "not equal", as "bcmp()" does).
257
258 Not all platforms necessarily have "bzero()"/"bcopy()"/"bcmp()", and
259 those that do might not declare them in the header file on which they're
260 declared on your platform.
261
262 Don't use "index()" or "rindex()"; instead, use the ANSI C equivalents,
263 "strchr()" and "strrchr()".  Not all platforms necessarily have
264 "index()" or "rindex()", and those that do might not declare them in the
265 header file on which they're declared on your platform.
266
267 Don't fetch data from packets by getting a pointer to data in the packet
268 with "tvb_get_ptr()", casting that pointer to a pointer to a structure,
269 and dereferencing that pointer.  That pointer won't necessarily be aligned
270 on the proper boundary, which can cause crashes on some platforms (even
271 if it doesn't crash on an x86-based PC); furthermore, the data in a
272 packet is not necessarily in the byte order of the machine on which
273 Wireshark is running.  Use the tvbuff routines to extract individual
274 items from the packet, or use "proto_tree_add_item()" and let it extract
275 the items for you.
276
277 Don't use structures that overlay packet data, or into which you copy
278 packet data; the C programming language does not guarantee any
279 particular alignment of fields within a structure, and even the
280 extensions that try to guarantee that are compiler-specific and not
281 necessarily supported by all compilers used to build Wireshark.  Using
282 bitfields in those structures is even worse; the order of bitfields
283 is not guaranteed.
284
285 Don't use "ntohs()", "ntohl()", "htons()", or "htonl()"; the header
286 files required to define or declare them differ between platforms, and
287 you might be able to get away with not including the appropriate header
288 file on your platform but that might not work on other platforms.
289 Instead, use "g_ntohs()", "g_ntohl()", "g_htons()", and "g_htonl()";
290 those are declared by <glib.h>, and you'll need to include that anyway,
291 as Wireshark header files that all dissectors must include use stuff from
292 <glib.h>.
293
294 Don't fetch a little-endian value using "tvb_get_ntohs() or
295 "tvb_get_ntohl()" and then using "g_ntohs()", "g_htons()", "g_ntohl()",
296 or "g_htonl()" on the resulting value - the g_ routines in question
297 convert between network byte order (big-endian) and *host* byte order,
298 not *little-endian* byte order; not all machines on which Wireshark runs
299 are little-endian, even though PCs are.  Fetch those values using
300 "tvb_get_letohs()" and "tvb_get_letohl()".
301
302 Don't put a comma after the last element of an enum - some compilers may
303 either warn about it (producing extra noise) or refuse to accept it.
304
305 Don't include <unistd.h> without protecting it with
306
307         #ifdef HAVE_UNISTD_H
308
309                 ...
310
311         #endif
312
313 and, if you're including it to get routines such as "open()", "close()",
314 "read()", and "write()" declared, also include <io.h> if present:
315
316         #ifdef HAVE_IO_H
317         #include <io.h>
318         #endif
319
320 in order to declare the Windows C library routines "_open()",
321 "_close()", "_read()", and "_write()".  Your file must include <glib.h>
322 - which many of the Wireshark header files include, so you might not have
323 to include it explicitly - in order to get "open()", "close()",
324 "read()", "write()", etc. mapped to "_open()", "_close()", "_read()",
325 "_write()", etc..
326
327 Do not use "open()", "rename()", "mkdir()", "stat()", "unlink()", "remove()",
328 "fopen()", "freopen()" directly.  Instead use "ws_open()", "ws_rename()",
329 "ws_mkdir()", "ws_stat()", "ws_unlink()", "ws_remove()", "ws_fopen()",
330 "ws_freopen()": these wrapper functions change the path and file name from
331 UTF8 to UTF16 on Windows allowing the functions to work correctly when the
332 path or file name contain non-ASCII characters.
333
334 When opening a file with "ws_fopen()", "ws_freopen()", or "ws_fdopen()", if
335 the file contains ASCII text, use "r", "w", "a", and so on as the open mode
336 - but if it contains binary data, use "rb", "wb", and so on.  On
337 Windows, if a file is opened in a text mode, writing a byte with the
338 value of octal 12 (newline) to the file causes two bytes, one with the
339 value octal 15 (carriage return) and one with the value octal 12, to be
340 written to the file, and causes bytes with the value octal 15 to be
341 discarded when reading the file (to translate between C's UNIX-style
342 lines that end with newline and Windows' DEC-style lines that end with
343 carriage return/line feed).
344
345 In addition, that also means that when opening or creating a binary
346 file, you must use "ws_open()" (with O_CREAT and possibly O_TRUNC if the
347 file is to be created if it doesn't exist), and OR in the O_BINARY flag.
348 That flag is not present on most, if not all, UNIX systems, so you must
349 also do
350
351         #ifndef O_BINARY
352         #define O_BINARY        0
353         #endif
354
355 to properly define it for UNIX (it's not necessary on UNIX).
356
357 Don't use forward declarations of static arrays without a specified size
358 in a fashion such as this:
359
360         static const value_string foo_vals[];
361
362                 ...
363
364         static const value_string foo_vals[] = {
365                 { 0,            "Red" },
366                 { 1,            "Green" },
367                 { 2,            "Blue" },
368                 { 0,            NULL }
369         };
370
371 as some compilers will reject the first of those statements.  Instead,
372 initialize the array at the point at which it's first declared, so that
373 the size is known.
374
375 Don't put a comma after the last tuple of an initializer of an array.
376
377 For #define names and enum member names, prefix the names with a tag so
378 as to avoid collisions with other names - this might be more of an issue
379 on Windows, as it appears to #define names such as DELETE and
380 OPTIONAL.
381
382 Don't use the "numbered argument" feature that many UNIX printf's
383 implement, e.g.:
384
385         g_snprintf(add_string, 30, " - (%1$d) (0x%1$04x)", value);
386
387 as not all UNIX printf's implement it, and Windows printf doesn't appear
388 to implement it.  Use something like
389
390         g_snprintf(add_string, 30, " - (%d) (0x%04x)", value, value);
391
392 instead.
393
394 Don't use "variadic macros", such as
395
396         #define DBG(format, args...)    fprintf(stderr, format, ## args)
397
398 as not all C compilers support them.  Use macros that take a fixed
399 number of arguments, such as
400
401         #define DBG0(format)            fprintf(stderr, format)
402         #define DBG1(format, arg1)      fprintf(stderr, format, arg1)
403         #define DBG2(format, arg1, arg2) fprintf(stderr, format, arg1, arg2)
404
405                 ...
406
407 or something such as
408
409         #define DBG(args)               printf args
410
411 Don't use
412
413         case N ... M:
414
415 as that's not supported by all compilers.
416
417 snprintf() -> g_snprintf()
418 snprintf() is not available on all platforms, so it's a good idea to use the
419 g_snprintf() function declared by <glib.h> instead.
420
421 tmpnam() -> mkstemp()
422 tmpnam is insecure and should not be used any more. Wireshark brings its
423 own mkstemp implementation for use on platforms that lack mkstemp.
424 Note: mkstemp does not accept NULL as a parameter.
425
426 The pointer returned by a call to "tvb_get_ptr()" is not guaranteed to be
427 aligned on any particular byte boundary; this means that you cannot
428 safely cast it to any data type other than a pointer to "char",
429 "unsigned char", "guint8", or other one-byte data types.  You cannot,
430 for example, safely cast it to a pointer to a structure, and then access
431 the structure members directly; on some systems, unaligned accesses to
432 integral data types larger than 1 byte, and floating-point data types,
433 cause a trap, which will, at best, result in the OS slowly performing an
434 unaligned access for you, and will, on at least some platforms, cause
435 the program to be terminated.
436
437 Wireshark supports platforms with GLib 2.4[.x]/GTK+ 2.4[.x] or newer.
438 If a Glib/GTK+ mechanism is available only in Glib/GTK+ versions
439 newer than 2.4/2.4 then use "#if GTK_CHECK_VERSION(...)" to conditionally
440 compile code using that mechanism.
441
442 When different code must be used on UN*X and Win32, use a #if or #ifdef
443 that tests _WIN32, not WIN32.  Try to write code portably whenever
444 possible, however; note that there are some routines in Wireshark with
445 platform-dependent implementations and platform-independent APIs, such
446 as the routines in epan/filesystem.c, allowing the code that calls it to
447 be written portably without #ifdefs.
448
449 1.1.2 String handling
450
451 Do not use functions such as strcat() or strcpy().
452 A lot of work has been done to remove the existing calls to these functions and
453 we do not want any new callers of these functions.
454
455 Instead use g_snprintf() since that function will if used correctly prevent
456 buffer overflows for large strings.
457
458 When using a buffer to create a string, do not use a buffer stored on the stack.
459 I.e. do not use a buffer declared as
460
461    char buffer[1024];
462
463 instead allocate a buffer dynamically using the string-specific or plain emem
464 routines (see README.malloc) such as
465
466    emem_strbuf_t *strbuf;
467    strbuf = ep_strbuf_new_label("");
468    ep_strbuf_append_printf(strbuf, ...
469
470 or
471
472    char *buffer=NULL;
473    ...
474    #define MAX_BUFFER 1024
475    buffer=ep_alloc(MAX_BUFFER);
476    buffer[0]='\0';
477    ...
478    g_snprintf(buffer, MAX_BUFFER, ...
479
480 This avoids the stack from being corrupted in case there is a bug in your code
481 that accidentally writes beyond the end of the buffer.
482
483
484 If you write a routine that will create and return a pointer to a filled in
485 string and if that buffer will not be further processed or appended to after
486 the routine returns (except being added to the proto tree),
487 do not preallocate the buffer to fill in and pass as a parameter instead
488 pass a pointer to a pointer to the function and return a pointer to an
489 emem allocated buffer that will be automatically freed. (see README.malloc)
490
491 I.e. do not write code such as
492   static void
493   foo_to_str(char *string, ... ){
494      <fill in string>
495   }
496   ...
497      char buffer[1024];
498      ...
499      foo_to_str(buffer, ...
500      proto_tree_add_text(... buffer ...
501
502 instead write the code as
503   static void
504   foo_to_str(char **buffer, ...
505     #define MAX_BUFFER x
506     *buffer=ep_alloc(MAX_BUFFER);
507     <fill in *buffer>
508   }
509   ...
510     char *buffer;
511     ...
512     foo_to_str(&buffer, ...
513     proto_tree_add_text(... *buffer ...
514
515 Use ep_ allocated buffers. They are very fast and nice. These buffers are all
516 automatically free()d when the dissection of the current packet ends so you
517 don't have to worry about free()ing them explicitly in order to not leak memory.
518 Please read README.malloc.
519
520 Don't use non-ASCII characters in source files; not all compiler
521 environments will be using the same encoding for non-ASCII characters,
522 and at least one compiler (Microsoft's Visual C) will, in environments
523 with double-byte character encodings, such as many Asian environments,
524 fail if it sees a byte sequence in a source file that doesn't correspond
525 to a valid character.  This causes source files using either an ISO
526 8859/n single-byte character encoding or UTF-8 to fail to compile.  Even
527 if the compiler doesn't fail, there is no guarantee that the compiler,
528 or a developer's text editor, will interpret the characters the way you
529 intend them to be interpreted.
530
531 1.1.3 Robustness.
532
533 Wireshark is not guaranteed to read only network traces that contain correctly-
534 formed packets. Wireshark is commonly used to track down networking
535 problems, and the problems might be due to a buggy protocol implementation
536 sending out bad packets.
537
538 Therefore, protocol dissectors not only have to be able to handle
539 correctly-formed packets without, for example, crashing or looping
540 infinitely, they also have to be able to handle *incorrectly*-formed
541 packets without crashing or looping infinitely.
542
543 Here are some suggestions for making dissectors more robust in the face
544 of incorrectly-formed packets:
545
546 Do *NOT* use "g_assert()" or "g_assert_not_reached()" in dissectors.
547 *NO* value in a packet's data should be considered "wrong" in the sense
548 that it's a problem with the dissector if found; if it cannot do
549 anything else with a particular value from a packet's data, the
550 dissector should put into the protocol tree an indication that the
551 value is invalid, and should return.  The "expert" mechanism should be
552 used for that purpose.
553
554 If there is a case where you are checking not for an invalid data item
555 in the packet, but for a bug in the dissector (for example, an
556 assumption being made at a particular point in the code about the
557 internal state of the dissector), use the DISSECTOR_ASSERT macro for
558 that purpose; this will put into the protocol tree an indication that
559 the dissector has a bug in it, and will not crash the application.
560
561 If you are allocating a chunk of memory to contain data from a packet,
562 or to contain information derived from data in a packet, and the size of
563 the chunk of memory is derived from a size field in the packet, make
564 sure all the data is present in the packet before allocating the buffer.
565 Doing so means that:
566
567         1) Wireshark won't leak that chunk of memory if an attempt to
568            fetch data not present in the packet throws an exception.
569
570 and
571
572         2) it won't crash trying to allocate an absurdly-large chunk of
573            memory if the size field has a bogus large value.
574
575 If you're fetching into such a chunk of memory a string from the buffer,
576 and the string has a specified size, you can use "tvb_get_*_string()",
577 which will check whether the entire string is present before allocating
578 a buffer for the string, and will also put a trailing '\0' at the end of
579 the buffer.
580
581 If you're fetching into such a chunk of memory a 2-byte Unicode string
582 from the buffer, and the string has a specified size, you can use
583 "tvb_get_ephemeral_faked_unicode()", which will check whether the entire
584 string is present before allocating a buffer for the string, and will also
585 put a trailing '\0' at the end of the buffer.  The resulting string will be
586 a sequence of single-byte characters; the only Unicode characters that
587 will be handled correctly are those in the ASCII range.  (Wireshark's
588 ability to handle non-ASCII strings is limited; it needs to be
589 improved.)
590
591 If you're fetching into such a chunk of memory a sequence of bytes from
592 the buffer, and the sequence has a specified size, you can use
593 "tvb_memdup()", which will check whether the entire sequence is present
594 before allocating a buffer for it.
595
596 Otherwise, you can check whether the data is present by using
597 "tvb_ensure_bytes_exist()" or by getting a pointer to the data by using
598 "tvb_get_ptr()", although note that there might be problems with using
599 the pointer from "tvb_get_ptr()" (see the item on this in the
600 Portability section above, and the next item below).
601
602 Note also that you should only fetch string data into a fixed-length
603 buffer if the code ensures that no more bytes than will fit into the
604 buffer are fetched ("the protocol ensures" isn't good enough, as
605 protocol specifications can't ensure only packets that conform to the
606 specification will be transmitted or that only packets for the protocol
607 in question will be interpreted as packets for that protocol by
608 Wireshark).  If there's no maximum length of string data to be fetched,
609 routines such as "tvb_get_*_string()" are safer, as they allocate a buffer
610 large enough to hold the string.  (Note that some variants of this call
611 require you to free the string once you're finished with it.)
612
613 If you have gotten a pointer using "tvb_get_ptr()", you must make sure
614 that you do not refer to any data past the length passed as the last
615 argument to "tvb_get_ptr()"; while the various "tvb_get" routines
616 perform bounds checking and throw an exception if you refer to data not
617 available in the tvbuff, direct references through a pointer gotten from
618 "tvb_get_ptr()" do not do any bounds checking.
619
620 If you have a loop that dissects a sequence of items, each of which has
621 a length field, with the offset in the tvbuff advanced by the length of
622 the item, then, if the length field is the total length of the item, and
623 thus can be zero, you *MUST* check for a zero-length item and abort the
624 loop if you see one.  Otherwise, a zero-length item could cause the
625 dissector to loop infinitely.  You should also check that the offset,
626 after having the length added to it, is greater than the offset before
627 the length was added to it, if the length field is greater than 24 bits
628 long, so that, if the length value is *very* large and adding it to the
629 offset causes an overflow, that overflow is detected.
630
631 If you have a
632
633         for (i = {start}; i < {end}; i++)
634
635 loop, make sure that the type of the loop index variable is large enough
636 to hold the maximum {end} value plus 1; otherwise, the loop index
637 variable can overflow before it ever reaches its maximum value.  In
638 particular, be very careful when using gint8, guint8, gint16, or guint16
639 variables as loop indices; you almost always want to use an "int"/"gint"
640 or "unsigned int"/"guint" as the loop index rather than a shorter type.
641
642 If you are fetching a length field from the buffer, corresponding to the
643 length of a portion of the packet, and subtracting from that length a
644 value corresponding to the length of, for example, a header in the
645 packet portion in question, *ALWAYS* check that the value of the length
646 field is greater than or equal to the length you're subtracting from it,
647 and report an error in the packet and stop dissecting the packet if it's
648 less than the length you're subtracting from it.  Otherwise, the
649 resulting length value will be negative, which will either cause errors
650 in the dissector or routines called by the dissector, or, if the value
651 is interpreted as an unsigned integer, will cause the value to be
652 interpreted as a very large positive value.
653
654 Any tvbuff offset that is added to as processing is done on a packet
655 should be stored in a 32-bit variable, such as an "int"; if you store it
656 in an 8-bit or 16-bit variable, you run the risk of the variable
657 overflowing.
658
659 sprintf() -> g_snprintf()
660 Prevent yourself from using the sprintf() function, as it does not test the
661 length of the given output buffer and might be writing into unintended memory
662 areas. This function is one of the main causes of security problems like buffer
663 exploits and many other bugs that are very hard to find. It's much better to
664 use the g_snprintf() function declared by <glib.h> instead.
665
666 You should test your dissector against incorrectly-formed packets.  This
667 can be done using the randpkt and editcap utilities that come with the
668 Wireshark distribution.  Testing using randpkt can be done by generating
669 output at the same layer as your protocol, and forcing Wireshark/TShark
670 to decode it as your protocol, e.g. if your protocol sits on top of UDP:
671
672     randpkt -c 50000 -t dns randpkt.pcap
673     tshark -nVr randpkt.pcap -d udp.port==53,<myproto>
674
675 Testing using editcap can be done using preexisting capture files and the
676 "-E" flag, which introduces errors in a capture file.  E.g.:
677
678     editcap -E 0.03 infile.pcap outfile.pcap
679     tshark -nVr outfile.pcap
680
681 The script fuzz-test.sh is available to help automate these tests.
682
683 1.1.4 Name convention.
684
685 Wireshark uses the underscore_convention rather than the InterCapConvention for
686 function names, so new code should probably use underscores rather than
687 intercaps for functions and variable names. This is especially important if you
688 are writing code that will be called from outside your code.  We are just
689 trying to keep things consistent for other developers.
690
691 1.1.5 White space convention.
692
693 Avoid using tab expansions different from 8 column widths, as not all
694 text editors in use by the developers support this. For a detailed
695 discussion of tabs, spaces, and indentation, see
696
697     http://www.jwz.org/doc/tabs-vs-spaces.html
698
699 When creating a new file, you are free to choose an indentation logic.
700 Most of the files in Wireshark tend to use 2-space or 4-space
701 indentation. You are encouraged to write a short comment on the
702 indentation logic at the beginning of this new file, especially if
703 you're using non-mod-8 tabs.  The tabs-vs-spaces document above provides
704 examples of Emacs and vi modelines for this purpose.
705
706 When editing an existing file, try following the existing indentation
707 logic and even if it very tempting, never ever use a restyler/reindenter
708 utility on an existing file.  If you run across wildly varying
709 indentation styles within the same file, it might be helpful to send a
710 note to wireshark-dev for guidance.
711
712 1.1.6 Compiler warnings
713
714 You should write code that is free of compiler warnings. Such warnings will
715 often indicate questionable code and sometimes even real bugs, so it's best
716 to avoid warnings at all.
717
718 The compiler flags in the Makefiles are set to "treat warnings as errors",
719 so your code won't even compile when warnings occur.
720
721 1.2 Skeleton code.
722
723 Wireshark requires certain things when setting up a protocol dissector.
724 Below is skeleton code for a dissector that you can copy to a file and
725 fill in.  Your dissector should follow the naming convention of packet-
726 followed by the abbreviated name for the protocol.  It is recommended
727 that where possible you keep to the IANA abbreviated name for the
728 protocol, if there is one, or a commonly-used abbreviation for the
729 protocol, if any.
730
731 Usually, you will put your newly created dissector file into the directory
732 epan/dissectors, just like all the other packet-....c files already in there.
733
734 Also, please add your dissector file to the corresponding makefiles,
735 described in section "1.9 Editing Makefile.common and CMakeLists.txt
736 to add your dissector" below.
737
738 Dissectors that use the dissector registration to register with a lower level
739 dissector don't need to define a prototype in the .h file. For other
740 dissectors the main dissector routine should have a prototype in a header
741 file whose name is "packet-", followed by the abbreviated name for the
742 protocol, followed by ".h"; any dissector file that calls your dissector
743 should be changed to include that file.
744
745 You may not need to include all the headers listed in the skeleton
746 below, and you may need to include additional headers.  For example, the
747 code inside
748
749         #ifdef HAVE_LIBPCRE
750
751                 ...
752
753         #endif
754
755 is needed only if you are using a function from libpcre, e.g. the
756 "pcre_compile()" function.
757
758 The stdio.h, stdlib.h and string.h header files should be included only as needed.
759
760
761 The "$Id$" in the comment will be updated by Subversion when the file is
762 checked in.
763
764 When creating a new file, it is fine to just write "$Id$" as Subversion will
765 automatically fill in the identifier at the time the file will be added to the
766 SVN repository (committed).
767
768 ------------------------------------Cut here------------------------------------
769 /* packet-PROTOABBREV.c
770  * Routines for PROTONAME dissection
771  * Copyright 201x, YOUR_NAME <YOUR_EMAIL_ADDRESS>
772  *
773  * $Id$
774  *
775  * Wireshark - Network traffic analyzer
776  * By Gerald Combs <gerald@wireshark.org>
777  * Copyright 1998 Gerald Combs
778  *
779  * Copied from WHATEVER_FILE_YOU_USED (where "WHATEVER_FILE_YOU_USED"
780  * is a dissector file; if you just copied this from README.developer,
781  * don't bother with the "Copied from" - you don't even need to put
782  * in a "Copied from" if you copied an existing dissector, especially
783  * if the bulk of the code in the new dissector is your code)
784  *
785  * This program is free software; you can redistribute it and/or modify
786  * it under the terms of the GNU General Public License as published by
787  * the Free Software Foundation; either version 2 of the License, or
788  * (at your option) any later version.
789  *
790  * This program is distributed in the hope that it will be useful,
791  * but WITHOUT ANY WARRANTY; without even the implied warranty of
792  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
793  * GNU General Public License for more details.
794  *
795  * You should have received a copy of the GNU General Public License along
796  * with this program; if not, write to the Free Software Foundation, Inc.,
797  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
798  */
799
800 #ifdef HAVE_CONFIG_H
801 # include "config.h"
802 #endif
803
804 #if 0
805 /* Include only as needed */
806 #include <stdio.h>
807 #include <stdlib.h>
808 #include <string.h>
809 #endif
810
811 #include <glib.h>
812
813 #include <epan/packet.h>
814 #include <epan/prefs.h>
815
816 /* IF PROTO exposes code to other dissectors, then it must be exported
817    in a header file. If not, a header file is not needed at all. */
818 #include "packet-PROTOABBREV.h"
819
820 /* Forward declaration we need below (if using proto_reg_handoff...
821    as a prefs callback)       */
822 void proto_reg_handoff_PROTOABBREV(void);
823
824 /* Initialize the protocol and registered fields */
825 static int proto_PROTOABBREV = -1;
826 static int hf_PROTOABBREV_FIELDABBREV = -1;
827
828 /* Global sample preference ("controls" display of numbers) */
829 static gboolean gPREF_HEX = FALSE;
830 /* Global sample port pref */
831 static guint gPORT_PREF = 1234;
832
833 /* Initialize the subtree pointers */
834 static gint ett_PROTOABBREV = -1;
835
836 /* Code to actually dissect the packets */
837 static int
838 dissect_PROTOABBREV(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
839 {
840
841 /* Set up structures needed to add the protocol subtree and manage it */
842         proto_item *ti;
843         proto_tree *PROTOABBREV_tree;
844
845 /*  First, if at all possible, do some heuristics to check if the packet cannot
846  *  possibly belong to your protocol.  This is especially important for
847  *  protocols directly on top of TCP or UDP where port collisions are
848  *  common place (e.g., even though your protocol uses a well known port,
849  *  someone else may set up, for example, a web server on that port which,
850  *  if someone analyzed that web server's traffic in Wireshark, would result
851  *  in Wireshark handing an HTTP packet to your dissector).  For example:
852  */
853         /* Check that there's enough data */
854         if (tvb_length(tvb) < /* your protocol's smallest packet size */)
855                 return 0;
856
857         /* Get some values from the packet header, probably using tvb_get_*() */
858         if ( /* these values are not possible in PROTONAME */ )
859                 /*  This packet does not appear to belong to PROTONAME.
860                  *  Return 0 to give another dissector a chance to dissect it.
861                  */
862                 return 0;
863
864 /* Make entries in Protocol column and Info column on summary display */
865         col_set_str(pinfo->cinfo, COL_PROTOCOL, "PROTOABBREV");
866
867 /* This field shows up as the "Info" column in the display; you should use
868    it, if possible, to summarize what's in the packet, so that a user looking
869    at the list of packets can tell what type of packet it is. See section 1.5
870    for more information.
871
872    If you are setting the column to a constant string, use "col_set_str()",
873    as it's more efficient than the other "col_set_XXX()" calls.
874
875    If you're setting it to a string you've constructed, or will be
876    appending to the column later, use "col_add_str()".
877
878    "col_add_fstr()" can be used instead of "col_add_str()"; it takes
879    "printf()"-like arguments.  Don't use "col_add_fstr()" with a format
880    string of "%s" - just use "col_add_str()" or "col_set_str()", as it's
881    more efficient than "col_add_fstr()".
882
883    If you will be fetching any data from the packet before filling in
884    the Info column, clear that column first, in case the calls to fetch
885    data from the packet throw an exception because they're fetching data
886    past the end of the packet, so that the Info column doesn't have data
887    left over from the previous dissector; do
888
889         col_clear(pinfo->cinfo, COL_INFO);
890
891    */
892
893         col_set_str(pinfo->cinfo, COL_INFO, "XXX Request");
894
895 /* A protocol dissector may be called in 2 different ways - with, or
896    without a non-null "tree" argument.
897
898    If the proto_tree argument is null, Wireshark does not need to use
899    the protocol tree information from your dissector, and therefore is
900    passing the dissector a null "tree" argument so that it doesn't
901    need to do work necessary to build the protocol tree.
902
903    In the interest of speed, if "tree" is NULL, avoid building a
904    protocol tree and adding stuff to it, or even looking at any packet
905    data needed only if you're building the protocol tree, if possible.
906
907    Note, however, that you must fill in column information, create
908    conversations, reassemble packets, build any other persistent state
909    needed for dissection, and call subdissectors regardless of whether
910    "tree" is NULL or not.  This might be inconvenient to do without
911    doing most of the dissection work; the routines for adding items to
912    the protocol tree can be passed a null protocol tree pointer, in
913    which case they'll return a null item pointer, and
914    "proto_item_add_subtree()" returns a null tree pointer if passed a
915    null item pointer, so, if you're careful not to dereference any null
916    tree or item pointers, you can accomplish this by doing all the
917    dissection work.  This might not be as efficient as skipping that
918    work if you're not building a protocol tree, but if the code would
919    have a lot of tests whether "tree" is null if you skipped that work,
920    you might still be better off just doing all that work regardless of
921    whether "tree" is null or not.
922
923    Note also that there is no guarantee, the first time the dissector is
924    called, whether "tree" will be null or not; your dissector must work
925    correctly, building or updating whatever state information is
926    necessary, in either case. */
927         if (tree) {
928
929 /* NOTE: The offset and length values in the call to
930    "proto_tree_add_item()" define what data bytes to highlight in the hex
931    display window when the line in the protocol tree display
932    corresponding to that item is selected.
933
934    Supplying a length of -1 is the way to highlight all data from the
935    offset to the end of the packet. */
936
937 /* create display subtree for the protocol */
938                 ti = proto_tree_add_item(tree, proto_PROTOABBREV, tvb, 0, -1, ENC_NA);
939
940                 PROTOABBREV_tree = proto_item_add_subtree(ti, ett_PROTOABBREV);
941
942 /* add an item to the subtree, see section 1.6 for more information */
943                 proto_tree_add_item(PROTOABBREV_tree,
944                     hf_PROTOABBREV_FIELDABBREV, tvb, offset, len, ENC_xxx);
945
946
947 /* Continue adding tree items to process the packet here */
948
949
950         }
951
952 /* If this protocol has a sub-dissector call it here, see section 1.8 */
953
954 /* Return the amount of data this dissector was able to dissect */
955         return tvb_length(tvb);
956 }
957
958
959 /* Register the protocol with Wireshark */
960
961 /* this format is require because a script is used to build the C function
962    that calls all the protocol registration.
963 */
964
965 void
966 proto_register_PROTOABBREV(void)
967 {
968         module_t *PROTOABBREV_module;
969
970 /* Setup list of header fields  See Section 1.6.1 for details*/
971         static hf_register_info hf[] = {
972                 { &hf_PROTOABBREV_FIELDABBREV,
973                         { "FIELDNAME",           "PROTOABBREV.FIELDABBREV",
974                         FIELDTYPE, FIELDDISPLAY, FIELDCONVERT, BITMASK,
975                         "FIELDDESCR", HFILL }
976                 }
977         };
978
979 /* Setup protocol subtree array */
980         static gint *ett[] = {
981                 &ett_PROTOABBREV
982         };
983
984 /* Register the protocol name and description */
985         proto_PROTOABBREV = proto_register_protocol("PROTONAME",
986             "PROTOSHORTNAME", "PROTOABBREV");
987
988 /* Required function calls to register the header fields and subtrees used */
989         proto_register_field_array(proto_PROTOABBREV, hf, array_length(hf));
990         proto_register_subtree_array(ett, array_length(ett));
991
992 /* Register preferences module (See Section 2.6 for more on preferences) */
993 /* (Registration of a prefs callback is not required if there are no     */
994 /*  prefs-dependent registration functions (eg: a port pref).            */
995 /*  See proto_reg_handoff below.                                         */
996 /*  If a prefs callback is not needed, use NULL instead of               */
997 /*  proto_reg_handoff_PROTOABBREV in the following).                     */
998         PROTOABBREV_module = prefs_register_protocol(proto_PROTOABBREV,
999             proto_reg_handoff_PROTOABBREV);
1000
1001 /* Register preferences module under preferences subtree.
1002    Use this function instead of prefs_register_protocol if you want to group
1003    preferences of several protocols under one preferences subtree.
1004    Argument subtree identifies grouping tree node name, several subnodes can be
1005    specified usign slash '/' (e.g. "OSI/X.500" - protocol preferences will be
1006    accessible under Protocols->OSI->X.500-><PROTOSHORTNAME> preferences node.
1007 */
1008   PROTOABBREV_module = prefs_register_protocol_subtree(const char *subtree,
1009        proto_PROTOABBREV, proto_reg_handoff_PROTOABBREV);
1010
1011 /* Register a sample preference */
1012         prefs_register_bool_preference(PROTOABBREV_module, "show_hex",
1013              "Display numbers in Hex",
1014              "Enable to display numerical values in hexadecimal.",
1015              &gPREF_HEX);
1016
1017 /* Register a sample port preference   */
1018         prefs_register_uint_preference(PROTOABBREV_module, "tcp.port", "PROTOABBREV TCP Port",
1019              " PROTOABBREV TCP port if other than the default",
1020              10, &gPORT_PREF);
1021 }
1022
1023
1024 /* If this dissector uses sub-dissector registration add a registration routine.
1025    This exact format is required because a script is used to find these
1026    routines and create the code that calls these routines.
1027
1028    If this function is registered as a prefs callback (see prefs_register_protocol
1029    above) this function is also called by preferences whenever "Apply" is pressed;
1030    In that case, it should accommodate being called more than once.
1031
1032    This form of the reg_handoff function is used if if you perform
1033    registration functions which are dependent upon prefs. See below
1034    for a simpler form  which can be used if there are no
1035    prefs-dependent registration functions.
1036 */
1037 void
1038 proto_reg_handoff_PROTOABBREV(void)
1039 {
1040         static gboolean initialized = FALSE;
1041         static dissector_handle_t PROTOABBREV_handle;
1042         static int currentPort;
1043
1044         if (!initialized) {
1045
1046 /*  Use new_create_dissector_handle() to indicate that dissect_PROTOABBREV()
1047  *  returns the number of bytes it dissected (or 0 if it thinks the packet
1048  *  does not belong to PROTONAME).
1049  */
1050                 PROTOABBREV_handle = new_create_dissector_handle(dissect_PROTOABBREV,
1051                                                                  proto_PROTOABBREV);
1052                 initialized = TRUE;
1053         } else {
1054
1055                 /*
1056                   If you perform registration functions which are dependent upon
1057                   prefs the you should de-register everything which was associated
1058                   with the previous settings and re-register using the new prefs
1059                   settings here. In general this means you need to keep track of
1060                   the PROTOABBREV_handle and the value the preference had at the time
1061                   you registered.  The PROTOABBREV_handle value and the value of the
1062                   preference can be saved using local statics in this
1063                   function (proto_reg_handoff).
1064                 */
1065
1066                 dissector_delete("tcp.port", currentPort, PROTOABBREV_handle);
1067         }
1068
1069         currentPort = gPORT_PREF;
1070
1071         dissector_add("tcp.port", currentPort, PROTOABBREV_handle);
1072
1073 }
1074
1075 #if 0
1076 /* Simple form of proto_reg_handoff_PROTOABBREV which can be used if there are
1077    no prefs-dependent registration function calls.
1078  */
1079
1080 void
1081 proto_reg_handoff_PROTOABBREV(void)
1082 {
1083         dissector_handle_t PROTOABBREV_handle;
1084
1085 /*  Use new_create_dissector_handle() to indicate that dissect_PROTOABBREV()
1086  *  returns the number of bytes it dissected (or 0 if it thinks the packet
1087  *  does not belong to PROTONAME).
1088  */
1089         PROTOABBREV_handle = new_create_dissector_handle(dissect_PROTOABBREV,
1090                                                          proto_PROTOABBREV);
1091         dissector_add("PARENT_SUBFIELD", ID_VALUE, PROTOABBREV_handle);
1092 }
1093 #endif
1094
1095
1096 ------------------------------------Cut here------------------------------------
1097
1098 1.3 Explanation of needed substitutions in code skeleton.
1099
1100 In the above code block the following strings should be substituted with
1101 your information.
1102
1103 YOUR_NAME       Your name, of course.  You do want credit, don't you?
1104                 It's the only payment you will receive....
1105 YOUR_EMAIL_ADDRESS      Keep those cards and letters coming.
1106 WHATEVER_FILE_YOU_USED  Add this line if you are using another file as a
1107                 starting point.
1108 PROTONAME       The name of the protocol; this is displayed in the
1109                 top-level protocol tree item for that protocol.
1110 PROTOSHORTNAME  An abbreviated name for the protocol; this is displayed
1111                 in the "Preferences" dialog box if your dissector has
1112                 any preferences, in the dialog box of enabled protocols,
1113                 and in the dialog box for filter fields when constructing
1114                 a filter expression.
1115 PROTOABBREV     A name for the protocol for use in filter expressions;
1116                 it shall contain only lower-case letters, digits, and
1117                 hyphens.
1118 FIELDNAME       The displayed name for the header field.
1119 FIELDABBREV     The abbreviated name for the header field. (NO SPACES)
1120 FIELDTYPE       FT_NONE, FT_BOOLEAN, FT_UINT8, FT_UINT16, FT_UINT24,
1121                 FT_UINT32, FT_UINT64, FT_INT8, FT_INT16, FT_INT24, FT_INT32,
1122                 FT_INT64, FT_FLOAT, FT_DOUBLE, FT_ABSOLUTE_TIME,
1123                 FT_RELATIVE_TIME, FT_STRING, FT_STRINGZ, FT_EBCDIC,
1124                 FT_UINT_STRING, FT_ETHER, FT_BYTES, FT_UINT_BYTES, FT_IPv4,
1125                 FT_IPv6, FT_IPXNET, FT_FRAMENUM, FT_PROTOCOL, FT_GUID, FT_OID
1126 FIELDDISPLAY    For FT_UINT{8,16,24,32,64} and FT_INT{8,16,24,32,64):
1127
1128                 BASE_DEC, BASE_HEX, BASE_OCT, BASE_DEC_HEX, BASE_HEX_DEC,
1129                 or BASE_CUSTOM, possibly ORed with BASE_RANGE_STRING
1130
1131                 For FT_ABSOLUTE_TIME:
1132
1133                 ABSOLUTE_TIME_LOCAL, ABSOLUTE_TIME_UTC, or
1134                 ABSOLUTE_TIME_DOY_UTC
1135
1136                 For FT_BOOLEAN if BITMASK is non-zero:
1137
1138                 Number of bits in the field containing the FT_BOOLEAN
1139                 bitfield
1140
1141                 For all other types:
1142
1143                 BASE_NONE
1144 FIELDCONVERT    VALS(x), RVALS(x), TFS(x), NULL
1145 BITMASK         Usually 0x0 unless using the TFS(x) field conversion.
1146 FIELDDESCR      A brief description of the field, or NULL. [Please do not use ""].
1147 PARENT_SUBFIELD Lower level protocol field used for lookup, i.e. "tcp.port"
1148 ID_VALUE        Lower level protocol field value that identifies this protocol
1149                 For example the TCP or UDP port number
1150
1151 If, for example, PROTONAME is "Internet Bogosity Discovery Protocol",
1152 PROTOSHORTNAME would be "IBDP", and PROTOABBREV would be "ibdp".  Try to
1153 conform with IANA names.
1154
1155 1.4 The dissector and the data it receives.
1156
1157
1158 1.4.1 Header file.
1159
1160 This is only needed if the dissector doesn't use self-registration to
1161 register itself with the lower level dissector, or if the protocol dissector
1162 wants/needs to expose code to other subdissectors.
1163
1164 The dissector must be declared exactly as follows in the file
1165 packet-PROTOABBREV.h:
1166
1167 int
1168 dissect_PROTOABBREV(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
1169
1170
1171 1.4.2 Extracting data from packets.
1172
1173 NOTE: See the file /epan/tvbuff.h for more details.
1174
1175 The "tvb" argument to a dissector points to a buffer containing the raw
1176 data to be analyzed by the dissector; for example, for a protocol
1177 running atop UDP, it contains the UDP payload (but not the UDP header,
1178 or any protocol headers above it).  A tvbuffer is an opaque data
1179 structure, the internal data structures are hidden and the data must be
1180 accessed via the tvbuffer accessors.
1181
1182 The accessors are:
1183
1184 Bit accessors for a maximum of 8-bits, 16-bits 32-bits and 64-bits:
1185
1186 guint8 tvb_get_bits8(tvbuff_t *tvb, gint bit_offset, gint no_of_bits);
1187 guint16 tvb_get_bits16(tvbuff_t *tvb, gint bit_offset, gint no_of_bits,gboolean little_endian);
1188 guint32 tvb_get_bits32(tvbuff_t *tvb, gint bit_offset, gint no_of_bits,gboolean little_endian);
1189 guint64 tvb_get_bits64(tvbuff_t *tvb, gint bit_offset, gint no_of_bits,gboolean little_endian);
1190
1191 Single-byte accessor:
1192
1193 guint8  tvb_get_guint8(tvbuff_t*, gint offset);
1194
1195 Network-to-host-order accessors for 16-bit integers (guint16), 24-bit
1196 integers, 32-bit integers (guint32), and 64-bit integers (guint64):
1197
1198 guint16 tvb_get_ntohs(tvbuff_t*, gint offset);
1199 guint32 tvb_get_ntoh24(tvbuff_t*, gint offset);
1200 guint32 tvb_get_ntohl(tvbuff_t*, gint offset);
1201 guint64 tvb_get_ntoh64(tvbuff_t*, gint offset);
1202
1203 Network-to-host-order accessors for single-precision and
1204 double-precision IEEE floating-point numbers:
1205
1206 gfloat tvb_get_ntohieee_float(tvbuff_t*, gint offset);
1207 gdouble tvb_get_ntohieee_double(tvbuff_t*, gint offset);
1208
1209 Little-Endian-to-host-order accessors for 16-bit integers (guint16),
1210 24-bit integers, 32-bit integers (guint32), and 64-bit integers
1211 (guint64):
1212
1213 guint16 tvb_get_letohs(tvbuff_t*, gint offset);
1214 guint32 tvb_get_letoh24(tvbuff_t*, gint offset);
1215 guint32 tvb_get_letohl(tvbuff_t*, gint offset);
1216 guint64 tvb_get_letoh64(tvbuff_t*, gint offset);
1217
1218 Little-Endian-to-host-order accessors for single-precision and
1219 double-precision IEEE floating-point numbers:
1220
1221 gfloat tvb_get_letohieee_float(tvbuff_t*, gint offset);
1222 gdouble tvb_get_letohieee_double(tvbuff_t*, gint offset);
1223
1224 Accessors for IPv4 and IPv6 addresses:
1225
1226 guint32 tvb_get_ipv4(tvbuff_t*, gint offset);
1227 void tvb_get_ipv6(tvbuff_t*, gint offset, struct e_in6_addr *addr);
1228
1229 NOTE: IPv4 addresses are not to be converted to host byte order before
1230 being passed to "proto_tree_add_ipv4()".  You should use "tvb_get_ipv4()"
1231 to fetch them, not "tvb_get_ntohl()" *OR* "tvb_get_letohl()" - don't,
1232 for example, try to use "tvb_get_ntohl()", find that it gives you the
1233 wrong answer on the PC on which you're doing development, and try
1234 "tvb_get_letohl()" instead, as "tvb_get_letohl()" will give the wrong
1235 answer on big-endian machines.
1236
1237 Accessors for GUID:
1238
1239 void tvb_get_ntohguid(tvbuff_t *, gint offset, e_guid_t *guid);
1240 void tvb_get_letohguid(tvbuff_t *, gint offset, e_guid_t *guid);
1241
1242 String accessors:
1243
1244 guint8 *tvb_get_string(tvbuff_t*, gint offset, gint length);
1245 guint8 *tvb_get_ephemeral_string(tvbuff_t*, gint offset, gint length);
1246 guint8 *tvb_get_seasonal_string(tvbuff_t*, gint offset, gint length);
1247
1248 Returns a null-terminated buffer containing data from the specified
1249 tvbuff, starting at the specified offset, and containing the specified
1250 length worth of characters (the length of the buffer will be length+1,
1251 as it includes a null character to terminate the string).
1252
1253 tvb_get_string() returns a buffer allocated by g_malloc() so you must
1254 g_free() it when you are finished with the string. Failure to g_free() this
1255 buffer will lead to memory leaks.
1256
1257 tvb_get_ephemeral_string() returns a buffer allocated from a special heap
1258 with a lifetime until the next packet is dissected. You do not need to
1259 free() this buffer, it will happen automatically once the next packet is
1260 dissected.
1261
1262 tvb_get_seasonal_string() returns a buffer allocated from a special heap
1263 with a lifetime of the current capture session. You do not need to
1264 free() this buffer, it will happen automatically once the a new capture or
1265 file is opened.
1266
1267 guint8 *tvb_get_stringz(tvbuff_t *tvb, gint offset, gint *lengthp);
1268 guint8 *tvb_get_ephemeral_stringz(tvbuff_t *tvb, gint offset, gint *lengthp);
1269 guint8 *tvb_get_seasonal_stringz(tvbuff_t *tvb, gint offset, gint *lengthp);
1270
1271 Returns a null-terminated buffer, allocated with "g_malloc()",
1272 containing data from the specified tvbuff, starting at the
1273 specified offset, and containing all characters from the tvbuff up to
1274 and including a terminating null character in the tvbuff.  "*lengthp"
1275 will be set to the length of the string, including the terminating null.
1276
1277 tvb_get_stringz() returns a buffer allocated by g_malloc() so you must
1278 g_free() it when you are finished with the string. Failure to g_free() this
1279 buffer will lead to memory leaks.
1280 tvb_get_ephemeral_stringz() returns a buffer allocated from a special heap
1281 with a lifetime until the next packet is dissected. You do not need to
1282 free() this buffer, it will happen automatically once the next packet is
1283 dissected.
1284
1285 tvb_get_seasonal_stringz() returns a buffer allocated from a special heap
1286 with a lifetime of the current capture session. You do not need to
1287 free() this buffer, it will happen automatically once the a new capture or
1288 file is opened.
1289
1290 guint8 *tvb_fake_unicode(tvbuff_t*, gint offset, gint length, gboolean little_endian);
1291 guint8 *tvb_get_ephemeral_faked_unicode(tvbuff_t*, gint offset, gint length, gboolean little_endian);
1292
1293 Converts a 2-byte unicode string to an ASCII string.
1294 Returns a null-terminated buffer containing data from the specified
1295 tvbuff, starting at the specified offset, and containing the specified
1296 length worth of characters (the length of the buffer will be length+1,
1297 as it includes a null character to terminate the string).
1298
1299 tvb_fake_unicode() returns a buffer allocated by g_malloc() so you must
1300 g_free() it when you are finished with the string. Failure to g_free() this
1301 buffer will lead to memory leaks.
1302 tvb_get_ephemeral_faked_unicode() returns a buffer allocated from a special
1303 heap with a lifetime until the next packet is dissected. You do not need to
1304 free() this buffer, it will happen automatically once the next packet is
1305 dissected.
1306
1307 Byte Array Accessors:
1308
1309 gchar *tvb_bytes_to_str(tvbuff_t *tvb, gint offset, gint len);
1310
1311 Formats a bunch of data from a tvbuff as bytes, returning a pointer
1312 to the string with the data formatted as two hex digits for each byte.
1313 The string pointed to is stored in an "ep_alloc'd" buffer which will be freed
1314 before the next frame is dissected. The formatted string will contain the hex digits
1315 for at most the first 16 bytes of the data. If len is greater than 16 bytes, a
1316 trailing "..." will be added to the string.
1317
1318 gchar *tvb_bytes_to_str_punct(tvbuff_t *tvb, gint offset, gint len, gchar punct);
1319
1320 This function is similar to tvb_bytes_to_str(...) except that 'punct' is inserted
1321 between the hex representation of each byte.
1322
1323
1324 Copying memory:
1325 guint8* tvb_memcpy(tvbuff_t*, guint8* target, gint offset, gint length);
1326
1327 Copies into the specified target the specified length's worth of data
1328 from the specified tvbuff, starting at the specified offset.
1329
1330 guint8* tvb_memdup(tvbuff_t*, gint offset, gint length);
1331 guint8* ep_tvb_memdup(tvbuff_t*, gint offset, gint length);
1332
1333 Returns a buffer, allocated with "g_malloc()", containing the specified
1334 length's worth of data from the specified tvbuff, starting at the
1335 specified offset. The ephemeral variant is freed automatically after the
1336 packet is dissected.
1337
1338 Pointer-retrieval:
1339 /* WARNING! This function is possibly expensive, temporarily allocating
1340  * another copy of the packet data. Furthermore, it's dangerous because once
1341  * this pointer is given to the user, there's no guarantee that the user will
1342  * honor the 'length' and not overstep the boundaries of the buffer.
1343  */
1344 guint8* tvb_get_ptr(tvbuff_t*, gint offset, gint length);
1345
1346 The reason that tvb_get_ptr() might have to allocate a copy of its data
1347 only occurs with TVBUFF_COMPOSITES, data that spans multiple tvbuffers.
1348 If the user requests a pointer to a range of bytes that span the member
1349 tvbuffs that make up the TVBUFF_COMPOSITE, the data will have to be
1350 copied to another memory region to assure that all the bytes are
1351 contiguous.
1352
1353
1354
1355 1.5 Functions to handle columns in the traffic summary window.
1356
1357 The topmost pane of the main window is a list of the packets in the
1358 capture, possibly filtered by a display filter.
1359
1360 Each line corresponds to a packet, and has one or more columns, as
1361 configured by the user.
1362
1363 Many of the columns are handled by code outside individual dissectors;
1364 most dissectors need only specify the value to put in the "Protocol" and
1365 "Info" columns.
1366
1367 Columns are specified by COL_ values; the COL_ value for the "Protocol"
1368 field, typically giving an abbreviated name for the protocol (but not
1369 the all-lower-case abbreviation used elsewhere) is COL_PROTOCOL, and the
1370 COL_ value for the "Info" field, giving a summary of the contents of the
1371 packet for that protocol, is COL_INFO.
1372
1373 The value for a column can be specified with one of several functions,
1374 all of which take the 'fd' argument to the dissector as their first
1375 argument, and the COL_ value for the column as their second argument.
1376
1377 1.5.1 The col_set_str function.
1378
1379 'col_set_str' takes a string as its third argument, and sets the value
1380 for the column to that value.  It assumes that the pointer passed to it
1381 points to a string constant or a static "const" array, not to a
1382 variable, as it doesn't copy the string, it merely saves the pointer
1383 value; the argument can itself be a variable, as long as it always
1384 points to a string constant or a static "const" array.
1385
1386 It is more efficient than 'col_add_str' or 'col_add_fstr'; however, if
1387 the dissector will be using 'col_append_str' or 'col_append_fstr" to
1388 append more information to the column, the string will have to be copied
1389 anyway, so it's best to use 'col_add_str' rather than 'col_set_str' in
1390 that case.
1391
1392 For example, to set the "Protocol" column
1393 to "PROTOABBREV":
1394
1395         col_set_str(pinfo->cinfo, COL_PROTOCOL, "PROTOABBREV");
1396
1397
1398 1.5.2 The col_add_str function.
1399
1400 'col_add_str' takes a string as its third argument, and sets the value
1401 for the column to that value.  It takes the same arguments as
1402 'col_set_str', but copies the string, so that if the string is, for
1403 example, an automatic variable that won't remain in scope when the
1404 dissector returns, it's safe to use.
1405
1406
1407 1.5.3 The col_add_fstr function.
1408
1409 'col_add_fstr' takes a 'printf'-style format string as its third
1410 argument, and 'printf'-style arguments corresponding to '%' format
1411 items in that string as its subsequent arguments.  For example, to set
1412 the "Info" field to "<XXX> request, <N> bytes", where "reqtype" is a
1413 string containing the type of the request in the packet and "n" is an
1414 unsigned integer containing the number of bytes in the request:
1415
1416         col_add_fstr(pinfo->cinfo, COL_INFO, "%s request, %u bytes",
1417                      reqtype, n);
1418
1419 Don't use 'col_add_fstr' with a format argument of just "%s" -
1420 'col_add_str', or possibly even 'col_set_str' if the string that matches
1421 the "%s" is a static constant string, will do the same job more
1422 efficiently.
1423
1424
1425 1.5.4 The col_clear function.
1426
1427 If the Info column will be filled with information from the packet, that
1428 means that some data will be fetched from the packet before the Info
1429 column is filled in.  If the packet is so small that the data in
1430 question cannot be fetched, the routines to fetch the data will throw an
1431 exception (see the comment at the beginning about tvbuffers improving
1432 the handling of short packets - the tvbuffers keep track of how much
1433 data is in the packet, and throw an exception on an attempt to fetch
1434 data past the end of the packet, so that the dissector won't process
1435 bogus data), causing the Info column not to be filled in.
1436
1437 This means that the Info column will have data for the previous
1438 protocol, which would be confusing if, for example, the Protocol column
1439 had data for this protocol.
1440
1441 Therefore, before a dissector fetches any data whatsoever from the
1442 packet (unless it's a heuristic dissector fetching data to determine
1443 whether the packet is one that it should dissect, in which case it
1444 should check, before fetching the data, whether there's any data to
1445 fetch; if there isn't, it should return FALSE), it should set the
1446 Protocol column and the Info column.
1447
1448 If the Protocol column will ultimately be set to, for example, a value
1449 containing a protocol version number, with the version number being a
1450 field in the packet, the dissector should, before fetching the version
1451 number field or any other field from the packet, set it to a value
1452 without a version number, using 'col_set_str', and should later set it
1453 to a value with the version number after it's fetched the version
1454 number.
1455
1456 If the Info column will ultimately be set to a value containing
1457 information from the packet, the dissector should, before fetching any
1458 fields from the packet, clear the column using 'col_clear' (which is
1459 more efficient than clearing it by calling 'col_set_str' or
1460 'col_add_str' with a null string), and should later set it to the real
1461 string after it's fetched the data to use when doing that.
1462
1463
1464 1.5.5 The col_append_str function.
1465
1466 Sometimes the value of a column, especially the "Info" column, can't be
1467 conveniently constructed at a single point in the dissection process;
1468 for example, it might contain small bits of information from many of the
1469 fields in the packet.  'col_append_str' takes, as arguments, the same
1470 arguments as 'col_add_str', but the string is appended to the end of the
1471 current value for the column, rather than replacing the value for that
1472 column.  (Note that no blank separates the appended string from the
1473 string to which it is appended; if you want a blank there, you must add
1474 it yourself as part of the string being appended.)
1475
1476
1477 1.5.6 The col_append_fstr function.
1478
1479 'col_append_fstr' is to 'col_add_fstr' as 'col_append_str' is to
1480 'col_add_str' - it takes, as arguments, the same arguments as
1481 'col_add_fstr', but the formatted string is appended to the end of the
1482 current value for the column, rather than replacing the value for that
1483 column.
1484
1485 1.5.7 The col_append_sep_str and col_append_sep_fstr functions.
1486
1487 In specific situations the developer knows that a column's value will be
1488 created in a stepwise manner, where the appended values are listed. Both
1489 'col_append_sep_str' and 'col_append_sep_fstr' functions will add an item
1490 separator between two consecutive items, and will not add the separator at the
1491 beginning of the column. The remainder of the work both functions do is
1492 identical to what 'col_append_str' and 'col_append_fstr' do.
1493
1494 1.5.8 The col_set_fence and col_prepend_fence_fstr functions.
1495
1496 Sometimes a dissector may be called multiple times for different PDUs in the
1497 same frame (for example in the case of SCTP chunk bundling: several upper
1498 layer data packets may be contained in one SCTP packet).  If the upper layer
1499 dissector calls 'col_set_str()' or 'col_clear()' on the Info column when it
1500 begins dissecting each of those PDUs then when the frame is fully dissected
1501 the Info column would contain only the string from the last PDU in the frame.
1502 The 'col_set_fence' function erects a "fence" in the column that prevents
1503 subsequent 'col_...' calls from clearing the data currently in that column.
1504 For example, the SCTP dissector calls 'col_set_fence' on the Info column
1505 after it has called any subdissectors for that chunk so that subdissectors
1506 of any subsequent chunks may only append to the Info column.
1507 'col_prepend_fence_fstr' prepends data before a fence (moving it if
1508 necessary).  It will create a fence at the end of the prepended data if the
1509 fence does not already exist.
1510
1511
1512 1.5.9 The col_set_time function.
1513
1514 The 'col_set_time' function takes an nstime value as its third argument.
1515 This nstime value is a relative value and will be added as such to the
1516 column. The fourth argument is the filtername holding this value. This
1517 way, rightclicking on the column makes it possible to build a filter
1518 based on the time-value.
1519
1520 For example:
1521
1522         nstime_delta(&ts, &pinfo->fd->abs_ts, &tcpd->ts_first);
1523         col_set_time(pinfo->cinfo, COL_REL_CONV_TIME, &ts, "tcp.time_relative");
1524
1525
1526 1.6 Constructing the protocol tree.
1527
1528 The middle pane of the main window, and the topmost pane of a packet
1529 popup window, are constructed from the "protocol tree" for a packet.
1530
1531 The protocol tree, or proto_tree, is a GNode, the N-way tree structure
1532 available within GLIB. Of course the protocol dissectors don't care
1533 what a proto_tree really is; they just pass the proto_tree pointer as an
1534 argument to the routines which allow them to add items and new branches
1535 to the tree.
1536
1537 When a packet is selected in the packet-list pane, or a packet popup
1538 window is created, a new logical protocol tree (proto_tree) is created.
1539 The pointer to the proto_tree (in this case, 'protocol tree'), is passed
1540 to the top-level protocol dissector, and then to all subsequent protocol
1541 dissectors for that packet, and then the GUI tree is drawn via
1542 proto_tree_draw().
1543
1544 The logical proto_tree needs to know detailed information about the protocols
1545 and fields about which information will be collected from the dissection
1546 routines. By strictly defining (or "typing") the data that can be attached to a
1547 proto tree, searching and filtering becomes possible.  This means that for
1548 every protocol and field (which I also call "header fields", since they are
1549 fields in the protocol headers) which might be attached to a tree, some
1550 information is needed.
1551
1552 Every dissector routine will need to register its protocols and fields
1553 with the central protocol routines (in proto.c). At first I thought I
1554 might keep all the protocol and field information about all the
1555 dissectors in one file, but decentralization seemed like a better idea.
1556 That one file would have gotten very large; one small change would have
1557 required a re-compilation of the entire file. Also, by allowing
1558 registration of protocols and fields at run-time, loadable modules of
1559 protocol dissectors (perhaps even user-supplied) is feasible.
1560
1561 To do this, each protocol should have a register routine, which will be
1562 called when Wireshark starts.  The code to call the register routines is
1563 generated automatically; to arrange that a protocol's register routine
1564 be called at startup:
1565
1566         the file containing a dissector's "register" routine must be
1567         added to "DISSECTOR_SRC" in "epan/dissectors/Makefile.common"
1568         (and in "epan/CMakeLists.txt");
1569
1570         the "register" routine must have a name of the form
1571         "proto_register_XXX";
1572
1573         the "register" routine must take no argument, and return no
1574         value;
1575
1576         the "register" routine's name must appear in the source file
1577         either at the beginning of the line, or preceded only by "void "
1578         at the beginning of the line (that would typically be the
1579         definition) - other white space shouldn't cause a problem, e.g.:
1580
1581 void proto_register_XXX(void) {
1582
1583         ...
1584
1585 }
1586
1587 and
1588
1589 void
1590 proto_register_XXX( void )
1591 {
1592
1593         ...
1594
1595 }
1596
1597         and so on should work.
1598
1599 For every protocol or field that a dissector wants to register, a variable of
1600 type int needs to be used to keep track of the protocol. The IDs are
1601 needed for establishing parent/child relationships between protocols and
1602 fields, as well as associating data with a particular field so that it
1603 can be stored in the logical tree and displayed in the GUI protocol
1604 tree.
1605
1606 Some dissectors will need to create branches within their tree to help
1607 organize header fields. These branches should be registered as header
1608 fields. Only true protocols should be registered as protocols. This is
1609 so that a display filter user interface knows how to distinguish
1610 protocols from fields.
1611
1612 A protocol is registered with the name of the protocol and its
1613 abbreviation.
1614
1615 Here is how the frame "protocol" is registered.
1616
1617         int proto_frame;
1618
1619         proto_frame = proto_register_protocol (
1620                 /* name */            "Frame",
1621                 /* short name */      "Frame",
1622                 /* abbrev */          "frame" );
1623
1624 A header field is also registered with its name and abbreviation, but
1625 information about its data type is needed. It helps to look at
1626 the header_field_info struct to see what information is expected:
1627
1628 struct header_field_info {
1629         const char                      *name;
1630         const char                      *abbrev;
1631         enum ftenum                     type;
1632         int                             display;
1633         const void                      *strings;
1634         guint32                         bitmask;
1635         const char                      *blurb;
1636         .....
1637 };
1638
1639 name
1640 ----
1641 A string representing the name of the field. This is the name
1642 that will appear in the graphical protocol tree.  It must be a non-empty
1643 string.
1644
1645 abbrev
1646 ------
1647 A string with an abbreviation of the field. We concatenate the
1648 abbreviation of the parent protocol with an abbreviation for the field,
1649 using a period as a separator. For example, the "src" field in an IP packet
1650 would have "ip.src" as an abbreviation. It is acceptable to have
1651 multiple levels of periods if, for example, you have fields in your
1652 protocol that are then subdivided into subfields. For example, TRMAC
1653 has multiple error fields, so the abbreviations follow this pattern:
1654 "trmac.errors.iso", "trmac.errors.noniso", etc.
1655
1656 The abbreviation is the identifier used in a display filter.  If it is
1657 an empty string then the field will not be filterable.
1658
1659 type
1660 ----
1661 The type of value this field holds. The current field types are:
1662
1663         FT_NONE                 No field type. Used for fields that
1664                                 aren't given a value, and that can only
1665                                 be tested for presence or absence; a
1666                                 field that represents a data structure,
1667                                 with a subtree below it containing
1668                                 fields for the members of the structure,
1669                                 or that represents an array with a
1670                                 subtree below it containing fields for
1671                                 the members of the array, might be an
1672                                 FT_NONE field.
1673         FT_PROTOCOL             Used for protocols which will be placing
1674                                 themselves as top-level items in the
1675                                 "Packet Details" pane of the UI.
1676         FT_BOOLEAN              0 means "false", any other value means
1677                                 "true".
1678         FT_FRAMENUM             A frame number; if this is used, the "Go
1679                                 To Corresponding Frame" menu item can
1680                                 work on that field.
1681         FT_UINT8                An 8-bit unsigned integer.
1682         FT_UINT16               A 16-bit unsigned integer.
1683         FT_UINT24               A 24-bit unsigned integer.
1684         FT_UINT32               A 32-bit unsigned integer.
1685         FT_UINT64               A 64-bit unsigned integer.
1686         FT_INT8                 An 8-bit signed integer.
1687         FT_INT16                A 16-bit signed integer.
1688         FT_INT24                A 24-bit signed integer.
1689         FT_INT32                A 32-bit signed integer.
1690         FT_INT64                A 64-bit signed integer.
1691         FT_FLOAT                A single-precision floating point number.
1692         FT_DOUBLE               A double-precision floating point number.
1693         FT_ABSOLUTE_TIME        Seconds (4 bytes) and nanoseconds (4 bytes)
1694                                 of time since January 1, 1970, midnight
1695                                 UTC, displayed as the date, followed by
1696                                 the time, as hours, minutes, and seconds
1697                                 with 9 digits after the decimal point.
1698         FT_RELATIVE_TIME        Seconds (4 bytes) and nanoseconds (4 bytes)
1699                                 of time relative to an arbitrary time.
1700                                 displayed as seconds and 9 digits
1701                                 after the decimal point.
1702         FT_STRING               A string of characters, not necessarily
1703                                 NUL-terminated, but possibly NUL-padded.
1704                                 This, and the other string-of-characters
1705                                 types, are to be used for text strings,
1706                                 not raw binary data.
1707         FT_STRINGZ              A NUL-terminated string of characters.
1708         FT_EBCDIC               A string of characters, not necessarily
1709                                 NUL-terminated, but possibly NUL-padded.
1710                                 The data from the packet is converted from
1711                                 EBCDIC to ASCII before displaying to the user.
1712         FT_UINT_STRING          A counted string of characters, consisting
1713                                 of a count (represented as an integral value,
1714                                 of width given in the proto_tree_add_item()
1715                                 call) followed immediately by that number of
1716                                 characters.
1717         FT_ETHER                A six octet string displayed in
1718                                 Ethernet-address format.
1719         FT_BYTES                A string of bytes with arbitrary values;
1720                                 used for raw binary data.
1721         FT_UINT_BYTES           A counted string of bytes, consisting
1722                                 of a count (represented as an integral value,
1723                                 of width given in the proto_tree_add_item()
1724                                 call) followed immediately by that number of
1725                                 arbitrary values; used for raw binary data.
1726         FT_IPv4                 A version 4 IP address (4 bytes) displayed
1727                                 in dotted-quad IP address format (4
1728                                 decimal numbers separated by dots).
1729         FT_IPv6                 A version 6 IP address (16 bytes) displayed
1730                                 in standard IPv6 address format.
1731         FT_IPXNET               An IPX address displayed in hex as a 6-byte
1732                                 network number followed by a 6-byte station
1733                                 address.
1734         FT_GUID                 A Globally Unique Identifier
1735         FT_OID                  An ASN.1 Object Identifier
1736
1737 Some of these field types are still not handled in the display filter
1738 routines, but the most common ones are. The FT_UINT* variables all
1739 represent unsigned integers, and the FT_INT* variables all represent
1740 signed integers; the number on the end represent how many bits are used
1741 to represent the number.
1742
1743 Some constraints are imposed on the header fields depending on the type
1744 (e.g.  FT_BYTES) of the field.  Fields of type FT_ABSOLUTE_TIME must use
1745 'ABSOLUTE_TIME_{LOCAL,UTC,DOY_UTC}, NULL, 0x0' as values for the
1746 'display, 'strings', and 'bitmask' fields, and all other non-integral
1747 types (i.e.. types that are _not_ FT_INT* and FT_UINT*) must use
1748 'BASE_NONE, NULL, 0x0' as values for the 'display', 'strings', 'bitmask'
1749 fields.  The reason is simply that the type itself implictly defines the
1750 nature of 'display', 'strings', 'bitmask'.
1751
1752 display
1753 -------
1754 The display field has a couple of overloaded uses. This is unfortunate,
1755 but since we're using C as an application programming language, this sometimes
1756 makes for cleaner programs. Right now I still think that overloading
1757 this variable was okay.
1758
1759 For integer fields (FT_UINT* and FT_INT*), this variable represents the
1760 base in which you would like the value displayed.  The acceptable bases
1761 are:
1762
1763         BASE_DEC,
1764         BASE_HEX,
1765         BASE_OCT,
1766         BASE_DEC_HEX,
1767         BASE_HEX_DEC,
1768         BASE_CUSTOM
1769
1770 BASE_DEC, BASE_HEX, and BASE_OCT are decimal, hexadecimal, and octal,
1771 respectively. BASE_DEC_HEX and BASE_HEX_DEC display value in two bases
1772 (the 1st representation followed by the 2nd in parenthesis).
1773
1774 BASE_CUSTOM allows one to specify a callback function pointer that will
1775 format the value. The function pointer of the same type as defined by
1776 custom_fmt_func_t in epan/proto.h, specifically:
1777
1778   void func(gchar *, guint32);
1779
1780 The first argument is a pointer to a buffer of the ITEM_LABEL_LENGTH size
1781 and the second argument is the value to be formatted.
1782
1783 For FT_BOOLEAN fields that are also bitfields (i.e. 'bitmask' is non-zero),
1784 'display' is used to tell the proto_tree how wide the parent bitfield is.
1785 With integers this is not needed since the type of integer itself
1786 (FT_UINT8, FT_UINT16, FT_UINT24, FT_UINT32, etc.) tells the proto_tree how
1787 wide the parent bitfield is.
1788
1789 For FT_ABSOLUTE_TIME fields, 'display' is used to indicate whether the
1790 time is to be displayed as a time in the time zone for the machine on
1791 which Wireshark/TShark is running or as UTC and, for UTC, whether the
1792 date should be displayed as "{monthname}, {month} {day_of_month},
1793 {year}" or as "{year/day_of_year}".
1794
1795 Additionally, BASE_NONE is used for 'display' as a NULL-value. That is, for
1796 non-integers other than FT_ABSOLUTE_TIME fields, and non-bitfield
1797 FT_BOOLEANs, you'll want to use BASE_NONE in the 'display' field.  You may
1798 not use BASE_NONE for integers.
1799
1800 It is possible that in the future we will record the endianness of
1801 integers. If so, it is likely that we'll use a bitmask on the display field
1802 so that integers would be represented as BEND|BASE_DEC or LEND|BASE_HEX.
1803 But that has not happened yet; note that there are protocols for which
1804 no endianness is specified, such as the X11 protocol and the DCE RPC
1805 protocol, so it would not be possible to record the endianness of all
1806 integral fields.
1807
1808 strings
1809 -------
1810 -- value_string
1811 Some integer fields, of type FT_UINT*, need labels to represent the true
1812 value of a field.  You could think of those fields as having an
1813 enumerated data type, rather than an integral data type.
1814
1815 A 'value_string' structure is a way to map values to strings.
1816
1817         typedef struct _value_string {
1818                 guint32  value;
1819                 gchar   *strptr;
1820         } value_string;
1821
1822 For fields of that type, you would declare an array of "value_string"s:
1823
1824         static const value_string valstringname[] = {
1825                 { INTVAL1, "Descriptive String 1" },
1826                 { INTVAL2, "Descriptive String 2" },
1827                 { 0,       NULL }
1828         };
1829
1830 (the last entry in the array must have a NULL 'strptr' value, to
1831 indicate the end of the array).  The 'strings' field would be set to
1832 'VALS(valstringname)'.
1833
1834 If the field has a numeric rather than an enumerated type, the 'strings'
1835 field would be set to NULL.
1836
1837 -- Extended value strings
1838 You can also use an extended version of the value_string for faster lookups.
1839 It requires a value_string as input.
1840 If all of a contiguous range of values from min to max are present in the array
1841 the value will be used as as a direct index into a value_string array.
1842
1843 If the values in the array are not contiguous (ie: there are "gaps"), but are in assending order
1844 a binary search will be used.
1845
1846 Note: "gaps" in a value_string array can be filled with "empty" entries eg: {value, "Unknown"} so that
1847 direct access to the array is is possible.
1848
1849 The init macro (see below) will perform a check on the value string
1850 the first time it is used to determine which search algorithm fits and fall back to a linear search
1851 if the value_string does not meet the criteria above.
1852
1853 Use this macro to initialise the extended value_string at comile time:
1854
1855 static value_string_ext valstringname_ext = VALUE_STRING_EXT_INIT(valstringname);
1856
1857 Extended value strings can be created at runtime by calling
1858    value_string_ext_new(<ptr to value_string array>,
1859                         <total number of entries in the value_string_array>, /* include {0, NULL} entry */
1860                         <value_string_name>);
1861
1862 For hf[] array FT_(U)INT* fields that need a 'valstringname_ext' struct, the 'strings' field
1863 would be set to '&valstringname_ext)'. Furthermore, 'display' field must be
1864 ORed with 'BASE_EXT_STRING' (e.g. BASE_DEC|BASE_EXT_STRING).
1865
1866
1867 -- Ranges
1868 If the field has a numeric type that might logically fit in ranges of values
1869 one can use a range_string struct.
1870
1871 Thus a 'range_string' structure is a way to map ranges to strings.
1872
1873         typedef struct _range_string {
1874                 guint32        value_min;
1875                 guint32        value_max;
1876                 const gchar   *strptr;
1877         } range_string;
1878
1879 For fields of that type, you would declare an array of "range_string"s:
1880
1881         static const range_string rvalstringname[] = {
1882                 { INTVAL_MIN1, INTVALMAX1, "Descriptive String 1" },
1883                 { INTVAL_MIN2, INTVALMAX2, "Descriptive String 2" },
1884                 { 0,           0,          NULL                   }
1885         };
1886
1887 If INTVAL_MIN equals INTVAL_MAX for a given entry the range_string
1888 behavior collapses to the one of value_string.
1889 For FT_(U)INT* fields that need a 'range_string' struct, the 'strings' field
1890 would be set to 'RVALS(rvalstringname)'. Furthermore, 'display' field must be
1891 ORed with 'BASE_RANGE_STRING' (e.g. BASE_DEC|BASE_RANGE_STRING).
1892
1893 -- Booleans
1894 FT_BOOLEANs have a default map of 0 = "False", 1 (or anything else) = "True".
1895 Sometimes it is useful to change the labels for boolean values (e.g.,
1896 to "Yes"/"No", "Fast"/"Slow", etc.).  For these mappings, a struct called
1897 true_false_string is used.
1898
1899         typedef struct true_false_string {
1900                 char    *true_string;
1901                 char    *false_string;
1902         } true_false_string;
1903
1904 For Boolean fields for which "False" and "True" aren't the desired
1905 labels, you would declare a "true_false_string"s:
1906
1907         static const true_false_string boolstringname = {
1908                 "String for True",
1909                 "String for False"
1910         };
1911
1912 Its two fields are pointers to the string representing truth, and the
1913 string representing falsehood.  For FT_BOOLEAN fields that need a
1914 'true_false_string' struct, the 'strings' field would be set to
1915 'TFS(&boolstringname)'.
1916
1917 If the Boolean field is to be displayed as "False" or "True", the
1918 'strings' field would be set to NULL.
1919
1920 Wireshark predefines a whole range of ready made "true_false_string"s
1921 in tfs.h, included via packet.h.
1922
1923 bitmask
1924 -------
1925 If the field is a bitfield, then the bitmask is the mask which will
1926 leave only the bits needed to make the field when ANDed with a value.
1927 The proto_tree routines will calculate 'bitshift' automatically
1928 from 'bitmask', by finding the rightmost set bit in the bitmask.
1929 This shift is applied before applying string mapping functions or
1930 filtering.
1931 If the field is not a bitfield, then bitmask should be set to 0.
1932
1933 blurb
1934 -----
1935 This is a string giving a proper description of the field.  It should be
1936 at least one grammatically complete sentence, or NULL in which case the
1937 name field is used. (Please do not use "").
1938 It is meant to provide a more detailed description of the field than the
1939 name alone provides. This information will be used in the man page, and
1940 in a future GUI display-filter creation tool. We might also add tooltips
1941 to the labels in the GUI protocol tree, in which case the blurb would
1942 be used as the tooltip text.
1943
1944
1945 1.6.1 Field Registration.
1946
1947 Protocol registration is handled by creating an instance of the
1948 header_field_info struct (or an array of such structs), and
1949 calling the registration function along with the registration ID of
1950 the protocol that is the parent of the fields. Here is a complete example:
1951
1952         static int proto_eg = -1;
1953         static int hf_field_a = -1;
1954         static int hf_field_b = -1;
1955
1956         static hf_register_info hf[] = {
1957
1958                 { &hf_field_a,
1959                 { "Field A",    "proto.field_a", FT_UINT8, BASE_HEX, NULL,
1960                         0xf0, "Field A represents Apples", HFILL }},
1961
1962                 { &hf_field_b,
1963                 { "Field B",    "proto.field_b", FT_UINT16, BASE_DEC, VALS(vs),
1964                         0x0, "Field B represents Bananas", HFILL }}
1965         };
1966
1967         proto_eg = proto_register_protocol("Example Protocol",
1968             "PROTO", "proto");
1969         proto_register_field_array(proto_eg, hf, array_length(hf));
1970
1971 Be sure that your array of hf_register_info structs is declared 'static',
1972 since the proto_register_field_array() function does not create a copy
1973 of the information in the array... it uses that static copy of the
1974 information that the compiler created inside your array. Here's the
1975 layout of the hf_register_info struct:
1976
1977 typedef struct hf_register_info {
1978         int                     *p_id;  /* pointer to parent variable */
1979         header_field_info       hfinfo;
1980 } hf_register_info;
1981
1982 Also be sure to use the handy array_length() macro found in packet.h
1983 to have the compiler compute the array length for you at compile time.
1984
1985 If you don't have any fields to register, do *NOT* create a zero-length
1986 "hf" array; not all compilers used to compile Wireshark support them.
1987 Just omit the "hf" array, and the "proto_register_field_array()" call,
1988 entirely.
1989
1990 It is OK to have header fields with a different format be registered with
1991 the same abbreviation. For instance, the following is valid:
1992
1993         static hf_register_info hf[] = {
1994
1995                 { &hf_field_8bit, /* 8-bit version of proto.field */
1996                 { "Field (8 bit)", "proto.field", FT_UINT8, BASE_DEC, NULL,
1997                         0x00, "Field represents FOO", HFILL }},
1998
1999                 { &hf_field_32bit, /* 32-bit version of proto.field */
2000                 { "Field (32 bit)", "proto.field", FT_UINT32, BASE_DEC, NULL,
2001                         0x00, "Field represents FOO", HFILL }}
2002         };
2003
2004 This way a filter expression can match a header field, irrespective of the
2005 representation of it in the specific protocol context. This is interesting
2006 for protocols with variable-width header fields.
2007
2008 The HFILL macro at the end of the struct will set reasonable default values
2009 for internally used fields.
2010
2011 1.6.2 Adding Items and Values to the Protocol Tree.
2012
2013 A protocol item is added to an existing protocol tree with one of a
2014 handful of proto_XXX_DO_YYY() functions.
2015
2016 Remember that it only makes sense to add items to a protocol tree if its
2017 proto_tree pointer is not null. Should you add an item to a NULL tree, then
2018 the proto_XXX_DO_YYY() function will immediately return. The cost of this
2019 function call can be avoided by checking for the tree pointer.
2020
2021 Subtrees can be made with the proto_item_add_subtree() function:
2022
2023         item = proto_tree_add_item(....);
2024         new_tree = proto_item_add_subtree(item, tree_type);
2025
2026 This will add a subtree under the item in question; a subtree can be
2027 created under an item made by any of the "proto_tree_add_XXX" functions,
2028 so that the tree can be given an arbitrary depth.
2029
2030 Subtree types are integers, assigned by
2031 "proto_register_subtree_array()".  To register subtree types, pass an
2032 array of pointers to "gint" variables to hold the subtree type values to
2033 "proto_register_subtree_array()":
2034
2035         static gint ett_eg = -1;
2036         static gint ett_field_a = -1;
2037
2038         static gint *ett[] = {
2039                 &ett_eg,
2040                 &ett_field_a
2041         };
2042
2043         proto_register_subtree_array(ett, array_length(ett));
2044
2045 in your "register" routine, just as you register the protocol and the
2046 fields for that protocol.
2047
2048 There are several functions that the programmer can use to add either
2049 protocol or field labels to the proto_tree:
2050
2051         proto_item*
2052         proto_tree_add_item(tree, id, tvb, start, length, encoding);
2053
2054         proto_item*
2055         proto_tree_add_none_format(tree, id, tvb, start, length, format, ...);
2056
2057         proto_item*
2058         proto_tree_add_protocol_format(tree, id, tvb, start, length,
2059                 format, ...);
2060
2061         proto_item *
2062         proto_tree_add_bytes(tree, id, tvb, start, length, start_ptr);
2063
2064         proto_item *
2065         proto_tree_add_bytes_format(tree, id, tvb, start, length, start_ptr,
2066                 format, ...);
2067
2068         proto_item *
2069         proto_tree_add_bytes_format_value(tree, id, tvb, start, length,
2070                 start_ptr, format, ...);
2071
2072         proto_item *
2073         proto_tree_add_time(tree, id, tvb, start, length, value_ptr);
2074
2075         proto_item *
2076         proto_tree_add_time_format(tree, id, tvb, start, length, value_ptr,
2077                 format, ...);
2078
2079         proto_item *
2080         proto_tree_add_time_format_value(tree, id, tvb, start, length,
2081                 value_ptr, format, ...);
2082
2083         proto_item *
2084         proto_tree_add_ipxnet(tree, id, tvb, start, length, value);
2085
2086         proto_item *
2087         proto_tree_add_ipxnet_format(tree, id, tvb, start, length, value,
2088                 format, ...);
2089
2090         proto_item *
2091         proto_tree_add_ipxnet_format_value(tree, id, tvb, start, length,
2092                 value, format, ...);
2093
2094         proto_item *
2095         proto_tree_add_ipv4(tree, id, tvb, start, length, value);
2096
2097         proto_item *
2098         proto_tree_add_ipv4_format(tree, id, tvb, start, length, value,
2099                 format, ...);
2100
2101         proto_item *
2102         proto_tree_add_ipv4_format_value(tree, id, tvb, start, length,
2103                 value, format, ...);
2104
2105         proto_item *
2106         proto_tree_add_ipv6(tree, id, tvb, start, length, value_ptr);
2107
2108         proto_item *
2109         proto_tree_add_ipv6_format(tree, id, tvb, start, length, value_ptr,
2110                 format, ...);
2111
2112         proto_item *
2113         proto_tree_add_ipv6_format_value(tree, id, tvb, start, length,
2114                 value_ptr, format, ...);
2115
2116         proto_item *
2117         proto_tree_add_ether(tree, id, tvb, start, length, value_ptr);
2118
2119         proto_item *
2120         proto_tree_add_ether_format(tree, id, tvb, start, length, value_ptr,
2121                 format, ...);
2122
2123         proto_item *
2124         proto_tree_add_ether_format_value(tree, id, tvb, start, length,
2125                 value_ptr, format, ...);
2126
2127         proto_item *
2128         proto_tree_add_string(tree, id, tvb, start, length, value_ptr);
2129
2130         proto_item *
2131         proto_tree_add_string_format(tree, id, tvb, start, length, value_ptr,
2132                 format, ...);
2133
2134         proto_item *
2135         proto_tree_add_string_format_value(tree, id, tvb, start, length,
2136                 value_ptr, format, ...);
2137
2138         proto_item *
2139         proto_tree_add_boolean(tree, id, tvb, start, length, value);
2140
2141         proto_item *
2142         proto_tree_add_boolean_format(tree, id, tvb, start, length, value,
2143                 format, ...);
2144
2145         proto_item *
2146         proto_tree_add_boolean_format_value(tree, id, tvb, start, length,
2147                 value, format, ...);
2148
2149         proto_item *
2150         proto_tree_add_float(tree, id, tvb, start, length, value);
2151
2152         proto_item *
2153         proto_tree_add_float_format(tree, id, tvb, start, length, value,
2154                 format, ...);
2155
2156         proto_item *
2157         proto_tree_add_float_format_value(tree, id, tvb, start, length,
2158                 value, format, ...);
2159
2160         proto_item *
2161         proto_tree_add_double(tree, id, tvb, start, length, value);
2162
2163         proto_item *
2164         proto_tree_add_double_format(tree, id, tvb, start, length, value,
2165                 format, ...);
2166
2167         proto_item *
2168         proto_tree_add_double_format_value(tree, id, tvb, start, length,
2169                 value, format, ...);
2170
2171         proto_item *
2172         proto_tree_add_uint(tree, id, tvb, start, length, value);
2173
2174         proto_item *
2175         proto_tree_add_uint_format(tree, id, tvb, start, length, value,
2176                 format, ...);
2177
2178         proto_item *
2179         proto_tree_add_uint_format_value(tree, id, tvb, start, length,
2180                 value, format, ...);
2181
2182         proto_item *
2183         proto_tree_add_uint64(tree, id, tvb, start, length, value);
2184
2185         proto_item *
2186         proto_tree_add_uint64_format(tree, id, tvb, start, length, value,
2187                 format, ...);
2188
2189         proto_item *
2190         proto_tree_add_uint64_format_value(tree, id, tvb, start, length,
2191                 value, format, ...);
2192
2193         proto_item *
2194         proto_tree_add_int(tree, id, tvb, start, length, value);
2195
2196         proto_item *
2197         proto_tree_add_int_format(tree, id, tvb, start, length, value,
2198                 format, ...);
2199
2200         proto_item *
2201         proto_tree_add_int_format_value(tree, id, tvb, start, length,
2202                 value, format, ...);
2203
2204         proto_item *
2205         proto_tree_add_int64(tree, id, tvb, start, length, value);
2206
2207         proto_item *
2208         proto_tree_add_int64_format(tree, id, tvb, start, length, value,
2209                 format, ...);
2210
2211         proto_item *
2212         proto_tree_add_int64_format_value(tree, id, tvb, start, length,
2213                 value, format, ...);
2214
2215         proto_item*
2216         proto_tree_add_text(tree, tvb, start, length, format, ...);
2217
2218         proto_item*
2219         proto_tree_add_text_valist(tree, tvb, start, length, format, ap);
2220
2221         proto_item *
2222         proto_tree_add_guid(tree, id, tvb, start, length, value_ptr);
2223
2224         proto_item *
2225         proto_tree_add_guid_format(tree, id, tvb, start, length, value_ptr,
2226                 format, ...);
2227
2228         proto_item *
2229         proto_tree_add_guid_format_value(tree, id, tvb, start, length,
2230                 value_ptr, format, ...);
2231
2232         proto_item *
2233         proto_tree_add_oid(tree, id, tvb, start, length, value_ptr);
2234
2235         proto_item *
2236         proto_tree_add_oid_format(tree, id, tvb, start, length, value_ptr,
2237                 format, ...);
2238
2239         proto_item *
2240         proto_tree_add_oid_format_value(tree, id, tvb, start, length,
2241                 value_ptr, format, ...);
2242
2243         proto_item*
2244         proto_tree_add_bits_item(tree, id, tvb, bit_offset, no_of_bits,
2245                 little_endian);
2246
2247         proto_item *
2248         proto_tree_add_bits_ret_val(tree, id, tvb, bit_offset, no_of_bits,
2249                 return_value, little_endian);
2250
2251         proto_item *
2252         proto_tree_add_bitmask(tree, tvb, start, header, ett, fields,
2253                 little_endian);
2254
2255         proto_item *
2256         proto_tree_add_bitmask_text(tree, tvb, offset, len, name, fallback,
2257                 ett, fields, little_endian, flags);
2258
2259 The 'tree' argument is the tree to which the item is to be added.  The
2260 'tvb' argument is the tvbuff from which the item's value is being
2261 extracted; the 'start' argument is the offset from the beginning of that
2262 tvbuff of the item being added, and the 'length' argument is the length,
2263 in bytes, of the item, bit_offset is the offset in bits and no_of_bits
2264 is the length in bits.
2265
2266 The length of some items cannot be determined until the item has been
2267 dissected; to add such an item, add it with a length of -1, and, when the
2268 dissection is complete, set the length with 'proto_item_set_len()':
2269
2270         void
2271         proto_item_set_len(ti, length);
2272
2273 The "ti" argument is the value returned by the call that added the item
2274 to the tree, and the "length" argument is the length of the item.
2275
2276 proto_tree_add_item()
2277 ---------------------
2278 proto_tree_add_item is used when you wish to do no special formatting.
2279 The item added to the GUI tree will contain the name (as passed in the
2280 proto_register_*() function) and a value.  The value will be fetched
2281 from the tvbuff by proto_tree_add_item(), based on the type of the field
2282 and, for integral and Boolean fields, the byte order of the value; the
2283 byte order, for items for which that's relevant, is specified by the
2284 'encoding' argument, which is ENC_LITTLE_ENDIAN if the value is
2285 little-endian and ENC_BIG_ENDIAN if it is big-endian.  If the byte order
2286 is not relevant, use ENC_NA (Not Applicable).  In the future, other
2287 elements of the encoding, such as the character encoding for
2288 character strings, might be supported.
2289
2290 Now that definitions of fields have detailed information about bitfield
2291 fields, you can use proto_tree_add_item() with no extra processing to
2292 add bitfield values to your tree.  Here's an example.  Take the Format
2293 Identifier (FID) field in the Transmission Header (TH) portion of the SNA
2294 protocol.  The FID is the high nibble of the first byte of the TH.  The
2295 FID would be registered like this:
2296
2297         name            = "Format Identifier"
2298         abbrev          = "sna.th.fid"
2299         type            = FT_UINT8
2300         display         = BASE_HEX
2301         strings         = sna_th_fid_vals
2302         bitmask         = 0xf0
2303
2304 The bitmask contains the value which would leave only the FID if bitwise-ANDed
2305 against the parent field, the first byte of the TH.
2306
2307 The code to add the FID to the tree would be;
2308
2309         proto_tree_add_item(bf_tree, hf_sna_th_fid, tvb, offset, 1,
2310             ENC_BIG_ENDIAN);
2311
2312 The definition of the field already has the information about bitmasking
2313 and bitshifting, so it does the work of masking and shifting for us!
2314 This also means that you no longer have to create value_string structs
2315 with the values bitshifted.  The value_string for FID looks like this,
2316 even though the FID value is actually contained in the high nibble.
2317 (You'd expect the values to be 0x0, 0x10, 0x20, etc.)
2318
2319 /* Format Identifier */
2320 static const value_string sna_th_fid_vals[] = {
2321         { 0x0,  "SNA device <--> Non-SNA Device" },
2322         { 0x1,  "Subarea Node <--> Subarea Node" },
2323         { 0x2,  "Subarea Node <--> PU2" },
2324         { 0x3,  "Subarea Node or SNA host <--> Subarea Node" },
2325         { 0x4,  "?" },
2326         { 0x5,  "?" },
2327         { 0xf,  "Adjacent Subarea Nodes" },
2328         { 0,    NULL }
2329 };
2330
2331 The final implication of this is that display filters work the way you'd
2332 naturally expect them to. You'd type "sna.th.fid == 0xf" to find Adjacent
2333 Subarea Nodes. The user does not have to shift the value of the FID to
2334 the high nibble of the byte ("sna.th.fid == 0xf0") as was necessary
2335 in the past.
2336
2337 proto_tree_add_protocol_format()
2338 --------------------------------
2339 proto_tree_add_protocol_format is used to add the top-level item for the
2340 protocol when the dissector routine wants complete control over how the
2341 field and value will be represented on the GUI tree.  The ID value for
2342 the protocol is passed in as the "id" argument; the rest of the
2343 arguments are a "printf"-style format and any arguments for that format.
2344 The caller must include the name of the protocol in the format; it is
2345 not added automatically as in proto_tree_add_item().
2346
2347 proto_tree_add_none_format()
2348 ----------------------------
2349 proto_tree_add_none_format is used to add an item of type FT_NONE.
2350 The caller must include the name of the field in the format; it is
2351 not added automatically as in proto_tree_add_item().
2352
2353 proto_tree_add_bytes()
2354 proto_tree_add_time()
2355 proto_tree_add_ipxnet()
2356 proto_tree_add_ipv4()
2357 proto_tree_add_ipv6()
2358 proto_tree_add_ether()
2359 proto_tree_add_string()
2360 proto_tree_add_boolean()
2361 proto_tree_add_float()
2362 proto_tree_add_double()
2363 proto_tree_add_uint()
2364 proto_tree_add_uint64()
2365 proto_tree_add_int()
2366 proto_tree_add_int64()
2367 proto_tree_add_guid()
2368 proto_tree_add_oid()
2369 ------------------------
2370 These routines are used to add items to the protocol tree if either:
2371
2372         the value of the item to be added isn't just extracted from the
2373         packet data, but is computed from data in the packet;
2374
2375         the value was fetched into a variable.
2376
2377 The 'value' argument has the value to be added to the tree.
2378
2379 NOTE: in all cases where the 'value' argument is a pointer, a copy is
2380 made of the object pointed to; if you have dynamically allocated a
2381 buffer for the object, that buffer will not be freed when the protocol
2382 tree is freed - you must free the buffer yourself when you don't need it
2383 any more.
2384
2385 For proto_tree_add_bytes(), the 'value_ptr' argument is a pointer to a
2386 sequence of bytes.
2387
2388 For proto_tree_add_time(), the 'value_ptr' argument is a pointer to an
2389 "nstime_t", which is a structure containing the time to be added; it has
2390 'secs' and 'nsecs' members, giving the integral part and the fractional
2391 part of a time in units of seconds, with 'nsecs' being the number of
2392 nanoseconds.  For absolute times, "secs" is a UNIX-style seconds since
2393 January 1, 1970, 00:00:00 GMT value.
2394
2395 For proto_tree_add_ipxnet(), the 'value' argument is a 32-bit IPX
2396 network address.
2397
2398 For proto_tree_add_ipv4(), the 'value' argument is a 32-bit IPv4
2399 address, in network byte order.
2400
2401 For proto_tree_add_ipv6(), the 'value_ptr' argument is a pointer to a
2402 128-bit IPv6 address.
2403
2404 For proto_tree_add_ether(), the 'value_ptr' argument is a pointer to a
2405 48-bit MAC address.
2406
2407 For proto_tree_add_string(), the 'value_ptr' argument is a pointer to a
2408 text string.
2409
2410 For proto_tree_add_boolean(), the 'value' argument is a 32-bit integer.
2411 It is masked and shifted as defined by the field info after which zero
2412 means "false", and non-zero means "true".
2413
2414 For proto_tree_add_float(), the 'value' argument is a 'float' in the
2415 host's floating-point format.
2416
2417 For proto_tree_add_double(), the 'value' argument is a 'double' in the
2418 host's floating-point format.
2419
2420 For proto_tree_add_uint(), the 'value' argument is a 32-bit unsigned
2421 integer value, in host byte order.  (This routine cannot be used to add
2422 64-bit integers.)
2423
2424 For proto_tree_add_uint64(), the 'value' argument is a 64-bit unsigned
2425 integer value, in host byte order.
2426
2427 For proto_tree_add_int(), the 'value' argument is a 32-bit signed
2428 integer value, in host byte order.  (This routine cannot be used to add
2429 64-bit integers.)
2430
2431 For proto_tree_add_int64(), the 'value' argument is a 64-bit signed
2432 integer value, in host byte order.
2433
2434 For proto_tree_add_guid(), the 'value_ptr' argument is a pointer to an
2435 e_guid_t structure.
2436
2437 For proto_tree_add_oid(), the 'value_ptr' argument is a pointer to an
2438 ASN.1 Object Identifier.
2439
2440 proto_tree_add_bytes_format()
2441 proto_tree_add_time_format()
2442 proto_tree_add_ipxnet_format()
2443 proto_tree_add_ipv4_format()
2444 proto_tree_add_ipv6_format()
2445 proto_tree_add_ether_format()
2446 proto_tree_add_string_format()
2447 proto_tree_add_boolean_format()
2448 proto_tree_add_float_format()
2449 proto_tree_add_double_format()
2450 proto_tree_add_uint_format()
2451 proto_tree_add_uint64_format()
2452 proto_tree_add_int_format()
2453 proto_tree_add_int64_format()
2454 proto_tree_add_guid_format()
2455 proto_tree_add_oid_format()
2456 ----------------------------
2457 These routines are used to add items to the protocol tree when the
2458 dissector routine wants complete control over how the field and value
2459 will be represented on the GUI tree.  The argument giving the value is
2460 the same as the corresponding proto_tree_add_XXX() function; the rest of
2461 the arguments are a "printf"-style format and any arguments for that
2462 format.  The caller must include the name of the field in the format; it
2463 is not added automatically as in the proto_tree_add_XXX() functions.
2464
2465 proto_tree_add_bytes_format_value()
2466 proto_tree_add_time_format_value()
2467 proto_tree_add_ipxnet_format_value()
2468 proto_tree_add_ipv4_format_value()
2469 proto_tree_add_ipv6_format_value()
2470 proto_tree_add_ether_format_value()
2471 proto_tree_add_string_format_value()
2472 proto_tree_add_boolean_format_value()
2473 proto_tree_add_float_format_value()
2474 proto_tree_add_double_format_value()
2475 proto_tree_add_uint_format_value()
2476 proto_tree_add_uint64_format_value()
2477 proto_tree_add_int_format_value()
2478 proto_tree_add_int64_format_value()
2479 proto_tree_add_guid_format_value()
2480 proto_tree_add_oid_format_value()
2481 ------------------------------------
2482
2483 These routines are used to add items to the protocol tree when the
2484 dissector routine wants complete control over how the value will be
2485 represented on the GUI tree.  The argument giving the value is the same
2486 as the corresponding proto_tree_add_XXX() function; the rest of the
2487 arguments are a "printf"-style format and any arguments for that format.
2488 With these routines, unlike the proto_tree_add_XXX_format() routines,
2489 the name of the field is added automatically as in the
2490 proto_tree_add_XXX() functions; only the value is added with the format.
2491
2492 proto_tree_add_text()
2493 ---------------------
2494 proto_tree_add_text() is used to add a label to the GUI tree.  It will
2495 contain no value, so it is not searchable in the display filter process.
2496 This function was needed in the transition from the old-style proto_tree
2497 to this new-style proto_tree so that Wireshark would still decode all
2498 protocols w/o being able to filter on all protocols and fields.
2499 Otherwise we would have had to cripple Wireshark's functionality while we
2500 converted all the old-style proto_tree calls to the new-style proto_tree
2501 calls.  In other words, you should not use this in new code unless you've got
2502 a specific reason (see below).
2503
2504 This can also be used for items with subtrees, which may not have values
2505 themselves - the items in the subtree are the ones with values.
2506
2507 For a subtree, the label on the subtree might reflect some of the items
2508 in the subtree.  This means the label can't be set until at least some
2509 of the items in the subtree have been dissected.  To do this, use
2510 'proto_item_set_text()' or 'proto_item_append_text()':
2511
2512         void
2513         proto_item_set_text(proto_item *ti, ...);
2514
2515         void
2516         proto_item_append_text(proto_item *ti, ...);
2517
2518 'proto_item_set_text()' takes as an argument the value returned by
2519 'proto_tree_add_text()', a 'printf'-style format string, and a set of
2520 arguments corresponding to '%' format items in that string, and replaces
2521 the text for the item created by 'proto_tree_add_text()' with the result
2522 of applying the arguments to the format string.
2523
2524 'proto_item_append_text()' is similar, but it appends to the text for
2525 the item the result of applying the arguments to the format string.
2526
2527 For example, early in the dissection, one might do:
2528
2529         ti = proto_tree_add_text(tree, tvb, offset, length, <label>);
2530
2531 and later do
2532
2533         proto_item_set_text(ti, "%s: %s", type, value);
2534
2535 after the "type" and "value" fields have been extracted and dissected.
2536 <label> would be a label giving what information about the subtree is
2537 available without dissecting any of the data in the subtree.
2538
2539 Note that an exception might be thrown when trying to extract the values of
2540 the items used to set the label, if not all the bytes of the item are
2541 available.  Thus, one should create the item with text that is as
2542 meaningful as possible, and set it or append additional information to
2543 it as the values needed to supply that information are extracted.
2544
2545 proto_tree_add_text_valist()
2546 ----------------------------
2547 This is like proto_tree_add_text(), but takes, as the last argument, a
2548 'va_list'; it is used to allow routines that take a printf-like
2549 variable-length list of arguments to add a text item to the protocol
2550 tree.
2551
2552 proto_tree_add_bits_item()
2553 --------------------------
2554 Adds a number of bits to the protocol tree which does not have to be byte
2555 aligned. The offset and length is in bits.
2556 Output format:
2557
2558 ..10 1010 10.. .... "value" (formatted as FT_ indicates).
2559
2560 proto_tree_add_bits_ret_val()
2561 -----------------------------
2562 Works in the same way but also returns the value of the read bits.
2563
2564 proto_tree_add_bitmask() and proto_tree_add_bitmask_text()
2565 ----------------------------------------------------------
2566 This function provides an easy to use and convenient helper function
2567 to manage many types of common bitmasks that occur in protocols.
2568
2569 This function will dissect a 1/2/3/4 byte large bitmask into its individual
2570 fields.
2571 header is an integer type and must be of type FT_[U]INT{8|16|24|32} and
2572 represents the entire width of the bitmask.
2573
2574 'header' and 'ett' are the hf fields and ett field respectively to create an
2575 expansion that covers the 1-4 bytes of the bitmask.
2576
2577 'fields' is a NULL terminated array of pointers to hf fields representing
2578 the individual subfields of the bitmask. These fields must either be integers
2579 of the same byte width as 'header' or of the type FT_BOOLEAN.
2580 Each of the entries in 'fields' will be dissected as an item under the
2581 'header' expansion and also IF the field is a boolean and IF it is set to 1,
2582 then the name of that boolean field will be printed on the 'header' expansion
2583 line.  For integer type subfields that have a value_string defined, the
2584 matched string from that value_string will be printed on the expansion line
2585 as well.
2586
2587 Example: (from the SCSI dissector)
2588         static int hf_scsi_inq_peripheral        = -1;
2589         static int hf_scsi_inq_qualifier         = -1;
2590         static int hf_scsi_inq_devtype           = -1;
2591         ...
2592         static gint ett_scsi_inq_peripheral = -1;
2593         ...
2594         static const int *peripheal_fields[] = {
2595                 &hf_scsi_inq_qualifier,
2596                 &hf_scsi_inq_devtype,
2597                 NULL
2598         };
2599         ...
2600         /* Qualifier and DeviceType */
2601         proto_tree_add_bitmask(tree, tvb, offset, hf_scsi_inq_peripheral,
2602                 ett_scsi_inq_peripheral, peripheal_fields, FALSE);
2603         offset+=1;
2604         ...
2605         { &hf_scsi_inq_peripheral,
2606           {"Peripheral", "scsi.inquiry.preipheral", FT_UINT8, BASE_HEX,
2607            NULL, 0, NULL, HFILL}},
2608         { &hf_scsi_inq_qualifier,
2609           {"Qualifier", "scsi.inquiry.qualifier", FT_UINT8, BASE_HEX,
2610            VALS (scsi_qualifier_val), 0xE0, NULL, HFILL}},
2611         { &hf_scsi_inq_devtype,
2612           {"Device Type", "scsi.inquiry.devtype", FT_UINT8, BASE_HEX,
2613            VALS (scsi_devtype_val), SCSI_DEV_BITS, NULL, HFILL}},
2614         ...
2615
2616 Which provides very pretty dissection of this one byte bitmask.
2617
2618     Peripheral: 0x05, Qualifier: Device type is connected to logical unit, Device Type: CD-ROM
2619         000. .... = Qualifier: Device type is connected to logical unit (0x00)
2620         ...0 0101 = Device Type: CD-ROM (0x05)
2621
2622 The proto_tree_add_bitmask_text() function is an extended version of
2623 the proto_tree_add_bitmask() function. In addition, it allows to:
2624 - Provide a leading text (e.g. "Flags: ") that will appear before
2625   the comma-separated list of field values
2626 - Provide a fallback text (e.g. "None") that will be appended if
2627   no fields warranted a change to the top-level title.
2628 - Using flags, specify which fields will affect the top-level title.
2629
2630 There are the following flags defined:
2631
2632   BMT_NO_APPEND - the title is taken "as-is" from the 'name' argument.
2633   BMT_NO_INT - only boolean flags are added to the title.
2634   BMT_NO_FALSE - boolean flags are only added to the title if they are set.
2635   BMT_NO_TFS - only add flag name to the title, do not use true_false_string
2636
2637 The proto_tree_add_bitmask() behavior can be obtained by providing
2638 both 'name' and 'fallback' arguments as NULL, and a flags of
2639 (BMT_NO_FALSE|BMT_NO_TFS).
2640
2641 PROTO_ITEM_SET_GENERATED()
2642 --------------------------
2643 PROTO_ITEM_SET_GENERATED is used to mark fields as not being read from the
2644 captured data directly, but inferred from one or more values.
2645
2646 One of the primary uses of this is the presentation of verification of
2647 checksums. Every IP packet has a checksum line, which can present the result
2648 of the checksum verification, if enabled in the preferences. The result is
2649 presented as a subtree, where the result is enclosed in square brackets
2650 indicating a generated field.
2651
2652   Header checksum: 0x3d42 [correct]
2653     [Good: True]
2654     [Bad: False]
2655
2656 PROTO_ITEM_SET_HIDDEN()
2657 -----------------------
2658 PROTO_ITEM_SET_HIDDEN is used to hide fields, which have already been added
2659 to the tree, from being visible in the displayed tree.
2660
2661 NOTE that creating hidden fields is actually quite a bad idea from a UI design
2662 perspective because the user (someone who did not write nor has ever seen the
2663 code) has no way of knowing that hidden fields are there to be filtered on
2664 thus defeating the whole purpose of putting them there.  A Better Way might
2665 be to add the fields (that might otherwise be hidden) to a subtree where they
2666 won't be seen unless the user opens the subtree--but they can be found if the
2667 user wants.
2668
2669 One use for hidden fields (which would be better implemented using visible
2670 fields in a subtree) follows: The caller may want a value to be
2671 included in a tree so that the packet can be filtered on this field, but
2672 the representation of that field in the tree is not appropriate.  An
2673 example is the token-ring routing information field (RIF).  The best way
2674 to show the RIF in a GUI is by a sequence of ring and bridge numbers.
2675 Rings are 3-digit hex numbers, and bridges are single hex digits:
2676
2677         RIF: 001-A-013-9-C0F-B-555
2678
2679 In the case of RIF, the programmer should use a field with no value and
2680 use proto_tree_add_none_format() to build the above representation. The
2681 programmer can then add the ring and bridge values, one-by-one, with
2682 proto_tree_add_item() and hide them with PROTO_ITEM_SET_HIDDEN() so that the
2683 user can then filter on or search for a particular ring or bridge. Here's a
2684 skeleton of how the programmer might code this.
2685
2686         char *rif;
2687         rif = create_rif_string(...);
2688
2689         proto_tree_add_none_format(tree, hf_tr_rif_label, ..., "RIF: %s", rif);
2690
2691         for(i = 0; i < num_rings; i++) {
2692                 proto_item *pi;
2693
2694                 pi = proto_tree_add_item(tree, hf_tr_rif_ring, ...,
2695                     ENC_BIG_ENDIAN);
2696                 PROTO_ITEM_SET_HIDDEN(pi);
2697         }
2698         for(i = 0; i < num_rings - 1; i++) {
2699                 proto_item *pi;
2700
2701                 pi = proto_tree_add_item(tree, hf_tr_rif_bridge, ...,
2702                     ENC_BIG_ENDIAN);
2703                 PROTO_ITEM_SET_HIDDEN(pi);
2704         }
2705
2706 The logical tree has these items:
2707
2708         hf_tr_rif_label, text="RIF: 001-A-013-9-C0F-B-555", value = NONE
2709         hf_tr_rif_ring,  hidden, value=0x001
2710         hf_tr_rif_bridge, hidden, value=0xA
2711         hf_tr_rif_ring,  hidden, value=0x013
2712         hf_tr_rif_bridge, hidden, value=0x9
2713         hf_tr_rif_ring,  hidden, value=0xC0F
2714         hf_tr_rif_bridge, hidden, value=0xB
2715         hf_tr_rif_ring,  hidden, value=0x555
2716
2717 GUI or print code will not display the hidden fields, but a display
2718 filter or "packet grep" routine will still see the values. The possible
2719 filter is then possible:
2720
2721         tr.rif_ring eq 0x013
2722
2723 PROTO_ITEM_SET_URL
2724 ------------------
2725 PROTO_ITEM_SET_URL is used to mark fields as containing a URL. This can only
2726 be done with fields of type FT_STRING(Z). If these fields are presented they
2727 are underlined, as could be done in a browser. These fields are sensitive to
2728 clicks as well, launching the configured browser with this URL as parameter.
2729
2730 1.7 Utility routines.
2731
2732 1.7.1 match_strval, match_strval_ext, val_to_str and val_to_str_ext.
2733
2734 A dissector may need to convert a value to a string, using a
2735 'value_string' structure, by hand, rather than by declaring a field with
2736 an associated 'value_string' structure; this might be used, for example,
2737 to generate a COL_INFO line for a frame.
2738
2739 'match_strval()' will do that:
2740
2741         gchar*
2742         match_strval(guint32 val, const value_string *vs)
2743
2744 It will look up the value 'val' in the 'value_string' table pointed to
2745 by 'vs', and return either the corresponding string, or NULL if the
2746 value could not be found in the table.  Note that, unless 'val' is
2747 guaranteed to be a value in the 'value_string' table ("guaranteed" as in
2748 "the code has already checked that it's one of those values" or "the
2749 table handles all possible values of the size of 'val'", not "the
2750 protocol spec says it has to be" - protocol specs do not prevent invalid
2751 packets from being put onto a network or into a purported packet capture
2752 file), you must check whether 'match_strval()' returns NULL, and arrange
2753 that its return value not be dereferenced if it's NULL. 'val_to_str()'
2754 can be used to generate a string for values not found in the table:
2755
2756         gchar*
2757         val_to_str(guint32 val, const value_string *vs, const char *fmt)
2758
2759 If the value 'val' is found in the 'value_string' table pointed to by
2760 'vs', 'val_to_str' will return the corresponding string; otherwise, it
2761 will use 'fmt' as an 'sprintf'-style format, with 'val' as an argument,
2762 to generate a string, and will return a pointer to that string.
2763 You can use it in a call to generate a COL_INFO line for a frame such as
2764
2765         col_add_fstr(COL_INFO, ", %s", val_to_str(val, table, "Unknown %d"));
2766
2767 The match_strval_ext and val_to_str_ext functions are "extended" versions
2768 of match_strval and val_to_str. They should be used for large value-string
2769 arrays which contain many entries. They implement value to string conversions
2770 which will do either a direct access or a binary search of the
2771 value string array if possible. See "Extended Value Strings" under
2772 section  1.6 "Constructing the protocol tree" for more information.
2773
2774 See epan/value_string.h for detailed information on the various value_string
2775 functions.
2776
2777
2778 1.7.2 match_strrval and rval_to_str.
2779
2780 A dissector may need to convert a range of values to a string, using a
2781 'range_string' structure.
2782
2783 'match_strrval()' will do that:
2784
2785         gchar*
2786         match_strrval(guint32 val, const range_string *rs)
2787
2788 It will look up the value 'val' in the 'range_string' table pointed to
2789 by 'rs', and return either the corresponding string, or NULL if the
2790 value could not be found in the table. Please note that its base
2791 behavior is inherited from match_strval().
2792
2793 'rval_to_str()' can be used to generate a string for values not found in
2794 the table:
2795
2796         gchar*
2797         rval_to_str(guint32 val, const range_string *rs, const char *fmt)
2798
2799 If the value 'val' is found in the 'range_string' table pointed to by
2800 'rs', 'rval_to_str' will return the corresponding string; otherwise, it
2801 will use 'fmt' as an 'sprintf'-style format, with 'val' as an argument,
2802 to generate a string, and will return a pointer to that string. Please
2803 note that its base behavior is inherited from match_strval().
2804
2805 1.8 Calling Other Dissectors.
2806
2807 As each dissector completes its portion of the protocol analysis, it
2808 is expected to create a new tvbuff of type TVBUFF_SUBSET which
2809 contains the payload portion of the protocol (that is, the bytes
2810 that are relevant to the next dissector).
2811
2812 The syntax for creating a new TVBUFF_SUBSET is:
2813
2814 next_tvb = tvb_new_subset(tvb, offset, length, reported_length)
2815
2816 Where:
2817         tvb is the tvbuff that the dissector has been working on. It
2818         can be a tvbuff of any type.
2819
2820         next_tvb is the new TVBUFF_SUBSET.
2821
2822         offset is the byte offset of 'tvb' at which the new tvbuff
2823         should start.  The first byte is the 0th byte.
2824
2825         length is the number of bytes in the new TVBUFF_SUBSET. A length
2826         argument of -1 says to use as many bytes as are available in
2827         'tvb'.
2828
2829         reported_length is the number of bytes that the current protocol
2830         says should be in the payload. A reported_length of -1 says that
2831         the protocol doesn't say anything about the size of its payload.
2832
2833
2834 An example from packet-ipx.c -
2835
2836 void
2837 dissect_ipx(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2838 {
2839         tvbuff_t        *next_tvb;
2840         int             reported_length, available_length;
2841
2842
2843         /* Make the next tvbuff */
2844
2845 /* IPX does have a length value in the header, so calculate report_length */
2846    Set this to -1 if there isn't any length information in the protocol
2847 */
2848         reported_length = ipx_length - IPX_HEADER_LEN;
2849
2850 /* Calculate the available data in the packet,
2851    set this to -1 to use all the data in the tv_buffer
2852 */
2853         available_length = tvb_length(tvb) - IPX_HEADER_LEN;
2854
2855 /* Create the tvbuffer for the next dissector */
2856         next_tvb = tvb_new_subset(tvb, IPX_HEADER_LEN,
2857                         MIN(available_length, reported_length),
2858                         reported_length);
2859
2860 /* call the next dissector */
2861         dissector_next( next_tvb, pinfo, tree);
2862
2863
2864 1.9 Editing Makefile.common and CMakeLists.txt to add your dissector.
2865
2866 To arrange that your dissector will be built as part of Wireshark, you
2867 must add the name of the source file for your dissector to the
2868 'DISSECTOR_SRC' macro in the 'Makefile.common' file in the 'epan/dissectors'
2869 directory.  (Note that this is for modern versions of UNIX, so there
2870 is no 14-character limitation on file names, and for modern versions of
2871 Windows, so there is no 8.3-character limitation on file names.)
2872
2873 If your dissector also has its own header file or files, you must add
2874 them to the 'DISSECTOR_INCLUDES' macro in the 'Makefile.common' file in
2875 the 'epan/dissectors' directory, so that it's included when release source
2876 tarballs are built (otherwise, the source in the release tarballs won't
2877 compile).
2878
2879 In addition to the above, you should add your dissector source file name
2880 to the DISSECTOR_SRC section of epan/CMakeLists.txt
2881
2882
2883 1.10 Using the SVN source code tree.
2884
2885   See <http://www.wireshark.org/develop.html>
2886
2887 1.11 Submitting code for your new dissector.
2888
2889   - VERIFY that your dissector code does not use prohibited or deprecated APIs
2890     as follows:
2891     perl <wireshark_root>/tools/checkAPIs.pl <source-filename(s)>
2892
2893   - TEST YOUR DISSECTOR BEFORE SUBMITTING IT.
2894     Use fuzz-test.sh and/or randpkt against your dissector.  These are
2895     described at <http://wiki.wireshark.org/FuzzTesting>.
2896
2897   - Subscribe to <mailto:wireshark-dev[AT]wireshark.org> by sending an email to
2898     <mailto:wireshark-dev-request[AT]wireshark.org?body="help"> or visiting
2899     <http://www.wireshark.org/lists/>.
2900
2901   - 'svn add' all the files of your new dissector.
2902
2903   - 'svn diff' the workspace and save the result to a file.
2904
2905   - Edit the diff file - remove any changes unrelated to your new dissector,
2906     e.g. changes in config.nmake
2907
2908   - Submit a bug report to the Wireshark bug database, found at
2909     <http://bugs.wireshark.org>, qualified as an enhancement and attach your
2910     diff file there. Set the review request flag to '?' so it will pop up in
2911     the patch review list.
2912
2913   - Create a Wiki page on the protocol at <http://wiki.wireshark.org>.
2914     A template is provided so it is easy to setup in a consistent style.
2915       See: <http://wiki.wireshark.org/HowToEdit>
2916       and  <http://wiki.wireshark.org/ProtocolReference>
2917
2918   - If possible, add sample capture files to the sample captures page at
2919     <http://wiki.wireshark.org/SampleCaptures>.  These files are used by
2920     the automated build system for fuzz testing.
2921
2922   - If you find that you are contributing a lot to wireshark on an ongoing
2923     basis you can request to become a committer which will allow you to
2924     commit files to subversion directly.
2925
2926 2. Advanced dissector topics.
2927
2928 2.1 Introduction.
2929
2930 Some of the advanced features are being worked on constantly. When using them
2931 it is wise to check the relevant header and source files for additional details.
2932
2933 2.2 Following "conversations".
2934
2935 In wireshark a conversation is defined as a series of data packets between two
2936 address:port combinations.  A conversation is not sensitive to the direction of
2937 the packet.  The same conversation will be returned for a packet bound from
2938 ServerA:1000 to ClientA:2000 and the packet from ClientA:2000 to ServerA:1000.
2939
2940 2.2.1 Conversation Routines
2941
2942 There are six routines that you will use to work with a conversation:
2943 conversation_new, find_conversation, conversation_add_proto_data,
2944 conversation_get_proto_data, conversation_delete_proto_data,
2945 and conversation_set_dissector.
2946
2947
2948 2.2.1.1 The conversation_init function.
2949
2950 This is an internal routine for the conversation code.  As such you
2951 will not have to call this routine.  Just be aware that this routine is
2952 called at the start of each capture and before the packets are filtered
2953 with a display filter.  The routine will destroy all stored
2954 conversations.  This routine does NOT clean up any data pointers that are
2955 passed in the conversation_add_proto_data 'data' variable.  You are
2956 responsible for this clean up if you pass a malloc'ed pointer
2957 in this variable.
2958
2959 See item 2.2.1.5 for more information about use of the 'data' pointer.
2960
2961
2962 2.2.1.2 The conversation_new function.
2963
2964 This routine will create a new conversation based upon two address/port
2965 pairs.  If you want to associate with the conversation a pointer to a
2966 private data structure you must use the conversation_add_proto_data
2967 function.  The ptype variable is used to differentiate between
2968 conversations over different protocols, i.e. TCP and UDP.  The options
2969 variable is used to define a conversation that will accept any destination
2970 address and/or port.  Set options = 0 if the destination port and address
2971 are know when conversation_new is called.  See section 2.4 for more
2972 information on usage of the options parameter.
2973
2974 The conversation_new prototype:
2975         conversation_t *conversation_new(guint32 setup_frame, address *addr1,
2976             address *addr2, port_type ptype, guint32 port1, guint32 port2,
2977             guint options);
2978
2979 Where:
2980         guint32 setup_frame = The lowest numbered frame for this conversation
2981         address* addr1      = first data packet address
2982         address* addr2      = second data packet address
2983         port_type ptype     = port type, this is defined in packet.h
2984         guint32 port1       = first data packet port
2985         guint32 port2       = second data packet port
2986         guint options       = conversation options, NO_ADDR2 and/or NO_PORT2
2987
2988 setup_frame indicates the first frame for this conversation, and is used to
2989 distinguish multiple conversations with the same addr1/port1 and addr2/port2
2990 pair that occur within the same capture session.
2991
2992 "addr1" and "port1" are the first address/port pair; "addr2" and "port2"
2993 are the second address/port pair.  A conversation doesn't have source
2994 and destination address/port pairs - packets in a conversation go in
2995 both directions - so "addr1"/"port1" may be the source or destination
2996 address/port pair; "addr2"/"port2" would be the other pair.
2997
2998 If NO_ADDR2 is specified, the conversation is set up so that a
2999 conversation lookup will match only the "addr1" address; if NO_PORT2 is
3000 specified, the conversation is set up so that a conversation lookup will
3001 match only the "port1" port; if both are specified, i.e.
3002 NO_ADDR2|NO_PORT2, the conversation is set up so that the lookup will
3003 match only the "addr1"/"port1" address/port pair.  This can be used if a
3004 packet indicates that, later in the capture, a conversation will be
3005 created using certain addresses and ports, in the case where the packet
3006 doesn't specify the addresses and ports of both sides.
3007
3008 2.2.1.3 The find_conversation function.
3009
3010 Call this routine to look up a conversation.  If no conversation is found,
3011 the routine will return a NULL value.
3012
3013 The find_conversation prototype:
3014
3015         conversation_t *find_conversation(guint32 frame_num, address *addr_a,
3016             address *addr_b, port_type ptype, guint32 port_a, guint32 port_b,
3017             guint options);
3018
3019 Where:
3020         guint32 frame_num = a frame number to match
3021         address* addr_a = first address
3022         address* addr_b = second address
3023         port_type ptype = port type
3024         guint32 port_a  = first data packet port
3025         guint32 port_b  = second data packet port
3026         guint options   = conversation options, NO_ADDR_B and/or NO_PORT_B
3027
3028 frame_num is a frame number to match. The conversation returned is where
3029         (frame_num >= conversation->setup_frame
3030         && frame_num < conversation->next->setup_frame)
3031 Suppose there are a total of 3 conversations (A, B, and C) that match
3032 addr_a/port_a and addr_b/port_b, where the setup_frame used in
3033 conversation_new() for A, B and C are 10, 50, and 100 respectively. The
3034 frame_num passed in find_conversation is compared to the setup_frame of each
3035 conversation. So if (frame_num >= 10 && frame_num < 50), conversation A is
3036 returned. If (frame_num >= 50 && frame_num < 100), conversation B is returned.
3037 If (frame_num >= 100) conversation C is returned.
3038
3039 "addr_a" and "port_a" are the first address/port pair; "addr_b" and
3040 "port_b" are the second address/port pair.  Again, as a conversation
3041 doesn't have source and destination address/port pairs, so
3042 "addr_a"/"port_a" may be the source or destination address/port pair;
3043 "addr_b"/"port_b" would be the other pair.  The search will match the
3044 "a" address/port pair against both the "1" and "2" address/port pairs,
3045 and match the "b" address/port pair against both the "2" and "1"
3046 address/port pairs; you don't have to worry about which side the "a" or
3047 "b" pairs correspond to.
3048
3049 If the NO_ADDR_B flag was specified to "find_conversation()", the
3050 "addr_b" address will be treated as matching any "wildcarded" address;
3051 if the NO_PORT_B flag was specified, the "port_b" port will be treated
3052 as matching any "wildcarded" port.  If both flags are specified, i.e.
3053 NO_ADDR_B|NO_PORT_B, the "addr_b" address will be treated as matching
3054 any "wildcarded" address and the "port_b" port will be treated as
3055 matching any "wildcarded" port.
3056
3057
3058 2.2.1.4 The find_or_create_conversation function.
3059
3060 This convenience function will create find an existing conversation (by calling
3061 find_conversation()) and, if a conversation does not already exist, create a
3062 new conversation by calling conversation_new().
3063
3064 The find_or_create_conversation prototype:
3065
3066         extern conversation_t *find_or_create_conversation(packet_info *pinfo);
3067
3068 Where:
3069         packet_info *pinfo = the packet_info structure
3070
3071 The frame number and the addresses necessary for find_conversation() and
3072 conversation_new() are taken from the pinfo structure (as is commonly done)
3073 and no 'options' are used.
3074
3075
3076 2.2.1.5 The conversation_add_proto_data function.
3077
3078 Once you have created a conversation with conversation_new, you can
3079 associate data with it using this function.
3080
3081 The conversation_add_proto_data prototype:
3082
3083         void conversation_add_proto_data(conversation_t *conv, int proto,
3084                 void *proto_data);
3085
3086 Where:
3087         conversation_t *conv = the conversation in question
3088         int proto            = registered protocol number
3089         void *data           = dissector data structure
3090
3091 "conversation" is the value returned by conversation_new.  "proto" is a
3092 unique protocol number created with proto_register_protocol.  Protocols
3093 are typically registered in the proto_register_XXXX section of your
3094 dissector.  "data" is a pointer to the data you wish to associate with the
3095 conversation.  "data" usually points to "se_alloc'd" memory; the
3096 memory will be automatically freed each time a new dissection begins
3097 and thus need not be managed (freed) by the dissector.
3098 Using the protocol number allows several dissectors to
3099 associate data with a given conversation.
3100
3101
3102 2.2.1.6 The conversation_get_proto_data function.
3103
3104 After you have located a conversation with find_conversation, you can use
3105 this function to retrieve any data associated with it.
3106
3107 The conversation_get_proto_data prototype:
3108
3109         void *conversation_get_proto_data(conversation_t *conv, int proto);
3110
3111 Where:
3112         conversation_t *conv = the conversation in question
3113         int proto            = registered protocol number
3114
3115 "conversation" is the conversation created with conversation_new.  "proto"
3116 is a unique protocol number created with proto_register_protocol,
3117 typically in the proto_register_XXXX portion of a dissector.  The function
3118 returns a pointer to the data requested, or NULL if no data was found.
3119
3120
3121 2.2.1.7 The conversation_delete_proto_data function.
3122
3123 After you are finished with a conversation, you can remove your association
3124 with this function.  Please note that ONLY the conversation entry is
3125 removed.  If you have allocated any memory for your data (other than with se_alloc),
3126  you must free it as well.
3127
3128 The conversation_delete_proto_data prototype:
3129
3130         void conversation_delete_proto_data(conversation_t *conv, int proto);
3131
3132 Where:
3133         conversation_t *conv = the conversation in question
3134         int proto            = registered protocol number
3135
3136 "conversation" is the conversation created with conversation_new.  "proto"
3137 is a unique protocol number created with proto_register_protocol,
3138 typically in the proto_register_XXXX portion of a dissector.
3139
3140 2.2.1.8 The conversation_set_dissector function
3141
3142 This function sets the protocol dissector to be invoked whenever
3143 conversation parameters (addresses, port_types, ports, etc) are matched
3144 during the dissection of a packet.
3145
3146 The conversation_set_dissector prototype:
3147
3148         void conversation_set_dissector(conversation_t *conversation, const dissector_handle_t handle);
3149
3150 Where:
3151         conversation_t *conv = the conversation in question
3152         const dissector_handle_t handle = the dissector handle.
3153
3154
3155 2.2.2 Using timestamps relative to the conversation
3156
3157 There is a framework to calculate timestamps relative to the start of the
3158 conversation. First of all the timestamp of the first packet that has been
3159 seen in the conversation must be kept in the protocol data to be able
3160 to calculate the timestamp of the current packet relative to the start
3161 of the conversation. The timestamp of the last packet that was seen in the
3162 conversation should also be kept in the protocol data. This way the
3163 delta time between the current packet and the previous packet in the
3164 conversation can be calculated.
3165
3166 So add the following items to the struct that is used for the protocol data:
3167
3168   nstime_t      ts_first;
3169   nstime_t      ts_prev;
3170
3171 The ts_prev value should only be set during the first run through the
3172 packets (ie pinfo->fd->flags.visited is false).
3173
3174 Next step is to use the per-packet information (described in section 2.5)
3175 to keep the calculated delta timestamp, as it can only be calculated
3176 on the first run through the packets. This is because a packet can be
3177 selected in random order once the whole file has been read.
3178
3179 After calculating the conversation timestamps, it is time to put them in
3180 the appropriate columns with the function 'col_set_time' (described in
3181 section 1.5.9). There are two columns for conversation timestamps:
3182
3183 COL_REL_CONV_TIME,  /* Relative time to beginning of conversation */
3184 COL_DELTA_CONV_TIME,/* Delta time to last frame in conversation */
3185
3186 Last but not least, there MUST be a preference in each dissector that
3187 uses conversation timestamps that makes it possible to enable and
3188 disable the calculation of conversation timestamps. The main argument
3189 for this is that a higher level conversation is able to overwrite
3190 the values of lowel level conversations in these two columns. Being
3191 able to actively select which protocols may overwrite the conversation
3192 timestamp columns gives the user the power to control these columns.
3193 (A second reason is that conversation timestamps use the per-packet
3194 data structure which uses additional memory, which should be avoided
3195 if these timestamps are not needed)
3196
3197 Have a look at the differences to packet-tcp.[ch] in SVN 22966 and
3198 SVN 23058 to see the implementation of conversation timestamps for
3199 the tcp-dissector.
3200
3201
3202 2.2.3 The example conversation code using se_alloc'd memory.
3203
3204 For a conversation between two IP addresses and ports you can use this as an
3205 example.  This example uses se_alloc() to allocate memory and stores the data
3206 pointer in the conversation 'data' variable.
3207
3208 /************************ Global values ************************/
3209
3210 /* define your structure here */
3211 typedef struct {
3212
3213 } my_entry_t;
3214
3215 /* Registered protocol number */
3216 static int my_proto = -1;
3217
3218 /********************* in the dissector routine *********************/
3219
3220 /* the local variables in the dissector */
3221
3222 conversation_t *conversation;
3223 my_entry_t *data_ptr;
3224
3225
3226 /* look up the conversation */
3227
3228 conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst,
3229         pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
3230
3231 /* if conversation found get the data pointer that you stored */
3232 if (conversation)
3233     data_ptr = (my_entry_t*)conversation_get_proto_data(conversation, my_proto);
3234 else {
3235
3236     /* new conversation create local data structure */
3237
3238     data_ptr = se_alloc(sizeof(my_entry_t));
3239
3240     /*** add your code here to setup the new data structure ***/
3241
3242     /* create the conversation with your data pointer  */
3243
3244     conversation = conversation_new(pinfo->fd->num,  &pinfo->src, &pinfo->dst, pinfo->ptype,
3245             pinfo->srcport, pinfo->destport, 0);
3246     conversation_add_proto_data(conversation, my_proto, (void *)data_ptr);
3247 }
3248
3249 /* at this point the conversation data is ready */
3250
3251 /***************** in the protocol register routine *****************/
3252
3253 my_proto = proto_register_protocol("My Protocol", "My Protocol", "my_proto");
3254
3255
3256 2.2.4 An example conversation code that starts at a specific frame number.
3257
3258 Sometimes a dissector has determined that a new conversation is needed that
3259 starts at a specific frame number, when a capture session encompasses multiple
3260 conversation that reuse the same src/dest ip/port pairs. You can use the
3261 conversation->setup_frame returned by find_conversation with
3262 pinfo->fd->num to determine whether or not there already exists a conversation
3263 that starts at the specific frame number.
3264
3265 /* in the dissector routine */
3266
3267         conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst,
3268             pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
3269         if (conversation == NULL || (conversation->setup_frame != pinfo->fd->num)) {
3270                 /* It's not part of any conversation or the returned
3271                  * conversation->setup_frame doesn't match the current frame
3272                  * create a new one.
3273                  */
3274                 conversation = conversation_new(pinfo->fd->num, &pinfo->src,
3275                     &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport,
3276                     NULL, 0);
3277         }
3278
3279
3280 2.2.5 The example conversation code using conversation index field.
3281
3282 Sometimes the conversation isn't enough to define a unique data storage
3283 value for the network traffic.  For example if you are storing information
3284 about requests carried in a conversation, the request may have an
3285 identifier that is used to  define the request. In this case the
3286 conversation and the identifier are required to find the data storage
3287 pointer.  You can use the conversation data structure index value to
3288 uniquely define the conversation.
3289
3290 See packet-afs.c for an example of how to use the conversation index.  In
3291 this dissector multiple requests are sent in the same conversation.  To store
3292 information for each request the dissector has an internal hash table based
3293 upon the conversation index and values inside the request packets.
3294
3295
3296         /* in the dissector routine */
3297
3298         /* to find a request value, first lookup conversation to get index */
3299         /* then used the conversation index, and request data to find data */
3300         /* in the local hash table */
3301
3302         conversation = find_or_create_conversation(pinfo);
3303
3304         request_key.conversation = conversation->index;
3305         request_key.service = pntohs(&rxh->serviceId);
3306         request_key.callnumber = pntohl(&rxh->callNumber);
3307
3308         request_val = (struct afs_request_val *)g_hash_table_lookup(
3309                 afs_request_hash, &request_key);
3310
3311         /* only allocate a new hash element when it's a request */
3312         opcode = 0;
3313         if (!request_val && !reply)
3314         {
3315                 new_request_key = se_alloc(sizeof(struct afs_request_key));
3316                 *new_request_key = request_key;
3317
3318                 request_val = se_alloc(sizeof(struct afs_request_val));
3319                 request_val -> opcode = pntohl(&afsh->opcode);
3320                 opcode = request_val->opcode;
3321
3322                 g_hash_table_insert(afs_request_hash, new_request_key,
3323                         request_val);
3324         }
3325
3326
3327
3328 2.3 Dynamic conversation dissector registration.
3329
3330
3331 NOTE:   This sections assumes that all information is available to
3332         create a complete conversation, source port/address and
3333         destination port/address.  If either the destination port or
3334         address is know, see section 2.4 Dynamic server port dissector
3335         registration.
3336
3337 For protocols that negotiate a secondary port connection, for example
3338 packet-msproxy.c, a conversation can install a dissector to handle
3339 the secondary protocol dissection.  After the conversation is created
3340 for the negotiated ports use the conversation_set_dissector to define
3341 the dissection routine.
3342 Before we create these conversations or assign a dissector to them we should
3343 first check that the conversation does not already exist and if it exists
3344 whether it is registered to our protocol or not.
3345 We should do this because it is uncommon but it does happen that multiple
3346 different protocols can use the same socketpair during different stages of
3347 an application cycle. By keeping track of the frame number a conversation
3348 was started in wireshark can still tell these different protocols apart.
3349
3350 The second argument to conversation_set_dissector is a dissector handle,
3351 which is created with a call to create_dissector_handle or
3352 register_dissector.
3353
3354 create_dissector_handle takes as arguments a pointer to the dissector
3355 function and a protocol ID as returned by proto_register_protocol;
3356 register_dissector takes as arguments a string giving a name for the
3357 dissector, a pointer to the dissector function, and a protocol ID.
3358
3359 The protocol ID is the ID for the protocol dissected by the function.
3360 The function will not be called if the protocol has been disabled by the
3361 user; instead, the data for the protocol will be dissected as raw data.
3362
3363 An example -
3364
3365 /* the handle for the dynamic dissector *
3366 static dissector_handle_t sub_dissector_handle;
3367
3368 /* prototype for the dynamic dissector */
3369 static void sub_dissector(tvbuff_t *tvb, packet_info *pinfo,
3370                 proto_tree *tree);
3371
3372 /* in the main protocol dissector, where the next dissector is setup */
3373
3374 /* if conversation has a data field, create it and load structure */
3375
3376 /* First check if a conversation already exists for this
3377         socketpair
3378 */
3379         conversation = find_conversation(pinfo->fd->num,
3380                                 &pinfo->src, &pinfo->dst, protocol,
3381                                 src_port, dst_port,  0);
3382
3383 /* If there is no such conversation, or if there is one but for
3384    someone else's protocol then we just create a new conversation
3385    and assign our protocol to it.
3386 */
3387         if ( (conversation == NULL) ||
3388              (conversation->dissector_handle != sub_dissector_handle) ) {
3389             new_conv_info = se_alloc(sizeof(struct _new_conv_info));
3390             new_conv_info->data1 = value1;
3391
3392 /* create the conversation for the dynamic port */
3393             conversation = conversation_new(pinfo->fd->num,
3394                 &pinfo->src, &pinfo->dst, protocol,
3395                 src_port, dst_port, new_conv_info, 0);
3396
3397 /* set the dissector for the new conversation */
3398             conversation_set_dissector(conversation, sub_dissector_handle);
3399         }
3400                 ...
3401
3402 void
3403 proto_register_PROTOABBREV(void)
3404 {
3405         ...
3406
3407         sub_dissector_handle = create_dissector_handle(sub_dissector,
3408             proto);
3409
3410         ...
3411 }
3412
3413 2.4 Dynamic server port dissector registration.
3414
3415 NOTE: While this example used both NO_ADDR2 and NO_PORT2 to create a
3416 conversation with only one port and address set, this isn't a
3417 requirement.  Either the second port or the second address can be set
3418 when the conversation is created.
3419
3420 For protocols that define a server address and port for a secondary
3421 protocol, a conversation can be used to link a protocol dissector to
3422 the server port and address.  The key is to create the new
3423 conversation with the second address and port set to the "accept
3424 any" values.
3425
3426 Some server applications can use the same port for different protocols during
3427 different stages of a transaction. For example it might initially use SNMP
3428 to perform some discovery and later switch to use TFTP using the same port.
3429 In order to handle this properly we must first check whether such a
3430 conversation already exists or not and if it exists we also check whether the
3431 registered dissector_handle for that conversation is "our" dissector or not.
3432 If not we create a new conversation on top of the previous one and set this new
3433 conversation to use our protocol.
3434 Since wireshark keeps track of the frame number where a conversation started
3435 wireshark will still be able to keep the packets apart even though they do use
3436 the same socketpair.
3437                 (See packet-tftp.c and packet-snmp.c for examples of this)
3438
3439 There are two support routines that will allow the second port and/or
3440 address to be set later.
3441
3442 conversation_set_port2( conversation_t *conv, guint32 port);
3443 conversation_set_addr2( conversation_t *conv, address addr);
3444
3445 These routines will change the second address or port for the
3446 conversation.  So, the server port conversation will be converted into a
3447 more complete conversation definition.  Don't use these routines if you
3448 want to create a conversation between the server and client and retain the
3449 server port definition, you must create a new conversation.
3450
3451
3452 An example -
3453
3454 /* the handle for the dynamic dissector *
3455 static dissector_handle_t sub_dissector_handle;
3456
3457         ...
3458
3459 /* in the main protocol dissector, where the next dissector is setup */
3460
3461 /* if conversation has a data field, create it and load structure */
3462
3463         new_conv_info = se_alloc(sizeof(struct _new_conv_info));
3464         new_conv_info->data1 = value1;
3465
3466 /* create the conversation for the dynamic server address and port      */
3467 /* NOTE: The second address and port values don't matter because the    */
3468 /* NO_ADDR2 and NO_PORT2 options are set.                               */
3469
3470 /* First check if a conversation already exists for this
3471         IP/protocol/port
3472 */
3473         conversation = find_conversation(pinfo->fd->num,
3474                                 &server_src_addr, 0, protocol,
3475                                 server_src_port, 0, NO_ADDR2 | NO_PORT_B);
3476 /* If there is no such conversation, or if there is one but for
3477    someone else's protocol then we just create a new conversation
3478    and assign our protocol to it.
3479 */
3480         if ( (conversation == NULL) ||
3481              (conversation->dissector_handle != sub_dissector_handle) ) {
3482             conversation = conversation_new(pinfo->fd->num,
3483             &server_src_addr, 0, protocol,
3484             server_src_port, 0, new_conv_info, NO_ADDR2 | NO_PORT2);
3485
3486 /* set the dissector for the new conversation */
3487             conversation_set_dissector(conversation, sub_dissector_handle);
3488         }
3489
3490 2.5 Per-packet information.
3491
3492 Information can be stored for each data packet that is processed by the
3493 dissector.  The information is added with the p_add_proto_data function and
3494 retrieved with the p_get_proto_data function.  The data pointers passed into
3495 the p_add_proto_data are not managed by the proto_data routines. If you use
3496 malloc or any other dynamic memory allocation scheme, you must release the
3497 data when it isn't required.
3498
3499 void
3500 p_add_proto_data(frame_data *fd, int proto, void *proto_data)
3501 void *
3502 p_get_proto_data(frame_data *fd, int proto)
3503
3504 Where:
3505         fd         - The fd pointer in the pinfo structure, pinfo->fd
3506         proto      - Protocol id returned by the proto_register_protocol call
3507                      during initialization
3508         proto_data - pointer to the dissector data.
3509
3510
3511 2.6 User Preferences.
3512
3513 If the dissector has user options, there is support for adding these preferences
3514 to a configuration dialog.
3515
3516 You must register the module with the preferences routine with -
3517
3518        module_t *prefs_register_protocol(proto_id, void (*apply_cb)(void))
3519        or
3520        module_t *prefs_register_protocol_subtree(const char *subtree, int id,
3521               void (*apply_cb)(void));
3522
3523
3524 Where: proto_id   - the value returned by "proto_register_protocol()" when
3525                     the protocol was registered.
3526        apply_cb   - Callback routine that is called when preferences are
3527                     applied. It may be NULL, which inhibits the callback.
3528        subtree    - grouping preferences tree node name (several protocols can
3529                     be grouped under one preferences subtree)
3530
3531 Then you can register the fields that can be configured by the user with these
3532 routines -
3533
3534         /* Register a preference with an unsigned integral value. */
3535         void prefs_register_uint_preference(module_t *module, const char *name,
3536             const char *title, const char *description, guint base, guint *var);
3537
3538         /* Register a preference with an Boolean value. */
3539         void prefs_register_bool_preference(module_t *module, const char *name,
3540             const char *title, const char *description, gboolean *var);
3541
3542         /* Register a preference with an enumerated value. */
3543         void prefs_register_enum_preference(module_t *module, const char *name,
3544             const char *title, const char *description, gint *var,
3545             const enum_val_t *enumvals, gboolean radio_buttons)
3546
3547         /* Register a preference with a character-string value. */
3548         void prefs_register_string_preference(module_t *module, const char *name,
3549             const char *title, const char *description, char **var)
3550
3551         /* Register a preference with a range of unsigned integers (e.g.,
3552          * "1-20,30-40").
3553          */
3554         void prefs_register_range_preference(module_t *module, const char *name,
3555             const char *title, const char *description, range_t *var,
3556             guint32 max_value)
3557
3558 Where: module - Returned by the prefs_register_protocol routine
3559          name     - This is appended to the name of the protocol, with a
3560                     "." between them, to construct a name that identifies
3561                     the field in the preference file; the name itself
3562                     should not include the protocol name, as the name in
3563                     the preference file will already have it
3564          title    - Field title in the preferences dialog
3565          description - Comments added to the preference file above the
3566                        preference value
3567          var      - pointer to the storage location that is updated when the
3568                     field is changed in the preference dialog box.  Note that
3569                     with string preferences the given pointer is overwritten
3570                     with a pointer to a new copy of the string during the
3571                     preference registration.  The passed-in string may be
3572                     freed, but you must keep another pointer to the string
3573                     in order to free it.
3574          base     - Base that the unsigned integer is expected to be in,
3575                     see strtoul(3).
3576          enumvals - an array of enum_val_t structures.  This must be
3577                     NULL-terminated; the members of that structure are:
3578
3579                         a short name, to be used with the "-o" flag - it
3580                         should not contain spaces or upper-case letters,
3581                         so that it's easier to put in a command line;
3582
3583                         a description, which is used in the GUI (and
3584                         which, for compatibility reasons, is currently
3585                         what's written to the preferences file) - it can
3586                         contain spaces, capital letters, punctuation,
3587                         etc.;
3588
3589                         the numerical value corresponding to that name
3590                         and description
3591          radio_buttons - TRUE if the field is to be displayed in the
3592                          preferences dialog as a set of radio buttons,
3593                          FALSE if it is to be displayed as an option
3594                          menu
3595          max_value - The maximum allowed value for a range (0 is the minimum).
3596
3597 An example from packet-beep.c -
3598
3599   proto_beep = proto_register_protocol("Blocks Extensible Exchange Protocol",
3600                                        "BEEP", "beep");
3601
3602         ...
3603
3604   /* Register our configuration options for BEEP, particularly our port */
3605
3606   beep_module = prefs_register_protocol(proto_beep, proto_reg_handoff_beep);
3607
3608   prefs_register_uint_preference(beep_module, "tcp.port", "BEEP TCP Port",
3609                                  "Set the port for BEEP messages (if other"
3610                                  " than the default of 10288)",
3611                                  10, &global_beep_tcp_port);
3612
3613   prefs_register_bool_preference(beep_module, "strict_header_terminator",
3614                                  "BEEP Header Requires CRLF",
3615                                  "Specifies that BEEP requires CRLF as a "
3616                                  "terminator, and not just CR or LF",
3617                                  &global_beep_strict_term);
3618
3619 This will create preferences "beep.tcp.port" and
3620 "beep.strict_header_terminator", the first of which is an unsigned
3621 integer and the second of which is a Boolean.
3622
3623 Note that a warning will pop up if you've saved such preference to the
3624 preference file and you subsequently take the code out. The way to make
3625 a preference obsolete is to register it as such:
3626
3627 /* Register a preference that used to be supported but no longer is. */
3628         void prefs_register_obsolete_preference(module_t *module,
3629             const char *name);
3630
3631 2.7 Reassembly/desegmentation for protocols running atop TCP.
3632
3633 There are two main ways of reassembling a Protocol Data Unit (PDU) which
3634 spans across multiple TCP segments.  The first approach is simpler, but
3635 assumes you are running atop of TCP when this occurs (but your dissector
3636 might run atop of UDP, too, for example), and that your PDUs consist of a
3637 fixed amount of data that includes enough information to determine the PDU
3638 length, possibly followed by additional data.  The second method is more
3639 generic but requires more code and is less efficient.
3640
3641 2.7.1 Using tcp_dissect_pdus().
3642
3643 For the first method, you register two different dissection methods, one
3644 for the TCP case, and one for the other cases.  It is a good idea to
3645 also have a dissect_PROTO_common function which will parse the generic
3646 content that you can find in all PDUs which is called from
3647 dissect_PROTO_tcp when the reassembly is complete and from
3648 dissect_PROTO_udp (or dissect_PROTO_other).
3649
3650 To register the distinct dissector functions, consider the following
3651 example, stolen from packet-dns.c:
3652
3653         dissector_handle_t dns_udp_handle;
3654         dissector_handle_t dns_tcp_handle;
3655         dissector_handle_t mdns_udp_handle;
3656
3657         dns_udp_handle = create_dissector_handle(dissect_dns_udp,
3658             proto_dns);
3659         dns_tcp_handle = create_dissector_handle(dissect_dns_tcp,
3660             proto_dns);
3661         mdns_udp_handle = create_dissector_handle(dissect_mdns_udp,
3662             proto_dns);
3663
3664         dissector_add("udp.port", UDP_PORT_DNS, dns_udp_handle);
3665         dissector_add("tcp.port", TCP_PORT_DNS, dns_tcp_handle);
3666         dissector_add("udp.port", UDP_PORT_MDNS, mdns_udp_handle);
3667         dissector_add("tcp.port", TCP_PORT_MDNS, dns_tcp_handle);
3668
3669 The dissect_dns_udp function does very little work and calls
3670 dissect_dns_common, while dissect_dns_tcp calls tcp_dissect_pdus with a
3671 reference to a callback which will be called with reassembled data:
3672
3673         static void
3674         dissect_dns_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
3675         {
3676                 tcp_dissect_pdus(tvb, pinfo, tree, dns_desegment, 2,
3677                     get_dns_pdu_len, dissect_dns_tcp_pdu);
3678         }
3679
3680 (The dissect_dns_tcp_pdu function acts similarly to dissect_dns_udp.)
3681 The arguments to tcp_dissect_pdus are:
3682
3683         the tvbuff pointer, packet_info pointer, and proto_tree pointer
3684         passed to the dissector;
3685
3686         a gboolean flag indicating whether desegmentation is enabled for
3687         your protocol;
3688
3689         the number of bytes of PDU data required to determine the length
3690         of the PDU;
3691
3692         a routine that takes as arguments a packet_info pointer, a tvbuff
3693         pointer and an offset value representing the offset into the tvbuff
3694         at which a PDU begins and should return - *without* throwing an
3695         exception (it is guaranteed that the number of bytes specified by the
3696         previous argument to tcp_dissect_pdus is available, but more data
3697         might not be available, so don't refer to any data past that) - the
3698         total length of the PDU, in bytes;
3699
3700         a routine that's passed a tvbuff pointer, packet_info pointer,
3701         and proto_tree pointer, with the tvbuff containing a
3702         possibly-reassembled PDU, and that should dissect that PDU.
3703
3704 2.7.2 Modifying the pinfo struct.
3705
3706 The second reassembly mode is preferred when the dissector cannot determine
3707 how many bytes it will need to read in order to determine the size of a PDU.
3708 It may also be useful if your dissector needs to support reassembly from
3709 protocols other than TCP.
3710
3711 Your dissect_PROTO will initially be passed a tvbuff containing the payload of
3712 the first packet. It should dissect as much data as it can, noting that it may
3713 contain more than one complete PDU. If the end of the provided tvbuff coincides
3714 with the end of a PDU then all is well and your dissector can just return as
3715 normal. (If it is a new-style dissector, it should return the number of bytes
3716 successfully processed.)
3717
3718 If the dissector discovers that the end of the tvbuff does /not/ coincide with
3719 the end of a PDU, (ie, there is half of a PDU at the end of the tvbuff), it can
3720 indicate this to the parent dissector, by updating the pinfo struct. The
3721 desegment_offset field is the offset in the tvbuff at which the dissector will
3722 continue processing when next called.  The desegment_len field should contain
3723 the estimated number of additional bytes required for completing the PDU.  Next
3724 time your dissect_PROTO is called, it will be passed a tvbuff composed of the
3725 end of the data from the previous tvbuff together with desegment_len more bytes.
3726
3727 If the dissector cannot tell how many more bytes it will need, it should set
3728 desegment_len=DESEGMENT_ONE_MORE_SEGMENT; it will then be called again as soon
3729 as any more data becomes available. Dissectors should set the desegment_len to a
3730 reasonable value when possible rather than always setting
3731 DESEGMENT_ONE_MORE_SEGMENT as it will generally be more efficient. Also, you
3732 *must not* set desegment_len=1 in this case, in the hope that you can change
3733 your mind later: once you return a positive value from desegment_len, your PDU
3734 boundary is set in stone.
3735
3736 static hf_register_info hf[] = {
3737     {&hf_cstring,
3738      {"C String", "c.string", FT_STRING, BASE_NONE, NULL, 0x0,
3739       NULL, HFILL}
3740      }
3741    };
3742
3743 /**
3744 *   Dissect a buffer containing C strings.
3745 *
3746 *   @param  tvb     The buffer to dissect.
3747 *   @param  pinfo   Packet Info.
3748 *   @param  tree    The protocol tree.
3749 **/
3750 static void dissect_cstr(tvbuff_t * tvb, packet_info * pinfo, proto_tree * tree)
3751 {
3752     guint offset = 0;
3753     while(offset < tvb_reported_length(tvb)) {
3754         gint available = tvb_reported_length_remaining(tvb, offset);
3755         gint len = tvb_strnlen(tvb, offset, available);
3756
3757         if( -1 == len ) {
3758             /* we ran out of data: ask for more */
3759             pinfo->desegment_offset = offset;
3760             pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
3761             return;
3762         }
3763
3764         col_set_str(pinfo->cinfo, COL_INFO, "C String");
3765
3766         len += 1; /* Add one for the '\0' */
3767
3768         if (tree) {
3769             proto_tree_add_item(tree, hf_cstring, tvb, offset, len,
3770                                 ENC_NA);
3771         }
3772         offset += (guint)len;
3773     }
3774
3775     /* if we get here, then the end of the tvb coincided with the end of a
3776        string. Happy days. */
3777 }
3778
3779 This simple dissector will repeatedly return DESEGMENT_ONE_MORE_SEGMENT
3780 requesting more data until the tvbuff contains a complete C string. The C string
3781 will then be added to the protocol tree. Note that there may be more
3782 than one complete C string in the tvbuff, so the dissection is done in a
3783 loop.
3784
3785 2.8 ptvcursors.
3786
3787 The ptvcursor API allows a simpler approach to writing dissectors for
3788 simple protocols. The ptvcursor API works best for protocols whose fields
3789 are static and whose format does not depend on the value of other fields.
3790 However, even if only a portion of your protocol is statically defined,
3791 then that portion could make use of ptvcursors.
3792
3793 The ptvcursor API lets you extract data from a tvbuff, and add it to a
3794 protocol tree in one step. It also keeps track of the position in the
3795 tvbuff so that you can extract data again without having to compute any
3796 offsets --- hence the "cursor" name of the API.
3797
3798 The three steps for a simple protocol are:
3799     1. Create a new ptvcursor with ptvcursor_new()
3800     2. Add fields with multiple calls of ptvcursor_add()
3801     3. Delete the ptvcursor with ptvcursor_free()
3802
3803 ptvcursor offers the possibility to add subtrees in the tree as well. It can be
3804 done in very simple steps :
3805     1. Create a new subtree with ptvcursor_push_subtree(). The old subtree is
3806        pushed in a stack and the new subtree will be used by ptvcursor.
3807     2. Add fields with multiple calls of ptvcursor_add(). The fields will be
3808        added in the new subtree created at the previous step.
3809     3. Pop the previous subtree with ptvcursor_pop_subtree(). The previous
3810        subtree is again used by ptvcursor.
3811 Note that at the end of the parsing of a packet you must have popped each
3812 subtree you pushed. If it's not the case, the dissector will generate an error.
3813
3814 To use the ptvcursor API, include the "ptvcursor.h" file. The PGM dissector
3815 is an example of how to use it. You don't need to look at it as a guide;
3816 instead, the API description here should be good enough.
3817
3818 2.8.1 ptvcursor API.
3819
3820 ptvcursor_t*
3821 ptvcursor_new(proto_tree* tree, tvbuff_t* tvb, gint offset)
3822     This creates a new ptvcursor_t object for iterating over a tvbuff.
3823 You must call this and use this ptvcursor_t object so you can use the
3824 ptvcursor API.
3825
3826 proto_item*
3827 ptvcursor_add(ptvcursor_t* ptvc, int hf, gint length, gboolean endianness)
3828     This will extract 'length' bytes from the tvbuff and place it in
3829 the proto_tree as field 'hf', which is a registered header_field. The
3830 pointer to the proto_item that is created is passed back to you. Internally,
3831 the ptvcursor advances its cursor so the next call to ptvcursor_add
3832 starts where this call finished. The 'endianness' parameter matters for
3833 FT_UINT* and FT_INT* fields.
3834
3835 proto_item*
3836 ptvcursor_add_no_advance(ptvcursor_t* ptvc, int hf, gint length, gboolean endianness)
3837     Like ptvcursor_add, but does not advance the internal cursor.
3838
3839 void
3840 ptvcursor_advance(ptvcursor_t* ptvc, gint length)
3841     Advances the internal cursor without adding anything to the proto_tree.
3842
3843 void
3844 ptvcursor_free(ptvcursor_t* ptvc)
3845     Frees the memory associated with the ptvcursor. You must call this
3846 after your dissection with the ptvcursor API is completed.
3847
3848
3849 proto_tree*
3850 ptvcursor_push_subtree(ptvcursor_t* ptvc, proto_item* it, gint ett_subtree)
3851     Pushes the current subtree in the tree stack of the cursor, creates a new
3852 one and sets this one as the working tree.
3853
3854 void
3855 ptvcursor_pop_subtree(ptvcursor_t* ptvc);
3856     Pops a subtree in the tree stack of the cursor
3857
3858 proto_tree*
3859 ptvcursor_add_with_subtree(ptvcursor_t* ptvc, int hfindex, gint length,
3860                             gboolean little_endian, gint ett_subtree);
3861     Adds an item to the tree and creates a subtree.
3862 If the length is unknown, length may be defined as SUBTREE_UNDEFINED_LENGTH.
3863 In this case, at the next pop, the item length will be equal to the advancement
3864 of the cursor since the creation of the subtree.
3865
3866 proto_tree*
3867 ptvcursor_add_text_with_subtree(ptvcursor_t* ptvc, gint length,
3868                                 gint ett_subtree, const char* format, ...);
3869     Add a text node to the tree and create a subtree.
3870 If the length is unknown, length may be defined as SUBTREE_UNDEFINED_LENGTH.
3871 In this case, at the next pop, the item length will be equal to the advancement
3872 of the cursor since the creation of the subtree.
3873
3874 2.8.2 Miscellaneous functions.
3875
3876 tvbuff_t*
3877 ptvcursor_tvbuff(ptvcursor_t* ptvc)
3878     Returns the tvbuff associated with the ptvcursor.
3879
3880 gint
3881 ptvcursor_current_offset(ptvcursor_t* ptvc)
3882     Returns the current offset.
3883
3884 proto_tree*
3885 ptvcursor_tree(ptvcursor_t* ptvc)
3886     Returns the proto_tree associated with the ptvcursor.
3887
3888 void
3889 ptvcursor_set_tree(ptvcursor_t* ptvc, proto_tree *tree)
3890     Sets a new proto_tree for the ptvcursor.
3891
3892 proto_tree*
3893 ptvcursor_set_subtree(ptvcursor_t* ptvc, proto_item* it, gint ett_subtree);
3894     Creates a subtree and adds it to the cursor as the working tree but does
3895 not save the old working tree.
3896