3 This file is a HOWTO for Wireshark developers. It describes how to start coding
4 a Wireshark protocol dissector and the use of some of the important functions
7 This file is compiled to give in depth information on Wireshark.
8 It is by no means all inclusive and complete. Please feel free to send
9 remarks and patches to the developer mailing list.
13 Before starting to develop a new dissector, a "running" Wireshark build
14 environment is required - there's no such thing as a standalone "dissector
17 How to setup such an environment is platform dependent, detailed information
18 about these steps can be found in the "Developer's Guide" (available from:
19 http://www.wireshark.org) and in the INSTALL and README files of the sources
22 0.1. General README files.
24 You'll find additional information in the following README files:
26 - README.capture - the capture engine internals
27 - README.design - Wireshark software design - incomplete
28 - README.developer - this file
29 - README.display_filter - Display Filter Engine
30 - README.idl2wrs - CORBA IDL converter
31 - README.packaging - how to distribute a software package containing WS
32 - README.regression - regression testing of WS and TS
33 - README.stats_tree - a tree statistics counting specific packets
34 - README.tapping - "tap" a dissector to get protocol specific events
35 - README.xml-output - how to work with the PDML exported output
36 - wiretap/README.developer - how to add additional capture file types to
39 0.2. Dissector related README files.
41 You'll find additional dissector related information in the following README
44 - README.binarytrees - fast access to large data collections
45 - README.malloc - how to obtain "memory leak free" memory
46 - README.plugins - how to "pluginize" a dissector
47 - README.request_response_tracking - how to track req./resp. times and such
51 James Coe <jammer[AT]cin.net>
52 Gilbert Ramirez <gram[AT]alumni.rice.edu>
53 Jeff Foster <jfoste[AT]woodward.com>
54 Olivier Abad <oabad[AT]cybercable.fr>
55 Laurent Deniel <laurent.deniel[AT]free.fr>
56 Gerald Combs <gerald[AT]wireshark.org>
57 Guy Harris <guy[AT]alum.mit.edu>
58 Ulf Lamping <ulf.lamping[AT]web.de>
60 1. Setting up your protocol dissector code.
62 This section provides skeleton code for a protocol dissector. It also explains
63 the basic functions needed to enter values in the traffic summary columns,
64 add to the protocol tree, and work with registered header fields.
70 Wireshark runs on many platforms, and can be compiled with a number of
71 different compilers; here are some rules for writing code that will work
72 on multiple platforms.
74 Don't use C++-style comments (comments beginning with "//" and running
75 to the end of the line); Wireshark's dissectors are written in C, and
76 thus run through C rather than C++ compilers, and not all C compilers
77 support C++-style comments (GCC does, but IBM's C compiler for AIX, for
78 example, doesn't do so by default).
80 Don't initialize variables in their declaration with non-constant
81 values. Not all compilers support this. E.g. don't use
82 guint32 i = somearray[2];
88 Don't use zero-length arrays; not all compilers support them. If an
89 array would have no members, just leave it out.
91 Don't declare variables in the middle of executable code; not all C
92 compilers support that. Variables should be declared outside a
93 function, or at the beginning of a function or compound statement.
95 Don't use anonymous unions; not all compilers support it.
102 } u; /* have a name here */
105 Don't use "uchar", "u_char", "ushort", "u_short", "uint", "u_int",
106 "ulong", "u_long" or "boolean"; they aren't defined on all platforms.
107 If you want an 8-bit unsigned quantity, use "guint8"; if you want an
108 8-bit character value with the 8th bit not interpreted as a sign bit,
109 use "guchar"; if you want a 16-bit unsigned quantity, use "guint16";
110 if you want a 32-bit unsigned quantity, use "guint32"; and if you want
111 an "int-sized" unsigned quantity, use "guint"; if you want a boolean,
112 use "gboolean". Use "%d", "%u", "%x", and "%o" to print those types;
113 don't use "%ld", "%lu", "%lx", or "%lo", as longs are 64 bits long on
114 many platforms, but "guint32" is 32 bits long.
116 Don't use "long" to mean "signed 32-bit integer", and don't use
117 "unsigned long" to mean "unsigned 32-bit integer"; "long"s are 64 bits
118 long on many platforms. Use "gint32" for signed 32-bit integers and use
119 "guint32" for unsigned 32-bit integers.
121 Don't use "long" to mean "signed 64-bit integer" and don't use "unsigned
122 long" to mean "unsigned 64-bit integer"; "long"s are 32 bits long on
123 many other platforms. Don't use "long long" or "unsigned long long",
124 either, as not all platforms support them; use "gint64" or "guint64",
125 which will be defined as the appropriate types for 64-bit signed and
128 When printing or displaying the values of 64-bit integral data types,
129 don't assume use "%lld", "%llu", "%llx", or "%llo" - not all platforms
130 support "%ll" for printing 64-bit integral data types. Instead, for
131 GLib routines, and routines that use them, such as all the routines in
132 Wireshark that take format arguments, use G_GINT64_MODIFIER, for example:
134 proto_tree_add_text(tree, tvb, offset, 8,
135 "Sequence Number: %" G_GINT64_MODIFIER "u",
138 When using standard C routines, such as printf and scanf, use
139 PRId64, PRIu64, PRIx64, PRIX64, and PRIo64, for example:
141 printf("Sequence Number: %" PRIu64 "\n", sequence_number);
143 When specifying an integral constant that doesn't fit in 32 bits, don't
144 use "LL" at the end of the constant - not all compilers use "LL" for
145 that. Instead, put the constant in a call to the "G_GINT64_CONSTANT()"
148 G_GINT64_CONSTANT(11644473600U)
154 Don't use a label without a statement following it. For example,
164 will not work with all compilers - you have to do
174 with some statement, even if it's a null statement, after the label.
176 Don't use "bzero()", "bcopy()", or "bcmp()"; instead, use the ANSI C
179 "memset()" (with zero as the second argument, so that it sets
180 all the bytes to zero);
182 "memcpy()" or "memmove()" (note that the first and second
183 arguments to "memcpy()" are in the reverse order to the
184 arguments to "bcopy()"; note also that "bcopy()" is typically
185 guaranteed to work on overlapping memory regions, while
186 "memcpy()" isn't, so if you may be copying from one region to a
187 region that overlaps it, use "memmove()", not "memcpy()" - but
188 "memcpy()" might be faster as a result of not guaranteeing
189 correct operation on overlapping memory regions);
191 and "memcmp()" (note that "memcmp()" returns 0, 1, or -1, doing
192 an ordered comparison, rather than just returning 0 for "equal"
193 and 1 for "not equal", as "bcmp()" does).
195 Not all platforms necessarily have "bzero()"/"bcopy()"/"bcmp()", and
196 those that do might not declare them in the header file on which they're
197 declared on your platform.
199 Don't use "index()" or "rindex()"; instead, use the ANSI C equivalents,
200 "strchr()" and "strrchr()". Not all platforms necessarily have
201 "index()" or "rindex()", and those that do might not declare them in the
202 header file on which they're declared on your platform.
204 Don't fetch data from packets by getting a pointer to data in the packet
205 with "tvb_get_ptr()", casting that pointer to a pointer to a structure,
206 and dereferencing that pointer. That pointer won't necessarily be aligned
207 on the proper boundary, which can cause crashes on some platforms (even
208 if it doesn't crash on an x86-based PC); furthermore, the data in a
209 packet is not necessarily in the byte order of the machine on which
210 Wireshark is running. Use the tvbuff routines to extract individual
211 items from the packet, or use "proto_tree_add_item()" and let it extract
214 Don't use structures that overlay packet data, or into which you copy
215 packet data; the C programming language does not guarantee any
216 particular alignment of fields within a structure, and even the
217 extensions that try to guarantee that are compiler-specific and not
218 necessarily supported by all compilers used to build Wireshark. Using
219 bitfields in those structures is even worse; the order of bitfields
222 Don't use "ntohs()", "ntohl()", "htons()", or "htonl()"; the header
223 files required to define or declare them differ between platforms, and
224 you might be able to get away with not including the appropriate header
225 file on your platform but that might not work on other platforms.
226 Instead, use "g_ntohs()", "g_ntohl()", "g_htons()", and "g_htonl()";
227 those are declared by <glib.h>, and you'll need to include that anyway,
228 as Wireshark header files that all dissectors must include use stuff from
231 Don't fetch a little-endian value using "tvb_get_ntohs() or
232 "tvb_get_ntohl()" and then using "g_ntohs()", "g_htons()", "g_ntohl()",
233 or "g_htonl()" on the resulting value - the g_ routines in question
234 convert between network byte order (big-endian) and *host* byte order,
235 not *little-endian* byte order; not all machines on which Wireshark runs
236 are little-endian, even though PCs are. Fetch those values using
237 "tvb_get_letohs()" and "tvb_get_letohl()".
239 Don't put a comma after the last element of an enum - some compilers may
240 either warn about it (producing extra noise) or refuse to accept it.
242 Don't include <unistd.h> without protecting it with
250 and, if you're including it to get routines such as "open()", "close()",
251 "read()", and "write()" declared, also include <io.h> if present:
257 in order to declare the Windows C library routines "_open()",
258 "_close()", "_read()", and "_write()". Your file must include <glib.h>
259 - which many of the Wireshark header files include, so you might not have
260 to include it explicitly - in order to get "open()", "close()",
261 "read()", "write()", etc. mapped to "_open()", "_close()", "_read()",
264 Do not use "open()", "rename()", "mkdir()", "stat()", "unlink()", "remove()",
265 "fopen()", "freopen()" directly. Instead use "eth_open()", "eth_rename()",
266 "eth_mkdir()", "eth_stat()", "eth_unlink()", "eth_remove()", "eth_fopen()",
267 "eth_freopen()": these wrapper functions change the path and file name from
268 UTF8 to UTF16 on Windows allowing the functions to work correctly when the
269 path or file name contain non-ASCII characters.
271 When opening a file with "eth_fopen()", "eth_freopen()", or "eth_fdopen()", if
272 the file contains ASCII text, use "r", "w", "a", and so on as the open mode
273 - but if it contains binary data, use "rb", "wb", and so on. On
274 Windows, if a file is opened in a text mode, writing a byte with the
275 value of octal 12 (newline) to the file causes two bytes, one with the
276 value octal 15 (carriage return) and one with the value octal 12, to be
277 written to the file, and causes bytes with the value octal 15 to be
278 discarded when reading the file (to translate between C's UNIX-style
279 lines that end with newline and Windows' DEC-style lines that end with
280 carriage return/line feed).
282 In addition, that also means that when opening or creating a binary
283 file, you must use "eth_open()" (with O_CREAT and possibly O_TRUNC if the
284 file is to be created if it doesn't exist), and OR in the O_BINARY flag.
285 That flag is not present on most, if not all, UNIX systems, so you must
292 to properly define it for UNIX (it's not necessary on UNIX).
294 Don't use forward declarations of static arrays without a specified size
295 in a fashion such as this:
297 static const value_string foo_vals[];
301 static const value_string foo_vals[] = {
308 as some compilers will reject the first of those statements. Instead,
309 initialize the array at the point at which it's first declared, so that
312 Don't put a comma after the last tuple of an initializer of an array.
314 For #define names and enum member names, prefix the names with a tag so
315 as to avoid collisions with other names - this might be more of an issue
316 on Windows, as it appears to #define names such as DELETE and
319 Don't use the "numbered argument" feature that many UNIX printf's
322 g_snprintf(add_string, 30, " - (%1$d) (0x%1$04x)", value);
324 as not all UNIX printf's implement it, and Windows printf doesn't appear
325 to implement it. Use something like
327 g_snprintf(add_string, 30, " - (%d) (0x%04x)", value, value);
331 Don't use "variadic macros", such as
333 #define DBG(format, args...) fprintf(stderr, format, ## args)
335 as not all C compilers support them. Use macros that take a fixed
336 number of arguments, such as
338 #define DBG0(format) fprintf(stderr, format)
339 #define DBG1(format, arg1) fprintf(stderr, format, arg1)
340 #define DBG2(format, arg1, arg2) fprintf(stderr, format, arg1, arg2)
346 #define DBG(args) printf args
352 as that's not supported by all compilers.
354 snprintf() -> g_snprintf()
355 snprintf() is not available on all platforms, so it's a good idea to use the
356 g_snprintf() function declared by <glib.h> instead.
358 tmpnam() -> mkstemp()
359 tmpnam is insecure and should not be used any more. Wireshark brings its
360 own mkstemp implementation for use on platforms that lack mkstemp.
361 Note: mkstemp does not accept NULL as a parameter.
363 The pointer returned by a call to "tvb_get_ptr()" is not guaranteed to be
364 aligned on any particular byte boundary; this means that you cannot
365 safely cast it to any data type other than a pointer to "char",
366 "unsigned char", "guint8", or other one-byte data types. You cannot,
367 for example, safely cast it to a pointer to a structure, and then access
368 the structure members directly; on some systems, unaligned accesses to
369 integral data types larger than 1 byte, and floating-point data types,
370 cause a trap, which will, at best, result in the OS slowly performing an
371 unaligned access for you, and will, on at least some platforms, cause
372 the program to be terminated.
374 Wireshark supports both platforms with GLib 1.2[.x]/GTK+ 1.2[.x] and GLib
375 2.x/GTK+ 1.3[.x] and 2.x. If at all possible, either use only
376 mechanisms that are present in GLib 1.2[.x] and GTK+ 1.2[.x], use #if's
377 to conditionally use older or newer mechanisms depending on the platform
378 on which Wireshark is being built, or, if the code in GLib or GTK+ that
379 implements that mechanism will build with GLib 1.2[.x]/GTK+ 1.2[.x],
380 conditionally include that code as part of the Wireshark source and use
381 the included version with GLib 1.2[.x] or GTK+ 1.2[.x]. In particular,
382 if the GLib 2.x or GTK+ 2.x mechanism indicates that a routine is
383 deprecated and shouldn't be used in new code, and that it was renamed in
384 GLib 2.x or GTK+ 2.x and the new name should be used, disregard that and
385 use the old name - it'll still work with GLib 2.x or GTK+ 2.x, but will
386 also work with GLib 1.2[.x] and GTK+ 1.2[.x].
388 When different code must be used on UN*X and Win32, use a #if or #ifdef
389 that tests _WIN32, not WIN32. Try to write code portably whenever
390 possible, however; note that there are some routines in Wireshark with
391 platform-dependent implementations and platform-independent APIs, such
392 as the routines in epan/filesystem.c, allowing the code that calls it to
393 be written portably without #ifdefs.
395 1.1.2 String handling
397 Do not use functions such as strcat() or strcpy().
398 A lot of work has been done to remove the existing calls to these functions and
399 we do not want any new callers of these functions.
401 Instead use g_snprintf() since that function will if used correctly prevent
402 buffer overflows for large strings.
404 When using a buffer to create a string, do not use a buffer stored on the stack.
405 I.e. do not use a buffer declared as
407 instead allocate a buffer dynamically using the emem routines (see
408 README.malloc) such as
411 #define MAX_BUFFER 1024
412 buffer=ep_alloc(MAX_BUFFER);
415 g_snprintf(buffer, MAX_BUFFER, ...
417 This avoids the stack from being corrupted in case there is a bug in your code
418 that accidentally writes beyond the end of the buffer.
421 If you write a routine that will create and return a pointer to a filled in
422 string and if that buffer will not be further processed or appended to after
423 the routine returns (except being added to the proto tree),
424 do not preallocate the buffer to fill in and pass as a parameter instead
425 pass a pointer to a pointer to the function and return a pointer to an
426 emem allocated buffer that will be automatically freed. (see README.malloc)
428 I.e. do not write code such as
430 foo_to_str(char *string, ... ){
436 foo_to_str(buffer, ...
437 proto_tree_add_text(... buffer ...
439 instead write the code as
441 foo_to_str(char **buffer, ...
443 *buffer=ep_alloc(MAX_BUFFER);
449 foo_to_str(&buffer, ...
450 proto_tree_add_text(... *buffer ...
452 Use ep_ allocated buffers. They are very fast and nice. These buffers are all
453 automatically free()d when the dissection of the current packet ends so you
454 don't have to worry about free()ing them explicitly in order to not leak memory.
455 Please read README.malloc.
457 When using g_strsplit() from glib, place an #include <epan/ws_strsplit.h> at
458 the top of your file. This file will leave in place g_strsplit() when using
459 GTK/GLib v2 and replace it with GLib v2 code when compiling for GTK/GLib 1.
460 This is necessary because the GLib v1 version of g_strsplit is known to be
461 buggy. In either case, you will still use the g_strsplit() function name
462 as usual in your code.
466 Wireshark is not guaranteed to read only network traces that contain correctly-
467 formed packets. Wireshark is commonly used is to track down networking
468 problems, and the problems might be due to a buggy protocol implementation
469 sending out bad packets.
471 Therefore, protocol dissectors not only have to be able to handle
472 correctly-formed packets without, for example, crashing or looping
473 infinitely, they also have to be able to handle *incorrectly*-formed
474 packets without crashing or looping infinitely.
476 Here are some suggestions for making dissectors more robust in the face
477 of incorrectly-formed packets:
479 Do *NOT* use "g_assert()" or "g_assert_not_reached()" in dissectors.
480 *NO* value in a packet's data should be considered "wrong" in the sense
481 that it's a problem with the dissector if found; if it cannot do
482 anything else with a particular value from a packet's data, the
483 dissector should put into the protocol tree an indication that the
484 value is invalid, and should return. You can use the DISSECTOR_ASSERT
485 macro for that purpose.
487 If you are allocating a chunk of memory to contain data from a packet,
488 or to contain information derived from data in a packet, and the size of
489 the chunk of memory is derived from a size field in the packet, make
490 sure all the data is present in the packet before allocating the buffer.
493 1) Wireshark won't leak that chunk of memory if an attempt to
494 fetch data not present in the packet throws an exception
498 2) it won't crash trying to allocate an absurdly-large chunk of
499 memory if the size field has a bogus large value.
501 If you're fetching into such a chunk of memory a string from the buffer,
502 and the string has a specified size, you can use "tvb_get_*_string()",
503 which will check whether the entire string is present before allocating
504 a buffer for the string, and will also put a trailing '\0' at the end of
507 If you're fetching into such a chunk of memory a 2-byte Unicode string
508 from the buffer, and the string has a specified size, you can use
509 "tvb_get_ephemeral_faked_unicode()", which will check whether the entire
510 string is present before allocating a buffer for the string, and will also
511 put a trailing '\0' at the end of the buffer. The resulting string will be
512 a sequence of single-byte characters; the only Unicode characters that
513 will be handled correctly are those in the ASCII range. (Wireshark's
514 ability to handle non-ASCII strings is limited; it needs to be
517 If you're fetching into such a chunk of memory a sequence of bytes from
518 the buffer, and the sequence has a specified size, you can use
519 "tvb_memdup()", which will check whether the entire sequence is present
520 before allocating a buffer for it.
522 Otherwise, you can check whether the data is present by using
523 "tvb_ensure_bytes_exist()" or by getting a pointer to the data by using
524 "tvb_get_ptr()", although note that there might be problems with using
525 the pointer from "tvb_get_ptr()" (see the item on this in the
526 Portability section above, and the next item below).
528 Note also that you should only fetch string data into a fixed-length
529 buffer if the code ensures that no more bytes than will fit into the
530 buffer are fetched ("the protocol ensures" isn't good enough, as
531 protocol specifications can't ensure only packets that conform to the
532 specification will be transmitted or that only packets for the protocol
533 in question will be interpreted as packets for that protocol by
534 Wireshark). If there's no maximum length of string data to be fetched,
535 routines such as "tvb_get_*_string()" are safer, as they allocate a buffer
536 large enough to hold the string. (Note that some variants of this call
537 require you to free the string once you're finished with it.)
539 If you have gotten a pointer using "tvb_get_ptr()", you must make sure
540 that you do not refer to any data past the length passed as the last
541 argument to "tvb_get_ptr()"; while the various "tvb_get" routines
542 perform bounds checking and throw an exception if you refer to data not
543 available in the tvbuff, direct references through a pointer gotten from
544 "tvb_get_ptr()" do not do any bounds checking.
546 If you have a loop that dissects a sequence of items, each of which has
547 a length field, with the offset in the tvbuff advanced by the length of
548 the item, then, if the length field is the total length of the item, and
549 thus can be zero, you *MUST* check for a zero-length item and abort the
550 loop if you see one. Otherwise, a zero-length item could cause the
551 dissector to loop infinitely. You should also check that the offset,
552 after having the length added to it, is greater than the offset before
553 the length was added to it, if the length field is greater than 24 bits
554 long, so that, if the length value is *very* large and adding it to the
555 offset causes an overflow, that overflow is detected.
557 If you are fetching a length field from the buffer, corresponding to the
558 length of a portion of the packet, and subtracting from that length a
559 value corresponding to the length of, for example, a header in the
560 packet portion in question, *ALWAYS* check that the value of the length
561 field is greater than or equal to the length you're subtracting from it,
562 and report an error in the packet and stop dissecting the packet if it's
563 less than the length you're subtracting from it. Otherwise, the
564 resulting length value will be negative, which will either cause errors
565 in the dissector or routines called by the dissector, or, if the value
566 is interpreted as an unsigned integer, will cause the value to be
567 interpreted as a very large positive value.
569 Any tvbuff offset that is added to as processing is done on a packet
570 should be stored in a 32-bit variable, such as an "int"; if you store it
571 in an 8-bit or 16-bit variable, you run the risk of the variable
574 sprintf() -> g_snprintf()
575 Prevent yourself from using the sprintf() function, as it does not test the
576 length of the given output buffer and might be writing into unintended memory
577 areas. This function is one of the main causes of security problems like buffer
578 exploits and many other bugs that are very hard to find. It's much better to
579 use the g_snprintf() function declared by <glib.h> instead.
581 You should test your dissector against incorrectly-formed packets. This
582 can be done using the randpkt and editcap utilities that come with the
583 Wireshark distribution. Testing using randpkt can be done by generating
584 output at the same layer as your protocol, and forcing Wireshark/TShark
585 to decode it as your protocol, e.g. if your protocol sits on top of UDP:
587 randpkt -c 50000 -t dns randpkt.pcap
588 tshark -nVr randpkt.pcap -d udp.port==53,<myproto>
590 Testing using editcap can be done using preexisting capture files and the
591 "-E" flag, which introduces errors in a capture file. E.g.:
593 editcap -E 0.03 infile.pcap outfile.pcap
594 tshark -nVr outfile.pcap
596 The script fuzz-test.sh is available to help automate these tests.
598 1.1.4 Name convention.
600 Wireshark uses the underscore_convention rather than the InterCapConvention for
601 function names, so new code should probably use underscores rather than
602 intercaps for functions and variable names. This is especially important if you
603 are writing code that will be called from outside your code. We are just
604 trying to keep things consistent for other developers.
606 1.1.5 White space convention.
608 Avoid using tab expansions different from 8 column widths, as not all
609 text editors in use by the developers support this. For a detailed
610 discussion of tabs, spaces, and indentation, see
612 http://www.jwz.org/doc/tabs-vs-spaces.html
614 When creating a new file, you are free to choose an indentation logic.
615 Most of the files in Wireshark tend to use 2-space or 4-space
616 indentation. You are encouraged to write a short comment on the
617 indentation logic at the beginning of this new file, especially if
618 you're using non-mod-8 tabs. The tabs-vs-spaces document above provides
619 examples of Emacs and vi modelines for this purpose.
621 When editing an existing file, try following the existing indentation
622 logic and even if it very tempting, never ever use a restyler/reindenter
623 utility on an existing file. If you run across wildly varying
624 indentation styles within the same file, it might be helpful to send a
625 note to wireshark-dev for guidance.
627 1.1.6 Compiler warnings
629 You should write code that is free of compiler warnings. Such warnings will
630 often indicate questionable code and sometimes even real bugs, so it's best
631 to avoid warnings at all.
633 The compiler flags in the Makefiles are set to "treat warnings as errors",
634 so your code won't even compile when warnings occur.
638 Wireshark requires certain things when setting up a protocol dissector.
639 Below is skeleton code for a dissector that you can copy to a file and
640 fill in. Your dissector should follow the naming convention of packet-
641 followed by the abbreviated name for the protocol. It is recommended
642 that where possible you keep to the IANA abbreviated name for the
643 protocol, if there is one, or a commonly-used abbreviation for the
646 Usually, you will put your newly created dissector file into the directory
647 epan/dissectors, just like all the other packet-....c files already in there.
649 Also, please add your dissector file to the corresponding makefile,
650 described in section "1.9 Editing Makefile.common to add your dissector" below.
652 Dissectors that use the dissector registration to register with a lower level
653 dissector don't need to define a prototype in the .h file. For other
654 dissectors the main dissector routine should have a prototype in a header
655 file whose name is "packet-", followed by the abbreviated name for the
656 protocol, followed by ".h"; any dissector file that calls your dissector
657 should be changed to include that file.
659 You may not need to include all the headers listed in the skeleton
660 below, and you may need to include additional headers. For example, the
669 is needed only if you are using a function from libpcre, e.g. the
670 "pcre_compile()" function.
672 The "$Id$" in the comment will be updated by Subversion when the file is
675 When creating a new file, it is fine to just write "$Id$" as Subversion will
676 automatically fill in the identifier at the time the file will be added to the
677 SVN repository (committed).
679 ------------------------------------Cut here------------------------------------
680 /* packet-PROTOABBREV.c
681 * Routines for PROTONAME dissection
682 * Copyright 200x, YOUR_NAME <YOUR_EMAIL_ADDRESS>
686 * Wireshark - Network traffic analyzer
687 * By Gerald Combs <gerald@wireshark.org>
688 * Copyright 1998 Gerald Combs
690 * Copied from WHATEVER_FILE_YOU_USED (where "WHATEVER_FILE_YOU_USED"
691 * is a dissector file; if you just copied this from README.developer,
692 * don't bother with the "Copied from" - you don't even need to put
693 * in a "Copied from" if you copied an existing dissector, especially
694 * if the bulk of the code in the new dissector is your code)
696 * This program is free software; you can redistribute it and/or
697 * modify it under the terms of the GNU General Public License
698 * as published by the Free Software Foundation; either version 2
699 * of the License, or (at your option) any later version.
701 * This program is distributed in the hope that it will be useful,
702 * but WITHOUT ANY WARRANTY; without even the implied warranty of
703 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
704 * GNU General Public License for more details.
706 * You should have received a copy of the GNU General Public License
707 * along with this program; if not, write to the Free Software
708 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
721 #include <epan/packet.h>
722 #include <epan/prefs.h>
724 /* IF PROTO exposes code to other dissectors, then it must be exported
725 in a header file. If not, a header file is not needed at all. */
726 #include "packet-PROTOABBREV.h"
728 /* Forward declaration we need below */
729 void proto_reg_handoff_PROTOABBREV(void);
731 /* Initialize the protocol and registered fields */
732 static int proto_PROTOABBREV = -1;
733 static int hf_PROTOABBREV_FIELDABBREV = -1;
735 /* Global sample preference ("controls" display of numbers) */
736 static gboolean gPREF_HEX = FALSE;
738 /* Initialize the subtree pointers */
739 static gint ett_PROTOABBREV = -1;
741 /* Code to actually dissect the packets */
743 dissect_PROTOABBREV(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
746 /* Set up structures needed to add the protocol subtree and manage it */
748 proto_tree *PROTOABBREV_tree;
750 /* First, if at all possible, do some heuristics to check if the packet cannot
751 * possibly belong to your protocol. This is especially important for
752 * protocols directly on top of TCP or UDP where port collisions are
753 * common place (e.g., even though your protocol uses a well known port,
754 * someone else may set up, for example, a web server on that port which,
755 * if someone analyzed that web server's traffic in Wireshark, would result
756 * in Wireshark handing an HTTP packet to your dissector). For example:
758 /* Check that there's enough data */
759 if (tvb_length(tvb) < /* your protocol's smallest packet size */)
762 /* Get some values from the packet header, probably using tvb_get_*() */
763 if ( /* these values are not possible in PROTONAME */ )
764 /* This packet does not appear to belong to PROTONAME.
765 * Return 0 to give another dissector a chance to dissect it.
769 /* Make entries in Protocol column and Info column on summary display */
770 if (check_col(pinfo->cinfo, COL_PROTOCOL))
771 col_set_str(pinfo->cinfo, COL_PROTOCOL, "PROTOABBREV");
773 /* This field shows up as the "Info" column in the display; you should use
774 it, if possible, to summarize what's in the packet, so that a user looking
775 at the list of packets can tell what type of packet it is. See section 1.5
776 for more information.
778 Before changing the contents of a column you should make sure the column is
779 active by calling "check_col(pinfo->cinfo, COL_*)". If it is not active
780 don't bother setting it.
782 If you are setting the column to a constant string, use "col_set_str()",
783 as it's more efficient than the other "col_set_XXX()" calls.
785 If you're setting it to a string you've constructed, or will be
786 appending to the column later, use "col_add_str()".
788 "col_add_fstr()" can be used instead of "col_add_str()"; it takes
789 "printf()"-like arguments. Don't use "col_add_fstr()" with a format
790 string of "%s" - just use "col_add_str()" or "col_set_str()", as it's
791 more efficient than "col_add_fstr()".
793 If you will be fetching any data from the packet before filling in
794 the Info column, clear that column first, in case the calls to fetch
795 data from the packet throw an exception because they're fetching data
796 past the end of the packet, so that the Info column doesn't have data
797 left over from the previous dissector; do
799 if (check_col(pinfo->cinfo, COL_INFO))
800 col_clear(pinfo->cinfo, COL_INFO);
804 if (check_col(pinfo->cinfo, COL_INFO))
805 col_set_str(pinfo->cinfo, COL_INFO, "XXX Request");
807 /* A protocol dissector can be called in 2 different ways:
809 (a) Operational dissection
811 In this mode, Wireshark is only interested in the way protocols
812 interact, protocol conversations are created, packets are
813 reassembled and handed over to higher-level protocol dissectors.
814 In this mode Wireshark does not build a so-called "protocol
817 (b) Detailed dissection
819 In this mode, Wireshark is also interested in all details of
820 a given protocol, so a "protocol tree" is created.
822 Wireshark distinguishes between the 2 modes with the proto_tree pointer:
826 In the interest of speed, if "tree" is NULL, avoid building a
827 protocol tree and adding stuff to it, or even looking at any packet
828 data needed only if you're building the protocol tree, if possible.
830 Note, however, that you must fill in column information, create
831 conversations, reassemble packets, build any other persistent state
832 needed for dissection, and call subdissectors regardless of whether
833 "tree" is NULL or not. This might be inconvenient to do without
834 doing most of the dissection work; the routines for adding items to
835 the protocol tree can be passed a null protocol tree pointer, in
836 which case they'll return a null item pointer, and
837 "proto_item_add_subtree()" returns a null tree pointer if passed a
838 null item pointer, so, if you're careful not to dereference any null
839 tree or item pointers, you can accomplish this by doing all the
840 dissection work. This might not be as efficient as skipping that
841 work if you're not building a protocol tree, but if the code would
842 have a lot of tests whether "tree" is null if you skipped that work,
843 you might still be better off just doing all that work regardless of
844 whether "tree" is null or not. */
847 /* NOTE: The offset and length values in the call to
848 "proto_tree_add_item()" define what data bytes to highlight in the hex
849 display window when the line in the protocol tree display
850 corresponding to that item is selected.
852 Supplying a length of -1 is the way to highlight all data from the
853 offset to the end of the packet. */
855 /* create display subtree for the protocol */
856 ti = proto_tree_add_item(tree, proto_PROTOABBREV, tvb, 0, -1, FALSE);
858 PROTOABBREV_tree = proto_item_add_subtree(ti, ett_PROTOABBREV);
860 /* add an item to the subtree, see section 1.6 for more information */
861 proto_tree_add_item(PROTOABBREV_tree,
862 hf_PROTOABBREV_FIELDABBREV, tvb, offset, len, FALSE);
865 /* Continue adding tree items to process the packet here */
870 /* If this protocol has a sub-dissector call it here, see section 1.8 */
872 /* Return the amount of data this dissector was able to dissect */
873 return tvb_length(tvb);
877 /* Register the protocol with Wireshark */
879 /* this format is require because a script is used to build the C function
880 that calls all the protocol registration.
884 proto_register_PROTOABBREV(void)
886 module_t *PROTOABBREV_module;
888 /* Setup list of header fields See Section 1.6.1 for details*/
889 static hf_register_info hf[] = {
890 { &hf_PROTOABBREV_FIELDABBREV,
891 { "FIELDNAME", "PROTOABBREV.FIELDABBREV",
892 FIELDTYPE, FIELDBASE, FIELDCONVERT, BITMASK,
893 "FIELDDESCR", HFILL }
897 /* Setup protocol subtree array */
898 static gint *ett[] = {
902 /* Register the protocol name and description */
903 proto_PROTOABBREV = proto_register_protocol("PROTONAME",
904 "PROTOSHORTNAME", "PROTOABBREV");
906 /* Required function calls to register the header fields and subtrees used */
907 proto_register_field_array(proto_PROTOABBREV, hf, array_length(hf));
908 proto_register_subtree_array(ett, array_length(ett));
910 /* Register preferences module (See Section 2.6 for more on preferences) */
911 PROTOABBREV_module = prefs_register_protocol(proto_PROTOABBREV,
912 proto_reg_handoff_PROTOABBREV);
914 /* Register a sample preference */
915 prefs_register_bool_preference(PROTOABBREV_module, "show_hex",
916 "Display numbers in Hex",
917 "Enable to display numerical values in hexadecimal.",
922 /* If this dissector uses sub-dissector registration add a registration routine.
923 This exact format is required because a script is used to find these
924 routines and create the code that calls these routines.
926 This function is also called by preferences whenever "Apply" is pressed
927 (see prefs_register_protocol above) so it should accommodate being called
931 proto_reg_handoff_PROTOABBREV(void)
933 static gboolean inited = FALSE;
937 dissector_handle_t PROTOABBREV_handle;
939 /* Use new_create_dissector_handle() to indicate that dissect_PROTOABBREV()
940 * returns the number of bytes it dissected (or 0 if it thinks the packet
941 * does not belong to PROTONAME).
943 PROTOABBREV_handle = new_create_dissector_handle(dissect_PROTOABBREV,
945 dissector_add("PARENT_SUBFIELD", ID_VALUE, PROTOABBREV_handle);
951 If you perform registration functions which are dependent upon
952 prefs the you should de-register everything which was associated
953 with the previous settings and re-register using the new prefs
954 settings here. In general this means you need to keep track of what
955 value the preference had at the time you registered using a local
956 static in this function. ie.
958 static int currentPort = -1;
960 if (currentPort != -1) {
961 dissector_delete("tcp.port", currentPort, PROTOABBREV_handle);
964 currentPort = gPortPref;
966 dissector_add("tcp.port", currentPort, PROTOABBREV_handle);
971 ------------------------------------Cut here------------------------------------
973 1.3 Explanation of needed substitutions in code skeleton.
975 In the above code block the following strings should be substituted with
978 YOUR_NAME Your name, of course. You do want credit, don't you?
979 It's the only payment you will receive....
980 YOUR_EMAIL_ADDRESS Keep those cards and letters coming.
981 WHATEVER_FILE_YOU_USED Add this line if you are using another file as a
983 PROTONAME The name of the protocol; this is displayed in the
984 top-level protocol tree item for that protocol.
985 PROTOSHORTNAME An abbreviated name for the protocol; this is displayed
986 in the "Preferences" dialog box if your dissector has
987 any preferences, in the dialog box of enabled protocols,
988 and in the dialog box for filter fields when constructing
990 PROTOABBREV A name for the protocol for use in filter expressions;
991 it shall contain only lower-case letters, digits, and
993 FIELDNAME The displayed name for the header field.
994 FIELDABBREV The abbreviated name for the header field. (NO SPACES)
995 FIELDTYPE FT_NONE, FT_BOOLEAN, FT_UINT8, FT_UINT16, FT_UINT24,
996 FT_UINT32, FT_UINT64, FT_INT8, FT_INT16, FT_INT24, FT_INT32,
997 FT_INT64, FT_FLOAT, FT_DOUBLE, FT_ABSOLUTE_TIME,
998 FT_RELATIVE_TIME, FT_STRING, FT_STRINGZ, FT_EBCDIC,
999 FT_UINT_STRING, FT_ETHER, FT_BYTES, FT_IPv4, FT_IPv6, FT_IPXNET,
1000 FT_FRAMENUM, FT_PROTOCOL, FT_GUID, FT_OID
1001 FIELDBASE BASE_NONE, BASE_DEC, BASE_HEX, BASE_OCT, BASE_DEC_HEX,
1002 BASE_HEX_DEC, BASE_RANGE_STRING
1003 FIELDCONVERT VALS(x), RVALS(x), TFS(x), NULL
1004 BITMASK Usually 0x0 unless using the TFS(x) field conversion.
1005 FIELDDESCR A brief description of the field, or NULL.
1006 PARENT_SUBFIELD Lower level protocol field used for lookup, i.e. "tcp.port"
1007 ID_VALUE Lower level protocol field value that identifies this protocol
1008 For example the TCP or UDP port number
1010 If, for example, PROTONAME is "Internet Bogosity Discovery Protocol",
1011 PROTOSHORTNAME would be "IBDP", and PROTOABBREV would be "ibdp". Try to
1012 conform with IANA names.
1014 1.4 The dissector and the data it receives.
1019 This is only needed if the dissector doesn't use self-registration to
1020 register itself with the lower level dissector, or if the protocol dissector
1021 wants/needs to expose code to other subdissectors.
1023 The dissector must declared as exactly as follows in the file
1024 packet-PROTOABBREV.h:
1027 dissect_PROTOABBREV(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
1030 1.4.2 Extracting data from packets.
1032 NOTE: See the file /epan/tvbuff.h for more details.
1034 The "tvb" argument to a dissector points to a buffer containing the raw
1035 data to be analyzed by the dissector; for example, for a protocol
1036 running atop UDP, it contains the UDP payload (but not the UDP header,
1037 or any protocol headers above it). A tvbuffer is a opaque data
1038 structure, the internal data structures are hidden and the data must be
1039 access via the tvbuffer accessors.
1043 Single-byte accessor:
1045 guint8 tvb_get_guint8(tvbuff_t*, gint offset);
1047 Network-to-host-order accessors for 16-bit integers (guint16), 24-bit
1048 integers, 32-bit integers (guint32), and 64-bit integers (guint64):
1050 guint16 tvb_get_ntohs(tvbuff_t*, gint offset);
1051 guint32 tvb_get_ntoh24(tvbuff_t*, gint offset);
1052 guint32 tvb_get_ntohl(tvbuff_t*, gint offset);
1053 guint64 tvb_get_ntoh64(tvbuff_t*, gint offset);
1055 Network-to-host-order accessors for single-precision and
1056 double-precision IEEE floating-point numbers:
1058 gfloat tvb_get_ntohieee_float(tvbuff_t*, gint offset);
1059 gdouble tvb_get_ntohieee_double(tvbuff_t*, gint offset);
1061 Little-Endian-to-host-order accessors for 16-bit integers (guint16),
1062 24-bit integers, 32-bit integers (guint32), and 64-bit integers
1065 guint16 tvb_get_letohs(tvbuff_t*, gint offset);
1066 guint32 tvb_get_letoh24(tvbuff_t*, gint offset);
1067 guint32 tvb_get_letohl(tvbuff_t*, gint offset);
1068 guint64 tvb_get_letoh64(tvbuff_t*, gint offset);
1070 Little-Endian-to-host-order accessors for single-precision and
1071 double-precision IEEE floating-point numbers:
1073 gfloat tvb_get_letohieee_float(tvbuff_t*, gint offset);
1074 gdouble tvb_get_letohieee_double(tvbuff_t*, gint offset);
1076 Accessors for IPv4 and IPv6 addresses:
1078 guint32 tvb_get_ipv4(tvbuff_t*, gint offset);
1079 void tvb_get_ipv6(tvbuff_t*, gint offset, struct e_in6_addr *addr);
1081 NOTE: IPv4 addresses are not to be converted to host byte order before
1082 being passed to "proto_tree_add_ipv4()". You should use "tvb_get_ipv4()"
1083 to fetch them, not "tvb_get_ntohl()" *OR* "tvb_get_letohl()" - don't,
1084 for example, try to use "tvb_get_ntohl()", find that it gives you the
1085 wrong answer on the PC on which you're doing development, and try
1086 "tvb_get_letohl()" instead, as "tvb_get_letohl()" will give the wrong
1087 answer on big-endian machines.
1091 void tvb_get_ntohguid(tvbuff_t *, gint offset, e_guid_t *guid);
1092 void tvb_get_letohguid(tvbuff_t *, gint offset, e_guid_t *guid);
1096 guint8 *tvb_get_string(tvbuff_t*, gint offset, gint length);
1097 guint8 *tvb_get_ephemeral_string(tvbuff_t*, gint offset, gint length);
1099 Returns a null-terminated buffer containing data from the specified
1100 tvbuff, starting at the specified offset, and containing the specified
1101 length worth of characters (the length of the buffer will be length+1,
1102 as it includes a null character to terminate the string).
1104 tvb_get_string() returns a buffer allocated by g_malloc() so you must
1105 g_free() it when you are finished with the string. Failure to g_free() this
1106 buffer will lead to memory leaks.
1107 tvb_get_ephemeral_string() returns a buffer allocated from a special heap
1108 with a lifetime until the next packet is dissected. You do not need to
1109 free() this buffer, it will happen automatically once the next packet is
1113 guint8 *tvb_get_stringz(tvbuff_t *tvb, gint offset, gint *lengthp);
1114 guint8 *tvb_get_ephemeral_stringz(tvbuff_t *tvb, gint offset, gint *lengthp);
1116 Returns a null-terminated buffer, allocated with "g_malloc()",
1117 containing data from the specified tvbuff, starting with at the
1118 specified offset, and containing all characters from the tvbuff up to
1119 and including a terminating null character in the tvbuff. "*lengthp"
1120 will be set to the length of the string, including the terminating null.
1122 tvb_get_stringz() returns a buffer allocated by g_malloc() so you must
1123 g_free() it when you are finished with the string. Failure to g_free() this
1124 buffer will lead to memory leaks.
1125 tvb_get_ephemeral_stringz() returns a buffer allocated from a special heap
1126 with a lifetime until the next packet is dissected. You do not need to
1127 free() this buffer, it will happen automatically once the next packet is
1131 guint8 *tvb_fake_unicode(tvbuff_t*, gint offset, gint length);
1132 guint8 *tvb_get_ephemeral_faked_unicode(tvbuff_t*, gint offset, gint length);
1134 Converts a 2-byte unicode string to an ASCII string.
1135 Returns a null-terminated buffer containing data from the specified
1136 tvbuff, starting at the specified offset, and containing the specified
1137 length worth of characters (the length of the buffer will be length+1,
1138 as it includes a null character to terminate the string).
1140 tvb_fake_unicode() returns a buffer allocated by g_malloc() so you must
1141 g_free() it when you are finished with the string. Failure to g_free() this
1142 buffer will lead to memory leaks.
1143 tvb_get_ephemeral_faked_unicode() returns a buffer allocated from a special
1144 heap with a lifetime until the next packet is dissected. You do not need to
1145 free() this buffer, it will happen automatically once the next packet is
1150 guint8* tvb_memcpy(tvbuff_t*, guint8* target, gint offset, gint length);
1152 Copies into the specified target the specified length's worth of data
1153 from the specified tvbuff, starting at the specified offset.
1155 guint8* tvb_memdup(tvbuff_t*, gint offset, gint length);
1156 guint8* ep_tvb_memdup(tvbuff_t*, gint offset, gint length);
1158 Returns a buffer, allocated with "g_malloc()", containing the specified
1159 length's worth of data from the specified tvbuff, starting at the
1160 specified offset. The ephemeral variant is freed automatically after the
1161 packet is dissected.
1164 /* WARNING! This function is possibly expensive, temporarily allocating
1165 * another copy of the packet data. Furthermore, it's dangerous because once
1166 * this pointer is given to the user, there's no guarantee that the user will
1167 * honor the 'length' and not overstep the boundaries of the buffer.
1169 guint8* tvb_get_ptr(tvbuff_t*, gint offset, gint length);
1171 The reason that tvb_get_ptr() might have to allocate a copy of its data
1172 only occurs with TVBUFF_COMPOSITES, data that spans multiple tvbuffers.
1173 If the user request a pointer to a range of bytes that spans the member
1174 tvbuffs that make up the TVBUFF_COMPOSITE, the data will have to be
1175 copied to another memory region to assure that all the bytes are
1180 1.5 Functions to handle columns in the traffic summary window.
1182 The topmost pane of the main window is a list of the packets in the
1183 capture, possibly filtered by a display filter.
1185 Each line corresponds to a packet, and has one or more columns, as
1186 configured by the user.
1188 Many of the columns are handled by code outside individual dissectors;
1189 most dissectors need only specify the value to put in the "Protocol" and
1192 Columns are specified by COL_ values; the COL_ value for the "Protocol"
1193 field, typically giving an abbreviated name for the protocol (but not
1194 the all-lower-case abbreviation used elsewhere) is COL_PROTOCOL, and the
1195 COL_ value for the "Info" field, giving a summary of the contents of the
1196 packet for that protocol, is COL_INFO.
1198 A value for a column should only be added if the user specified that it
1199 be displayed; to check whether a given column is to be displayed, call
1200 'check_col' with the COL_ value for that field as an argument - it will
1201 return TRUE if the column is to be displayed and FALSE if it is not to
1204 The value for a column can be specified with one of several functions,
1205 all of which take the 'fd' argument to the dissector as their first
1206 argument, and the COL_ value for the column as their second argument.
1208 1.5.1 The col_set_str function.
1210 'col_set_str' takes a string as its third argument, and sets the value
1211 for the column to that value. It assumes that the pointer passed to it
1212 points to a string constant or a static "const" array, not to a
1213 variable, as it doesn't copy the string, it merely saves the pointer
1214 value; the argument can itself be a variable, as long as it always
1215 points to a string constant or a static "const" array.
1217 It is more efficient than 'col_add_str' or 'col_add_fstr'; however, if
1218 the dissector will be using 'col_append_str' or 'col_append_fstr" to
1219 append more information to the column, the string will have to be copied
1220 anyway, so it's best to use 'col_add_str' rather than 'col_set_str' in
1223 For example, to set the "Protocol" column
1226 if (check_col(pinfo->cinfo, COL_PROTOCOL))
1227 col_set_str(pinfo->cinfo, COL_PROTOCOL, "PROTOABBREV");
1230 1.5.2 The col_add_str function.
1232 'col_add_str' takes a string as its third argument, and sets the value
1233 for the column to that value. It takes the same arguments as
1234 'col_set_str', but copies the string, so that if the string is, for
1235 example, an automatic variable that won't remain in scope when the
1236 dissector returns, it's safe to use.
1239 1.5.3 The col_add_fstr function.
1241 'col_add_fstr' takes a 'printf'-style format string as its third
1242 argument, and 'printf'-style arguments corresponding to '%' format
1243 items in that string as its subsequent arguments. For example, to set
1244 the "Info" field to "<XXX> request, <N> bytes", where "reqtype" is a
1245 string containing the type of the request in the packet and "n" is an
1246 unsigned integer containing the number of bytes in the request:
1248 if (check_col(pinfo->cinfo, COL_INFO))
1249 col_add_fstr(pinfo->cinfo, COL_INFO, "%s request, %u bytes",
1252 Don't use 'col_add_fstr' with a format argument of just "%s" -
1253 'col_add_str', or possibly even 'col_set_str' if the string that matches
1254 the "%s" is a static constant string, will do the same job more
1258 1.5.4 The col_clear function.
1260 If the Info column will be filled with information from the packet, that
1261 means that some data will be fetched from the packet before the Info
1262 column is filled in. If the packet is so small that the data in
1263 question cannot be fetched, the routines to fetch the data will throw an
1264 exception (see the comment at the beginning about tvbuffers improving
1265 the handling of short packets - the tvbuffers keep track of how much
1266 data is in the packet, and throw an exception on an attempt to fetch
1267 data past the end of the packet, so that the dissector won't process
1268 bogus data), causing the Info column not to be filled in.
1270 This means that the Info column will have data for the previous
1271 protocol, which would be confusing if, for example, the Protocol column
1272 had data for this protocol.
1274 Therefore, before a dissector fetches any data whatsoever from the
1275 packet (unless it's a heuristic dissector fetching data to determine
1276 whether the packet is one that it should dissect, in which case it
1277 should check, before fetching the data, whether there's any data to
1278 fetch; if there isn't, it should return FALSE), it should set the
1279 Protocol column and the Info column.
1281 If the Protocol column will ultimately be set to, for example, a value
1282 containing a protocol version number, with the version number being a
1283 field in the packet, the dissector should, before fetching the version
1284 number field or any other field from the packet, set it to a value
1285 without a version number, using 'col_set_str', and should later set it
1286 to a value with the version number after it's fetched the version
1289 If the Info column will ultimately be set to a value containing
1290 information from the packet, the dissector should, before fetching any
1291 fields from the packet, clear the column using 'col_clear' (which is
1292 more efficient than clearing it by calling 'col_set_str' or
1293 'col_add_str' with a null string), and should later set it to the real
1294 string after it's fetched the data to use when doing that.
1297 1.5.5 The col_append_str function.
1299 Sometimes the value of a column, especially the "Info" column, can't be
1300 conveniently constructed at a single point in the dissection process;
1301 for example, it might contain small bits of information from many of the
1302 fields in the packet. 'col_append_str' takes, as arguments, the same
1303 arguments as 'col_add_str', but the string is appended to the end of the
1304 current value for the column, rather than replacing the value for that
1305 column. (Note that no blank separates the appended string from the
1306 string to which it is appended; if you want a blank there, you must add
1307 it yourself as part of the string being appended.)
1310 1.5.6 The col_append_fstr function.
1312 'col_append_fstr' is to 'col_add_fstr' as 'col_append_str' is to
1313 'col_add_str' - it takes, as arguments, the same arguments as
1314 'col_add_fstr', but the formatted string is appended to the end of the
1315 current value for the column, rather than replacing the value for that
1318 1.5.7 The col_append_sep_str and col_append_sep_fstr functions.
1320 In specific situations the developer knows that a column's value will be
1321 created in a stepwise manner, where the appended values are listed. Both
1322 'col_append_sep_str' and 'col_append_sep_fstr' functions will add an item
1323 separator between two consecutive items, and will not add the separator at the
1324 beginning of the column. The remainder of the work both functions do is
1325 identical to what 'col_append_str' and 'col_append_fstr' do.
1327 1.5.8 The col_set_fence and col_prepend_fence_fstr functions.
1329 Sometimes a dissector may be called multiple times for different PDUs in the
1330 same frame (for example in the case of SCTP chunk bundling: several upper
1331 layer data packets may be contained in one SCTP packet). If the upper layer
1332 dissector calls 'col_set_str()' or 'col_clear()' on the Info column when it
1333 begins dissecting each of those PDUs then when the frame is fully dissected
1334 the Info column would contain only the string from the last PDU in the frame.
1335 The 'col_set_fence' function erects a "fence" in the column that prevents
1336 subsequent 'col_...' calls from clearing the data currently in that column.
1337 For example, the SCTP dissector calls 'col_set_fence' on the Info column
1338 after it has called any subdissectors for that chunk so that subdissectors
1339 of any subsequent chunks may only append to the Info column.
1340 'col_prepend_fence_fstr' prepends data before a fence (moving it if
1341 necessary). It will create a fence at the end of the prended data if the
1342 fence does not already exist.
1345 1.5.9 The col_set_time function.
1347 The 'col_set_time' function takes a nstime value as it's third argument.
1348 This nstime value is a relative value and will be added as such to the
1349 column. The fourth argument is the filtername holding this value. This
1350 way, rightclicking on the column makes it possible to build a filter
1351 based on the time-value.
1355 if (check_col(pinfo->cinfo, COL_REL_CONV_TIME)) {
1356 nstime_delta(&ts, &pinfo->fd->abs_ts, &tcpd->ts_first);
1357 col_set_time(pinfo->cinfo, COL_REL_CONV_TIME, &ts, "tcp.time_relative");
1361 1.6 Constructing the protocol tree.
1363 The middle pane of the main window, and the topmost pane of a packet
1364 popup window, are constructed from the "protocol tree" for a packet.
1366 The protocol tree, or proto_tree, is a GNode, the N-way tree structure
1367 available within GLIB. Of course the protocol dissectors don't care
1368 what a proto_tree really is; they just pass the proto_tree pointer as an
1369 argument to the routines which allow them to add items and new branches
1372 When a packet is selected in the packet-list pane, or a packet popup
1373 window is created, a new logical protocol tree (proto_tree) is created.
1374 The pointer to the proto_tree (in this case, 'protocol tree'), is passed
1375 to the top-level protocol dissector, and then to all subsequent protocol
1376 dissectors for that packet, and then the GUI tree is drawn via
1379 The logical proto_tree needs to know detailed information about the protocols
1380 and fields about which information will be collected from the dissection
1381 routines. By strictly defining (or "typing") the data that can be attached to a
1382 proto tree, searching and filtering becomes possible. This means that for
1383 every protocol and field (which I also call "header fields", since they are
1384 fields in the protocol headers) which might be attached to a tree, some
1385 information is needed.
1387 Every dissector routine will need to register its protocols and fields
1388 with the central protocol routines (in proto.c). At first I thought I
1389 might keep all the protocol and field information about all the
1390 dissectors in one file, but decentralization seemed like a better idea.
1391 That one file would have gotten very large; one small change would have
1392 required a re-compilation of the entire file. Also, by allowing
1393 registration of protocols and fields at run-time, loadable modules of
1394 protocol dissectors (perhaps even user-supplied) is feasible.
1396 To do this, each protocol should have a register routine, which will be
1397 called when Wireshark starts. The code to call the register routines is
1398 generated automatically; to arrange that a protocol's register routine
1399 be called at startup:
1401 the file containing a dissector's "register" routine must be
1402 added to "DISSECTOR_SRC" in "epan/dissectors/Makefile.common";
1404 the "register" routine must have a name of the form
1405 "proto_register_XXX";
1407 the "register" routine must take no argument, and return no
1410 the "register" routine's name must appear in the source file
1411 either at the beginning of the line, or preceded only by "void "
1412 at the beginning of the line (that would typically be the
1413 definition) - other white space shouldn't cause a problem, e.g.:
1415 void proto_register_XXX(void) {
1424 proto_register_XXX( void )
1431 and so on should work.
1433 For every protocol or field that a dissector wants to register, a variable of
1434 type int needs to be used to keep track of the protocol. The IDs are
1435 needed for establishing parent/child relationships between protocols and
1436 fields, as well as associating data with a particular field so that it
1437 can be stored in the logical tree and displayed in the GUI protocol
1440 Some dissectors will need to create branches within their tree to help
1441 organize header fields. These branches should be registered as header
1442 fields. Only true protocols should be registered as protocols. This is
1443 so that a display filter user interface knows how to distinguish
1444 protocols from fields.
1446 A protocol is registered with the name of the protocol and its
1449 Here is how the frame "protocol" is registered.
1453 proto_frame = proto_register_protocol (
1455 /* short name */ "Frame",
1456 /* abbrev */ "frame" );
1458 A header field is also registered with its name and abbreviation, but
1459 information about the its data type is needed. It helps to look at
1460 the header_field_info struct to see what information is expected:
1462 struct header_field_info {
1471 int id; /* calculated */
1473 int bitshift; /* calculated */
1478 A string representing the name of the field. This is the name
1479 that will appear in the graphical protocol tree. It must be a non-empty
1484 A string with an abbreviation of the field. We concatenate the
1485 abbreviation of the parent protocol with an abbreviation for the field,
1486 using a period as a separator. For example, the "src" field in an IP packet
1487 would have "ip.src" as an abbreviation. It is acceptable to have
1488 multiple levels of periods if, for example, you have fields in your
1489 protocol that are then subdivided into subfields. For example, TRMAC
1490 has multiple error fields, so the abbreviations follow this pattern:
1491 "trmac.errors.iso", "trmac.errors.noniso", etc.
1493 The abbreviation is the identifier used in a display filter. If it is
1494 an empty string then the field will not be filterable.
1498 The type of value this field holds. The current field types are:
1500 FT_NONE No field type. Used for fields that
1501 aren't given a value, and that can only
1502 be tested for presence or absence; a
1503 field that represents a data structure,
1504 with a subtree below it containing
1505 fields for the members of the structure,
1506 or that represents an array with a
1507 subtree below it containing fields for
1508 the members of the array, might be an
1510 FT_PROTOCOL Used for protocols which will be placing
1511 themselves as top-level items in the
1512 "Packet Details" pane of the UI.
1513 FT_BOOLEAN 0 means "false", any other value means
1515 FT_FRAMENUM A frame number; if this is used, the "Go
1516 To Corresponding Frame" menu item can
1518 FT_UINT8 An 8-bit unsigned integer.
1519 FT_UINT16 A 16-bit unsigned integer.
1520 FT_UINT24 A 24-bit unsigned integer.
1521 FT_UINT32 A 32-bit unsigned integer.
1522 FT_UINT64 A 64-bit unsigned integer.
1523 FT_INT8 An 8-bit signed integer.
1524 FT_INT16 A 16-bit signed integer.
1525 FT_INT24 A 24-bit signed integer.
1526 FT_INT32 A 32-bit signed integer.
1527 FT_INT64 A 64-bit signed integer.
1528 FT_FLOAT A single-precision floating point number.
1529 FT_DOUBLE A double-precision floating point number.
1530 FT_ABSOLUTE_TIME Seconds (4 bytes) and nanoseconds (4 bytes)
1531 of time displayed as month name, month day,
1532 year, hours, minutes, and seconds with 9
1533 digits after the decimal point.
1534 FT_RELATIVE_TIME Seconds (4 bytes) and nanoseconds (4 bytes)
1535 of time displayed as seconds and 9 digits
1536 after the decimal point.
1537 FT_STRING A string of characters, not necessarily
1538 NUL-terminated, but possibly NUL-padded.
1539 This, and the other string-of-characters
1540 types, are to be used for text strings,
1541 not raw binary data.
1542 FT_STRINGZ A NUL-terminated string of characters.
1543 FT_EBCDIC A string of characters, not necessarily
1544 NUL-terminated, but possibly NUL-padded.
1545 The data from the packet is converted from
1546 EBCDIC to ASCII before displaying to the user.
1547 FT_UINT_STRING A counted string of characters, consisting
1548 of a count (represented as an integral
1549 value) followed immediately by the
1550 specified number of characters.
1551 FT_ETHER A six octet string displayed in
1552 Ethernet-address format.
1553 FT_BYTES A string of bytes with arbitrary values;
1554 used for raw binary data.
1555 FT_IPv4 A version 4 IP address (4 bytes) displayed
1556 in dotted-quad IP address format (4
1557 decimal numbers separated by dots).
1558 FT_IPv6 A version 6 IP address (16 bytes) displayed
1559 in standard IPv6 address format.
1560 FT_IPXNET An IPX address displayed in hex as a 6-byte
1561 network number followed by a 6-byte station
1563 FT_GUID A Globally Unique Identifier
1564 FT_OID An ASN.1 Object Identifier
1566 Some of these field types are still not handled in the display filter
1567 routines, but the most common ones are. The FT_UINT* variables all
1568 represent unsigned integers, and the FT_INT* variables all represent
1569 signed integers; the number on the end represent how many bits are used
1570 to represent the number.
1574 The display field has a couple of overloaded uses. This is unfortunate,
1575 but since we're C as an application programming language, this sometimes
1576 makes for cleaner programs. Right now I still think that overloading
1577 this variable was okay.
1579 For integer fields (FT_UINT* and FT_INT*), this variable represents the
1580 base in which you would like the value displayed. The acceptable bases
1589 BASE_DEC, BASE_HEX, and BASE_OCT are decimal, hexadecimal, and octal,
1590 respectively. BASE_DEC_HEX and BASE_HEX_DEC display value in two bases
1591 (the 1st representation followed by the 2nd in parenthesis)
1593 For FT_BOOLEAN fields that are also bitfields, 'display' is used to tell
1594 the proto_tree how wide the parent bitfield is. With integers this is
1595 not needed since the type of integer itself (FT_UINT8, FT_UINT16,
1596 FT_UINT24, FT_UINT32, etc.) tells the proto_tree how wide the parent
1599 Additionally, BASE_NONE is used for 'display' as a NULL-value. That is,
1600 for non-integers and non-bitfield FT_BOOLEANs, you'll want to use BASE_NONE
1601 in the 'display' field. You may not use BASE_NONE for integers.
1603 It is possible that in the future we will record the endianness of
1604 integers. If so, it is likely that we'll use a bitmask on the display field
1605 so that integers would be represented as BEND|BASE_DEC or LEND|BASE_HEX.
1606 But that has not happened yet.
1610 Some integer fields, of type FT_UINT*, need labels to represent the true
1611 value of a field. You could think of those fields as having an
1612 enumerated data type, rather than an integral data type.
1614 A 'value_string' structure is a way to map values to strings.
1616 typedef struct _value_string {
1621 For fields of that type, you would declare an array of "value_string"s:
1623 static const value_string valstringname[] = {
1624 { INTVAL1, "Descriptive String 1" },
1625 { INTVAL2, "Descriptive String 2" },
1629 (the last entry in the array must have a NULL 'strptr' value, to
1630 indicate the end of the array). The 'strings' field would be set to
1631 'VALS(valstringname)'.
1633 If the field has a numeric rather than an enumerated type, the 'strings'
1634 field would be set to NULL.
1636 If the field has a numeric type that might logically fit in ranges of values
1637 one can use a range_string struct.
1639 Thus a 'range_string' structure is a way to map ranges to strings.
1641 typedef struct _range_string {
1644 const gchar *strptr;
1647 For fields of that type, you would declare an array of "range_string"s:
1649 static const range_string rvalstringname[] = {
1650 { INTVAL_MIN1, INTVALMAX1, "Descriptive String 1" },
1651 { INTVAL_MIN2, INTVALMAX2, "Descriptive String 2" },
1655 If INTVAL_MIN equals INTVAL_MAX for a given entry the range_string
1656 behavior collapses to the one of value_string.
1657 For FT_(U)INT* fields that need a 'range_string' struct, the 'strings' field
1658 would be set to 'RVALS(rvalstringname)'. Furthermore, 'display' field must be
1659 ORed with 'BASE_RANGE_STRING' (e.g. BASE_DEC|BASE_RANGE_STRING).
1661 FT_BOOLEANs have a default map of 0 = "False", 1 (or anything else) = "True".
1662 Sometimes it is useful to change the labels for boolean values (e.g.,
1663 to "Yes"/"No", "Fast"/"Slow", etc.). For these mappings, a struct called
1664 true_false_string is used.
1666 typedef struct true_false_string {
1669 } true_false_string;
1671 For Boolean fields for which "False" and "True" aren't the desired
1672 labels, you would declare a "true_false_string"s:
1674 static const true_false_string boolstringname = {
1679 Its two fields are pointers to the string representing truth, and the
1680 string representing falsehood. For FT_BOOLEAN fields that need a
1681 'true_false_string' struct, the 'strings' field would be set to
1682 'TFS(&boolstringname)'.
1684 If the Boolean field is to be displayed as "False" or "True", the
1685 'strings' field would be set to NULL.
1687 Wireshark predefines a whole range of ready made "true_false_string"s
1688 in tfs.h, included via packet.h.
1692 If the field is a bitfield, then the bitmask is the mask which will
1693 leave only the bits needed to make the field when ANDed with a value.
1694 The proto_tree routines will calculate 'bitshift' automatically
1695 from 'bitmask', by finding the rightmost set bit in the bitmask.
1696 If the field is not a bitfield, then bitmask should be set to 0.
1700 This is a string giving a proper description of the field.
1701 It should be at least one grammatically complete sentence.
1702 It is meant to provide a more detailed description of the field than the
1703 name alone provides. This information will be used in the man page, and
1704 in a future GUI display-filter creation tool. We might also add tooltips
1705 to the labels in the GUI protocol tree, in which case the blurb would
1706 be used as the tooltip text.
1709 1.6.1 Field Registration.
1711 Protocol registration is handled by creating an instance of the
1712 header_field_info struct (or an array of such structs), and
1713 calling the registration function along with the registration ID of
1714 the protocol that is the parent of the fields. Here is a complete example:
1716 static int proto_eg = -1;
1717 static int hf_field_a = -1;
1718 static int hf_field_b = -1;
1720 static hf_register_info hf[] = {
1723 { "Field A", "proto.field_a", FT_UINT8, BASE_HEX, NULL,
1724 0xf0, "Field A represents Apples", HFILL }},
1727 { "Field B", "proto.field_b", FT_UINT16, BASE_DEC, VALS(vs),
1728 0x0, "Field B represents Bananas", HFILL }}
1731 proto_eg = proto_register_protocol("Example Protocol",
1733 proto_register_field_array(proto_eg, hf, array_length(hf));
1735 Be sure that your array of hf_register_info structs is declared 'static',
1736 since the proto_register_field_array() function does not create a copy
1737 of the information in the array... it uses that static copy of the
1738 information that the compiler created inside your array. Here's the
1739 layout of the hf_register_info struct:
1741 typedef struct hf_register_info {
1742 int *p_id; /* pointer to parent variable */
1743 header_field_info hfinfo;
1746 Also be sure to use the handy array_length() macro found in packet.h
1747 to have the compiler compute the array length for you at compile time.
1749 If you don't have any fields to register, do *NOT* create a zero-length
1750 "hf" array; not all compilers used to compile Wireshark support them.
1751 Just omit the "hf" array, and the "proto_register_field_array()" call,
1754 It is OK to have header fields with a different format be registered with
1755 the same abbreviation. For instance, the following is valid:
1757 static hf_register_info hf[] = {
1759 { &hf_field_8bit, /* 8-bit version of proto.field */
1760 { "Field (8 bit)", "proto.field", FT_UINT8, BASE_DEC, NULL,
1761 0x00, "Field represents FOO", HFILL }},
1763 { &hf_field_32bit, /* 32-bit version of proto.field */
1764 { "Field (32 bit)", "proto.field", FT_UINT32, BASE_DEC, NULL,
1765 0x00, "Field represents FOO", HFILL }}
1768 This way a filter expression can match a header field, irrespective of the
1769 representation of it in the specific protocol context. This is interesting
1770 for protocols with variable-width header fields.
1772 The HFILL macro at the end of the struct will set reasonable default values
1773 for internally used fields.
1775 1.6.2 Adding Items and Values to the Protocol Tree.
1777 A protocol item is added to an existing protocol tree with one of a
1778 handful of proto_XXX_DO_YYY() functions.
1780 Remember that it only makes sense to add items to a protocol tree if its
1781 proto_tree pointer is not null. Should you add an item to a NULL tree, then
1782 the proto_XXX_DO_YYY() function will immediately return. The cost of this
1783 function call can be avoided by checking for the tree pointer.
1785 Subtrees can be made with the proto_item_add_subtree() function:
1787 item = proto_tree_add_item(....);
1788 new_tree = proto_item_add_subtree(item, tree_type);
1790 This will add a subtree under the item in question; a subtree can be
1791 created under an item made by any of the "proto_tree_add_XXX" functions,
1792 so that the tree can be given an arbitrary depth.
1794 Subtree types are integers, assigned by
1795 "proto_register_subtree_array()". To register subtree types, pass an
1796 array of pointers to "gint" variables to hold the subtree type values to
1797 "proto_register_subtree_array()":
1799 static gint ett_eg = -1;
1800 static gint ett_field_a = -1;
1802 static gint *ett[] = {
1807 proto_register_subtree_array(ett, array_length(ett));
1809 in your "register" routine, just as you register the protocol and the
1810 fields for that protocol.
1812 There are several functions that the programmer can use to add either
1813 protocol or field labels to the proto_tree:
1816 proto_tree_add_item(tree, id, tvb, start, length, little_endian);
1819 proto_tree_add_item_hidden(tree, id, tvb, start, length, little_endian);
1822 proto_tree_add_none_format(tree, id, tvb, start, length, format, ...);
1825 proto_tree_add_protocol_format(tree, id, tvb, start, length,
1829 proto_tree_add_bytes(tree, id, tvb, start, length, start_ptr);
1832 proto_tree_add_bytes_hidden(tree, id, tvb, start, length, start_ptr);
1835 proto_tree_add_bytes_format(tree, id, tvb, start, length, start_ptr,
1839 proto_tree_add_bytes_format_value(tree, id, tvb, start, length,
1840 start_ptr, format, ...);
1843 proto_tree_add_time(tree, id, tvb, start, length, value_ptr);
1846 proto_tree_add_time_hidden(tree, id, tvb, start, length, value_ptr);
1849 proto_tree_add_time_format(tree, id, tvb, start, length, value_ptr,
1853 proto_tree_add_time_format_value(tree, id, tvb, start, length,
1854 value_ptr, format, ...);
1857 proto_tree_add_ipxnet(tree, id, tvb, start, length, value);
1860 proto_tree_add_ipxnet_hidden(tree, id, tvb, start, length, value);
1863 proto_tree_add_ipxnet_format(tree, id, tvb, start, length, value,
1867 proto_tree_add_ipxnet_format_value(tree, id, tvb, start, length,
1868 value, format, ...);
1871 proto_tree_add_ipv4(tree, id, tvb, start, length, value);
1874 proto_tree_add_ipv4_hidden(tree, id, tvb, start, length, value);
1877 proto_tree_add_ipv4_format(tree, id, tvb, start, length, value,
1881 proto_tree_add_ipv4_format_value(tree, id, tvb, start, length,
1882 value, format, ...);
1885 proto_tree_add_ipv6(tree, id, tvb, start, length, value_ptr);
1888 proto_tree_add_ipv6_hidden(tree, id, tvb, start, length, value_ptr);
1891 proto_tree_add_ipv6_format(tree, id, tvb, start, length, value_ptr,
1895 proto_tree_add_ipv6_format_value(tree, id, tvb, start, length,
1896 value_ptr, format, ...);
1899 proto_tree_add_ether(tree, id, tvb, start, length, value_ptr);
1902 proto_tree_add_ether_hidden(tree, id, tvb, start, length, value_ptr);
1905 proto_tree_add_ether_format(tree, id, tvb, start, length, value_ptr,
1909 proto_tree_add_ether_format_value(tree, id, tvb, start, length,
1910 value_ptr, format, ...);
1913 proto_tree_add_string(tree, id, tvb, start, length, value_ptr);
1916 proto_tree_add_string_hidden(tree, id, tvb, start, length, value_ptr);
1919 proto_tree_add_string_format(tree, id, tvb, start, length, value_ptr,
1923 proto_tree_add_string_format_value(tree, id, tvb, start, length,
1924 value_ptr, format, ...);
1927 proto_tree_add_boolean(tree, id, tvb, start, length, value);
1930 proto_tree_add_boolean_hidden(tree, id, tvb, start, length, value);
1933 proto_tree_add_boolean_format(tree, id, tvb, start, length, value,
1937 proto_tree_add_boolean_format_value(tree, id, tvb, start, length,
1938 value, format, ...);
1941 proto_tree_add_float(tree, id, tvb, start, length, value);
1944 proto_tree_add_float_hidden(tree, id, tvb, start, length, value);
1947 proto_tree_add_float_format(tree, id, tvb, start, length, value,
1951 proto_tree_add_float_format_value(tree, id, tvb, start, length,
1952 value, format, ...);
1955 proto_tree_add_double(tree, id, tvb, start, length, value);
1958 proto_tree_add_double_hidden(tree, id, tvb, start, length, value);
1961 proto_tree_add_double_format(tree, id, tvb, start, length, value,
1965 proto_tree_add_double_format_value(tree, id, tvb, start, length,
1966 value, format, ...);
1969 proto_tree_add_uint(tree, id, tvb, start, length, value);
1972 proto_tree_add_uint_hidden(tree, id, tvb, start, length, value);
1975 proto_tree_add_uint_format(tree, id, tvb, start, length, value,
1979 proto_tree_add_uint_format_value(tree, id, tvb, start, length,
1980 value, format, ...);
1983 proto_tree_add_uint64(tree, id, tvb, start, length, value);
1986 proto_tree_add_uint64_format(tree, id, tvb, start, length, value,
1990 proto_tree_add_uint64_format_value(tree, id, tvb, start, length,
1991 value, format, ...);
1994 proto_tree_add_int(tree, id, tvb, start, length, value);
1997 proto_tree_add_int_hidden(tree, id, tvb, start, length, value);
2000 proto_tree_add_int_format(tree, id, tvb, start, length, value,
2004 proto_tree_add_int_format_value(tree, id, tvb, start, length,
2005 value, format, ...);
2008 proto_tree_add_int64(tree, id, tvb, start, length, value);
2011 proto_tree_add_int64_format(tree, id, tvb, start, length, value,
2015 proto_tree_add_int64_format_value(tree, id, tvb, start, length,
2016 value, format, ...);
2019 proto_tree_add_text(tree, tvb, start, length, format, ...);
2022 proto_tree_add_text_valist(tree, tvb, start, length, format, ap);
2025 proto_tree_add_guid(tree, id, tvb, start, length, value_ptr);
2028 proto_tree_add_guid_hidden(tree, id, tvb, start, length, value_ptr);
2031 proto_tree_add_guid_format(tree, id, tvb, start, length, value_ptr,
2035 proto_tree_add_guid_format_value(tree, id, tvb, start, length,
2036 value_ptr, format, ...);
2039 proto_tree_add_oid(tree, id, tvb, start, length, value_ptr);
2042 proto_tree_add_oid_hidden(tree, id, tvb, start, length, value_ptr);
2045 proto_tree_add_oid_format(tree, id, tvb, start, length, value_ptr,
2049 proto_tree_add_oid_format_value(tree, id, tvb, start, length,
2050 value_ptr, format, ...);
2053 proto_tree_add_bitmask(tree, tvb, start, header, ett, **fields,
2056 The 'tree' argument is the tree to which the item is to be added. The
2057 'tvb' argument is the tvbuff from which the item's value is being
2058 extracted; the 'start' argument is the offset from the beginning of that
2059 tvbuff of the item being added, and the 'length' argument is the length,
2060 in bytes, of the item.
2062 The length of some items cannot be determined until the item has been
2063 dissected; to add such an item, add it with a length of -1, and, when the
2064 dissection is complete, set the length with 'proto_item_set_len()':
2067 proto_item_set_len(ti, length);
2069 The "ti" argument is the value returned by the call that added the item
2070 to the tree, and the "length" argument is the length of the item.
2072 proto_tree_add_item()
2073 ---------------------
2074 proto_tree_add_item is used when you wish to do no special formatting.
2075 The item added to the GUI tree will contain the name (as passed in the
2076 proto_register_*() function) and a value. The value will be fetched
2077 from the tvbuff by proto_tree_add_item(), based on the type of the field
2078 and, for integral and Boolean fields, the byte order of the value; the
2079 byte order is specified by the 'little_endian' argument, which is TRUE
2080 if the value is little-endian and FALSE if it is big-endian.
2082 Now that definitions of fields have detailed information about bitfield
2083 fields, you can use proto_tree_add_item() with no extra processing to
2084 add bitfield values to your tree. Here's an example. Take the Format
2085 Identifier (FID) field in the Transmission Header (TH) portion of the SNA
2086 protocol. The FID is the high nibble of the first byte of the TH. The
2087 FID would be registered like this:
2089 name = "Format Identifier"
2090 abbrev = "sna.th.fid"
2093 strings = sna_th_fid_vals
2096 The bitmask contains the value which would leave only the FID if bitwise-ANDed
2097 against the parent field, the first byte of the TH.
2099 The code to add the FID to the tree would be;
2101 proto_tree_add_item(bf_tree, hf_sna_th_fid, tvb, offset, 1, TRUE);
2103 The definition of the field already has the information about bitmasking
2104 and bitshifting, so it does the work of masking and shifting for us!
2105 This also means that you no longer have to create value_string structs
2106 with the values bitshifted. The value_string for FID looks like this,
2107 even though the FID value is actually contained in the high nibble.
2108 (You'd expect the values to be 0x0, 0x10, 0x20, etc.)
2110 /* Format Identifier */
2111 static const value_string sna_th_fid_vals[] = {
2112 { 0x0, "SNA device <--> Non-SNA Device" },
2113 { 0x1, "Subarea Node <--> Subarea Node" },
2114 { 0x2, "Subarea Node <--> PU2" },
2115 { 0x3, "Subarea Node or SNA host <--> Subarea Node" },
2118 { 0xf, "Adjaced Subarea Nodes" },
2122 The final implication of this is that display filters work the way you'd
2123 naturally expect them to. You'd type "sna.th.fid == 0xf" to find Adjacent
2124 Subarea Nodes. The user does not have to shift the value of the FID to
2125 the high nibble of the byte ("sna.th.fid == 0xf0") as was necessary
2128 proto_tree_add_item_hidden()
2129 ----------------------------
2130 proto_tree_add_item_hidden is used to add fields and values to a tree,
2131 but not show them on a GUI tree.
2133 NOTE that creating hidden fields is actually quite a bad idea from a UI design
2134 perspective because the user (someone who did not write nor has ever seen the
2135 code) has no way of knowing that hidden fields are there to be filtered on
2136 thus defeating the whole purpose of putting them there. A Better Way might
2137 be to add the fields (that might otherwise be hidden) to a subtree where they
2138 won't be seen unless the user opens the subtree--but they can be found if the
2141 NOTE, too, that all of the proto_tree_add_*_hidden() APIs are deprecated:
2142 instead of using them, use add the item using proto_tree_add_item() and then
2143 make it hidden using PROTO_ITEM_SET_HIDDEN().
2145 One use for hidden fields (which would be better implemented using visible
2146 fields in a subtree) follows: The caller may want a value to be
2147 included in a tree so that the packet can be filtered on this field, but
2148 the representation of that field in the tree is not appropriate. An
2149 example is the token-ring routing information field (RIF). The best way
2150 to show the RIF in a GUI is by a sequence of ring and bridge numbers.
2151 Rings are 3-digit hex numbers, and bridges are single hex digits:
2153 RIF: 001-A-013-9-C0F-B-555
2155 In the case of RIF, the programmer should use a field with no value and
2156 use proto_tree_add_none_format() to build the above representation. The
2157 programmer can then add the ring and bridge values, one-by-one, with
2158 proto_tree_add_item_hidden() so that the user can then filter on or
2159 search for a particular ring or bridge. Here's a skeleton of how the
2160 programmer might code this.
2163 rif = create_rif_string(...);
2165 proto_tree_add_none_format(tree, hf_tr_rif_label, ..., "RIF: %s", rif);
2167 for(i = 0; i < num_rings; i++) {
2168 proto_tree_add_item_hidden(tree, hf_tr_rif_ring, ..., FALSE);
2170 for(i = 0; i < num_rings - 1; i++) {
2171 proto_tree_add_item_hidden(tree, hf_tr_rif_bridge, ..., FALSE);
2174 The logical tree has these items:
2176 hf_tr_rif_label, text="RIF: 001-A-013-9-C0F-B-555", value = NONE
2177 hf_tr_rif_ring, hidden, value=0x001
2178 hf_tr_rif_bridge, hidden, value=0xA
2179 hf_tr_rif_ring, hidden, value=0x013
2180 hf_tr_rif_bridge, hidden, value=0x9
2181 hf_tr_rif_ring, hidden, value=0xC0F
2182 hf_tr_rif_bridge, hidden, value=0xB
2183 hf_tr_rif_ring, hidden, value=0x555
2185 GUI or print code will not display the hidden fields, but a display
2186 filter or "packet grep" routine will still see the values. The possible
2187 filter is then possible:
2189 tr.rif_ring eq 0x013
2191 proto_tree_add_protocol_format()
2192 --------------------------------
2193 proto_tree_add_protocol_format is used to add the top-level item for the
2194 protocol when the dissector routines wants complete control over how the
2195 field and value will be represented on the GUI tree. The ID value for
2196 the protocol is passed in as the "id" argument; the rest of the
2197 arguments are a "printf"-style format and any arguments for that format.
2198 The caller must include the name of the protocol in the format; it is
2199 not added automatically as in proto_tree_add_item().
2201 proto_tree_add_none_format()
2202 ----------------------------
2203 proto_tree_add_none_format is used to add an item of type FT_NONE.
2204 The caller must include the name of the field in the format; it is
2205 not added automatically as in proto_tree_add_item().
2207 proto_tree_add_bytes()
2208 proto_tree_add_time()
2209 proto_tree_add_ipxnet()
2210 proto_tree_add_ipv4()
2211 proto_tree_add_ipv6()
2212 proto_tree_add_ether()
2213 proto_tree_add_string()
2214 proto_tree_add_boolean()
2215 proto_tree_add_float()
2216 proto_tree_add_double()
2217 proto_tree_add_uint()
2218 proto_tree_add_uint64()
2219 proto_tree_add_int()
2220 proto_tree_add_int64()
2221 proto_tree_add_guid()
2222 proto_tree_add_oid()
2223 ------------------------
2224 These routines are used to add items to the protocol tree if either:
2226 the value of the item to be added isn't just extracted from the
2227 packet data, but is computed from data in the packet;
2229 the value was fetched into a variable.
2231 The 'value' argument has the value to be added to the tree.
2233 NOTE: in all cases where the 'value' argument is a pointer, a copy is
2234 made of the object pointed to; if you have dynamically allocated a
2235 buffer for the object, that buffer will not be freed when the protocol
2236 tree is freed - you must free the buffer yourself when you don't need it
2239 For proto_tree_add_bytes(), the 'value_ptr' argument is a pointer to a
2242 For proto_tree_add_time(), the 'value_ptr' argument is a pointer to an
2243 "nstime_t", which is a structure containing the time to be added; it has
2244 'secs' and 'nsecs' members, giving the integral part and the fractional
2245 part of a time in units of seconds, with 'nsecs' being the number of
2246 nanoseconds. For absolute times, "secs" is a UNIX-style seconds since
2247 January 1, 1970, 00:00:00 GMT value.
2249 For proto_tree_add_ipxnet(), the 'value' argument is a 32-bit IPX
2252 For proto_tree_add_ipv4(), the 'value' argument is a 32-bit IPv4
2253 address, in network byte order.
2255 For proto_tree_add_ipv6(), the 'value_ptr' argument is a pointer to a
2256 128-bit IPv6 address.
2258 For proto_tree_add_ether(), the 'value_ptr' argument is a pointer to a
2261 For proto_tree_add_string(), the 'value_ptr' argument is a pointer to a
2264 For proto_tree_add_boolean(), the 'value' argument is a 32-bit integer.
2265 It is masked and shifted as defined by the field info after which zero
2266 means "false", and non-zero means "true".
2268 For proto_tree_add_float(), the 'value' argument is a 'float' in the
2269 host's floating-point format.
2271 For proto_tree_add_double(), the 'value' argument is a 'double' in the
2272 host's floating-point format.
2274 For proto_tree_add_uint(), the 'value' argument is a 32-bit unsigned
2275 integer value, in host byte order. (This routine cannot be used to add
2278 For proto_tree_add_uint64(), the 'value' argument is a 64-bit unsigned
2279 integer value, in host byte order.
2281 For proto_tree_add_int(), the 'value' argument is a 32-bit signed
2282 integer value, in host byte order. (This routine cannot be used to add
2285 For proto_tree_add_int64(), the 'value' argument is a 64-bit signed
2286 integer value, in host byte order.
2288 For proto_tree_add_guid(), the 'value_ptr' argument is a pointer to an
2291 For proto_tree_add_oid(), the 'value_ptr' argument is a pointer to an
2292 ASN.1 Object Identifier.
2294 proto_tree_add_bytes_hidden()
2295 proto_tree_add_time_hidden()
2296 proto_tree_add_ipxnet_hidden()
2297 proto_tree_add_ipv4_hidden()
2298 proto_tree_add_ipv6_hidden()
2299 proto_tree_add_ether_hidden()
2300 proto_tree_add_string_hidden()
2301 proto_tree_add_boolean_hidden()
2302 proto_tree_add_float_hidden()
2303 proto_tree_add_double_hidden()
2304 proto_tree_add_uint_hidden()
2305 proto_tree_add_int_hidden()
2306 proto_tree_add_guid_hidden()
2307 proto_tree_add_oid_hidden()
2308 ----------------------------
2309 These routines add fields and values to a tree, but don't show them in the GUI
2310 tree. They are used for the same reason that proto_tree_add_item_hidden() is
2311 used (and they should not be used for the same reasons).
2313 proto_tree_add_bytes_format()
2314 proto_tree_add_time_format()
2315 proto_tree_add_ipxnet_format()
2316 proto_tree_add_ipv4_format()
2317 proto_tree_add_ipv6_format()
2318 proto_tree_add_ether_format()
2319 proto_tree_add_string_format()
2320 proto_tree_add_boolean_format()
2321 proto_tree_add_float_format()
2322 proto_tree_add_double_format()
2323 proto_tree_add_uint_format()
2324 proto_tree_add_uint64_format()
2325 proto_tree_add_int_format()
2326 proto_tree_add_int64_format()
2327 proto_tree_add_guid_format()
2328 proto_tree_add_oid_format()
2329 ----------------------------
2330 These routines are used to add items to the protocol tree when the
2331 dissector routines wants complete control over how the field and value
2332 will be represented on the GUI tree. The argument giving the value is
2333 the same as the corresponding proto_tree_add_XXX() function; the rest of
2334 the arguments are a "printf"-style format and any arguments for that
2335 format. The caller must include the name of the field in the format; it
2336 is not added automatically as in the proto_tree_add_XXX() functions.
2338 proto_tree_add_bytes_format_value()
2339 proto_tree_add_time_format_value()
2340 proto_tree_add_ipxnet_format_value()
2341 proto_tree_add_ipv4_format_value()
2342 proto_tree_add_ipv6_format_value()
2343 proto_tree_add_ether_format_value()
2344 proto_tree_add_string_format_value()
2345 proto_tree_add_boolean_format_value()
2346 proto_tree_add_float_format_value()
2347 proto_tree_add_double_format_value()
2348 proto_tree_add_uint_format_value()
2349 proto_tree_add_uint64_format_value()
2350 proto_tree_add_int_format_value()
2351 proto_tree_add_int64_format_value()
2352 proto_tree_add_guid_format_value()
2353 proto_tree_add_oid_format_value()
2354 ------------------------------------
2356 These routines are used to add items to the protocol tree when the
2357 dissector routines wants complete control over how the value will be
2358 represented on the GUI tree. The argument giving the value is the same
2359 as the corresponding proto_tree_add_XXX() function; the rest of the
2360 arguments are a "printf"-style format and any arguments for that format.
2361 With these routines, unlike the proto_tree_add_XXX_format() routines,
2362 the name of the field is added automatically as in the
2363 proto_tree_add_XXX() functions; only the value is added with the format.
2365 proto_tree_add_text()
2366 ---------------------
2367 proto_tree_add_text() is used to add a label to the GUI tree. It will
2368 contain no value, so it is not searchable in the display filter process.
2369 This function was needed in the transition from the old-style proto_tree
2370 to this new-style proto_tree so that Wireshark would still decode all
2371 protocols w/o being able to filter on all protocols and fields.
2372 Otherwise we would have had to cripple Wireshark's functionality while we
2373 converted all the old-style proto_tree calls to the new-style proto_tree
2374 calls. In other words, you should not use this in new code unless you've got
2375 a specific reason (see below).
2377 This can also be used for items with subtrees, which may not have values
2378 themselves - the items in the subtree are the ones with values.
2380 For a subtree, the label on the subtree might reflect some of the items
2381 in the subtree. This means the label can't be set until at least some
2382 of the items in the subtree have been dissected. To do this, use
2383 'proto_item_set_text()' or 'proto_item_append_text()':
2386 proto_item_set_text(proto_item *ti, ...);
2389 proto_item_append_text(proto_item *ti, ...);
2391 'proto_item_set_text()' takes as an argument the value returned by
2392 'proto_tree_add_text()', a 'printf'-style format string, and a set of
2393 arguments corresponding to '%' format items in that string, and replaces
2394 the text for the item created by 'proto_tree_add_text()' with the result
2395 of applying the arguments to the format string.
2397 'proto_item_append_text()' is similar, but it appends to the text for
2398 the item the result of applying the arguments to the format string.
2400 For example, early in the dissection, one might do:
2402 ti = proto_tree_add_text(tree, tvb, offset, length, <label>);
2406 proto_item_set_text(ti, "%s: %s", type, value);
2408 after the "type" and "value" fields have been extracted and dissected.
2409 <label> would be a label giving what information about the subtree is
2410 available without dissecting any of the data in the subtree.
2412 Note that an exception might thrown when trying to extract the values of
2413 the items used to set the label, if not all the bytes of the item are
2414 available. Thus, one should create the item with text that is as
2415 meaningful as possible, and set it or append additional information to
2416 it as the values needed to supply that information is extracted.
2418 proto_tree_add_text_valist()
2419 ----------------------------
2420 This is like proto_tree_add_text(), but takes, as the last argument, a
2421 'va_list'; it is used to allow routines that take a printf-like
2422 variable-length list of arguments to add a text item to the protocol
2425 proto_tree_add_bitmask()
2426 ------------------------
2427 This function provides an easy to use and convenient helper function
2428 to manage many types of common bitmasks that occur in protocols.
2430 This function will dissect a 1/2/3/4 byte large bitmask into its individual
2432 header is an integer type and must be of type FT_[U]INT{8|16|24|32} and
2433 represents the entire width of the bitmask.
2435 'header' and 'ett' are the hf fields and ett field respectively to create an
2436 expansion that covers the 1-4 bytes of the bitmask.
2438 '**fields' is a NULL terminated a array of pointers to hf fields representing
2439 the individual subfields of the bitmask. These fields must either be integers
2440 of the same byte width as 'header' or of the type FT_BOOLEAN.
2441 Each of the entries in '**fields' will be dissected as an item under the
2442 'header' expansion and also IF the field is a boolean and IF it is set to 1,
2443 then the name of that boolean field will be printed on the 'header' expansion
2444 line. For integer type subfields that have a value_string defined, the
2445 matched string from that value_string will be printed on the expansion line as well.
2447 Example: (from the scsi dissector)
2448 static int hf_scsi_inq_peripheral = -1;
2449 static int hf_scsi_inq_qualifier = -1;
2450 static gint ett_scsi_inq_peripheral = -1;
2452 static const int *peripheal_fields[] = {
2453 &hf_scsi_inq_qualifier,
2454 &hf_scsi_inq_devtype,
2458 /* Qualifier and DeviceType */
2459 proto_tree_add_bitmask(tree, tvb, offset, hf_scsi_inq_peripheral, ett_scsi_inq_peripheral, peripheal_fields, FALSE);
2462 { &hf_scsi_inq_peripheral,
2463 {"Peripheral", "scsi.inquiry.preipheral", FT_UINT8, BASE_HEX,
2464 NULL, 0, NULL, HFILL}},
2465 { &hf_scsi_inq_qualifier,
2466 {"Qualifier", "scsi.inquiry.qualifier", FT_UINT8, BASE_HEX,
2467 VALS (scsi_qualifier_val), 0xE0, NULL, HFILL}},
2470 Which provides very pretty dissection of this one byte bitmask.
2473 1.7 Utility routines.
2475 1.7.1 match_strval and val_to_str.
2477 A dissector may need to convert a value to a string, using a
2478 'value_string' structure, by hand, rather than by declaring a field with
2479 an associated 'value_string' structure; this might be used, for example,
2480 to generate a COL_INFO line for a frame.
2482 'match_strval()' will do that:
2485 match_strval(guint32 val, const value_string *vs)
2487 It will look up the value 'val' in the 'value_string' table pointed to
2488 by 'vs', and return either the corresponding string, or NULL if the
2489 value could not be found in the table. Note that, unless 'val' is
2490 guaranteed to be a value in the 'value_string' table ("guaranteed" as in
2491 "the code has already checked that it's one of those values" or "the
2492 table handles all possible values of the size of 'val'", not "the
2493 protocol spec says it has to be" - protocol specs do not prevent invalid
2494 packets from being put onto a network or into a purported packet capture
2495 file), you must check whether 'match_strval()' returns NULL, and arrange
2496 that its return value not be dereferenced if it's NULL. 'val_to_str()'
2497 can be used to generate a string for values not found in the table:
2500 val_to_str(guint32 val, const value_string *vs, const char *fmt)
2502 If the value 'val' is found in the 'value_string' table pointed to by
2503 'vs', 'val_to_str' will return the corresponding string; otherwise, it
2504 will use 'fmt' as an 'sprintf'-style format, with 'val' as an argument,
2505 to generate a string, and will return a pointer to that string.
2506 You can use it in a call to generate a COL_INFO line for a frame such as
2508 col_add_fstr(COL_INFO, ", %s", val_to_str(val, table, "Unknown %d"));
2510 1.7.2 match_strrval and rval_to_str.
2512 A dissector may need to convert a range of values to a string, using a
2513 'range_string' structure.
2515 'match_strrval()' will do that:
2518 match_strrval(guint32 val, const range_string *rs)
2520 It will look up the value 'val' in the 'range_string' table pointed to
2521 by 'rs', and return either the corresponding string, or NULL if the
2522 value could not be found in the table. Please note that its base
2523 behavior is inherited from match_strval().
2525 'rval_to_str()' can be used to generate a string for values not found in
2529 rval_to_str(guint32 val, const range_string *rs, const char *fmt)
2531 If the value 'val' is found in the 'range_string' table pointed to by
2532 'rs', 'rval_to_str' will return the corresponding string; otherwise, it
2533 will use 'fmt' as an 'sprintf'-style format, with 'val' as an argument,
2534 to generate a string, and will return a pointer to that string. Please
2535 note that its base behavior is inherited from match_strval().
2537 1.8 Calling Other Dissectors.
2539 As each dissector completes its portion of the protocol analysis, it
2540 is expected to create a new tvbuff of type TVBUFF_SUBSET which
2541 contains the payload portion of the protocol (that is, the bytes
2542 that are relevant to the next dissector).
2544 The syntax for creating a new TVBUFF_SUBSET is:
2546 next_tvb = tvb_new_subset(tvb, offset, length, reported_length)
2549 tvb is the tvbuff that the dissector has been working on. It
2550 can be a tvbuff of any type.
2552 next_tvb is the new TVBUFF_SUBSET.
2554 offset is the byte offset of 'tvb' at which the new tvbuff
2555 should start. The first byte is the 0th byte.
2557 length is the number of bytes in the new TVBUFF_SUBSET. A length
2558 argument of -1 says to use as many bytes as are available in
2561 reported_length is the number of bytes that the current protocol
2562 says should be in the payload. A reported_length of -1 says that
2563 the protocol doesn't say anything about the size of its payload.
2566 An example from packet-ipx.c -
2569 dissect_ipx(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2572 int reported_length, available_length;
2575 /* Make the next tvbuff */
2577 /* IPX does have a length value in the header, so calculate report_length */
2578 Set this to -1 if there isn't any length information in the protocol
2580 reported_length = ipx_length - IPX_HEADER_LEN;
2582 /* Calculate the available data in the packet,
2583 set this to -1 to use all the data in the tv_buffer
2585 available_length = tvb_length(tvb) - IPX_HEADER_LEN;
2587 /* Create the tvbuffer for the next dissector */
2588 next_tvb = tvb_new_subset(tvb, IPX_HEADER_LEN,
2589 MIN(available_length, reported_length),
2592 /* call the next dissector */
2593 dissector_next( next_tvb, pinfo, tree);
2596 1.9 Editing Makefile.common to add your dissector.
2598 To arrange that your dissector will be built as part of Wireshark, you
2599 must add the name of the source file for your dissector to the
2600 'DISSECTOR_SRC' macro in the 'Makefile.common' file in the 'epan/dissectors'
2601 directory. (Note that this is for modern versions of UNIX, so there
2602 is no 14-character limitation on file names, and for modern versions of
2603 Windows, so there is no 8.3-character limitation on file names.)
2605 If your dissector also has its own header file or files, you must add
2606 them to the 'DISSECTOR_INCLUDES' macro in the 'Makefile.common' file in
2607 the 'epan/dissectors' directory, so that it's included when release source
2608 tarballs are built (otherwise, the source in the release tarballs won't
2611 1.10 Using the SVN source code tree.
2613 See <http://www.wireshark.org/develop.html>
2615 1.11 Submitting code for your new dissector.
2617 - TEST YOUR DISSECTOR BEFORE SUBMITTING IT.
2618 Use fuzz-test.sh and/or randpkt against your dissector. These are
2619 described at <http://wiki.wireshark.org/FuzzTesting>.
2621 - Subscribe to <mailto:wireshark-dev[AT]wireshark.org> by sending an email to
2622 <mailto:wireshark-dev-request[AT]wireshark.org?body="help"> or visiting
2623 <http://www.wireshark.org/lists/>.
2625 - 'svn add' all the files of your new dissector.
2627 - 'svn diff' the workspace and save the result to a file.
2629 - Edit the diff file - remove any changes unrelated to your new dissector,
2630 e.g. changes in config.nmake
2632 - Send a note with the attached diff file requesting its inclusion to
2633 <mailto:wireshark-dev[AT]wireshark.org>. You can also use this procedure for
2634 providing patches to your dissector or any other part of Wireshark.
2636 - Create a Wiki page on the protocol at <http://wiki.wireshark.org>.
2637 A template is provided so it is easy to setup in a consistent style.
2639 - If possible, add sample capture files to the sample captures page at
2640 <http://wiki.wireshark.org/SampleCaptures>. These files are used by
2641 the automated build system for fuzz testing.
2643 - If you find that you are contributing a lot to wireshark on an ongoing
2644 basis you can request to become a committer which will allow you to
2645 commit files to subversion directly.
2647 2. Advanced dissector topics.
2651 Some of the advanced features are being worked on constantly. When using them
2652 it is wise to check the relevant header and source files for additional details.
2654 2.2 Following "conversations".
2656 In wireshark a conversation is defined as a series of data packet between two
2657 address:port combinations. A conversation is not sensitive to the direction of
2658 the packet. The same conversation will be returned for a packet bound from
2659 ServerA:1000 to ClientA:2000 and the packet from ClientA:2000 to ServerA:1000.
2661 There are five routines that you will use to work with a conversation:
2662 conversation_new, find_conversation, conversation_add_proto_data,
2663 conversation_get_proto_data, and conversation_delete_proto_data.
2666 2.2.1 The conversation_init function.
2668 This is an internal routine for the conversation code. As such the you
2669 will not have to call this routine. Just be aware that this routine is
2670 called at the start of each capture and before the packets are filtered
2671 with a display filter. The routine will destroy all stored
2672 conversations. This routine does NOT clean up any data pointers that are
2673 passed in the conversation_new 'data' variable. You are responsible for
2674 this clean up if you pass a malloc'ed pointer in this variable.
2676 See item 2.2.8 for more information about the 'data' pointer.
2679 2.2.2 The conversation_new function.
2681 This routine will create a new conversation based upon two address/port
2682 pairs. If you want to associate with the conversation a pointer to a
2683 private data structure you must use the conversation_add_proto_data
2684 function. The ptype variable is used to differentiate between
2685 conversations over different protocols, i.e. TCP and UDP. The options
2686 variable is used to define a conversation that will accept any destination
2687 address and/or port. Set options = 0 if the destination port and address
2688 are know when conversation_new is called. See section 2.4 for more
2689 information on usage of the options parameter.
2691 The conversation_new prototype:
2692 conversation_t *conversation_new(guint32 setup_frame, address *addr1,
2693 address *addr2, port_type ptype, guint32 port1, guint32 port2,
2697 guint32 setup_frame = The lowest numbered frame for this conversation
2698 address* addr1 = first data packet address
2699 address* addr2 = second data packet address
2700 port_type ptype = port type, this is defined in packet.h
2701 guint32 port1 = first data packet port
2702 guint32 port2 = second data packet port
2703 guint options = conversation options, NO_ADDR2 and/or NO_PORT2
2705 setup_frame indicates the first frame for this conversation, and is used to
2706 distinguish multiple conversations with the same addr1/port1 and addr2/port2
2707 pair that occur within the same capture session.
2709 "addr1" and "port1" are the first address/port pair; "addr2" and "port2"
2710 are the second address/port pair. A conversation doesn't have source
2711 and destination address/port pairs - packets in a conversation go in
2712 both directions - so "addr1"/"port1" may be the source or destination
2713 address/port pair; "addr2"/"port2" would be the other pair.
2715 If NO_ADDR2 is specified, the conversation is set up so that a
2716 conversation lookup will match only the "addr1" address; if NO_PORT2 is
2717 specified, the conversation is set up so that a conversation lookup will
2718 match only the "port1" port; if both are specified, i.e.
2719 NO_ADDR2|NO_PORT2, the conversation is set up so that the lookup will
2720 match only the "addr1"/"port1" address/port pair. This can be used if a
2721 packet indicates that, later in the capture, a conversation will be
2722 created using certain addresses and ports, in the case where the packet
2723 doesn't specify the addresses and ports of both sides.
2725 2.2.3 The find_conversation function.
2727 Call this routine to look up a conversation. If no conversation is found,
2728 the routine will return a NULL value.
2730 The find_conversation prototype:
2732 conversation_t *find_conversation(guint32 frame_num, address *addr_a,
2733 address *addr_b, port_type ptype, guint32 port_a, guint32 port_b,
2737 guint32 frame_num = a frame number to match
2738 address* addr_a = first address
2739 address* addr_b = second address
2740 port_type ptype = port type
2741 guint32 port_a = first data packet port
2742 guint32 port_b = second data packet port
2743 guint options = conversation options, NO_ADDR_B and/or NO_PORT_B
2745 frame_num is a frame number to match. The conversation returned is where
2746 (frame_num >= conversation->setup_frame
2747 && frame_num < conversation->next->setup_frame)
2748 Suppose there are a total of 3 conversations (A, B, and C) that match
2749 addr_a/port_a and addr_b/port_b, where the setup_frame used in
2750 conversation_new() for A, B and C are 10, 50, and 100 respectively. The
2751 frame_num passed in find_conversation is compared to the setup_frame of each
2752 conversation. So if (frame_num >= 10 && frame_num < 50), conversation A is
2753 returned. If (frame_num >= 50 && frame_num < 100), conversation B is returned.
2754 If (frame_num >= 100) conversation C is returned.
2756 "addr_a" and "port_a" are the first address/port pair; "addr_b" and
2757 "port_b" are the second address/port pair. Again, as a conversation
2758 doesn't have source and destination address/port pairs, so
2759 "addr_a"/"port_a" may be the source or destination address/port pair;
2760 "addr_b"/"port_b" would be the other pair. The search will match the
2761 "a" address/port pair against both the "1" and "2" address/port pairs,
2762 and match the "b" address/port pair against both the "2" and "1"
2763 address/port pairs; you don't have to worry about which side the "a" or
2764 "b" pairs correspond to.
2766 If the NO_ADDR_B flag was specified to "find_conversation()", the
2767 "addr_b" address will be treated as matching any "wildcarded" address;
2768 if the NO_PORT_B flag was specified, the "port_b" port will be treated
2769 as matching any "wildcarded" port. If both flags are specified, i.e.
2770 NO_ADDR_B|NO_PORT_B, the "addr_b" address will be treated as matching
2771 any "wildcarded" address and the "port_b" port will be treated as
2772 matching any "wildcarded" port.
2775 2.2.4 The conversation_add_proto_data function.
2777 Once you have created a conversation with conversation_new, you can
2778 associate data with it using this function.
2780 The conversation_add_proto_data prototype:
2782 void conversation_add_proto_data(conversation_t *conv, int proto,
2786 conversation_t *conv = the conversation in question
2787 int proto = registered protocol number
2788 void *data = dissector data structure
2790 "conversation" is the value returned by conversation_new. "proto" is a
2791 unique protocol number created with proto_register_protocol. Protocols
2792 are typically registered in the proto_register_XXXX section of your
2793 dissector. "data" is a pointer to the data you wish to associate with the
2794 conversation. Using the protocol number allows several dissectors to
2795 associate data with a given conversation.
2798 2.2.5 The conversation_get_proto_data function.
2800 After you have located a conversation with find_conversation, you can use
2801 this function to retrieve any data associated with it.
2803 The conversation_get_proto_data prototype:
2805 void *conversation_get_proto_data(conversation_t *conv, int proto);
2808 conversation_t *conv = the conversation in question
2809 int proto = registered protocol number
2811 "conversation" is the conversation created with conversation_new. "proto"
2812 is a unique protocol number created with proto_register_protocol,
2813 typically in the proto_register_XXXX portion of a dissector. The function
2814 returns a pointer to the data requested, or NULL if no data was found.
2817 2.2.6 The conversation_delete_proto_data function.
2819 After you are finished with a conversation, you can remove your association
2820 with this function. Please note that ONLY the conversation entry is
2821 removed. If you have allocated any memory for your data, you must free it
2824 The conversation_delete_proto_data prototype:
2826 void conversation_delete_proto_data(conversation_t *conv, int proto);
2829 conversation_t *conv = the conversation in question
2830 int proto = registered protocol number
2832 "conversation" is the conversation created with conversation_new. "proto"
2833 is a unique protocol number created with proto_register_protocol,
2834 typically in the proto_register_XXXX portion of a dissector.
2837 2.2.7 Using timestamps relative to the conversation
2839 There is a framework to calculate timestams relative to the start of the
2840 conversation. First of all the timestamp of the first packet that has been
2841 seen in the conversation must be kept in the protocol data to be able
2842 to calculate the timestamp of the current packet relative to the start
2843 of the conversation. The timestamp of the last packet that was seen in the
2844 conversation should also be kept in the protocol data. This way the
2845 delta time between the current packet and the previous packet in the
2846 conversation can be calculated.
2848 So add the following items to the struct that is used for the protocol data:
2853 The ts_prev value should only be set during the first run through the
2854 packets (ie pinfo->fd->flags.visited is false).
2856 Next step is to use the per packet information (described in section 2.5)
2857 to keep the calculated delta timestamp, as it can only be calculated
2858 on the first run through the packets. This is because a packet can be
2859 selected in random order once the whole file has been read.
2861 After calculating the conversation timestamps, it is time to put them in
2862 the appropriate columns with the function 'col_set_time' (described in
2863 section 1.5.9). There are two columns for conversation timestamps:
2865 COL_REL_CONV_TIME, /* Relative time to beginning of conversation */
2866 COL_DELTA_CONV_TIME,/* Delta time to last frame in conversation */
2868 Last but not least, there MUST be a preference in each dissector that
2869 uses conversation timestamps that makes it possible to enable and
2870 dissable the calculation of conversation timestamps. The main argument
2871 for this is that a higher level conversation is able to overwrite
2872 the values of lowel level conversations in these two columns. Being
2873 able to actively select which protocols may overwrite the conversation
2874 timestamp columns give the user the power to control these columns.
2875 (A second reason is that conversation timestamps use the per packet
2876 data structure which uses additional memory, which should be avoided
2877 if these timestamps are not needed)
2879 Have a look at the differences to packet-tcp.[ch] in SVN 22966 and
2880 SVN 23058 to see the implementation of conversation timestamps for
2884 2.2.8 The example conversation code with GMemChunk's.
2886 For a conversation between two IP addresses and ports you can use this as an
2887 example. This example uses the GMemChunk to allocate memory and stores the data
2888 pointer in the conversation 'data' variable.
2890 NOTE: Remember to register the init routine (my_dissector_init) in the
2891 protocol_register routine.
2894 /************************ Global values ************************/
2896 /* the number of entries in the memory chunk array */
2897 #define my_init_count 10
2899 /* define your structure here */
2904 /* the GMemChunk base structure */
2905 static GMemChunk *my_vals = NULL;
2907 /* Registered protocol number */
2908 static int my_proto = -1;
2911 /********************* in the dissector routine *********************/
2913 /* the local variables in the dissector */
2915 conversation_t *conversation;
2916 my_entry_t *data_ptr;
2919 /* look up the conversation */
2921 conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst,
2922 pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
2924 /* if conversation found get the data pointer that you stored */
2926 data_ptr = (my_entry_t*)conversation_get_proto_data(conversation, my_proto);
2929 /* new conversation create local data structure */
2931 data_ptr = g_mem_chunk_alloc(my_vals);
2933 /*** add your code here to setup the new data structure ***/
2935 /* create the conversation with your data pointer */
2937 conversation = conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst, pinfo->ptype,
2938 pinfo->srcport, pinfo->destport, 0);
2939 conversation_add_proto_data(conversation, my_proto, (void *)data_ptr);
2942 /* at this point the conversation data is ready */
2945 /******************* in the dissector init routine *******************/
2947 #define my_init_count 20
2950 my_dissector_init(void)
2953 /* destroy memory chunks if needed */
2956 g_mem_chunk_destroy(my_vals);
2958 /* now create memory chunks */
2960 my_vals = g_mem_chunk_new("my_proto_vals",
2962 my_init_count * sizeof(my_entry_t),
2966 /***************** in the protocol register routine *****************/
2968 /* register re-init routine */
2970 register_init_routine(&my_dissector_init);
2972 my_proto = proto_register_protocol("My Protocol", "My Protocol", "my_proto");
2975 2.2.9 An example conversation code that starts at a specific frame number.
2977 Sometimes a dissector has determined that a new conversation is needed that
2978 starts at a specific frame number, when a capture session encompasses multiple
2979 conversation that reuse the same src/dest ip/port pairs. You can use the
2980 compare the conversation->setup_frame returned by find_conversation with
2981 pinfo->fd->num to determine whether or not there already exists a conversation
2982 that starts at the specific frame number.
2984 /* in the dissector routine */
2986 conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst,
2987 pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
2988 if (conversation == NULL || (conversation->setup_frame != pinfo->fd->num)) {
2989 /* It's not part of any conversation or the returned
2990 * conversation->setup_frame doesn't match the current frame
2993 conversation = conversation_new(pinfo->fd->num, &pinfo->src,
2994 &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport,
2999 2.2.10 The example conversation code using conversation index field.
3001 Sometimes the conversation isn't enough to define a unique data storage
3002 value for the network traffic. For example if you are storing information
3003 about requests carried in a conversation, the request may have an
3004 identifier that is used to define the request. In this case the
3005 conversation and the identifier are required to find the data storage
3006 pointer. You can use the conversation data structure index value to
3007 uniquely define the conversation.
3009 See packet-afs.c for an example of how to use the conversation index. In
3010 this dissector multiple requests are sent in the same conversation. To store
3011 information for each request the dissector has an internal hash table based
3012 upon the conversation index and values inside the request packets.
3015 /* in the dissector routine */
3017 /* to find a request value, first lookup conversation to get index */
3018 /* then used the conversation index, and request data to find data */
3019 /* in the local hash table */
3021 conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst,
3022 pinfo->ptype, pinfo->srcport, pinfo->destport, 0);
3023 if (conversation == NULL) {
3024 /* It's not part of any conversation - create a new one. */
3025 conversation = conversation_new(pinfo->fd->num, &pinfo->src,
3026 &pinfo->dst, pinfo->ptype, pinfo->srcport, pinfo->destport,
3030 request_key.conversation = conversation->index;
3031 request_key.service = pntohs(&rxh->serviceId);
3032 request_key.callnumber = pntohl(&rxh->callNumber);
3034 request_val = (struct afs_request_val *)g_hash_table_lookup(
3035 afs_request_hash, &request_key);
3037 /* only allocate a new hash element when it's a request */
3039 if (!request_val && !reply)
3041 new_request_key = g_mem_chunk_alloc(afs_request_keys);
3042 *new_request_key = request_key;
3044 request_val = g_mem_chunk_alloc(afs_request_vals);
3045 request_val -> opcode = pntohl(&afsh->opcode);
3046 opcode = request_val->opcode;
3048 g_hash_table_insert(afs_request_hash, new_request_key,
3054 2.3 Dynamic conversation dissector registration.
3057 NOTE: This sections assumes that all information is available to
3058 create a complete conversation, source port/address and
3059 destination port/address. If either the destination port or
3060 address is know, see section 2.4 Dynamic server port dissector
3063 For protocols that negotiate a secondary port connection, for example
3064 packet-msproxy.c, a conversation can install a dissector to handle
3065 the secondary protocol dissection. After the conversation is created
3066 for the negotiated ports use the conversation_set_dissector to define
3067 the dissection routine.
3068 Before we create these conversations or assign a dissector to them we should
3069 first check that the conversation does not already exist and if it exists
3070 whether it is registered to our protocol or not.
3071 We should do this because is uncommon but it does happen that multiple
3072 different protocols can use the same socketpair during different stages of
3073 an application cycle. By keeping track of the frame number a conversation
3074 was started in wireshark can still tell these different protocols apart.
3076 The second argument to conversation_set_dissector is a dissector handle,
3077 which is created with a call to create_dissector_handle or
3080 create_dissector_handle takes as arguments a pointer to the dissector
3081 function and a protocol ID as returned by proto_register_protocol;
3082 register_dissector takes as arguments a string giving a name for the
3083 dissector, a pointer to the dissector function, and a protocol ID.
3085 The protocol ID is the ID for the protocol dissected by the function.
3086 The function will not be called if the protocol has been disabled by the
3087 user; instead, the data for the protocol will be dissected as raw data.
3091 /* the handle for the dynamic dissector *
3092 static dissector_handle_t sub_dissector_handle;
3094 /* prototype for the dynamic dissector */
3095 static void sub_dissector(tvbuff_t *tvb, packet_info *pinfo,
3098 /* in the main protocol dissector, where the next dissector is setup */
3100 /* if conversation has a data field, create it and load structure */
3102 /* First check if a conversation already exists for this
3105 conversation = find_conversation(pinfo->fd->num,
3106 &pinfo->src, &pinfo->dst, protocol,
3107 src_port, dst_port, new_conv_info, 0);
3109 /* If there is no such conversation, or if there is one but for
3110 someone else's protocol then we just create a new conversation
3111 and assign our protocol to it.
3113 if ( (conversation == NULL) ||
3114 (conversation->dissector_handle != sub_dissector_handle) ) {
3115 new_conv_info = g_mem_chunk_alloc(new_conv_vals);
3116 new_conv_info->data1 = value1;
3118 /* create the conversation for the dynamic port */
3119 conversation = conversation_new(pinfo->fd->num,
3120 &pinfo->src, &pinfo->dst, protocol,
3121 src_port, dst_port, new_conv_info, 0);
3123 /* set the dissector for the new conversation */
3124 conversation_set_dissector(conversation, sub_dissector_handle);
3129 proto_register_PROTOABBREV(void)
3133 sub_dissector_handle = create_dissector_handle(sub_dissector,
3139 2.4 Dynamic server port dissector registration.
3141 NOTE: While this example used both NO_ADDR2 and NO_PORT2 to create a
3142 conversation with only one port and address set, this isn't a
3143 requirement. Either the second port or the second address can be set
3144 when the conversation is created.
3146 For protocols that define a server address and port for a secondary
3147 protocol, a conversation can be used to link a protocol dissector to
3148 the server port and address. The key is to create the new
3149 conversation with the second address and port set to the "accept
3152 Some server applications can use the same port for different protocols during
3153 different stages of a transaction. For example it might initially use SNMP
3154 to perform some discovery and later switch to use TFTP using the same port.
3155 In order to handle this properly we must first check whether such a
3156 conversation already exists or not and if it exists we also check whether the
3157 registered dissector_handle for that conversation is "our" dissector or not.
3158 If not we create a new conversation on top of the previous one and set this new
3159 conversation to use our protocol.
3160 Since wireshark keeps track of the frame number where a conversation started
3161 wireshark will still be able to keep the packets apart even though they do use
3162 the same socketpair.
3163 (See packet-tftp.c and packet-snmp.c for examples of this)
3165 There are two support routines that will allow the second port and/or
3166 address to be set latter.
3168 conversation_set_port2( conversation_t *conv, guint32 port);
3169 conversation_set_addr2( conversation_t *conv, address addr);
3171 These routines will change the second address or port for the
3172 conversation. So, the server port conversation will be converted into a
3173 more complete conversation definition. Don't use these routines if you
3174 want create a conversation between the server and client and retain the
3175 server port definition, you must create a new conversation.
3180 /* the handle for the dynamic dissector *
3181 static dissector_handle_t sub_dissector_handle;
3185 /* in the main protocol dissector, where the next dissector is setup */
3187 /* if conversation has a data field, create it and load structure */
3189 new_conv_info = g_mem_chunk_alloc(new_conv_vals);
3190 new_conv_info->data1 = value1;
3192 /* create the conversation for the dynamic server address and port */
3193 /* NOTE: The second address and port values don't matter because the */
3194 /* NO_ADDR2 and NO_PORT2 options are set. */
3196 /* First check if a conversation already exists for this
3199 conversation = find_conversation(pinfo->fd->num,
3200 &server_src_addr, 0, protocol,
3201 server_src_port, 0, NO_ADDR2 | NO_PORT_B);
3202 /* If there is no such conversation, or if there is one but for
3203 someone else's protocol then we just create a new conversation
3204 and assign our protocol to it.
3206 if ( (conversation == NULL) ||
3207 (conversation->dissector_handle != sub_dissector_handle) ) {
3208 conversation = conversation_new(pinfo->fd->num,
3209 &server_src_addr, 0, protocol,
3210 server_src_port, 0, new_conv_info, NO_ADDR2 | NO_PORT2);
3212 /* set the dissector for the new conversation */
3213 conversation_set_dissector(conversation, sub_dissector_handle);
3216 2.5 Per packet information.
3218 Information can be stored for each data packet that is processed by the
3219 dissector. The information is added with the p_add_proto_data function and
3220 retrieved with the p_get_proto_data function. The data pointers passed into
3221 the p_add_proto_data are not managed by the proto_data routines. If you use
3222 malloc or any other dynamic memory allocation scheme, you must release the
3223 data when it isn't required.
3226 p_add_proto_data(frame_data *fd, int proto, void *proto_data)
3228 p_get_proto_data(frame_data *fd, int proto)
3231 fd - The fd pointer in the pinfo structure, pinfo->fd
3232 proto - Protocol id returned by the proto_register_protocol call
3233 during initialization
3234 proto_data - pointer to the dissector data.
3237 2.6 User Preferences.
3239 If the dissector has user options, there is support for adding these preferences
3240 to a configuration dialog.
3242 You must register the module with the preferences routine with -
3244 module_t *prefs_register_protocol(proto_id, void (*apply_cb)(void))
3246 Where: proto_id - the value returned by "proto_register_protocol()" when
3247 the protocol was registered
3248 apply_cb - Callback routine that is call when preferences are applied
3251 Then you can register the fields that can be configured by the user with these
3254 /* Register a preference with an unsigned integral value. */
3255 void prefs_register_uint_preference(module_t *module, const char *name,
3256 const char *title, const char *description, guint base, guint *var);
3258 /* Register a preference with an Boolean value. */
3259 void prefs_register_bool_preference(module_t *module, const char *name,
3260 const char *title, const char *description, gboolean *var);
3262 /* Register a preference with an enumerated value. */
3263 void prefs_register_enum_preference(module_t *module, const char *name,
3264 const char *title, const char *description, gint *var,
3265 const enum_val_t *enumvals, gboolean radio_buttons)
3267 /* Register a preference with a character-string value. */
3268 void prefs_register_string_preference(module_t *module, const char *name,
3269 const char *title, const char *description, char **var)
3271 /* Register a preference with a range of unsigned integers (e.g.,
3274 void prefs_register_range_preference(module_t *module, const char *name,
3275 const char *title, const char *description, range_t *var,
3278 Where: module - Returned by the prefs_register_protocol routine
3279 name - This is appended to the name of the protocol, with a
3280 "." between them, to construct a name that identifies
3281 the field in the preference file; the name itself
3282 should not include the protocol name, as the name in
3283 the preference file will already have it
3284 title - Field title in the preferences dialog
3285 description - Comments added to the preference file above the
3287 var - pointer to the storage location that is updated when the
3288 field is changed in the preference dialog box
3289 base - Base that the unsigned integer is expected to be in,
3291 enumvals - an array of enum_val_t structures. This must be
3292 NULL-terminated; the members of that structure are:
3294 a short name, to be used with the "-o" flag - it
3295 should not contain spaces or upper-case letters,
3296 so that it's easier to put in a command line;
3298 a description, which is used in the GUI (and
3299 which, for compatibility reasons, is currently
3300 what's written to the preferences file) - it can
3301 contain spaces, capital letters, punctuation,
3304 the numerical value corresponding to that name
3306 radio_buttons - TRUE if the field is to be displayed in the
3307 preferences dialog as a set of radio buttons,
3308 FALSE if it is to be displayed as an option
3310 max_value - The maximum allowed value for a range (0 is the minimum).
3312 An example from packet-beep.c -
3314 proto_beep = proto_register_protocol("Blocks Extensible Exchange Protocol",
3319 /* Register our configuration options for BEEP, particularly our port */
3321 beep_module = prefs_register_protocol(proto_beep, proto_reg_handoff_beep);
3323 prefs_register_uint_preference(beep_module, "tcp.port", "BEEP TCP Port",
3324 "Set the port for BEEP messages (if other"
3325 " than the default of 10288)",
3326 10, &global_beep_tcp_port);
3328 prefs_register_bool_preference(beep_module, "strict_header_terminator",
3329 "BEEP Header Requires CRLF",
3330 "Specifies that BEEP requires CRLF as a "
3331 "terminator, and not just CR or LF",
3332 &global_beep_strict_term);
3334 This will create preferences "beep.tcp.port" and
3335 "beep.strict_header_terminator", the first of which is an unsigned
3336 integer and the second of which is a Boolean.
3338 Note that a warning will pop up if you've saved such preference to the
3339 preference file and you subsequently take the code out. The way to make
3340 a preference obsolete is to register it as such:
3342 /* Register a preference that used to be supported but no longer is. */
3343 void prefs_register_obsolete_preference(module_t *module,
3346 2.7 Reassembly/desegmentation for protocols running atop TCP.
3348 There are two main ways of reassembling a Protocol Data Unit (PDU) which
3349 spans across multiple TCP segments. The first approach is simpler, but
3350 assumes you are running atop of TCP when this occurs (but your dissector
3351 might run atop of UDP, too, for example), and that your PDUs consist of a
3352 fixed amount of data that includes enough information to determine the PDU
3353 length, possibly followed by additional data. The second method is more
3354 generic but requires more code and is less efficient.
3356 2.7.1 Using tcp_dissect_pdus().
3358 For the first method, you register two different dissection methods, one
3359 for the TCP case, and one for the other cases. It is a good idea to
3360 also have a dissect_PROTO_common function which will parse the generic
3361 content that you can find in all PDUs which is called from
3362 dissect_PROTO_tcp when the reassembly is complete and from
3363 dissect_PROTO_udp (or dissect_PROTO_other).
3365 To register the distinct dissector functions, consider the following
3366 example, stolen from packet-dns.c:
3368 dissector_handle_t dns_udp_handle;
3369 dissector_handle_t dns_tcp_handle;
3370 dissector_handle_t mdns_udp_handle;
3372 dns_udp_handle = create_dissector_handle(dissect_dns_udp,
3374 dns_tcp_handle = create_dissector_handle(dissect_dns_tcp,
3376 mdns_udp_handle = create_dissector_handle(dissect_mdns_udp,
3379 dissector_add("udp.port", UDP_PORT_DNS, dns_udp_handle);
3380 dissector_add("tcp.port", TCP_PORT_DNS, dns_tcp_handle);
3381 dissector_add("udp.port", UDP_PORT_MDNS, mdns_udp_handle);
3382 dissector_add("tcp.port", TCP_PORT_MDNS, dns_tcp_handle);
3384 The dissect_dns_udp function does very little work and calls
3385 dissect_dns_common, while dissect_dns_tcp calls tcp_dissect_pdus with a
3386 reference to a callback which will be called with reassembled data:
3389 dissect_dns_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
3391 tcp_dissect_pdus(tvb, pinfo, tree, dns_desegment, 2,
3392 get_dns_pdu_len, dissect_dns_tcp_pdu);
3395 (The dissect_dns_tcp_pdu function acts similarly to dissect_dns_udp.)
3396 The arguments to tcp_dissect_pdus are:
3398 the tvbuff pointer, packet_info pointer, and proto_tree pointer
3399 passed to the dissector;
3401 a gboolean flag indicating whether desegmentation is enabled for
3404 the number of bytes of PDU data required to determine the length
3407 a routine that takes as arguments a packet_info pointer, a tvbuff
3408 pointer and an offset value representing the offset into the tvbuff
3409 at which a PDU begins and should return - *without* throwing an
3410 exception (it is guaranteed that the number of bytes specified by the
3411 previous argument to tcp_dissect_pdus is available, but more data
3412 might not be available, so don't refer to any data past that) - the
3413 total length of the PDU, in bytes;
3415 a routine that's passed a tvbuff pointer, packet_info pointer,
3416 and proto_tree pointer, with the tvbuff containing a
3417 possibly-reassembled PDU, and that should dissect that PDU.
3419 2.7.2 Modifying the pinfo struct.
3421 The second reassembly mode is preferred when the dissector cannot determine
3422 how many bytes it will need to read in order to determine the size of a PDU.
3423 It may also be useful if your dissector needs to support reassembly from
3424 protocols other than TCP.
3426 Your dissect_PROTO will initially be passed a tvbuff containing the payload of
3427 the first packet. It should dissect as much data as it can, noting that it may
3428 contain more than one complete PDU. If the end of the provided tvbuff coincides
3429 with the end of a PDU then all is well and your dissector can just return as
3430 normal. (If it is a new-style dissector, it should return the number of bytes
3431 successfully processed.)
3433 If the dissector discovers that the end of the tvbuff does /not/ coincide with
3434 the end of a PDU, (ie, there is half of a PDU at the end of the tvbuff), it can
3435 indicate this to the parent dissector, by updating the pinfo struct. The
3436 desegment_offset field is the offset in the tvbuff at which the dissector will
3437 continue processing when next called. The desegment_len field should contain
3438 the estimated number of additional bytes required for completing the PDU. Next
3439 time your dissect_PROTO is called, it will be passed a tvbuff composed of the
3440 end of the data from the previous tvbuff together with desegment_len more bytes.
3442 If the dissector cannot tell how many more bytes it will need, it should set
3443 desegment_len=DESEGMENT_ONE_MORE_SEGMENT; it will then be called again as soon
3444 as any more data becomes available. Dissectors should set the desegment_len to a
3445 reasonable value when possible rather than always setting
3446 DESEGMENT_ONE_MORE_SEGMENT as it will generally be more efficient. Also, you
3447 *must not* set desegment_len=1 in this case, in the hope that you can change
3448 your mind later: once you return a positive value from desegment_len, your PDU
3449 boundary is set in stone.
3451 static hf_register_info hf[] = {
3453 {"C String", "c.string", FT_STRING, BASE_NONE, NULL, 0x0,
3459 * Dissect a buffer containing C strings.
3461 * @param tvb The buffer to dissect.
3462 * @param pinfo Packet Info.
3463 * @param tree The protocol tree.
3465 static void dissect_cstr(tvbuff_t * tvb, packet_info * pinfo, proto_tree * tree)
3468 while(offset < tvb_reported_length(tvb)) {
3469 gint available = tvb_reported_length_remaining(tvb, offset);
3470 gint len = tvb_strnlen(tvb, offset, available);
3473 /* we ran out of data: ask for more */
3474 pinfo->desegment_offset = offset;
3475 pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
3479 if (check_col(pinfo->cinfo, COL_INFO)) {
3480 col_set_str(pinfo->cinfo, COL_INFO, "C String");
3483 len += 1; /* Add one for the '\0' */
3486 proto_tree_add_item(tree, hf_cstring, tvb, offset, len, FALSE);
3488 offset += (guint)len;
3491 /* if we get here, then the end of the tvb coincided with the end of a
3492 string. Happy days. */
3495 This simple dissector will repeatedly return DESEGMENT_ONE_MORE_SEGMENT
3496 requesting more data until the tvbuff contains a complete C string. The C string
3497 will then be added to the protocol tree. Note that there may be more
3498 than one complete C string in the tvbuff, so the dissection is done in a
3503 The ptvcursor API allows a simpler approach to writing dissectors for
3504 simple protocols. The ptvcursor API works best for protocols whose fields
3505 are static and whose format does not depend on the value of other fields.
3506 However, even if only a portion of your protocol is statically defined,
3507 then that portion could make use of ptvcursors.
3509 The ptvcursor API lets you extract data from a tvbuff, and add it to a
3510 protocol tree in one step. It also keeps track of the position in the
3511 tvbuff so that you can extract data again without having to compute any
3512 offsets --- hence the "cursor" name of the API.
3514 The three steps for a simple protocol are:
3515 1. Create a new ptvcursor with ptvcursor_new()
3516 2. Add fields with multiple calls of ptvcursor_add()
3517 3. Delete the ptvcursor with ptvcursor_free()
3519 ptvcursor offers the possibility to add subtrees in the tree as well. It can be
3520 done in very simple steps :
3521 1. Create a new subtree with ptvcursor_push_subtree(). The old subtree is
3522 pushed in a stack and the new subtree will be used by ptvcursor.
3523 2. Add fields with multiple calls of ptvcursor_add(). The fields will be
3524 added in the new subtree created at the previous step.
3525 3. Pop the previous subtree with ptvcursor_pop_subtree(). The previous
3526 subtree is again used by ptvcursor.
3527 Note that at the end of the parsing of a packet you must have popped each
3528 subtree you pushed. If it's not the case, the dissector will generate an error.
3530 To use the ptvcursor API, include the "ptvcursor.h" file. The PGM dissector
3531 is an example of how to use it. You don't need to look at it as a guide;
3532 instead, the API description here should be good enough.
3534 2.8.1 ptvcursor API.
3537 ptvcursor_new(proto_tree*, tvbuff_t*, gint offset)
3538 This creates a new ptvcursor_t object for iterating over a tvbuff.
3539 You must call this and use this ptvcursor_t object so you can use the
3543 ptvcursor_add(ptvcursor_t*, int hf, gint length, gboolean endianness)
3544 This will extract 'length' bytes from the tvbuff and place it in
3545 the proto_tree as field 'hf', which is a registered header_field. The
3546 pointer to the proto_item that is created is passed back to you. Internally,
3547 the ptvcursor advances its cursor so the next call to ptvcursor_add
3548 starts where this call finished. The 'endianness' parameter matters for
3549 FT_UINT* and FT_INT* fields.
3552 ptvcursor_add_no_advance(ptvcursor_t*, int hf, gint length, gboolean endianness)
3553 Like ptvcursor_add, but does not advance the internal cursor.
3556 ptvcursor_advance(ptvcursor_t*, gint length)
3557 Advances the internal cursor without adding anything to the proto_tree.
3560 ptvcursor_free(ptvcursor_t*)
3561 Frees the memory associated with the ptvcursor. You must call this
3562 after your dissection with the ptvcursor API is completed.
3566 ptvcursor_push_subtree(ptvcursor_t *ptvc, proto_item *it, gint ett_subtree)
3567 Pushes the current subtree in the tree stack of the cursor, creates a new
3568 one and sets this one as the working tree.
3571 ptvcursor_pop_subtree(ptvcursor_t *ptvc);
3572 Pops a subtree in the tree stack of the cursor
3575 ptvcursor_add_with_subtree(ptvcursor_t * ptvc, int hfindex, gint length,
3576 gboolean little_endian, gint ett_subtree);
3577 Adds an item to the tree and creates a subtree.
3578 If the length is unknown, length may be defined as
3579 SUBTREE_UNDEFINED_LENGTH. In this case, at the next pop, the item length
3580 will be equal to the advancement of the cursor since the creation of the
3584 ptvcursor_add_text_with_subtree(ptvcursor_t * ptvc, gint length,
3585 gint ett_subtree, const char *format, ...);
3586 Add a text node to the tree and create a subtree
3587 If the length is unknown, length may be defined as
3588 SUBTREE_UNDEFINED_LENGTH. In this case, at the next pop, the item length
3589 will be equal to the advancement of the cursor since the creation of the
3592 2.8.2 Miscellaneous functions.
3595 ptvcursor_tvbuff(ptvcursor_t*)
3596 returns the tvbuff associated with the ptvcursor
3599 ptvcursor_current_offset(ptvcursor_t*)
3600 returns the current offset
3603 ptvcursor_tree(ptvcursor_t*)
3604 returns the proto_tree associated with the ptvcursor
3607 ptvcursor_set_tree(ptvcursor_t*, proto_tree *)
3608 sets a new proto_tree for the ptvcursor