Document the new Copy Profile button.
[obnox/wireshark/wip.git] / epan / follow.c
1 /* follow.c
2  *
3  * $Id$
4  *
5  * Copyright 1998 Mike Hall <mlh@io.com>
6  *
7  * Wireshark - Network traffic analyzer
8  * By Gerald Combs <gerald@wireshark.org>
9  * Copyright 1998 Gerald Combs
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  *
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #include <glib.h>
39 #include <epan/packet.h>
40 #include <epan/ipproto.h>
41 #include "follow.h"
42 #include <epan/conversation.h>
43
44 #define MAX_IPADDR_LEN  16
45
46 typedef struct _tcp_frag {
47   gulong              seq;
48   gulong              len;
49   gulong              data_len;
50   gchar              *data;
51   struct _tcp_frag   *next;
52 } tcp_frag;
53
54 FILE* data_out_file = NULL;
55
56 gboolean empty_tcp_stream;
57 gboolean incomplete_tcp_stream;
58
59 static guint32 tcp_stream_to_follow;
60 static guint8  ip_address[2][MAX_IPADDR_LEN];
61 static guint   port[2];
62 static guint   bytes_written[2];
63 static gboolean is_ipv6 = FALSE;
64
65 static int check_fragments( int, tcp_stream_chunk *, gulong );
66 static void write_packet_data( int, tcp_stream_chunk *, const char * );
67
68 void
69 follow_stats(follow_stats_t* stats)
70 {
71         int i;
72
73         for (i = 0; i < 2 ; i++) {
74                 memcpy(stats->ip_address[i], ip_address[i], MAX_IPADDR_LEN);
75                 stats->port[i] = port[i];
76                 stats->bytes_written[i] = bytes_written[i];
77                 stats->is_ipv6 = is_ipv6;
78         }
79 }
80
81 /* this will build libpcap filter text that will only
82    pass the packets related to the stream. There is a
83    chance that two streams could intersect, but not a
84    very good one */
85 char*
86 build_follow_filter( packet_info *pi ) {
87   char* buf;
88   int len;
89   conversation_t *conv=NULL;
90
91   if( pi->net_src.type == AT_IPv4 && pi->net_dst.type == AT_IPv4
92         && pi->ipproto == IP_PROTO_TCP 
93         && (conv=find_conversation(pi->fd->num, &pi->src, &pi->dst, pi->ptype,
94               pi->srcport, pi->destport, 0)) != NULL ) {
95     /* TCP over IPv4 */
96     buf = g_strdup_printf("tcp.stream eq %d", conv->index);
97     len = 4;
98     is_ipv6 = FALSE;
99     tcp_stream_to_follow = conv->index;
100   }
101   else if( pi->net_src.type == AT_IPv4 && pi->net_dst.type == AT_IPv4
102            && pi->ipproto == IP_PROTO_UDP ) {
103   /* UDP over IPv4 */
104     buf = g_strdup_printf(
105              "(ip.addr eq %s and ip.addr eq %s) and (udp.port eq %d and udp.port eq %d)",
106              ip_to_str( pi->net_src.data),
107              ip_to_str( pi->net_dst.data),
108              pi->srcport, pi->destport );
109     len = 4;
110     is_ipv6 = FALSE;
111   }
112   else if( pi->net_src.type == AT_IPv6 && pi->net_dst.type == AT_IPv6
113         && pi->ipproto == IP_PROTO_TCP 
114         && (conv=find_conversation(pi->fd->num, &pi->src, &pi->dst, pi->ptype,
115               pi->srcport, pi->destport, 0)) != NULL ) {
116     /* TCP over IPv6 */
117     buf = g_strdup_printf("tcp.stream eq %d", conv->index);
118     len = 16;
119     is_ipv6 = TRUE;
120     tcp_stream_to_follow = conv->index;
121   }
122   else if( pi->net_src.type == AT_IPv6 && pi->net_dst.type == AT_IPv6
123         && pi->ipproto == IP_PROTO_UDP ) {
124     /* UDP over IPv6 */
125     buf = g_strdup_printf(
126              "(ipv6.addr eq %s and ipv6.addr eq %s) and (udp.port eq %d and udp.port eq %d)",
127              ip6_to_str((const struct e_in6_addr *)pi->net_src.data),
128              ip6_to_str((const struct e_in6_addr *)pi->net_dst.data),
129              pi->srcport, pi->destport );
130     len = 16;
131     is_ipv6 = TRUE;
132   }
133   else {
134     return NULL;
135   }
136   memcpy(ip_address[0], pi->net_src.data, len);
137   memcpy(ip_address[1], pi->net_dst.data, len);
138   port[0] = pi->srcport;
139   port[1] = pi->destport;
140   return buf;
141 }
142
143 /* here we are going to try and reconstruct the data portion of a TCP
144    session. We will try and handle duplicates, TCP fragments, and out
145    of order packets in a smart way. */
146
147 static tcp_frag *frags[2] = { 0, 0 };
148 static gulong seq[2];
149 static guint8 src_addr[2][MAX_IPADDR_LEN];
150 static guint src_port[2] = { 0, 0 };
151
152 void
153 reassemble_tcp( guint32 tcp_stream, gulong sequence, gulong acknowledgement,
154                 gulong length, const char* data, gulong data_length, 
155                 int synflag, address *net_src, address *net_dst, 
156                 guint srcport, guint dstport) {
157   guint8 srcx[MAX_IPADDR_LEN], dstx[MAX_IPADDR_LEN];
158   int src_index, j, first = 0, len;
159   gulong newseq;
160   tcp_frag *tmp_frag;
161   tcp_stream_chunk sc;
162
163   src_index = -1;
164
165   /* First, check if this packet should be processed. */
166   if ( tcp_stream != tcp_stream_to_follow )
167     return;
168
169   if ((net_src->type != AT_IPv4 && net_src->type != AT_IPv6) ||
170       (net_dst->type != AT_IPv4 && net_dst->type != AT_IPv6))
171     return;
172
173   if (net_src->type == AT_IPv4)
174     len = 4;
175   else
176     len = 16;
177
178   memcpy(srcx, net_src->data, len);
179   memcpy(dstx, net_dst->data, len);
180
181   /* Check to see if we have seen this source IP and port before.
182      (Yes, we have to check both source IP and port; the connection
183      might be between two different ports on the same machine.) */
184   for( j=0; j<2; j++ ) {
185     if (memcmp(src_addr[j], srcx, len) == 0 && src_port[j] == srcport ) {
186       src_index = j;
187     }
188   }
189   /* we didn't find it if src_index == -1 */
190   if( src_index < 0 ) {
191     /* assign it to a src_index and get going */
192     for( j=0; j<2; j++ ) {
193       if( src_port[j] == 0 ) {
194         memcpy(src_addr[j], srcx, len);
195         src_port[j] = srcport;
196         src_index = j;
197         first = 1;
198         break;
199       }
200     }
201   }
202   if( src_index < 0 ) {
203     fprintf( stderr, "ERROR in reassemble_tcp: Too many addresses!\n");
204     return;
205   }
206
207   if( data_length < length ) {
208     incomplete_tcp_stream = TRUE;
209   }
210
211   /* Before adding data for this flow to the data_out_file, check whether
212    * this frame acks fragments that were already seen. This happens when
213    * frames are not in the capture file, but were actually seen by the 
214    * receiving host (Fixes bug 592).
215    */
216   if( frags[1-src_index] ) {
217     memcpy(sc.src_addr, dstx, len);
218     sc.src_port = dstport;
219     sc.dlen     = 0;        /* Will be filled in in check_fragments */
220     while ( check_fragments( 1-src_index, &sc, acknowledgement ) )
221       ;
222   }
223
224   /* Initialize our stream chunk.  This data gets written to disk. */
225   memcpy(sc.src_addr, srcx, len);
226   sc.src_port = srcport;
227   sc.dlen     = data_length;
228
229   /* now that we have filed away the srcs, lets get the sequence number stuff
230      figured out */
231   if( first ) {
232     /* this is the first time we have seen this src's sequence number */
233     seq[src_index] = sequence + length;
234     if( synflag ) {
235       seq[src_index]++;
236     }
237     /* write out the packet data */
238     write_packet_data( src_index, &sc, data );
239     return;
240   }
241   /* if we are here, we have already seen this src, let's
242      try and figure out if this packet is in the right place */
243   if( sequence < seq[src_index] ) {
244     /* this sequence number seems dated, but
245        check the end to make sure it has no more
246        info than we have already seen */
247     newseq = sequence + length;
248     if( newseq > seq[src_index] ) {
249       gulong new_len;
250
251       /* this one has more than we have seen. let's get the
252          payload that we have not seen. */
253
254       new_len = seq[src_index] - sequence;
255
256       if ( data_length <= new_len ) {
257         data = NULL;
258         data_length = 0;
259         incomplete_tcp_stream = TRUE;
260       } else {
261         data += new_len;
262         data_length -= new_len;
263       }
264       sc.dlen = data_length;
265       sequence = seq[src_index];
266       length = newseq - seq[src_index];
267
268       /* this will now appear to be right on time :) */
269     }
270   }
271   if ( sequence == seq[src_index] ) {
272     /* right on time */
273     seq[src_index] += length;
274     if( synflag ) seq[src_index]++;
275     if( data ) {
276       write_packet_data( src_index, &sc, data );
277     }
278     /* done with the packet, see if it caused a fragment to fit */
279     while( check_fragments( src_index, &sc, 0 ) )
280       ;
281   }
282   else {
283     /* out of order packet */
284     if(data_length > 0 && ((glong)(sequence - seq[src_index]) > 0) ) {
285       tmp_frag = (tcp_frag *)g_malloc( sizeof( tcp_frag ) );
286       tmp_frag->data = (gchar *)g_malloc( data_length );
287       tmp_frag->seq = sequence;
288       tmp_frag->len = length;
289       tmp_frag->data_len = data_length;
290       memcpy( tmp_frag->data, data, data_length );
291       if( frags[src_index] ) {
292         tmp_frag->next = frags[src_index];
293       } else {
294         tmp_frag->next = NULL;
295       }
296       frags[src_index] = tmp_frag;
297     }
298   }
299 } /* end reassemble_tcp */
300
301 /* here we search through all the frag we have collected to see if
302    one fits */
303 static int
304 check_fragments( int index, tcp_stream_chunk *sc, gulong acknowledged ) {
305   tcp_frag *prev = NULL;
306   tcp_frag *current;
307   gulong lowest_seq;
308   gchar *dummy_str;
309
310   current = frags[index];
311   if( current ) {
312     lowest_seq = current->seq;
313     while( current ) {
314       if( (glong)(lowest_seq - current->seq) > 0 ) {
315         lowest_seq = current->seq;
316       }
317
318       if( current->seq < seq[index] ) {
319         gulong newseq;
320         /* this sequence number seems dated, but
321            check the end to make sure it has no more
322            info than we have already seen */
323         newseq = current->seq + current->len;
324         if( newseq > seq[index] ) {
325           gulong new_pos;
326
327           /* this one has more than we have seen. let's get the
328              payload that we have not seen. This happens when 
329              part of this frame has been retransmitted */
330
331           new_pos = seq[index] - current->seq;
332
333           if ( current->data_len > new_pos ) {
334             sc->dlen = current->data_len - new_pos;
335             write_packet_data( index, sc, current->data + new_pos );
336           }
337
338           seq[index] += (current->len - new_pos);
339         } 
340
341         /* Remove the fragment from the list as the "new" part of it
342          * has been processed or its data has been seen already in 
343          * another packet. */
344         if( prev ) {
345           prev->next = current->next;
346         } else {
347           frags[index] = current->next;
348         }
349         g_free( current->data );
350         g_free( current );
351         return 1;
352       }
353
354       if( current->seq == seq[index] ) {
355         /* this fragment fits the stream */
356         if( current->data ) {
357           sc->dlen = current->data_len;
358           write_packet_data( index, sc, current->data );
359         }
360         seq[index] += current->len;
361         if( prev ) {
362           prev->next = current->next;
363         } else {
364           frags[index] = current->next;
365         }
366         g_free( current->data );
367         g_free( current );
368         return 1;
369       }
370       prev = current;
371       current = current->next;
372     }
373     if( (glong)(acknowledged - lowest_seq) > 0 ) {
374       /* There are frames missing in the capture file that were seen
375        * by the receiving host. Add dummy stream chunk with the data
376        * "[xxx bytes missing in capture file]".
377        */
378       dummy_str = g_strdup_printf("[%d bytes missing in capture file]",
379                         (int)(lowest_seq - seq[index]) );
380       sc->dlen = (guint32) strlen(dummy_str);
381       write_packet_data( index, sc, dummy_str );
382       g_free(dummy_str);
383       seq[index] = lowest_seq;
384       return 1;
385     }
386   } 
387   return 0;
388 }
389
390 /* this should always be called before we start to reassemble a stream */
391 void
392 reset_tcp_reassembly(void)
393 {
394   tcp_frag *current, *next;
395   int i;
396
397   empty_tcp_stream = TRUE;
398   incomplete_tcp_stream = FALSE;
399   for( i=0; i<2; i++ ) {
400     seq[i] = 0;
401     memset(src_addr[i], '\0', MAX_IPADDR_LEN);
402     src_port[i] = 0;
403     memset(ip_address[i], '\0', MAX_IPADDR_LEN);
404     port[i] = 0;
405     bytes_written[i] = 0;
406     current = frags[i];
407     while( current ) {
408       next = current->next;
409       g_free( current->data );
410       g_free( current );
411       current = next;
412     }
413     frags[i] = NULL;
414   }
415 }
416
417 static void
418 write_packet_data( int index, tcp_stream_chunk *sc, const char *data )
419 {
420   size_t ret;
421
422   ret = fwrite( sc, 1, sizeof(tcp_stream_chunk), data_out_file );
423   DISSECTOR_ASSERT(sizeof(tcp_stream_chunk) == ret);
424   
425   ret = fwrite( data, 1, sc->dlen, data_out_file );
426   DISSECTOR_ASSERT(sc->dlen == ret);
427
428   bytes_written[index] += sc->dlen;
429   empty_tcp_stream = FALSE;
430 }