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