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