The first byte of the frame header in atmsnoop does, in fact, contain an
[obnox/wireshark/wip.git] / reassemble.c
1 /* reassemble.c
2  * Routines for {fragment,segment} reassembly
3  *
4  * $Id: reassemble.c,v 1.17 2002/04/25 21:28:15 guy Exp $
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 typedef struct _fragment_key {
36         address src;
37         address dst;
38         guint32 id;
39 } fragment_key;
40
41 static GMemChunk *fragment_key_chunk = NULL;
42 static GMemChunk *fragment_data_chunk = NULL;
43 static int fragment_init_count = 200;
44
45 #define LINK_FRAG(fd_head,fd)                                   \
46         {       fragment_data *fd_i;                            \
47                 /* add fragment to list, keep list sorted */            \
48                 for(fd_i=(fd_head);fd_i->next;fd_i=fd_i->next){ \
49                         if( ((fd)->offset) < (fd_i->next->offset) )     \
50                                 break;                                  \
51                 }                                                       \
52                 (fd)->next=fd_i->next;                          \
53                 fd_i->next=(fd);                                        \
54         }
55
56 static gint
57 fragment_equal(gconstpointer k1, gconstpointer k2)
58 {
59         fragment_key* key1 = (fragment_key*) k1;
60         fragment_key* key2 = (fragment_key*) k2;
61
62         /*key.id is the first item to compare since item is most
63           likely to differ between sessions, thus shortcircuiting
64           the comparasion of addresses.
65         */
66         return ( ( (key1->id    == key2->id) &&
67                    (ADDRESSES_EQUAL(&key1->src, &key2->src)) &&
68                    (ADDRESSES_EQUAL(&key1->dst, &key2->dst))
69                  ) ?
70                  TRUE : FALSE);
71 }
72
73 static guint
74 fragment_hash(gconstpointer k)
75 {
76         fragment_key* key = (fragment_key*) k;
77         guint hash_val;
78 /*
79         int i;
80 */
81
82         hash_val = 0;
83
84 /*      More than likely: in most captures src and dst addresses are the
85         same, and would hash the same.
86         We only use id as the hash as an optimization.
87
88         for (i = 0; i < key->src.len; i++)
89                 hash_val += key->src.data[i];
90         for (i = 0; i < key->dst.len; i++)
91                 hash_val += key->dst.data[i];
92 */
93
94         hash_val += key->id;
95
96         return hash_val;
97 }
98
99 /*
100  * XXX - we use the frame_data structure for a frame as the key
101  * structure, with the frame number as the item compared.
102  *
103  * This won't work if there's more than one form of reassembly using
104  * the reassembled-packet hash tables going on in the frame, and two
105  * or more are using the same protocol and thus the same hash table.
106  *
107  * We could use the addresses, or the reassembly ID, to distinguish
108  * between the reassemblies, if necessary.
109  *
110  * Hopefully, we won't see anything perverse such as that (say, some
111  * form of IP-in-IP tunneling, with fragments of an IP datagram
112  * tunneled inside IP datagrams that are themselves fragmented).
113  */
114 static gint
115 reassembled_equal(gconstpointer k1, gconstpointer k2)
116 {
117         frame_data* key1 = (frame_data*) k1;
118         frame_data* key2 = (frame_data*) k2;
119
120         return (key1->num == key2->num);
121 }
122
123 static guint
124 reassembled_hash(gconstpointer k)
125 {
126         frame_data* key = (frame_data*) k;
127
128         return key->num;
129 }
130
131 /*
132  * For a fragment hash table entry, free the address data to which the key
133  * refers and the fragment data to which the value refers.
134  * (The actual key and value structures get freed by "reassemble_init()".)
135  */
136 static gboolean
137 free_all_fragments(gpointer key_arg, gpointer value, gpointer user_data _U_)
138 {
139         fragment_key *key = key_arg;
140         fragment_data *fd_head;
141
142         /*
143          * Grr.  I guess the theory here is that freeing
144          * something sure as heck modifies it, so you
145          * want to ban attempts to free it, but, alas,
146          * if we make the "data" field of an "address"
147          * structure not a "const", the compiler whines if
148          * we try to make it point into the data for a packet,
149          * as that's a "const" array (and should be, as dissectors
150          * shouldn't trash it).
151          *
152          * So we cast the complaint into oblivion, and rely on
153          * the fact that these addresses are known to have had
154          * their data mallocated, i.e. they don't point into,
155          * say, the middle of the data for a packet.
156          */
157         g_free((gpointer)key->src.data);
158         g_free((gpointer)key->dst.data);
159
160         for (fd_head = value; fd_head != NULL; fd_head = fd_head->next) {
161                 if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED))
162                         g_free(fd_head->data);
163         }
164
165         return TRUE;
166 }
167
168 /*
169  * For a reassembled-packet hash table entry, free the fragment data
170  * to which the value refers.
171  * (The actual value structures get freed by "reassemble_init()".)
172  */
173 static gboolean
174 free_all_reassembled_fragments(gpointer key_arg _U_, gpointer value,
175                                gpointer user_data _U_)
176 {
177         fragment_data *fd_head;
178
179         for (fd_head = value; fd_head != NULL; fd_head = fd_head->next) {
180                 if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED))
181                         g_free(fd_head->data);
182         }
183
184         return TRUE;
185 }
186
187 /*
188  * Initialize a fragment table.
189  */
190 void
191 fragment_table_init(GHashTable **fragment_table)
192 {
193         if (*fragment_table != NULL) {
194                 /*
195                  * The fragment hash table exists.
196                  * 
197                  * Remove all entries and free fragment data for
198                  * each entry.  (The key and value data is freed
199                  * by "reassemble_init()".)
200                  */
201                 g_hash_table_foreach_remove(*fragment_table,
202                                 free_all_fragments, NULL);
203         } else {
204                 /* The fragment table does not exist. Create it */
205                 *fragment_table = g_hash_table_new(fragment_hash,
206                                 fragment_equal);
207         }
208 }
209
210 /*
211  * Initialize a reassembled-packet table.
212  */
213 void
214 reassembled_table_init(GHashTable **reassembled_table)
215 {
216         if (*reassembled_table != NULL) {
217                 /*
218                  * The reassembled-packet hash table exists.
219                  * 
220                  * Remove all entries and free fragment data for
221                  * each entry.  (The key and value data is freed
222                  * by "reassemble_init()".)
223                  */
224                 g_hash_table_foreach_remove(*reassembled_table,
225                                 free_all_reassembled_fragments, NULL);
226         } else {
227                 /* The fragment table does not exist. Create it */
228                 *reassembled_table = g_hash_table_new(reassembled_hash,
229                                 reassembled_equal);
230         }
231 }
232
233 /*
234  * Free up all space allocated for fragment keys and data.
235  */
236 void
237 reassemble_init(void)
238 {
239         if (fragment_key_chunk != NULL)
240                 g_mem_chunk_destroy(fragment_key_chunk);
241         if (fragment_data_chunk != NULL)
242                 g_mem_chunk_destroy(fragment_data_chunk);
243         fragment_key_chunk = g_mem_chunk_new("fragment_key_chunk",
244             sizeof(fragment_key),
245             fragment_init_count * sizeof(fragment_key),
246             G_ALLOC_AND_FREE);
247         fragment_data_chunk = g_mem_chunk_new("fragment_data_chunk",
248             sizeof(fragment_data),
249             fragment_init_count * sizeof(fragment_data),
250             G_ALLOC_ONLY);
251 }
252
253 /* This function cleans up the stored state and removes the reassembly data and
254  * (with one exception) all allocated memory for matching reassembly.
255  * 
256  * The exception is :
257  * If the PDU was already completely reassembled, then the buffer containing the 
258  * reassembled data WILL NOT be free()d, and the pointer to that buffer will be
259  * returned.
260  * Othervise the function will return NULL.
261  *
262  * So, if you call fragment_delete and it returns non-NULL, YOU are responsible to 
263  * g_free() that buffer.
264  */
265 unsigned char *
266 fragment_delete(packet_info *pinfo, guint32 id, GHashTable *fragment_table)
267 {
268         fragment_data *fd_head, *fd;
269         fragment_key key;
270         unsigned char *data=NULL;
271
272         /* create key to search hash with */
273         key.src = pinfo->src;
274         key.dst = pinfo->dst;
275         key.id  = id;
276
277         fd_head = g_hash_table_lookup(fragment_table, &key);
278
279         if(fd_head==NULL){
280                 /* We do not recognize this as a PDU we have seen before. return*/
281                 return NULL;
282         }
283
284         data=fd_head->data;
285         /* loop over all partial fragments and free any buffers */
286         for(fd=fd_head->next;fd;){
287                 fragment_data *tmp_fd;
288                 tmp_fd=fd->next;
289
290                 if( !(fd->flags&FD_NOT_MALLOCED) )
291                         g_free(fd->data);
292                 g_mem_chunk_free(fragment_data_chunk, fd);
293                 fd=tmp_fd;
294         }
295         g_mem_chunk_free(fragment_data_chunk, fd_head);
296         g_hash_table_remove(fragment_table, &key);
297
298         return data;
299 }
300
301 /* This function is used to check if there is partial or completed reassembly state
302  * matching this packet. I.e. Are there reassembly going on or not for this packet?
303  */
304 fragment_data *
305 fragment_get(packet_info *pinfo, guint32 id, GHashTable *fragment_table)
306 {
307         fragment_data *fd_head;
308         fragment_key key;
309
310         /* create key to search hash with */
311         key.src = pinfo->src;
312         key.dst = pinfo->dst;
313         key.id  = id;
314
315         fd_head = g_hash_table_lookup(fragment_table, &key);
316         
317         return fd_head;
318 }
319
320 /* This function can be used to explicitely set the total length (if known)
321  * for reassembly of a PDU.
322  * This is useful for reassembly of PDUs where one may have the total length specified
323  * in the first fragment instead of as for, say, IPv4 where a flag indicates which
324  * is the last fragment.
325  *
326  * Such protocols might fragment_add with a more_frags==TRUE for every fragment
327  * and just tell the reassembly engine the expected total length of the reassembled data
328  * using fragment_set_tot_len immediately after doing fragment_add for the first packet.
329  *
330  * note that for FD_BLOCKSEQUENCE tot_len is the index for the tail fragment.
331  * i.e. since the block numbers start at 0, if we specify tot_len==2, that 
332  * actually means we want to defragment 3 blocks, block 0, 1 and 2.
333  */
334 void
335 fragment_set_tot_len(packet_info *pinfo, guint32 id, GHashTable *fragment_table, 
336                      guint32 tot_len)
337 {
338         fragment_data *fd_head;
339         fragment_key key;
340
341         /* create key to search hash with */
342         key.src = pinfo->src;
343         key.dst = pinfo->dst;
344         key.id  = id;
345
346         fd_head = g_hash_table_lookup(fragment_table, &key);
347
348         if(fd_head){
349                 fd_head->datalen = tot_len;
350         }
351
352         return;
353 }
354
355
356 /* This function will set the partial reassembly flag for a fh.
357    When this function is called, the fh MUST already exist, i.e.
358    the fh MUST be created by the initial call to fragment_add() before
359    this function is called.
360    Also note that this function MUST be called to indicate a fh will be 
361    extended (increase the already stored data)
362 */
363
364 void
365 fragment_set_partial_reassembly(packet_info *pinfo, guint32 id, GHashTable *fragment_table)
366 {
367         fragment_data *fd_head;
368         fragment_key key;
369
370         /* create key to search hash with */
371         key.src = pinfo->src;
372         key.dst = pinfo->dst;
373         key.id  = id;
374
375         fd_head = g_hash_table_lookup(fragment_table, &key);
376
377         if(fd_head){
378                 fd_head->flags |= FD_PARTIAL_REASSEMBLY;
379         }
380 }
381
382 /*
383  * This function adds a new fragment to the fragment hash table.
384  * If this is the first fragment seen for this datagram, a new entry
385  * is created in the hash table, otherwise this fragment is just added
386  * to the linked list of fragments for this packet.
387  * The list of fragments for a specific datagram is kept sorted for
388  * easier handling.
389  *
390  * Returns a pointer to the head of the fragment data list if we have all the
391  * fragments, NULL otherwise.
392  *
393  * This function assumes frag_offset being a byte offset into the defragment
394  * packet.
395  *
396  * 01-2002
397  * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be
398  * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set 
399  * using fragment_set_partial_reassembly() before calling fragment_add
400  * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags
401  * are lowered when a new extension process is started.
402  */
403 fragment_data *
404 fragment_add(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
405              GHashTable *fragment_table, guint32 frag_offset,
406              guint32 frag_data_len, gboolean more_frags)
407 {
408         fragment_key key, *new_key;
409         fragment_data *fd_head;
410         fragment_data *fd;
411         fragment_data *fd_i;
412         guint32 max, dfpos;
413         unsigned char *old_data;
414
415         /* create key to search hash with */
416         key.src = pinfo->src;
417         key.dst = pinfo->dst;
418         key.id  = id;
419
420         fd_head = g_hash_table_lookup(fragment_table, &key);
421
422         /* have we already seen this frame ?*/
423         if (pinfo->fd->flags.visited) {
424                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
425                         return fd_head;
426                 } else {
427                         return NULL;
428                 }
429         }
430
431         if (fd_head==NULL){
432                 /* not found, this must be the first snooped fragment for this
433                  * packet. Create list-head.
434                  */
435                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
436                 /* head/first structure in list only holds no other data than
437                  * 'datalen' then we don't have to change the head of the list
438                  * even if we want to keep it sorted
439                  */
440                 fd_head->next=NULL;
441                 fd_head->datalen=0;
442                 fd_head->offset=0;
443                 fd_head->len=0;
444                 fd_head->flags=0;
445                 fd_head->data=NULL;
446
447                 /*
448                  * We're going to use the key to insert the fragment,
449                  * so allocate a structure for it, and copy the
450                  * addresses, allocating new buffers for the address
451                  * data.
452                  */
453                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
454                 COPY_ADDRESS(&new_key->src, &key.src);
455                 COPY_ADDRESS(&new_key->dst, &key.dst);
456                 new_key->id = key.id;
457                 g_hash_table_insert(fragment_table, new_key, fd_head);
458         }
459
460         /* create new fd describing this fragment */
461         fd = g_mem_chunk_alloc(fragment_data_chunk);
462         fd->next = NULL;
463         fd->flags = 0;
464         fd->frame = pinfo->fd->num;
465         fd->offset = frag_offset;
466         fd->len  = frag_data_len;
467         fd->data = NULL;
468
469         /*
470          * If it was already defragmented and this new fragment goes beyond
471          * data limits, set flag in already empty fds & point old fds to malloc'ed data.
472          */
473         if(fd_head->flags & FD_DEFRAGMENTED && (frag_offset+frag_data_len) >= fd_head->datalen &&
474                 fd_head->flags & FD_PARTIAL_REASSEMBLY){
475                 for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){
476                         if( !fd_i->data ) {
477                                 fd_i->data = fd_head->data + fd_i->offset;
478                                 fd_i->flags |= FD_NOT_MALLOCED;
479                         }
480                         fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
481                 }
482                 fd_head->flags ^= FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY;
483                 fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS);
484                 fd_head->datalen=0;
485         }
486
487         if (!more_frags) {  
488                 /*
489                  * This is the tail fragment in the sequence.
490                  */
491                 if (fd_head->datalen) {
492                         /* ok we have already seen other tails for this packet
493                          * it might be a duplicate.
494                          */
495                         if (fd_head->datalen != (fd->offset + fd->len) ){
496                                 /* Oops, this tail indicates a different packet
497                                  * len than the previous ones. Somethings wrong
498                                  */
499                                 fd->flags      |= FD_MULTIPLETAILS;
500                                 fd_head->flags |= FD_MULTIPLETAILS;
501                         }
502                 } else {
503                         /* this was the first tail fragment, now we know the
504                          * length of the packet
505                          */
506                         fd_head->datalen = fd->offset + fd->len;
507                 }
508         }
509
510
511
512
513         /* If the packet is already defragmented, this MUST be an overlap.
514          * The entire defragmented packet is in fd_head->data
515          * Even if we have previously defragmented this packet, we still check
516          * check it. Someone might play overlap and TTL games.
517          */
518         if (fd_head->flags & FD_DEFRAGMENTED) {
519                 fd->flags      |= FD_OVERLAP;
520                 fd_head->flags |= FD_OVERLAP;
521                 /* make sure its not too long */
522                 if (fd->offset + fd->len > fd_head->datalen) {
523                         fd->flags      |= FD_TOOLONGFRAGMENT;
524                         fd_head->flags |= FD_TOOLONGFRAGMENT;
525                         LINK_FRAG(fd_head,fd);
526                         return (fd_head);
527                 }
528                 /* make sure it doesnt conflict with previous data */
529                 if ( memcmp(fd_head->data+fd->offset,
530                         tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
531                         fd->flags      |= FD_OVERLAPCONFLICT;
532                         fd_head->flags |= FD_OVERLAPCONFLICT;
533                         LINK_FRAG(fd_head,fd);
534                         return (fd_head);
535                 }
536                 /* it was just an overlap, link it and return */
537                 LINK_FRAG(fd_head,fd);
538                 return (fd_head);
539         }
540
541
542
543         /* If we have reached this point, the packet is not defragmented yet.
544          * Save all payload in a buffer until we can defragment.
545          * XXX - what if we didn't capture the entire fragment due
546          * to a too-short snapshot length?
547          */
548         fd->data = g_malloc(fd->len);
549         tvb_memcpy(tvb, fd->data, offset, fd->len);
550         LINK_FRAG(fd_head,fd);
551
552
553         if( !(fd_head->datalen) ){
554                 /* if we dont know the datalen, there are still missing
555                  * packets. Cheaper than the check below.
556                  */
557                 return NULL;
558         }
559
560
561         /* check if we have received the entire fragment
562          * this is easy since the list is sorted and the head is faked.
563          */
564         max = 0;
565         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
566                 if ( ((fd_i->offset)<=max) && 
567                     ((fd_i->offset+fd_i->len)>max) ){
568                         max = fd_i->offset+fd_i->len;
569                 }
570         }
571
572         if (max < (fd_head->datalen)) {
573                 /* we have not received all packets yet */
574                 return NULL;
575         }
576
577
578         if (max > (fd_head->datalen)) {
579                 /*XXX not sure if current fd was the TOOLONG*/
580                 /*XXX is it fair to flag current fd*/
581                 /* oops, too long fragment detected */
582                 fd->flags      |= FD_TOOLONGFRAGMENT;
583                 fd_head->flags |= FD_TOOLONGFRAGMENT;
584         }
585
586
587         /* we have received an entire packet, defragment it and
588          * free all fragments 
589          */
590         /* store old data just in case */
591         old_data=fd_head->data;
592         fd_head->data = g_malloc(max);
593
594         /* add all data fragments */
595         for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) {
596                 if (fd_i->len) {
597                         if (fd_i->offset < dfpos) {
598                                 fd_i->flags    |= FD_OVERLAP;
599                                 fd_head->flags |= FD_OVERLAP;
600                                 if ( memcmp(fd_head->data+fd_i->offset,
601                                         fd_i->data,
602                                         MIN(fd_i->len,(dfpos-fd_i->offset))
603                                         ) ){
604                                         fd_i->flags    |= FD_OVERLAPCONFLICT;
605                                         fd_head->flags |= FD_OVERLAPCONFLICT;
606                                 }
607                         } 
608                         /* dfpos is always >= than fd_i->offset */
609                         /* No gaps can exist here, max_loop(above) does this */
610                         if( fd_i->offset+fd_i->len > dfpos )
611                                 memcpy(fd_head->data+dfpos, fd_i->data+(dfpos-fd_i->offset),
612                                         fd_i->len-(dfpos-fd_i->offset));
613                         if( fd_i->flags & FD_NOT_MALLOCED )
614                                 fd_i->flags ^= FD_NOT_MALLOCED;
615                         else
616                                 g_free(fd_i->data);
617                         fd_i->data=NULL;
618
619                         dfpos=MAX(dfpos,(fd_i->offset+fd_i->len));
620                 }
621         }
622
623         if( old_data )
624                 g_free(old_data);
625         /* mark this packet as defragmented.
626            allows us to skip any trailing fragments */
627         fd_head->flags |= FD_DEFRAGMENTED;
628
629         return fd_head;
630 }
631
632 /*
633  * This function adds a new fragment to the entry for a reassembly
634  * operation.
635  *
636  * The list of fragments for a specific datagram is kept sorted for
637  * easier handling.
638  *
639  * Returns TRUE if we have all the fragments, FALSE otherwise.
640  *
641  * This function assumes frag_number being a block sequence number.
642  * The bsn for the first block is 0.
643  */
644 static gboolean
645 fragment_add_seq_work(fragment_data *fd_head, tvbuff_t *tvb, int offset,
646              packet_info *pinfo, guint32 frag_number,
647              guint32 frag_data_len, gboolean more_frags)
648 {
649         fragment_data *fd;
650         fragment_data *fd_i;
651         fragment_data *last_fd;
652         guint32 max, dfpos, size;
653
654         /* create new fd describing this fragment */
655         fd = g_mem_chunk_alloc(fragment_data_chunk);
656         fd->next = NULL;
657         fd->flags = 0;
658         fd->frame = pinfo->fd->num;
659         fd->offset = frag_number;
660         fd->len  = frag_data_len;
661         fd->data = NULL;
662
663         if (!more_frags) {  
664                 /*
665                  * This is the tail fragment in the sequence.
666                  */
667                 if (fd_head->datalen) {
668                         /* ok we have already seen other tails for this packet
669                          * it might be a duplicate.
670                          */
671                         if (fd_head->datalen != fd->offset ){
672                                 /* Oops, this tail indicates a different packet
673                                  * len than the previous ones. Somethings wrong
674                                  */
675                                 fd->flags      |= FD_MULTIPLETAILS;
676                                 fd_head->flags |= FD_MULTIPLETAILS;
677                         }
678                 } else {
679                         /* this was the first tail fragment, now we know the
680                          * length of the packet
681                          */
682                         fd_head->datalen = fd->offset;
683                 }
684         }
685
686         /* If the packet is already defragmented, this MUST be an overlap.
687          * The entire defragmented packet is in fd_head->data
688          * Even if we have previously defragmented this packet, we still check
689          * check it. Someone might play overlap and TTL games.
690          */
691         if (fd_head->flags & FD_DEFRAGMENTED) {
692                 fd->flags      |= FD_OVERLAP;
693                 fd_head->flags |= FD_OVERLAP;
694
695                 /* make sure its not too long */
696                 if (fd->offset > fd_head->datalen) {
697                         fd->flags      |= FD_TOOLONGFRAGMENT;
698                         fd_head->flags |= FD_TOOLONGFRAGMENT;
699                         LINK_FRAG(fd_head,fd);
700                         return TRUE;
701                 }
702                 /* make sure it doesnt conflict with previous data */
703                 dfpos=0;
704                 for (fd_i=fd_head->next;fd_i->offset!=fd->offset;fd_i=fd_i->next) {
705                   dfpos += fd_i->len;
706                 }
707                 if(fd_i->datalen!=fd->datalen){
708                         fd->flags      |= FD_OVERLAPCONFLICT;
709                         fd_head->flags |= FD_OVERLAPCONFLICT;
710                         LINK_FRAG(fd_head,fd);
711                         return TRUE;
712                 }
713                 if ( memcmp(fd_head->data+dfpos,
714                         tvb_get_ptr(tvb,offset,fd->len),fd->len) ){
715                         fd->flags      |= FD_OVERLAPCONFLICT;
716                         fd_head->flags |= FD_OVERLAPCONFLICT;
717                         LINK_FRAG(fd_head,fd);
718                         return TRUE;
719                 }
720                 /* it was just an overlap, link it and return */
721                 LINK_FRAG(fd_head,fd);
722                 return TRUE;
723         }
724
725         /* If we have reached this point, the packet is not defragmented yet.
726          * Save all payload in a buffer until we can defragment.
727          * XXX - what if we didn't capture the entire fragment due
728          * to a too-short snapshot length?
729          */
730         fd->data = g_malloc(fd->len);
731         tvb_memcpy(tvb, fd->data, offset, fd->len);
732         LINK_FRAG(fd_head,fd);
733
734
735         if( !(fd_head->datalen) ){
736                 /* if we dont know the datalen, there are still missing
737                  * packets. Cheaper than the check below.
738                  */
739                 return FALSE;
740         }
741
742
743         /* check if we have received the entire fragment
744          * this is easy since the list is sorted and the head is faked.
745          */
746         max = 0;
747         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
748           if ( fd_i->offset==max ){
749             max++;
750           }
751         }
752         /* max will now be datalen+1 if all fragments have been seen */
753
754         if (max <= fd_head->datalen) {
755                 /* we have not received all packets yet */
756                 return FALSE;
757         }
758
759
760         if (max > (fd_head->datalen+1)) {
761                 /* oops, too long fragment detected */
762                 fd->flags      |= FD_TOOLONGFRAGMENT;
763                 fd_head->flags |= FD_TOOLONGFRAGMENT;
764         }
765
766
767         /* we have received an entire packet, defragment it and
768          * free all fragments 
769          */
770         size=0;
771         last_fd=NULL;
772         for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
773           if(!last_fd || last_fd->offset!=fd_i->offset){
774             size+=fd_i->len;
775           }
776           last_fd=fd_i;
777         }
778         fd_head->data = g_malloc(size);
779         fd_head->len = size;            /* record size for caller       */
780
781         /* add all data fragments */
782         last_fd=NULL;
783         for (dfpos=0,fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
784           if (fd_i->len) {
785             if(!last_fd || last_fd->offset!=fd_i->offset){
786               memcpy(fd_head->data+dfpos,fd_i->data,fd_i->len);
787               dfpos += fd_i->len;
788             } else {
789               /* duplicate/retransmission/overlap */
790               if( (last_fd->len!=fd_i->datalen)
791                   || memcmp(last_fd->data, fd_i->data, last_fd->len) ){
792                         fd->flags      |= FD_OVERLAPCONFLICT;
793                         fd_head->flags |= FD_OVERLAPCONFLICT;
794               }
795             }
796             last_fd=fd_i;
797           }
798         }
799
800         /* we have defragmented the pdu, now free all fragments*/
801         for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) {
802           if(fd_i->data){
803             g_free(fd_i->data);
804             fd_i->data=NULL;
805           }
806         }
807
808         /* mark this packet as defragmented.
809            allows us to skip any trailing fragments */
810         fd_head->flags |= FD_DEFRAGMENTED;
811
812         return TRUE;
813 }
814
815 /*
816  * This function adds a new fragment to the fragment hash table.
817  * If this is the first fragment seen for this datagram, a new entry
818  * is created in the hash table, otherwise this fragment is just added
819  * to the linked list of fragments for this packet.
820  *
821  * Returns a pointer to the head of the fragment data list if we have all the
822  * fragments, NULL otherwise.
823  *
824  * This function assumes frag_number being a block sequence number.
825  * The bsn for the first block is 0.
826  */
827 fragment_data *
828 fragment_add_seq(tvbuff_t *tvb, int offset, packet_info *pinfo, guint32 id,
829              GHashTable *fragment_table, guint32 frag_number,
830              guint32 frag_data_len, gboolean more_frags)
831 {
832         fragment_key key, *new_key;
833         fragment_data *fd_head;
834
835         /* create key to search hash with */
836         key.src = pinfo->src;
837         key.dst = pinfo->dst;
838         key.id  = id;
839
840         fd_head = g_hash_table_lookup(fragment_table, &key);
841
842         /* have we already seen this frame ?*/
843         if (pinfo->fd->flags.visited) {
844                 if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) {
845                         return fd_head;
846                 } else {
847                         return NULL;
848                 }
849         }
850
851         if (fd_head==NULL){
852                 /* not found, this must be the first snooped fragment for this
853                  * packet. Create list-head.
854                  */
855                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
856                 /* head/first structure in list only holds no other data than
857                  * 'datalen' then we don't have to change the head of the list
858                  * even if we want to keep it sorted
859                  */
860                 fd_head->next=NULL;
861                 fd_head->datalen=0;
862                 fd_head->offset=0;
863                 fd_head->len=0;
864                 fd_head->flags=FD_BLOCKSEQUENCE;
865                 fd_head->data=NULL;
866
867                 /*
868                  * We're going to use the key to insert the fragment,
869                  * so allocate a structure for it, and copy the
870                  * addresses, allocating new buffers for the address
871                  * data.
872                  */
873                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
874                 COPY_ADDRESS(&new_key->src, &key.src);
875                 COPY_ADDRESS(&new_key->dst, &key.dst);
876                 new_key->id = key.id;
877                 g_hash_table_insert(fragment_table, new_key, fd_head);
878         }
879
880         if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
881                                   frag_number, frag_data_len, more_frags)) {
882                 /*
883                  * Reassembly is complete.
884                  */
885                 return fd_head;
886         } else {
887                 /*
888                  * Reassembly isn't complete.
889                  */
890                 return NULL;
891         }
892 }
893
894 /*
895  * This function gets rid of an entry from a fragment table, given
896  * a pointer to the key for that entry; it also frees up the key
897  * and the addresses in it.
898  */
899 static void
900 fragment_unhash(GHashTable *fragment_table, fragment_key *key)
901 {
902         /*
903          * Free up the copies of the addresses from the old key.
904          */
905         g_free((gpointer)key->src.data);
906         g_free((gpointer)key->dst.data);
907
908         /*
909          * Remove the entry from the fragment table.
910          */
911         g_hash_table_remove(fragment_table, key);
912
913         /*
914          * Free the key itself.
915          */
916         g_mem_chunk_free(fragment_key_chunk, key);
917 }
918
919 /*
920  * This function adds fragment_data structure to a reassembled-packet
921  * hash table, using the frame data structure as the key.
922  */
923 static void
924 fragment_reassembled(fragment_data *fd_head, packet_info *pinfo,
925              GHashTable *reassembled_table)
926 {
927         g_hash_table_insert(reassembled_table, pinfo->fd, fd_head);
928 }
929
930 /*
931  * This function adds a new fragment to the fragment hash table.
932  * If this is the first fragment seen for this datagram, a new
933  * "fragment_data" structure is allocated to refer to the reassembled,
934  * packet, and:
935  *
936  *      if "more_frags" is false, the structure is not added to
937  *      the hash table, and not given any fragments to refer to,
938  *      but is just returned;
939  *
940  *      if "more_frags" is true, this fragment is added to the linked
941  *      list of fragments for this packet, and the "fragment_data"
942  *      structure is put into the hash table.
943  *
944  * Otherwise, this fragment is just added to the linked list of fragments
945  * for this packet.
946  *
947  * Returns a pointer to the head of the fragment data list, and removes
948  * that from the fragment hash table if necessary and adds it to the
949  * table of reassembled fragments, if we have all the fragments or if
950  * this is the only fragment and "more_frags" is false, returns NULL
951  * otherwise.
952  *
953  * This function assumes frag_number being a block sequence number.
954  * The bsn for the first block is 0.
955  */
956 fragment_data *
957 fragment_add_seq_check(tvbuff_t *tvb, int offset, packet_info *pinfo,
958              guint32 id, GHashTable *fragment_table,
959              GHashTable *reassembled_table, guint32 frag_number,
960              guint32 frag_data_len, gboolean more_frags)
961 {
962         fragment_key key, *new_key, *old_key;
963         gpointer orig_key, value;
964         fragment_data *fd_head;
965         gboolean short_frame;
966
967         /*
968          * Have we already seen this frame?
969          * If so, look for it in the table of reassembled packets.
970          */
971         if (pinfo->fd->flags.visited)
972                 return g_hash_table_lookup(reassembled_table, pinfo->fd);
973
974         short_frame = (tvb_reported_length(tvb) > tvb_length(tvb));
975
976         /* create key to search hash with */
977         key.src = pinfo->src;
978         key.dst = pinfo->dst;
979         key.id  = id;
980
981         if (!g_hash_table_lookup_extended(fragment_table, &key,
982                                           &orig_key, &value)) {
983                 /* not found, this must be the first snooped fragment for this
984                  * packet. Create list-head.
985                  */
986                 fd_head=g_mem_chunk_alloc(fragment_data_chunk);
987
988                 /* head/first structure in list only holds no other data than
989                  * 'datalen' then we don't have to change the head of the list
990                  * even if we want to keep it sorted
991                  */
992                 fd_head->next=NULL;
993                 fd_head->datalen=0;
994                 fd_head->offset=0;
995                 fd_head->len=0;
996                 fd_head->flags=FD_BLOCKSEQUENCE;
997                 fd_head->data=NULL;
998
999                 if (!more_frags) {
1000                         /*
1001                          * This is the last snooped fragment for this
1002                          * packet as well; that means it's the only
1003                          * fragment.  Just add it to the table of
1004                          * reassembled packets, and return it.
1005                          */
1006                         fragment_reassembled(fd_head, pinfo,
1007                                reassembled_table);
1008                         return fd_head;
1009                 }
1010
1011                 /*
1012                  * We're going to use the key to insert the fragment,
1013                  * so allocate a structure for it, and copy the
1014                  * addresses, allocating new buffers for the address
1015                  * data.
1016                  */
1017                 new_key = g_mem_chunk_alloc(fragment_key_chunk);
1018                 COPY_ADDRESS(&new_key->src, &key.src);
1019                 COPY_ADDRESS(&new_key->dst, &key.dst);
1020                 new_key->id = key.id;
1021                 g_hash_table_insert(fragment_table, new_key, fd_head);
1022
1023                 orig_key = new_key;     /* for unhashing it later */
1024         } else {
1025                 /*
1026                  * We found it.
1027                  */
1028                 fd_head = value;
1029         }
1030
1031         /*
1032          * If this is a short frame, then we can't, and don't, do
1033          * reassembly on it.
1034          *
1035          * If it's the first frame (fragment number is 0), handle it
1036          * as an unfragmented packet.  Otherwise, just handle it
1037          * as a fragment.
1038          *
1039          * If "more_frags" isn't set, we get rid of the entry in the
1040          * hash table for this reassembly, as we don't need it any more.
1041          */
1042         if (short_frame) {
1043                 if (!more_frags) {
1044                         /*
1045                          * Remove this from the table of in-progress
1046                          * reassemblies, and free up any memory used for
1047                          * it in that table.
1048                          */
1049                         old_key = orig_key;
1050                         fragment_unhash(fragment_table, old_key);
1051                 }
1052                 return frag_number == 0 ? fd_head : NULL;
1053         }
1054
1055         if (fragment_add_seq_work(fd_head, tvb, offset, pinfo,
1056                                   frag_number, frag_data_len, more_frags)) {
1057                 /*
1058                  * Reassembly is complete.
1059                  * Remove this from the table of in-progress
1060                  * reassemblies, add it to the table of
1061                  * reassembled packets, and return it.
1062                  */
1063
1064                 /*
1065                  * Remove this from the table of in-progress reassemblies,
1066                  * and free up any memory used for it in that table.
1067                  */
1068                 old_key = orig_key;
1069                 fragment_unhash(fragment_table, old_key);
1070
1071                 /*
1072                  * Add this item to the table of reassembled packets.
1073                  */
1074                 fragment_reassembled(fd_head, pinfo, reassembled_table);
1075                 return fd_head;
1076         } else {
1077                 /*
1078                  * Reassembly isn't complete.
1079                  */
1080                 return NULL;
1081         }
1082 }