Fix Dead Store (Dead nested assignment) Warning found by Clang
[obnox/wireshark/wip.git] / tap-icmpstat.c
1 /* tap-icmpstat.c
2  * icmpstat   2011 Christopher Maynard
3  *
4  * $Id$
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
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 /* This module provides icmp echo request/reply SRT statistics to tshark.
26  * It is only used by tshark and not wireshark
27  *
28  * It was based on tap-rpcstat.c and doc/README.tapping.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <stdio.h>
36
37 #ifdef HAVE_SYS_TYPES_H
38 # include <sys/types.h>
39 #endif
40
41 #include <string.h>
42 #include "epan/packet_info.h"
43 #include <epan/tap.h>
44 #include <epan/stat_cmd_args.h>
45 #include <epan/dissectors/packet-icmp.h>
46 #include <math.h>
47
48 /* used to keep track of the ICMP statistics */
49 typedef struct _icmpstat_t {
50     char *filter;
51     GSList *rt_list;
52     guint num_rqsts;
53     guint num_resps;
54     guint min_frame;
55     guint max_frame;
56     double min_msecs;
57     double max_msecs;
58     double tot_msecs;
59 } icmpstat_t;
60
61
62 /* This callback is never used by tshark but it is here for completeness.  When
63  * registering below, we could just have left this function as NULL.
64  *
65  * When used by wireshark, this function will be called whenever we would need
66  * to reset all state, such as when wireshark opens a new file, when it starts
67  * a new capture, when it rescans the packetlist after some prefs have changed,
68  * etc.
69  *
70  * So if your application has some state it needs to clean up in those
71  * situations, here is a good place to put that code.
72  */
73 static void
74 icmpstat_reset(void *tapdata)
75 {
76     icmpstat_t *icmpstat = tapdata;
77
78     g_slist_free(icmpstat->rt_list);
79     memset(icmpstat, 0, sizeof(icmpstat_t));
80     icmpstat->min_msecs = 1.0 * G_MAXUINT;
81 }
82
83
84 static gint compare_doubles(gconstpointer a, gconstpointer b)
85 {
86     double ad, bd;
87
88     ad = *(double *)a;
89     bd = *(double *)b;
90
91     if (ad < bd)
92         return -1;
93     if (ad > bd)
94         return 1;
95     return 0;
96 }
97
98
99 /* This callback is invoked whenever the tap system has seen a packet we might
100  * be interested in.  The function is to be used to only update internal state
101  * information in the *tapdata structure, and if there were state changes which
102  * requires the window to be redrawn, return 1 and (*draw) will be called
103  * sometime later.
104  *
105  * This function should be as lightweight as possible since it executes
106  * together with the normal wireshark dissectors.  Try to push as much
107  * processing as possible into (*draw) instead since that function executes
108  * asynchronously and does not affect the main thread's performance.
109  *
110  * If it is possible, try to do all "filtering" explicitly since you will get
111  * MUCH better performance than applying a similar display-filter in the
112  * register call.
113  *
114  * The third parameter is tap dependent.  Since we register this one to the
115  * "icmp" tap, the third parameter type is icmp_transaction_t.
116  *
117  * function returns :
118  *  0: no updates, no need to call (*draw) later
119  * !0: state has changed, call (*draw) sometime later
120  */
121 static int
122 icmpstat_packet(void *tapdata, packet_info *pinfo _U_, epan_dissect_t *edt _U_, const void *data)
123 {
124     icmpstat_t *icmpstat = tapdata;
125     const icmp_transaction_t *trans = data;
126     double *rt;
127
128     if (trans == NULL)
129         return 0;
130
131     if (trans->resp_frame) {
132         rt = g_malloc(sizeof(double));
133         if (rt == NULL)
134             return 0;
135         *rt = trans->resp_time;
136         icmpstat->rt_list = g_slist_insert_sorted(icmpstat->rt_list, rt, compare_doubles);
137         icmpstat->num_resps++;
138         if (icmpstat->min_msecs > trans->resp_time) {
139             icmpstat->min_frame = trans->resp_frame;
140             icmpstat->min_msecs = trans->resp_time;
141         }
142         if (icmpstat->max_msecs < trans->resp_time) {
143             icmpstat->max_frame = trans->resp_frame;
144             icmpstat->max_msecs = trans->resp_time;
145         }
146         icmpstat->tot_msecs += trans->resp_time;
147     } else if (trans->rqst_frame)
148         icmpstat->num_rqsts++;
149     else
150         return 0;
151
152     return 1;
153 }
154
155
156 /*
157  * Compute the mean, median and standard deviation.
158  */
159 static void compute_stats(icmpstat_t *icmpstat, double *mean, double *med, double *sdev)
160 {
161     GSList *slist = icmpstat->rt_list;
162     double diff;
163     double sq_diff_sum = 0.0;
164
165     if (icmpstat->num_resps == 0 || slist == NULL) {
166         *mean = 0.0;
167         *med = 0.0;
168         *sdev = 0.0;
169         return;
170     }
171
172     /* (arithmetic) mean */
173     *mean = icmpstat->tot_msecs / icmpstat->num_resps;
174
175     /* median: If we have an odd number of elements in our list, then the
176      * median is simply the middle element, otherwise the median is computed by
177      * averaging the 2 elements on either side of the mid-point. */
178     if (icmpstat->num_resps & 1)
179         *med = *(double *)g_slist_nth_data(slist, icmpstat->num_resps / 2);
180     else {
181         *med =
182             (*(double *)g_slist_nth_data(slist, (icmpstat->num_resps - 1) / 2) +
183             *(double *)g_slist_nth_data(slist, icmpstat->num_resps / 2)) / 2;
184     }
185
186     /* (sample) standard deviation */
187     for ( ; slist; slist = g_slist_next(slist)) {
188         diff = *(double *)slist->data - *mean;
189         sq_diff_sum += diff * diff;
190     }
191     if (icmpstat->num_resps > 1)
192         *sdev = sqrt(sq_diff_sum / (icmpstat->num_resps - 1));
193     else
194         *sdev = 0.0;
195 }
196
197
198 /* This callback is used when tshark wants us to draw/update our data to the
199  * output device.  Since this is tshark, the only output is stdout.
200  * TShark will only call this callback once, which is when tshark has finished
201  * reading all packets and exits.
202  * If used with wireshark this may be called any time, perhaps once every 3
203  * seconds or so.
204  * This function may even be called in parallel with (*reset) or (*draw), so
205  * make sure there are no races.  The data in the icmpstat_t can thus change
206  * beneath us.  Beware!
207  *
208  * How best to display the data?  For now, following other tap statistics
209  * output, but here are a few other alternatives we might choose from:
210  *
211  * -> Windows ping output:
212  *      Ping statistics for <IP>:
213  *          Packets: Sent = <S>, Received = <R>, Lost = <L> (<LP>% loss),
214  *      Approximate round trip times in milli-seconds:
215  *          Minimum = <m>ms, Maximum = <M>ms, Average = <A>ms
216  *
217  * -> Cygwin ping output:
218  *      ----<HOST> PING Statistics----
219  *      <S> packets transmitted, <R> packets received, <LP>% packet loss
220  *      round-trip (ms)  min/avg/max/med = <m>/<M>/<A>/<D>
221  *
222  * -> Linux ping output:
223  *      --- <HOST> ping statistics ---
224  *      <S> packets transmitted, <R> received, <LP>% packet loss, time <T>ms
225  *      rtt min/avg/max/mdev = <m>/<A>/<M>/<D> ms
226  */
227 static void
228 icmpstat_draw(void *tapdata)
229 {
230     icmpstat_t *icmpstat = tapdata;
231     unsigned int lost;
232     double mean, sdev, med;
233
234     printf("\n");
235     printf("==========================================================================\n");
236     printf("ICMP Service Response Time (SRT) Statistics (all times in ms):\n");
237     printf("Filter: %s\n", icmpstat->filter ? icmpstat->filter : "<none>");
238     printf("\nRequests  Replies   Lost      %% Loss\n");
239
240     if (icmpstat->num_rqsts) {
241         lost =  icmpstat->num_rqsts - icmpstat->num_resps;
242         compute_stats(icmpstat, &mean, &med, &sdev);
243
244         printf("%-10u%-10u%-10u%5.1f%%\n\n",
245             icmpstat->num_rqsts, icmpstat->num_resps, lost,
246             100.0 * lost / icmpstat->num_rqsts);
247         printf("Minimum   Maximum   Mean      Median    SDeviation     Min Frame Max Frame\n");
248         printf("%-10.3f%-10.3f%-10.3f%-10.3f%-10.3f     %-10u%-10u\n",
249             icmpstat->min_msecs >= G_MAXUINT ? 0.0 : icmpstat->min_msecs,
250             icmpstat->max_msecs, mean, med, sdev,
251             icmpstat->min_frame, icmpstat->max_frame);
252     } else {
253         printf("0         0         0           0.0%%\n\n");
254         printf("Minimum   Maximum   Mean      Median    SDeviation     Min Frame Max Frame\n");
255         printf("0.000     0.000     0.000     0.000     0.000          0         0\n");
256     }
257     printf("==========================================================================\n");
258 }
259
260
261 /* When called, this function will create a new instance of icmpstat.
262  *
263  * This function is called from tshark when it parses the -z icmp, arguments
264  * and it creates a new instance to store statistics in and registers this new
265  * instance for the icmp tap.
266  */
267 static void
268 icmpstat_init(const char *optarg, void* userdata _U_)
269 {
270     icmpstat_t *icmpstat;
271     const char *filter = NULL;
272     GString *error_string;
273
274     if (strstr(optarg, "icmp,srt,"))
275         filter = optarg + strlen("icmp,srt,");
276
277     icmpstat = g_try_malloc(sizeof(icmpstat_t));
278     if (icmpstat == NULL) {
279         fprintf(stderr, "tshark: g_try_malloc() fatal error.\n");
280         exit(1);
281     }
282     memset(icmpstat, 0, sizeof(icmpstat_t));
283     icmpstat->min_msecs = 1.0 * G_MAXUINT;
284
285     if (filter)
286         icmpstat->filter = g_strdup(filter);
287
288 /* It is possible to create a filter and attach it to the callbacks.  Then the
289  * callbacks would only be invoked if the filter matched.
290  *
291  * Evaluating filters is expensive and if we can avoid it and not use them,
292  * then we gain performance.
293  *
294  * In this case we do the filtering for protocol and version inside the
295  * callback itself but use whatever filter the user provided.
296  */
297
298     error_string = register_tap_listener("icmp", icmpstat, icmpstat->filter,
299         TL_REQUIRES_NOTHING, icmpstat_reset, icmpstat_packet, icmpstat_draw);
300     if (error_string) {
301         /* error, we failed to attach to the tap. clean up */
302         if (icmpstat->filter)
303             g_free(icmpstat->filter);
304         g_free(icmpstat);
305
306         fprintf(stderr, "tshark: Couldn't register icmp,srt tap: %s\n",
307             error_string->str);
308         g_string_free(error_string, TRUE);
309         exit(1);
310     }
311 }
312
313
314 void
315 register_tap_listener_icmpstat(void)
316 {
317     register_stat_cmd_arg("icmp,srt", icmpstat_init, NULL);
318 }
319