1 <!-- WSDG Chapter Dissection -->
4 <chapter id="ChapterDissection">
5 <title>Packet dissection</title>
6 <!-- Julian Onions additions -->
7 <section id="ChDissectWorks">
8 <title>How it works</title>
10 Each dissector decodes it's part of the protocol, and then hand off
11 decoding to subsequent dissectors for an encapsulated protocol.
14 So it might all start with a Frame dissector which dissects the packet details
15 of the capture file itself (e.g. timestamps), passes the data on to an
16 Ethernet frame dissector that decodes the Ethernet header,
17 and then passes the payload to the next dissector (e.g. IP) and so on.
18 At each stage, details of the packet will be decoded and displayed.
21 Dissection can be implemented in two possible ways. One is to have a dissector
22 module compiled into the main program, which means its always available.
23 Another way is to make a plugin (a shared library/DLL) that registers itself
24 to handle dissection. - XXX add a special explanation section for this?
28 <section id="ChDissectAdd">
29 <title>Adding a basic dissector</title>
31 Lets step through adding a basic dissector. We'll start with the made up
32 "foo" protocol. It consists of the following basic items.
36 A packet type - 8 bits, possible values: 1 - initialisation, 2 - terminate, 3 - data.
39 A set of flags stored in 8 bits, 0x01 - start packet, 0x02 - end packet, 0x04 - priority packet.
42 A sequence number - 16 bits.
48 <section id="ChDissectSetup">
49 <title>Setting up the dissector</title>
51 The first decision you need to make is if this dissector will be a
52 built in dissector, included in the main program, or a plugin.
55 Plugins are the easiest to write initially as they don't need
56 write permission on the main code base. So lets start with that.
57 With a little care, the plugin can be made to run as a built in
58 easily too - so we haven't lost anything.
60 <example><title>Basic Plugin setup.</title>
68 #include <epan/packet.h>
69 #include <epan/prefs.h>
71 /* forward reference */
72 void proto_register_foo();
73 void proto_reg_handoff_foo();
74 void dissect_foo(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
76 /* Define version if we are not building Wireshark statically */
78 G_MODULE_EXPORT const gchar version[] = "0.0";
81 static int proto_foo = -1;
82 static int global_foo_port = 1234;
83 static dissector_handle_t foo_handle;
89 /* register the new protocol, protocol fields, and subtrees */
90 if (proto_foo == -1) { /* execute protocol initialization only once */
96 plugin_reg_handoff(void){
97 proto_reg_handoff_foo();
103 Lets go through this a bit at a time. First we have some boiler plate
104 include files. These will be pretty constant to start with. Here we also
105 pre-declare some functions that we'll be writing shortly.
108 Next we have a section surrounded by #ifdef ENABLE_STATIC. This is what
109 makes this a plugin rather than a built in dissector.
112 The version is a simple string that is used to report on the version of this
113 dissector. You should increase this number each time you make changes that you
114 need to keep track of.
117 Next we have an int that is initialised to -1 that records our protocol.
118 This will get updated when we register this plugin with the main program.
119 We can use this as a handy way to detect if we've been initialised yet.
120 Its good practice to make all variables and functions that aren't exported
121 static to keep name space pollution. Normally this isn't a problem unless your
122 dissector gets so big it has to span multiple files.
125 Then a global variable which contains the UDP port that we'll assume we are dissecting traffic for.
128 Next a dissector reference that we'll initialise later.
131 Next, the first plugin entry point. The function plugin_register() is called
132 when the plugin is loaded and allows you to do some initialisation stuff,
133 which will include communicating with the main program what you're plugins
137 The plugin_reg_handoff routine is used when dissecting sub protocols. As our
138 hypothetical protocol will be hypothetically carried over UDP then we will
142 Now we have the basics in place to interact with the main program, we had
143 better fill in those missing functions. Lets start with register function.
145 <example><title>Plugin Initialisation.</title>
149 proto_register_foo(void)
151 module_t *foo_module;
153 if (proto_foo == -1) {
154 proto_foo = proto_register_protocol (
155 "FOO Protocol", /* name */
156 "FOO", /* short name */
160 foo_module = prefs_register_protocol(proto_foo, proto_reg_handoff_foo);
162 </programlisting></example>
164 First a call to proto_register_protocol that
165 registers the protocol. We can give it three names that
166 will be used in various places to display it.
167 - XXX explain where, this can be confusing
170 Then we call the preference register function. At the moment we have
171 no specific protocol preferences so this will be all that we need.
172 This takes a function parameter which is our handoff function.
173 I guess we'd better write that next.
175 <example><title>Plugin Handoff.</title>
179 proto_reg_handoff_foo(void)
181 static int Initialized=FALSE;
184 foo_handle = create_dissector_handle(dissect_foo, proto_foo);
185 dissector_add("udp.port", global_foo_port, foo_handle);
188 </programlisting></example>
190 What's happening here? We are initialising the dissector if it hasn't
191 been initialised yet.
192 First we create the dissector. This registers a routine
193 to be called to do the actual dissecting.
194 Then we associate it with a udp port number
195 so that the main program will know to call us when it gets UDP traffic on that port.
198 Now at last we finally get to write some dissecting code. For the moment we'll
199 leave it as a basic placeholder.
201 <example><title>Plugin Dissection.</title>
205 dissect_foo(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
208 if (check_col(pinfo->cinfo, COL_PROTOCOL))
209 col_set_str(pinfo->cinfo, COL_PROTOCOL, "FOO");
210 /* Clear out stuff in the info column */
211 if(check_col(pinfo->cinfo,COL_INFO)){
212 col_clear(pinfo->cinfo,COL_INFO);
215 </programlisting></example>
217 This function is called to dissect the packets presented to it.
218 The packet data is held in a special buffer referenced here as tvb.
219 We shall become fairly familiar with this as we get deeper into the details
221 The packet info structure contains general data about the protocol, and we
222 can update information here.
223 The tree parameter is where the detail dissection takes place.
226 For now we'll do the minimum we can get away with.
227 The first two lines check to see if the Protocol column is being displayed in
228 the UI. If it is, we set the text of this to our protocol, so everyone
229 can see its been recognised.
230 The only other thing we do is to clear out any data in the INFO column
231 if its being displayed.
234 At this point we should have a basic dissector ready to compile and install.
235 It doesn't do much at present, than identify the protocol and label it.
236 Compile the dissector to a dll or shared library, and copy it into the plugin
237 directory of the installation. To finish this off a Makefile of some sort will be
238 required. A Makefile.nmake for Windows platforms and a Makefile.am for unix/linux
242 <example><title>Makefile.nmake for Windows.</title>
245 include ..\..\config.nmake
247 ############### no need to modify below this line #########
249 CFLAGS=/DHAVE_CONFIG_H /I../.. /I../../wiretap $(GLIB_CFLAGS) \
250 /I$(PCAP_DIR)\include -D_U_="" $(LOCAL_CFLAGS)
252 LDFLAGS = /NOLOGO /INCREMENTAL:no /MACHINE:I386 $(LOCAL_LDFLAGS)
254 !IFDEF ENABLE_LIBWIRESHARK
255 LINK_PLUGIN_WITH=..\..\epan\libwireshark.lib
256 CFLAGS=/DHAVE_WIN32_LIBWIRESHARK_LIB /D_NEED_VAR_IMPORT_ $(CFLAGS)
260 foo.dll foo.exp foo.lib : $(OBJECTS) $(LINK_PLUGIN_WITH)
261 link -dll /out:foo.dll $(LDFLAGS) $(OBJECTS) $(LINK_PLUGIN_WITH) \
267 rm -f $(OBJECTS) foo.dll foo.exp foo.lib *.pdb
271 maintainer-clean: distclean]]>
272 </programlisting></example>
273 <example><title>Makefile.am for unix/linux.</title>
276 INCLUDES = -I$(top_srcdir)
278 plugindir = @plugindir@
280 plugin_LTLIBRARIES = foo.la
281 foo_la_SOURCES = foo.c moduleinfo.h
282 foo_la_LDFLAGS = -module -avoid-version
283 foo_la_LIBADD = @PLUGIN_LIBS@
285 # Libs must be cleared, or else libtool won't create a shared module.
286 # If your module needs to be linked against any particular libraries,
297 </programlisting></example>
300 <section id="ChDissectDetails">
301 <title>Dissecting the details of the protocol</title>
303 Now we have our basic dissector up and running, lets do something with it.
304 The simplest thing to do to start with is to just label the payload.
305 This will allow us to set up some of the parts we will need.
308 The first thing we will do is to build a subtree to decode our results into.
309 This helps to keep things looking nice in the detailed display.
310 Now the dissector is called in two different cases. In one case
311 it is called to get a summary of the packet, in the other case it is
312 called to look into details of the packet. These two cases can be
313 distinguished by the tree pointer. If the tree pointer is NULL, then
314 we are being asked for a summary. If it is non null, we can pick apart
315 the protocol for display. So with that in mind, lets enhance our dissector.
317 <example><title>Plugin Packet Dissection.</title>
321 dissect_foo(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
324 if (check_col(pinfo->cinfo, COL_PROTOCOL))
325 col_set_str(pinfo->cinfo, COL_PROTOCOL, "FOO");
326 /* Clear out stuff in the info column */
327 if(check_col(pinfo->cinfo,COL_INFO)){
328 col_clear(pinfo->cinfo,COL_INFO);
331 if (tree) { /* we are being asked for details */
332 proto_item *ti = NULL;
333 ti = proto_tree_add_item(tree, proto_foo, tvb, 0, -1, FALSE);
336 </programlisting></example>
338 What we're doing here is adding a subtree to the dissection.
339 This subtree will hold all the details of this protocol and so not clutter
340 up the display when not required.
343 We are also marking the area of data that is being consumed by this
344 protocol. In our cases its all that has been passed to us, as we're assuming
345 this protocol does not encapsulate another.
346 Therefore, we add the new tree node with proto_tree_add_item, adding
347 it to the passed in tree, label it with the protocol, use the passed in
348 tvb buffer as the data, and consume from 0 to the end (-1) of this data.
349 The FALSE we'll ignore for now.
352 After this change, there should be a label in the detailed display for the protocol,
353 and selecting this will highlight the remaining contents of the packet.
356 Now lets go to the next step and add some protocol dissection.
357 For this step we'll need to construct a couple of tables that help with dissection.
358 This needs some changes to proto_register_foo. First a couple of statically
361 <example><title>Plugin Registering data structures.</title>
364 static hf_register_info hf[] = {
366 { "FOO PDU Type", "foo.type",
367 FT_UINT8, BASE_DEC, NULL, 0x0,
374 /* Setup protocol subtree array */
375 static gint *ett[] = {
379 </programlisting></example>
381 Then, after the registration code, we register these arrays.
383 <example><title>Plugin Registering data structures.</title>
387 proto_register_field_array(proto_foo, hf, array_length(hf));
388 proto_register_subtree_array(ett, array_length(ett));
390 </programlisting></example>
392 The variables hf_foo_pdu_type and ett_foo also need to be declared
393 somewhere near the top of the file.
395 <example><title>Plugin data structure globals.</title>
398 static int hf_foo_pdu_type = -1;
400 static gint ett_foo = -1;
402 </programlisting></example>
404 Now we can enhance the protocol display with some detail.
406 <example><title>Plugin starting to dissect the packets.</title>
409 if (tree) { /* we are being asked for details */
410 proto_item *ti = NULL;
411 proto_tree *foo_tree = NULL;
413 ti = proto_tree_add_item(tree, proto_foo, tvb, 0, -1, FALSE);
414 foo_tree = proto_item_add_subtree(ti, ett_foo);
415 proto_tree_add_item(foo_tree, hf_foo_pdu_type, tvb, 0, 1, FALSE);
418 </programlisting></example>
420 Now the dissection is starting to look more interesting. We have picked apart
421 our first bit of the protocol. One byte of data at the start of the packet
422 that defines the packet type for foo protocol.
425 The proto_item_add_subtree call has added a child node to the protocol tree
426 which is where we will do our detail dissection. The expansion of this
427 node is controlled by the ett_foo variable. This remembers if the node should
428 be expanded or not as you move between packets.
429 All subsequent dissection will be added to this tree, as you can see from the next call.
430 A call to proto_tree_add_item in the foo_tree, this time using the
431 hf_foo_pdu_type to control the formatting of the item. The pdu type
432 is one byte of data, starting at 0. We assume it is in network order,
433 so that is why we use FALSE. Although for 1 byte there is no order issues
434 its best to keep right.
437 If we look in detail at the hf_foo_pdu_type declaration in the static array
438 we can see the details of the definition.
442 hf_foo_pdu_type - the index for this node.
445 FOO PDU Type - the label for this item.
448 foo.type - this is the filter string. It enables us to type constructs such
449 as foo.type=1 into the filter box.
452 FT_UNIT8 - this specifies this item is an 8bit unsigned integer.
453 This tallies with our call above where we tell it to only look at one byte.
456 BASE_DEC - for an integer type, this tells it to be printed as a decimal
457 number. It could be BASE_HEX or BASE_OCT if that made more sense.
461 We'll ignore the rest of the structure for now.
464 If you install this plugin and try it out, you'll see something that begins to look
468 Now lets finish off dissecting the simple protocol. We need to add a few
469 more variables to the hf array, and a couple more procedure calls.
471 <example><title>Plugin wrapping up the packet dissection.</title>
474 static int hf_foo_flags = -1;
475 static int hf_foo_sequenceno = -1;
476 static int hf_foo_initialip = -1;
479 { "FOO PDU Flags", "foo.flags",
480 FT_UINT8, BASE_HEX, NULL, 0x0,
483 { &hf_foo_sequenceno,
484 { "FOO PDU Sequence Number", "foo.seqn",
485 FT_UINT16, BASE_DEC, NULL, 0x0,
489 { "FOO PDU Initial IP", "foo.initialip",
490 FT_IPv4, BASE_NONE, NULL, 0x0,
496 ti = proto_tree_add_item(tree, proto_foo, tvb, 0, -1, FALSE);
497 foo_tree = proto_item_add_subtree(ti, ett_foo);
498 proto_tree_add_item(foo_tree, hf_foo_pdu_type, tvb, offset, 1, FALSE); offset += 1;
499 proto_tree_add_item(foo_tree, hf_foo_flags, tvb, offset, 1, FALSE); offset += 1;
500 proto_tree_add_item(foo_tree, hf_foo_sequenceno, tvb, offset, 2, FALSE); offset += 2;
501 proto_tree_add_item(foo_tree, hf_foo_initialip, tvb, offset, 4, FALSE); offset += 4;
504 </programlisting></example>
506 This dissects all the bits of this simple hypothetical protocol. We've introduced a new
507 variable offset into the mix to help keep track of where we are in the packet dissection.
508 With these extra bits in place, the whole protocol is now dissected.
511 <section><title>Improving the dissection information</title>
513 We can certainly improve the display of the proto with a bit of extra data.
514 The first step is to add some text labels. Lets start by labelling the packet types.
515 There is some useful support for this sort of thing by adding a couple of extra things.
516 First we add a simple table of type to name.
518 <example><title>Naming the packet types.</title>
521 static const value_string packettypenames[] = {
528 </programlisting></example>
530 This is a handy data structure that can be used to look up value to names.
531 There are routines to directly access this lookup table, but we don't need to
532 do that, as the support code already has that added in. We just have to give
533 these details to the appropriate part of data, using the VALS macro.
535 <example><title>Adding Names to the protocol.</title>
539 { "FOO PDU Type", "foo.type",
541 VALS(packettypenames), 0x0,
545 </programlisting></example>
547 This helps in deciphering the packets, and we can do a similar thing for the
548 flags structure. For this we need to add some more data to the table though.
550 <example><title>Adding Flags to the protocol.</title>
553 #define FOO_START_FLAG 0x01
554 #define FOO_END_FLAG 0x02
555 #define FOO_PRIORITY_FLAG 0x04
557 static int hf_foo_startflag = -1;
558 static int hf_foo_endflag = -1;
559 static int hf_foo_priorityflag = -1;
562 { "FOO PDU Start Flags", "foo.flags.start",
564 NULL, FOO_START_FLAG,
568 { "FOO PDU End Flags", "foo.flags.end",
573 { &hf_foo_priorityflag,
574 { "FOO PDU Priority Flags", "foo.flags.priority",
576 NULL, FOO_PRIORITY_FLAG,
580 proto_tree_add_item(foo_tree, hf_foo_flags, tvb, offset, 1, FALSE);
581 proto_tree_add_item(foo_tree, hf_foo_startflag, tvb, offset, 1, FALSE);
582 proto_tree_add_item(foo_tree, hf_foo_endflag, tvb, offset, 1, FALSE);
583 proto_tree_add_item(foo_tree, hf_foo_priorityflag, tvb, offset, 1, FALSE); offset += 1;
585 </programlisting></example>
587 Some things to note here. For the flags, as each bit is a different flag, we use
588 the type FT_BOOLEAN, as the flag is either on or off. Second, we include the flag
589 mask in the 7th field of the data, which allows the system to mask the relevant bit.
590 We've also changed the 5th field to 8, to indicate that we are looking at an 8 bit
591 quantity when the flags are extracted. Then finally we add the extra constructs
592 to the dissection routine. Note we keep the same offset for each of the flags.
595 This is starting to look fairly full featured now, but there are a couple of other
596 things we can do to make things look even more pretty. At the moment our dissection
597 shows the packets as "Foo Protocol" which whilst correct is a little uninformative.
598 We can enhance this by adding a little more detail.
599 First, lets get hold of the actual value of the protocol type. We can use the handy
600 function tvb_get_guint8 to do this.
601 With this value in hand, there are a couple of things we can do.
602 First we can set the INFO column of the non-detailed view to show what sort of
603 PDU it is - which is extremely helpful when looking at protocol traces.
604 Second, we can also display this information in the dissection window.
606 <example><title>Enhancing the display.</title>
610 dissect_foo(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
612 guint8 packet_type = tvb_get_guint8(tvb, 0);
614 if (check_col(pinfo->cinfo, COL_PROTOCOL))
615 col_set_str(pinfo->cinfo, COL_PROTOCOL, "FOO");
616 /* Clear out stuff in the info column */
617 if(check_col(pinfo->cinfo,COL_INFO)){
618 col_clear(pinfo->cinfo,COL_INFO);
620 if (check_col(pinfo->cinfo, COL_INFO)) {
621 col_add_fstr(pinfo->cinfo, COL_INFO, "Type %s",
622 val_to_str(packet_type, packettypenames, "Unknown (0x%02x)"));
625 if (tree) { /* we are being asked for details */
626 proto_item *ti = NULL;
627 proto_tree *foo_tree = NULL;
630 ti = proto_tree_add_item(tree, proto_foo, tvb, 0, -1, FALSE);
631 proto_item_append_text(ti, ", Type %s",
632 val_to_str(packet_type, packettypenames, "Unknown (0x%02x)"));
633 foo_tree = proto_item_add_subtree(ti, ett_foo);
634 proto_tree_add_item(foo_tree, hf_foo_pdu_type, tvb, offset, 1, FALSE); offset += 1;
637 </programlisting></example>
639 So here, after grabbing the value of the first 8 bits, we use it with one of the
640 built in utility routines val_to_str, to lookup the value. If the value isn't
641 found we provide a fallback which just prints the value in hex.
642 We use this twice, once in the INFO field of the columns - if its displayed, and
643 similarly we append this data to the base of our dissecting tree.
649 <section id="ChDissectTransformed">
650 <title>How to handle transformed data</title>
652 Some protocols do clever things with data. They might possibly
653 encrypt the data, or compress data, or part of it. If you know
654 how these steps are taken it is possible to reverse them within the
658 As encryption can be tricky, lets consider the case of compression.
659 These techniques can also work for other transformations of data,
660 where some step is required before the data can be examined.
663 What basically needs to happen here, is to identify the data that
664 needs conversion, take that data and transform it into a new stream,
665 and then call a dissector on it.
666 Often this needs to be done "on-the-fly" based on clues in the packet.
667 Sometimes this needs to be used in conjunction with other techniques,
668 such as packet reassembly. The following shows a technique to
671 <example><title>Decompressing data packets for dissection.</title>
674 guint8 flags = tvb_get_guint8(tvb, offset); offset ++;
675 if (flags & FLAG_COMPRESSED) { /* the remainder of the packet is compressed */
676 guint16 orig_size = tvb_get_ntohs(tvb, offset); offset += 2;
677 guchar *decompressed_buffer; /* Buffers for decompression */
678 decompressed_buffer = (guchar*) g_malloc (orig_size);
679 decompress_packet (tvb_get_ptr(tvb, offset, -1), tvb_length_remaining(tvb, offset),
680 decompressed_buffer, orig_size);
681 /* Now re-setup the tvb buffer to have the new data */
682 next_tvb = tvb_new_real_data(decompressed_buffer, orig_size, orig_size);
683 tvb_set_child_real_data_tvbuff(tvb, next_tvb);
684 add_new_data_source(pinfo, next_tvb, "Decompressed Data");
685 tvb_set_free_cb(next_tvb, g_free);
687 next_tvb = tvb_new_subset(tvb, offset, -1, -1);
690 /* process next_tvb from here on */
692 </programlisting></example>
694 The first steps here are to recognise the compression. In this case
695 a flag byte alerts us to the fact the remainder of the packet is compressed.
696 Next we retrieve the original size of the packet, which in this case
697 is conveniently within the protocol. If its not, it may be part of the
698 compression routine to work it out for you, in which case the logic would
702 So armed with the size, a buffer is allocated to receive the uncompressed
703 data using g_malloc, and the packet is decompressed into it.
704 The tvb_get_ptr function is useful to get a pointer to the raw data of
705 the packet from the offset onwards. In this case the
706 decompression routine also needs to know the length, which is
707 given by the tvb_length_remaining function.
710 Next we build a new tvb buffer from this data, using the tvb_new_real_data
711 call. This data is a child of our original data, so we acknowledge that
712 in the next call to tvb_set_child_real_data_tvbuff.
713 Finally we add this data as a new data source, so that
714 the detailed display can show the decompressed bytes as well as the original.
715 One procedural step is to add a handler to free the data when its no longer needed.
716 In this case as g_malloc was used to allocate the memory, g_free is the appropriate
720 After this has been set up the remainder of the dissector can dissect the
721 buffer next_tvb, as its a new buffer the offset needs to be 0 as we start
722 again from the beginning of this buffer. To make the rest of the dissector
723 work regardless of whether compression was involved or not, in the case that
724 compression was not signaled, we use the tvb_new_subset to deliver us
725 a new buffer based on the old one but starting at the current offset, and
726 extending to the end. This makes dissecting the packet from this point on
727 exactly the same regardless of compression.
730 <section id="ChDissectReassemble">
731 <title>How to reassemble split packets</title>
733 Some protocols have times when they have to split a large packet across
734 multiple other packets. In this case the dissection can't be carried out correctly
735 until you have all the data. The first packet doesn't have enough data,
736 and the subsequent packets don't have the expect format.
737 To dissect these packets you need to wait until all the parts have
738 arrived and then start the dissection.
740 <section id="ChDissectReassembleUdp">
741 <title>How to reassemble split UDP packets</title>
743 As an example, lets examine a protocol that is layered on
744 top of UDP that splits up its own data stream.
745 If a packet is bigger than some given size, it will be split into
746 chunks, and somehow signaled within its protocol.
749 To deal with such streams, we need several things to trigger
750 from. We need to know that this packet is part of a multi-packet
751 sequence. We need to know how many packets are in the sequence.
752 We also need to know when we have all the packets.
755 For this example we'll assume there is a simple in-protocol
756 signaling mechanism to give details. A flag byte that signals
757 the presence of a multi-packet sequence and also the last packet,
758 followed by an ID of the sequence and a packet sequence number.
762 msg_pkt ::= SEQUENCE {
766 last_fragment BOOLEAN,
769 msg_id INTEGER(0..65535),
770 frag_id INTEGER(0..65535),
775 <example><title>Reassembling fragments - Part 1</title>
778 #include <epan/reassemble.h>
780 save_fragmented = pinfo->fragmented;
781 flags = tvb_get_guint8(tvb, offset); offset++;
782 if (flags & FL_FRAGMENT) { /* fragmented */
783 tvbuff_t* new_tvb = NULL;
784 fragment_data *frag_msg = NULL;
785 guint16 msg_seqid = tvb_get_ntohs(tvb, offset); offset += 2;
786 guint16 msg_num = tvb_get_ntohs(tvb, offset); offset += 2;
788 pinfo->fragmented = TRUE;
789 frag_msg = fragment_add_seq_check(tvb, offset, pinfo,
790 msg_seqid, /* ID for fragments belonging together */
791 msg_fragment_table, /* list of message fragments */
792 msg_reassembled_table, /* list of reassembled messages */
793 msg_num, /* fragment sequence number */
794 tvb_length_remaining(tvb, offset), /* fragment length - to the end */
795 flags & FL_FRAG_LAST); /* More fragments? */
797 </programlisting></example>
799 We start by saving the fragmented state of this packet, so we can restore it later.
800 Next comes some protocol specific stuff, to dig the fragment data
801 out of the stream if it's present. Having decided it is present, we
802 let the function fragment_add_seq_check do its work.
803 We need to provide this with a certain amount of data.
807 The tvb buffer we are dissecting.
810 The offset where the partial packet starts.
813 The provided packet info.
816 The sequence number of the fragment stream. There may be several
817 streams of fragments in flight, and this is used to key the
818 relevant one to be used for reassembly.
821 The msg_fragment_table and the msg_reassembled_table are variables
822 we need to declare. We'll consider these in detail later.
825 msg_num is the packet number within the sequence.
828 The length here is specified as the rest of the tvb as we want the rest of the packet data.
831 Finally a parameter that signals if this is the last fragment or not.
832 This might be a flag as in this case, or there may be a counter in the
836 <example><title>Reassembling fragments part 2</title>
839 new_tvb = process_reassembled_data(tvb, offset, pinfo,
840 "Reassembled Message", frag_msg, &msg_frag_items,
843 if (frag_msg) { /* Reassembled */
844 if (check_col(pinfo->cinfo, COL_INFO))
845 col_append_str(pinfo->cinfo, COL_INFO,
846 " (Message Reassembled)");
847 } else { /* Not last packet of reassembled Short Message */
848 if (check_col(pinfo->cinfo, COL_INFO))
849 col_append_fstr(pinfo->cinfo, COL_INFO,
850 " (Message fragment %u)", msg_num);
853 if (new_tvb) { /* take it all */
855 } else { /* make a new subset */
856 next_tvb = tvb_new_subset(tvb, offset, -1, -1);
859 else { /* Not fragmented */
860 next_tvb = tvb_new_subset(tvb, offset, -1, -1);
864 pinfo->fragmented = save_fragmented;
866 </programlisting></example>
868 Having passed the fragment data to the reassembly handler, we can
869 now check if we have the whole message. If there is enough information,
870 this routine will return the newly reassembled data buffer.
873 After that, we add a couple of informative messages to the display
874 to show that this is part of a sequence. Then a bit of manipulation
875 of the buffers and the dissection can proceed.
876 Normally you will probably not bother dissecting further unless the
877 fragments have been reassembled as there won't be much to find. Sometimes
878 the first packet in the sequence can be partially decoded though if you wish.
881 Now the mysterious data we passed into the fragment_add_seq_check.
883 <example><title>Reassembling fragments - Initialisation</title>
886 static GHashTable *msg_fragment_table = NULL;
887 static GHashTable *msg_reassembled_table = NULL;
891 msg_init_protocol(void)
893 fragment_table_init (&msg_fragment_table);
894 reassembled_table_init(&msg_reassembled_table);
897 </programlisting></example>
899 First a couple of hash tables are declared, and these are initialised
900 in the protocol initialisation routine.
901 Following that, a fragment_items structure is allocated and filled
902 in with a series of ett items, hf data items, and a string tag.
903 The ett and hf values should be included in the relevant tables like
904 all the other variables your protocol may use. The hf variables
905 need to be placed in the structure something like the following.
906 Of course the names may need to be adjusted.
908 <example><title>Reassembling fragments - Data</title>
912 static int hf_msg_fragments = -1;
913 static int hf_msg_fragment = -1;
914 static int hf_msg_fragment_overlap = -1;
915 static int hf_msg_fragment_overlap_conflicts = -1;
916 static int hf_msg_fragment_multiple_tails = -1;
917 static int hf_msg_fragment_too_long_fragment = -1;
918 static int hf_msg_fragment_error = -1;
919 static int hf_msg_reassembled_in = -1;
921 static gint ett_msg_fragment = -1;
922 static gint ett_msg_fragments = -1;
924 static const fragment_items msg_frag_items = {
925 /* Fragment subtrees */
928 /* Fragment fields */
931 &hf_msg_fragment_overlap,
932 &hf_msg_fragment_overlap_conflicts,
933 &hf_msg_fragment_multiple_tails,
934 &hf_msg_fragment_too_long_fragment,
935 &hf_msg_fragment_error,
936 /* Reassembled in field */
937 &hf_msg_reassembled_in,
942 static hf_register_info hf[] =
946 {"Message fragments", "msg.fragments",
947 FT_NONE, BASE_NONE, NULL, 0x00, NULL, HFILL } },
949 {"Message fragment", "msg.fragment",
950 FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL } },
951 {&hf_msg_fragment_overlap,
952 {"Message fragment overlap", "msg.fragment.overlap",
953 FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
954 {&hf_msg_fragment_overlap_conflicts,
955 {"Message fragment overlapping with conflicting data",
956 "msg.fragment.overlap.conflicts",
957 FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
958 {&hf_msg_fragment_multiple_tails,
959 {"Message has multiple tail fragments",
960 "msg.fragment.multiple_tails",
961 FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
962 {&hf_msg_fragment_too_long_fragment,
963 {"Message fragment too long", "msg.fragment.too_long_fragment",
964 FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL } },
965 {&hf_msg_fragment_error,
966 {"Message defragmentation error", "msg.fragment.error",
967 FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL } },
968 {&hf_msg_reassembled_in,
969 {"Reassembled in", "msg.reassembled.in",
970 FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL } },
979 </programlisting></example>
981 These hf variables are used internally within the reassembly routines
982 to make useful links, and to add data to the dissection. It produces
983 links from one packet to another - such as a partial packet having
984 a link to the fully reassembled packet. Likewise there are back pointers
985 to the individual packets from the reassembled one.
986 The other variables are used for flagging up errors.
989 <section id="TcpDissectPdus">
990 <title>How to reassemble split TCP Packets</title>
992 A dissector gets a tvbuff_t pointer which holds the payload
993 of a TCP packet. This payload contains the header and data
994 of your application layer protocol.
997 When dissecting an application layer protocol you cannot assume
998 that each TCP packet contains exactly one application layer message.
999 One application layer message can be split into several TCP packets.
1002 You also cannot assume the a TCP packet contains only one application layer message
1003 and that the message header is at the start of your TCP payload.
1004 More than one messages can be transmitted in one TCP packet,
1005 so that a message can start at an abitrary position.
1009 This sounds complicated, but there is a simple solution.
1010 <methodname>tcp_dissect_pdus()</methodname> does all this tcp packet reassembling for you.
1011 This function is implemented in <filename>epan/dissectors/packet-tcp.h</filename>.
1014 <title>Reassembling TCP fragments</title>
1017 #ifdef HAVE_CONFIG_H
1018 # include "config.h"
1021 #include <gmodule.h>
1022 #include <epan/packet.h>
1023 #include <epan/emem.h>
1024 #include <epan/dissectors/packet-tcp.h>
1025 #include <epan/prefs.h>
1029 #define FRAME_HEADER_LEN 8
1031 /* The main dissecting routine */
1032 static void dissect_foo(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1034 tcp_dissect_pdus(tvb, pinfo, tree, TRUE, FRAME_HEADER_LEN,
1035 get_foo_message_len, dissect_foo_message);
1038 /* This method dissects fully reassembled messages */
1039 static void dissect_foo_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1041 /* TODO: implement your dissecting code */
1044 /* determine PDU length of protocol foo */
1045 static guint get_foo_message_len(packet_info *pinfo, tvbuff_t *tvb, int offset)
1047 /* TODO: change this to your needs */
1048 return (guint)tvb_get_ntohl(tvb, offset+4); /* e.g. length is at offset 4 */
1056 As you can see this is really simple. Just call <function>tcp_dissect_pdus()</function> in
1057 your main dissection routine and move you message parsing code into another function.
1058 This function gets called whenever a message has been reassembled.
1061 The parameters <parameter>tvb</parameter>, <parameter>pinfo</parameter> and <parameter>tree</parameter>
1062 are just handed over to <function>tcp_dissect_pdus()</function>.
1063 The 4th parameter is a flag to indicate if the data should be reassebled or not. This could be set
1064 according to a dissector preference as well.
1065 Parameter 5 indicates how much data has at least to be available to be able to determine the length
1067 Parameter 6 is a function pointer to a method that returns this length. It gets called when at least
1068 the number of bytes given in the previous parameter is available.
1069 Parameter 7 is a function pointer to your real message dissector.
1073 <section id="ChDissectTap">
1074 <title>How to tap protocols</title>
1076 Adding a Tap interface to a protocol allows it to do some useful things.
1077 In particular you can produce protocol statistics from the tap interface.
1080 A tap is basically a way of allowing other items to see whats happening as
1081 a protocol is dissected. A tap is registered with the main program, and
1082 then called on each dissection. Some arbritary protocol specific data
1083 is provided with the routine that can be used.
1086 To create a tap, you first need to register a tap.
1087 A tap is registered with an integer handle, and registered
1088 with the routine register_tap. This takes a string name
1089 with which to find it again.
1091 <example><title>Initialising a tap</title>
1094 #include <epan/tap.h>
1096 static int foo_tap = -1;
1104 foo_tap = register_tap("foo");
1106 </programlisting></example>
1108 Whilst you can program a tap without protocol specific data, it
1109 is generally not very useful. Therefore its a good idea
1110 to declare a structure that can be passed through the tap.
1111 This needs to be a static structure as it will be used after the
1112 dissection routine has returned. Its generally best to pick out some
1113 generic parts of the protocol you are dissecting into the tap data.
1114 A packet type, a priority, a status code maybe.
1115 The structure really needs to be included in a header file so
1116 that it can be included by other components that want to listen in
1120 Once you have these defined, its simply a case of populating the
1121 protocol specific structure and then calling tap_queue_packet probably
1122 as the last part of the dissector.
1124 <example><title>Calling a protocol tap</title>
1127 static struct FooTap pinfo;
1129 pinfo.packet_type = tvb_get_guint8(tvb, 0);
1130 pinfo.priority = tvb_get_ntohs(tvb, 8);
1132 tap_queue_packet(foo_tap, pinfo, &pinfo);
1134 </programlisting></example>
1136 This now enables those interested parties to listen in on the details
1137 of this protocol conversation.
1140 <section id="ChDissectStats">
1141 <title>How to produce protocol stats</title>
1143 Given that you have a tap interface for the protocol, you can use this
1144 to produce some interesting statistics (well presumably interesting!) from
1148 This can be done in a separate plugin, or in the same plugin that is
1149 doing the dissection. The latter scheme is better, as the tap and stats
1150 module typically rely on sharing protocol specific data, which might get out
1151 of step between two different plugins.
1154 Here is a mechanism to produce statistics from the above TAP interface.
1156 <example><title>Initialising a stats interface</title>
1159 /* register all http trees */
1160 static void register_foo_stat_trees(void) {
1161 stats_tree_register("foo","foo","Foo/Packet Types",
1162 foo_stats_tree_packet, foo_stats_tree_init, NULL );
1164 #ifndef ENABLE_STATIC
1165 //G_MODULE_EXPORT const gchar version[] = "0.0";
1167 G_MODULE_EXPORT void plugin_register_tap_listener(void)
1169 register_foo_stat_trees();
1174 </programlisting></example>
1176 Working from the bottom up, first the plugin interface entry point is defined,
1177 plugin_register_tap_listener. This simply calls the initialisation function
1178 register_foo_stat_trees.
1181 This in turn calls the stats_tree_register function, which takes
1182 three strings, and three functions.
1186 This is the tap name that is registered.
1189 An abbreviation of the stats name.
1192 The name of the stats module. A '/' character can be used to make sub menus.
1195 The function that will called to generate the stats.
1198 A function that can be called to initialise the stats data.
1201 A function that will be called to clean up the stats data.
1205 In this case we only need the first two functions, as there is nothing specific to clean up.
1207 <example><title>Initialising a stats session</title>
1210 static const guint8* st_str_packets = "Total Packets";
1211 static const guint8* st_str_packet_types = "FOO Packet Types";
1212 static int st_node_packets = -1;
1213 static int st_node_packet_types = -1;
1215 static void foo_stats_tree_init(stats_tree* st) {
1216 st_node_packets = stats_tree_create_node(st, st_str_packets, 0, TRUE);
1217 st_node_packet_types = stats_tree_create_pivot(st, st_str_packet_types, st_node_packets);
1220 </programlisting></example>
1222 In this case we create a new tree node, to handle the total packets,
1223 and as a child of that we create a pivot table to handle the stats about
1224 different packet types.
1226 <example><title>Generating the stats</title>
1229 static int foo_stats_tree_packet(stats_tree* st, packet_info* pinfo , epan_dissect_t* edt , const void* p) {
1230 struct FooTap *pi = (struct FooTap *)p;
1231 tick_stat_node(st, st_str_packets, 0, FALSE);
1232 stats_tree_tick_pivot(st, st_node_packet_types,
1233 val_to_str(pi->packet_type, msgtypevalues, "Unknown packet type (%d)"));
1237 </programlisting></example>
1239 In this case the processing of the stats is quite simple.
1240 First we call the tick_stat_node for the st_str_packets packet node, to count
1242 Then a call to stats_tree_tick_pivot on the st_node_packet_types subtree
1243 allows us to record statistics by packet type.
1247 <section id="ChDissectConversation">
1248 <title>How to use conversations</title>
1250 Some info about how to use conversations in a dissector can be
1251 found in the file doc/README.developer.
1256 <!-- End of WSDG Chapter Dissection -->