1.9.3 → 1.11.0.
[metze/wireshark/wip.git] / capture_opts.c
1 /* capture_opts.c
2  * Routines for capture options setting
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include "config.h"
26
27 #include <stdio.h>
28
29 #ifdef HAVE_LIBPCAP
30
31 #include <string.h>
32 #include <ctype.h>
33
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #include <glib.h>
39
40 #include <epan/packet.h>
41 #include <epan/prefs.h>
42 #include "ui/simple_dialog.h"
43 #include "capture_ui_utils.h"
44
45 #include "capture_opts.h"
46 #include "ringbuffer.h"
47 #include "clopts_common.h"
48 #include "console_io.h"
49 #include "cmdarg_err.h"
50
51 #include "capture_ifinfo.h"
52 #include "capture-pcap-util.h"
53 #include <wsutil/file_util.h>
54
55 static gboolean capture_opts_output_to_pipe(const char *save_file, gboolean *is_pipe);
56
57
58 void
59 capture_opts_init(capture_options *capture_opts, void *cf)
60 {
61   capture_opts->cf                              = cf;
62   capture_opts->ifaces                          = g_array_new(FALSE, FALSE, sizeof(interface_options));
63   capture_opts->all_ifaces                      = g_array_new(FALSE, FALSE, sizeof(interface_t));
64   capture_opts->num_selected                    = 0;
65   capture_opts->default_options.name            = NULL;
66   capture_opts->default_options.descr           = NULL;
67   capture_opts->default_options.cfilter         = NULL;
68   capture_opts->default_options.has_snaplen     = FALSE;
69   capture_opts->default_options.snaplen         = WTAP_MAX_PACKET_SIZE;
70   capture_opts->default_options.linktype        = -1;
71   capture_opts->default_options.promisc_mode    = TRUE;
72 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
73   capture_opts->default_options.buffer_size     = DEFAULT_CAPTURE_BUFFER_SIZE;
74 #endif
75   capture_opts->default_options.monitor_mode    = FALSE;
76 #ifdef HAVE_PCAP_REMOTE
77   capture_opts->default_options.src_type        = CAPTURE_IFLOCAL;
78   capture_opts->default_options.remote_host     = NULL;
79   capture_opts->default_options.remote_port     = NULL;
80   capture_opts->default_options.auth_type       = CAPTURE_AUTH_NULL;
81   capture_opts->default_options.auth_username   = NULL;
82   capture_opts->default_options.auth_password   = NULL;
83   capture_opts->default_options.datatx_udp      = FALSE;
84   capture_opts->default_options.nocap_rpcap     = TRUE;
85   capture_opts->default_options.nocap_local     = FALSE;
86 #endif
87 #ifdef HAVE_PCAP_SETSAMPLING
88   capture_opts->default_options.sampling_method = CAPTURE_SAMP_NONE;
89   capture_opts->default_options.sampling_param  = 0;
90 #endif
91   capture_opts->saving_to_file                  = FALSE;
92   capture_opts->save_file                       = NULL;
93   capture_opts->group_read_access               = FALSE;
94 #ifdef PCAP_NG_DEFAULT
95   capture_opts->use_pcapng                      = TRUE;             /* Save as pcap-ng by default */
96 #else
97   capture_opts->use_pcapng                      = FALSE;            /* Save as pcap by default */
98 #endif
99   capture_opts->real_time_mode                  = TRUE;
100   capture_opts->show_info                       = TRUE;
101   capture_opts->quit_after_cap                  = getenv("WIRESHARK_QUIT_AFTER_CAPTURE") ? TRUE : FALSE;
102   capture_opts->restart                         = FALSE;
103
104   capture_opts->multi_files_on                  = FALSE;
105   capture_opts->has_file_duration               = FALSE;
106   capture_opts->file_duration                   = 60;               /* 1 min */
107   capture_opts->has_ring_num_files              = FALSE;
108   capture_opts->ring_num_files                  = RINGBUFFER_MIN_NUM_FILES;
109
110   capture_opts->has_autostop_files              = FALSE;
111   capture_opts->autostop_files                  = 1;
112   capture_opts->has_autostop_packets            = FALSE;
113   capture_opts->autostop_packets                = 0;
114   capture_opts->has_autostop_filesize           = FALSE;
115   capture_opts->autostop_filesize               = 1024;             /* 1 MB */
116   capture_opts->has_autostop_duration           = FALSE;
117   capture_opts->autostop_duration               = 60;               /* 1 min */
118
119
120   capture_opts->fork_child                      = -1;               /* invalid process handle */
121 #ifdef _WIN32
122   capture_opts->signal_pipe_write_fd            = -1;
123 #endif
124   capture_opts->state                           = CAPTURE_STOPPED;
125   capture_opts->output_to_pipe                  = FALSE;
126 #ifndef _WIN32
127   capture_opts->owner                           = getuid();
128   capture_opts->group                           = getgid();
129 #endif
130   capture_opts->session_started                 = FALSE;
131 }
132
133
134 /* log content of capture_opts */
135 void
136 capture_opts_log(const char *log_domain, GLogLevelFlags log_level, capture_options *capture_opts) {
137     guint i;
138
139     g_log(log_domain, log_level, "CAPTURE OPTIONS     :");
140     g_log(log_domain, log_level, "CFile               : %p", capture_opts->cf);
141
142     for (i = 0; i < capture_opts->ifaces->len; i++) {
143         interface_options interface_opts;
144
145         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
146         g_log(log_domain, log_level, "Interface name[%02d]  : %s", i, interface_opts.name ? interface_opts.name : "(unspecified)");
147         g_log(log_domain, log_level, "Interface description[%02d] : %s", i, interface_opts.descr ? interface_opts.descr : "(unspecified)");
148         g_log(log_domain, log_level, "Console display name[%02d]: %s", i, interface_opts.console_display_name ? interface_opts.console_display_name : "(unspecified)");
149         g_log(log_domain, log_level, "Capture filter[%02d]  : %s", i, interface_opts.cfilter ? interface_opts.cfilter : "(unspecified)");
150         g_log(log_domain, log_level, "Snap length[%02d] (%u) : %d", i, interface_opts.has_snaplen, interface_opts.snaplen);
151         g_log(log_domain, log_level, "Link Type[%02d]       : %d", i, interface_opts.linktype);
152         g_log(log_domain, log_level, "Promiscuous Mode[%02d]: %s", i, interface_opts.promisc_mode?"TRUE":"FALSE");
153 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
154         g_log(log_domain, log_level, "Buffer size[%02d]     : %d (MB)", i, interface_opts.buffer_size);
155 #endif
156         g_log(log_domain, log_level, "Monitor Mode[%02d]    : %s", i, interface_opts.monitor_mode?"TRUE":"FALSE");
157 #ifdef HAVE_PCAP_REMOTE
158         g_log(log_domain, log_level, "Capture source[%02d]  : %s", i,
159             interface_opts.src_type == CAPTURE_IFLOCAL ? "Local interface" :
160             interface_opts.src_type == CAPTURE_IFREMOTE ? "Remote interface" :
161             "Unknown");
162         if (interface_opts.src_type == CAPTURE_IFREMOTE) {
163             g_log(log_domain, log_level, "Remote host[%02d]     : %s", i, interface_opts.remote_host ? interface_opts.remote_host : "(unspecified)");
164             g_log(log_domain, log_level, "Remote port[%02d]     : %s", i, interface_opts.remote_port ? interface_opts.remote_port : "(unspecified)");
165         }
166         g_log(log_domain, log_level, "Authentication[%02d]  : %s", i,
167             interface_opts.auth_type == CAPTURE_AUTH_NULL ? "Null" :
168             interface_opts.auth_type == CAPTURE_AUTH_PWD ? "By username/password" :
169             "Unknown");
170         if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
171             g_log(log_domain, log_level, "Auth username[%02d]   : %s", i, interface_opts.auth_username ? interface_opts.auth_username : "(unspecified)");
172             g_log(log_domain, log_level, "Auth password[%02d]   : <hidden>", i);
173         }
174         g_log(log_domain, log_level, "UDP data tfer[%02d]   : %u", i, interface_opts.datatx_udp);
175         g_log(log_domain, log_level, "No cap. RPCAP[%02d]   : %u", i, interface_opts.nocap_rpcap);
176         g_log(log_domain, log_level, "No cap. local[%02d]   : %u", i, interface_opts.nocap_local);
177 #endif
178 #ifdef HAVE_PCAP_SETSAMPLING
179         g_log(log_domain, log_level, "Sampling meth.[%02d]  : %d", i, interface_opts.sampling_method);
180         g_log(log_domain, log_level, "Sampling param.[%02d] : %d", i, interface_opts.sampling_param);
181 #endif
182     }
183     g_log(log_domain, log_level, "Interface name[df]  : %s", capture_opts->default_options.name ? capture_opts->default_options.name : "(unspecified)");
184     g_log(log_domain, log_level, "Interface Descr[df] : %s", capture_opts->default_options.descr ? capture_opts->default_options.descr : "(unspecified)");
185     g_log(log_domain, log_level, "Capture filter[df]  : %s", capture_opts->default_options.cfilter ? capture_opts->default_options.cfilter : "(unspecified)");
186     g_log(log_domain, log_level, "Snap length[df] (%u) : %d", capture_opts->default_options.has_snaplen, capture_opts->default_options.snaplen);
187     g_log(log_domain, log_level, "Link Type[df]       : %d", capture_opts->default_options.linktype);
188     g_log(log_domain, log_level, "Promiscuous Mode[df]: %s", capture_opts->default_options.promisc_mode?"TRUE":"FALSE");
189 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
190     g_log(log_domain, log_level, "Buffer size[df]     : %d (MB)", capture_opts->default_options.buffer_size);
191 #endif
192     g_log(log_domain, log_level, "Monitor Mode[df]    : %s", capture_opts->default_options.monitor_mode?"TRUE":"FALSE");
193 #ifdef HAVE_PCAP_REMOTE
194     g_log(log_domain, log_level, "Capture source[df]  : %s",
195         capture_opts->default_options.src_type == CAPTURE_IFLOCAL ? "Local interface" :
196         capture_opts->default_options.src_type == CAPTURE_IFREMOTE ? "Remote interface" :
197         "Unknown");
198     if (capture_opts->default_options.src_type == CAPTURE_IFREMOTE) {
199         g_log(log_domain, log_level, "Remote host[df]     : %s", capture_opts->default_options.remote_host ? capture_opts->default_options.remote_host : "(unspecified)");
200         g_log(log_domain, log_level, "Remote port[df]     : %s", capture_opts->default_options.remote_port ? capture_opts->default_options.remote_port : "(unspecified)");
201     }
202     g_log(log_domain, log_level, "Authentication[df]  : %s",
203         capture_opts->default_options.auth_type == CAPTURE_AUTH_NULL ? "Null" :
204         capture_opts->default_options.auth_type == CAPTURE_AUTH_PWD ? "By username/password" :
205         "Unknown");
206     if (capture_opts->default_options.auth_type == CAPTURE_AUTH_PWD) {
207         g_log(log_domain, log_level, "Auth username[df]   : %s", capture_opts->default_options.auth_username ? capture_opts->default_options.auth_username : "(unspecified)");
208         g_log(log_domain, log_level, "Auth password[df]   : <hidden>");
209     }
210     g_log(log_domain, log_level, "UDP data tfer[df]   : %u", capture_opts->default_options.datatx_udp);
211     g_log(log_domain, log_level, "No cap. RPCAP[df]   : %u", capture_opts->default_options.nocap_rpcap);
212     g_log(log_domain, log_level, "No cap. local[df]   : %u", capture_opts->default_options.nocap_local);
213 #endif
214 #ifdef HAVE_PCAP_SETSAMPLING
215     g_log(log_domain, log_level, "Sampling meth. [df] : %d", capture_opts->default_options.sampling_method);
216     g_log(log_domain, log_level, "Sampling param.[df] : %d", capture_opts->default_options.sampling_param);
217 #endif
218     g_log(log_domain, log_level, "SavingToFile        : %u", capture_opts->saving_to_file);
219     g_log(log_domain, log_level, "SaveFile            : %s", (capture_opts->save_file) ? capture_opts->save_file : "");
220     g_log(log_domain, log_level, "GroupReadAccess     : %u", capture_opts->group_read_access);
221     g_log(log_domain, log_level, "Fileformat          : %s", (capture_opts->use_pcapng) ? "PCAPNG" : "PCAP");
222     g_log(log_domain, log_level, "RealTimeMode        : %u", capture_opts->real_time_mode);
223     g_log(log_domain, log_level, "ShowInfo            : %u", capture_opts->show_info);
224     g_log(log_domain, log_level, "QuitAfterCap        : %u", capture_opts->quit_after_cap);
225
226     g_log(log_domain, log_level, "MultiFilesOn        : %u", capture_opts->multi_files_on);
227     g_log(log_domain, log_level, "FileDuration    (%u) : %u", capture_opts->has_file_duration, capture_opts->file_duration);
228     g_log(log_domain, log_level, "RingNumFiles    (%u) : %u", capture_opts->has_ring_num_files, capture_opts->ring_num_files);
229
230     g_log(log_domain, log_level, "AutostopFiles   (%u) : %u", capture_opts->has_autostop_files, capture_opts->autostop_files);
231     g_log(log_domain, log_level, "AutostopPackets (%u) : %u", capture_opts->has_autostop_packets, capture_opts->autostop_packets);
232     g_log(log_domain, log_level, "AutostopFilesize(%u) : %u (KB)", capture_opts->has_autostop_filesize, capture_opts->autostop_filesize);
233     g_log(log_domain, log_level, "AutostopDuration(%u) : %u", capture_opts->has_autostop_duration, capture_opts->autostop_duration);
234
235     g_log(log_domain, log_level, "ForkChild           : %d", capture_opts->fork_child);
236 #ifdef _WIN32
237     g_log(log_domain, log_level, "SignalPipeWrite     : %d", capture_opts->signal_pipe_write_fd);
238 #endif
239 }
240
241 /*
242  * Given a string of the form "<autostop criterion>:<value>", as might appear
243  * as an argument to a "-a" option, parse it and set the criterion in
244  * question.  Return an indication of whether it succeeded or failed
245  * in some fashion.
246  */
247 static gboolean
248 set_autostop_criterion(capture_options *capture_opts, const char *autostoparg)
249 {
250   gchar *p, *colonp;
251
252   colonp = strchr(autostoparg, ':');
253   if (colonp == NULL)
254     return FALSE;
255
256   p = colonp;
257   *p++ = '\0';
258
259   /*
260    * Skip over any white space (there probably won't be any, but
261    * as we allow it in the preferences file, we might as well
262    * allow it here).
263    */
264   while (isspace((guchar)*p))
265     p++;
266   if (*p == '\0') {
267     /*
268      * Put the colon back, so if our caller uses, in an
269      * error message, the string they passed us, the message
270      * looks correct.
271      */
272     *colonp = ':';
273     return FALSE;
274   }
275   if (strcmp(autostoparg,"duration") == 0) {
276     capture_opts->has_autostop_duration = TRUE;
277     capture_opts->autostop_duration = get_positive_int(p,"autostop duration");
278   } else if (strcmp(autostoparg,"filesize") == 0) {
279     capture_opts->has_autostop_filesize = TRUE;
280     capture_opts->autostop_filesize = get_positive_int(p,"autostop filesize");
281   } else if (strcmp(autostoparg,"files") == 0) {
282     capture_opts->multi_files_on = TRUE;
283     capture_opts->has_autostop_files = TRUE;
284     capture_opts->autostop_files = get_positive_int(p,"autostop files");
285   } else {
286     return FALSE;
287   }
288   *colonp = ':'; /* put the colon back */
289   return TRUE;
290 }
291
292 /*
293  * Given a string of the form "<ring buffer file>:<duration>", as might appear
294  * as an argument to a "-b" option, parse it and set the arguments in
295  * question.  Return an indication of whether it succeeded or failed
296  * in some fashion.
297  */
298 static gboolean
299 get_ring_arguments(capture_options *capture_opts, const char *arg)
300 {
301   gchar *p = NULL, *colonp;
302
303   colonp = strchr(arg, ':');
304   if (colonp == NULL)
305     return FALSE;
306
307   p = colonp;
308   *p++ = '\0';
309
310   /*
311    * Skip over any white space (there probably won't be any, but
312    * as we allow it in the preferences file, we might as well
313    * allow it here).
314    */
315   while (isspace((guchar)*p))
316     p++;
317   if (*p == '\0') {
318     /*
319      * Put the colon back, so if our caller uses, in an
320      * error message, the string they passed us, the message
321      * looks correct.
322      */
323     *colonp = ':';
324     return FALSE;
325   }
326
327   if (strcmp(arg,"files") == 0) {
328     capture_opts->has_ring_num_files = TRUE;
329     capture_opts->ring_num_files = get_positive_int(p, "number of ring buffer files");
330   } else if (strcmp(arg,"filesize") == 0) {
331     capture_opts->has_autostop_filesize = TRUE;
332     capture_opts->autostop_filesize = get_positive_int(p, "ring buffer filesize");
333   } else if (strcmp(arg,"duration") == 0) {
334     capture_opts->has_file_duration = TRUE;
335     capture_opts->file_duration = get_positive_int(p, "ring buffer duration");
336   }
337
338   *colonp = ':';    /* put the colon back */
339   return TRUE;
340 }
341
342 #ifdef HAVE_PCAP_SETSAMPLING
343 /*
344  * Given a string of the form "<sampling type>:<value>", as might appear
345  * as an argument to a "-m" option, parse it and set the arguments in
346  * question.  Return an indication of whether it succeeded or failed
347  * in some fashion.
348  */
349 static gboolean
350 get_sampling_arguments(capture_options *capture_opts, const char *arg)
351 {
352     gchar *p = NULL, *colonp;
353
354     colonp = strchr(arg, ':');
355     if (colonp == NULL)
356         return FALSE;
357
358     p = colonp;
359     *p++ = '\0';
360
361     while (isspace((guchar)*p))
362         p++;
363     if (*p == '\0') {
364         *colonp = ':';
365         return FALSE;
366     }
367
368     if (strcmp(arg, "count") == 0) {
369         if (capture_opts->ifaces->len > 0) {
370             interface_options interface_opts;
371
372             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
373             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
374             interface_opts.sampling_method = CAPTURE_SAMP_BY_COUNT;
375             interface_opts.sampling_param = get_positive_int(p, "sampling count");
376             g_array_append_val(capture_opts->ifaces, interface_opts);
377         } else {
378             capture_opts->default_options.sampling_method = CAPTURE_SAMP_BY_COUNT;
379             capture_opts->default_options.sampling_param = get_positive_int(p, "sampling count");
380         }
381     } else if (strcmp(arg, "timer") == 0) {
382         if (capture_opts->ifaces->len > 0) {
383             interface_options interface_opts;
384
385             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
386             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
387             interface_opts.sampling_method = CAPTURE_SAMP_BY_TIMER;
388             interface_opts.sampling_param = get_positive_int(p, "sampling timer");
389             g_array_append_val(capture_opts->ifaces, interface_opts);
390         } else {
391             capture_opts->default_options.sampling_method = CAPTURE_SAMP_BY_TIMER;
392             capture_opts->default_options.sampling_param = get_positive_int(p, "sampling timer");
393         }
394     }
395     *colonp = ':';
396     return TRUE;
397 }
398 #endif
399
400 #ifdef HAVE_PCAP_REMOTE
401 /*
402  * Given a string of the form "<username>:<password>", as might appear
403  * as an argument to a "-A" option, parse it and set the arguments in
404  * question.  Return an indication of whether it succeeded or failed
405  * in some fashion.
406  */
407 static gboolean
408 get_auth_arguments(capture_options *capture_opts, const char *arg)
409 {
410     gchar *p = NULL, *colonp;
411
412     colonp = strchr(arg, ':');
413     if (colonp == NULL)
414         return FALSE;
415
416     p = colonp;
417     *p++ = '\0';
418
419     while (isspace((guchar)*p))
420         p++;
421
422     if (capture_opts->ifaces->len > 0) {
423         interface_options interface_opts;
424
425         interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
426         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
427         interface_opts.auth_type = CAPTURE_AUTH_PWD;
428         interface_opts.auth_username = g_strdup(arg);
429         interface_opts.auth_password = g_strdup(p);
430         g_array_append_val(capture_opts->ifaces, interface_opts);
431     } else {
432         capture_opts->default_options.auth_type = CAPTURE_AUTH_PWD;
433         capture_opts->default_options.auth_username = g_strdup(arg);
434         capture_opts->default_options.auth_password = g_strdup(p);
435     }
436     *colonp = ':';
437     return TRUE;
438 }
439 #endif
440
441 static int
442 capture_opts_add_iface_opt(capture_options *capture_opts, const char *optarg_str_p)
443 {
444     long        adapter_index;
445     char        *p;
446     GList       *if_list;
447     if_info_t   *if_info;
448     int         err;
449     gchar       *err_str;
450     interface_options interface_opts;
451
452     /*
453      * If the argument is a number, treat it as an index into the list
454      * of adapters, as printed by "tshark -D".
455      *
456      * This should be OK on UNIX systems, as interfaces shouldn't have
457      * names that begin with digits.  It can be useful on Windows, where
458      * more than one interface can have the same name.
459      */
460     adapter_index = strtol(optarg_str_p, &p, 10);
461     if (p != NULL && *p == '\0') {
462         if (adapter_index < 0) {
463             cmdarg_err("The specified adapter index is a negative number");
464             return 1;
465         }
466         if (adapter_index > INT_MAX) {
467             cmdarg_err("The specified adapter index is too large (greater than %d)",
468                        INT_MAX);
469             return 1;
470         }
471         if (adapter_index == 0) {
472             cmdarg_err("There is no interface with that adapter index");
473             return 1;
474         }
475         if_list = capture_interface_list(&err, &err_str);
476         if (if_list == NULL) {
477             switch (err) {
478
479             case CANT_GET_INTERFACE_LIST:
480             case DONT_HAVE_PCAP:
481                 cmdarg_err("%s", err_str);
482                 g_free(err_str);
483                 break;
484
485             case NO_INTERFACES_FOUND:
486                 cmdarg_err("There are no interfaces on which a capture can be done");
487                 break;
488             }
489             return 2;
490         }
491         if_info = (if_info_t *)g_list_nth_data(if_list, (int)(adapter_index - 1));
492         if (if_info == NULL) {
493             cmdarg_err("There is no interface with that adapter index");
494             return 1;
495         }
496         interface_opts.name = g_strdup(if_info->name);
497         if (if_info->friendly_name != NULL) {
498             /*
499              * We have a friendly name for the interface, so display that
500              * instead of the interface name/guid.
501              *
502              * XXX - on UN*X, the interface name is not quite so ugly,
503              * and might be more familiar to users; display them both?
504              */
505             interface_opts.console_display_name = g_strdup(if_info->friendly_name);
506         } else {
507             /* fallback to the interface name */
508             interface_opts.console_display_name = g_strdup(if_info->name);
509         }
510         free_interface_list(if_list);
511     } else {
512         /*
513          * Retrieve the interface list so that we can search for the
514          * specified option amongst both the interface names and the
515          * friendly names and so that we find the friendly name even
516          * if an interface name was specified.
517          *
518          * If we can't get the list, just use the specified option as
519          * the interface name, so that the user can try specifying an
520          * interface explicitly for testing purposes.
521          */
522         if_list = capture_interface_list(&err, &err_str);
523         if (if_list != NULL) {
524             /* try and do an exact match (case insensitive) */
525             GList   *if_entry;
526             gboolean matched;
527
528             matched = FALSE;
529             for (if_entry = g_list_first(if_list); if_entry != NULL;
530                  if_entry = g_list_next(if_entry))
531             {
532                 if_info = (if_info_t *)if_entry->data;
533                 /* exact name check */
534                 if (g_ascii_strcasecmp(if_info->name, optarg_str_p) == 0) {
535                     /* exact match on the interface name, use that for displaying etc */
536                     interface_opts.name = g_strdup(if_info->name);
537
538                     if (if_info->friendly_name != NULL) {
539                         /*
540                          * If we have a friendly name, use that for the
541                          * console display name, as it is the basis for
542                          * the auto generated temp filename.
543                          */
544                         interface_opts.console_display_name = g_strdup(if_info->friendly_name);
545                     } else {
546                         interface_opts.console_display_name = g_strdup(if_info->name);
547                     }
548                     matched = TRUE;
549                     break;
550                 }
551
552                 /* exact friendly name check */
553                 if (if_info->friendly_name != NULL &&
554                     g_ascii_strcasecmp(if_info->friendly_name, optarg_str_p) == 0) {
555                     /* exact match - use the friendly name for display */
556                     interface_opts.name = g_strdup(if_info->name);
557                     interface_opts.console_display_name = g_strdup(if_info->friendly_name);
558                     matched = TRUE;
559                     break;
560                 }
561             }
562
563             /* didn't find, attempt a case insensitive prefix match of the friendly name*/
564             if (!matched) {
565                 size_t prefix_length;
566
567                 prefix_length = strlen(optarg_str_p);
568                 for (if_entry = g_list_first(if_list); if_entry != NULL;
569                      if_entry = g_list_next(if_entry))
570                 {
571                     if_info = (if_info_t *)if_entry->data;
572
573                     if (if_info->friendly_name != NULL &&
574                         g_ascii_strncasecmp(if_info->friendly_name, optarg_str_p, prefix_length) == 0) {
575                         /* prefix match - use the friendly name for display */
576                         interface_opts.name = g_strdup(if_info->name);
577                         interface_opts.console_display_name = g_strdup(if_info->friendly_name);
578                         matched = TRUE;
579                         break;
580                     }
581                 }
582             }
583             if (!matched) {
584                 /*
585                  * We didn't find the interface in the list; just use
586                  * the specified name, so that, for example, if an
587                  * interface doesn't show up in the list for some
588                  * reason, the user can try specifying it explicitly
589                  * for testing purposes.
590                  */
591                 interface_opts.name = g_strdup(optarg_str_p);
592                 interface_opts.console_display_name = g_strdup(optarg_str_p);
593             }
594             free_interface_list(if_list);
595         } else {
596             interface_opts.name = g_strdup(optarg_str_p);
597             interface_opts.console_display_name = g_strdup(optarg_str_p);
598         }
599     }
600
601     /*  We don't set iface_descr here because doing so requires
602      *  capture_ui_utils.c which requires epan/prefs.c which is
603      *  probably a bit too much dependency for here...
604      */
605     interface_opts.descr = g_strdup(capture_opts->default_options.descr);
606     interface_opts.cfilter = g_strdup(capture_opts->default_options.cfilter);
607     interface_opts.snaplen = capture_opts->default_options.snaplen;
608     interface_opts.has_snaplen = capture_opts->default_options.has_snaplen;
609     interface_opts.linktype = capture_opts->default_options.linktype;
610     interface_opts.promisc_mode = capture_opts->default_options.promisc_mode;
611 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
612     interface_opts.buffer_size = capture_opts->default_options.buffer_size;
613 #endif
614     interface_opts.monitor_mode = capture_opts->default_options.monitor_mode;
615 #ifdef HAVE_PCAP_REMOTE
616     interface_opts.src_type = capture_opts->default_options.src_type;
617     interface_opts.remote_host = g_strdup(capture_opts->default_options.remote_host);
618     interface_opts.remote_port = g_strdup(capture_opts->default_options.remote_port);
619     interface_opts.auth_type = capture_opts->default_options.auth_type;
620     interface_opts.auth_username = g_strdup(capture_opts->default_options.auth_username);
621     interface_opts.auth_password = g_strdup(capture_opts->default_options.auth_password);
622     interface_opts.datatx_udp = capture_opts->default_options.datatx_udp;
623     interface_opts.nocap_rpcap = capture_opts->default_options.nocap_rpcap;
624     interface_opts.nocap_local = capture_opts->default_options.nocap_local;
625 #endif
626 #ifdef HAVE_PCAP_SETSAMPLING
627     interface_opts.sampling_method = capture_opts->default_options.sampling_method;
628     interface_opts.sampling_param  = capture_opts->default_options.sampling_param;
629 #endif
630
631     g_array_append_val(capture_opts->ifaces, interface_opts);
632
633     return 0;
634 }
635
636
637 int
638 capture_opts_add_opt(capture_options *capture_opts, int opt, const char *optarg_str_p, gboolean *start_capture)
639 {
640     int status, snaplen;
641
642     switch(opt) {
643     case 'a':        /* autostop criteria */
644         if (set_autostop_criterion(capture_opts, optarg_str_p) == FALSE) {
645             cmdarg_err("Invalid or unknown -a flag \"%s\"", optarg_str_p);
646             return 1;
647         }
648         break;
649 #ifdef HAVE_PCAP_REMOTE
650     case 'A':
651         if (get_auth_arguments(capture_opts, optarg_str_p) == FALSE) {
652             cmdarg_err("Invalid or unknown -A arg \"%s\"", optarg_str_p);
653             return 1;
654         }
655         break;
656 #endif
657     case 'b':        /* Ringbuffer option */
658         capture_opts->multi_files_on = TRUE;
659         if (get_ring_arguments(capture_opts, optarg_str_p) == FALSE) {
660             cmdarg_err("Invalid or unknown -b arg \"%s\"", optarg_str_p);
661             return 1;
662         }
663         break;
664 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
665     case 'B':        /* Buffer size */
666         if (capture_opts->ifaces->len > 0) {
667             interface_options interface_opts;
668
669             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
670             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
671             interface_opts.buffer_size = get_positive_int(optarg_str_p, "buffer size");
672             g_array_append_val(capture_opts->ifaces, interface_opts);
673         } else {
674             capture_opts->default_options.buffer_size = get_positive_int(optarg_str_p, "buffer size");
675         }
676         break;
677 #endif
678     case 'c':        /* Capture n packets */
679         capture_opts->has_autostop_packets = TRUE;
680         capture_opts->autostop_packets = get_positive_int(optarg_str_p, "packet count");
681         break;
682     case 'f':        /* capture filter */
683         if (capture_opts->ifaces->len > 0) {
684             interface_options interface_opts;
685
686             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
687             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
688             g_free(interface_opts.cfilter);
689             interface_opts.cfilter = g_strdup(optarg_str_p);
690             g_array_append_val(capture_opts->ifaces, interface_opts);
691         } else {
692             g_free(capture_opts->default_options.cfilter);
693             capture_opts->default_options.cfilter = g_strdup(optarg_str_p);
694         }
695         break;
696     case 'g':        /* enable group read access on the capture file(s) */
697         capture_opts->group_read_access = TRUE;
698         break;
699     case 'H':        /* Hide capture info dialog box */
700         capture_opts->show_info = FALSE;
701         break;
702     case 'i':        /* Use interface x */
703         status = capture_opts_add_iface_opt(capture_opts, optarg_str_p);
704         if (status != 0) {
705             return status;
706         }
707         break;
708 #ifdef HAVE_PCAP_CREATE
709     case 'I':        /* Capture in monitor mode */
710         if (capture_opts->ifaces->len > 0) {
711             interface_options interface_opts;
712
713             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
714             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
715             interface_opts.monitor_mode = TRUE;
716             g_array_append_val(capture_opts->ifaces, interface_opts);
717         } else {
718             capture_opts->default_options.monitor_mode = TRUE;
719         }
720         break;
721 #endif
722     case 'k':        /* Start capture immediately */
723         *start_capture = TRUE;
724         break;
725     /*case 'l':*/    /* Automatic scrolling in live capture mode */
726 #ifdef HAVE_PCAP_SETSAMPLING
727     case 'm':
728         if (get_sampling_arguments(capture_opts, optarg_str_p) == FALSE) {
729             cmdarg_err("Invalid or unknown -m arg \"%s\"", optarg_str_p);
730             return 1;
731         }
732         break;
733 #endif
734     case 'n':        /* Use pcapng format */
735         capture_opts->use_pcapng = TRUE;
736         break;
737     case 'p':        /* Don't capture in promiscuous mode */
738         if (capture_opts->ifaces->len > 0) {
739             interface_options interface_opts;
740
741             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
742             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
743             interface_opts.promisc_mode = FALSE;
744             g_array_append_val(capture_opts->ifaces, interface_opts);
745         } else {
746             capture_opts->default_options.promisc_mode = FALSE;
747         }
748         break;
749     case 'P':        /* Use pcap format */
750         capture_opts->use_pcapng = FALSE;
751         break;
752 #ifdef HAVE_PCAP_REMOTE
753     case 'r':
754         if (capture_opts->ifaces->len > 0) {
755             interface_options interface_opts;
756
757             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
758             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
759             interface_opts.nocap_rpcap = FALSE;
760             g_array_append_val(capture_opts->ifaces, interface_opts);
761         } else {
762             capture_opts->default_options.nocap_rpcap = FALSE;
763         }
764         break;
765 #endif
766     case 's':        /* Set the snapshot (capture) length */
767         snaplen = get_natural_int(optarg_str_p, "snapshot length");
768         /*
769          * Make a snapshot length of 0 equivalent to the maximum packet
770          * length, mirroring what tcpdump does.
771          */
772         if (snaplen == 0)
773             snaplen = WTAP_MAX_PACKET_SIZE;
774         if (capture_opts->ifaces->len > 0) {
775             interface_options interface_opts;
776
777             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
778             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
779             interface_opts.has_snaplen = TRUE;
780             interface_opts.snaplen = snaplen;
781             g_array_append_val(capture_opts->ifaces, interface_opts);
782         } else {
783             capture_opts->default_options.snaplen = snaplen;
784             capture_opts->default_options.has_snaplen = TRUE;
785         }
786         break;
787     case 'S':        /* "Real-Time" mode: used for following file ala tail -f */
788         capture_opts->real_time_mode = TRUE;
789         break;
790 #ifdef HAVE_PCAP_REMOTE
791     case 'u':
792         if (capture_opts->ifaces->len > 0) {
793             interface_options interface_opts;
794
795             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
796             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
797             interface_opts.datatx_udp = TRUE;
798             g_array_append_val(capture_opts->ifaces, interface_opts);
799         } else {
800             capture_opts->default_options.datatx_udp = TRUE;
801         }
802         break;
803 #endif
804     case 'w':        /* Write to capture file x */
805         capture_opts->saving_to_file = TRUE;
806         g_free(capture_opts->save_file);
807         capture_opts->save_file = g_strdup(optarg_str_p);
808         status = capture_opts_output_to_pipe(capture_opts->save_file, &capture_opts->output_to_pipe);
809         return status;
810     case 'y':        /* Set the pcap data link type */
811         if (capture_opts->ifaces->len > 0) {
812             interface_options interface_opts;
813
814             interface_opts = g_array_index(capture_opts->ifaces, interface_options, capture_opts->ifaces->len - 1);
815             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, capture_opts->ifaces->len - 1);
816             interface_opts.linktype = linktype_name_to_val(optarg_str_p);
817             if (interface_opts.linktype == -1) {
818                 cmdarg_err("The specified data link type \"%s\" isn't valid",
819                            optarg_str_p);
820                 return 1;
821             }
822             g_array_append_val(capture_opts->ifaces, interface_opts);
823         } else {
824             capture_opts->default_options.linktype = linktype_name_to_val(optarg_str_p);
825             if (capture_opts->default_options.linktype == -1) {
826                 cmdarg_err("The specified data link type \"%s\" isn't valid",
827                            optarg_str_p);
828                 return 1;
829             }
830         }
831         break;
832     default:
833         /* the caller is responsible to send us only the right opt's */
834         g_assert_not_reached();
835     }
836
837     return 0;
838 }
839
840 void
841 capture_opts_print_if_capabilities(if_capabilities_t *caps, char *name,
842                                    gboolean monitor_mode)
843 {
844     GList *lt_entry;
845     data_link_info_t *data_link_info;
846
847     if (caps->can_set_rfmon)
848         fprintf_stderr("Data link types of interface %s when %sin monitor mode (use option -y to set):\n",
849                        name, monitor_mode ? "" : "not ");
850     else
851         fprintf_stderr("Data link types of interface %s (use option -y to set):\n", name);
852     for (lt_entry = caps->data_link_types; lt_entry != NULL;
853          lt_entry = g_list_next(lt_entry)) {
854         data_link_info = (data_link_info_t *)lt_entry->data;
855         fprintf_stderr("  %s", data_link_info->name);
856         if (data_link_info->description != NULL)
857             fprintf_stderr(" (%s)", data_link_info->description);
858         else
859             fprintf_stderr(" (not supported)");
860         fprintf_stderr("\n");
861     }
862 }
863
864 /* Print an ASCII-formatted list of interfaces. */
865 void
866 capture_opts_print_interfaces(GList *if_list)
867 {
868     int         i;
869     GList       *if_entry;
870     if_info_t   *if_info;
871
872     i = 1;  /* Interface id number */
873     for (if_entry = g_list_first(if_list); if_entry != NULL;
874          if_entry = g_list_next(if_entry)) {
875         if_info = (if_info_t *)if_entry->data;
876         fprintf_stderr("%d. %s", i++, if_info->name);
877
878         /* Print the interface friendly name, if it exists;
879           if not fall back to vendor description, if it exists. */
880         if (if_info->friendly_name != NULL){
881             fprintf_stderr(" (%s)", if_info->friendly_name);
882         } else {
883             if (if_info->vendor_description != NULL)
884                 fprintf_stderr(" (%s)", if_info->vendor_description);
885         }
886         fprintf_stderr("\n");
887     }
888 }
889
890
891 void
892 capture_opts_trim_snaplen(capture_options *capture_opts, int snaplen_min)
893 {
894     guint i;
895     interface_options interface_opts;
896
897     if (capture_opts->ifaces->len > 0) {
898         for (i = 0; i < capture_opts->ifaces->len; i++) {
899             interface_opts = g_array_index(capture_opts->ifaces, interface_options, 0);
900             capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, 0);
901             if (interface_opts.snaplen < 1)
902                 interface_opts.snaplen = WTAP_MAX_PACKET_SIZE;
903             else if (interface_opts.snaplen < snaplen_min)
904                 interface_opts.snaplen = snaplen_min;
905             g_array_append_val(capture_opts->ifaces, interface_opts);
906         }
907     } else {
908         if (capture_opts->default_options.snaplen < 1)
909             capture_opts->default_options.snaplen = WTAP_MAX_PACKET_SIZE;
910         else if (capture_opts->default_options.snaplen < snaplen_min)
911             capture_opts->default_options.snaplen = snaplen_min;
912     }
913 }
914
915
916 void
917 capture_opts_trim_ring_num_files(capture_options *capture_opts)
918 {
919     /* Check the value range of the ring_num_files parameter */
920     if (capture_opts->ring_num_files > RINGBUFFER_MAX_NUM_FILES) {
921         cmdarg_err("Too many ring buffer files (%u). Reducing to %u.\n", capture_opts->ring_num_files, RINGBUFFER_MAX_NUM_FILES);
922         capture_opts->ring_num_files = RINGBUFFER_MAX_NUM_FILES;
923     } else if (capture_opts->ring_num_files > RINGBUFFER_WARN_NUM_FILES) {
924         cmdarg_err("%u is a lot of ring buffer files.\n", capture_opts->ring_num_files);
925     }
926 #if RINGBUFFER_MIN_NUM_FILES > 0
927     else if (capture_opts->ring_num_files < RINGBUFFER_MIN_NUM_FILES)
928         cmdarg_err("Too few ring buffer files (%u). Increasing to %u.\n", capture_opts->ring_num_files, RINGBUFFER_MIN_NUM_FILES);
929         capture_opts->ring_num_files = RINGBUFFER_MIN_NUM_FILES;
930 #endif
931 }
932
933
934 int
935 capture_opts_trim_iface(capture_options *capture_opts, const char *capture_device)
936 {
937     int status;
938
939     /* Did the user specify an interface to use? */
940     if (capture_opts->num_selected != 0 || capture_opts->ifaces->len != 0) {
941         /* yes they did, return immediately - nothing further to do here */
942         return 0;
943     }
944
945     /* No - is a default specified in the preferences file? */
946     if (capture_device != NULL) {
947         /* Yes - use it. */
948         status = capture_opts_add_iface_opt(capture_opts, capture_device);
949         return status;
950     }
951     /* No default in preferences file, just pick the first interface from the list of interfaces. */
952     return capture_opts_add_iface_opt(capture_opts, "1");
953 }
954
955 #ifndef S_IFIFO
956 #define S_IFIFO _S_IFIFO
957 #endif
958 #ifndef S_ISFIFO
959 #define S_ISFIFO(mode)  (((mode) & S_IFMT) == S_IFIFO)
960 #endif
961
962 /* copied from filesystem.c */
963 static int
964 capture_opts_test_for_fifo(const char *path)
965 {
966   ws_statb64 statb;
967
968   if (ws_stat64(path, &statb) < 0)
969     return errno;
970
971   if (S_ISFIFO(statb.st_mode))
972     return ESPIPE;
973   else
974     return 0;
975 }
976
977 static gboolean
978 capture_opts_output_to_pipe(const char *save_file, gboolean *is_pipe)
979 {
980   int err;
981
982   *is_pipe = FALSE;
983
984   if (save_file != NULL) {
985     /* We're writing to a capture file. */
986     if (strcmp(save_file, "-") == 0) {
987       /* Writing to stdout. */
988       /* XXX - should we check whether it's a pipe?  It's arguably
989          silly to do "-w - >output_file" rather than "-w output_file",
990          but by not checking we might be violating the Principle Of
991          Least Astonishment. */
992       *is_pipe = TRUE;
993     } else {
994       /* not writing to stdout, test for a FIFO (aka named pipe) */
995       err = capture_opts_test_for_fifo(save_file);
996       switch (err) {
997
998       case ENOENT:      /* it doesn't exist, so we'll be creating it,
999                            and it won't be a FIFO */
1000       case 0:           /* found it, but it's not a FIFO */
1001         break;
1002
1003       case ESPIPE:      /* it is a FIFO */
1004         *is_pipe = TRUE;
1005         break;
1006
1007       default:          /* couldn't stat it              */
1008         break;          /* ignore: later attempt to open */
1009                         /*  will generate a nice msg     */
1010       }
1011     }
1012   }
1013
1014   return 0;
1015 }
1016
1017 /*
1018  * Add all non-hidden selected interfaces in the "all interfaces" list
1019  * to the list of interfaces for the capture.
1020  */
1021 void
1022 collect_ifaces(capture_options *capture_opts)
1023 {
1024   guint i;
1025   interface_t device;
1026   interface_options interface_opts;
1027
1028   /* Empty out the existing list of interfaces. */
1029   for (i = capture_opts->ifaces->len; i != 0; i--) {
1030     interface_opts = g_array_index(capture_opts->ifaces, interface_options, i - 1);
1031     g_free(interface_opts.name);
1032     g_free(interface_opts.descr);
1033     if (interface_opts.console_display_name != NULL)
1034         g_free(interface_opts.console_display_name);
1035     g_free(interface_opts.cfilter);
1036 #ifdef HAVE_PCAP_REMOTE
1037     if (interface_opts.src_type == CAPTURE_IFREMOTE) {
1038       g_free(interface_opts.remote_host);
1039       g_free(interface_opts.remote_port);
1040       g_free(interface_opts.auth_username);
1041       g_free(interface_opts.auth_password);
1042     }
1043 #endif
1044     capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i - 1);
1045   }
1046
1047   /* Now fill the list up again. */
1048   for (i = 0; i < capture_opts->all_ifaces->len; i++) {
1049     device = g_array_index(capture_opts->all_ifaces, interface_t, i);
1050     if (!device.hidden && device.selected) {
1051       interface_opts.name = g_strdup(device.name);
1052       interface_opts.descr = g_strdup(device.display_name);
1053       interface_opts.console_display_name = g_strdup(device.name);
1054       interface_opts.linktype = device.active_dlt;
1055       interface_opts.cfilter = g_strdup(device.cfilter);
1056       interface_opts.snaplen = device.snaplen;
1057       interface_opts.has_snaplen = device.has_snaplen;
1058       interface_opts.promisc_mode = device.pmode;
1059 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1060       interface_opts.buffer_size =  device.buffer;
1061 #endif
1062 #ifdef HAVE_PCAP_CREATE
1063       interface_opts.monitor_mode = device.monitor_mode_enabled;
1064 #endif
1065 #ifdef HAVE_PCAP_REMOTE
1066       interface_opts.src_type = CAPTURE_IFREMOTE;
1067       interface_opts.remote_host = g_strdup(device.remote_opts.remote_host_opts.remote_host);
1068       interface_opts.remote_port = g_strdup(device.remote_opts.remote_host_opts.remote_port);
1069       interface_opts.auth_type = device.remote_opts.remote_host_opts.auth_type;
1070       interface_opts.auth_username = g_strdup(device.remote_opts.remote_host_opts.auth_username);
1071       interface_opts.auth_password = g_strdup(device.remote_opts.remote_host_opts.auth_password);
1072       interface_opts.datatx_udp = device.remote_opts.remote_host_opts.datatx_udp;
1073       interface_opts.nocap_rpcap = device.remote_opts.remote_host_opts.nocap_rpcap;
1074       interface_opts.nocap_local = device.remote_opts.remote_host_opts.nocap_local;
1075 #endif
1076 #ifdef HAVE_PCAP_SETSAMPLING
1077       interface_opts.sampling_method = device.remote_opts.sampling_method;
1078       interface_opts.sampling_param  = device.remote_opts.sampling_param;
1079 #endif
1080       g_array_append_val(capture_opts->ifaces, interface_opts);
1081     } else {
1082       continue;
1083     }
1084   }
1085 }
1086
1087
1088 #endif /* HAVE_LIBPCAP */