Make the "per_choice_t" and "per_sequence_t" pointer arguments pointers
[obnox/wireshark/wip.git] / reassemble.c
1 /* reassemble.c
2  * Routines for {fragment,segment} reassembly
3  *
4  * $Id$
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <string.h>
30
31 #include <epan/packet.h>
32
33 #include "reassemble.h"
34
35 #include <epan/dissectors/packet-dcerpc.h>
36
37 typedef struct _fragment_key {
38         address src;
39         address dst;
40         guint32 id;
41 } fragment_key;
42
43 typedef struct _dcerpc_fragment_key {
44        address src;
45        address dst;
46        guint32 id;
47     e_uuid_t act_id;
48 } dcerpc_fragment_key;
49
50 static GMemChunk *fragment_key_chunk = NULL;
51 static GMemChunk *dcerpc_fragment_key_chunk = NULL;
52 static GMemChunk *fragment_data_chunk = NULL;
53 static int fragment_init_count = 200;
54
55 #define LINK_FRAG(fd_head,fd)                                   \
56         {       fragment_data *fd_i;                            \
57                 /* add fragment to list, keep list sorted */            \
58                 for(fd_i=(fd_head);fd_i->next;fd_i=fd_i->next){ \
59                         if( ((fd)->offset) < (fd_i->next->offset) )     \
60                                 break;                                  \
61                 }                                                       \
62                 (fd)->next=fd_i->next;                          \
63                 fd_i->next=(fd);                                        \
64         }
65
66 static gint
67 fragment_equal(gconstpointer k1, gconstpointer k2)
68 {
69         const fragment_key* key1 = (const fragment_key*) k1;
70         const fragment_key* key2 = (const fragment_key*) k2;
71
72         /*key.id is the first item to compare since item is most
73           likely to differ between sessions, thus shortcircuiting
74           the comparasion of addresses.
75         */
76         return ( ( (key1->id    == key2->id) &&
77                    (ADDRESSES_EQUAL(&key1->src, &key2->src)) &&
78                    (ADDRESSES_EQUAL(&key1->dst, &key2->dst))
79                  ) ?
80                  TRUE : FALSE);
81 }
82
83 static guint
84 fragment_hash(gconstpointer k)
85 {
86         const fragment_key* key = (const fragment_key*) k;
87         guint hash_val;
88 /*
89         int i;
90 */
91
92         hash_val = 0;
93
94 /*      More than likely: in most captures src and dst addresses are the
95         same, and would hash the same.
96         We only use id as the hash as an optimization.
97
98         for (i = 0; i < key->src.len; i++)
99                 hash_val += key->src.data[i];
100         for (i = 0; i < key->dst.len; i++)
101                 hash_val += key->dst.data[i];
102 */
103
104         hash_val += key->id;
105
106         return hash_val;
107 }
108
109 static gint
110 dcerpc_fragment_equal(gconstpointer k1, gconstpointer k2)
111 {
112        const dcerpc_fragment_key* key1 = (const dcerpc_fragment_key*) k1;
113        const dcerpc_fragment_key* key2 = (const dcerpc_fragment_key*) k2;
114
115        /*key.id is the first item to compare since item is most
116          likely to differ between sessions, thus shortcircuiting
117          the comparasion of addresses.
118        */
119        return (((key1->id == key2->id)
120              && (ADDRESSES_EQUAL(&key1->src, &key2->src))
121              && (ADDRESSES_EQUAL(&key1->dst, &key2->dst))
122              && (memcmp (&key1->act_id, &key2->act_id, sizeof (e_uuid_t)) == 0))
123             ? TRUE : FALSE);
124 }
125
126 static guint
127 dcerpc_fragment_hash(gconstpointer k)
128 {
129        const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k;
130        guint hash_val;
131
132        hash_val = 0;
133
134        hash_val += key->id;
135        hash_val += key->act_id.Data1;
136        hash_val += key->act_id.Data2 << 16;
137        hash_val += key->act_id.Data3;
138
139        return hash_val;
140 }
141
142 typedef struct _reassembled_key {
143         guint32 id;
144         guint32 frame;
145 } reassembled_key;
146
147 static GMemChunk *reassembled_key_chunk = NULL;
148
149 static gint
150 reassembled_equal(gconstpointer k1, gconstpointer k2)
151 {
152         const reassembled_key* key1 = (const reassembled_key*) k1;
153         const reassembled_key* key2 = (const reassembled_key*) k2;
154
155         /*
156          * We assume that the frame numbers are unlikely to be equal,
157          * so we check them first.
158          */
159         return key1->frame == key2->frame && key1->id == key2->id;
160 }
161
162 static guint
163 reassembled_hash(gconstpointer k)
164 {
165         const reassembled_key* key = (const reassembled_key*) k;
166
167         return key->frame;
168 }
169
170 /*
171  * For a fragment hash table entry, free the address data to which the key
172  * refers and the fragment data to which the value refers.
173  * (The actual key and value structures get freed by "reassemble_init()".)
174  */
175 static gboolean
176 free_all_fragments(gpointer key_arg, gpointer value, gpointer user_data _U_)
177 {
178         fragment_key *key = key_arg;
179         fragment_data *fd_head;
180
181         /*
182          * Grr.  I guess the theory here is that freeing
183          * something sure as heck modifies it, so you
184          * want to ban attempts to free it, but, alas,
185          * if we make the "data" field of an "address"
186          * structure not a "const", the compiler whines if
187          * we try to make it point into the data for a packet,
188          * as that's a "const" array (and should be, as dissectors
189          * shouldn't trash it).
190          *
191          * So we cast the complaint into oblivion, and rely on
192          * the fact that these addresses are known to have had
193          * their data mallocated, i.e. they don't point into,
194          * say, the middle of the data for a packet.
195          */
196         g_free((gpointer)key->src.data);
197         g_free((gpointer)key->dst.data);
198
199         for (fd_head = value; fd_head != NULL; fd_head = fd_head->next) {
200                 if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED))
201                         g_free(fd_head->data);
202         }
203
204         return TRUE;
205 }
206
207 /*
208  * For a reassembled-packet hash table entry, free the fragment data
209  * to which the value refers.
210  * (The actual value structures get freed by "reassemble_init()".)
211  */
212 static gboolean
213 free_all_reassembled_fragments(gpointer key_arg _U_, gpointer value,
214                                gpointer user_data _U_)
215 {
216         fragment_data *fd_head;
217
218         for (fd_head = value; fd_head != NULL; fd_head = fd_head->next) {
219                 if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) {
220                         g_free(fd_head->data);
221
222                         /*
223                          * A reassembled packet is inserted into the
224                          * hash table once for every frame that made
225                          * up the reassembled packet; clear the data
226                          * pointer so that we only free the data the
227                          * first time we see it.
228                          */
229                         fd_head->data = NULL;
230                 }
231         }
232
233         return TRUE;
234 }
235
236 /*
237  * Initialize a fragment table.
238  */
239 void
240 fragment_table_init(GHashTable **fragment_table)
241 {
242         if (*fragment_table != NULL) {
243                 /*
244                  * The fragment hash table exists.
245                  *
246                  * Remove all entries and free fragment data for
247                  * each entry.  (The key and value data is freed
248                  * by "reassemble_init()".)
249                  */
250                 g_hash_table_foreach_remove(*fragment_table,
251                                 free_all_fragments, NULL);
252         } else {
253                 /* The fragment table does not exist. Create it */
254                 *fragment_table = g_hash_table_new(fragment_hash,
255                                 fragment_equal);
256         }
257 }
258
259 void
260 dcerpc_fragment_table_init(GHashTable **fragment_table)
261 {
262        if (*fragment_table != NULL) {
263                /*
264                 * The fragment hash table exists.
265                 *
266                 * Remove all entries and free fragment data for
267                 * each entry.  (The key and value data is freed
268                 * by "reassemble_init()".)
269                 */
270                g_hash_table_foreach_remove(*fragment_table,
271                                free_all_fragments, NULL);
272        } else {
273                /* The fragment table does not exist. Create it */
274                *fragment_table = g_hash_table_new(dcerpc_fragment_hash,
275                                dcerpc_fragment_equal);
276        }
277 }
278
279 /*
280  * Initialize a reassembled-packet table.
281  */
282 void
283 reassembled_table_init(GHashTable **reassembled_table)
284 {
285         if (*reassembled_table != NULL) {
286                 /*
287                  * The reassembled-packet hash table exists.
288                  *
289                  * Remove all entries and free reassembled packet
290                  * data for each entry.  (The key data is freed
291                  * by "reassemble_init()".)
292                  */
293                 g_hash_table_foreach_remove(*reassembled_table,
294                                 free_all_reassembled_fragments, NULL);
295         } else {
296                 /* The fragment table does not exist. Create it */
297                 *reassembled_table = g_hash_table_new(reassembled_hash,
298                                 reassembled_equal);
299         }
300 }
301
302 /*
303  * Free up all space allocated for fragment keys and data and
304  * reassembled keys.
305  */
306 void
307 reassemble_init(void)
308 {
309         if (fragment_key_chunk != NULL)
310                 g_mem_chunk_destroy(fragment_key_chunk);
311         if (dcerpc_fragment_key_chunk != NULL)
312                 g_mem_chunk_destroy(dcerpc_fragment_key_chunk);
313         if (fragment_data_chunk != NULL)
314                 g_mem_chunk_destroy(fragment_data_chunk);
315         if (reassembled_key_chunk != NULL)
316                 g_mem_chunk_destroy(reassembled_key_chunk);
317         fragment_key_chunk = g_mem_chunk_new("fragment_key_chunk",
318             sizeof(fragment_key),
319             fragment_init_count * sizeof(fragment_key),
320             G_ALLOC_AND_FREE);
321         dcerpc_fragment_key_chunk = g_mem_chunk_new("dcerpc_fragment_key_chunk",
322             sizeof(dcerpc_fragment_key),
323             fragment_init_count * sizeof(dcerpc_fragment_key),
324             G_ALLOC_AND_FREE);
325         fragment_data_chunk = g_mem_chunk_new("fragment_data_chunk",
326             sizeof(fragment_data),
327             fragment_init_count * sizeof(fragment_data),
328             G_ALLOC_ONLY);
329         reassembled_key_chunk = g_mem_chunk_new("reassembled_key_chunk",
330             sizeof(reassembled_key),
331             fragment_init_count * sizeof(reassembled_key),
332             G_ALLOC_AND_FREE);
333 }
334
335 /* This function cleans up the stored state and removes the reassembly data and
336  * (with one exception) all allocated memory for matching reassembly.
337  *
338  * The exception is :
339  * If the PDU was already completely reassembled, then the buffer containing the
340  * reassembled data WILL NOT be free()d, and the pointer to that buffer will be
341  * returned.
342  * Othervise the function will return NULL.
343  *
344  * So, if you call fragment_delete and it returns non-NULL, YOU are responsible to
345  * g_free() that buffer.
346  */
347 unsigned char *
348 fragment_delete(packet_info *pinfo, guint32 id, GHashTable *fragment_table)
349 {
350         fragment_data *fd_head, *fd;
351         fragment_key key;
352         unsigned char *data=NULL;
353
354         /* create key to search hash with */
355         key.src = pinfo->src;
356         key.dst = pinfo->dst;
357         key.id  = id;
358
359         fd_head = g_hash_table_lookup(fragment_table, &key);
360
361         if(fd_head==NULL){
362                 /* We do not recognize this as a PDU we have seen before. return*/
363                 return NULL;
364         }
365
366         data=fd_head->data;
367         /* loop over all partial fragments and free any buffers */
368         for(fd=fd_head->next;fd;){
369                 fragment_data *tmp_fd;
370                 tmp_fd=fd->next;
371
372                 if( !(fd->flags&FD_NOT_MALLOCED) )
373                         g_free(fd->data);
374                 g_mem_chunk_free(fragment_data_chunk, fd);
375                 fd=tmp_fd;
376         }
377         g_mem_chunk_free(fragment_data_chunk, fd_head);
378         g_hash_table_remove(fragment_table, &key);
379
380         return data;
381 }
382
383 /* This function is used to check if there is partial or completed reassembly state
384  * matching this packet. I.e. Are there reassembly going on or not for this packet?
385  */
386 fragment_data *
387 fragment_get(packet_info *pinfo, guint32 id, GHashTable *fragment_table)
388 {
389         fragment_data *fd_head;
390         fragment_key key;
391
392         /* create key to search hash with */
393         key.src = pinfo->src;
394         key.dst = pinfo->dst;
395         key.id  = id;
396
397         fd_head = g_hash_table_lookup(fragment_table, &key);
398
399         return fd_head;
400 }
401
402 /* This function can be used to explicitely set the total length (if known)
403  * for reassembly of a PDU.
404  * This is useful for reassembly of PDUs where one may have the total length specified
405  * in the first fragment instead of as for, say, IPv4 where a flag indicates which
406  * is the last fragment.
407  *
408  * Such protocols might fragment_add with a more_frags==TRUE for every fragment
409  * and just tell the reassembly engine the expected total length of the reassembled data
410  * using fragment_set_tot_len immediately after doing fragment_add for the first packet.
411  *
412  * note that for FD_BLOCKSEQUENCE tot_len is the index for the tail fragment.
413  * i.e. since the block numbers start at 0, if we specify tot_len==2, that
414  * actually means we want to defragment 3 blocks, block 0, 1 and 2.
415  */
416 void
417 fragment_set_tot_len(packet_info *pinfo, guint32 id, GHashTable *fragment_table,
418                      guint32 tot_len)
419 {
420         fragment_data *fd_head;
421         fragment_key key;
422
423         /* create key to search hash with */
424         key.src = pinfo->src;
425         key.dst = pinfo->dst;
426         key.id  = id;
427
428         fd_head = g_hash_table_lookup(fragment_table, &key);
429
430         if(fd_head){
431                 fd_head->datalen = tot_len;
432         }
433
434         return;
435 }
436
437 guint32
438 fragment_get_tot_len(packet_info *pinfo, guint32 id, GHashTable *fragment_table)
439 {
440         fragment_data *fd_head;
441         fragment_key key;
442
443         /* create key to search hash with */
444         key.src = pinfo->src;
445         key.dst = pinfo->dst;
446         key.id  = id;
447
448         fd_head = g_hash_table_lookup(fragment_table, &key);
449
450         if(fd_head){
451                 return fd_head->datalen;
452         }
453
454         return 0;
455 }
456
457
458 /* This function will set the partial reassembly flag for a fh.
459    When this function is called, the fh MUST already exist, i.e.
460    the fh MUST be created by the initial call to fragment_add() before
461    this function is called.
462    Also note that this function MUST be called to indicate a fh will be
463    extended (increase the already stored data)
464 */
465
466 void
467 fragment_set_partial_reassembly(packet_info *pinfo, guint32 id, GHashTable *fragment_table)
468 {
469         fragment_data *fd_head;
470         fragment_key key;
471
472         /* create key to search hash with */
473         key.src = pinfo->src;
474         key.dst = pinfo->dst;
475         key.id  = id;
476
477         fd_head = g_hash_table_lookup(fragment_table, &key);
478
479         if(fd_head){
480                 fd_head->flags |= FD_PARTIAL_REASSEMBLY;
481         }
482 }
483
484 /*
485  * This function gets rid of an entry from a fragment table, given
486  * a pointer to the key for that entry; it also frees up the key
487  * and the addresses in it.
488  */
489 static void
490 fragment_unhash(GHashTable *fragment_table, fragment_key *key)
491 {
492         /*
493          * Free up the copies of the addresses from the old key.
494          */
495         g_free((gpointer)key->src.data);
496         g_free((gpointer)key->dst.data);
497
498         /*
499          * Remove the entry from the fragment table.
500          */
501         g_hash_table_remove(fragment_table, key);
502
503         /*
504          * Free the key itself.
505          */
506         g_mem_chunk_free(fragment_key_chunk, key);
507 }
508
509 /*
510  * This function adds fragment_data structure to a reassembled-packet
511  * hash table, using the frame numbers of each of the frames from
512  * which it was reassembled as keys, and sets the "reassembled_in"
513  * frame number.
514  */
515 static void
516 fragment_reassembled(fragment_data *fd_head, packet_info *pinfo,
517              GHashTable *reassembled_table, guint32 id)
518 {
519         reassembled_key *new_key;
520         fragment_data *fd;
521
522         if (fd_head->next == NULL) {
523                 /*
524                  * This was not fragmented, so there's no fragment
525                  * table; just hash it using the current frame number.
526                  */
527                 new_key = g_mem_chunk_alloc(reassembled_key_chunk);
528                 new_key->frame = pinfo->fd->num;
529                 new_key->id = id;
530                 g_hash_table_insert(reassembled_table, new_key, fd_head);
531         } else {
532                 /*
533                  * Hash it with the frame numbers for all the frames.
534                  */
535                 for (fd = fd_head->next; fd != NULL; fd = fd->next){
536                         new_key = g_mem_chunk_alloc(reassembled_key_chunk);
537                         new_key->frame = fd->frame;
538                         new_key->id = id;
539                         g_hash_table_insert(reassembled_table, new_key,
540                             fd_head);
541                 }
542         }
543         fd_head->flags |= FD_DEFRAGMENTED;
544         fd_head->reassembled_in = pinfo->fd->num;
545 }
546
547 /*
548  * This function adds a new fragment to the fragment hash table.
549  * If this is the first fragment seen for this datagram, a new entry
550  * is created in the hash table, otherwise this fragment is just added
551  * to the linked list of fragments for this packet.
552  * The list of fragments for a specific datagram is kept sorted for
553  * easier handling.
554  *
555  * Returns a pointer to the head of the fragment data list if we have all the
556  * fragments, NULL otherwise.
557  *
558  * This function assumes frag_offset being a byte offset into the defragment
559  * packet.
560  *
561  * 01-2002
562  * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be
563  * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set
564  * using fragment_set_partial_reassembly() before calling fragment_add
565  * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags
566  * are lowered when a new extension process is started.
567  */
568 static gboolean
569 fragment_add_work(fragment_data *fd_head, tvbuff_t *tvb, int offset,
570              packet_info *pinfo, guint32 frag_offset,
571              guint32 frag_data_len, gboolean more_frags)
572 {
573         fragment_data *fd;
574         fragment_data *fd_i;
575         guint32 max, dfpos;
576         unsigned char *old_data;
577
578         /* create new fd describing this fragment */
579         fd = g_mem_chunk_alloc(fragment_data_chunk);
580         fd->next = NULL;
581         fd->flags = 0;
582         fd->frame = pinfo->fd->num;
583         fd->offset = frag_offset;
584         fd->len  = frag_data_len;
585         fd->data = NULL;
586
587         /*
588          * If it was already defragmented and this new fragment goes beyond
589          * data limits, set flag in already empty fds & point old fds to malloc'ed data.
590          */
591         if(fd_head->flags & FD_DEFRAGMENTED && (frag_offset+frag_data_len) >= fd_head->datalen &&
592                 fd_head->flags & FD_PARTIAL_REASSEMBLY){
593                 for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){
594                         if( !fd_i->data ) {
595                                 fd_i->data = fd_head->data + fd_i->offset;
596                                 fd_i->flags |= FD_NOT_MALLOCED;
597                         }
598                         fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
599                 }
600                 fd_head->flags ^= FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY;
601                 fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
602                 fd_head->datalen=0;
603         }
604
605         if (!more_frags) {
606                 /*
607                  * This is the tail fragment in the sequence.
608                  */
609                 if (fd_head->datalen) {
610                         /* ok we have already seen other tails for this packet
611                          * it might be a duplicate.
612                          */
613                         if (fd_head->datalen != (fd->offset + fd->len) ){
614                                 /* Oops, this tail indicates a different packet
615                                  * len than the previous ones. Somethings wrong
616                                  */
617                                 fd->flags      |= FD_MULTIPLETAILS;
618                                 fd_head->flags |= FD_MULTIPLETAILS;
619                         }
620                 } else {
621                         /* this was the first tail fragment, now we know the
622                          * length of the packet
623                          */
624                         fd_head->datalen = fd->offset + fd->len;
625                 }
626         }
627
628
629
630
631         /* If the packet is already defragmented, this MUST be an overlap.
632          * The entire defragmented packet is in fd_head->data
633          * Even if we have previously defragmented this packet, we still check
634          * check it. Someone might play overlap and TTL games.
635          */
636         if (fd_head->flags & FD_DEFRAGMENTED) {
637                 fd->flags      |= FD_OVERLAP;
638                 fd_head->flags |= FD_OVERLAP;
639                 /* make sure its not too long */
640                 if (fd->offset + fd->len > fd_head->datalen) {
641                         fd->flags      |= FD_TOOLONGFRAGMENT;
642                         fd_head->flags |= FD_TOOLONGFRAGMENT;
643                         LINK_FRAG(fd_head,fd);
644                         return TRUE;
645                 }
646                 /* make sure it doesnt conflict with previous data */
647                 if ( memcmp(fd_head->data+fd->offset,
648                         tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
649                         fd->flags      |= FD_OVERLAPCONFLICT;
650                         fd_head->flags |= FD_OVERLAPCONFLICT;
651                         LINK_FRAG(fd_head,fd);
652                         return TRUE;
653                 }
654                 /* it was just an overlap, link it and return */
655                 LINK_FRAG(fd_head,fd);
656                 return TRUE;
657         }
658
659
660
661         /* If we have reached this point, the packet is not defragmented yet.
662          * Save all payload in a buffer until we can defragment.
663          * XXX - what if we didn't capture the entire fragment due
664          * to a too-short snapshot length?
665          */
666         fd->data = g_malloc(fd->len);
667         tvb_memcpy(tvb, fd->data, offset, fd->len);
668         LINK_FRAG(fd_head,fd);
669
670
671         if( !(fd_head->datalen) ){
672                 /* if we dont know the datalen, there are still missing
673                  * packets. Cheaper than the check below.
674                  */
675                 return FALSE;
676         }
677
678
679         /* check if we have received the entire fragment
680          * this is easy since the list is sorted and the head is faked.
681          */
682         max = 0;
683         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
684                 if ( ((fd_i->offset)<=max) &&
685                     ((fd_i->offset+fd_i->len)>max) ){
686                         max = fd_i->offset+fd_i->len;
687                 }
688         }
689
690         if (max < (fd_head->datalen)) {
691                 /* we have not received all packets yet */
692                 return FALSE;
693         }
694
695
696         if (max > (fd_head->datalen)) {
697                 /*XXX not sure if current fd was the TOOLONG*/
698                 /*XXX is it fair to flag current fd*/
699                 /* oops, too long fragment detected */
700                 fd->flags      |= FD_TOOLONGFRAGMENT;
701                 fd_head->flags |= FD_TOOLONGFRAGMENT;
702         }
703
704
705         /* we have received an entire packet, defragment it and
706          * free all fragments
707          */
708         /* store old data just in case */
709         old_data=fd_head->data;
710         fd_head->data = g_malloc(max);
711
712         /* add all data fragments */
713         for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) {
714                 if (fd_i->len) {
715                         if (fd_i->offset < dfpos) {
716                                 fd_i->flags    |= FD_OVERLAP;
717                                 fd_head->flags |= FD_OVERLAP;
718                                 if ( memcmp(fd_head->data+fd_i->offset,
719                                         fd_i->data,
720                                         MIN(fd_i->len,(dfpos-fd_i->offset))
721                                         ) ){
722                                         fd_i->flags    |= FD_OVERLAPCONFLICT;
723                                         fd_head->flags |= FD_OVERLAPCONFLICT;
724                                 }
725                         }
726                         /* dfpos is always >= than fd_i->offset */
727                         /* No gaps can exist here, max_loop(above) does this */
728                         if( fd_i->offset+fd_i->len > dfpos )
729                                 memcpy(fd_head->data+dfpos, fd_i->data+(dfpos-fd_i->offset),
730                                         fd_i->len-(dfpos-fd_i->offset));
731                         if( fd_i->flags & FD_NOT_MALLOCED )
732                                 fd_i->flags ^= FD_NOT_MALLOCED;
733                         else
734                                 g_free(fd_i->data);
735                         fd_i->data=NULL;
736
737                         dfpos=MAX(dfpos,(fd_i->offset+fd_i->len));
738                 }
739         }
740
741         if( old_data )
742                 g_free(old_data);
743         /* mark this packet as defragmented.
744            allows us to skip any trailing fragments */
745         fd_head->flags |= FD_DEFRAGMENTED;
746         fd_head->reassembled_in=pinfo->fd->num;
747
748         return TRUE;
749 }
750
751 fragment_data *
752 fragment_add_common(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
753              GHashTable *fragment_table, guint32 frag_offset,
754              guint32 frag_data_len, gboolean more_frags,
755              gboolean check_already_added)
756 {
757         fragment_key key, *new_key;
758         fragment_data *fd_head;
759         fragment_data *fd_item;
760         gboolean already_added=pinfo->fd->flags.visited;
761
762         /* create key to search hash with */
763         key.src = pinfo->src;
764         key.dst = pinfo->dst;
765         key.id  = id;
766
767         fd_head = g_hash_table_lookup(fragment_table, &key);
768
769         /*
770          * "already_added" is true if "pinfo->fd->flags.visited" is true;
771          * if "pinfo->fd->flags.visited", this isn't the first pass, so
772          * we've already done all the reassembly and added all the
773          * fragments.
774          *
775          * If it's not true, but "check_already_added" is true, just check
776          * if we have seen this fragment before, i.e., if we have already
777          * added it to reassembly.
778          * That can be true even if "pinfo->fd->flags.visited" is false
779          * since we sometimes might call a subdissector multiple times.
780          * As an additional check, just make sure we have not already added 
781          * this frame to the reassembly list, if there is a reassembly list;
782          * note that the first item in the reassembly list is not a
783          * fragment, it's a data structure for the reassembled packet.
784          * We don't check it because its "frame" member isn't initialized
785          * to anything, and because it doesn't count in any case.
786          */
787         if (!already_added && check_already_added && fd_head != NULL) {
788                 for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){
789                         if(pinfo->fd->num==fd_item->frame){
790                                 already_added=TRUE;
791                         }
792                 }
793         }
794         /* have we already added this frame ?*/
795         if (already_added) {
796                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
797                         return fd_head;
798                 } else {
799                         return NULL;
800                 }
801         }
802
803         if (fd_head==NULL){
804                 /* not found, this must be the first snooped fragment for this
805                  * packet. Create list-head.
806                  */
807                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
808
809                 /* head/first structure in list only holds no other data than
810                  * 'datalen' then we don't have to change the head of the list
811                  * even if we want to keep it sorted
812                  */
813                 fd_head->next=NULL;
814                 fd_head->datalen=0;
815                 fd_head->offset=0;
816                 fd_head->len=0;
817                 fd_head->flags=0;
818                 fd_head->data=NULL;
819                 fd_head->reassembled_in=0;
820
821                 /*
822                  * We're going to use the key to insert the fragment,
823                  * so allocate a structure for it, and copy the
824                  * addresses, allocating new buffers for the address
825                  * data.
826                  */
827                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
828                 COPY_ADDRESS(&new_key->src, &key.src);
829                 COPY_ADDRESS(&new_key->dst, &key.dst);
830                 new_key->id = key.id;
831                 g_hash_table_insert(fragment_table, new_key, fd_head);
832         }
833
834         if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset,
835             frag_data_len, more_frags)) {
836                 /*
837                  * Reassembly is complete.
838                  */
839                 return fd_head;
840         } else {
841                 /*
842                  * Reassembly isn't complete.
843                  */
844                 return NULL;
845         }
846 }
847
848 fragment_data *
849 fragment_add(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
850              GHashTable *fragment_table, guint32 frag_offset,
851              guint32 frag_data_len, gboolean more_frags)
852 {
853         return fragment_add_common(tvb, offset, pinfo, id, fragment_table,
854             frag_offset, frag_data_len, more_frags, TRUE);
855 }
856
857 /*
858  * For use when you can have multiple fragments in the same frame added
859  * to the same reassembled PDU, e.g. with ONC RPC-over-TCP.
860  */
861 fragment_data *
862 fragment_add_multiple_ok(tvbuff_t *tvb, int offset, packet_info *pinfo,
863                          guint32 id, GHashTable *fragment_table,
864                          guint32 frag_offset, guint32 frag_data_len,
865                          gboolean more_frags)
866 {
867         return fragment_add_common(tvb, offset, pinfo, id, fragment_table,
868             frag_offset, frag_data_len, more_frags, FALSE);
869 }
870
871 fragment_data *
872 fragment_add_check(tvbuff_t *tvb, int offset, packet_info *pinfo,
873              guint32 id, GHashTable *fragment_table,
874              GHashTable *reassembled_table, guint32 frag_offset,
875              guint32 frag_data_len, gboolean more_frags)
876 {
877         reassembled_key reass_key;
878         fragment_key key, *new_key, *old_key;
879         gpointer orig_key, value;
880         fragment_data *fd_head;
881
882         /*
883          * If this isn't the first pass, look for this frame in the table
884          * of reassembled packets.
885          */
886         if (pinfo->fd->flags.visited) {
887                 reass_key.frame = pinfo->fd->num;
888                 reass_key.id = id;
889                 return g_hash_table_lookup(reassembled_table, &reass_key);
890         }
891
892         /* create key to search hash with */
893         key.src = pinfo->src;
894         key.dst = pinfo->dst;
895         key.id  = id;
896
897         if (!g_hash_table_lookup_extended(fragment_table, &key,
898                                           &orig_key, &value)) {
899                 /* not found, this must be the first snooped fragment for this
900                  * packet. Create list-head.
901                  */
902                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
903
904                 /* head/first structure in list only holds no other data than
905                  * 'datalen' then we don't have to change the head of the list
906                  * even if we want to keep it sorted
907                  */
908                 fd_head->next=NULL;
909                 fd_head->datalen=0;
910                 fd_head->offset=0;
911                 fd_head->len=0;
912                 fd_head->flags=0;
913                 fd_head->data=NULL;
914                 fd_head->reassembled_in=0;
915
916                 /*
917                  * We're going to use the key to insert the fragment,
918                  * so allocate a structure for it, and copy the
919                  * addresses, allocating new buffers for the address
920                  * data.
921                  */
922                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
923                 COPY_ADDRESS(&new_key->src, &key.src);
924                 COPY_ADDRESS(&new_key->dst, &key.dst);
925                 new_key->id = key.id;
926                 g_hash_table_insert(fragment_table, new_key, fd_head);
927
928                 orig_key = new_key;     /* for unhashing it later */
929         } else {
930                 /*
931                  * We found it.
932                  */
933                 fd_head = value;
934         }
935
936         /*
937          * If this is a short frame, then we can't, and don't, do
938          * reassembly on it.  We just give up.
939          */
940         if (tvb_reported_length(tvb) > tvb_length(tvb))
941                 return NULL;
942
943         if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset,
944             frag_data_len, more_frags)) {
945                 /*
946                  * Reassembly is complete.
947                  * Remove this from the table of in-progress
948                  * reassemblies, add it to the table of
949                  * reassembled packets, and return it.
950                  */
951
952                 /*
953                  * Remove this from the table of in-progress reassemblies,
954                  * and free up any memory used for it in that table.
955                  */
956                 old_key = orig_key;
957                 fragment_unhash(fragment_table, old_key);
958
959                 /*
960                  * Add this item to the table of reassembled packets.
961                  */
962                 fragment_reassembled(fd_head, pinfo, reassembled_table, id);
963                 return fd_head;
964         } else {
965                 /*
966                  * Reassembly isn't complete.
967                  */
968                 return NULL;
969         }
970 }
971
972 /*
973  * This function adds a new fragment to the entry for a reassembly
974  * operation.
975  *
976  * The list of fragments for a specific datagram is kept sorted for
977  * easier handling.
978  *
979  * Returns TRUE if we have all the fragments, FALSE otherwise.
980  *
981  * This function assumes frag_number being a block sequence number.
982  * The bsn for the first block is 0.
983  */
984 static gboolean
985 fragment_add_seq_work(fragment_data *fd_head, tvbuff_t *tvb, int offset,
986              packet_info *pinfo, guint32 frag_number,
987              guint32 frag_data_len, gboolean more_frags)
988 {
989         fragment_data *fd;
990         fragment_data *fd_i;
991         fragment_data *last_fd;
992         guint32 max, dfpos, size;
993
994         /* create new fd describing this fragment */
995         fd = g_mem_chunk_alloc(fragment_data_chunk);
996         fd->next = NULL;
997         fd->flags = 0;
998         fd->frame = pinfo->fd->num;
999         fd->offset = frag_number;
1000         fd->len  = frag_data_len;
1001         fd->data = NULL;
1002
1003         if (!more_frags) {
1004                 /*
1005                  * This is the tail fragment in the sequence.
1006                  */
1007                 if (fd_head->datalen) {
1008                         /* ok we have already seen other tails for this packet
1009                          * it might be a duplicate.
1010                          */
1011                         if (fd_head->datalen != fd->offset ){
1012                                 /* Oops, this tail indicates a different packet
1013                                  * len than the previous ones. Somethings wrong
1014                                  */
1015                                 fd->flags      |= FD_MULTIPLETAILS;
1016                                 fd_head->flags |= FD_MULTIPLETAILS;
1017                         }
1018                 } else {
1019                         /* this was the first tail fragment, now we know the
1020                          * sequence number of that fragment (which is NOT
1021                          * the length of the packet!)
1022                          */
1023                         fd_head->datalen = fd->offset;
1024                 }
1025         }
1026
1027         /* If the packet is already defragmented, this MUST be an overlap.
1028          * The entire defragmented packet is in fd_head->data
1029          * Even if we have previously defragmented this packet, we still check
1030          * check it. Someone might play overlap and TTL games.
1031          */
1032         if (fd_head->flags & FD_DEFRAGMENTED) {
1033                 fd->flags      |= FD_OVERLAP;
1034                 fd_head->flags |= FD_OVERLAP;
1035
1036                 /* make sure it's not past the end */
1037                 if (fd->offset > fd_head->datalen) {
1038                         /* new fragment comes after the end */
1039                         fd->flags      |= FD_TOOLONGFRAGMENT;
1040                         fd_head->flags |= FD_TOOLONGFRAGMENT;
1041                         LINK_FRAG(fd_head,fd);
1042                         return TRUE;
1043                 }
1044                 /* make sure it doesnt conflict with previous data */
1045                 dfpos=0;
1046                 last_fd=NULL;
1047                 for (fd_i=fd_head->next;fd_i->offset!=fd->offset;fd_i=fd_i->next) {
1048                   if (!last_fd || last_fd->offset!=fd_i->offset){
1049                     dfpos += fd_i->len;
1050                   }
1051                   last_fd=fd_i;
1052                 }
1053                 if(fd_i){
1054                         /* new fragment overlaps existing fragment */
1055                         if(fd_i->len!=fd->len){
1056                                 /*
1057                                  * They have different lengths; this
1058                                  * is definitely a conflict.
1059                                  */
1060                                 fd->flags      |= FD_OVERLAPCONFLICT;
1061                                 fd_head->flags |= FD_OVERLAPCONFLICT;
1062                                 LINK_FRAG(fd_head,fd);
1063                                 return TRUE;
1064                         }
1065                         g_assert(fd_head->len >= dfpos + fd->len);
1066                         if ( memcmp(fd_head->data+dfpos,
1067                             tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
1068                                 /*
1069                                  * They have the same length, but the
1070                                  * data isn't the same.
1071                                  */
1072                                 fd->flags      |= FD_OVERLAPCONFLICT;
1073                                 fd_head->flags |= FD_OVERLAPCONFLICT;
1074                                 LINK_FRAG(fd_head,fd);
1075                                 return TRUE;
1076                         }
1077                         /* it was just an overlap, link it and return */
1078                         LINK_FRAG(fd_head,fd);
1079                         return TRUE;
1080                 } else {
1081                         /*
1082                          * New fragment doesn't overlap an existing
1083                          * fragment - there was presumably a gap in
1084                          * the sequence number space.
1085                          *
1086                          * XXX - what should we do here?  Is it always
1087                          * the case that there are no gaps, or are there
1088                          * protcols using sequence numbers where there
1089                          * can be gaps?
1090                          *
1091                          * If the former, the check below for having
1092                          * received all the fragments should check for
1093                          * holes in the sequence number space and for the
1094                          * first sequence number being 0.  If we do that,
1095                          * the only way we can get here is if this fragment
1096                          * is past the end of the sequence number space -
1097                          * but the check for "fd->offset > fd_head->datalen"
1098                          * would have caught that above, so it can't happen.
1099                          *
1100                          * If the latter, we don't have a good way of
1101                          * knowing whether reassembly is complete if we
1102                          * get packet out of order such that the "last"
1103                          * fragment doesn't show up last - but, unless
1104                          * in-order reliable delivery of fragments is
1105                          * guaranteed, an implementation of the protocol
1106                          * has no way of knowing whether reassembly is
1107                          * complete, either.
1108                          *
1109                          * For now, we just link the fragment in and
1110                          * return.
1111                          */
1112                         LINK_FRAG(fd_head,fd);
1113                         return TRUE;
1114                 }
1115         }
1116
1117         /* If we have reached this point, the packet is not defragmented yet.
1118          * Save all payload in a buffer until we can defragment.
1119          * XXX - what if we didn't capture the entire fragment due
1120          * to a too-short snapshot length?
1121          */
1122         fd->data = g_malloc(fd->len);
1123         tvb_memcpy(tvb, fd->data, offset, fd->len);
1124         LINK_FRAG(fd_head,fd);
1125
1126
1127         if( !(fd_head->datalen) ){
1128                 /* if we dont know the sequence number of the last fragment,
1129                  * there are definitely still missing packets. Cheaper than
1130                  * the check below.
1131                  */
1132                 return FALSE;
1133         }
1134
1135
1136         /* check if we have received the entire fragment
1137          * this is easy since the list is sorted and the head is faked.
1138          */
1139         max = 0;
1140         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1141           if ( fd_i->offset==max ){
1142             max++;
1143           }
1144         }
1145         /* max will now be datalen+1 if all fragments have been seen */
1146
1147         if (max <= fd_head->datalen) {
1148                 /* we have not received all packets yet */
1149                 return FALSE;
1150         }
1151
1152
1153         if (max > (fd_head->datalen+1)) {
1154                 /* oops, too long fragment detected */
1155                 fd->flags      |= FD_TOOLONGFRAGMENT;
1156                 fd_head->flags |= FD_TOOLONGFRAGMENT;
1157         }
1158
1159
1160         /* we have received an entire packet, defragment it and
1161          * free all fragments
1162          */
1163         size=0;
1164         last_fd=NULL;
1165         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1166           if(!last_fd || last_fd->offset!=fd_i->offset){
1167             size+=fd_i->len;
1168           }
1169           last_fd=fd_i;
1170         }
1171         fd_head->data = g_malloc(size);
1172         fd_head->len = size;            /* record size for caller       */
1173
1174         /* add all data fragments */
1175         last_fd=NULL;
1176         for (dfpos=0,fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1177           if (fd_i->len) {
1178             if(!last_fd || last_fd->offset!=fd_i->offset){
1179               memcpy(fd_head->data+dfpos,fd_i->data,fd_i->len);
1180               dfpos += fd_i->len;
1181             } else {
1182               /* duplicate/retransmission/overlap */
1183               fd_i->flags    |= FD_OVERLAP;
1184               fd_head->flags |= FD_OVERLAP;
1185               if( (last_fd->len!=fd_i->datalen)
1186                   || memcmp(last_fd->data, fd_i->data, last_fd->len) ){
1187                         fd->flags      |= FD_OVERLAPCONFLICT;
1188                         fd_head->flags |= FD_OVERLAPCONFLICT;
1189               }
1190             }
1191             last_fd=fd_i;
1192           }
1193         }
1194
1195         /* we have defragmented the pdu, now free all fragments*/
1196         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1197           if(fd_i->data){
1198             g_free(fd_i->data);
1199             fd_i->data=NULL;
1200           }
1201         }
1202
1203         /* mark this packet as defragmented.
1204            allows us to skip any trailing fragments */
1205         fd_head->flags |= FD_DEFRAGMENTED;
1206         fd_head->reassembled_in=pinfo->fd->num;
1207
1208         return TRUE;
1209 }
1210
1211 /*
1212  * This function adds a new fragment to the fragment hash table.
1213  * If this is the first fragment seen for this datagram, a new entry
1214  * is created in the hash table, otherwise this fragment is just added
1215  * to the linked list of fragments for this packet.
1216  *
1217  * Returns a pointer to the head of the fragment data list if we have all the
1218  * fragments, NULL otherwise.
1219  *
1220  * This function assumes frag_number being a block sequence number.
1221  * The bsn for the first block is 0.
1222  */
1223 fragment_data *
1224 fragment_add_seq(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
1225              GHashTable *fragment_table, guint32 frag_number,
1226              guint32 frag_data_len, gboolean more_frags)
1227 {
1228         fragment_key key, *new_key;
1229         fragment_data *fd_head;
1230
1231         /* create key to search hash with */
1232         key.src = pinfo->src;
1233         key.dst = pinfo->dst;
1234         key.id  = id;
1235
1236         fd_head = g_hash_table_lookup(fragment_table, &key);
1237
1238         /* have we already seen this frame ?*/
1239         if (pinfo->fd->flags.visited) {
1240                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
1241                         return fd_head;
1242                 } else {
1243                         return NULL;
1244                 }
1245         }
1246
1247         if (fd_head==NULL){
1248                 /* not found, this must be the first snooped fragment for this
1249                  * packet. Create list-head.
1250                  */
1251                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
1252
1253                 /* head/first structure in list only holds no other data than
1254                  * 'datalen' then we don't have to change the head of the list
1255                  * even if we want to keep it sorted
1256                  */
1257                 fd_head->next=NULL;
1258                 fd_head->datalen=0;
1259                 fd_head->offset=0;
1260                 fd_head->len=0;
1261                 fd_head->flags=FD_BLOCKSEQUENCE;
1262                 fd_head->data=NULL;
1263                 fd_head->reassembled_in=0;
1264
1265                 /*
1266                  * We're going to use the key to insert the fragment,
1267                  * so allocate a structure for it, and copy the
1268                  * addresses, allocating new buffers for the address
1269                  * data.
1270                  */
1271                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
1272                 COPY_ADDRESS(&new_key->src, &key.src);
1273                 COPY_ADDRESS(&new_key->dst, &key.dst);
1274                 new_key->id = key.id;
1275                 g_hash_table_insert(fragment_table, new_key, fd_head);
1276         }
1277
1278         if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1279                                   frag_number, frag_data_len, more_frags)) {
1280                 /*
1281                  * Reassembly is complete.
1282                  */
1283                 return fd_head;
1284         } else {
1285                 /*
1286                  * Reassembly isn't complete.
1287                  */
1288                 return NULL;
1289         }
1290 }
1291
1292 fragment_data *
1293 fragment_add_dcerpc(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
1294                     void *v_act_id,
1295                     GHashTable *fragment_table, guint32 frag_number,
1296                     guint32 frag_data_len, gboolean more_frags)
1297 {
1298        dcerpc_fragment_key key, *new_key;
1299        fragment_data *fd_head;
1300        e_uuid_t *act_id = (e_uuid_t *)v_act_id;
1301
1302        /* create key to search hash with */
1303        key.src = pinfo->src;
1304        key.dst = pinfo->dst;
1305        key.id  = id;
1306        key.act_id  = *act_id;
1307
1308        fd_head = g_hash_table_lookup(fragment_table, &key);
1309
1310        /* have we already seen this frame ?*/
1311        if (pinfo->fd->flags.visited) {
1312                if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
1313                        return fd_head;
1314                } else {
1315                        return NULL;
1316                }
1317        }
1318
1319        if (fd_head==NULL){
1320                /* not found, this must be the first snooped fragment for this
1321                  * packet. Create list-head.
1322                 */
1323                fd_head=g_mem_chunk_alloc(fragment_data_chunk);
1324
1325                /* head/first structure in list only holds no other data than
1326                  * 'datalen' then we don't have to change the head of the list
1327                  * even if we want to keep it sorted
1328                  */
1329                fd_head->next=NULL;
1330                fd_head->datalen=0;
1331                fd_head->offset=0;
1332                fd_head->len=0;
1333                fd_head->flags=FD_BLOCKSEQUENCE;
1334                fd_head->data=NULL;
1335                fd_head->reassembled_in=0;
1336
1337                /*
1338                 * We're going to use the key to insert the fragment,
1339                 * so allocate a structure for it, and copy the
1340                 * addresses, allocating new buffers for the address
1341                 * data.
1342                 */
1343                new_key = g_mem_chunk_alloc(dcerpc_fragment_key_chunk);
1344                COPY_ADDRESS(&new_key->src, &key.src);
1345                COPY_ADDRESS(&new_key->dst, &key.dst);
1346                new_key->id = key.id;
1347                new_key->act_id = key.act_id;
1348                g_hash_table_insert(fragment_table, new_key, fd_head);
1349        }
1350
1351        if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1352                                  frag_number, frag_data_len, more_frags)) {
1353                /*
1354                 * Reassembly is complete.
1355                 */
1356                return fd_head;
1357        } else {
1358                /*
1359                 * Reassembly isn't complete.
1360                 */
1361                return NULL;
1362        }
1363 }
1364
1365 /*
1366  * This does the work for "fragment_add_seq_check()" and
1367  * "fragment_add_seq_next()".
1368  *
1369  * This function assumes frag_number being a block sequence number.
1370  * The bsn for the first block is 0.
1371  *
1372  * If "no_frag_number" is TRUE, it uses the next expected fragment number
1373  * as the fragment number if there is a reassembly in progress, otherwise
1374  * it uses 0.
1375  *
1376  * If "no_frag_number" is FALSE, it uses the "frag_number" argument as
1377  * the fragment number.
1378  *
1379  * If this is the first fragment seen for this datagram, a new
1380  * "fragment_data" structure is allocated to refer to the reassembled,
1381  * packet, and:
1382  *
1383  *      if "more_frags" is false and "frag_802_11_hack" is true, the
1384  *      structure is not added to the hash table, and not given any
1385  *      fragments to refer to, but is just returned - this is a special
1386  *      hack for the 802.11 dissector (see packet-80211.c);
1387  *
1388  *      otherwise, this fragment is added to the linked list of fragments
1389  *      for this packet, and the "fragment_data" structure is put into
1390  *      the hash table.
1391  *
1392  * Otherwise, this fragment is just added to the linked list of fragments
1393  * for this packet.
1394  *
1395  * If, after processing this fragment, we have all the fragments,
1396  * "fragment_add_seq_check_work()" removes that from the fragment hash
1397  * table if necessary and adds it to the table of reassembled fragments,
1398  * and returns a pointer to the head of the fragment list.
1399  *
1400  * If this is the first fragment we've seen, and "more_frags" is false
1401  * and "frag_802_11_hack" is true, "fragment_add_seq_check_work()" does
1402  * nothing to the fragment data list, and returns a pointer to the head
1403  * of that (empty) list.
1404  *
1405  * Otherwise, it returns NULL.
1406  */
1407 static fragment_data *
1408 fragment_add_seq_check_work(tvbuff_t *tvb, int offset, packet_info *pinfo,
1409              guint32 id, GHashTable *fragment_table,
1410              GHashTable *reassembled_table, guint32 frag_number,
1411              guint32 frag_data_len, gboolean more_frags,
1412              gboolean no_frag_number, gboolean frag_802_11_hack)
1413 {
1414         reassembled_key reass_key;
1415         fragment_key key, *new_key, *old_key;
1416         gpointer orig_key, value;
1417         fragment_data *fd_head, *fd;
1418
1419         /*
1420          * Have we already seen this frame?
1421          * If so, look for it in the table of reassembled packets.
1422          */
1423         if (pinfo->fd->flags.visited) {
1424                 reass_key.frame = pinfo->fd->num;
1425                 reass_key.id = id;
1426                 return g_hash_table_lookup(reassembled_table, &reass_key);
1427         }
1428
1429         /* create key to search hash with */
1430         key.src = pinfo->src;
1431         key.dst = pinfo->dst;
1432         key.id  = id;
1433
1434         if (!g_hash_table_lookup_extended(fragment_table, &key,
1435                                           &orig_key, &value)) {
1436                 /* not found, this must be the first snooped fragment for this
1437                  * packet. Create list-head.
1438                  */
1439                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
1440
1441                 /* head/first structure in list only holds no other data than
1442                  * 'datalen' then we don't have to change the head of the list
1443                  * even if we want to keep it sorted
1444                  */
1445                 fd_head->next=NULL;
1446                 fd_head->datalen=0;
1447                 fd_head->offset=0;
1448                 fd_head->len=0;
1449                 fd_head->flags=FD_BLOCKSEQUENCE;
1450                 fd_head->data=NULL;
1451                 fd_head->reassembled_in=0;
1452
1453                 if ((no_frag_number || frag_802_11_hack) && !more_frags) {
1454                         /*
1455                          * This is the last fragment for this packet, and
1456                          * is the only one we've seen.
1457                          *
1458                          * Either we don't have sequence numbers, in which
1459                          * case we assume this is the first fragment for
1460                          * this packet, or we're doing special 802.11
1461                          * processing, in which case we assume it's one
1462                          * of those reassembled packets with a non-zero
1463                          * fragment number (see packet-80211.c); just
1464                          * add the fragment to the table of reassembled
1465                          * packets, and return a pointer to the head of
1466                          * the list.
1467                          */
1468                         fragment_reassembled(fd_head, pinfo,
1469                                reassembled_table, id);
1470                         return fd_head;
1471                 }
1472
1473                 /*
1474                  * We're going to use the key to insert the fragment,
1475                  * so allocate a structure for it, and copy the
1476                  * addresses, allocating new buffers for the address
1477                  * data.
1478                  */
1479                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
1480                 COPY_ADDRESS(&new_key->src, &key.src);
1481                 COPY_ADDRESS(&new_key->dst, &key.dst);
1482                 new_key->id = key.id;
1483                 g_hash_table_insert(fragment_table, new_key, fd_head);
1484
1485                 orig_key = new_key;     /* for unhashing it later */
1486
1487                 /*
1488                  * If we weren't given an initial fragment number,
1489                  * make it 0.
1490                  */
1491                 if (no_frag_number)
1492                         frag_number = 0;
1493         } else {
1494                 /*
1495                  * We found it.
1496                  */
1497                 fd_head = value;
1498
1499                 /*
1500                  * If we weren't given an initial fragment number,
1501                  * use the next expected fragment number as the fragment
1502                  * number for this fragment.
1503                  */
1504                 if (no_frag_number) {
1505                         for (fd = fd_head; fd != NULL; fd = fd->next) {
1506                                 if (fd->next == NULL)
1507                                         frag_number = fd->offset + 1;
1508                         }
1509                 }
1510         }
1511
1512         /*
1513          * If we don't have all the data that is in this fragment,
1514          * then we can't, and don't, do reassembly on it.
1515          *
1516          * If it's the first frame, handle it as an unfragmented packet.
1517          * Otherwise, just handle it as a fragment.
1518          *
1519          * If "more_frags" isn't set, we get rid of the entry in the
1520          * hash table for this reassembly, as we don't need it any more.
1521          */
1522         if (!tvb_bytes_exist(tvb, offset, frag_data_len)) {
1523                 if (!more_frags) {
1524                         /*
1525                          * Remove this from the table of in-progress
1526                          * reassemblies, and free up any memory used for
1527                          * it in that table.
1528                          */
1529                         old_key = orig_key;
1530                         fragment_unhash(fragment_table, old_key);
1531                 }
1532                 return frag_number == 0 ? fd_head : NULL;
1533         }
1534
1535         if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1536                                   frag_number, frag_data_len, more_frags)) {
1537                 /*
1538                  * Reassembly is complete.
1539                  * Remove this from the table of in-progress
1540                  * reassemblies, add it to the table of
1541                  * reassembled packets, and return it.
1542                  */
1543
1544                 /*
1545                  * Remove this from the table of in-progress reassemblies,
1546                  * and free up any memory used for it in that table.
1547                  */
1548                 old_key = orig_key;
1549                 fragment_unhash(fragment_table, old_key);
1550
1551                 /*
1552                  * Add this item to the table of reassembled packets.
1553                  */
1554                 fragment_reassembled(fd_head, pinfo, reassembled_table, id);
1555                 return fd_head;
1556         } else {
1557                 /*
1558                  * Reassembly isn't complete.
1559                  */
1560                 return NULL;
1561         }
1562 }
1563
1564 fragment_data *
1565 fragment_add_seq_check(tvbuff_t *tvb, int offset, packet_info *pinfo,
1566              guint32 id, GHashTable *fragment_table,
1567              GHashTable *reassembled_table, guint32 frag_number,
1568              guint32 frag_data_len, gboolean more_frags)
1569 {
1570         return fragment_add_seq_check_work(tvb, offset, pinfo, id,
1571             fragment_table, reassembled_table, frag_number, frag_data_len,
1572             more_frags, FALSE, FALSE);
1573 }
1574
1575 fragment_data *
1576 fragment_add_seq_802_11(tvbuff_t *tvb, int offset, packet_info *pinfo,
1577              guint32 id, GHashTable *fragment_table,
1578              GHashTable *reassembled_table, guint32 frag_number,
1579              guint32 frag_data_len, gboolean more_frags)
1580 {
1581         return fragment_add_seq_check_work(tvb, offset, pinfo, id,
1582             fragment_table, reassembled_table, frag_number, frag_data_len,
1583             more_frags, FALSE, TRUE);
1584 }
1585
1586 fragment_data *
1587 fragment_add_seq_next(tvbuff_t *tvb, int offset, packet_info *pinfo,
1588              guint32 id, GHashTable *fragment_table,
1589              GHashTable *reassembled_table, guint32 frag_data_len,
1590              gboolean more_frags)
1591 {
1592         return fragment_add_seq_check_work(tvb, offset, pinfo, id,
1593             fragment_table, reassembled_table, 0, frag_data_len,
1594             more_frags, TRUE, FALSE);
1595 }
1596
1597 /*
1598  * Process reassembled data; if we're on the frame in which the data
1599  * was reassembled, put the fragment information into the protocol
1600  * tree, and construct a tvbuff with the reassembled data, otherwise
1601  * just put a "reassembled in" item into the protocol tree.
1602  */
1603 tvbuff_t *
1604 process_reassembled_data(tvbuff_t *tvb, int offset, packet_info *pinfo,
1605     char *name, fragment_data *fd_head, const fragment_items *fit,
1606     gboolean *update_col_infop, proto_tree *tree)
1607 {
1608         tvbuff_t *next_tvb;
1609         gboolean update_col_info;
1610
1611         if (fd_head != NULL && pinfo->fd->num == fd_head->reassembled_in) {
1612                 /*
1613                  * OK, we've reassembled this.
1614                  * Is this something that's been reassembled from more
1615                  * than one fragment?
1616                  */
1617                 if (fd_head->next != NULL) {
1618                         /*
1619                          * Yes.
1620                          * Allocate a new tvbuff, referring to the
1621                          * reassembled payload.
1622                          */
1623                         if (fd_head->flags & FD_BLOCKSEQUENCE) {
1624                                 next_tvb = tvb_new_real_data(fd_head->data,
1625                                       fd_head->len, fd_head->len);
1626                         } else {
1627                                 next_tvb = tvb_new_real_data(fd_head->data,
1628                                       fd_head->datalen, fd_head->datalen);
1629                         }
1630
1631                         /*
1632                          * Add the tvbuff to the list of tvbuffs to which
1633                          * the tvbuff we were handed refers, so it'll get
1634                          * cleaned up when that tvbuff is cleaned up.
1635                          */
1636                         tvb_set_child_real_data_tvbuff(tvb, next_tvb);
1637
1638                         /* Add the defragmented data to the data source list. */
1639                         add_new_data_source(pinfo, next_tvb, name);
1640
1641                         /* show all fragments */
1642                         if (fd_head->flags & FD_BLOCKSEQUENCE) {
1643                                 update_col_info = !show_fragment_seq_tree(
1644                                     fd_head, fit,  tree, pinfo, next_tvb);
1645                         } else {
1646                                 update_col_info = !show_fragment_tree(fd_head,
1647                                     fit, tree, pinfo, next_tvb);
1648                         }
1649                 } else {
1650                         /*
1651                          * No.
1652                          * Return a tvbuff with the payload.
1653                          */
1654                         next_tvb = tvb_new_subset(tvb, offset, -1, -1);
1655                         pinfo->fragmented = FALSE;      /* one-fragment packet */
1656                         update_col_info = TRUE;
1657                 }
1658                 if (update_col_infop != NULL)
1659                         *update_col_infop = update_col_info;
1660         } else {
1661                 /*
1662                  * We don't have the complete reassembled payload, or this
1663                  * isn't the final frame of that payload.
1664                  */
1665                 next_tvb = NULL;
1666
1667                 /*
1668                  * If we know what frame this was reassembled in,
1669                  * and if there's a field to use for the number of
1670                  * the frame in which the packet was reassembled,
1671                  * add it to the protocol tree.
1672                  */
1673                 if (fd_head != NULL && fit->hf_reassembled_in != NULL) {
1674                         proto_tree_add_uint(tree,
1675                             *(fit->hf_reassembled_in), tvb,
1676                             0, 0, fd_head->reassembled_in);
1677                 }
1678         }
1679         return next_tvb;
1680 }
1681
1682 /*
1683  * Show a single fragment in a fragment subtree.
1684  */
1685 static void
1686 show_fragment(fragment_data *fd, int offset, const fragment_items *fit,
1687     proto_tree *ft, tvbuff_t *tvb)
1688 {
1689         proto_item *fei=NULL;
1690         int hf;
1691
1692         if (fd->flags & (FD_OVERLAPCONFLICT
1693                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
1694                 hf = *(fit->hf_fragment_error);
1695         } else {
1696                 hf = *(fit->hf_fragment);
1697         }
1698         if (fd->len == 0) {
1699                 fei = proto_tree_add_uint_format(ft, hf,
1700                         tvb, offset, fd->len,
1701                         fd->frame,
1702                         "Frame: %u (no data)",
1703                         fd->frame);
1704         } else {
1705                 fei = proto_tree_add_uint_format(ft, hf,
1706                         tvb, offset, fd->len,
1707                         fd->frame,
1708                         "Frame: %u, payload: %u-%u (%u bytes)",
1709                         fd->frame,
1710                         offset,
1711                         offset+fd->len-1,
1712                         fd->len);
1713         }
1714         PROTO_ITEM_SET_GENERATED(fei);
1715         if (fd->flags & (FD_OVERLAP|FD_OVERLAPCONFLICT
1716                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
1717                 /* this fragment has some flags set, create a subtree
1718                  * for it and display the flags.
1719                  */
1720                 proto_tree *fet=NULL;
1721
1722                 fet = proto_item_add_subtree(fei, *(fit->ett_fragment));
1723                 if (fd->flags&FD_OVERLAP) {
1724                         fei=proto_tree_add_boolean(fet,
1725                                 *(fit->hf_fragment_overlap),
1726                                 tvb, 0, 0,
1727                                 TRUE);
1728                         PROTO_ITEM_SET_GENERATED(fei);
1729                 }
1730                 if (fd->flags&FD_OVERLAPCONFLICT) {
1731                         fei=proto_tree_add_boolean(fet,
1732                                 *(fit->hf_fragment_overlap_conflict),
1733                                 tvb, 0, 0,
1734                                 TRUE);
1735                         PROTO_ITEM_SET_GENERATED(fei);
1736                 }
1737                 if (fd->flags&FD_MULTIPLETAILS) {
1738                         fei=proto_tree_add_boolean(fet,
1739                                 *(fit->hf_fragment_multiple_tails),
1740                                 tvb, 0, 0,
1741                                 TRUE);
1742                         PROTO_ITEM_SET_GENERATED(fei);
1743                 }
1744                 if (fd->flags&FD_TOOLONGFRAGMENT) {
1745                         fei=proto_tree_add_boolean(fet,
1746                                 *(fit->hf_fragment_too_long_fragment),
1747                                 tvb, 0, 0,
1748                                 TRUE);
1749                         PROTO_ITEM_SET_GENERATED(fei);
1750                 }
1751         }
1752 }
1753
1754 static gboolean
1755 show_fragment_errs_in_col(fragment_data *fd_head, const fragment_items *fit,
1756     packet_info *pinfo)
1757 {
1758         if (fd_head->flags & (FD_OVERLAPCONFLICT
1759                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
1760                 if (check_col(pinfo->cinfo, COL_INFO)) {
1761                         col_add_fstr(pinfo->cinfo, COL_INFO,
1762                                 "[Illegal %s]", fit->tag);
1763                         return TRUE;
1764                 }
1765         }
1766
1767         return FALSE;
1768 }
1769
1770 /* This function will build the fragment subtree; it's for fragments
1771    reassembled with "fragment_add()".
1772
1773    It will return TRUE if there were fragmentation errors
1774    or FALSE if fragmentation was ok.
1775 */
1776 gboolean
1777 show_fragment_tree(fragment_data *fd_head, const fragment_items *fit,
1778     proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb)
1779 {
1780         fragment_data *fd;
1781         proto_tree *ft;
1782         proto_item *fi;
1783
1784         /* It's not fragmented. */
1785         pinfo->fragmented = FALSE;
1786
1787         fi = proto_tree_add_item(tree, *(fit->hf_fragments),
1788             tvb, 0, -1, FALSE);
1789         PROTO_ITEM_SET_GENERATED(fi);
1790
1791         ft = proto_item_add_subtree(fi, *(fit->ett_fragments));
1792         for (fd = fd_head->next; fd != NULL; fd = fd->next)
1793                 show_fragment(fd, fd->offset, fit, ft, tvb);
1794
1795         return show_fragment_errs_in_col(fd_head, fit, pinfo);
1796 }
1797
1798 /* This function will build the fragment subtree; it's for fragments
1799    reassembled with "fragment_add_seq()" or "fragment_add_seq_check()".
1800
1801    It will return TRUE if there were fragmentation errors
1802    or FALSE if fragmentation was ok.
1803 */
1804 gboolean
1805 show_fragment_seq_tree(fragment_data *fd_head, const fragment_items *fit,
1806     proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb)
1807 {
1808         guint32 offset, next_offset;
1809         fragment_data *fd, *last_fd;
1810         proto_tree *ft;
1811         proto_item *fi;
1812
1813         /* It's not fragmented. */
1814         pinfo->fragmented = FALSE;
1815
1816         fi = proto_tree_add_item(tree, *(fit->hf_fragments),
1817             tvb, 0, -1, FALSE);
1818         PROTO_ITEM_SET_GENERATED(fi);
1819         ft = proto_item_add_subtree(fi, *(fit->ett_fragments));
1820         offset = 0;
1821         next_offset = 0;
1822         last_fd = NULL;
1823         for (fd = fd_head->next; fd != NULL; fd = fd->next){
1824                 if (last_fd == NULL || last_fd->offset != fd->offset) {
1825                         offset = next_offset;
1826                         next_offset += fd->len;
1827                 }
1828                 last_fd = fd;
1829                 show_fragment(fd, offset, fit, ft, tvb);
1830         }
1831
1832         return show_fragment_errs_in_col(fd_head, fit, pinfo);
1833 }