various code cleanup:
[obnox/wireshark/wip.git] / epan / 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 <epan/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         /*
480          * XXX - why not do all the stuff done early in "fragment_add_work()",
481          * turning off FD_DEFRAGMENTED and pointing the fragments' data
482          * pointers to the appropriate part of the already-reassembled
483          * data, and clearing the data length and "reassembled in" frame
484          * number, here?  We currently have a hack in the TCP dissector
485          * not to set the "reassembled in" value if the "partial reassembly"
486          * flag is set, so that in the first pass through the packets
487          * we don't falsely set a packet as reassembled in that packet
488          * if the dissector decided that even more reassembly was needed.
489          */
490         if(fd_head){
491                 fd_head->flags |= FD_PARTIAL_REASSEMBLY;
492         }
493 }
494
495 /*
496  * This function gets rid of an entry from a fragment table, given
497  * a pointer to the key for that entry; it also frees up the key
498  * and the addresses in it.
499  */
500 static void
501 fragment_unhash(GHashTable *fragment_table, fragment_key *key)
502 {
503         /*
504          * Remove the entry from the fragment table.
505          */
506         g_hash_table_remove(fragment_table, key);
507
508         /*
509          * Free up the copies of the addresses from the old key.
510          */
511         g_free((gpointer)key->src.data);
512         g_free((gpointer)key->dst.data);
513
514         /*
515          * Free the key itself.
516          */
517         g_mem_chunk_free(fragment_key_chunk, key);
518 }
519
520 /*
521  * This function adds fragment_data structure to a reassembled-packet
522  * hash table, using the frame numbers of each of the frames from
523  * which it was reassembled as keys, and sets the "reassembled_in"
524  * frame number.
525  */
526 static void
527 fragment_reassembled(fragment_data *fd_head, packet_info *pinfo,
528              GHashTable *reassembled_table, guint32 id)
529 {
530         reassembled_key *new_key;
531         fragment_data *fd;
532
533         if (fd_head->next == NULL) {
534                 /*
535                  * This was not fragmented, so there's no fragment
536                  * table; just hash it using the current frame number.
537                  */
538                 new_key = g_mem_chunk_alloc(reassembled_key_chunk);
539                 new_key->frame = pinfo->fd->num;
540                 new_key->id = id;
541                 g_hash_table_insert(reassembled_table, new_key, fd_head);
542         } else {
543                 /*
544                  * Hash it with the frame numbers for all the frames.
545                  */
546                 for (fd = fd_head->next; fd != NULL; fd = fd->next){
547                         new_key = g_mem_chunk_alloc(reassembled_key_chunk);
548                         new_key->frame = fd->frame;
549                         new_key->id = id;
550                         g_hash_table_insert(reassembled_table, new_key,
551                             fd_head);
552                 }
553         }
554         fd_head->flags |= FD_DEFRAGMENTED;
555         fd_head->reassembled_in = pinfo->fd->num;
556 }
557
558 /*
559  * This function adds a new fragment to the fragment hash table.
560  * If this is the first fragment seen for this datagram, a new entry
561  * is created in the hash table, otherwise this fragment is just added
562  * to the linked list of fragments for this packet.
563  * The list of fragments for a specific datagram is kept sorted for
564  * easier handling.
565  *
566  * Returns a pointer to the head of the fragment data list if we have all the
567  * fragments, NULL otherwise.
568  *
569  * This function assumes frag_offset being a byte offset into the defragment
570  * packet.
571  *
572  * 01-2002
573  * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be
574  * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set
575  * using fragment_set_partial_reassembly() before calling fragment_add
576  * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags
577  * are lowered when a new extension process is started.
578  */
579 static gboolean
580 fragment_add_work(fragment_data *fd_head, tvbuff_t *tvb, int offset,
581              packet_info *pinfo, guint32 frag_offset,
582              guint32 frag_data_len, gboolean more_frags)
583 {
584         fragment_data *fd;
585         fragment_data *fd_i;
586         guint32 max, dfpos;
587         unsigned char *old_data;
588
589         /* create new fd describing this fragment */
590         fd = g_mem_chunk_alloc(fragment_data_chunk);
591         fd->next = NULL;
592         fd->flags = 0;
593         fd->frame = pinfo->fd->num;
594         fd->offset = frag_offset;
595         fd->len  = frag_data_len;
596         fd->data = NULL;
597
598         /*
599          * If it was already defragmented and this new fragment goes beyond
600          * data limits, set flag in already empty fds & point old fds to malloc'ed data.
601          */
602         if(fd_head->flags & FD_DEFRAGMENTED && (frag_offset+frag_data_len) >= fd_head->datalen &&
603                 fd_head->flags & FD_PARTIAL_REASSEMBLY){
604                 for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){
605                         if( !fd_i->data ) {
606                                 fd_i->data = fd_head->data + fd_i->offset;
607                                 fd_i->flags |= FD_NOT_MALLOCED;
608                         }
609                         fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
610                 }
611                 fd_head->flags ^= FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY;
612                 fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
613                 fd_head->datalen=0;
614                 fd_head->reassembled_in=0;
615         }
616
617         if (!more_frags) {
618                 /*
619                  * This is the tail fragment in the sequence.
620                  */
621                 if (fd_head->datalen) {
622                         /* ok we have already seen other tails for this packet
623                          * it might be a duplicate.
624                          */
625                         if (fd_head->datalen != (fd->offset + fd->len) ){
626                                 /* Oops, this tail indicates a different packet
627                                  * len than the previous ones. Somethings wrong
628                                  */
629                                 fd->flags      |= FD_MULTIPLETAILS;
630                                 fd_head->flags |= FD_MULTIPLETAILS;
631                         }
632                 } else {
633                         /* this was the first tail fragment, now we know the
634                          * length of the packet
635                          */
636                         fd_head->datalen = fd->offset + fd->len;
637                 }
638         }
639
640
641
642
643         /* If the packet is already defragmented, this MUST be an overlap.
644          * The entire defragmented packet is in fd_head->data
645          * Even if we have previously defragmented this packet, we still check
646          * check it. Someone might play overlap and TTL games.
647          */
648         if (fd_head->flags & FD_DEFRAGMENTED) {
649                 fd->flags      |= FD_OVERLAP;
650                 fd_head->flags |= FD_OVERLAP;
651                 /* make sure its not too long */
652                 if (fd->offset + fd->len > fd_head->datalen) {
653                         fd->flags      |= FD_TOOLONGFRAGMENT;
654                         fd_head->flags |= FD_TOOLONGFRAGMENT;
655                         LINK_FRAG(fd_head,fd);
656                         return TRUE;
657                 }
658                 /* make sure it doesnt conflict with previous data */
659                 if ( memcmp(fd_head->data+fd->offset,
660                         tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
661                         fd->flags      |= FD_OVERLAPCONFLICT;
662                         fd_head->flags |= FD_OVERLAPCONFLICT;
663                         LINK_FRAG(fd_head,fd);
664                         return TRUE;
665                 }
666                 /* it was just an overlap, link it and return */
667                 LINK_FRAG(fd_head,fd);
668                 return TRUE;
669         }
670
671
672
673         /* If we have reached this point, the packet is not defragmented yet.
674          * Save all payload in a buffer until we can defragment.
675          * XXX - what if we didn't capture the entire fragment due
676          * to a too-short snapshot length?
677          */
678         fd->data = g_malloc(fd->len);
679         tvb_memcpy(tvb, fd->data, offset, fd->len);
680         LINK_FRAG(fd_head,fd);
681
682
683         if( !(fd_head->datalen) ){
684                 /* if we dont know the datalen, there are still missing
685                  * packets. Cheaper than the check below.
686                  */
687                 return FALSE;
688         }
689
690
691         /*
692          * Check if we have received the entire fragment.
693          * This is easy since the list is sorted and the head is faked.
694          *
695          * First, we compute the amount of contiguous data that's
696          * available.  (The check for fd_i->offset <= max rules out
697          * fragments that don't start before or at the end of the
698          * previous fragment, i.e. fragments that have a gap between
699          * them and the previous fragment.)
700          */
701         max = 0;
702         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
703                 if ( ((fd_i->offset)<=max) &&
704                     ((fd_i->offset+fd_i->len)>max) ){
705                         max = fd_i->offset+fd_i->len;
706                 }
707         }
708
709         if (max < (fd_head->datalen)) {
710                 /*
711                  * The amount of contiguous data we have is less than the
712                  * amount of data we're trying to reassemble, so we haven't
713                  * received all packets yet.
714                  */
715                 return FALSE;
716         }
717
718
719         if (max > (fd_head->datalen)) {
720                 /*XXX not sure if current fd was the TOOLONG*/
721                 /*XXX is it fair to flag current fd*/
722                 /* oops, too long fragment detected */
723                 fd->flags      |= FD_TOOLONGFRAGMENT;
724                 fd_head->flags |= FD_TOOLONGFRAGMENT;
725         }
726
727
728         /* we have received an entire packet, defragment it and
729          * free all fragments
730          */
731         /* store old data just in case */
732         old_data=fd_head->data;
733         fd_head->data = g_malloc(max);
734
735         /* add all data fragments */
736         for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) {
737                 if (fd_i->len) {
738                         if (fd_i->offset < dfpos) {
739                                 fd_i->flags    |= FD_OVERLAP;
740                                 fd_head->flags |= FD_OVERLAP;
741                                 if ( memcmp(fd_head->data+fd_i->offset,
742                                         fd_i->data,
743                                         MIN(fd_i->len,(dfpos-fd_i->offset))
744                                         ) ){
745                                         fd_i->flags    |= FD_OVERLAPCONFLICT;
746                                         fd_head->flags |= FD_OVERLAPCONFLICT;
747                                 }
748                         }
749                         /* dfpos is always >= than fd_i->offset */
750                         /* No gaps can exist here, max_loop(above) does this */
751                         /* XXX - true? Can we get fd_i->offset+fd-i->len */
752                         /* overflowing, for example? */
753                         if( fd_i->offset+fd_i->len > dfpos ) {
754                                 if (fd_i->offset+fd_i->len > max)
755                                         g_warning("Reassemble error in frame %u: offset %u + len %u > max %u",
756                                             pinfo->fd->num, fd_i->offset,
757                                             fd_i->len, max);
758                                 else if (dfpos < fd_i->offset)
759                                         g_warning("Reassemble error in frame %u: dfpos %u < offset %u",
760                                             pinfo->fd->num, dfpos, fd_i->offset);
761                                 else if (dfpos-fd_i->offset > fd_i->len)
762                                         g_warning("Reassemble error in frame %u: dfpos %u - offset %u > len %u",
763                                             pinfo->fd->num, dfpos, fd_i->offset,
764                                             fd_i->len);
765                                 else
766                                         memcpy(fd_head->data+dfpos,
767                                             fd_i->data+(dfpos-fd_i->offset),
768                                             fd_i->len-(dfpos-fd_i->offset));
769                         } else {
770                                 if (fd_i->offset+fd_i->len < fd_i->offset)
771                                         g_warning("Reassemble error in frame %u: offset %u + len %u < offset",
772                                             pinfo->fd->num, fd_i->offset,
773                                             fd_i->len);
774                         }
775                         if( fd_i->flags & FD_NOT_MALLOCED )
776                                 fd_i->flags &= ~FD_NOT_MALLOCED;
777                         else
778                                 g_free(fd_i->data);
779                         fd_i->data=NULL;
780
781                         dfpos=MAX(dfpos,(fd_i->offset+fd_i->len));
782                 }
783         }
784
785         if( old_data )
786                 g_free(old_data);
787         /* mark this packet as defragmented.
788            allows us to skip any trailing fragments */
789         fd_head->flags |= FD_DEFRAGMENTED;
790         fd_head->reassembled_in=pinfo->fd->num;
791
792         return TRUE;
793 }
794
795 static fragment_data *
796 fragment_add_common(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
797              GHashTable *fragment_table, guint32 frag_offset,
798              guint32 frag_data_len, gboolean more_frags,
799              gboolean check_already_added)
800 {
801         fragment_key key, *new_key;
802         fragment_data *fd_head;
803         fragment_data *fd_item;
804         gboolean already_added=pinfo->fd->flags.visited;
805
806         /* create key to search hash with */
807         key.src = pinfo->src;
808         key.dst = pinfo->dst;
809         key.id  = id;
810
811         fd_head = g_hash_table_lookup(fragment_table, &key);
812
813         /*
814          * "already_added" is true if "pinfo->fd->flags.visited" is true;
815          * if "pinfo->fd->flags.visited", this isn't the first pass, so
816          * we've already done all the reassembly and added all the
817          * fragments.
818          *
819          * If it's not true, but "check_already_added" is true, just check
820          * if we have seen this fragment before, i.e., if we have already
821          * added it to reassembly.
822          * That can be true even if "pinfo->fd->flags.visited" is false
823          * since we sometimes might call a subdissector multiple times.
824          * As an additional check, just make sure we have not already added 
825          * this frame to the reassembly list, if there is a reassembly list;
826          * note that the first item in the reassembly list is not a
827          * fragment, it's a data structure for the reassembled packet.
828          * We don't check it because its "frame" member isn't initialized
829          * to anything, and because it doesn't count in any case.
830          */
831         if (!already_added && check_already_added && fd_head != NULL) {
832                 for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){
833                         if(pinfo->fd->num==fd_item->frame){
834                                 already_added=TRUE;
835                         }
836                 }
837         }
838         /* have we already added this frame ?*/
839         if (already_added) {
840                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
841                         return fd_head;
842                 } else {
843                         return NULL;
844                 }
845         }
846
847         if (fd_head==NULL){
848                 /* not found, this must be the first snooped fragment for this
849                  * packet. Create list-head.
850                  */
851                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
852
853                 /* head/first structure in list only holds no other data than
854                  * 'datalen' then we don't have to change the head of the list
855                  * even if we want to keep it sorted
856                  */
857                 fd_head->next=NULL;
858                 fd_head->datalen=0;
859                 fd_head->offset=0;
860                 fd_head->len=0;
861                 fd_head->flags=0;
862                 fd_head->data=NULL;
863                 fd_head->reassembled_in=0;
864
865                 /*
866                  * We're going to use the key to insert the fragment,
867                  * so allocate a structure for it, and copy the
868                  * addresses, allocating new buffers for the address
869                  * data.
870                  */
871                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
872                 COPY_ADDRESS(&new_key->src, &key.src);
873                 COPY_ADDRESS(&new_key->dst, &key.dst);
874                 new_key->id = key.id;
875                 g_hash_table_insert(fragment_table, new_key, fd_head);
876         }
877
878         if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset,
879             frag_data_len, more_frags)) {
880                 /*
881                  * Reassembly is complete.
882                  */
883                 return fd_head;
884         } else {
885                 /*
886                  * Reassembly isn't complete.
887                  */
888                 return NULL;
889         }
890 }
891
892 fragment_data *
893 fragment_add(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
894              GHashTable *fragment_table, guint32 frag_offset,
895              guint32 frag_data_len, gboolean more_frags)
896 {
897         return fragment_add_common(tvb, offset, pinfo, id, fragment_table,
898             frag_offset, frag_data_len, more_frags, TRUE);
899 }
900
901 /*
902  * For use when you can have multiple fragments in the same frame added
903  * to the same reassembled PDU, e.g. with ONC RPC-over-TCP.
904  */
905 fragment_data *
906 fragment_add_multiple_ok(tvbuff_t *tvb, int offset, packet_info *pinfo,
907                          guint32 id, GHashTable *fragment_table,
908                          guint32 frag_offset, guint32 frag_data_len,
909                          gboolean more_frags)
910 {
911         return fragment_add_common(tvb, offset, pinfo, id, fragment_table,
912             frag_offset, frag_data_len, more_frags, FALSE);
913 }
914
915 fragment_data *
916 fragment_add_check(tvbuff_t *tvb, int offset, packet_info *pinfo,
917              guint32 id, GHashTable *fragment_table,
918              GHashTable *reassembled_table, guint32 frag_offset,
919              guint32 frag_data_len, gboolean more_frags)
920 {
921         reassembled_key reass_key;
922         fragment_key key, *new_key, *old_key;
923         gpointer orig_key, value;
924         fragment_data *fd_head;
925
926         /*
927          * If this isn't the first pass, look for this frame in the table
928          * of reassembled packets.
929          */
930         if (pinfo->fd->flags.visited) {
931                 reass_key.frame = pinfo->fd->num;
932                 reass_key.id = id;
933                 return g_hash_table_lookup(reassembled_table, &reass_key);
934         }
935
936         /* create key to search hash with */
937         key.src = pinfo->src;
938         key.dst = pinfo->dst;
939         key.id  = id;
940
941         if (!g_hash_table_lookup_extended(fragment_table, &key,
942                                           &orig_key, &value)) {
943                 /* not found, this must be the first snooped fragment for this
944                  * packet. Create list-head.
945                  */
946                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
947
948                 /* head/first structure in list only holds no other data than
949                  * 'datalen' then we don't have to change the head of the list
950                  * even if we want to keep it sorted
951                  */
952                 fd_head->next=NULL;
953                 fd_head->datalen=0;
954                 fd_head->offset=0;
955                 fd_head->len=0;
956                 fd_head->flags=0;
957                 fd_head->data=NULL;
958                 fd_head->reassembled_in=0;
959
960                 /*
961                  * We're going to use the key to insert the fragment,
962                  * so allocate a structure for it, and copy the
963                  * addresses, allocating new buffers for the address
964                  * data.
965                  */
966                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
967                 COPY_ADDRESS(&new_key->src, &key.src);
968                 COPY_ADDRESS(&new_key->dst, &key.dst);
969                 new_key->id = key.id;
970                 g_hash_table_insert(fragment_table, new_key, fd_head);
971
972                 orig_key = new_key;     /* for unhashing it later */
973         } else {
974                 /*
975                  * We found it.
976                  */
977                 fd_head = value;
978         }
979
980         /*
981          * If this is a short frame, then we can't, and don't, do
982          * reassembly on it.  We just give up.
983          */
984         if (tvb_reported_length(tvb) > tvb_length(tvb))
985                 return NULL;
986
987         if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset,
988             frag_data_len, more_frags)) {
989                 /*
990                  * Reassembly is complete.
991                  * Remove this from the table of in-progress
992                  * reassemblies, add it to the table of
993                  * reassembled packets, and return it.
994                  */
995
996                 /*
997                  * Remove this from the table of in-progress reassemblies,
998                  * and free up any memory used for it in that table.
999                  */
1000                 old_key = orig_key;
1001                 fragment_unhash(fragment_table, old_key);
1002
1003                 /*
1004                  * Add this item to the table of reassembled packets.
1005                  */
1006                 fragment_reassembled(fd_head, pinfo, reassembled_table, id);
1007                 return fd_head;
1008         } else {
1009                 /*
1010                  * Reassembly isn't complete.
1011                  */
1012                 return NULL;
1013         }
1014 }
1015
1016 /*
1017  * This function adds a new fragment to the entry for a reassembly
1018  * operation.
1019  *
1020  * The list of fragments for a specific datagram is kept sorted for
1021  * easier handling.
1022  *
1023  * Returns TRUE if we have all the fragments, FALSE otherwise.
1024  *
1025  * This function assumes frag_number being a block sequence number.
1026  * The bsn for the first block is 0.
1027  */
1028 static gboolean
1029 fragment_add_seq_work(fragment_data *fd_head, tvbuff_t *tvb, int offset,
1030              packet_info *pinfo, guint32 frag_number,
1031              guint32 frag_data_len, gboolean more_frags)
1032 {
1033         fragment_data *fd;
1034         fragment_data *fd_i;
1035         fragment_data *last_fd;
1036         guint32 max, dfpos, size;
1037
1038         /* create new fd describing this fragment */
1039         fd = g_mem_chunk_alloc(fragment_data_chunk);
1040         fd->next = NULL;
1041         fd->flags = 0;
1042         fd->frame = pinfo->fd->num;
1043         fd->offset = frag_number;
1044         fd->len  = frag_data_len;
1045         fd->data = NULL;
1046
1047         if (!more_frags) {
1048                 /*
1049                  * This is the tail fragment in the sequence.
1050                  */
1051                 if (fd_head->datalen) {
1052                         /* ok we have already seen other tails for this packet
1053                          * it might be a duplicate.
1054                          */
1055                         if (fd_head->datalen != fd->offset ){
1056                                 /* Oops, this tail indicates a different packet
1057                                  * len than the previous ones. Somethings wrong
1058                                  */
1059                                 fd->flags      |= FD_MULTIPLETAILS;
1060                                 fd_head->flags |= FD_MULTIPLETAILS;
1061                         }
1062                 } else {
1063                         /* this was the first tail fragment, now we know the
1064                          * sequence number of that fragment (which is NOT
1065                          * the length of the packet!)
1066                          */
1067                         fd_head->datalen = fd->offset;
1068                 }
1069         }
1070
1071         /* If the packet is already defragmented, this MUST be an overlap.
1072          * The entire defragmented packet is in fd_head->data
1073          * Even if we have previously defragmented this packet, we still check
1074          * check it. Someone might play overlap and TTL games.
1075          */
1076         if (fd_head->flags & FD_DEFRAGMENTED) {
1077                 fd->flags      |= FD_OVERLAP;
1078                 fd_head->flags |= FD_OVERLAP;
1079
1080                 /* make sure it's not past the end */
1081                 if (fd->offset > fd_head->datalen) {
1082                         /* new fragment comes after the end */
1083                         fd->flags      |= FD_TOOLONGFRAGMENT;
1084                         fd_head->flags |= FD_TOOLONGFRAGMENT;
1085                         LINK_FRAG(fd_head,fd);
1086                         return TRUE;
1087                 }
1088                 /* make sure it doesnt conflict with previous data */
1089                 dfpos=0;
1090                 last_fd=NULL;
1091                 for (fd_i=fd_head->next;fd_i->offset!=fd->offset;fd_i=fd_i->next) {
1092                   if (!last_fd || last_fd->offset!=fd_i->offset){
1093                     dfpos += fd_i->len;
1094                   }
1095                   last_fd=fd_i;
1096                 }
1097                 if(fd_i){
1098                         /* new fragment overlaps existing fragment */
1099                         if(fd_i->len!=fd->len){
1100                                 /*
1101                                  * They have different lengths; this
1102                                  * is definitely a conflict.
1103                                  */
1104                                 fd->flags      |= FD_OVERLAPCONFLICT;
1105                                 fd_head->flags |= FD_OVERLAPCONFLICT;
1106                                 LINK_FRAG(fd_head,fd);
1107                                 return TRUE;
1108                         }
1109                         DISSECTOR_ASSERT(fd_head->len >= dfpos + fd->len);
1110                         if ( memcmp(fd_head->data+dfpos,
1111                             tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
1112                                 /*
1113                                  * They have the same length, but the
1114                                  * data isn't the same.
1115                                  */
1116                                 fd->flags      |= FD_OVERLAPCONFLICT;
1117                                 fd_head->flags |= FD_OVERLAPCONFLICT;
1118                                 LINK_FRAG(fd_head,fd);
1119                                 return TRUE;
1120                         }
1121                         /* it was just an overlap, link it and return */
1122                         LINK_FRAG(fd_head,fd);
1123                         return TRUE;
1124                 } else {
1125                         /*
1126                          * New fragment doesn't overlap an existing
1127                          * fragment - there was presumably a gap in
1128                          * the sequence number space.
1129                          *
1130                          * XXX - what should we do here?  Is it always
1131                          * the case that there are no gaps, or are there
1132                          * protcols using sequence numbers where there
1133                          * can be gaps?
1134                          *
1135                          * If the former, the check below for having
1136                          * received all the fragments should check for
1137                          * holes in the sequence number space and for the
1138                          * first sequence number being 0.  If we do that,
1139                          * the only way we can get here is if this fragment
1140                          * is past the end of the sequence number space -
1141                          * but the check for "fd->offset > fd_head->datalen"
1142                          * would have caught that above, so it can't happen.
1143                          *
1144                          * If the latter, we don't have a good way of
1145                          * knowing whether reassembly is complete if we
1146                          * get packet out of order such that the "last"
1147                          * fragment doesn't show up last - but, unless
1148                          * in-order reliable delivery of fragments is
1149                          * guaranteed, an implementation of the protocol
1150                          * has no way of knowing whether reassembly is
1151                          * complete, either.
1152                          *
1153                          * For now, we just link the fragment in and
1154                          * return.
1155                          */
1156                         LINK_FRAG(fd_head,fd);
1157                         return TRUE;
1158                 }
1159         }
1160
1161         /* If we have reached this point, the packet is not defragmented yet.
1162          * Save all payload in a buffer until we can defragment.
1163          * XXX - what if we didn't capture the entire fragment due
1164          * to a too-short snapshot length?
1165          */
1166         fd->data = g_malloc(fd->len);
1167         tvb_memcpy(tvb, fd->data, offset, fd->len);
1168         LINK_FRAG(fd_head,fd);
1169
1170
1171         if( !(fd_head->datalen) ){
1172                 /* if we dont know the sequence number of the last fragment,
1173                  * there are definitely still missing packets. Cheaper than
1174                  * the check below.
1175                  */
1176                 return FALSE;
1177         }
1178
1179
1180         /* check if we have received the entire fragment
1181          * this is easy since the list is sorted and the head is faked.
1182          */
1183         max = 0;
1184         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1185           if ( fd_i->offset==max ){
1186             max++;
1187           }
1188         }
1189         /* max will now be datalen+1 if all fragments have been seen */
1190
1191         if (max <= fd_head->datalen) {
1192                 /* we have not received all packets yet */
1193                 return FALSE;
1194         }
1195
1196
1197         if (max > (fd_head->datalen+1)) {
1198                 /* oops, too long fragment detected */
1199                 fd->flags      |= FD_TOOLONGFRAGMENT;
1200                 fd_head->flags |= FD_TOOLONGFRAGMENT;
1201         }
1202
1203
1204         /* we have received an entire packet, defragment it and
1205          * free all fragments
1206          */
1207         size=0;
1208         last_fd=NULL;
1209         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1210           if(!last_fd || last_fd->offset!=fd_i->offset){
1211             size+=fd_i->len;
1212           }
1213           last_fd=fd_i;
1214         }
1215         fd_head->data = g_malloc(size);
1216         fd_head->len = size;            /* record size for caller       */
1217
1218         /* add all data fragments */
1219         dfpos = 0;
1220         last_fd=NULL;
1221         for (fd_i=fd_head->next;fd_i && fd_i->len + dfpos <= size;fd_i=fd_i->next) {
1222           if (fd_i->len) {
1223             if(!last_fd || last_fd->offset!=fd_i->offset){
1224               memcpy(fd_head->data+dfpos,fd_i->data,fd_i->len);
1225               dfpos += fd_i->len;
1226             } else {
1227               /* duplicate/retransmission/overlap */
1228               fd_i->flags    |= FD_OVERLAP;
1229               fd_head->flags |= FD_OVERLAP;
1230               if( (last_fd->len!=fd_i->datalen)
1231                   || memcmp(last_fd->data, fd_i->data, last_fd->len) ){
1232                         fd->flags      |= FD_OVERLAPCONFLICT;
1233                         fd_head->flags |= FD_OVERLAPCONFLICT;
1234               }
1235             }
1236           }
1237           last_fd=fd_i;
1238         }
1239
1240         /* we have defragmented the pdu, now free all fragments*/
1241         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
1242           if(fd_i->data){
1243             g_free(fd_i->data);
1244             fd_i->data=NULL;
1245           }
1246         }
1247
1248         /* mark this packet as defragmented.
1249            allows us to skip any trailing fragments */
1250         fd_head->flags |= FD_DEFRAGMENTED;
1251         fd_head->reassembled_in=pinfo->fd->num;
1252
1253         return TRUE;
1254 }
1255
1256 /*
1257  * This function adds a new fragment to the fragment hash table.
1258  * If this is the first fragment seen for this datagram, a new entry
1259  * is created in the hash table, otherwise this fragment is just added
1260  * to the linked list of fragments for this packet.
1261  *
1262  * Returns a pointer to the head of the fragment data list if we have all the
1263  * fragments, NULL otherwise.
1264  *
1265  * This function assumes frag_number being a block sequence number.
1266  * The bsn for the first block is 0.
1267  */
1268 fragment_data *
1269 fragment_add_seq(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
1270              GHashTable *fragment_table, guint32 frag_number,
1271              guint32 frag_data_len, gboolean more_frags)
1272 {
1273         fragment_key key, *new_key;
1274         fragment_data *fd_head;
1275
1276         /* create key to search hash with */
1277         key.src = pinfo->src;
1278         key.dst = pinfo->dst;
1279         key.id  = id;
1280
1281         fd_head = g_hash_table_lookup(fragment_table, &key);
1282
1283         /* have we already seen this frame ?*/
1284         if (pinfo->fd->flags.visited) {
1285                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
1286                         return fd_head;
1287                 } else {
1288                         return NULL;
1289                 }
1290         }
1291
1292         if (fd_head==NULL){
1293                 /* not found, this must be the first snooped fragment for this
1294                  * packet. Create list-head.
1295                  */
1296                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
1297
1298                 /* head/first structure in list only holds no other data than
1299                  * 'datalen' then we don't have to change the head of the list
1300                  * even if we want to keep it sorted
1301                  */
1302                 fd_head->next=NULL;
1303                 fd_head->datalen=0;
1304                 fd_head->offset=0;
1305                 fd_head->len=0;
1306                 fd_head->flags=FD_BLOCKSEQUENCE;
1307                 fd_head->data=NULL;
1308                 fd_head->reassembled_in=0;
1309
1310                 /*
1311                  * We're going to use the key to insert the fragment,
1312                  * so allocate a structure for it, and copy the
1313                  * addresses, allocating new buffers for the address
1314                  * data.
1315                  */
1316                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
1317                 COPY_ADDRESS(&new_key->src, &key.src);
1318                 COPY_ADDRESS(&new_key->dst, &key.dst);
1319                 new_key->id = key.id;
1320                 g_hash_table_insert(fragment_table, new_key, fd_head);
1321         }
1322
1323         if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1324                                   frag_number, frag_data_len, more_frags)) {
1325                 /*
1326                  * Reassembly is complete.
1327                  */
1328                 return fd_head;
1329         } else {
1330                 /*
1331                  * Reassembly isn't complete.
1332                  */
1333                 return NULL;
1334         }
1335 }
1336
1337 fragment_data *
1338 fragment_add_dcerpc(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
1339                     void *v_act_id,
1340                     GHashTable *fragment_table, guint32 frag_number,
1341                     guint32 frag_data_len, gboolean more_frags)
1342 {
1343        dcerpc_fragment_key key, *new_key;
1344        fragment_data *fd_head;
1345        e_uuid_t *act_id = (e_uuid_t *)v_act_id;
1346
1347        /* create key to search hash with */
1348        key.src = pinfo->src;
1349        key.dst = pinfo->dst;
1350        key.id  = id;
1351        key.act_id  = *act_id;
1352
1353        fd_head = g_hash_table_lookup(fragment_table, &key);
1354
1355        /* have we already seen this frame ?*/
1356        if (pinfo->fd->flags.visited) {
1357                if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
1358                        return fd_head;
1359                } else {
1360                        return NULL;
1361                }
1362        }
1363
1364        if (fd_head==NULL){
1365                /* not found, this must be the first snooped fragment for this
1366                  * packet. Create list-head.
1367                 */
1368                fd_head=g_mem_chunk_alloc(fragment_data_chunk);
1369
1370                /* head/first structure in list only holds no other data than
1371                  * 'datalen' then we don't have to change the head of the list
1372                  * even if we want to keep it sorted
1373                  */
1374                fd_head->next=NULL;
1375                fd_head->datalen=0;
1376                fd_head->offset=0;
1377                fd_head->len=0;
1378                fd_head->flags=FD_BLOCKSEQUENCE;
1379                fd_head->data=NULL;
1380                fd_head->reassembled_in=0;
1381
1382                /*
1383                 * We're going to use the key to insert the fragment,
1384                 * so allocate a structure for it, and copy the
1385                 * addresses, allocating new buffers for the address
1386                 * data.
1387                 */
1388                new_key = g_mem_chunk_alloc(dcerpc_fragment_key_chunk);
1389                COPY_ADDRESS(&new_key->src, &key.src);
1390                COPY_ADDRESS(&new_key->dst, &key.dst);
1391                new_key->id = key.id;
1392                new_key->act_id = key.act_id;
1393                g_hash_table_insert(fragment_table, new_key, fd_head);
1394        }
1395
1396        if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1397                                  frag_number, frag_data_len, more_frags)) {
1398                /*
1399                 * Reassembly is complete.
1400                 */
1401                return fd_head;
1402        } else {
1403                /*
1404                 * Reassembly isn't complete.
1405                 */
1406                return NULL;
1407        }
1408 }
1409
1410 /*
1411  * This does the work for "fragment_add_seq_check()" and
1412  * "fragment_add_seq_next()".
1413  *
1414  * This function assumes frag_number being a block sequence number.
1415  * The bsn for the first block is 0.
1416  *
1417  * If "no_frag_number" is TRUE, it uses the next expected fragment number
1418  * as the fragment number if there is a reassembly in progress, otherwise
1419  * it uses 0.
1420  *
1421  * If "no_frag_number" is FALSE, it uses the "frag_number" argument as
1422  * the fragment number.
1423  *
1424  * If this is the first fragment seen for this datagram, a new
1425  * "fragment_data" structure is allocated to refer to the reassembled,
1426  * packet, and:
1427  *
1428  *      if "more_frags" is false and "frag_802_11_hack" is true, the
1429  *      structure is not added to the hash table, and not given any
1430  *      fragments to refer to, but is just returned - this is a special
1431  *      hack for the 802.11 dissector (see packet-80211.c);
1432  *
1433  *      otherwise, this fragment is added to the linked list of fragments
1434  *      for this packet, and the "fragment_data" structure is put into
1435  *      the hash table.
1436  *
1437  * Otherwise, this fragment is just added to the linked list of fragments
1438  * for this packet.
1439  *
1440  * If, after processing this fragment, we have all the fragments,
1441  * "fragment_add_seq_check_work()" removes that from the fragment hash
1442  * table if necessary and adds it to the table of reassembled fragments,
1443  * and returns a pointer to the head of the fragment list.
1444  *
1445  * If this is the first fragment we've seen, and "more_frags" is false
1446  * and "frag_802_11_hack" is true, "fragment_add_seq_check_work()" does
1447  * nothing to the fragment data list, and returns a pointer to the head
1448  * of that (empty) list.
1449  *
1450  * Otherwise, it returns NULL.
1451  */
1452 static fragment_data *
1453 fragment_add_seq_check_work(tvbuff_t *tvb, int offset, packet_info *pinfo,
1454              guint32 id, GHashTable *fragment_table,
1455              GHashTable *reassembled_table, guint32 frag_number,
1456              guint32 frag_data_len, gboolean more_frags,
1457              gboolean no_frag_number, gboolean frag_802_11_hack)
1458 {
1459         reassembled_key reass_key;
1460         fragment_key key, *new_key, *old_key;
1461         gpointer orig_key, value;
1462         fragment_data *fd_head, *fd;
1463
1464         /*
1465          * Have we already seen this frame?
1466          * If so, look for it in the table of reassembled packets.
1467          */
1468         if (pinfo->fd->flags.visited) {
1469                 reass_key.frame = pinfo->fd->num;
1470                 reass_key.id = id;
1471                 return g_hash_table_lookup(reassembled_table, &reass_key);
1472         }
1473
1474         /* create key to search hash with */
1475         key.src = pinfo->src;
1476         key.dst = pinfo->dst;
1477         key.id  = id;
1478
1479         if (!g_hash_table_lookup_extended(fragment_table, &key,
1480                                           &orig_key, &value)) {
1481                 /* not found, this must be the first snooped fragment for this
1482                  * packet. Create list-head.
1483                  */
1484                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
1485
1486                 /* head/first structure in list only holds no other data than
1487                  * 'datalen' then we don't have to change the head of the list
1488                  * even if we want to keep it sorted
1489                  */
1490                 fd_head->next=NULL;
1491                 fd_head->datalen=0;
1492                 fd_head->offset=0;
1493                 fd_head->len=0;
1494                 fd_head->flags=FD_BLOCKSEQUENCE;
1495                 fd_head->data=NULL;
1496                 fd_head->reassembled_in=0;
1497
1498                 if ((no_frag_number || frag_802_11_hack) && !more_frags) {
1499                         /*
1500                          * This is the last fragment for this packet, and
1501                          * is the only one we've seen.
1502                          *
1503                          * Either we don't have sequence numbers, in which
1504                          * case we assume this is the first fragment for
1505                          * this packet, or we're doing special 802.11
1506                          * processing, in which case we assume it's one
1507                          * of those reassembled packets with a non-zero
1508                          * fragment number (see packet-80211.c); just
1509                          * add the fragment to the table of reassembled
1510                          * packets, and return a pointer to the head of
1511                          * the list.
1512                          */
1513                         fragment_reassembled(fd_head, pinfo,
1514                                reassembled_table, id);
1515                         return fd_head;
1516                 }
1517
1518                 /*
1519                  * We're going to use the key to insert the fragment,
1520                  * so allocate a structure for it, and copy the
1521                  * addresses, allocating new buffers for the address
1522                  * data.
1523                  */
1524                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
1525                 COPY_ADDRESS(&new_key->src, &key.src);
1526                 COPY_ADDRESS(&new_key->dst, &key.dst);
1527                 new_key->id = key.id;
1528                 g_hash_table_insert(fragment_table, new_key, fd_head);
1529
1530                 orig_key = new_key;     /* for unhashing it later */
1531
1532                 /*
1533                  * If we weren't given an initial fragment number,
1534                  * make it 0.
1535                  */
1536                 if (no_frag_number)
1537                         frag_number = 0;
1538         } else {
1539                 /*
1540                  * We found it.
1541                  */
1542                 fd_head = value;
1543
1544                 /*
1545                  * If we weren't given an initial fragment number,
1546                  * use the next expected fragment number as the fragment
1547                  * number for this fragment.
1548                  */
1549                 if (no_frag_number) {
1550                         for (fd = fd_head; fd != NULL; fd = fd->next) {
1551                                 if (fd->next == NULL)
1552                                         frag_number = fd->offset + 1;
1553                         }
1554                 }
1555         }
1556
1557         /*
1558          * If we don't have all the data that is in this fragment,
1559          * then we can't, and don't, do reassembly on it.
1560          *
1561          * If it's the first frame, handle it as an unfragmented packet.
1562          * Otherwise, just handle it as a fragment.
1563          *
1564          * If "more_frags" isn't set, we get rid of the entry in the
1565          * hash table for this reassembly, as we don't need it any more.
1566          */
1567         if (!tvb_bytes_exist(tvb, offset, frag_data_len)) {
1568                 if (!more_frags) {
1569                         /*
1570                          * Remove this from the table of in-progress
1571                          * reassemblies, and free up any memory used for
1572                          * it in that table.
1573                          */
1574                         old_key = orig_key;
1575                         fragment_unhash(fragment_table, old_key);
1576                 }
1577                 return frag_number == 0 ? fd_head : NULL;
1578         }
1579
1580         if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1581                                   frag_number, frag_data_len, more_frags)) {
1582                 /*
1583                  * Reassembly is complete.
1584                  * Remove this from the table of in-progress
1585                  * reassemblies, add it to the table of
1586                  * reassembled packets, and return it.
1587                  */
1588
1589                 /*
1590                  * Remove this from the table of in-progress reassemblies,
1591                  * and free up any memory used for it in that table.
1592                  */
1593                 old_key = orig_key;
1594                 fragment_unhash(fragment_table, old_key);
1595
1596                 /*
1597                  * Add this item to the table of reassembled packets.
1598                  */
1599                 fragment_reassembled(fd_head, pinfo, reassembled_table, id);
1600                 return fd_head;
1601         } else {
1602                 /*
1603                  * Reassembly isn't complete.
1604                  */
1605                 return NULL;
1606         }
1607 }
1608
1609 fragment_data *
1610 fragment_add_seq_check(tvbuff_t *tvb, int offset, packet_info *pinfo,
1611              guint32 id, GHashTable *fragment_table,
1612              GHashTable *reassembled_table, guint32 frag_number,
1613              guint32 frag_data_len, gboolean more_frags)
1614 {
1615         return fragment_add_seq_check_work(tvb, offset, pinfo, id,
1616             fragment_table, reassembled_table, frag_number, frag_data_len,
1617             more_frags, FALSE, FALSE);
1618 }
1619
1620 fragment_data *
1621 fragment_add_seq_802_11(tvbuff_t *tvb, int offset, packet_info *pinfo,
1622              guint32 id, GHashTable *fragment_table,
1623              GHashTable *reassembled_table, guint32 frag_number,
1624              guint32 frag_data_len, gboolean more_frags)
1625 {
1626         return fragment_add_seq_check_work(tvb, offset, pinfo, id,
1627             fragment_table, reassembled_table, frag_number, frag_data_len,
1628             more_frags, FALSE, TRUE);
1629 }
1630
1631 fragment_data *
1632 fragment_add_seq_next(tvbuff_t *tvb, int offset, packet_info *pinfo,
1633              guint32 id, GHashTable *fragment_table,
1634              GHashTable *reassembled_table, guint32 frag_data_len,
1635              gboolean more_frags)
1636 {
1637         return fragment_add_seq_check_work(tvb, offset, pinfo, id,
1638             fragment_table, reassembled_table, 0, frag_data_len,
1639             more_frags, TRUE, FALSE);
1640 }
1641
1642 /*
1643  * Process reassembled data; if we're on the frame in which the data
1644  * was reassembled, put the fragment information into the protocol
1645  * tree, and construct a tvbuff with the reassembled data, otherwise
1646  * just put a "reassembled in" item into the protocol tree.
1647  */
1648 tvbuff_t *
1649 process_reassembled_data(tvbuff_t *tvb, int offset, packet_info *pinfo,
1650     const char *name, fragment_data *fd_head, const fragment_items *fit,
1651     gboolean *update_col_infop, proto_tree *tree)
1652 {
1653         tvbuff_t *next_tvb;
1654         gboolean update_col_info;
1655         proto_item *frag_tree_item;
1656
1657         if (fd_head != NULL && pinfo->fd->num == fd_head->reassembled_in) {
1658                 /*
1659                  * OK, we've reassembled this.
1660                  * Is this something that's been reassembled from more
1661                  * than one fragment?
1662                  */
1663                 if (fd_head->next != NULL) {
1664                         /*
1665                          * Yes.
1666                          * Allocate a new tvbuff, referring to the
1667                          * reassembled payload.
1668                          */
1669                         if (fd_head->flags & FD_BLOCKSEQUENCE) {
1670                                 next_tvb = tvb_new_real_data(fd_head->data,
1671                                       fd_head->len, fd_head->len);
1672                         } else {
1673                                 next_tvb = tvb_new_real_data(fd_head->data,
1674                                       fd_head->datalen, fd_head->datalen);
1675                         }
1676
1677                         /*
1678                          * Add the tvbuff to the list of tvbuffs to which
1679                          * the tvbuff we were handed refers, so it'll get
1680                          * cleaned up when that tvbuff is cleaned up.
1681                          */
1682                         tvb_set_child_real_data_tvbuff(tvb, next_tvb);
1683
1684                         /* Add the defragmented data to the data source list. */
1685                         add_new_data_source(pinfo, next_tvb, name);
1686
1687                         /* show all fragments */
1688                         if (fd_head->flags & FD_BLOCKSEQUENCE) {
1689                                 update_col_info = !show_fragment_seq_tree(
1690                                     fd_head, fit,  tree, pinfo, next_tvb, &frag_tree_item);
1691                         } else {
1692                                 update_col_info = !show_fragment_tree(fd_head,
1693                                     fit, tree, pinfo, next_tvb, &frag_tree_item);
1694                         }
1695                 } else {
1696                         /*
1697                          * No.
1698                          * Return a tvbuff with the payload.
1699                          */
1700                         next_tvb = tvb_new_subset(tvb, offset, -1, -1);
1701                         pinfo->fragmented = FALSE;      /* one-fragment packet */
1702                         update_col_info = TRUE;
1703                 }
1704                 if (update_col_infop != NULL)
1705                         *update_col_infop = update_col_info;
1706         } else {
1707                 /*
1708                  * We don't have the complete reassembled payload, or this
1709                  * isn't the final frame of that payload.
1710                  */
1711                 next_tvb = NULL;
1712
1713                 /*
1714                  * If we know what frame this was reassembled in,
1715                  * and if there's a field to use for the number of
1716                  * the frame in which the packet was reassembled,
1717                  * add it to the protocol tree.
1718                  */
1719                 if (fd_head != NULL && fit->hf_reassembled_in != NULL) {
1720                         proto_tree_add_uint(tree,
1721                             *(fit->hf_reassembled_in), tvb,
1722                             0, 0, fd_head->reassembled_in);
1723                 }
1724         }
1725         return next_tvb;
1726 }
1727
1728 /*
1729  * Show a single fragment in a fragment subtree, and put information about
1730  * it in the top-level item for that subtree.
1731  */
1732 static void
1733 show_fragment(fragment_data *fd, int offset, const fragment_items *fit,
1734     proto_tree *ft, proto_item *fi, gboolean first_frag, tvbuff_t *tvb)
1735 {
1736         proto_item *fei=NULL;
1737         int hf;
1738
1739         if (first_frag)
1740                 proto_item_append_text(fi, " (%u bytes): ", tvb_length(tvb));
1741         else
1742                 proto_item_append_text(fi, ", ");
1743         proto_item_append_text(fi, "#%u(%u)", fd->frame, fd->len);
1744
1745         if (fd->flags & (FD_OVERLAPCONFLICT
1746                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
1747                 hf = *(fit->hf_fragment_error);
1748         } else {
1749                 hf = *(fit->hf_fragment);
1750         }
1751         if (fd->len == 0) {
1752                 fei = proto_tree_add_uint_format(ft, hf,
1753                         tvb, offset, fd->len,
1754                         fd->frame,
1755                         "Frame: %u (no data)",
1756                         fd->frame);
1757         } else {
1758                 fei = proto_tree_add_uint_format(ft, hf,
1759                         tvb, offset, fd->len,
1760                         fd->frame,
1761                         "Frame: %u, payload: %u-%u (%u bytes)",
1762                         fd->frame,
1763                         offset,
1764                         offset+fd->len-1,
1765                         fd->len);
1766         }
1767         PROTO_ITEM_SET_GENERATED(fei);
1768         if (fd->flags & (FD_OVERLAP|FD_OVERLAPCONFLICT
1769                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
1770                 /* this fragment has some flags set, create a subtree
1771                  * for it and display the flags.
1772                  */
1773                 proto_tree *fet=NULL;
1774
1775                 fet = proto_item_add_subtree(fei, *(fit->ett_fragment));
1776                 if (fd->flags&FD_OVERLAP) {
1777                         fei=proto_tree_add_boolean(fet,
1778                                 *(fit->hf_fragment_overlap),
1779                                 tvb, 0, 0,
1780                                 TRUE);
1781                         PROTO_ITEM_SET_GENERATED(fei);
1782                 }
1783                 if (fd->flags&FD_OVERLAPCONFLICT) {
1784                         fei=proto_tree_add_boolean(fet,
1785                                 *(fit->hf_fragment_overlap_conflict),
1786                                 tvb, 0, 0,
1787                                 TRUE);
1788                         PROTO_ITEM_SET_GENERATED(fei);
1789                 }
1790                 if (fd->flags&FD_MULTIPLETAILS) {
1791                         fei=proto_tree_add_boolean(fet,
1792                                 *(fit->hf_fragment_multiple_tails),
1793                                 tvb, 0, 0,
1794                                 TRUE);
1795                         PROTO_ITEM_SET_GENERATED(fei);
1796                 }
1797                 if (fd->flags&FD_TOOLONGFRAGMENT) {
1798                         fei=proto_tree_add_boolean(fet,
1799                                 *(fit->hf_fragment_too_long_fragment),
1800                                 tvb, 0, 0,
1801                                 TRUE);
1802                         PROTO_ITEM_SET_GENERATED(fei);
1803                 }
1804         }
1805 }
1806
1807 static gboolean
1808 show_fragment_errs_in_col(fragment_data *fd_head, const fragment_items *fit,
1809     packet_info *pinfo)
1810 {
1811         if (fd_head->flags & (FD_OVERLAPCONFLICT
1812                 |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) {
1813                 if (check_col(pinfo->cinfo, COL_INFO)) {
1814                         col_add_fstr(pinfo->cinfo, COL_INFO,
1815                                 "[Illegal %s]", fit->tag);
1816                         return TRUE;
1817                 }
1818         }
1819
1820         return FALSE;
1821 }
1822
1823 /* This function will build the fragment subtree; it's for fragments
1824    reassembled with "fragment_add()".
1825
1826    It will return TRUE if there were fragmentation errors
1827    or FALSE if fragmentation was ok.
1828 */
1829 gboolean
1830 show_fragment_tree(fragment_data *fd_head, const fragment_items *fit,
1831     proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi)
1832 {
1833         fragment_data *fd;
1834         proto_tree *ft;
1835         gboolean first_frag;
1836
1837         /* It's not fragmented. */
1838         pinfo->fragmented = FALSE;
1839
1840         *fi = proto_tree_add_item(tree, *(fit->hf_fragments),
1841             tvb, 0, -1, FALSE);
1842         PROTO_ITEM_SET_GENERATED(*fi);
1843
1844         ft = proto_item_add_subtree(*fi, *(fit->ett_fragments));
1845         first_frag = TRUE;
1846         for (fd = fd_head->next; fd != NULL; fd = fd->next) {
1847                 show_fragment(fd, fd->offset, fit, ft, *fi, first_frag, tvb);
1848                 first_frag = FALSE;
1849         }
1850
1851         return show_fragment_errs_in_col(fd_head, fit, pinfo);
1852 }
1853
1854 /* This function will build the fragment subtree; it's for fragments
1855    reassembled with "fragment_add_seq()" or "fragment_add_seq_check()".
1856
1857    It will return TRUE if there were fragmentation errors
1858    or FALSE if fragmentation was ok.
1859 */
1860 gboolean
1861 show_fragment_seq_tree(fragment_data *fd_head, const fragment_items *fit,
1862     proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi)
1863 {
1864         guint32 offset, next_offset;
1865         fragment_data *fd, *last_fd;
1866         proto_tree *ft;
1867         gboolean first_frag;
1868
1869         /* It's not fragmented. */
1870         pinfo->fragmented = FALSE;
1871
1872         *fi = proto_tree_add_item(tree, *(fit->hf_fragments),
1873             tvb, 0, -1, FALSE);
1874         PROTO_ITEM_SET_GENERATED(*fi);
1875
1876         ft = proto_item_add_subtree(*fi, *(fit->ett_fragments));
1877         offset = 0;
1878         next_offset = 0;
1879         last_fd = NULL;
1880         first_frag = TRUE;
1881         for (fd = fd_head->next; fd != NULL; fd = fd->next){
1882                 if (last_fd == NULL || last_fd->offset != fd->offset) {
1883                         offset = next_offset;
1884                         next_offset += fd->len;
1885                 }
1886                 last_fd = fd;
1887                 show_fragment(fd, offset, fit, ft, *fi, first_frag, tvb);
1888                 first_frag = FALSE;
1889         }
1890
1891         return show_fragment_errs_in_col(fd_head, fit, pinfo);
1892 }