From Ishraq Ibne Ashraf: Tinkerforge protocol dissector
[metze/wireshark/wip.git] / epan / reassemble.c
1 /* reassemble.c
2  * Routines for {fragment,segment} reassembly
3  *
4  * $Id$
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include "config.h"
26
27 #include <string.h>
28
29 #include <epan/packet.h>
30 #include <epan/emem.h>
31 #include <epan/reassemble.h>
32 #include <epan/tvbuff-int.h>
33
34 /*
35  * Functions for reassembly tables where the endpoint addresses, and a
36  * fragment ID, are used as the key.
37  */
38 typedef struct _fragment_addresses_key {
39         address src;
40         address dst;
41         guint32 id;
42 } fragment_addresses_key;
43
44 static guint
45 fragment_addresses_hash(gconstpointer k)
46 {
47         const fragment_addresses_key* key = (const fragment_addresses_key*) k;
48         guint hash_val;
49 /*
50         int i;
51 */
52
53         hash_val = 0;
54
55 /*      More than likely: in most captures src and dst addresses are the
56         same, and would hash the same.
57         We only use id as the hash as an optimization.
58
59         for (i = 0; i < key->src.len; i++)
60                 hash_val += key->src.data[i];
61         for (i = 0; i < key->dst.len; i++)
62                 hash_val += key->dst.data[i];
63 */
64
65         hash_val += key->id;
66
67         return hash_val;
68 }
69
70 static gint
71 fragment_addresses_equal(gconstpointer k1, gconstpointer k2)
72 {
73         const fragment_addresses_key* key1 = (const fragment_addresses_key*) k1;
74         const fragment_addresses_key* key2 = (const fragment_addresses_key*) k2;
75
76         /*
77          * key.id is the first item to compare since it's the item most
78          * likely to differ between sessions, thus short-circuiting
79          * the comparison of addresses.
80          */
81         return (key1->id == key2->id) &&
82                (ADDRESSES_EQUAL(&key1->src, &key2->src)) &&
83                (ADDRESSES_EQUAL(&key1->dst, &key2->dst));
84 }
85
86 /*
87  * Create a fragment key for temporary use; it can point to non-
88  * persistent data, and so must only be used to look up and
89  * delete entries, not to add them.
90  */
91 static gpointer
92 fragment_addresses_temporary_key(const packet_info *pinfo, const guint32 id,
93                                  const void *data _U_)
94 {
95         fragment_addresses_key *key = g_slice_new(fragment_addresses_key);
96
97         /*
98          * Do a shallow copy of the addresses.
99          */
100         key->src = pinfo->src;
101         key->dst = pinfo->dst;
102         key->id = id;
103
104         return (gpointer)key;
105 }
106
107 /*
108  * Create a fragment key for permanent use; it must point to persistent
109  * data, so that it can be used to add entries.
110  */
111 static gpointer
112 fragment_addresses_persistent_key(const packet_info *pinfo, const guint32 id,
113                                   const void *data _U_)
114 {
115         fragment_addresses_key *key = g_slice_new(fragment_addresses_key);
116
117         /*
118          * Do a deep copy of the addresses.
119          */
120         COPY_ADDRESS(&key->src, &pinfo->src);
121         COPY_ADDRESS(&key->dst, &pinfo->dst);
122         key->id = id;
123
124         return (gpointer)key;
125 }
126
127 static void
128 fragment_addresses_free_temporary_key(gpointer ptr)
129 {
130         fragment_addresses_key *key = (fragment_addresses_key *)ptr;
131
132         if(key)
133                 g_slice_free(fragment_addresses_key, key);
134 }
135
136 static void
137 fragment_addresses_free_persistent_key(gpointer ptr)
138 {
139         fragment_addresses_key *key = (fragment_addresses_key *)ptr;
140
141         if(key){
142                 /*
143                  * Free up the copies of the addresses from the old key.
144                  */
145                 g_free((gpointer)key->src.data);
146                 g_free((gpointer)key->dst.data);
147
148                 g_slice_free(fragment_addresses_key, key);
149         }
150 }
151
152 const reassembly_table_functions
153 addresses_reassembly_table_functions = {
154         fragment_addresses_hash,
155         fragment_addresses_equal,
156         fragment_addresses_temporary_key,
157         fragment_addresses_persistent_key,
158         fragment_addresses_free_temporary_key,
159         fragment_addresses_free_persistent_key
160 };
161
162 /*
163  * Functions for reassembly tables where the endpoint addresses and ports,
164  * and a fragment ID, are used as the key.
165  */
166 typedef struct _fragment_addresses_ports_key {
167         address src_addr;
168         address dst_addr;
169         guint32 src_port;
170         guint32 dst_port;
171         guint32 id;
172 } fragment_addresses_ports_key;
173
174 static guint
175 fragment_addresses_ports_hash(gconstpointer k)
176 {
177         const fragment_addresses_ports_key* key = (const fragment_addresses_ports_key*) k;
178         guint hash_val;
179 /*
180         int i;
181 */
182
183         hash_val = 0;
184
185 /*      More than likely: in most captures src and dst addresses and ports
186         are the same, and would hash the same.
187         We only use id as the hash as an optimization.
188
189         for (i = 0; i < key->src.len; i++)
190                 hash_val += key->src_addr.data[i];
191         for (i = 0; i < key->dst.len; i++)
192                 hash_val += key->dst_addr.data[i];
193         hash_val += key->src_port;
194         hash_val += key->dst_port;
195 */
196
197         hash_val += key->id;
198
199         return hash_val;
200 }
201
202 static gint
203 fragment_addresses_ports_equal(gconstpointer k1, gconstpointer k2)
204 {
205         const fragment_addresses_ports_key* key1 = (const fragment_addresses_ports_key*) k1;
206         const fragment_addresses_ports_key* key2 = (const fragment_addresses_ports_key*) k2;
207
208         /*
209          * key.id is the first item to compare since it's the item most
210          * likely to differ between sessions, thus short-circuiting
211          * the comparison of addresses and ports.
212          */
213         return (key1->id == key2->id) &&
214                (ADDRESSES_EQUAL(&key1->src_addr, &key2->src_addr)) &&
215                (ADDRESSES_EQUAL(&key1->dst_addr, &key2->dst_addr)) &&
216                (key1->src_port == key2->src_port) &&
217                (key1->dst_port == key2->dst_port);
218 }
219
220 /*
221  * Create a fragment key for temporary use; it can point to non-
222  * persistent data, and so must only be used to look up and
223  * delete entries, not to add them.
224  */
225 static gpointer
226 fragment_addresses_ports_temporary_key(const packet_info *pinfo, const guint32 id,
227                                        const void *data _U_)
228 {
229         fragment_addresses_ports_key *key = g_slice_new(fragment_addresses_ports_key);
230
231         /*
232          * Do a shallow copy of the addresses.
233          */
234         key->src_addr = pinfo->src;
235         key->dst_addr = pinfo->dst;
236         key->src_port = pinfo->srcport;
237         key->dst_port = pinfo->destport;
238         key->id = id;
239
240         return (gpointer)key;
241 }
242
243 /*
244  * Create a fragment key for permanent use; it must point to persistent
245  * data, so that it can be used to add entries.
246  */
247 static gpointer
248 fragment_addresses_ports_persistent_key(const packet_info *pinfo,
249                                         const guint32 id, const void *data _U_)
250 {
251         fragment_addresses_ports_key *key = g_slice_new(fragment_addresses_ports_key);
252
253         /*
254          * Do a deep copy of the addresses.
255          */
256         COPY_ADDRESS(&key->src_addr, &pinfo->src);
257         COPY_ADDRESS(&key->dst_addr, &pinfo->dst);
258         key->src_port = pinfo->srcport;
259         key->dst_port = pinfo->destport;
260         key->id = id;
261
262         return (gpointer)key;
263 }
264
265 static void
266 fragment_addresses_ports_free_temporary_key(gpointer ptr)
267 {
268         fragment_addresses_ports_key *key = (fragment_addresses_ports_key *)ptr;
269
270         if(key)
271                 g_slice_free(fragment_addresses_ports_key, key);
272 }
273
274 static void
275 fragment_addresses_ports_free_persistent_key(gpointer ptr)
276 {
277         fragment_addresses_ports_key *key = (fragment_addresses_ports_key *)ptr;
278
279         if(key){
280                 /*
281                  * Free up the copies of the addresses from the old key.
282                  */
283                 g_free((gpointer)key->src_addr.data);
284                 g_free((gpointer)key->dst_addr.data);
285
286                 g_slice_free(fragment_addresses_ports_key, key);
287         }
288 }
289
290 const reassembly_table_functions
291 addresses_ports_reassembly_table_functions = {
292         fragment_addresses_ports_hash,
293         fragment_addresses_ports_equal,
294         fragment_addresses_ports_temporary_key,
295         fragment_addresses_ports_persistent_key,
296         fragment_addresses_ports_free_temporary_key,
297         fragment_addresses_ports_free_persistent_key
298 };
299
300 typedef struct _reassembled_key {
301         guint32 id;
302         guint32 frame;
303 } reassembled_key;
304
305 static gint
306 reassembled_equal(gconstpointer k1, gconstpointer k2)
307 {
308         const reassembled_key* key1 = (const reassembled_key*) k1;
309         const reassembled_key* key2 = (const reassembled_key*) k2;
310
311         /*
312          * We assume that the frame numbers are unlikely to be equal,
313          * so we check them first.
314          */
315         return key1->frame == key2->frame && key1->id == key2->id;
316 }
317
318 static guint
319 reassembled_hash(gconstpointer k)
320 {
321         const reassembled_key* key = (const reassembled_key*) k;
322
323         return key->frame;
324 }
325
326 /*
327  * For a fragment hash table entry, free the associated fragments.
328  * The entry value (fd_chain) is freed herein and the entry is freed
329  * when the key freeing routine is called (as a consequence of returning
330  * TRUE from this function).
331  */
332 static gboolean
333 free_all_fragments(gpointer key_arg _U_, gpointer value, gpointer user_data _U_)
334 {
335         fragment_head *fd_head;
336         fragment_item *tmp_fd;
337
338         /* g_hash_table_new_full() was used to supply a function
339          * to free the key and anything to which it points
340          */
341         for (fd_head = (fragment_head *)value; fd_head != NULL; fd_head = tmp_fd) {
342                 tmp_fd=fd_head->next;
343
344                 if(fd_head->tvb_data && !(fd_head->flags&FD_SUBSET_TVB))
345                         tvb_free(fd_head->tvb_data);
346                 g_slice_free(fragment_item, fd_head);
347         }
348
349         return TRUE;
350 }
351
352 /* ------------------------- */
353 static fragment_head *new_head(const guint32 flags)
354 {
355         fragment_head *fd_head;
356         /* If head/first structure in list only holds no other data than
357         * 'datalen' then we don't have to change the head of the list
358         * even if we want to keep it sorted
359         */
360         fd_head=g_slice_new0(fragment_head);
361
362         fd_head->flags=flags;
363         return fd_head;
364 }
365
366 #define FD_VISITED_FREE 0xffff
367
368 /*
369  * For a reassembled-packet hash table entry, free the fragment data
370  * to which the value refers and also the key itself.
371  */
372 static gboolean
373 free_all_reassembled_fragments(gpointer key_arg, gpointer value,
374                                    gpointer user_data)
375 {
376         GPtrArray *allocated_fragments = (GPtrArray *) user_data;
377         fragment_head *fd_head;
378
379         for (fd_head = (fragment_head *)value; fd_head != NULL; fd_head = fd_head->next) {
380                 /*
381                  * A reassembled packet is inserted into the
382                  * hash table once for every frame that made
383                  * up the reassembled packet; add first seen
384                  * fragments to array and later free them in
385                  * free_fragments()
386                  */
387                 if (fd_head->flags != FD_VISITED_FREE) {
388                         if (fd_head->flags & FD_SUBSET_TVB)
389                                 fd_head->tvb_data = NULL;
390                         g_ptr_array_add(allocated_fragments, fd_head);
391                         fd_head->flags = FD_VISITED_FREE;
392                 }
393         }
394
395         g_slice_free(reassembled_key, (reassembled_key *)key_arg);
396
397         return TRUE;
398 }
399
400 static void
401 free_fragments(gpointer data, gpointer user_data _U_)
402 {
403         fragment_item *fd_head = (fragment_item *) data;
404
405         if (fd_head->tvb_data)
406                 tvb_free(fd_head->tvb_data);
407         g_slice_free(fragment_item, fd_head);
408 }
409
410 /*
411  * Initialize a reassembly table, with specified functions.
412  */
413 void
414 reassembly_table_init(reassembly_table *table,
415                       const reassembly_table_functions *funcs)
416 {
417         if (table->temporary_key_func == NULL)
418                 table->temporary_key_func = funcs->temporary_key_func;
419         if (table->persistent_key_func == NULL)
420                 table->persistent_key_func = funcs->persistent_key_func;
421         if (table->free_temporary_key_func == NULL)
422                 table->free_temporary_key_func = funcs->free_temporary_key_func;
423         if (table->fragment_table != NULL) {
424                 /*
425                  * The fragment hash table exists.
426                  *
427                  * Remove all entries and free fragment data for each entry.
428                  *
429                  * The keys, and anything to which they point, are freed by
430                  * calling the table's key freeing function.  The values
431                  * are freed in free_all_fragments().
432                  */
433                 g_hash_table_foreach_remove(table->fragment_table,
434                                             free_all_fragments, NULL);
435         } else {
436                 /* The fragment table does not exist. Create it */
437                 table->fragment_table = g_hash_table_new_full(funcs->hash_func,
438                     funcs->equal_func, funcs->free_persistent_key_func, NULL);
439         }
440
441         if (table->reassembled_table != NULL) {
442                 GPtrArray *allocated_fragments;
443
444                 /*
445                  * The reassembled-packet hash table exists.
446                  *
447                  * Remove all entries and free reassembled packet
448                  * data and key for each entry.
449                  */
450
451                 allocated_fragments = g_ptr_array_new();
452                 g_hash_table_foreach_remove(table->reassembled_table,
453                                 free_all_reassembled_fragments, allocated_fragments);
454
455                 g_ptr_array_foreach(allocated_fragments, free_fragments, NULL);
456                 g_ptr_array_free(allocated_fragments, TRUE);
457         } else {
458                 /* The fragment table does not exist. Create it */
459                 table->reassembled_table = g_hash_table_new(reassembled_hash,
460                     reassembled_equal);
461         }
462 }
463
464 /*
465  * Destroy a reassembly table.
466  */
467 void
468 reassembly_table_destroy(reassembly_table *table)
469 {
470         /*
471          * Clear the function pointers.
472          */
473         table->temporary_key_func = NULL;
474         table->persistent_key_func = NULL;
475         table->free_temporary_key_func = NULL;
476         if (table->fragment_table != NULL) {
477                 /*
478                  * The fragment hash table exists.
479                  *
480                  * Remove all entries and free fragment data for each entry.
481                  *
482                  * The keys, and anything to which they point, are freed by
483                  * calling the table's key freeing function.  The values
484                  * are freed in free_all_fragments().
485                  */
486                 g_hash_table_foreach_remove(table->fragment_table,
487                                             free_all_fragments, NULL);
488
489                 /*
490                  * Now destroy the hash table.
491                  */
492                 g_hash_table_destroy(table->fragment_table);
493                 table->fragment_table = NULL;
494         }
495         if (table->reassembled_table != NULL) {
496                 GPtrArray *allocated_fragments;
497
498                 /*
499                  * The reassembled-packet hash table exists.
500                  *
501                  * Remove all entries and free reassembled packet
502                  * data and key for each entry.
503                  */
504
505                 allocated_fragments = g_ptr_array_new();
506                 g_hash_table_foreach_remove(table->reassembled_table,
507                                 free_all_reassembled_fragments, allocated_fragments);
508
509                 g_ptr_array_foreach(allocated_fragments, free_fragments, NULL);
510                 g_ptr_array_free(allocated_fragments, TRUE);
511
512                 /*
513                  * Now destroy the hash table.
514                  */
515                 g_hash_table_destroy(table->reassembled_table);
516                 table->reassembled_table = NULL;
517         }
518 }
519
520 /*
521  * Look up an fd_head in the fragment table, optionally returning the key
522  * for it.
523  */
524 static fragment_head *
525 lookup_fd_head(reassembly_table *table, const packet_info *pinfo,
526                const guint32 id, const void *data, gpointer *orig_keyp)
527 {
528         gpointer key;
529         gpointer value;
530
531         /* Create key to search hash with */
532         key = table->temporary_key_func(pinfo, id, data);
533
534         /*
535          * Look up the reassembly in the fragment table.
536          */
537         if (!g_hash_table_lookup_extended(table->fragment_table, key, orig_keyp,
538                                           &value))
539                 value = NULL;
540         /* Free the key */
541         table->free_temporary_key_func(key);
542
543         return (fragment_head *)value;
544 }
545
546 /*
547  * Insert an fd_head into the fragment table, and return the key used.
548  */
549 static gpointer
550 insert_fd_head(reassembly_table *table, fragment_head *fd_head,
551                const packet_info *pinfo, const guint32 id, const void *data)
552 {
553         gpointer key;
554
555         /*
556          * We're going to use the key to insert the fragment,
557          * so make a persistent version of it.
558          */
559         key = table->persistent_key_func(pinfo, id, data);
560         g_hash_table_insert(table->fragment_table, key, fd_head);
561         return key;
562 }
563
564 /* This function cleans up the stored state and removes the reassembly data and
565  * (with one exception) all allocated memory for matching reassembly.
566  *
567  * The exception is :
568  * If the PDU was already completely reassembled, then the tvbuff containing the
569  * reassembled data WILL NOT be free()d, and the pointer to that tvbuff will be
570  * returned.
571  * Othervise the function will return NULL.
572  *
573  * So, if you call fragment_delete and it returns non-NULL, YOU are responsible
574  * to tvb_free() that tvbuff.
575  */
576 tvbuff_t *
577 fragment_delete(reassembly_table *table, const packet_info *pinfo,
578                 const guint32 id, const void *data)
579 {
580         fragment_head *fd_head;
581         fragment_item *fd;
582         tvbuff_t *fd_tvb_data=NULL;
583         gpointer key;
584
585         fd_head = lookup_fd_head(table, pinfo, id, data, &key);
586         if(fd_head==NULL){
587                 /* We do not recognize this as a PDU we have seen before. return */
588                 return NULL;
589         }
590
591         fd_tvb_data=fd_head->tvb_data; 
592         /* loop over all partial fragments and free any tvbuffs */
593         for(fd=fd_head->next;fd;){
594                 fragment_item *tmp_fd;
595                 tmp_fd=fd->next;
596
597                 if (fd->tvb_data && !(fd->flags & FD_SUBSET_TVB))
598                         tvb_free(fd->tvb_data);
599                 g_slice_free(fragment_item, fd);
600                 fd=tmp_fd;
601         }
602         g_slice_free(fragment_head, fd_head);
603         g_hash_table_remove(table->fragment_table, key);
604
605         return fd_tvb_data;
606 }
607
608 /* This function is used to check if there is partial or completed reassembly state
609  * matching this packet. I.e. Is there reassembly going on or not for this packet?
610  */
611 fragment_head *
612 fragment_get(reassembly_table *table, const packet_info *pinfo,
613              const guint32 id, const void *data)
614 {
615         return lookup_fd_head(table, pinfo, id, data, NULL);
616 }
617
618 /* id *must* be the frame number for this to work! */
619 fragment_head *
620 fragment_get_reassembled(reassembly_table *table, const guint32 id)
621 {
622         fragment_head *fd_head;
623         reassembled_key key;
624
625         /* create key to search hash with */
626         key.frame = id;
627         key.id = id;
628         fd_head = (fragment_head *)g_hash_table_lookup(table->reassembled_table, &key);
629
630         return fd_head;
631 }
632
633 fragment_head *
634 fragment_get_reassembled_id(reassembly_table *table, const packet_info *pinfo,
635                             const guint32 id)
636 {
637         fragment_head *fd_head;
638         reassembled_key key;
639
640         /* create key to search hash with */
641         key.frame = pinfo->fd->num;
642         key.id = id;
643         fd_head = (fragment_head *)g_hash_table_lookup(table->reassembled_table, &key);
644
645         return fd_head;
646 }
647
648 /* To specify the offset for the fragment numbering, the first fragment is added with 0, and
649  * afterwards this offset is set. All additional calls to off_seq_check will calculate
650  * the number in sequence in regards to the offset */
651 void
652 fragment_add_seq_offset(reassembly_table *table, const packet_info *pinfo, const guint32 id,
653                 const void *data, const guint32 fragment_offset)
654 {
655         fragment_head *fd_head;
656
657         fd_head = lookup_fd_head(table, pinfo, id, data, NULL);
658         if (!fd_head)
659                 return;
660
661         /* Reseting the offset is not allowed */
662         if ( fd_head->fragment_nr_offset != 0 )
663                 return;
664
665         fd_head->fragment_nr_offset = fragment_offset;
666 }
667
668 /* This function can be used to explicitly set the total length (if known)
669  * for reassembly of a PDU.
670  * This is useful for reassembly of PDUs where one may have the total length specified
671  * in the first fragment instead of as for, say, IPv4 where a flag indicates which
672  * is the last fragment.
673  *
674  * Such protocols might fragment_add with a more_frags==TRUE for every fragment
675  * and just tell the reassembly engine the expected total length of the reassembled data
676  * using fragment_set_tot_len immediately after doing fragment_add for the first packet.
677  *
678  * Note that for FD_BLOCKSEQUENCE tot_len is the index for the tail fragment.
679  * i.e. since the block numbers start at 0, if we specify tot_len==2, that
680  * actually means we want to defragment 3 blocks, block 0, 1 and 2.
681  */
682 void
683 fragment_set_tot_len(reassembly_table *table, const packet_info *pinfo,
684                      const guint32 id, const void *data, const guint32 tot_len)
685 {
686         fragment_head *fd_head;
687         fragment_item *fd;
688         guint32        max_offset = 0;
689
690         fd_head = lookup_fd_head(table, pinfo, id, data, NULL);
691         if (!fd_head)
692                 return;
693
694         /* If we're setting a block sequence number, verify that it
695          * doesn't conflict with values set by existing fragments.
696          * XXX - eliminate this check?
697          */
698         fd = fd_head;
699         if (fd_head->flags & FD_BLOCKSEQUENCE) {
700                 while (fd) {
701                         if (fd->offset > max_offset) {
702                                 max_offset = fd->offset;
703                                 if (max_offset > tot_len) {
704                                         fd_head->error = "Bad total reassembly block count";
705                                         THROW_MESSAGE(ReassemblyError, fd_head->error);
706                                 }
707                         }
708                         fd = fd->next;
709                 }
710         }
711
712         if (fd_head->flags & FD_DEFRAGMENTED) {
713                 if (max_offset != tot_len) {
714                         fd_head->error = "Defragmented complete but total length not satisfied";
715                         THROW_MESSAGE(ReassemblyError, fd_head->error);
716                 }
717         }
718
719         /* We got this far so the value is sane. */
720         fd_head->datalen = tot_len;
721         fd_head->flags |= FD_DATALEN_SET;
722 }
723
724 guint32
725 fragment_get_tot_len(reassembly_table *table, const packet_info *pinfo,
726                      const guint32 id, const void *data)
727 {
728         fragment_head *fd_head;
729
730         fd_head = lookup_fd_head(table, pinfo, id, data, NULL);
731
732         if(fd_head){
733                 return fd_head->datalen;
734         }
735
736         return 0;
737 }
738
739
740 /* This function will set the partial reassembly flag for a fh.
741    When this function is called, the fh MUST already exist, i.e.
742    the fh MUST be created by the initial call to fragment_add() before
743    this function is called.
744    Also note that this function MUST be called to indicate a fh will be
745    extended (increase the already stored data)
746 */
747
748 void
749 fragment_set_partial_reassembly(reassembly_table *table,
750                                 const packet_info *pinfo, const guint32 id,
751                                 const void *data)
752 {
753         fragment_head *fd_head;
754
755         fd_head = lookup_fd_head(table, pinfo, id, data, NULL);
756
757         /*
758          * XXX - why not do all the stuff done early in "fragment_add_work()",
759          * turning off FD_DEFRAGMENTED and pointing the fragments' data
760          * pointers to the appropriate part of the already-reassembled
761          * data, and clearing the data length and "reassembled in" frame
762          * number, here?  We currently have a hack in the TCP dissector
763          * not to set the "reassembled in" value if the "partial reassembly"
764          * flag is set, so that in the first pass through the packets
765          * we don't falsely set a packet as reassembled in that packet
766          * if the dissector decided that even more reassembly was needed.
767          */
768         if(fd_head){
769                 fd_head->flags |= FD_PARTIAL_REASSEMBLY;
770         }
771 }
772
773 /*
774  * This function gets rid of an entry from a fragment table, given
775  * a pointer to the key for that entry.
776  *
777  * The key freeing routine will be called by g_hash_table_remove().
778  */
779 static void
780 fragment_unhash(reassembly_table *table, gpointer key)
781 {
782         /*
783          * Remove the entry from the fragment table.
784          */
785         g_hash_table_remove(table->fragment_table, key);
786 }
787
788 /*
789  * This function adds fragment_head structure to a reassembled-packet
790  * hash table, using the frame numbers of each of the frames from
791  * which it was reassembled as keys, and sets the "reassembled_in"
792  * frame number.
793  */
794 static void
795 fragment_reassembled(reassembly_table *table, fragment_head *fd_head,
796                      const packet_info *pinfo, const guint32 id)
797 {
798         reassembled_key *new_key;
799         fragment_item *fd;
800
801         if (fd_head->next == NULL) {
802                 /*
803                  * This was not fragmented, so there's no fragment
804                  * table; just hash it using the current frame number.
805                  */
806                 new_key = g_slice_new(reassembled_key);
807                 new_key->frame = pinfo->fd->num;
808                 new_key->id = id;
809                 g_hash_table_insert(table->reassembled_table, new_key, fd_head);
810         } else {
811                 /*
812                  * Hash it with the frame numbers for all the frames.
813                  */
814                 for (fd = fd_head->next; fd != NULL; fd = fd->next){
815                         new_key = g_slice_new(reassembled_key);
816                         new_key->frame = fd->frame;
817                         new_key->id = id;
818                         g_hash_table_insert(table->reassembled_table, new_key,
819                                 fd_head);
820                 }
821         }
822         fd_head->flags |= FD_DEFRAGMENTED;
823         fd_head->reassembled_in = pinfo->fd->num;
824 }
825
826 static void
827 LINK_FRAG(fragment_head *fd_head,fragment_item *fd)
828 {
829         fragment_item *fd_i;
830
831         /* add fragment to list, keep list sorted */
832         for(fd_i= fd_head; fd_i->next;fd_i=fd_i->next) {
833                 if (fd->offset < fd_i->next->offset )
834                         break;
835         }
836         fd->next=fd_i->next;
837         fd_i->next=fd;
838 }
839
840 /*
841  * This function adds a new fragment to the fragment hash table.
842  * If this is the first fragment seen for this datagram, a new entry
843  * is created in the hash table, otherwise this fragment is just added
844  * to the linked list of fragments for this packet.
845  * The list of fragments for a specific datagram is kept sorted for
846  * easier handling.
847  *
848  * Returns a pointer to the head of the fragment data list if we have all the
849  * fragments, NULL otherwise.
850  *
851  * This function assumes frag_offset being a byte offset into the defragment
852  * packet.
853  *
854  * 01-2002
855  * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be
856  * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set
857  * using fragment_set_partial_reassembly() before calling fragment_add
858  * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags
859  * are lowered when a new extension process is started.
860  */
861 static gboolean
862 fragment_add_work(fragment_head *fd_head, tvbuff_t *tvb, const int offset,
863                  const packet_info *pinfo, const guint32 frag_offset,
864                  const guint32 frag_data_len, const gboolean more_frags)
865 {
866         fragment_item *fd;
867         fragment_item *fd_i;
868         guint32 max, dfpos, fraglen;
869         tvbuff_t *old_tvb_data;
870         guint8 *data;
871
872         /* create new fd describing this fragment */
873         fd = g_slice_new(fragment_item);
874         fd->next = NULL;
875         fd->flags = 0;
876         fd->frame = pinfo->fd->num;
877         fd->offset = frag_offset;
878         fd->fragment_nr_offset = 0; /* will only be used with sequence */
879         fd->len  = frag_data_len;
880         fd->tvb_data = NULL;
881         fd->error = NULL;
882
883         /*
884          * Are we adding to an already-completed reassembly?
885          */
886         if (fd_head->flags & FD_DEFRAGMENTED) {
887                 /*
888                  * Yes.  Does this fragment go past the end of the results
889                  * of that reassembly?
890                  * XXX - shouldn't this be ">"?  If frag_offset + frag_data_len
891                  * == fd_head->datalen, this overlaps the end of the
892                  * reassembly, but doesn't go past it, right?
893                  */
894                 if (frag_offset + frag_data_len >= fd_head->datalen) {
895                         /*
896                          * Yes.  Have we been requested to continue reassembly?
897                          */
898                         if (fd_head->flags & FD_PARTIAL_REASSEMBLY) {
899                                 /*
900                                  * Yes.  Set flag in already empty fds &
901                                  * point old fds to malloc'ed data.
902                                  */
903                                 for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){
904                                         if( !fd_i->tvb_data ) {
905                                                 fd_i->tvb_data = tvb_new_subset_remaining(fd_head->tvb_data, fd_i->offset);
906                                                 fd_i->flags |= FD_SUBSET_TVB;
907                                         }
908                                         fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
909                                 }
910                                 fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET);
911                                 fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
912                                 fd_head->datalen=0;
913                                 fd_head->reassembled_in=0;
914                         } else {
915                                 /*
916                                  * No.  Bail out since we have no idea what to
917                                  * do with this fragment (and if we keep going
918                                  * we'll run past the end of a buffer sooner
919                                  * or later).
920                                  */
921                                 g_slice_free(fragment_item, fd);
922                                  
923                                 /*
924                                  * This is an attempt to add a fragment to a
925                                  * reassembly that had already completed.
926                                  * If it had no error, we don't want to
927                                  * mark it with an error, and if it had an
928                                  * error, we don't want to overwrite it, so
929                                  * we don't set fd_head->error.
930                                  */
931                                 if (frag_offset >= fd_head->datalen) {
932                                         /*
933                                          * The fragment starts past the end
934                                          * of the reassembled data.
935                                          */
936                                         THROW_MESSAGE(ReassemblyError, "New fragment past old data limits");
937                                 } else {
938                                         /*
939                                          * The fragment starts before the end
940                                          * of the reassembled data, but
941                                          * runs past the end.  That could
942                                          * just be a retransmission.
943                                          */
944                                         THROW_MESSAGE(ReassemblyError, "New fragment overlaps old data (retransmission?)");
945                                 }
946                         }
947                 } else {
948                         /*
949                          * No.  That means it still overlaps that, so report
950                          * this as a problem, possibly a retransmission.
951                          */
952                         g_slice_free(fragment_item, fd);
953                         THROW_MESSAGE(ReassemblyError, "New fragment overlaps old data (retransmission?)");
954                 }
955         }
956
957         /* Do this after we may have bailed out (above) so that we don't leave
958          * fd_head->frame in a bad state if we do */
959         if (fd->frame > fd_head->frame)
960                 fd_head->frame = fd->frame;
961
962         if (!more_frags) {
963                 /*
964                  * This is the tail fragment in the sequence.
965                  */
966                 if (fd_head->flags & FD_DATALEN_SET) {
967                         /* ok we have already seen other tails for this packet
968                          * it might be a duplicate.
969                          */
970                         if (fd_head->datalen != (fd->offset + fd->len) ){
971                                 /* Oops, this tail indicates a different packet
972                                  * len than the previous ones. Something's wrong.
973                                  */
974                                 fd->flags          |= FD_MULTIPLETAILS;
975                                 fd_head->flags |= FD_MULTIPLETAILS;
976                         }
977                 } else {
978                         /* This was the first tail fragment; now we know
979                          * what the length of the packet should be.
980                          */
981                         fd_head->datalen = fd->offset + fd->len;
982                         fd_head->flags |= FD_DATALEN_SET;
983                 }
984         }
985
986
987
988         /* If the packet is already defragmented, this MUST be an overlap.
989          * The entire defragmented packet is in fd_head->data.
990          * Even if we have previously defragmented this packet, we still
991          * check it. Someone might play overlap and TTL games.
992          */
993         if (fd_head->flags & FD_DEFRAGMENTED) {
994                 guint32 end_offset = fd->offset + fd->len;
995                 fd->flags          |= FD_OVERLAP;
996                 fd_head->flags |= FD_OVERLAP;
997                 /* make sure it's not too long */
998                 if (end_offset > fd_head->datalen || end_offset < fd->offset || end_offset < fd->len) {
999                         fd->flags          |= FD_TOOLONGFRAGMENT;
1000                         fd_head->flags |= FD_TOOLONGFRAGMENT;
1001                 }
1002                 /* make sure it doesn't conflict with previous data */
1003                 else if ( tvb_memeql(fd_head->tvb_data, fd->offset,
1004                         tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
1005                         fd->flags          |= FD_OVERLAPCONFLICT;
1006                         fd_head->flags |= FD_OVERLAPCONFLICT;
1007                 }
1008                 /* it was just an overlap, link it and return */
1009                 LINK_FRAG(fd_head,fd);
1010                 return TRUE;
1011         }
1012
1013
1014
1015         /* If we have reached this point, the packet is not defragmented yet.
1016          * Save all payload in a buffer until we can defragment.
1017          * XXX - what if we didn't capture the entire fragment due
1018          * to a too-short snapshot length?
1019          */
1020         fd->tvb_data = tvb_clone_offset_len(tvb, offset, fd->len);
1021         LINK_FRAG(fd_head,fd);
1022
1023
1024         if( !(fd_head->flags & FD_DATALEN_SET) ){
1025                 /* if we dont know the datalen, there are still missing
1026                  * packets. Cheaper than the check below.
1027                  */
1028                 return FALSE;
1029         }
1030
1031
1032         /*
1033          * Check if we have received the entire fragment.
1034          * This is easy since the list is sorted and the head is faked.
1035          *
1036          * First, we compute the amount of contiguous data that's
1037          * available.  (The check for fd_i->offset <= max rules out
1038          * fragments that don't start before or at the end of the
1039          * previous fragment, i.e. fragments that have a gap between
1040          * them and the previous fragment.)
1041          */
1042         max = 0;
1043         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1044                 if ( ((fd_i->offset)<=max) &&
1045                         ((fd_i->offset+fd_i->len)>max) ){
1046                         max = fd_i->offset+fd_i->len;
1047                 }
1048         }
1049
1050         if (max < (fd_head->datalen)) {
1051                 /*
1052                  * The amount of contiguous data we have is less than the
1053                  * amount of data we're trying to reassemble, so we haven't
1054                  * received all packets yet.
1055                  */
1056                 return FALSE;
1057         }
1058
1059         /* we have received an entire packet, defragment it and
1060          * free all fragments
1061          */
1062         /* store old data just in case */
1063         old_tvb_data=fd_head->tvb_data;
1064         data = (guint8 *) g_malloc(fd_head->datalen);
1065         fd_head->tvb_data = tvb_new_real_data(data, fd_head->datalen, fd_head->datalen);
1066         tvb_set_free_cb(fd_head->tvb_data, g_free);
1067
1068         /* add all data fragments */
1069         for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) {
1070                 if (fd_i->len) {
1071                         /*
1072                          * The loop above that calculates max also
1073                          * ensures that the only gaps that exist here
1074                          * are ones where a fragment starts past the
1075                          * end of the reassembled datagram, and there's
1076                          * a gap between the previous fragment and
1077                          * that fragment.
1078                          *
1079                          * A "DESEGMENT_UNTIL_FIN" was involved wherein the
1080                          * FIN packet had an offset less than the highest
1081                          * fragment offset seen. [Seen from a fuzz-test:
1082                          * bug #2470]).
1083                          *
1084                          * Note that the "overlap" compare must only be
1085                          * done for fragments with (offset+len) <= fd_head->datalen
1086                          * and thus within the newly g_malloc'd buffer.
1087                          */
1088                         if (fd_i->offset + fd_i->len > dfpos) {
1089                                 if (fd_i->offset >= fd_head->datalen) {
1090                                         /*
1091                                          * Fragment starts after the end
1092                                          * of the reassembled packet.
1093                                          *
1094                                          * This can happen if the length was
1095                                          * set after the offending fragment
1096                                          * was added to the reassembly.
1097                                          *
1098                                          * Flag this fragment, but don't
1099                                          * try to extract any data from
1100                                          * it, as there's no place to put
1101                                          * it.
1102                                          *
1103                                          * XXX - add different flag value
1104                                          * for this.
1105                                          */
1106                                         fd_i->flags    |= FD_TOOLONGFRAGMENT;
1107                                         fd_head->flags |= FD_TOOLONGFRAGMENT;
1108                                 } else if (dfpos < fd_i->offset) {
1109                                         /*
1110                                          * XXX - can this happen?  We've
1111                                          * already rejected fragments that
1112                                          * start past the end of the
1113                                          * reassembled datagram, and
1114                                          * the loop that calculated max
1115                                          * should have ruled out gaps,
1116                                          * but could fd_i->offset +
1117                                          * fd_i->len overflow?
1118                                          */
1119                                         fd_head->error = "dfpos < offset";
1120                                 } else if (dfpos - fd_i->offset > fd_i->len)
1121                                         fd_head->error = "dfpos - offset > len";
1122                                 else if (!fd_head->tvb_data)
1123                                         fd_head->error = "no data";
1124                                 else {
1125                                         fraglen = fd_i->len;
1126                                         if (fd_i->offset + fraglen > fd_head->datalen) {
1127                                                 /*
1128                                                  * Fragment goes past the end
1129                                                  * of the packet, as indicated
1130                                                  * by the last fragment.
1131                                                  *
1132                                                  * This can happen if the
1133                                                  * length was set after the
1134                                                  * offending fragment was
1135                                                  * added to the reassembly.
1136                                                  *
1137                                                  * Mark it as such, and only
1138                                                  * copy from it what fits in
1139                                                  * the packet.
1140                                                  */
1141                                                 fd_i->flags    |= FD_TOOLONGFRAGMENT;
1142                                                 fd_head->flags |= FD_TOOLONGFRAGMENT;
1143                                                 fraglen = fd_head->datalen - fd_i->offset;
1144                                         }
1145                                         if (fd_i->offset < dfpos) {
1146                                                 guint32 cmp_len = MIN(fd_i->len,(dfpos-fd_i->offset));
1147
1148                                                 fd_i->flags    |= FD_OVERLAP;
1149                                                 fd_head->flags |= FD_OVERLAP;
1150                                                 if ( memcmp(data + fd_i->offset,
1151                                                                 tvb_get_ptr(fd_i->tvb_data, 0, cmp_len),
1152                                                                 cmp_len)
1153                                                                  ) {
1154                                                         fd_i->flags    |= FD_OVERLAPCONFLICT;
1155                                                         fd_head->flags |= FD_OVERLAPCONFLICT;
1156                                                 }
1157                                         }
1158                                         if (fraglen < dfpos - fd_i->offset) {
1159                                                 /*
1160                                                  * XXX - can this happen?
1161                                                  */
1162                                                 fd_head->error = "fraglen < dfpos - offset";
1163                                         } else {
1164                                                 memcpy(data+dfpos,
1165                                                         tvb_get_ptr(fd_i->tvb_data, (dfpos-fd_i->offset), fraglen-(dfpos-fd_i->offset)),
1166                                                         fraglen-(dfpos-fd_i->offset));
1167                                                 dfpos=MAX(dfpos, (fd_i->offset + fraglen));
1168                                         }
1169                                 }
1170                         } else {
1171                                 if (fd_i->offset + fd_i->len < fd_i->offset) {
1172                                         /* Integer overflow? */
1173                                         fd_head->error = "offset + len < offset";
1174                                 }
1175                         }
1176
1177                         if (fd_i->flags & FD_SUBSET_TVB)
1178                                 fd_i->flags &= ~FD_SUBSET_TVB;
1179                         else if (fd_i->tvb_data)
1180                                 tvb_free(fd_i->tvb_data);
1181
1182                         fd_i->tvb_data=NULL;
1183                 }
1184         }
1185
1186         if (old_tvb_data)
1187                 tvb_add_to_chain(tvb, old_tvb_data);
1188         /* mark this packet as defragmented.
1189            allows us to skip any trailing fragments */
1190         fd_head->flags |= FD_DEFRAGMENTED;
1191         fd_head->reassembled_in=pinfo->fd->num;
1192
1193         /* we don't throw until here to avoid leaking old_data and others */
1194         if (fd_head->error) {
1195                 THROW_MESSAGE(ReassemblyError, fd_head->error);
1196         }
1197
1198         return TRUE;
1199 }
1200
1201 static fragment_head *
1202 fragment_add_common(reassembly_table *table, tvbuff_t *tvb, const int offset,
1203                     const packet_info *pinfo, const guint32 id,
1204                     const void *data, const guint32 frag_offset,
1205                     const guint32 frag_data_len, const gboolean more_frags,
1206                     const gboolean check_already_added)
1207 {
1208         fragment_head *fd_head;
1209         fragment_item *fd_item;
1210         gboolean already_added;
1211
1212
1213         /* dissector shouldn't give us garbage tvb info */
1214         DISSECTOR_ASSERT(tvb_bytes_exist(tvb, offset, frag_data_len));
1215
1216         fd_head = lookup_fd_head(table, pinfo, id, data, NULL);
1217
1218 #if 0
1219         /* debug output of associated fragments. */
1220         /* leave it here for future debugging sessions */
1221         if(strcmp(pinfo->current_proto, "DCERPC") == 0) {
1222                 printf("proto:%s num:%u id:%u offset:%u len:%u more:%u visited:%u\n",
1223                         pinfo->current_proto, pinfo->fd->num, id, frag_offset, frag_data_len, more_frags, pinfo->fd->flags.visited);
1224                 if(fd_head != NULL) {
1225                         for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){
1226                                 printf("fd_frame:%u fd_offset:%u len:%u datalen:%u\n",
1227                                         fd_item->frame, fd_item->offset, fd_item->len, fd_item->datalen);
1228                         }
1229                 }
1230         }
1231 #endif
1232
1233         /*
1234          * Is this the first pass through the capture?
1235          */
1236         if (!pinfo->fd->flags.visited) {
1237                 /*
1238                  * Yes, so we could be doing reassembly.  If
1239                  * "check_already_added" is true, and fd_head is non-null,
1240                  * meaning that this fragment would be added to an
1241                  * in-progress reassembly, check if we have seen this
1242                  * fragment before, i.e., if we have already added it to
1243                  * that reassembly. That can be true even on the first pass
1244                  * since we sometimes might call a subdissector multiple
1245                  * times.
1246                  *
1247                  * We check both the frame number and the fragment offset,
1248                  * so that we support multiple fragments from the same
1249                  * frame being added to the same reassembled PDU.
1250                  */
1251                 if (check_already_added && fd_head != NULL) {
1252                         /*
1253                          * fd_head->frame is the maximum of the frame
1254                          * numbers of all the fragments added to this
1255                          * reassembly; if this frame is later than that
1256                          * frame, we know it hasn't been added yet.
1257                          */
1258                         if (pinfo->fd->num <= fd_head->frame) {
1259                                 already_added = FALSE;
1260                                 /*
1261                                  * The first item in the reassembly list
1262                                  * is not a fragment, it's a data structure
1263                                  * for the reassembled packet, so we
1264                                  * start checking with the next item.
1265                                  */
1266                                 for (fd_item = fd_head->next; fd_item;
1267                                     fd_item = fd_item->next) {
1268                                         if (pinfo->fd->num == fd_item->frame &&
1269                                             frag_offset == fd_item->offset) {
1270                                                 already_added = TRUE;
1271                                                 break;
1272                                         }
1273                                 }
1274                                 if (already_added) {
1275                                         /*
1276                                          * Have we already finished
1277                                          * reassembling?
1278                                          */
1279                                         if (fd_head->flags & FD_DEFRAGMENTED) {
1280                                                 /*
1281                                                  * Yes.
1282                                                  * XXX - can this ever happen?
1283                                                  */
1284                                                 THROW_MESSAGE(ReassemblyError,
1285                                                     "Frame already added in first pass");
1286                                         } else {
1287                                                 /*
1288                                                  * No.
1289                                                  */
1290                                                 return NULL;
1291                                         }
1292                                 }
1293                         }
1294                 }
1295         } else {
1296                 /*
1297                  * No, so we've already done all the reassembly and added
1298                  * all the fragments.  Do we have a reassembly and, if so,
1299                  * have we finished reassembling?
1300                  */
1301                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
1302                         /*
1303                          * Yes.  This is probably being done after the
1304                          * first pass, and we've already done the work
1305                          * on the first pass.
1306                          *
1307                          * If the reassembly got a fatal error, throw that
1308                          * error again.
1309                          */
1310                         if (fd_head->error)
1311                                 THROW_MESSAGE(ReassemblyError, fd_head->error);
1312
1313                         /*
1314                          * Is it later in the capture than all of the
1315                          * fragments in the reassembly?
1316                          */
1317                         if (pinfo->fd->num > fd_head->frame) {
1318                                 /*
1319                                  * Yes, so report this as a problem,
1320                                  * possibly a retransmission.
1321                                  */
1322                                 THROW_MESSAGE(ReassemblyError, "New fragment overlaps old data (retransmission?)");
1323                         }
1324
1325                         /*
1326                          * Does this fragment go past the end of the
1327                          * results of that reassembly?
1328                          */
1329                         if (frag_offset + frag_data_len > fd_head->datalen) {
1330                                 /*
1331                                  * Yes.
1332                                  */
1333                                 if (frag_offset >= fd_head->datalen) {
1334                                         /*
1335                                          * The fragment starts past the
1336                                          * end of the reassembled data.
1337                                          */
1338                                         THROW_MESSAGE(ReassemblyError, "New fragment past old data limits");
1339                                 } else {
1340                                         /*
1341                                          * The fragment starts before the end
1342                                          * of the reassembled data, but
1343                                          * runs past the end.  That could
1344                                          * just be a retransmission.
1345                                          */
1346                                         THROW_MESSAGE(ReassemblyError, "New fragment overlaps old data (retransmission?)");
1347                                 }
1348                         }
1349
1350                         return fd_head;
1351                 } else {
1352                         /*
1353                          * No.
1354                          */
1355                         return NULL;
1356                 }
1357         }
1358
1359         if (fd_head==NULL){
1360                 /* not found, this must be the first snooped fragment for this
1361                  * packet. Create list-head.
1362                  */
1363                 fd_head = new_head(0);
1364
1365                 /*
1366                  * Insert it into the hash table.
1367                  */
1368                 insert_fd_head(table, fd_head, pinfo, id, data);
1369         }
1370
1371         if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset,
1372                 frag_data_len, more_frags)) {
1373                 /*
1374                  * Reassembly is complete.
1375                  */
1376                 return fd_head;
1377         } else {
1378                 /*
1379                  * Reassembly isn't complete.
1380                  */
1381                 return NULL;
1382         }
1383 }
1384
1385 fragment_head *
1386 fragment_add(reassembly_table *table, tvbuff_t *tvb, const int offset,
1387              const packet_info *pinfo, const guint32 id, const void *data,
1388              const guint32 frag_offset, const guint32 frag_data_len,
1389              const gboolean more_frags)
1390 {
1391         return fragment_add_common(table, tvb, offset, pinfo, id, data,
1392                 frag_offset, frag_data_len, more_frags, TRUE);
1393 }
1394
1395 /*
1396  * For use when you can have multiple fragments in the same frame added
1397  * to the same reassembled PDU, e.g. with ONC RPC-over-TCP.
1398  */
1399 fragment_head *
1400 fragment_add_multiple_ok(reassembly_table *table, tvbuff_t *tvb,
1401                          const int offset, const packet_info *pinfo,
1402                          const guint32 id, const void *data,
1403                          const guint32 frag_offset,
1404                          const guint32 frag_data_len, const gboolean more_frags)
1405 {
1406         return fragment_add_common(table, tvb, offset, pinfo, id, data,
1407                 frag_offset, frag_data_len, more_frags, FALSE);
1408 }
1409
1410 fragment_head *
1411 fragment_add_check(reassembly_table *table, tvbuff_t *tvb, const int offset,
1412                    const packet_info *pinfo, const guint32 id,
1413                    const void *data, const guint32 frag_offset,
1414                    const guint32 frag_data_len, const gboolean more_frags)
1415 {
1416         reassembled_key reass_key;
1417         fragment_head *fd_head;
1418         gpointer orig_key;
1419
1420         /*
1421          * If this isn't the first pass, look for this frame in the table
1422          * of reassembled packets.
1423          */
1424         if (pinfo->fd->flags.visited) {
1425                 reass_key.frame = pinfo->fd->num;
1426                 reass_key.id = id;
1427                 return (fragment_head *)g_hash_table_lookup(table->reassembled_table, &reass_key);
1428         }
1429
1430         /* Looks up a key in the GHashTable, returning the original key and the associated value
1431          * and a gboolean which is TRUE if the key was found. This is useful if you need to free
1432          * the memory allocated for the original key, for example before calling g_hash_table_remove()
1433          */
1434         fd_head = lookup_fd_head(table, pinfo, id, data, &orig_key);
1435         if (fd_head == NULL) {
1436                 /* not found, this must be the first snooped fragment for this
1437                  * packet. Create list-head.
1438                  */
1439                 fd_head = new_head(0);
1440
1441                 /*
1442                  * Save the key, for unhashing it later.
1443                  */
1444                 orig_key = insert_fd_head(table, fd_head, pinfo, id, data);
1445         }
1446
1447         /*
1448          * If this is a short frame, then we can't, and don't, do
1449          * reassembly on it.  We just give up.
1450          */
1451         if (tvb_reported_length(tvb) > tvb_length(tvb))
1452                 return NULL;
1453
1454         if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset,
1455                 frag_data_len, more_frags)) {
1456                 /*
1457                  * Reassembly is complete.
1458                  * Remove this from the table of in-progress
1459                  * reassemblies, add it to the table of
1460                  * reassembled packets, and return it.
1461                  */
1462
1463                 /*
1464                  * Remove this from the table of in-progress reassemblies,
1465                  * and free up any memory used for it in that table.
1466                  */
1467                 fragment_unhash(table, orig_key);
1468
1469                 /*
1470                  * Add this item to the table of reassembled packets.
1471                  */
1472                 fragment_reassembled(table, fd_head, pinfo, id);
1473                 return fd_head;
1474         } else {
1475                 /*
1476                  * Reassembly isn't complete.
1477                  */
1478                 return NULL;
1479         }
1480 }
1481
1482 static void
1483 fragment_defragment_and_free (fragment_head *fd_head, const packet_info *pinfo)
1484 {
1485         fragment_item *fd_i = NULL;
1486         fragment_item *last_fd = NULL;
1487         guint32  dfpos = 0, size = 0;
1488         tvbuff_t *old_tvb_data = NULL;
1489         guint8 *data;
1490
1491         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1492                 if(!last_fd || last_fd->offset!=fd_i->offset){
1493                         size+=fd_i->len;
1494                 }
1495                 last_fd=fd_i;
1496         }
1497
1498         /* store old data in case the fd_i->data pointers refer to it */
1499         old_tvb_data=fd_head->tvb_data;
1500         data = (guint8 *) g_malloc(size);
1501         fd_head->tvb_data = tvb_new_real_data(data, size, size);
1502         tvb_set_free_cb(fd_head->tvb_data, g_free);
1503         fd_head->len = size;            /* record size for caller       */
1504
1505         /* add all data fragments */
1506         last_fd=NULL;
1507         for (fd_i=fd_head->next; fd_i; fd_i=fd_i->next) {
1508                 if (fd_i->len) {
1509                         if(!last_fd || last_fd->offset != fd_i->offset) {
1510                                 /* First fragment or in-sequence fragment */
1511                                 memcpy(data+dfpos, tvb_get_ptr(fd_i->tvb_data, 0, fd_i->len), fd_i->len);
1512                                 dfpos += fd_i->len;
1513                         } else {
1514                                 /* duplicate/retransmission/overlap */
1515                                 fd_i->flags    |= FD_OVERLAP;
1516                                 fd_head->flags |= FD_OVERLAP;
1517                                 if(last_fd->len != fd_i->len
1518                                    || tvb_memeql(last_fd->tvb_data, 0, tvb_get_ptr(fd_i->tvb_data, 0, last_fd->len), last_fd->len) ) {
1519                                         fd_i->flags    |= FD_OVERLAPCONFLICT;
1520                                         fd_head->flags |= FD_OVERLAPCONFLICT;
1521                                 }
1522                         }
1523                 }
1524                 last_fd=fd_i;
1525         }
1526
1527         /* we have defragmented the pdu, now free all fragments*/
1528         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1529                 if (fd_i->flags & FD_SUBSET_TVB)
1530                         fd_i->flags &= ~FD_SUBSET_TVB;
1531                 else if (fd_i->tvb_data)
1532                         tvb_free(fd_i->tvb_data);
1533                 fd_i->tvb_data=NULL;
1534         }
1535         if (old_tvb_data)
1536                 tvb_free(old_tvb_data);
1537
1538         /* mark this packet as defragmented.
1539          * allows us to skip any trailing fragments.
1540          */
1541         fd_head->flags |= FD_DEFRAGMENTED;
1542         fd_head->reassembled_in=pinfo->fd->num;
1543 }
1544
1545 /*
1546  * This function adds a new fragment to the entry for a reassembly
1547  * operation.
1548  *
1549  * The list of fragments for a specific datagram is kept sorted for
1550  * easier handling.
1551  *
1552  * Returns TRUE if we have all the fragments, FALSE otherwise.
1553  *
1554  * This function assumes frag_number being a block sequence number.
1555  * The bsn for the first block is 0.
1556  */
1557 static gboolean
1558 fragment_add_seq_work(fragment_head *fd_head, tvbuff_t *tvb, const int offset,
1559                  const packet_info *pinfo, const guint32 frag_number,
1560                  const guint32 frag_data_len, const gboolean more_frags)
1561 {
1562         fragment_item *fd;
1563         fragment_item *fd_i;
1564         fragment_item *last_fd;
1565         guint32 max, dfpos;
1566         guint32 frag_number_work;
1567
1568         /* Enables the use of fragment sequence numbers, which do not start with 0 */
1569         frag_number_work = frag_number;
1570         if ( fd_head->fragment_nr_offset != 0 )
1571                 if ( frag_number_work >= fd_head->fragment_nr_offset )
1572                         frag_number_work = frag_number - fd_head->fragment_nr_offset;
1573
1574         /* if the partial reassembly flag has been set, and we are extending
1575          * the pdu, un-reassemble the pdu. This means pointing old fds to malloc'ed data.
1576          */
1577         if(fd_head->flags & FD_DEFRAGMENTED && frag_number_work >= fd_head->datalen &&
1578                 fd_head->flags & FD_PARTIAL_REASSEMBLY){
1579                 guint32 lastdfpos = 0;
1580                 dfpos = 0;
1581                 for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){
1582                         if( !fd_i->tvb_data ) {
1583                                 if( fd_i->flags & FD_OVERLAP ) {
1584                                         /* this is a duplicate of the previous
1585                                          * fragment. */
1586                                         fd_i->tvb_data = tvb_new_subset_remaining(fd_head->tvb_data, lastdfpos);
1587                                 } else {
1588                                         fd_i->tvb_data = tvb_new_subset_remaining(fd_head->tvb_data, dfpos);
1589                                         lastdfpos = dfpos;
1590                                         dfpos += fd_i->len;
1591                                 }
1592                                 fd_i->flags |= FD_SUBSET_TVB;
1593                         }
1594                         fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
1595                 }
1596                 fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET);
1597                 fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
1598                 fd_head->datalen=0;
1599                 fd_head->reassembled_in=0;
1600         }
1601
1602
1603         /* create new fd describing this fragment */
1604         fd = g_slice_new(fragment_item);
1605         fd->next = NULL;
1606         fd->flags = 0;
1607         fd->frame = pinfo->fd->num;
1608         fd->offset = frag_number_work;
1609         fd->len  = frag_data_len;
1610         fd->tvb_data = NULL;
1611         fd->error = NULL;
1612
1613         if (!more_frags) {
1614                 /*
1615                  * This is the tail fragment in the sequence.
1616                  */
1617                 if (fd_head->flags&FD_DATALEN_SET) {
1618                         /* ok we have already seen other tails for this packet
1619                          * it might be a duplicate.
1620                          */
1621                         if (fd_head->datalen != fd->offset ){
1622                                 /* Oops, this tail indicates a different packet
1623                                  * len than the previous ones. Something's wrong.
1624                                  */
1625                                 fd->flags       |= FD_MULTIPLETAILS;
1626                                 fd_head->flags  |= FD_MULTIPLETAILS;
1627                         }
1628                 } else {
1629                         /* this was the first tail fragment, now we know the
1630                          * sequence number of that fragment (which is NOT
1631                          * the length of the packet!)
1632                          */
1633                         fd_head->datalen = fd->offset;
1634                         fd_head->flags |= FD_DATALEN_SET;
1635                 }
1636         }
1637
1638         /* If the packet is already defragmented, this MUST be an overlap.
1639          * The entire defragmented packet is in fd_head->data
1640          * Even if we have previously defragmented this packet, we still check
1641          * check it. Someone might play overlap and TTL games.
1642          */
1643         if (fd_head->flags & FD_DEFRAGMENTED) {
1644                 fd->flags       |= FD_OVERLAP;
1645                 fd_head->flags  |= FD_OVERLAP;
1646
1647                 /* make sure it's not past the end */
1648                 if (fd->offset > fd_head->datalen) {
1649                         /* new fragment comes after the end */
1650                         fd->flags       |= FD_TOOLONGFRAGMENT;
1651                         fd_head->flags  |= FD_TOOLONGFRAGMENT;
1652                         LINK_FRAG(fd_head,fd);
1653                         return TRUE;
1654                 }
1655                 /* make sure it doesn't conflict with previous data */
1656                 dfpos=0;
1657                 last_fd=NULL;
1658                 for (fd_i=fd_head->next;fd_i && (fd_i->offset!=fd->offset);fd_i=fd_i->next) {
1659                   if (!last_fd || last_fd->offset!=fd_i->offset){
1660                         dfpos += fd_i->len;
1661                   }
1662                   last_fd=fd_i;
1663                 }
1664                 if(fd_i){
1665                         /* new fragment overlaps existing fragment */
1666                         if(fd_i->len!=fd->len){
1667                                 /*
1668                                  * They have different lengths; this
1669                                  * is definitely a conflict.
1670                                  */
1671                                 fd->flags       |= FD_OVERLAPCONFLICT;
1672                                 fd_head->flags  |= FD_OVERLAPCONFLICT;
1673                                 LINK_FRAG(fd_head,fd);
1674                                 return TRUE;
1675                         }
1676                         DISSECTOR_ASSERT(fd_head->len >= dfpos + fd->len);
1677                         if (tvb_memeql(fd_head->tvb_data, dfpos,
1678                                 tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
1679                                 /*
1680                                  * They have the same length, but the
1681                                  * data isn't the same.
1682                                  */
1683                                 fd->flags       |= FD_OVERLAPCONFLICT;
1684                                 fd_head->flags  |= FD_OVERLAPCONFLICT;
1685                                 LINK_FRAG(fd_head,fd);
1686                                 return TRUE;
1687                         }
1688                         /* it was just an overlap, link it and return */
1689                         LINK_FRAG(fd_head,fd);
1690                         return TRUE;
1691                 } else {
1692                         /*
1693                          * New fragment doesn't overlap an existing
1694                          * fragment - there was presumably a gap in
1695                          * the sequence number space.
1696                          *
1697                          * XXX - what should we do here?  Is it always
1698                          * the case that there are no gaps, or are there
1699                          * protcols using sequence numbers where there
1700                          * can be gaps?
1701                          *
1702                          * If the former, the check below for having
1703                          * received all the fragments should check for
1704                          * holes in the sequence number space and for the
1705                          * first sequence number being 0.  If we do that,
1706                          * the only way we can get here is if this fragment
1707                          * is past the end of the sequence number space -
1708                          * but the check for "fd->offset > fd_head->datalen"
1709                          * would have caught that above, so it can't happen.
1710                          *
1711                          * If the latter, we don't have a good way of
1712                          * knowing whether reassembly is complete if we
1713                          * get packet out of order such that the "last"
1714                          * fragment doesn't show up last - but, unless
1715                          * in-order reliable delivery of fragments is
1716                          * guaranteed, an implementation of the protocol
1717                          * has no way of knowing whether reassembly is
1718                          * complete, either.
1719                          *
1720                          * For now, we just link the fragment in and
1721                          * return.
1722                          */
1723                         LINK_FRAG(fd_head,fd);
1724                         return TRUE;
1725                 }
1726         }
1727
1728         /* If we have reached this point, the packet is not defragmented yet.
1729          * Save all payload in a buffer until we can defragment.
1730          * XXX - what if we didn't capture the entire fragment due
1731          * to a too-short snapshot length?
1732          */
1733         /* check len, there may be a fragment with 0 len, that is actually the tail */
1734         if (fd->len) {
1735                 fd->tvb_data = tvb_clone_offset_len(tvb, offset, fd->len);
1736         }
1737         LINK_FRAG(fd_head,fd);
1738
1739
1740         if( !(fd_head->flags & FD_DATALEN_SET) ){
1741                 /* if we dont know the sequence number of the last fragment,
1742                  * there are definitely still missing packets. Cheaper than
1743                  * the check below.
1744                  */
1745                 return FALSE;
1746         }
1747
1748
1749         /* check if we have received the entire fragment
1750          * this is easy since the list is sorted and the head is faked.
1751          * common case the whole list is scanned.
1752          */
1753         max = 0;
1754         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1755           if ( fd_i->offset==max ){
1756                 max++;
1757           }
1758         }
1759         /* max will now be datalen+1 if all fragments have been seen */
1760
1761         if (max <= fd_head->datalen) {
1762                 /* we have not received all packets yet */
1763                 return FALSE;
1764         }
1765
1766
1767         if (max > (fd_head->datalen+1)) {
1768                 /* oops, too long fragment detected */
1769                 fd->flags       |= FD_TOOLONGFRAGMENT;
1770                 fd_head->flags  |= FD_TOOLONGFRAGMENT;
1771         }
1772
1773
1774         /* we have received an entire packet, defragment it and
1775          * free all fragments
1776          */
1777         fragment_defragment_and_free(fd_head, pinfo);
1778
1779         return TRUE;
1780 }
1781
1782 /*
1783  * This function adds a new fragment to the fragment hash table.
1784  * If this is the first fragment seen for this datagram, a new entry
1785  * is created in the hash table, otherwise this fragment is just added
1786  * to the linked list of fragments for this packet.
1787  *
1788  * Returns a pointer to the head of the fragment data list if we have all the
1789  * fragments, NULL otherwise.
1790  *
1791  * This function assumes frag_number being a block sequence number.
1792  * The bsn for the first block is 0.
1793  */
1794 static fragment_head *
1795 fragment_add_seq_common(reassembly_table *table, tvbuff_t *tvb,
1796                         const int offset, const packet_info *pinfo,
1797                         const guint32 id, const void *data, 
1798                         guint32 frag_number, const guint32 frag_data_len,
1799                         const gboolean more_frags, const guint32 flags,
1800                         gpointer *orig_keyp)
1801 {
1802         fragment_head *fd_head;
1803         gpointer orig_key;
1804
1805         fd_head = lookup_fd_head(table, pinfo, id, data, &orig_key);
1806
1807         /* have we already seen this frame ?*/
1808         if (pinfo->fd->flags.visited) {
1809                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
1810                         if (orig_keyp != NULL)
1811                                 *orig_keyp = orig_key;
1812                         return fd_head;
1813                 } else {
1814                         return NULL;
1815                 }
1816         }
1817
1818         if (fd_head==NULL){
1819                 /* not found, this must be the first snooped fragment for this
1820                  * packet. Create list-head.
1821                  */
1822                 fd_head= new_head(FD_BLOCKSEQUENCE);
1823
1824                 if((flags & (REASSEMBLE_FLAGS_NO_FRAG_NUMBER|REASSEMBLE_FLAGS_802_11_HACK))
1825                    && !more_frags) {
1826                         /*
1827                          * This is the last fragment for this packet, and
1828                          * is the only one we've seen.
1829                          *
1830                          * Either we don't have sequence numbers, in which
1831                          * case we assume this is the first fragment for
1832                          * this packet, or we're doing special 802.11
1833                          * processing, in which case we assume it's one
1834                          * of those reassembled packets with a non-zero
1835                          * fragment number (see packet-80211.c); just
1836                          * return a pointer to the head of the list;
1837                          * fragment_add_seq_check will then add it to the table
1838                          * of reassembled packets.
1839                          */
1840                         if (orig_keyp != NULL)
1841                                 *orig_keyp = NULL;
1842                         fd_head->reassembled_in=pinfo->fd->num;
1843                         return fd_head;
1844                 }
1845
1846                 orig_key = insert_fd_head(table, fd_head, pinfo, id, data);
1847                 if (orig_keyp != NULL)
1848                         *orig_keyp = orig_key;
1849
1850                 /*
1851                  * If we weren't given an initial fragment number,
1852                  * make it 0.
1853                  */
1854                 if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER)
1855                         frag_number = 0;
1856         } else {
1857                 if (orig_keyp != NULL)
1858                         *orig_keyp = orig_key;
1859
1860                 if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) {
1861                         fragment_item *fd;
1862                         /*
1863                          * If we weren't given an initial fragment number,
1864                          * use the next expected fragment number as the fragment
1865                          * number for this fragment.
1866                          */
1867                         for (fd = fd_head; fd != NULL; fd = fd->next) {
1868                                 if (fd->next == NULL)
1869                                         frag_number = fd->offset + 1;
1870                         }
1871                 }
1872         }
1873
1874         /*
1875          * XXX I've copied this over from the old separate
1876          * fragment_add_seq_check_work, but I'm not convinced it's doing the
1877          * right thing -- rav
1878          *
1879          * If we don't have all the data that is in this fragment,
1880          * then we can't, and don't, do reassembly on it.
1881          *
1882          * If it's the first frame, handle it as an unfragmented packet.
1883          * Otherwise, just handle it as a fragment.
1884          *
1885          * If "more_frags" isn't set, we get rid of the entry in the
1886          * hash table for this reassembly, as we don't need it any more.
1887          */
1888         if ((flags & REASSEMBLE_FLAGS_CHECK_DATA_PRESENT) &&
1889                 !tvb_bytes_exist(tvb, offset, frag_data_len)) {
1890                 fd_head -> flags |= FD_DATA_NOT_PRESENT;
1891                 if (frag_number == 0) {
1892                         return fd_head;
1893                 }
1894                 else {
1895                         if (!more_frags) {
1896                                 /*
1897                                  * Remove this from the table of in-progress
1898                                  * reassemblies, and free up any memory used for
1899                                  * it in that table.
1900                                  */
1901                                 fragment_unhash(table, *orig_keyp);
1902                                 free_all_fragments(NULL, fd_head, NULL);
1903                         }
1904                         return NULL;
1905                 }
1906         }
1907
1908         if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1909                                   frag_number, frag_data_len, more_frags)) {
1910                 /*
1911                  * Reassembly is complete.
1912                  */
1913                 return fd_head;
1914         } else {
1915                 /*
1916                  * Reassembly isn't complete.
1917                  */
1918                 return NULL;
1919         }
1920 }
1921
1922 fragment_head *
1923 fragment_add_seq(reassembly_table *table, tvbuff_t *tvb, const int offset,
1924                  const packet_info *pinfo, const guint32 id, const void *data, 
1925                  const guint32 frag_number, const guint32 frag_data_len,
1926                  const gboolean more_frags, const guint32 flags)
1927 {
1928         return fragment_add_seq_common(table, tvb, offset, pinfo, id, data,
1929                                        frag_number, frag_data_len,
1930                                        more_frags, flags, NULL);
1931 }
1932
1933 /*
1934  * This does the work for "fragment_add_seq_check()" and
1935  * "fragment_add_seq_next()".
1936  *
1937  * This function assumes frag_number being a block sequence number.
1938  * The bsn for the first block is 0.
1939  *
1940  * If "no_frag_number" is TRUE, it uses the next expected fragment number
1941  * as the fragment number if there is a reassembly in progress, otherwise
1942  * it uses 0.
1943  *
1944  * If "no_frag_number" is FALSE, it uses the "frag_number" argument as
1945  * the fragment number.
1946  *
1947  * If this is the first fragment seen for this datagram, a new
1948  * "fragment_head" structure is allocated to refer to the reassembled
1949  * packet.
1950  *
1951  * This fragment is added to the linked list of fragments for this packet.
1952  *
1953  * If "more_frags" is false and REASSEMBLE_FLAGS_802_11_HACK (as the name
1954  * implies, a special hack for 802.11) or REASSEMBLE_FLAGS_NO_FRAG_NUMBER
1955  * (implying messages must be in order since there's no sequence number) are
1956  * set in "flags", then this (one element) list is returned.
1957  *
1958  * If, after processing this fragment, we have all the fragments,
1959  * "fragment_add_seq_check_work()" removes that from the fragment hash
1960  * table if necessary and adds it to the table of reassembled fragments,
1961  * and returns a pointer to the head of the fragment list.
1962  *
1963  * Otherwise, it returns NULL.
1964  *
1965  * XXX - Should we simply return NULL for zero-length fragments?
1966  */
1967 static fragment_head *
1968 fragment_add_seq_check_work(reassembly_table *table, tvbuff_t *tvb,
1969                             const int offset, const packet_info *pinfo,
1970                             const guint32 id, const void *data, 
1971                             const guint32 frag_number,
1972                             const guint32 frag_data_len,
1973                             const gboolean more_frags, const guint32 flags)
1974 {
1975         reassembled_key reass_key;
1976         fragment_head *fd_head;
1977         gpointer orig_key;
1978
1979         /*
1980          * Have we already seen this frame?
1981          * If so, look for it in the table of reassembled packets.
1982          */
1983         if (pinfo->fd->flags.visited) {
1984                 reass_key.frame = pinfo->fd->num;
1985                 reass_key.id = id;
1986                 return (fragment_head *)g_hash_table_lookup(table->reassembled_table, &reass_key);
1987         }
1988
1989         fd_head = fragment_add_seq_common(table, tvb, offset, pinfo, id, data, 
1990                                           frag_number, frag_data_len,
1991                                           more_frags,
1992                                           flags|REASSEMBLE_FLAGS_CHECK_DATA_PRESENT,
1993                                           &orig_key);
1994         if (fd_head) {
1995                 if(fd_head->flags & FD_DATA_NOT_PRESENT) {
1996                         /* this is the first fragment of a datagram with
1997                          * truncated fragments. Don't move it to the
1998                          * reassembled table. */
1999                         return fd_head;
2000                 }
2001
2002                 /*
2003                  * Reassembly is complete.
2004                  *
2005                  * If this is in the table of in-progress reassemblies,
2006                  * remove it from that table.  (It could be that this
2007                  * was the first and last fragment, so that no
2008                  * reassembly was done.)
2009                  */
2010                 if (orig_key != NULL)
2011                         fragment_unhash(table, orig_key);
2012
2013                 /*
2014                  * Add this item to the table of reassembled packets.
2015                  */
2016                 fragment_reassembled(table, fd_head, pinfo, id);
2017                 return fd_head;
2018         } else {
2019                 /*
2020                  * Reassembly isn't complete.
2021                  */
2022                 return NULL;
2023         }
2024 }
2025
2026 fragment_head *
2027 fragment_add_seq_check(reassembly_table *table, tvbuff_t *tvb, const int offset,
2028                        const packet_info *pinfo, const guint32 id,
2029                        const void *data,
2030                        const guint32 frag_number, const guint32 frag_data_len,
2031                        const gboolean more_frags)
2032 {
2033         return fragment_add_seq_check_work(table, tvb, offset, pinfo, id, data,
2034                                            frag_number, frag_data_len,
2035                                            more_frags, 0);
2036 }
2037
2038 fragment_head *
2039 fragment_add_seq_802_11(reassembly_table *table, tvbuff_t *tvb,
2040                         const int offset, const packet_info *pinfo,
2041                         const guint32 id, const void *data,
2042                         const guint32 frag_number, const guint32 frag_data_len,
2043                         const gboolean more_frags)
2044 {
2045         return fragment_add_seq_check_work(table, tvb, offset, pinfo, id, data,
2046                                            frag_number, frag_data_len,
2047                                            more_frags,
2048                                            REASSEMBLE_FLAGS_802_11_HACK);
2049 }
2050
2051 fragment_head *
2052 fragment_add_seq_next(reassembly_table *table, tvbuff_t *tvb, const int offset,
2053                       const packet_info *pinfo, const guint32 id,
2054                       const void *data, const guint32 frag_data_len,
2055                       const gboolean more_frags)
2056 {
2057         return fragment_add_seq_check_work(table, tvb, offset, pinfo, id, data,
2058                                            0, frag_data_len, more_frags,
2059                                            REASSEMBLE_FLAGS_NO_FRAG_NUMBER);
2060 }
2061
2062 void
2063 fragment_start_seq_check(reassembly_table *table, const packet_info *pinfo,
2064                          const guint32 id, const void *data, 
2065                          const guint32 tot_len)
2066 {
2067         fragment_head *fd_head;
2068
2069         /* Have we already seen this frame ?*/
2070         if (pinfo->fd->flags.visited) {
2071                 return;
2072         }
2073
2074         /* Check if fragment data exists */
2075         fd_head = lookup_fd_head(table, pinfo, id, data, NULL);
2076
2077         if (fd_head == NULL) {
2078                 /* Create list-head. */
2079                 fd_head = g_slice_new(fragment_head);
2080                 fd_head->next = NULL;
2081                 fd_head->datalen = tot_len;
2082                 fd_head->offset = 0;
2083                 fd_head->fragment_nr_offset = 0;
2084                 fd_head->len = 0;
2085                 fd_head->flags = FD_BLOCKSEQUENCE|FD_DATALEN_SET;
2086                 fd_head->tvb_data = NULL;
2087                 fd_head->reassembled_in = 0;
2088                 fd_head->error = NULL;
2089
2090                 insert_fd_head(table, fd_head, pinfo, id, data);
2091         }
2092 }
2093
2094 fragment_head *
2095 fragment_end_seq_next(reassembly_table *table, const packet_info *pinfo,
2096                       const guint32 id, const void *data)
2097 {
2098         reassembled_key reass_key;
2099         reassembled_key *new_key;
2100         fragment_head *fd_head;
2101         gpointer orig_key;
2102
2103         /*
2104          * Have we already seen this frame?
2105          * If so, look for it in the table of reassembled packets.
2106          */
2107         if (pinfo->fd->flags.visited) {
2108                 reass_key.frame = pinfo->fd->num;
2109                 reass_key.id = id;
2110                 return (fragment_head *)g_hash_table_lookup(table->reassembled_table, &reass_key);
2111         }
2112
2113         fd_head = lookup_fd_head(table, pinfo, id, data, &orig_key);
2114
2115         if (fd_head) {
2116                 if (fd_head->flags & FD_DATA_NOT_PRESENT) {
2117                         /* No data added */
2118                         return NULL;
2119                 }
2120
2121                 fd_head->datalen = fd_head->offset;
2122                 fd_head->flags |= FD_DATALEN_SET;
2123
2124                 fragment_defragment_and_free (fd_head, pinfo);
2125
2126                 /*
2127                  * Remove this from the table of in-progress reassemblies,
2128                  * and free up any memory used for it in that table.
2129                  */
2130                 fragment_unhash(table, orig_key);
2131
2132                 /*
2133                  * Add this item to the table of reassembled packets.
2134                  */
2135                 fragment_reassembled(table, fd_head, pinfo, id);
2136                 if (fd_head->next != NULL) {
2137                         new_key = g_slice_new(reassembled_key);
2138                         new_key->frame = pinfo->fd->num;
2139                         new_key->id = id;
2140                         g_hash_table_insert(table->reassembled_table, new_key, fd_head);
2141                 }
2142
2143                 return fd_head;
2144         } else {
2145                 /*
2146                  * Fragment data not found.
2147                  */
2148                 return NULL;
2149         }
2150 }
2151
2152 /*
2153  * Process reassembled data; if we're on the frame in which the data
2154  * was reassembled, put the fragment information into the protocol
2155  * tree, and construct a tvbuff with the reassembled data, otherwise
2156  * just put a "reassembled in" item into the protocol tree.
2157  */
2158 tvbuff_t *
2159 process_reassembled_data(tvbuff_t *tvb, const int offset, packet_info *pinfo,
2160         const char *name, fragment_head *fd_head, const fragment_items *fit,
2161         gboolean *update_col_infop, proto_tree *tree)
2162 {
2163         tvbuff_t *next_tvb;
2164         gboolean update_col_info;
2165         proto_item *frag_tree_item;
2166
2167         if (fd_head != NULL && pinfo->fd->num == fd_head->reassembled_in) {
2168                 /*
2169                  * OK, we've reassembled this.
2170                  * Is this something that's been reassembled from more
2171                  * than one fragment?
2172                  */
2173                 if (fd_head->next != NULL) {
2174                         /*
2175                          * Yes.
2176                          * Allocate a new tvbuff, referring to the
2177                          * reassembled payload, and set
2178                          * the tvbuff to the list of tvbuffs to which
2179                          * the tvbuff we were handed refers, so it'll get
2180                          * cleaned up when that tvbuff is cleaned up.
2181                          */
2182                         next_tvb = tvb_new_chain(tvb, fd_head->tvb_data);
2183
2184                         /* Add the defragmented data to the data source list. */
2185                         add_new_data_source(pinfo, next_tvb, name);
2186
2187                         /* show all fragments */
2188                         if (fd_head->flags & FD_BLOCKSEQUENCE) {
2189                                 update_col_info = !show_fragment_seq_tree(
2190                                         fd_head, fit,  tree, pinfo, next_tvb, &frag_tree_item);
2191                         } else {
2192                                 update_col_info = !show_fragment_tree(fd_head,
2193                                         fit, tree, pinfo, next_tvb, &frag_tree_item);
2194                         }
2195                 } else {
2196                         /*
2197                          * No.
2198                          * Return a tvbuff with the payload.
2199                          */
2200                         next_tvb = tvb_new_subset_remaining(tvb, offset);
2201                         pinfo->fragmented = FALSE;      /* one-fragment packet */
2202                         update_col_info = TRUE;
2203                 }
2204                 if (update_col_infop != NULL)
2205                         *update_col_infop = update_col_info;
2206         } else {
2207                 /*
2208                  * We don't have the complete reassembled payload, or this
2209                  * isn't the final frame of that payload.
2210                  */
2211                 next_tvb = NULL;
2212
2213                 /*
2214                  * If we know what frame this was reassembled in,
2215                  * and if there's a field to use for the number of
2216                  * the frame in which the packet was reassembled,
2217                  * add it to the protocol tree.
2218                  */
2219                 if (fd_head != NULL && fit->hf_reassembled_in != NULL) {
2220                         proto_tree_add_uint(tree,
2221                                 *(fit->hf_reassembled_in), tvb,
2222                                 0, 0, fd_head->reassembled_in);
2223                 }
2224         }
2225         return next_tvb;
2226 }
2227
2228 /*
2229  * Show a single fragment in a fragment subtree, and put information about
2230  * it in the top-level item for that subtree.
2231  */
2232 static void
2233 show_fragment(fragment_item *fd, const int offset, const fragment_items *fit,
2234         proto_tree *ft, proto_item *fi, const gboolean first_frag,
2235         const guint32 count, tvbuff_t *tvb, packet_info *pinfo)
2236 {
2237         proto_item *fei=NULL;
2238         int hf;
2239
2240         if (first_frag) {
2241                 gchar *name;
2242                 if (count == 1) {
2243                         name = g_strdup(proto_registrar_get_name(*(fit->hf_fragment)));
2244                 } else {
2245                         name = g_strdup(proto_registrar_get_name(*(fit->hf_fragments)));
2246                 }
2247                 proto_item_set_text(fi, "%u %s (%u byte%s): ", count, name, tvb_length(tvb),
2248                                     plurality(tvb_length(tvb), "", "s"));
2249                 g_free(name);
2250         } else {
2251                 proto_item_append_text(fi, ", ");
2252         }
2253         proto_item_append_text(fi, "#%u(%u)", fd->frame, fd->len);
2254
2255         if (fd->flags & (FD_OVERLAPCONFLICT
2256                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
2257                 hf = *(fit->hf_fragment_error);
2258         } else {
2259                 hf = *(fit->hf_fragment);
2260         }
2261         if (fd->len == 0) {
2262                 fei = proto_tree_add_uint_format(ft, hf,
2263                         tvb, offset, fd->len,
2264                         fd->frame,
2265                         "Frame: %u (no data)",
2266                         fd->frame);
2267         } else {
2268                 fei = proto_tree_add_uint_format(ft, hf,
2269                         tvb, offset, fd->len,
2270                         fd->frame,
2271                         "Frame: %u, payload: %u-%u (%u byte%s)",
2272                         fd->frame,
2273                         offset,
2274                         offset+fd->len-1,
2275                         fd->len,
2276                         plurality(fd->len, "", "s"));
2277         }
2278         PROTO_ITEM_SET_GENERATED(fei);
2279         mark_frame_as_depended_upon(pinfo, fd->frame);
2280         if (fd->flags & (FD_OVERLAP|FD_OVERLAPCONFLICT
2281                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
2282                 /* this fragment has some flags set, create a subtree
2283                  * for it and display the flags.
2284                  */
2285                 proto_tree *fet=NULL;
2286
2287                 fet = proto_item_add_subtree(fei, *(fit->ett_fragment));
2288                 if (fd->flags&FD_OVERLAP) {
2289                         fei=proto_tree_add_boolean(fet,
2290                                 *(fit->hf_fragment_overlap),
2291                                 tvb, 0, 0,
2292                                 TRUE);
2293                         PROTO_ITEM_SET_GENERATED(fei);
2294                 }
2295                 if (fd->flags&FD_OVERLAPCONFLICT) {
2296                         fei=proto_tree_add_boolean(fet,
2297                                 *(fit->hf_fragment_overlap_conflict),
2298                                 tvb, 0, 0,
2299                                 TRUE);
2300                         PROTO_ITEM_SET_GENERATED(fei);
2301                 }
2302                 if (fd->flags&FD_MULTIPLETAILS) {
2303                         fei=proto_tree_add_boolean(fet,
2304                                 *(fit->hf_fragment_multiple_tails),
2305                                 tvb, 0, 0,
2306                                 TRUE);
2307                         PROTO_ITEM_SET_GENERATED(fei);
2308                 }
2309                 if (fd->flags&FD_TOOLONGFRAGMENT) {
2310                         fei=proto_tree_add_boolean(fet,
2311                                 *(fit->hf_fragment_too_long_fragment),
2312                                 tvb, 0, 0,
2313                                 TRUE);
2314                         PROTO_ITEM_SET_GENERATED(fei);
2315                 }
2316         }
2317 }
2318
2319 static gboolean
2320 show_fragment_errs_in_col(fragment_head *fd_head, const fragment_items *fit,
2321         packet_info *pinfo)
2322 {
2323         if (fd_head->flags & (FD_OVERLAPCONFLICT
2324                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
2325                 col_add_fstr(pinfo->cinfo, COL_INFO, "[Illegal %s]", fit->tag);
2326                 return TRUE;
2327         }
2328
2329         return FALSE;
2330 }
2331
2332 /* This function will build the fragment subtree; it's for fragments
2333    reassembled with "fragment_add()".
2334
2335    It will return TRUE if there were fragmentation errors
2336    or FALSE if fragmentation was ok.
2337 */
2338 gboolean
2339 show_fragment_tree(fragment_head *fd_head, const fragment_items *fit,
2340         proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi)
2341 {
2342         fragment_item *fd;
2343         proto_tree *ft;
2344         gboolean first_frag;
2345         guint32 count = 0;
2346         /* It's not fragmented. */
2347         pinfo->fragmented = FALSE;
2348
2349         *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, ENC_NA);
2350         PROTO_ITEM_SET_GENERATED(*fi);
2351
2352         ft = proto_item_add_subtree(*fi, *(fit->ett_fragments));
2353         first_frag = TRUE;
2354         for (fd = fd_head->next; fd != NULL; fd = fd->next) {
2355                 count++;
2356         }
2357         for (fd = fd_head->next; fd != NULL; fd = fd->next) {
2358                 show_fragment(fd, fd->offset, fit, ft, *fi, first_frag, count, tvb, pinfo);
2359                 first_frag = FALSE;
2360         }
2361
2362         if (fit->hf_fragment_count) {
2363                 proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count),
2364                                                       tvb, 0, 0, count);
2365                 PROTO_ITEM_SET_GENERATED(fli);
2366         }
2367
2368         if (fit->hf_reassembled_length) {
2369                 proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length),
2370                                                       tvb, 0, 0, tvb_length (tvb));
2371                 PROTO_ITEM_SET_GENERATED(fli);
2372         }
2373
2374         if (fit->hf_reassembled_data) {
2375                 proto_item *fli = proto_tree_add_item(ft, *(fit->hf_reassembled_data),
2376                                                       tvb, 0, tvb_length(tvb), ENC_NA);
2377                 PROTO_ITEM_SET_GENERATED(fli);
2378         }
2379
2380         return show_fragment_errs_in_col(fd_head, fit, pinfo);
2381 }
2382
2383 /* This function will build the fragment subtree; it's for fragments
2384    reassembled with "fragment_add_seq()" or "fragment_add_seq_check()".
2385
2386    It will return TRUE if there were fragmentation errors
2387    or FALSE if fragmentation was ok.
2388 */
2389 gboolean
2390 show_fragment_seq_tree(fragment_head *fd_head, const fragment_items *fit,
2391         proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi)
2392 {
2393         guint32 offset, next_offset, count = 0;
2394         fragment_item *fd, *last_fd;
2395         proto_tree *ft;
2396         gboolean first_frag;
2397
2398         /* It's not fragmented. */
2399         pinfo->fragmented = FALSE;
2400
2401         *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, ENC_NA);
2402         PROTO_ITEM_SET_GENERATED(*fi);
2403
2404         ft = proto_item_add_subtree(*fi, *(fit->ett_fragments));
2405         offset = 0;
2406         next_offset = 0;
2407         last_fd = NULL;
2408         first_frag = TRUE;
2409         for (fd = fd_head->next; fd != NULL; fd = fd->next){
2410                 count++;
2411         }
2412         for (fd = fd_head->next; fd != NULL; fd = fd->next){
2413                 if (last_fd == NULL || last_fd->offset != fd->offset) {
2414                         offset = next_offset;
2415                         next_offset += fd->len;
2416                 }
2417                 last_fd = fd;
2418                 show_fragment(fd, offset, fit, ft, *fi, first_frag, count, tvb, pinfo);
2419                 first_frag = FALSE;
2420         }
2421
2422         if (fit->hf_fragment_count) {
2423                 proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count),
2424                                                       tvb, 0, 0, count);
2425                 PROTO_ITEM_SET_GENERATED(fli);
2426         }
2427
2428         if (fit->hf_reassembled_length) {
2429                 proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length),
2430                                                       tvb, 0, 0, tvb_length (tvb));
2431                 PROTO_ITEM_SET_GENERATED(fli);
2432         }
2433
2434         if (fit->hf_reassembled_data) {
2435                 proto_item *fli = proto_tree_add_item(ft, *(fit->hf_reassembled_data),
2436                                                       tvb, 0, tvb_length(tvb), ENC_NA);
2437                 PROTO_ITEM_SET_GENERATED(fli);
2438         }
2439
2440         return show_fragment_errs_in_col(fd_head, fit, pinfo);
2441 }
2442
2443 /*
2444  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
2445  *
2446  * Local variables:
2447  * c-basic-offset: 8
2448  * tab-width: 8
2449  * indent-tabs-mode: t
2450  * End:
2451  *
2452  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
2453  * :indentSize=8:tabSize=8:noTabs=false:
2454  */