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