extcap: Add list of extcaps to about dialog
[metze/wireshark/wip.git] / doc / README.developer
1 Tabsize: 4
2
3 This file is a HOWTO for Wireshark developers. It describes general development
4 and coding practices for contributing to Wireshark no matter which part of
5 Wireshark you want to work on.
6
7 To learn how to write a dissector, read this first, then read the file
8 README.dissector.
9
10 This file is compiled to give in depth information on Wireshark.
11 It is by no means all inclusive and complete. Please feel free to send
12 remarks and patches to the developer mailing list.
13
14 0. Prerequisites.
15
16 Before starting to develop a new dissector, a "running" Wireshark build
17 environment is required - there's no such thing as a standalone "dissector
18 build toolkit".
19
20 How to setup such an environment is platform dependent; detailed information
21 about these steps can be found in the "Developer's Guide" (available from:
22 https://www.wireshark.org) and in the INSTALL and README files of the sources
23 root dir.
24
25 0.1. General README files.
26
27 You'll find additional information in the following README files:
28
29 - README.capture        - the capture engine internals
30 - README.design         - Wireshark software design - incomplete
31 - README.developer      - this file
32 - README.dissector      - How to dissect a packet
33 - README.display_filter - Display Filter Engine
34 - README.idl2wrs        - CORBA IDL converter
35 - README.packaging      - how to distribute a software package containing WS
36 - README.regression     - regression testing of WS and TS
37 - README.stats_tree     - a tree statistics counting specific packets
38 - README.tapping        - "tap" a dissector to get protocol specific events
39 - README.xml-output     - how to work with the PDML exported output
40 - wiretap/README.developer - how to add additional capture file types to
41   Wiretap
42
43 0.2. Dissector related README files.
44
45 You'll find additional dissector related information in the file
46 README.dissector as well as the following README files:
47
48 - README.heuristic      - what are heuristic dissectors and how to write them
49 - README.plugins        - how to "pluginize" a dissector
50 - README.request_response_tracking - how to track req./resp. times and such
51 - README.wmem           - how to obtain "memory leak free" memory
52
53 0.3 Contributors
54
55 James Coe <jammer[AT]cin.net>
56 Gilbert Ramirez <gram[AT]alumni.rice.edu>
57 Jeff Foster <jfoste[AT]woodward.com>
58 Olivier Abad <oabad[AT]cybercable.fr>
59 Laurent Deniel <laurent.deniel[AT]free.fr>
60 Gerald Combs <gerald[AT]wireshark.org>
61 Guy Harris <guy[AT]alum.mit.edu>
62 Ulf Lamping <ulf.lamping[AT]web.de>
63
64 1. Portability.
65
66 Wireshark runs on many platforms, and can be compiled with a number of
67 different compilers; here are some rules for writing code that will work
68 on multiple platforms.
69
70 Don't use C++-style comments (comments beginning with "//" and running
71 to the end of the line) in C code. Wireshark's dissectors are written in
72 C, and thus run through C rather than C++ compilers, and not all C
73 compilers support C++-style comments (GCC does, but IBM's C compiler for
74 AIX, for example, doesn't do so by default). C++-style comments can be
75 used in C++ code, of course.
76
77 In general, don't use C99 features since some C compilers used to compile
78 Wireshark, such as Microsoft's C compiler, don't support all C99
79 features.  The C99 features that can be used are:
80
81         variadic macros
82
83 Don't initialize variables in their declaration with non-constant
84 values. Not all compilers support this. E.g. don't use
85     guint32 i = somearray[2];
86 use
87     guint32 i;
88     i = somearray[2];
89 instead.
90
91 Don't use zero-length arrays; not all compilers support them.  If an
92 array would have no members, just leave it out.
93
94 Don't declare variables in the middle of executable code; not all C
95 compilers support that.  Variables should be declared outside a
96 function, or at the beginning of a function or compound statement.
97
98 Don't use anonymous unions; not all compilers support them.
99 Example:
100
101     typedef struct foo {
102       guint32 foo;
103       union {
104         guint32 foo_l;
105         guint16 foo_s;
106       } u;  /* have a name here */
107     } foo_t;
108
109 Don't use "uchar", "u_char", "ushort", "u_short", "uint", "u_int",
110 "ulong", "u_long" or "boolean"; they aren't defined on all platforms.
111 If you want an 8-bit unsigned quantity, use "guint8"; if you want an
112 8-bit character value with the 8th bit not interpreted as a sign bit,
113 use "guchar"; if you want a 16-bit unsigned quantity, use "guint16";
114 if you want a 32-bit unsigned quantity, use "guint32"; and if you want
115 an "int-sized" unsigned quantity, use "guint"; if you want a boolean,
116 use "gboolean".  Use "%d", "%u", "%x", and "%o" to print those types;
117 don't use "%ld", "%lu", "%lx", or "%lo", as longs are 64 bits long on
118 many platforms, but "guint32" is 32 bits long.
119
120 Don't use "long" to mean "signed 32-bit integer", and don't use
121 "unsigned long" to mean "unsigned 32-bit integer"; "long"s are 64 bits
122 long on many platforms.  Use "gint32" for signed 32-bit integers and use
123 "guint32" for unsigned 32-bit integers.
124
125 Don't use "long" to mean "signed 64-bit integer" and don't use "unsigned
126 long" to mean "unsigned 64-bit integer"; "long"s are 32 bits long on
127 many other platforms.  Don't use "long long" or "unsigned long long",
128 either, as not all platforms support them; use "gint64" or "guint64",
129 which will be defined as the appropriate types for 64-bit signed and
130 unsigned integers.
131
132 On LLP64 data model systems (notably 64-bit Windows), "int" and "long"
133 are 32 bits while "size_t" and "ptrdiff_t" are 64 bits. This means that
134 the following will generate a compiler warning:
135
136     int i;
137     i = strlen("hello, sailor");  /* Compiler warning */
138
139 Normally, you'd just make "i" a size_t. However, many GLib and Wireshark
140 functions won't accept a size_t on LLP64:
141
142     size_t i;
143     char greeting[] = "hello, sailor";
144     guint byte_after_greet;
145
146     i = strlen(greeting);
147     byte_after_greet = tvb_get_guint8(tvb, i); /* Compiler warning */
148
149 Try to use the appropriate data type when you can. When you can't, you
150 will have to cast to a compatible data type, e.g.
151
152     size_t i;
153     char greeting[] = "hello, sailor";
154     guint byte_after_greet;
155
156     i = strlen(greeting);
157     byte_after_greet = tvb_get_guint8(tvb, (gint) i); /* OK */
158
159 or
160
161     gint i;
162     char greeting[] = "hello, sailor";
163     guint byte_after_greet;
164
165     i = (gint) strlen(greeting);
166     byte_after_greet = tvb_get_guint8(tvb, i); /* OK */
167
168 See http://www.unix.org/version2/whatsnew/lp64_wp.html for more
169 information on the sizes of common types in different data models.
170
171 When printing or displaying the values of 64-bit integral data types,
172 don't use "%lld", "%llu", "%llx", or "%llo" - not all platforms
173 support "%ll" for printing 64-bit integral data types.  Instead, for
174 GLib routines, and routines that use them, such as all the routines in
175 Wireshark that take format arguments, use G_GINT64_MODIFIER, for example:
176
177     proto_tree_add_uint64_format_value(tree, hf_uint64, tvb, offset, len,
178                                        val, "%" G_GINT64_MODIFIER "u", val);
179
180 When specifying an integral constant that doesn't fit in 32 bits, don't
181 use "LL" at the end of the constant - not all compilers use "LL" for
182 that.  Instead, put the constant in a call to the "G_GINT64_CONSTANT()"
183 macro, e.g.
184
185     G_GINT64_CONSTANT(-11644473600), G_GUINT64_CONSTANT(11644473600)
186
187 rather than
188
189     -11644473600LL, 11644473600ULL
190
191 Don't assume that you can scan through a va_list initialized by va_start
192 more than once without closing it with va_end and re-initializing it with
193 va_start.  This applies even if you're not scanning through it yourself,
194 but are calling a routine that scans through it, such as vfprintf() or
195 one of the routines in Wireshark that takes a format and a va_list as an
196 argument.  You must do
197
198     va_start(ap, format);
199     call_routine1(xxx, format, ap);
200     va_end(ap);
201     va_start(ap, format);
202     call_routine2(xxx, format, ap);
203     va_end(ap);
204
205 rather
206     va_start(ap, format);
207     call_routine1(xxx, format, ap);
208     call_routine2(xxx, format, ap);
209     va_end(ap);
210
211 Don't use a label without a statement following it.  For example,
212 something such as
213
214     if (...) {
215
216         ...
217
218     done:
219     }
220
221 will not work with all compilers - you have to do
222
223     if (...) {
224
225         ...
226
227     done:
228         ;
229     }
230
231 with some statement, even if it's a null statement, after the label.
232
233 Don't use "bzero()", "bcopy()", or "bcmp()"; instead, use the ANSI C
234 routines
235
236     "memset()" (with zero as the second argument, so that it sets
237     all the bytes to zero);
238
239     "memcpy()" or "memmove()" (note that the first and second
240     arguments to "memcpy()" are in the reverse order to the
241     arguments to "bcopy()"; note also that "bcopy()" is typically
242     guaranteed to work on overlapping memory regions, while
243     "memcpy()" isn't, so if you may be copying from one region to a
244     region that overlaps it, use "memmove()", not "memcpy()" - but
245     "memcpy()" might be faster as a result of not guaranteeing
246     correct operation on overlapping memory regions);
247
248     and "memcmp()" (note that "memcmp()" returns 0, 1, or -1, doing
249     an ordered comparison, rather than just returning 0 for "equal"
250     and 1 for "not equal", as "bcmp()" does).
251
252 Not all platforms necessarily have "bzero()"/"bcopy()"/"bcmp()", and
253 those that do might not declare them in the header file on which they're
254 declared on your platform.
255
256 Don't use "index()" or "rindex()"; instead, use the ANSI C equivalents,
257 "strchr()" and "strrchr()".  Not all platforms necessarily have
258 "index()" or "rindex()", and those that do might not declare them in the
259 header file on which they're declared on your platform.
260
261 Don't use "tvb_get_ptr().  If you must use it, keep in mind that the pointer
262 returned by a call to "tvb_get_ptr()" is not guaranteed to be aligned on any
263 particular byte boundary; this means that you cannot safely cast it to any
264 data type other than a pointer to "char", unsigned char", "guint8", or other
265 one-byte data types.  Casting a pointer returned by tvb_get_ptr() into any
266 multi-byte data type or structure may cause crashes on some platforms (even
267 if it does not crash on x86-based PCs).  Even if such mis-aligned accesses
268 don't crash on your platform they will be slower than properly aligned
269 accesses would be.  Furthermore, the data in a packet is not necessarily in
270 the byte order of the machine on which Wireshark is running.  Use the tvbuff
271 routines to extract individual items from the packet, or, better yet, use
272 "proto_tree_add_item()" and let it extract the items for you.
273
274 Don't use structures that overlay packet data, or into which you copy
275 packet data; the C programming language does not guarantee any
276 particular alignment of fields within a structure, and even the
277 extensions that try to guarantee that are compiler-specific and not
278 necessarily supported by all compilers used to build Wireshark.  Using
279 bitfields in those structures is even worse; the order of bitfields
280 is not guaranteed.
281
282 Don't use "ntohs()", "ntohl()", "htons()", or "htonl()"; the header
283 files required to define or declare them differ between platforms, and
284 you might be able to get away with not including the appropriate header
285 file on your platform but that might not work on other platforms.
286 Instead, use "g_ntohs()", "g_ntohl()", "g_htons()", and "g_htonl()";
287 those are declared by <glib.h>, and you'll need to include that anyway,
288 as Wireshark header files that all dissectors must include use stuff from
289 <glib.h>.
290
291 Don't fetch a little-endian value using "tvb_get_ntohs() or
292 "tvb_get_ntohl()" and then using "g_ntohs()", "g_htons()", "g_ntohl()",
293 or "g_htonl()" on the resulting value - the g_ routines in question
294 convert between network byte order (big-endian) and *host* byte order,
295 not *little-endian* byte order; not all machines on which Wireshark runs
296 are little-endian, even though PCs are.  Fetch those values using
297 "tvb_get_letohs()" and "tvb_get_letohl()".
298
299 Don't put a comma after the last element of an enum - some compilers may
300 either warn about it (producing extra noise) or refuse to accept it.
301
302 Do not use "open()", "rename()", "mkdir()", "stat()", "unlink()", "remove()",
303 "fopen()", "freopen()" directly.  Instead use "ws_open()", "ws_rename()",
304 "ws_mkdir()", "ws_stat()", "ws_unlink()", "ws_remove()", "ws_fopen()",
305 "ws_freopen()": these wrapper functions change the path and file name from
306 UTF8 to UTF16 on Windows allowing the functions to work correctly when the
307 path or file name contain non-ASCII characters.
308
309 Also, use ws_read(), ws_write(), ws_lseek(), ws_dup(), ws_fstat(), and
310 ws_fdopen(), rather than read(), write(), lseek(), dup(), fstat(), and
311 fdopen() on descriptors returned by ws_open().
312
313 Those functions are declared in <wsutil/file_util.h>; include that
314 header in any code that uses any of those routines.
315
316 When opening a file with "ws_fopen()", "ws_freopen()", or "ws_fdopen()", if
317 the file contains ASCII text, use "r", "w", "a", and so on as the open mode
318 - but if it contains binary data, use "rb", "wb", and so on.  On
319 Windows, if a file is opened in a text mode, writing a byte with the
320 value of octal 12 (newline) to the file causes two bytes, one with the
321 value octal 15 (carriage return) and one with the value octal 12, to be
322 written to the file, and causes bytes with the value octal 15 to be
323 discarded when reading the file (to translate between C's UNIX-style
324 lines that end with newline and Windows' DEC-style lines that end with
325 carriage return/line feed).
326
327 In addition, that also means that when opening or creating a binary
328 file, you must use "ws_open()" (with O_CREAT and possibly O_TRUNC if the
329 file is to be created if it doesn't exist), and OR in the O_BINARY flag,
330 even on UN*X - O_BINARY is defined by <wsutil/file_util.h> as 0 on UN*X.
331
332 Do not include <unistd.h>, <fcntl.h>, or <io.h> to declare any of the
333 routines listed as replaced by routines in <wsutil/file_util.h>;
334 instead, just include <wsutil/file_util.h>.
335
336 If you need the declarations of other functions defined by <unistd.h>,
337 don't include it without protecting it with
338
339     #ifdef HAVE_UNISTD_H
340
341         ...
342
343     #endif
344
345 Don't use forward declarations of static arrays without a specified size
346 in a fashion such as this:
347
348     static const value_string foo_vals[];
349
350         ...
351
352     static const value_string foo_vals[] = {
353         { 0,        "Red" },
354         { 1,        "Green" },
355         { 2,        "Blue" },
356         { 0,        NULL }
357     };
358
359 as some compilers will reject the first of those statements.  Instead,
360 initialize the array at the point at which it's first declared, so that
361 the size is known.
362
363 Don't put a comma after the last tuple of an initializer of an array.
364
365 For #define names and enum member names, prefix the names with a tag so
366 as to avoid collisions with other names - this might be more of an issue
367 on Windows, as it appears to #define names such as DELETE and
368 OPTIONAL.
369
370 Don't use the "numbered argument" feature that many UNIX printf's
371 implement, e.g.:
372
373     g_snprintf(add_string, 30, " - (%1$d) (0x%1$04x)", value);
374
375 as not all UNIX printf's implement it, and Windows printf doesn't appear
376 to implement it.  Use something like
377
378     g_snprintf(add_string, 30, " - (%d) (0x%04x)", value, value);
379
380 instead.
381
382 Don't use
383
384     case N ... M:
385
386 as that's not supported by all compilers.
387
388 snprintf() -> g_snprintf()
389 snprintf() is not available on all platforms, so it's a good idea to use the
390 g_snprintf() function declared by <glib.h> instead.
391
392 tmpnam() -> mkstemp()
393 tmpnam is insecure and should not be used any more. Wireshark brings its
394 own mkstemp implementation for use on platforms that lack mkstemp.
395 Note: mkstemp does not accept NULL as a parameter.
396
397 Wireshark supports platforms with GLib 2.14[.x]/GTK+ 2.12[.x] or newer.
398 If a Glib/GTK+ mechanism is available only in Glib/GTK+ versions newer
399 than 2.14/2.12 then use "#if GLIB_CHECK_VERSION(...)" or "#if
400 GTK_CHECK_VERSION(...)" to conditionally compile code using that
401 mechanism.
402
403 When different code must be used on UN*X and Win32, use a #if or #ifdef
404 that tests _WIN32, not WIN32.  Try to write code portably whenever
405 possible, however; note that there are some routines in Wireshark with
406 platform-dependent implementations and platform-independent APIs, such
407 as the routines in epan/filesystem.c, allowing the code that calls it to
408 be written portably without #ifdefs.
409
410 Wireshark uses libgcrypt as general-purpose crypto library. To use it from
411 your dissector, protect libgcrypt calls with #ifdef HAVE_LIBGCRYPT. Don't
412 include gcrypt.h directly, include the wrapper file wsutil/wsgcrypt.h
413 instead.
414
415 2. String handling
416
417 Do not use functions such as strcat() or strcpy().
418 A lot of work has been done to remove the existing calls to these functions and
419 we do not want any new callers of these functions.
420
421 Instead use g_snprintf() since that function will if used correctly prevent
422 buffer overflows for large strings.
423
424 Be sure that all pointers passed to %s specifiers in format strings are non-
425 NULL. Some implementations will automatically replace NULL pointers with the
426 string "(NULL)", but most will not.
427
428 When using a buffer to create a string, do not use a buffer stored on the stack.
429 I.e. do not use a buffer declared as
430
431    char buffer[1024];
432
433 instead allocate a buffer dynamically using the string-specific or plain wmem
434 routines (see README.wmem) such as
435
436    wmem_strbuf_t *strbuf;
437    strbuf = wmem_strbuf_new(wmem_packet_scope(), "");
438    wmem_strbuf_append_printf(strbuf, ...
439
440 or
441
442    char *buffer=NULL;
443    ...
444    #define MAX_BUFFER 1024
445    buffer=wmem_alloc(wmem_packet_scope(), MAX_BUFFER);
446    buffer[0]='\0';
447    ...
448    g_snprintf(buffer, MAX_BUFFER, ...
449
450 This avoids the stack from being corrupted in case there is a bug in your code
451 that accidentally writes beyond the end of the buffer.
452
453
454 If you write a routine that will create and return a pointer to a filled in
455 string and if that buffer will not be further processed or appended to after
456 the routine returns (except being added to the proto tree),
457 do not preallocate the buffer to fill in and pass as a parameter instead
458 pass a pointer to a pointer to the function and return a pointer to a
459 wmem-allocated buffer that will be automatically freed. (see README.wmem)
460
461 I.e. do not write code such as
462   static void
463   foo_to_str(char *string, ... ){
464      <fill in string>
465   }
466   ...
467      char buffer[1024];
468      ...
469      foo_to_str(buffer, ...
470      proto_tree_add_string(... buffer ...
471
472 instead write the code as
473   static void
474   foo_to_str(char **buffer, ...
475     #define MAX_BUFFER x
476     *buffer=wmem_alloc(wmem_packet_scope(), MAX_BUFFER);
477     <fill in *buffer>
478   }
479   ...
480     char *buffer;
481     ...
482     foo_to_str(&buffer, ...
483     proto_tree_add_string(... *buffer ...
484
485 Use wmem_ allocated buffers. They are very fast and nice. These buffers are all
486 automatically free()d when the dissection of the current packet ends so you
487 don't have to worry about free()ing them explicitly in order to not leak memory.
488 Please read README.wmem.
489
490 Don't use non-ASCII characters in source files; not all compiler
491 environments will be using the same encoding for non-ASCII characters,
492 and at least one compiler (Microsoft's Visual C) will, in environments
493 with double-byte character encodings, such as many Asian environments,
494 fail if it sees a byte sequence in a source file that doesn't correspond
495 to a valid character.  This causes source files using either an ISO
496 8859/n single-byte character encoding or UTF-8 to fail to compile.  Even
497 if the compiler doesn't fail, there is no guarantee that the compiler,
498 or a developer's text editor, will interpret the characters the way you
499 intend them to be interpreted.
500
501 3. Robustness.
502
503 Wireshark is not guaranteed to read only network traces that contain correctly-
504 formed packets. Wireshark is commonly used to track down networking
505 problems, and the problems might be due to a buggy protocol implementation
506 sending out bad packets.
507
508 Therefore, code does not only have to be able to handle
509 correctly-formed packets without, for example, crashing or looping
510 infinitely, they also have to be able to handle *incorrectly*-formed
511 packets without crashing or looping infinitely.
512
513 Here are some suggestions for making code more robust in the face
514 of incorrectly-formed packets:
515
516 Do *NOT* use "g_assert()" or "g_assert_not_reached()" in dissectors.
517 *NO* value in a packet's data should be considered "wrong" in the sense
518 that it's a problem with the dissector if found; if it cannot do
519 anything else with a particular value from a packet's data, the
520 dissector should put into the protocol tree an indication that the
521 value is invalid, and should return.  The "expert" mechanism should be
522 used for that purpose.
523
524 If there is a case where you are checking not for an invalid data item
525 in the packet, but for a bug in the dissector (for example, an
526 assumption being made at a particular point in the code about the
527 internal state of the dissector), use the DISSECTOR_ASSERT macro for
528 that purpose; this will put into the protocol tree an indication that
529 the dissector has a bug in it, and will not crash the application.
530
531 If you are allocating a chunk of memory to contain data from a packet,
532 or to contain information derived from data in a packet, and the size of
533 the chunk of memory is derived from a size field in the packet, make
534 sure all the data is present in the packet before allocating the buffer.
535 Doing so means that:
536
537     1) Wireshark won't leak that chunk of memory if an attempt to
538        fetch data not present in the packet throws an exception.
539
540 and
541
542     2) it won't crash trying to allocate an absurdly-large chunk of
543        memory if the size field has a bogus large value.
544
545 If you're fetching into such a chunk of memory a string from the buffer,
546 and the string has a specified size, you can use "tvb_get_*_string()",
547 which will check whether the entire string is present before allocating
548 a buffer for the string, and will also put a trailing '\0' at the end of
549 the buffer.
550
551 If you're fetching into such a chunk of memory a 2-byte Unicode string
552 from the buffer, and the string has a specified size, you can use
553 "tvb_get_faked_unicode()", which will check whether the entire string
554 is present before allocating a buffer for the string, and will also
555 put a trailing '\0' at the end of the buffer.  The resulting string will be
556 a sequence of single-byte characters; the only Unicode characters that
557 will be handled correctly are those in the ASCII range.  (Wireshark's
558 ability to handle non-ASCII strings is limited; it needs to be
559 improved.)
560
561 If you're fetching into such a chunk of memory a sequence of bytes from
562 the buffer, and the sequence has a specified size, you can use
563 "tvb_memdup()", which will check whether the entire sequence is present
564 before allocating a buffer for it.
565
566 Otherwise, you can check whether the data is present by using
567 "tvb_ensure_bytes_exist()" although this frequently is not needed: the
568 TVB-accessor routines can handle requests to read data beyond the end of
569 the TVB (by throwing an exception which will either mark the frame as
570 truncated--not all the data was captured--or as malformed).
571
572 Note also that you should only fetch string data into a fixed-length
573 buffer if the code ensures that no more bytes than will fit into the
574 buffer are fetched ("the protocol ensures" isn't good enough, as
575 protocol specifications can't ensure only packets that conform to the
576 specification will be transmitted or that only packets for the protocol
577 in question will be interpreted as packets for that protocol by
578 Wireshark).  If there's no maximum length of string data to be fetched,
579 routines such as "tvb_get_*_string()" are safer, as they allocate a buffer
580 large enough to hold the string.  (Note that some variants of this call
581 require you to free the string once you're finished with it.)
582
583 If you have gotten a pointer using "tvb_get_ptr()" (which you should not
584 have: you should seriously consider a better alternative to this function),
585 you must make sure that you do not refer to any data past the length passed
586 as the last argument to "tvb_get_ptr()"; while the various "tvb_get"
587 routines perform bounds checking and throw an exception if you refer to data
588 not available in the tvbuff, direct references through a pointer gotten from
589 "tvb_get_ptr()" do not do any bounds checking.
590
591 If you have a loop that dissects a sequence of items, each of which has
592 a length field, with the offset in the tvbuff advanced by the length of
593 the item, then, if the length field is the total length of the item, and
594 thus can be zero, you *MUST* check for a zero-length item and abort the
595 loop if you see one.  Otherwise, a zero-length item could cause the
596 dissector to loop infinitely.  You should also check that the offset,
597 after having the length added to it, is greater than the offset before
598 the length was added to it, if the length field is greater than 24 bits
599 long, so that, if the length value is *very* large and adding it to the
600 offset causes an overflow, that overflow is detected.
601
602 If you have a
603
604     for (i = {start}; i < {end}; i++)
605
606 loop, make sure that the type of the loop index variable is large enough
607 to hold the maximum {end} value plus 1; otherwise, the loop index
608 variable can overflow before it ever reaches its maximum value.  In
609 particular, be very careful when using gint8, guint8, gint16, or guint16
610 variables as loop indices; you almost always want to use an "int"/"gint"
611 or "unsigned int"/"guint" as the loop index rather than a shorter type.
612
613 If you are fetching a length field from the buffer, corresponding to the
614 length of a portion of the packet, and subtracting from that length a
615 value corresponding to the length of, for example, a header in the
616 packet portion in question, *ALWAYS* check that the value of the length
617 field is greater than or equal to the length you're subtracting from it,
618 and report an error in the packet and stop dissecting the packet if it's
619 less than the length you're subtracting from it.  Otherwise, the
620 resulting length value will be negative, which will either cause errors
621 in the dissector or routines called by the dissector, or, if the value
622 is interpreted as an unsigned integer, will cause the value to be
623 interpreted as a very large positive value.
624
625 Any tvbuff offset that is added to as processing is done on a packet
626 should be stored in a 32-bit variable, such as an "int"; if you store it
627 in an 8-bit or 16-bit variable, you run the risk of the variable
628 overflowing.
629
630 sprintf() -> g_snprintf()
631 Prevent yourself from using the sprintf() function, as it does not test the
632 length of the given output buffer and might be writing into unintended memory
633 areas. This function is one of the main causes of security problems like buffer
634 exploits and many other bugs that are very hard to find. It's much better to
635 use the g_snprintf() function declared by <glib.h> instead.
636
637 You should test your dissector against incorrectly-formed packets.  This
638 can be done using the randpkt and editcap utilities that come with the
639 Wireshark distribution.  Testing using randpkt can be done by generating
640 output at the same layer as your protocol, and forcing Wireshark/TShark
641 to decode it as your protocol, e.g. if your protocol sits on top of UDP:
642
643     randpkt -c 50000 -t dns randpkt.pcap
644     tshark -nVr randpkt.pcap -d udp.port==53,<myproto>
645
646 Testing using editcap can be done using preexisting capture files and the
647 "-E" flag, which introduces errors in a capture file.  E.g.:
648
649     editcap -E 0.03 infile.pcap outfile.pcap
650     tshark -nVr outfile.pcap
651
652 The script fuzz-test.sh is available to help automate these tests.
653
654 4. Name convention.
655
656 Wireshark uses the underscore_convention rather than the InterCapConvention for
657 function names, so new code should probably use underscores rather than
658 intercaps for functions and variable names. This is especially important if you
659 are writing code that will be called from outside your code.  We are just
660 trying to keep things consistent for other developers.
661
662 5. White space convention.
663
664 Please avoid using tab expansions different from 8 column widths, as not all
665 text editors in use by the developers support this. For a detailed
666 discussion of tabs, spaces, and indentation, see
667
668     http://www.jwz.org/doc/tabs-vs-spaces.html
669
670 When creating a new file, you are free to choose an indentation logic.
671 Most of the files in Wireshark tend to use 2-space or 4-space
672 indentation. You are encouraged to write a short comment on the
673 indentation logic at the beginning of this new files.  The
674 tabs-vs-spaces document above provides examples of Emacs and vi
675 modelines for this purpose.
676
677 Please do not leave trailing whitespace (spaces/tabs) on lines.
678
679 When editing an existing file, try following the existing indentation
680 logic and even if it very tempting, never ever use a restyler/reindenter
681 utility on an existing file.  If you run across wildly varying
682 indentation styles within the same file, it might be helpful to send a
683 note to wireshark-dev for guidance.
684
685 6. Compiler warnings
686
687 You should write code that is free of compiler warnings. Such warnings will
688 often indicate questionable code and sometimes even real bugs, so it's best
689 to avoid warnings at all.
690
691 The compiler flags in the Makefiles are set to "treat warnings as errors",
692 so your code won't even compile when warnings occur.
693
694 /*
695  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
696  *
697  * Local variables:
698  * c-basic-offset: 4
699  * tab-width: 8
700  * indent-tabs-mode: nil
701  * End:
702  *
703  * vi: set shiftwidth=4 tabstop=8 expandtab:
704  * :indentSize=4:tabSize=8:noTabs=true:
705  */