Set the svn:eol-style property on all text files to "native", so that
[obnox/wireshark/wip.git] / epan / tvbuff.h
1 /* tvbuff.h
2  *
3  * Testy, Virtual(-izable) Buffer of guint8*'s
4  *
5  * "Testy" -- the buffer gets mad when an attempt is made to access data
6  *              beyond the bounds of the buffer. An exception is thrown.
7  *
8  * "Virtual" -- the buffer can have its own data, can use a subset of
9  *              the data of a backing tvbuff, or can be a composite of
10  *              other tvbuffs.
11  *
12  * $Id$
13  *
14  * Copyright (c) 2000 by Gilbert Ramirez <gram@alumni.rice.edu>
15  *
16  * Ethereal - Network traffic analyzer
17  * By Gerald Combs <gerald@ethereal.com>
18  * Copyright 1998 Gerald Combs
19  *
20  * This program is free software; you can redistribute it and/or
21  * modify it under the terms of the GNU General Public License
22  * as published by the Free Software Foundation; either version 2
23  * of the License, or (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program; if not, write to the Free Software
32  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  */
34
35 #ifndef __TVBUFF_H__
36 #define __TVBUFF_H__
37
38 #include <glib.h>
39 #include "exceptions.h"
40
41 /* The different types of tvbuff's */
42 typedef enum {
43         TVBUFF_REAL_DATA,
44         TVBUFF_SUBSET,
45         TVBUFF_COMPOSITE
46 } tvbuff_type;
47
48 typedef struct {
49         /* The backing tvbuff_t */
50         struct tvbuff   *tvb;
51
52         /* The offset/length of 'tvb' to which I'm privy */
53         guint           offset;
54         guint           length;
55
56 } tvb_backing_t;
57
58 typedef struct {
59         GSList          *tvbs;
60
61         /* Used for quick testing to see if this
62          * is the tvbuff that a COMPOSITE is
63          * interested in. */
64         guint           *start_offsets;
65         guint           *end_offsets;
66
67 } tvb_comp_t;
68
69 typedef void (*tvbuff_free_cb_t)(void*);
70
71 typedef struct tvbuff {
72         /* Record-keeping */
73         tvbuff_type             type;
74         gboolean                initialized;
75         guint                   usage_count;
76         struct tvbuff           *ds_tvb;  /* data source top-level tvbuff */
77
78         /* The tvbuffs in which this tvbuff is a member
79          * (that is, a backing tvbuff for a TVBUFF_SUBSET
80          * or a member for a TVB_COMPOSITE) */
81         GSList                  *used_in;
82
83         /* TVBUFF_SUBSET and TVBUFF_COMPOSITE keep track
84          * of the other tvbuff's they use */
85         union {
86                 tvb_backing_t   subset;
87                 tvb_comp_t      composite;
88         } tvbuffs;
89
90         /* We're either a TVBUFF_REAL_DATA or a
91          * TVBUFF_SUBSET that has a backing buffer that
92          * has real_data != NULL, or a TVBUFF_COMPOSITE
93          * which has flattened its data due to a call
94          * to tvb_get_ptr().
95          */
96         const guint8            *real_data;
97
98         /* Length of virtual buffer (and/or real_data). */
99         guint                   length;
100
101         /* Reported length. */
102         guint                   reported_length;
103
104         /* Offset from beginning of first TVBUFF_REAL. */
105         gint                    raw_offset;
106
107         /* Func to call when actually freed */
108         tvbuff_free_cb_t        free_cb;
109 } tvbuff_t;
110
111
112
113 /* TVBUFF_REAL_DATA contains a guint8* that points to real data.
114  * The data is allocated and contiguous.
115  *
116  * TVBUFF_SUBSET has a backing tvbuff. The TVBUFF_SUBSET is a "window"
117  * through which the program sees only a portion of the backing tvbuff.
118  *
119  * TVBUFF_COMPOSITE combines multiple tvbuffs sequentually to produce
120  * a larger byte array.
121  *
122  * tvbuff's of any type can be used as the backing-tvbuff of a
123  * TVBUFF_SUBSET or as the member of a TVBUFF_COMPOSITE.
124  * TVBUFF_COMPOSITEs can have member-tvbuffs of different types.
125  *
126  * Once a tvbuff is create/initialized/finalized, the tvbuff is read-only.
127  * That is, it cannot point to any other data. A new tvbuff must be created if
128  * you want a tvbuff that points to other data.
129  */
130
131
132 /* "class" initialization. Called once during execution of program
133  * so that tvbuff.c can initialize its data. */
134 extern void tvbuff_init(void);
135
136 /* "class" cleanup. Called once during execution of program
137  * so that tvbuff.c can clean up its data. */
138 extern void tvbuff_cleanup(void);
139
140
141 /* Returns a pointer to a newly initialized tvbuff. Note that
142  * tvbuff's of types TVBUFF_SUBSET and TVBUFF_COMPOSITE
143  * require further initialization via the appropriate functions */
144 extern tvbuff_t* tvb_new(tvbuff_type);
145
146 /* Marks a tvbuff for freeing. The guint8* data of a TVBUFF_REAL_DATA
147  * is *never* freed by the tvbuff routines. The tvbuff itself is actually freed
148  * once its usage count drops to 0.
149  *
150  * Usage counts increment for any time the tvbuff is
151  * used as a member of another tvbuff, i.e., as the backing buffer for
152  * a TVBUFF_SUBSET or as a member of a TVBUFF_COMPOSITE.
153  *
154  * Although you may call tvb_free(), the tvbuff may still be in use
155  * by other tvbuff's (TVBUFF_SUBSET or TVBUFF_COMPOSITE), so it is not
156  * safe, unless you know otherwise, to free your guint8* data. If you
157  * cannot be sure that your TVBUFF_REAL_DATA is not in use by another
158  * tvbuff, register a callback with tvb_set_free_cb(); when your tvbuff
159  * is _really_ freed, then your callback will be called, and at that time
160  * you can free your original data.
161  *
162  * The caller can artificially increment/decrement the usage count
163  * with tvbuff_increment_usage_count()/tvbuff_decrement_usage_count().
164  */
165 extern void tvb_free(tvbuff_t*);
166
167 /* Free the tvbuff_t and all tvbuff's created from it. */
168 extern void tvb_free_chain(tvbuff_t*);
169
170 /* Both return the new usage count, after the increment or decrement */
171 extern guint tvb_increment_usage_count(tvbuff_t*, guint count);
172
173 /* If a decrement causes the usage count to drop to 0, a the tvbuff
174  * is immediately freed. Be sure you know exactly what you're doing
175  * if you decide to use this function, as another tvbuff could
176  * still have a pointer to the just-freed tvbuff, causing corrupted data
177  * or a segfault in the future */
178 extern guint tvb_decrement_usage_count(tvbuff_t*, guint count);
179
180 /* Set a callback function to call when a tvbuff is actually freed
181  * (once the usage count drops to 0). One argument is passed to
182  * that callback --- a void* that points to the real data.
183  * Obviously, this only applies to a TVBUFF_REAL_DATA tvbuff. */
184 extern void tvb_set_free_cb(tvbuff_t*, tvbuff_free_cb_t);
185
186
187 /* Attach a TVBUFF_REAL_DATA tvbuff to a parent tvbuff. This connection
188  * is used during a tvb_free_chain()... the "child" TVBUFF_REAL_DATA acts
189  * as if is part of the chain-of-creation of the parent tvbuff, although it
190  * isn't. This is useful if you need to take the data from some tvbuff,
191  * run some operation on it, like decryption or decompression, and make a new
192  * tvbuff from it, yet want the new tvbuff to be part of the chain. The reality
193  * is that the new tvbuff *is* part of the "chain of creation", but in a way
194  * that these tvbuff routines is ignorant of. Use this function to make
195  * the tvbuff routines knowledgable of this fact. */
196 extern void tvb_set_child_real_data_tvbuff(tvbuff_t* parent, tvbuff_t* child);
197
198 /* Sets parameters for TVBUFF_REAL_DATA. Can throw ReportedBoundsError. */
199 extern void tvb_set_real_data(tvbuff_t*, const guint8* data, guint length,
200     gint reported_length);
201
202 /* Combination of tvb_new() and tvb_set_real_data(). Can throw ReportedBoundsError. */
203 extern tvbuff_t* tvb_new_real_data(const guint8* data, guint length,
204     gint reported_length);
205
206
207 /* Define the subset of the backing buffer to use.
208  *
209  * 'backing_offset' can be negative, to indicate bytes from
210  * the end of the backing buffer.
211  *
212  * 'backing_length' can be 0, although the usefulness of the buffer would
213  * be rather limited.
214  *
215  * 'backing_length' of -1 means "to the end of the backing buffer"
216  *
217  * Will throw BoundsError if 'backing_offset'/'length'
218  * is beyond the bounds of the backing tvbuff.
219  * Can throw ReportedBoundsError. */
220 extern void tvb_set_subset(tvbuff_t* tvb, tvbuff_t* backing,
221                 gint backing_offset, gint backing_length, gint reported_length);
222
223 /* Combination of tvb_new() and tvb_set_subset()
224  * Can throw ReportedBoundsError. */
225 extern tvbuff_t* tvb_new_subset(tvbuff_t* backing,
226                 gint backing_offset, gint backing_length, gint reported_length);
227
228
229 /* Both tvb_composite_append and tvb_composite_prepend can throw
230  * BoundsError if member_offset/member_length goes beyond bounds of
231  * the 'member' tvbuff. */
232
233 /* Append to the list of tvbuffs that make up this composite tvbuff */
234 extern void tvb_composite_append(tvbuff_t* tvb, tvbuff_t* member);
235
236 /* Prepend to the list of tvbuffs that make up this composite tvbuff */
237 extern void tvb_composite_prepend(tvbuff_t* tvb, tvbuff_t* member);
238
239 /* Helper function that calls tvb_new(TVBUFF_COMPOSITE).
240  * Provided only to maintain symmetry with other constructors */
241 extern tvbuff_t* tvb_new_composite(void);
242
243 /* Mark a composite tvbuff as initialized. No further appends or prepends
244  * occur, data access can finally happen after this finalization. */
245 extern void tvb_composite_finalize(tvbuff_t* tvb);
246
247
248 /* Get total length of buffer */
249 extern guint tvb_length(tvbuff_t*);
250
251 /* Computes bytes to end of buffer, from offset (which can be negative,
252  * to indicate bytes from end of buffer). Function returns -1 to
253  * indicate that offset is out of bounds. No exception is thrown. */
254 extern gint tvb_length_remaining(tvbuff_t*, gint offset);
255
256 /* Same as above, but throws an exception if the offset is out of bounds. */
257 extern guint tvb_ensure_length_remaining(tvbuff_t*, gint offset);
258
259 /* Checks (w/o throwing exception) that the bytes referred to by
260  * 'offset'/'length' actually exist in the buffer */
261 extern gboolean tvb_bytes_exist(tvbuff_t*, gint offset, gint length);
262
263 /* Checks that the bytes referred to by 'offset'/'length' actually exist
264  * in the buffer, and throws an exception if they aren't. */
265 extern void tvb_ensure_bytes_exist(tvbuff_t *tvb, gint offset, gint length);
266
267 /* Checks (w/o throwing exception) that offset exists in buffer */
268 extern gboolean tvb_offset_exists(tvbuff_t*, gint offset);
269
270 /* Get reported length of buffer */
271 extern guint tvb_reported_length(tvbuff_t*);
272
273 /* Computes bytes of reported packet data to end of buffer, from offset
274  * (which can be negative, to indicate bytes from end of buffer). Function
275  * returns -1 to indicate that offset is out of bounds. No exception is
276  * thrown. */
277 extern gint tvb_reported_length_remaining(tvbuff_t *tvb, gint offset);
278
279 /* Set the reported length of a tvbuff to a given value; used for protocols
280    whose headers contain an explicit length and where the calling
281    dissector's payload may include padding as well as the packet for
282    this protocol.
283
284    Also adjusts the data length. */
285 extern void tvb_set_reported_length(tvbuff_t*, guint);
286
287 extern int offset_from_real_beginning(tvbuff_t *tvb, int counter);
288
289 /* Returns the offset from the first byte of real data. */
290 #define TVB_RAW_OFFSET(tvb)                     \
291         ((tvb->raw_offset==-1)?(tvb->raw_offset = offset_from_real_beginning(tvb, 0)):tvb->raw_offset)
292
293 /************** START OF ACCESSORS ****************/
294 /* All accessors will throw an exception if appropriate */
295
296 extern guint8  tvb_get_guint8(tvbuff_t*, gint offset);
297
298 extern guint16 tvb_get_ntohs(tvbuff_t*, gint offset);
299 extern guint32 tvb_get_ntoh24(tvbuff_t*, gint offset);
300 extern guint32 tvb_get_ntohl(tvbuff_t*, gint offset);
301 extern gfloat tvb_get_ntohieee_float(tvbuff_t*, gint offset);
302 extern gdouble tvb_get_ntohieee_double(tvbuff_t*, gint offset);
303
304 extern guint16 tvb_get_letohs(tvbuff_t*, gint offset);
305 extern guint32 tvb_get_letoh24(tvbuff_t*, gint offset);
306 extern guint32 tvb_get_letohl(tvbuff_t*, gint offset);
307 extern gfloat tvb_get_letohieee_float(tvbuff_t*, gint offset);
308 extern gdouble tvb_get_letohieee_double(tvbuff_t*, gint offset);
309
310 /* Returns target for convenience. Does not suffer from possible
311  * expense of tvb_get_ptr(), since this routine is smart enough
312  * to copy data in chunks if the request range actually exists in
313  * different TVBUFF_REAL_DATA tvbuffs. This function assumes that the
314  * target memory is already allocated; it does not allocate or free the
315  * target memory. */
316 extern guint8* tvb_memcpy(tvbuff_t*, guint8* target, gint offset, gint length);
317
318 /* It is the user's responsibility to g_free() the memory allocated by
319  * tvb_memdup(). Calls tvb_memcpy() */
320 extern guint8* tvb_memdup(tvbuff_t*, gint offset, gint length);
321
322 /* WARNING! This function is possibly expensive, temporarily allocating
323  * another copy of the packet data. Furthermore, it's dangerous because once
324  * this pointer is given to the user, there's no guarantee that the user will
325  * honor the 'length' and not overstep the boundaries of the buffer.
326  *
327  * The returned pointer is data that is internal to the tvbuff, so do not
328  * attempt to free it. Don't modify the data, either, because another tvbuff
329  * that might be using this tvbuff may have already copied that portion of
330  * the data (sometimes tvbuff's need to make copies of data, but that's the
331  * internal implementation that you need not worry about). Assume that the
332  * guint8* points to read-only data that the tvbuff manages.
333  *
334  * Return a pointer into our buffer if the data asked for via 'offset'/'length'
335  * is contiguous (which might not be the case for TVBUFF_COMPOSITE). If the
336  * data is not contiguous, a tvb_memdup() is called for the entire buffer
337  * and the pointer to the newly-contiguous data is returned. This dynamically-
338  * allocated memory will be freed when the tvbuff is freed, after the
339  * tvbuff_free_cb_t() is called, if any. */
340 extern const guint8* tvb_get_ptr(tvbuff_t*, gint offset, gint length);
341
342 /* Find first occurence of any of the needles in tvbuff, starting at offset.
343  * Searches at most maxlength number of bytes; if maxlength is -1, searches
344  * to end of tvbuff.
345  * Returns the offset of the found needle, or -1 if not found.
346  * Will not throw an exception, even if maxlength exceeds boundary of tvbuff;
347  * in that case, -1 will be returned if the boundary is reached before
348  * finding needle. */
349 extern gint tvb_find_guint8(tvbuff_t*, gint offset, gint maxlength,
350     guint8 needle);
351
352 /* Find first occurence of any of the needles in tvbuff, starting at offset.
353  * Searches at most maxlength number of bytes. Returns the offset of the
354  * found needle, or -1 if not found. Will not throw an exception, even if
355  * maxlength exceeds boundary of tvbuff; in that case, -1 will be returned if
356  * the boundary is reached before finding needle. */
357 extern gint tvb_pbrk_guint8(tvbuff_t *, gint offset, gint maxlength,
358     guint8 *needles);
359
360 /* Find size of stringz (NUL-terminated string) by looking for terminating
361  * NUL.  The size of the string includes the terminating NUL.
362  *
363  * If the NUL isn't found, it throws the appropriate exception.
364  */
365 extern guint tvb_strsize(tvbuff_t *tvb, gint offset);
366
367 /* Find length of string by looking for end of string ('\0'), up to
368  * 'maxlength' characters'; if 'maxlength' is -1, searches to end
369  * of tvbuff.
370  * Returns -1 if 'maxlength' reached before finding EOS. */
371 extern gint tvb_strnlen(tvbuff_t*, gint offset, guint maxlength);
372
373 /* Convert a string from Unicode to ASCII.  At the moment we fake it by
374  * assuming all characters are ASCII  )-:  The caller must free the
375  * result returned.  The len parameter is the number of guint16's to
376  * convert from Unicode. */
377 extern char *tvb_fake_unicode(tvbuff_t *tvb, int offset, int len,
378                               gboolean little_endian);
379
380 /*
381  * Format the data in the tvb from offset for size ...
382  */
383 extern gchar * tvb_format_text(tvbuff_t *tvb, gint offset, gint size);
384
385 /*
386  * Like "tvb_format_text()", but for null-padded strings; don't show
387  * the null padding characters as "\000".
388  */
389 extern gchar *tvb_format_stringzpad(tvbuff_t *tvb, gint offset, gint size);
390
391 /*
392  * Given a tvbuff, an offset, and a length, allocate a buffer big enough
393  * to hold a non-null-terminated string of that length at that offset,
394  * plus a trailing '\0', copy the string into it, and return a pointer
395  * to the string.
396  *
397  * Throws an exception if the tvbuff ends before the string does.
398  */
399 extern guint8 *tvb_get_string(tvbuff_t *tvb, gint offset, gint length);
400
401 /*
402  * Given a tvbuff and an offset, with the offset assumed to refer to
403  * a null-terminated string, find the length of that string (and throw
404  * an exception if the tvbuff ends before we find the null), allocate
405  * a buffer big enough to hold the string, copy the string into it,
406  * and return a pointer to the string.  Also return the length of the
407  * string (including the terminating null) through a pointer.
408  */
409 extern guint8 *tvb_get_stringz(tvbuff_t *tvb, gint offset, gint *lengthp);
410
411 /* Looks for a stringz (NUL-terminated string) in tvbuff and copies
412  * no more than bufsize number of bytes, including terminating NUL, to buffer.
413  * Returns length of string (not including terminating NUL), or -1 if the string was
414  * truncated in the buffer due to not having reached the terminating NUL.
415  * In this way, it acts like snprintf().
416  *
417  * When processing a packet where the remaining number of bytes is less
418  * than bufsize, an exception is not thrown if the end of the packet
419  * is reached before the NUL is found. If no NUL is found before reaching
420  * the end of the short packet, -1 is still returned, and the string
421  * is truncated with a NUL, albeit not at buffer[bufsize - 1], but
422  * at the correct spot, terminating the string.
423  */
424 extern gint tvb_get_nstringz(tvbuff_t *tvb, gint offset, guint bufsize,
425     guint8* buffer);
426
427 /* Like tvb_get_nstringz(), but never returns -1. The string is guaranteed to
428  * have a terminating NUL. If the string was truncated when copied into buffer,
429  * a NUL is placed at the end of buffer to terminate it.
430  *
431  * bufsize MUST be greater than 0.
432  */
433 extern gint tvb_get_nstringz0(tvbuff_t *tvb, gint offset, guint bufsize,
434     guint8* buffer);
435
436 /*
437  * Given a tvbuff, an offset into the tvbuff, and a length that starts
438  * at that offset (which may be -1 for "all the way to the end of the
439  * tvbuff"), find the end of the (putative) line that starts at the
440  * specified offset in the tvbuff, going no further than the specified
441  * length.
442  *
443  * Return the length of the line (not counting the line terminator at
444  * the end), or, if we don't find a line terminator:
445  *
446  *      if "deseg" is true, return -1;
447  *
448  *      if "deseg" is false, return the amount of data remaining in
449  *      the buffer.
450  *
451  * Set "*next_offset" to the offset of the character past the line
452  * terminator, or past the end of the buffer if we don't find a line
453  * terminator.  (It's not set if we return -1.)
454  */
455 extern gint tvb_find_line_end(tvbuff_t *tvb, gint offset, int len,
456     gint *next_offset, gboolean desegment);
457
458 /*
459  * Given a tvbuff, an offset into the tvbuff, and a length that starts
460  * at that offset (which may be -1 for "all the way to the end of the
461  * tvbuff"), find the end of the (putative) line that starts at the
462  * specified offset in the tvbuff, going no further than the specified
463  * length.
464  *
465  * However, treat quoted strings inside the buffer specially - don't
466  * treat newlines in quoted strings as line terminators.
467  *
468  * Return the length of the line (not counting the line terminator at
469  * the end), or the amount of data remaining in the buffer if we don't
470  * find a line terminator.
471  *
472  * Set "*next_offset" to the offset of the character past the line
473  * terminator, or past the end of the buffer if we don't find a line
474  * terminator.
475  */
476 extern gint tvb_find_line_end_unquoted(tvbuff_t *tvb, gint offset, int len,
477     gint *next_offset);
478
479 /*
480  * Call strncmp after checking if enough chars left, returning 0 if
481  * it returns 0 (meaning "equal") and -1 otherwise, otherwise return -1.
482  */
483 extern gint tvb_strneql(tvbuff_t *tvb, gint offset, const gchar *str,
484     gint size);
485
486 /*
487  * Call strncasecmp after checking if enough chars left, returning 0 if
488  * it returns 0 (meaning "equal") and -1 otherwise, otherwise return -1.
489  */
490 extern gint tvb_strncaseeql(tvbuff_t *tvb, gint offset, const gchar *str,
491     gint size);
492
493 /*
494  * Call memcmp after checking if enough chars left, returning 0 if
495  * it returns 0 (meaning "equal") and -1 otherwise, otherwise return -1.
496  */
497 extern gint tvb_memeql(tvbuff_t *tvb, gint offset, const guint8 *str,
498     gint size);
499
500 /*
501  * Format a bunch of data from a tvbuff as bytes, returning a pointer
502  * to the string with the formatted data.
503  */
504 extern gchar *tvb_bytes_to_str(tvbuff_t *tvb, gint offset, gint len);
505
506 #define TVB_GET_DS_TVB(tvb)             \
507         (tvb->ds_tvb)
508
509 /* Locate a sub-tvbuff within another tvbuff, starting at position
510  * 'haystack_offset'. Returns the index of the beginning of 'needle' within
511  * 'haystack', or -1 if 'needle' is not found. The index is relative
512  * to the start of 'haystack', not 'haystack_offset'. */
513 extern gint tvb_find_tvb(tvbuff_t *haystack_tvb, tvbuff_t *needle_tvb,
514         gint haystack_offset);
515
516 /*
517  * Uncompresses a zlib compressed packet inside a tvbuff at offset with
518  * length comprlen.  Returns an uncompressed tvbuffer if uncompression
519  * succeeded or NULL if uncompression failed.
520  */
521 extern tvbuff_t* tvb_uncompress(tvbuff_t *tvb, int offset, int comprlen);
522
523 /************** END OF ACCESSORS ****************/
524
525 #endif /* __TVBUFF_H__ */