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