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