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