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