Add editor modelines; Adjust whitespace as needed.
[metze/wireshark/wip.git] / epan / follow.c
1 /* follow.c
2  *
3  * Copyright 1998 Mike Hall <mlh@io.com>
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  *
23  */
24
25 #include "config.h"
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33
34 #include <glib.h>
35 #include <epan/packet.h>
36 #include <epan/to_str.h>
37 #include <epan/emem.h>
38 #include <epan/dissectors/packet-tcp.h>
39 #include "follow.h"
40 #include <epan/conversation.h>
41
42 #define MAX_IPADDR_LEN  16
43
44 typedef struct _tcp_frag {
45   guint32             seq;
46   guint32             len;
47   guint32             data_len;
48   gchar              *data;
49   struct _tcp_frag   *next;
50 } tcp_frag;
51
52 WS_DLL_PUBLIC_DEF
53 FILE* data_out_file = NULL;
54
55 gboolean empty_tcp_stream;
56 gboolean incomplete_tcp_stream;
57
58 static guint32 tcp_stream_to_follow = 0;
59 static guint8  ip_address[2][MAX_IPADDR_LEN];
60 static guint   port[2];
61 static guint   bytes_written[2];
62 static gboolean is_ipv6 = FALSE;
63
64 static int check_fragments( int, tcp_stream_chunk *, guint32 );
65 static void write_packet_data( int, tcp_stream_chunk *, const char * );
66
67 void
68 follow_stats(follow_stats_t* stats)
69 {
70   int i;
71
72   for (i = 0; i < 2 ; i++) {
73     memcpy(stats->ip_address[i], ip_address[i], MAX_IPADDR_LEN);
74     stats->port[i] = port[i];
75     stats->bytes_written[i] = bytes_written[i];
76     stats->is_ipv6 = is_ipv6;
77   }
78 }
79
80 /* This will build a display filter text that will only
81    pass the packets related to the stream. There is a
82    chance that two streams could intersect, but not a
83    very good one */
84 gchar*
85 build_follow_conv_filter( packet_info *pi ) {
86   char* buf;
87   int len;
88   conversation_t *conv=NULL;
89   struct tcp_analysis *tcpd;
90   wmem_list_frame_t* protos;
91   int proto_id;
92   const char* proto_name;
93   gboolean is_tcp = FALSE, is_udp = FALSE;
94
95   protos = wmem_list_head(pi->layers);
96
97   /* walk the list of a available protocols in the packet to
98       figure out if any of them affect context sensitivity */
99   while (protos != NULL)
100   {
101     proto_id = GPOINTER_TO_INT(wmem_list_frame_data(protos));
102     proto_name = proto_get_protocol_filter_name(proto_id);
103
104     if (!strcmp(proto_name, "tcp")) {
105         is_tcp = TRUE;
106     } else if (!strcmp(proto_name, "udp")) {
107         is_udp = TRUE;
108     }
109
110     protos = wmem_list_frame_next(protos);
111   }
112
113   if( ((pi->net_src.type == AT_IPv4 && pi->net_dst.type == AT_IPv4) ||
114        (pi->net_src.type == AT_IPv6 && pi->net_dst.type == AT_IPv6))
115        && is_tcp && (conv=find_conversation(pi->fd->num, &pi->src, &pi->dst, pi->ptype,
116               pi->srcport, pi->destport, 0)) != NULL ) {
117     /* TCP over IPv4 */
118     tcpd=get_tcp_conversation_data(conv, pi);
119     if (tcpd) {
120       buf = g_strdup_printf("tcp.stream eq %d", tcpd->stream);
121       tcp_stream_to_follow = tcpd->stream;
122       if (pi->net_src.type == AT_IPv4) {
123         len = 4;
124         is_ipv6 = FALSE;
125       } else {
126         len = 16;
127         is_ipv6 = TRUE;
128       }
129     } else {
130       return NULL;
131     }
132   }
133   else if( pi->net_src.type == AT_IPv4 && pi->net_dst.type == AT_IPv4
134           && is_udp ) {
135   /* UDP over IPv4 */
136     buf = g_strdup_printf(
137             "(ip.addr eq %s and ip.addr eq %s) and (udp.port eq %d and udp.port eq %d)",
138             ip_to_str((const guint8 *)pi->net_src.data),
139             ip_to_str((const guint8 *)pi->net_dst.data),
140             pi->srcport, pi->destport );
141     len = 4;
142     is_ipv6 = FALSE;
143   }
144   else if( pi->net_src.type == AT_IPv6 && pi->net_dst.type == AT_IPv6
145        && is_udp ) {
146     /* UDP over IPv6 */
147     buf = g_strdup_printf(
148             "(ipv6.addr eq %s and ipv6.addr eq %s) and (udp.port eq %d and udp.port eq %d)",
149             ip6_to_str((const struct e_in6_addr *)pi->net_src.data),
150             ip6_to_str((const struct e_in6_addr *)pi->net_dst.data),
151             pi->srcport, pi->destport );
152     len = 16;
153     is_ipv6 = TRUE;
154   }
155   else {
156     return NULL;
157   }
158   memcpy(ip_address[0], pi->net_src.data, len);
159   memcpy(ip_address[1], pi->net_dst.data, len);
160   port[0] = pi->srcport;
161   port[1] = pi->destport;
162   return buf;
163 }
164
165 static gboolean         find_tcp_addr;
166 static address          tcp_addr[2];
167 static gboolean         find_tcp_index;
168
169 gchar*
170 build_follow_index_filter(void) {
171   gchar *buf;
172
173   find_tcp_addr = TRUE;
174   buf = g_strdup_printf("tcp.stream eq %d", tcp_stream_to_follow);
175   return buf;
176 }
177
178 /* select a tcp stream to follow via it's address/port pairs */
179 gboolean
180 follow_tcp_addr(const address *addr0, guint port0,
181                 const address *addr1, guint port1)
182 {
183   if (addr0 == NULL || addr1 == NULL || addr0->type != addr1->type ||
184       port0 > G_MAXUINT16 || port1 > G_MAXUINT16 )  {
185     return FALSE;
186   }
187
188   if (find_tcp_index || find_tcp_addr) {
189     return FALSE;
190   }
191
192   switch (addr0->type) {
193   default:
194     return FALSE;
195   case AT_IPv4:
196   case AT_IPv6:
197     is_ipv6 = addr0->type == AT_IPv6;
198     break;
199   }
200
201   find_tcp_index = TRUE;
202
203   memcpy(ip_address[0], addr0->data, addr0->len);
204   SET_ADDRESS(&tcp_addr[0], addr0->type, addr0->len, ip_address[0]);
205   port[0] = port0;
206
207   memcpy(ip_address[1], addr1->data, addr1->len);
208   SET_ADDRESS(&tcp_addr[1], addr1->type, addr1->len, ip_address[1]);
209   port[1] = port1;
210
211   return TRUE;
212 }
213
214 /* select a tcp stream to follow via its index */
215 gboolean
216 follow_tcp_index(guint32 indx)
217 {
218   if (find_tcp_index || find_tcp_addr) {
219     return FALSE;
220   }
221
222   find_tcp_addr = TRUE;
223   tcp_stream_to_follow = indx;
224   memset(ip_address, 0, sizeof ip_address);
225   port[0] = port[1] = 0;
226
227   return TRUE;
228 }
229
230 guint32
231 get_follow_tcp_index(void) {
232   return tcp_stream_to_follow;
233 }
234
235 /* here we are going to try and reconstruct the data portion of a TCP
236    session. We will try and handle duplicates, TCP fragments, and out
237    of order packets in a smart way. */
238
239 static tcp_frag *frags[2] = { 0, 0 };
240 static guint32 seq[2];
241 static guint8 src_addr[2][MAX_IPADDR_LEN];
242 static guint src_port[2] = { 0, 0 };
243
244 void
245 reassemble_tcp( guint32 tcp_stream, guint32 sequence, guint32 acknowledgement,
246                 guint32 length, const char* data, guint32 data_length,
247                 int synflag, address *net_src, address *net_dst,
248                 guint srcport, guint dstport, guint32 packet_num) {
249   guint8 srcx[MAX_IPADDR_LEN], dstx[MAX_IPADDR_LEN];
250   int src_index, j, first = 0, len;
251   guint32 newseq;
252   tcp_frag *tmp_frag;
253   tcp_stream_chunk sc;
254
255   src_index = -1;
256
257   /* First, check if this packet should be processed. */
258   if (find_tcp_index) {
259     if ((port[0] == srcport && port[1] == dstport &&
260          ADDRESSES_EQUAL(&tcp_addr[0], net_src) &&
261          ADDRESSES_EQUAL(&tcp_addr[1], net_dst))
262         ||
263         (port[1] == srcport && port[0] == dstport &&
264          ADDRESSES_EQUAL(&tcp_addr[1], net_src) &&
265          ADDRESSES_EQUAL(&tcp_addr[0], net_dst))) {
266       find_tcp_index = FALSE;
267       tcp_stream_to_follow = tcp_stream;
268     }
269     else {
270       return;
271     }
272   }
273   else if ( tcp_stream != tcp_stream_to_follow )
274     return;
275
276   if ((net_src->type != AT_IPv4 && net_src->type != AT_IPv6) ||
277       (net_dst->type != AT_IPv4 && net_dst->type != AT_IPv6))
278     return;
279
280   if (net_src->type == AT_IPv4)
281     len = 4;
282   else
283     len = 16;
284
285   memcpy(srcx, net_src->data, len);
286   memcpy(dstx, net_dst->data, len);
287
288   /* follow_tcp_index() needs to learn address/port pairs */
289   if (find_tcp_addr) {
290     find_tcp_addr = FALSE;
291     memcpy(ip_address[0], net_src->data, net_src->len);
292     port[0] = srcport;
293     memcpy(ip_address[1], net_dst->data, net_dst->len);
294     port[1] = dstport;
295     if (net_src->type == AT_IPv6 && net_dst->type == AT_IPv6) {
296       is_ipv6 = TRUE;
297     } else {
298       is_ipv6 = FALSE;
299     }
300   }
301
302   /* Check to see if we have seen this source IP and port before.
303      (Yes, we have to check both source IP and port; the connection
304      might be between two different ports on the same machine.) */
305   for( j=0; j<2; j++ ) {
306     if (memcmp(src_addr[j], srcx, len) == 0 && src_port[j] == srcport ) {
307       src_index = j;
308     }
309   }
310   /* we didn't find it if src_index == -1 */
311   if( src_index < 0 ) {
312     /* assign it to a src_index and get going */
313     for( j=0; j<2; j++ ) {
314       if( src_port[j] == 0 ) {
315         memcpy(src_addr[j], srcx, len);
316         src_port[j] = srcport;
317         src_index = j;
318         first = 1;
319         break;
320       }
321     }
322   }
323   if( src_index < 0 ) {
324     fprintf( stderr, "ERROR in reassemble_tcp: Too many addresses!\n");
325     return;
326   }
327
328   if( data_length < length ) {
329     incomplete_tcp_stream = TRUE;
330   }
331
332   /* Before adding data for this flow to the data_out_file, check whether
333    * this frame acks fragments that were already seen. This happens when
334    * frames are not in the capture file, but were actually seen by the
335    * receiving host (Fixes bug 592).
336    */
337   if( frags[1-src_index] ) {
338     memcpy(sc.src_addr, dstx, len);
339     sc.src_port = dstport;
340     sc.dlen     = 0;        /* Will be filled in in check_fragments */
341     while ( check_fragments( 1-src_index, &sc, acknowledgement ) )
342       ;
343   }
344
345   /* Initialize our stream chunk.  This data gets written to disk. */
346   memcpy(sc.src_addr, srcx, len);
347   sc.src_port   = srcport;
348   sc.dlen       = data_length;
349   sc.packet_num = packet_num;
350
351   /* now that we have filed away the srcs, lets get the sequence number stuff
352      figured out */
353   if( first ) {
354     /* this is the first time we have seen this src's sequence number */
355     seq[src_index] = sequence + length;
356     if( synflag ) {
357       seq[src_index]++;
358     }
359     /* write out the packet data */
360     write_packet_data( src_index, &sc, data );
361     return;
362   }
363   /* if we are here, we have already seen this src, let's
364      try and figure out if this packet is in the right place */
365   if( LT_SEQ(sequence, seq[src_index]) ) {
366     /* this sequence number seems dated, but
367        check the end to make sure it has no more
368        info than we have already seen */
369     newseq = sequence + length;
370     if( GT_SEQ(newseq, seq[src_index]) ) {
371       guint32 new_len;
372
373       /* this one has more than we have seen. let's get the
374          payload that we have not seen. */
375
376       new_len = seq[src_index] - sequence;
377
378       if ( data_length <= new_len ) {
379         data = NULL;
380         data_length = 0;
381         incomplete_tcp_stream = TRUE;
382       } else {
383         data += new_len;
384         data_length -= new_len;
385       }
386       sc.dlen = data_length;
387       sequence = seq[src_index];
388       length = newseq - seq[src_index];
389
390       /* this will now appear to be right on time :) */
391     }
392   }
393   if ( EQ_SEQ(sequence, seq[src_index]) ) {
394     /* right on time */
395     seq[src_index] += length;
396     if( synflag ) seq[src_index]++;
397     if( data ) {
398       write_packet_data( src_index, &sc, data );
399     }
400     /* done with the packet, see if it caused a fragment to fit */
401     while( check_fragments( src_index, &sc, 0 ) )
402       ;
403   }
404   else {
405     /* out of order packet */
406     if(data_length > 0 && GT_SEQ(sequence, seq[src_index]) ) {
407       tmp_frag = (tcp_frag *)g_malloc( sizeof( tcp_frag ) );
408       tmp_frag->data = (gchar *)g_malloc( data_length );
409       tmp_frag->seq = sequence;
410       tmp_frag->len = length;
411       tmp_frag->data_len = data_length;
412       memcpy( tmp_frag->data, data, data_length );
413       if( frags[src_index] ) {
414         tmp_frag->next = frags[src_index];
415       } else {
416         tmp_frag->next = NULL;
417       }
418       frags[src_index] = tmp_frag;
419     }
420   }
421 } /* end reassemble_tcp */
422
423 /* here we search through all the frag we have collected to see if
424    one fits */
425 static int
426 check_fragments( int idx, tcp_stream_chunk *sc, guint32 acknowledged ) {
427   tcp_frag *prev = NULL;
428   tcp_frag *current;
429   guint32 lowest_seq;
430   gchar *dummy_str;
431
432   current = frags[idx];
433   if( current ) {
434     lowest_seq = current->seq;
435     while( current ) {
436       if( GT_SEQ(lowest_seq, current->seq) ) {
437         lowest_seq = current->seq;
438       }
439
440       if( LT_SEQ(current->seq, seq[idx]) ) {
441         guint32 newseq;
442         /* this sequence number seems dated, but
443            check the end to make sure it has no more
444            info than we have already seen */
445         newseq = current->seq + current->len;
446         if( GT_SEQ(newseq, seq[idx]) ) {
447           guint32 new_pos;
448
449           /* this one has more than we have seen. let's get the
450              payload that we have not seen. This happens when
451              part of this frame has been retransmitted */
452
453           new_pos = seq[idx] - current->seq;
454
455           if ( current->data_len > new_pos ) {
456             sc->dlen = current->data_len - new_pos;
457             write_packet_data( idx, sc, current->data + new_pos );
458           }
459
460           seq[idx] += (current->len - new_pos);
461         }
462
463         /* Remove the fragment from the list as the "new" part of it
464          * has been processed or its data has been seen already in
465          * another packet. */
466         if( prev ) {
467           prev->next = current->next;
468         } else {
469           frags[idx] = current->next;
470         }
471         g_free( current->data );
472         g_free( current );
473         return 1;
474       }
475
476       if( EQ_SEQ(current->seq, seq[idx]) ) {
477         /* this fragment fits the stream */
478         if( current->data ) {
479           sc->dlen = current->data_len;
480           write_packet_data( idx, sc, current->data );
481         }
482         seq[idx] += current->len;
483         if( prev ) {
484           prev->next = current->next;
485         } else {
486           frags[idx] = current->next;
487         }
488         g_free( current->data );
489         g_free( current );
490         return 1;
491       }
492       prev = current;
493       current = current->next;
494     }
495     if( GT_SEQ(acknowledged, lowest_seq) ) {
496       /* There are frames missing in the capture file that were seen
497        * by the receiving host. Add dummy stream chunk with the data
498        * "[xxx bytes missing in capture file]".
499        */
500       dummy_str = g_strdup_printf("[%d bytes missing in capture file]",
501                         (int)(lowest_seq - seq[idx]) );
502       sc->dlen = (guint32) strlen(dummy_str);
503       write_packet_data( idx, sc, dummy_str );
504       g_free(dummy_str);
505       seq[idx] = lowest_seq;
506       return 1;
507     }
508   }
509   return 0;
510 }
511
512 /* this should always be called before we start to reassemble a stream */
513 void
514 reset_tcp_reassembly(void)
515 {
516   tcp_frag *current, *next;
517   int i;
518
519   empty_tcp_stream = TRUE;
520   incomplete_tcp_stream = FALSE;
521   find_tcp_addr = FALSE;
522   find_tcp_index = FALSE;
523   for( i=0; i<2; i++ ) {
524     seq[i] = 0;
525     memset(src_addr[i], '\0', MAX_IPADDR_LEN);
526     src_port[i] = 0;
527     memset(ip_address[i], '\0', MAX_IPADDR_LEN);
528     port[i] = 0;
529     bytes_written[i] = 0;
530     current = frags[i];
531     while( current ) {
532       next = current->next;
533       g_free( current->data );
534       g_free( current );
535       current = next;
536     }
537     frags[i] = NULL;
538   }
539 }
540
541 static void
542 write_packet_data( int idx, tcp_stream_chunk *sc, const char *data )
543 {
544   size_t ret;
545
546   ret = fwrite( sc, 1, sizeof(tcp_stream_chunk), data_out_file );
547   DISSECTOR_ASSERT(sizeof(tcp_stream_chunk) == ret);
548
549   ret = fwrite( data, 1, sc->dlen, data_out_file );
550   DISSECTOR_ASSERT(sc->dlen == ret);
551
552   bytes_written[idx] += sc->dlen;
553   empty_tcp_stream = FALSE;
554 }
555
556 /*
557  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
558  *
559  * Local Variables:
560  * c-basic-offset: 2
561  * tab-width: 8
562  * indent-tabs-mode: nil
563  * End:
564  *
565  * ex: set shiftwidth=2 tabstop=8 expandtab:
566  * :indentSize=2:tabSize=8:noTabs=true:
567  */