If we have pcap_open, call it instead of pcap_open_live, otherwise we might
[obnox/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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
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 #ifdef HAVE_SYS_TYPES_H
39 # include <sys/types.h>
40 #endif
41
42 #ifdef HAVE_NETINET_IN_H
43 #include <netinet/in.h>
44 #endif
45
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
48 #endif
49
50 #ifdef HAVE_SYS_SOCKET_H
51 #include <sys/socket.h>         /* needed to define AF_ values on UNIX */
52 #endif
53
54 #ifdef HAVE_WINSOCK2_H
55 #include <winsock2.h>           /* needed to define AF_ values on Windows */
56 #endif
57
58 #ifdef NEED_INET_V6DEFS_H
59 # include "inet_v6defs.h"
60 #endif
61
62 #include <glib.h>
63
64 #include <epan/packet.h>
65
66 #include "capture_opts.h"
67 #include "ringbuffer.h"
68 #include "clopts_common.h"
69 #include "cmdarg_err.h"
70
71 #include "capture-pcap-util.h"
72 #include <wiretap/file_util.h>
73
74 typedef struct {
75     char *name;
76     pcap_t *pch;
77 } if_stat_t;
78
79 static gboolean capture_opts_output_to_pipe(const char *save_file, gboolean *is_pipe);
80
81
82 void
83 capture_opts_init(capture_options *capture_opts, void *cfile)
84 {
85   capture_opts->cf                      = cfile;
86   capture_opts->cfilter                 = g_strdup("");     /* No capture filter string specified */
87   capture_opts->iface                   = NULL;             /* Default is "pick the first interface" */
88   capture_opts->iface_descr             = NULL;
89 #ifdef HAVE_PCAP_REMOTE
90   capture_opts->src_type                = CAPTURE_IFLOCAL;
91   capture_opts->remote_host             = NULL;
92   capture_opts->remote_port             = NULL;
93   capture_opts->auth_type               = CAPTURE_AUTH_NULL;
94   capture_opts->auth_username           = NULL;
95   capture_opts->auth_password           = NULL;
96   capture_opts->datatx_udp              = FALSE;
97   capture_opts->nocap_rpcap             = TRUE;
98   capture_opts->nocap_local             = FALSE;
99 #ifdef HAVE_PCAP_SETSAMPLING
100   capture_opts->sampling_method         = CAPTURE_SAMP_NONE;
101   capture_opts->sampling_param          = 0;
102 #endif
103 #endif
104 #ifdef _WIN32
105   capture_opts->buffer_size             = 1;                /* 1 MB */
106 #endif
107   capture_opts->has_snaplen             = FALSE;
108   capture_opts->snaplen                 = WTAP_MAX_PACKET_SIZE; /* snapshot length - default is
109                                                                    infinite, in effect */
110   capture_opts->promisc_mode            = TRUE;             /* promiscuous mode is the default */
111   capture_opts->linktype                = -1;               /* the default linktype */
112   capture_opts->saving_to_file          = FALSE;
113   capture_opts->save_file               = NULL;
114   capture_opts->real_time_mode          = TRUE;
115   capture_opts->show_info               = TRUE;
116   capture_opts->quit_after_cap          = FALSE;
117   capture_opts->restart                 = FALSE;
118
119   capture_opts->multi_files_on          = FALSE;
120   capture_opts->has_file_duration       = FALSE;
121   capture_opts->file_duration           = 60;               /* 1 min */
122   capture_opts->has_ring_num_files      = FALSE;
123   capture_opts->ring_num_files          = RINGBUFFER_MIN_NUM_FILES;
124
125   capture_opts->has_autostop_files      = FALSE;
126   capture_opts->autostop_files          = 1;
127   capture_opts->has_autostop_packets    = FALSE;
128   capture_opts->autostop_packets        = 0;
129   capture_opts->has_autostop_filesize   = FALSE;
130   capture_opts->autostop_filesize       = 1024;             /* 1 MB */
131   capture_opts->has_autostop_duration   = FALSE;
132   capture_opts->autostop_duration       = 60;               /* 1 min */
133
134
135   capture_opts->fork_child              = -1;               /* invalid process handle */
136 #ifdef _WIN32
137   capture_opts->signal_pipe_write_fd    = -1;
138 #endif
139   capture_opts->state                   = CAPTURE_STOPPED;
140   capture_opts->output_to_pipe          = FALSE;
141 #ifndef _WIN32
142   capture_opts->owner                   = getuid();
143   capture_opts->group                   = getgid();
144 #endif
145 }
146
147
148 /* log content of capture_opts */
149 void
150 capture_opts_log(const char *log_domain, GLogLevelFlags log_level, capture_options *capture_opts) {
151     g_log(log_domain, log_level, "CAPTURE OPTIONS    :");
152     g_log(log_domain, log_level, "CFile              : 0x%p", capture_opts->cf);
153     g_log(log_domain, log_level, "Filter             : %s", capture_opts->cfilter);
154     g_log(log_domain, log_level, "Interface          : %s", capture_opts->iface);
155     /* iface_descr may not been filled in and some C Libraries hate a null ptr for %s */
156     g_log(log_domain, log_level, "Interface Descr    : %s",
157           capture_opts->iface_descr ? capture_opts->iface_descr : "<null>");
158 #ifdef HAVE_PCAP_REMOTE
159     g_log(log_domain, log_level, "Capture source     : %s",
160         capture_opts->src_type == CAPTURE_IFLOCAL ? "Local interface" :
161         capture_opts->src_type == CAPTURE_IFREMOTE ? "Remote interface" :
162         "Unknown");
163     if (capture_opts->src_type == CAPTURE_IFREMOTE) {
164         g_log(log_domain, log_level, "Remote host        : %s", capture_opts->remote_host);
165         g_log(log_domain, log_level, "Remote port        : %u", capture_opts->remote_port);
166     }
167     g_log(log_domain, log_level, "Authentication     : %s",
168         capture_opts->auth_type == CAPTURE_AUTH_NULL ? "Null" :
169         capture_opts->auth_type == CAPTURE_AUTH_PWD ? "By username/password" :
170         "Unknown");
171     if (capture_opts->auth_type == CAPTURE_AUTH_PWD) {
172         g_log(log_domain, log_level, "Auth username      : %s", capture_opts->auth_password);
173         g_log(log_domain, log_level, "Auth password      : <hidden>");
174     }
175     g_log(log_domain, log_level, "UDP data transfer  : %u", capture_opts->datatx_udp);
176     g_log(log_domain, log_level, "No capture RPCAP   : %u", capture_opts->nocap_rpcap);
177     g_log(log_domain, log_level, "No capture local   : %u", capture_opts->nocap_local);
178 #endif
179 #ifdef _WIN32
180     g_log(log_domain, log_level, "BufferSize         : %u (MB)", capture_opts->buffer_size);
181 #endif
182     g_log(log_domain, log_level, "SnapLen         (%u): %u", capture_opts->has_snaplen, capture_opts->snaplen);
183     g_log(log_domain, log_level, "Promisc            : %u", capture_opts->promisc_mode);
184     g_log(log_domain, log_level, "LinkType           : %d", capture_opts->linktype);
185     g_log(log_domain, log_level, "SavingToFile       : %u", capture_opts->saving_to_file);
186     g_log(log_domain, log_level, "SaveFile           : %s", (capture_opts->save_file) ? capture_opts->save_file : "");
187     g_log(log_domain, log_level, "RealTimeMode       : %u", capture_opts->real_time_mode);
188     g_log(log_domain, log_level, "ShowInfo           : %u", capture_opts->show_info);
189     g_log(log_domain, log_level, "QuitAfterCap       : %u", capture_opts->quit_after_cap);
190
191     g_log(log_domain, log_level, "MultiFilesOn       : %u", capture_opts->multi_files_on);
192     g_log(log_domain, log_level, "FileDuration    (%u): %u", capture_opts->has_file_duration, capture_opts->file_duration);
193     g_log(log_domain, log_level, "RingNumFiles    (%u): %u", capture_opts->has_ring_num_files, capture_opts->ring_num_files);
194
195     g_log(log_domain, log_level, "AutostopFiles   (%u): %u", capture_opts->has_autostop_files, capture_opts->autostop_files);
196     g_log(log_domain, log_level, "AutostopPackets (%u): %u", capture_opts->has_autostop_packets, capture_opts->autostop_packets);
197     g_log(log_domain, log_level, "AutostopFilesize(%u): %u (KB)", capture_opts->has_autostop_filesize, capture_opts->autostop_filesize);
198     g_log(log_domain, log_level, "AutostopDuration(%u): %u", capture_opts->has_autostop_duration, capture_opts->autostop_duration);
199
200     g_log(log_domain, log_level, "ForkChild          : %d", capture_opts->fork_child);
201 #ifdef _WIN32
202     g_log(log_domain, log_level, "SignalPipeWrite    : %d", capture_opts->signal_pipe_write_fd);
203 #endif
204 }
205
206 /*
207  * Given a string of the form "<autostop criterion>:<value>", as might appear
208  * as an argument to a "-a" option, parse it and set the criterion in
209  * question.  Return an indication of whether it succeeded or failed
210  * in some fashion.
211  */
212 static gboolean
213 set_autostop_criterion(capture_options *capture_opts, const char *autostoparg)
214 {
215   gchar *p, *colonp;
216
217   colonp = strchr(autostoparg, ':');
218   if (colonp == NULL)
219     return FALSE;
220
221   p = colonp;
222   *p++ = '\0';
223
224   /*
225    * Skip over any white space (there probably won't be any, but
226    * as we allow it in the preferences file, we might as well
227    * allow it here).
228    */
229   while (isspace((guchar)*p))
230     p++;
231   if (*p == '\0') {
232     /*
233      * Put the colon back, so if our caller uses, in an
234      * error message, the string they passed us, the message
235      * looks correct.
236      */
237     *colonp = ':';
238     return FALSE;
239   }
240   if (strcmp(autostoparg,"duration") == 0) {
241     capture_opts->has_autostop_duration = TRUE;
242     capture_opts->autostop_duration = get_positive_int(p,"autostop duration");
243   } else if (strcmp(autostoparg,"filesize") == 0) {
244     capture_opts->has_autostop_filesize = TRUE;
245     capture_opts->autostop_filesize = get_positive_int(p,"autostop filesize");
246   } else if (strcmp(autostoparg,"files") == 0) {
247     capture_opts->multi_files_on = TRUE;
248     capture_opts->has_autostop_files = TRUE;
249     capture_opts->autostop_files = get_positive_int(p,"autostop files");
250   } else {
251     return FALSE;
252   }
253   *colonp = ':'; /* put the colon back */
254   return TRUE;
255 }
256
257 /*
258  * Given a string of the form "<ring buffer file>:<duration>", as might appear
259  * as an argument to a "-b" option, parse it and set the arguments in
260  * question.  Return an indication of whether it succeeded or failed
261  * in some fashion.
262  */
263 static gboolean
264 get_ring_arguments(capture_options *capture_opts, const char *arg)
265 {
266   gchar *p = NULL, *colonp;
267
268   colonp = strchr(arg, ':');
269   if (colonp == NULL)
270     return FALSE;
271
272   p = colonp;
273   *p++ = '\0';
274
275   /*
276    * Skip over any white space (there probably won't be any, but
277    * as we allow it in the preferences file, we might as well
278    * allow it here).
279    */
280   while (isspace((guchar)*p))
281     p++;
282   if (*p == '\0') {
283     /*
284      * Put the colon back, so if our caller uses, in an
285      * error message, the string they passed us, the message
286      * looks correct.
287      */
288     *colonp = ':';
289     return FALSE;
290   }
291
292   if (strcmp(arg,"files") == 0) {
293     capture_opts->has_ring_num_files = TRUE;
294     capture_opts->ring_num_files = get_natural_int(p, "number of ring buffer files");
295   } else if (strcmp(arg,"filesize") == 0) {
296     capture_opts->has_autostop_filesize = TRUE;
297     capture_opts->autostop_filesize = get_positive_int(p, "ring buffer filesize");
298   } else if (strcmp(arg,"duration") == 0) {
299     capture_opts->has_file_duration = TRUE;
300     capture_opts->file_duration = get_positive_int(p, "ring buffer duration");
301   }
302
303   *colonp = ':';    /* put the colon back */
304   return TRUE;
305 }
306
307 #ifdef HAVE_PCAP_SETSAMPLING
308 /*
309  * Given a string of the form "<sampling type>:<value>", as might appear
310  * as an argument to a "-m" option, parse it and set the arguments in
311  * question.  Return an indication of whether it succeeded or failed
312  * in some fashion.
313  */
314 static gboolean
315 get_sampling_arguments(capture_options *capture_opts, const char *arg)
316 {
317     gchar *p = NULL, *colonp;
318
319     colonp = strchr(arg, ':');
320     if (colonp == NULL)
321         return FALSE;
322
323     p = colonp;
324     *p++ = '\0';
325
326     while (isspace((guchar)*p))
327         p++;
328     if (*p == '\0') {
329         *colonp = ':';
330         return FALSE;
331     }
332
333     if (strcmp(arg, "count") == 0) {
334         capture_opts->sampling_method = CAPTURE_SAMP_BY_COUNT;
335         capture_opts->sampling_param = get_positive_int(p, "sampling count");
336     } else if (strcmp(arg, "timer") == 0) {
337         capture_opts->sampling_method = CAPTURE_SAMP_BY_TIMER;
338         capture_opts->sampling_param = get_positive_int(p, "sampling timer");
339     }
340     *colonp = ':';
341     return TRUE;
342 }
343 #endif
344
345 #ifdef HAVE_PCAP_REMOTE
346 /*
347  * Given a string of the form "<username>:<password>", as might appear
348  * as an argument to a "-A" option, parse it and set the arguments in
349  * question.  Return an indication of whether it succeeded or failed
350  * in some fashion.
351  */
352 static gboolean
353 get_auth_arguments(capture_options *capture_opts, const char *arg)
354 {
355     gchar *p = NULL, *colonp;
356
357     colonp = strchr(arg, ':');
358     if (colonp == NULL)
359         return FALSE;
360
361     p = colonp;
362     *p++ = '\0';
363
364     while (isspace((guchar)*p))
365         p++;
366
367     capture_opts->auth_type = CAPTURE_AUTH_PWD;
368     capture_opts->auth_username = g_strdup(arg);
369     capture_opts->auth_password = g_strdup(p);
370     *colonp = ':';
371     return TRUE;
372 }
373 #endif
374
375 static int
376 capture_opts_add_iface_opt(capture_options *capture_opts, const char *optarg)
377 {
378     long        adapter_index;
379     char        *p;
380     GList       *if_list;
381     if_info_t   *if_info;
382     int         err;
383     gchar       *err_str;
384
385
386     /*
387      * If the argument is a number, treat it as an index into the list
388      * of adapters, as printed by "tshark -D".
389      *
390      * This should be OK on UNIX systems, as interfaces shouldn't have
391      * names that begin with digits.  It can be useful on Windows, where
392      * more than one interface can have the same name.
393      */
394     adapter_index = strtol(optarg, &p, 10);
395     if (p != NULL && *p == '\0') {
396       if (adapter_index < 0) {
397         cmdarg_err("The specified adapter index is a negative number");
398         return 1;
399       }
400       if (adapter_index > INT_MAX) {
401         cmdarg_err("The specified adapter index is too large (greater than %d)",
402             INT_MAX);
403         return 1;
404       }
405       if (adapter_index == 0) {
406         cmdarg_err("There is no interface with that adapter index");
407         return 1;
408       }
409       if_list = get_interface_list(&err, &err_str);
410       if (if_list == NULL) {
411         switch (err) {
412
413         case CANT_GET_INTERFACE_LIST:
414             cmdarg_err("%s", err_str);
415             g_free(err_str);
416             break;
417
418         case NO_INTERFACES_FOUND:
419             cmdarg_err("There are no interfaces on which a capture can be done");
420             break;
421         }
422         return 2;
423       }
424       if_info = g_list_nth_data(if_list, adapter_index - 1);
425       if (if_info == NULL) {
426         cmdarg_err("There is no interface with that adapter index");
427         return 1;
428       }
429       capture_opts->iface = g_strdup(if_info->name);
430       /*  We don't set iface_descr here because doing so requires
431        *  capture_ui_utils.c which requires epan/prefs.c which is
432        *  probably a bit too much dependency for here...
433        */
434       free_interface_list(if_list);
435     } else {
436       capture_opts->iface = g_strdup(optarg);
437     }
438
439     return 0;
440 }
441
442 int
443 capture_opts_add_opt(capture_options *capture_opts, int opt, const char *optarg, gboolean *start_capture)
444 {
445     int status;
446
447     switch(opt) {
448     case 'a':        /* autostop criteria */
449         if (set_autostop_criterion(capture_opts, optarg) == FALSE) {
450           cmdarg_err("Invalid or unknown -a flag \"%s\"", optarg);
451           return 1;
452         }
453         break;
454 #ifdef HAVE_PCAP_REMOTE
455     case 'A':
456         if (get_auth_arguments(capture_opts, optarg) == FALSE) {
457             cmdarg_err("Invalid or unknown -A arg \"%s\"", optarg);
458             return 1;
459         }
460         break;
461 #endif
462     case 'b':        /* Ringbuffer option */
463         capture_opts->multi_files_on = TRUE;
464         if (get_ring_arguments(capture_opts, optarg) == FALSE) {
465           cmdarg_err("Invalid or unknown -b arg \"%s\"", optarg);
466           return 1;
467         }
468         break;
469 #ifdef _WIN32
470     case 'B':        /* Buffer size */
471         capture_opts->buffer_size = get_positive_int(optarg, "buffer size");
472         break;
473 #endif
474     case 'c':        /* Capture n packets */
475         capture_opts->has_autostop_packets = TRUE;
476         capture_opts->autostop_packets = get_positive_int(optarg, "packet count");
477         break;
478     case 'f':        /* capture filter */
479         if (capture_opts->has_cfilter) {
480             cmdarg_err("More than one -f argument specified");
481             return 1;
482         }
483         capture_opts->has_cfilter = TRUE;
484         g_free(capture_opts->cfilter);
485         capture_opts->cfilter = g_strdup(optarg);
486         break;
487     case 'H':        /* Hide capture info dialog box */
488         capture_opts->show_info = FALSE;
489         break;
490     case 'i':        /* Use interface x */
491         status = capture_opts_add_iface_opt(capture_opts, optarg);
492         if(status != 0) {
493             return status;
494         }
495         break;
496     case 'k':        /* Start capture immediately */
497         *start_capture = TRUE;
498         break;
499     /*case 'l':*/    /* Automatic scrolling in live capture mode */
500 #ifdef HAVE_PCAP_SETSAMPLING
501     case 'm':
502         if (get_sampling_arguments(capture_opts, optarg) == FALSE) {
503             cmdarg_err("Invalid or unknown -m arg \"%s\"", optarg);
504             return 1;
505         }
506         break;
507 #endif
508     case 'p':        /* Don't capture in promiscuous mode */
509         capture_opts->promisc_mode = FALSE;
510         break;
511     case 'Q':        /* Quit after capture (just capture to file) */
512         capture_opts->quit_after_cap  = TRUE;
513         *start_capture   = TRUE;  /*** -Q implies -k !! ***/
514         break;
515 #ifdef HAVE_PCAP_REMOTE
516     case 'r':
517         capture_opts->nocap_rpcap = FALSE;
518         break;
519 #endif
520     case 's':        /* Set the snapshot (capture) length */
521         capture_opts->has_snaplen = TRUE;
522         capture_opts->snaplen = get_positive_int(optarg, "snapshot length");
523         break;
524     case 'S':        /* "Real-Time" mode: used for following file ala tail -f */
525         capture_opts->real_time_mode = TRUE;
526         break;
527 #ifdef HAVE_PCAP_REMOTE
528     case 'u':
529         capture_opts->datatx_udp = TRUE;
530         break;
531 #endif
532     case 'w':        /* Write to capture file x */
533         capture_opts->saving_to_file = TRUE;
534         g_free(capture_opts->save_file);
535 #if defined _WIN32 && GLIB_CHECK_VERSION(2,6,0)
536         /* since GLib 2.6, we need to convert filenames to utf8 for Win32 */
537         capture_opts->save_file = g_locale_to_utf8(optarg, -1, NULL, NULL, NULL);
538 #else
539         capture_opts->save_file = g_strdup(optarg);
540 #endif
541         status = capture_opts_output_to_pipe(capture_opts->save_file, &capture_opts->output_to_pipe);
542         return status;
543     case 'y':        /* Set the pcap data link type */
544 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
545         capture_opts->linktype = linktype_name_to_val(optarg);
546         if (capture_opts->linktype == -1) {
547           cmdarg_err("The specified data link type \"%s\" isn't valid",
548                   optarg);
549           return 1;
550         }
551 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
552         /* we can't get the type name, just treat it as a number */
553         capture_opts->linktype = get_natural_int(optarg, "data link type");
554 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
555         break;
556     default:
557         /* the caller is responsible to send us only the right opt's */
558         g_assert_not_reached();
559     }
560
561     return 0;
562 }
563
564 /*
565  * If you change the output format of this function, you MUST update
566  * capture_sync.c:sync_linktype_list_open() accordingly!
567  */
568 int
569 capture_opts_list_link_layer_types(capture_options *capture_opts, gboolean machine_readable)
570 {
571     gchar *err_str, *desc_str;
572     GList *lt_list, *lt_entry;
573     data_link_info_t *data_link_info;
574
575     /* Get the list of link-layer types for the capture device. */
576     lt_list = get_pcap_linktype_list(capture_opts->iface, &err_str);
577     if (lt_list == NULL) {
578       if (err_str != NULL) {
579         cmdarg_err("The list of data link types for the capture device \"%s\" could not be obtained (%s)."
580          "Please check to make sure you have sufficient permissions, and that\n"
581          "you have the proper interface or pipe specified.\n", capture_opts->iface, err_str);
582         g_free(err_str);
583       } else
584         cmdarg_err("The capture device \"%s\" has no data link types.", capture_opts->iface);
585       return 2;
586     }
587     if (machine_readable) {    /* tab-separated values to stdout */
588         for (lt_entry = lt_list; lt_entry != NULL; lt_entry = g_list_next(lt_entry)) {
589           data_link_info = lt_entry->data;
590           if (data_link_info->description != NULL)
591               desc_str = data_link_info->description;
592           else
593               desc_str = "(not supported)";
594           printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
595               desc_str);
596         }
597     } else {
598         cmdarg_err_cont("Data link types (use option -y to set):");
599         for (lt_entry = lt_list; lt_entry != NULL;
600              lt_entry = g_list_next(lt_entry)) {
601           data_link_info = lt_entry->data;
602           cmdarg_err_cont("  %s", data_link_info->name);
603           if (data_link_info->description != NULL)
604             cmdarg_err_cont(" (%s)", data_link_info->description);
605           else
606             cmdarg_err_cont(" (not supported)");
607           putchar('\n');
608         }
609     }
610     free_pcap_linktype_list(lt_list);
611
612     return 0;
613 }
614
615 /* Return an ASCII-formatted list of interfaces. */
616 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
617 int
618 capture_opts_list_interfaces(gboolean machine_readable)
619 {
620     GList       *if_list;
621     GList       *if_entry;
622     if_info_t   *if_info;
623     int         err;
624     gchar       *err_str;
625     int         i;
626     GSList      *ip_addr;
627     if_addr_t   *if_addr;
628     char        addr_str[ADDRSTRLEN];
629
630     if_list = get_interface_list(&err, &err_str);
631     if (if_list == NULL) {
632         switch (err) {
633         case CANT_GET_INTERFACE_LIST:
634             cmdarg_err("%s", err_str);
635             g_free(err_str);
636         break;
637
638         case NO_INTERFACES_FOUND:
639             cmdarg_err("There are no interfaces on which a capture can be done");
640         break;
641         }
642         return err;
643     }
644
645     i = 1;  /* Interface id number */
646     for (if_entry = g_list_first(if_list); if_entry != NULL;
647     if_entry = g_list_next(if_entry)) {
648         if_info = if_entry->data;
649         printf("%d. %s", i++, if_info->name);
650
651         if (!machine_readable) {
652             /* Add the description if it exists */
653             if (if_info->description != NULL)
654                 printf(" (%s)", if_info->description);
655         } else {
656             /*
657              * Add the contents of the if_entry struct in a parseable format.
658              * Each if_entry element is tab-separated.  Addresses are comma-
659              * separated.
660              */
661             /* XXX - Make sure our description doesn't contain a tab */
662             if (if_info->description != NULL)
663                 printf("\t%s\t", if_info->description);
664             else
665                 printf("\t\t");
666
667             for(ip_addr = g_slist_nth(if_info->ip_addr, 0); ip_addr != NULL;
668                         ip_addr = g_slist_next(ip_addr)) {
669                 if (ip_addr != g_slist_nth(if_info->ip_addr, 0))
670                     printf(",");
671
672                 if_addr = ip_addr->data;
673                 switch(if_addr->type) {
674                 case AT_IPv4:
675                     if (inet_ntop(AF_INET, &if_addr->ip_addr.ip4_addr, addr_str,
676                                 ADDRSTRLEN)) {
677                         printf(addr_str);
678                     } else {
679                         printf("<unknown IPv4>");
680                     }
681                     break;
682                 case AT_IPv6:
683                     if (inet_ntop(AF_INET6, &if_addr->ip_addr.ip6_addr,
684                                 addr_str, ADDRSTRLEN)) {
685                         printf(addr_str);
686                     } else {
687                         printf("<unknown IPv6>");
688                     }
689                     break;
690                 default:
691                     printf("<type unknown %u>", if_addr->type);
692                 }
693             }
694
695             if (if_info->loopback)
696                 printf("\tloopback");
697             else
698                 printf("\tnetwork");
699
700         }
701         printf("\n");
702     }
703     free_interface_list(if_list);
704
705     return 0;
706 }
707
708 /* Print the number of packets captured for each interface until we're killed. */
709 int
710 capture_opts_print_statistics(gboolean machine_readable)
711 {
712     GList       *if_list, *if_entry, *stat_list = NULL, *stat_entry;
713     if_info_t   *if_info;
714     if_stat_t   *if_stat;
715     int         err;
716     gchar       *err_str;
717     pcap_t      *pch;
718     char        errbuf[PCAP_ERRBUF_SIZE];
719     struct pcap_stat ps;
720
721     if_list = get_interface_list(&err, &err_str);
722     if (if_list == NULL) {
723         switch (err) {
724         case CANT_GET_INTERFACE_LIST:
725             cmdarg_err("%s", err_str);
726             g_free(err_str);
727         break;
728
729         case NO_INTERFACES_FOUND:
730             cmdarg_err("There are no interfaces on which a capture can be done");
731         break;
732         }
733         return err;
734     }
735
736     for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
737         if_info = if_entry->data;
738 #ifdef HAVE_PCAP_OPEN
739         pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
740 #else
741         pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
742 #endif
743
744         if (pch) {
745             if_stat = g_malloc(sizeof(if_stat_t));
746             if_stat->name = g_strdup(if_info->name);
747             if_stat->pch = pch;
748             stat_list = g_list_append(stat_list, if_stat);
749         }
750     }
751
752     if (!stat_list) {
753         cmdarg_err("There are no interfaces on which a capture can be done");
754         return 2;
755     }
756
757     if (!machine_readable) {
758         printf("%-15s  %10s  %10s\n", "Interface", "Received",
759             "Dropped");
760     }
761
762     while (1) {    /* XXX - Add signal handling? */
763         for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
764             if_stat = stat_entry->data;
765             pcap_stats(if_stat->pch, &ps);
766
767             if (!machine_readable) {
768                 printf("%-15s  %10d  %10d\n", if_stat->name,
769                     ps.ps_recv, ps.ps_drop);
770             } else {
771                 printf("%s\t%d\t%d\n", if_stat->name,
772                     ps.ps_recv, ps.ps_drop);
773                 fflush(stdout);
774             }
775         }
776 #ifdef _WIN32
777         Sleep(1 * 1000);
778 #else
779         sleep(1);
780 #endif
781     }
782
783     /* XXX - Not reached.  Should we look for 'q' in stdin? */
784     for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
785         if_stat = stat_entry->data;
786         pcap_close(if_stat->pch);
787         g_free(if_stat->name);
788         g_free(if_stat);
789     }
790     g_list_free(stat_list);
791     free_interface_list(if_list);
792
793     return 0;
794 }
795
796
797 void capture_opts_trim_snaplen(capture_options *capture_opts, int snaplen_min)
798 {
799   if (capture_opts->snaplen < 1)
800     capture_opts->snaplen = WTAP_MAX_PACKET_SIZE;
801   else if (capture_opts->snaplen < snaplen_min)
802     capture_opts->snaplen = snaplen_min;
803 }
804
805
806 void capture_opts_trim_ring_num_files(capture_options *capture_opts)
807 {
808   /* Check the value range of the ring_num_files parameter */
809   if (capture_opts->ring_num_files > RINGBUFFER_MAX_NUM_FILES)
810     capture_opts->ring_num_files = RINGBUFFER_MAX_NUM_FILES;
811 #if RINGBUFFER_MIN_NUM_FILES > 0
812   else if (capture_opts->ring_num_files < RINGBUFFER_MIN_NUM_FILES)
813     capture_opts->ring_num_files = RINGBUFFER_MIN_NUM_FILES;
814 #endif
815 }
816
817
818 gboolean capture_opts_trim_iface(capture_options *capture_opts, const char *capture_device)
819 {
820     GList       *if_list;
821     if_info_t   *if_info;
822     int         err;
823     gchar       *err_str;
824
825
826     /* Did the user specify an interface to use? */
827     if (capture_opts->iface == NULL) {
828       /* No - is a default specified in the preferences file? */
829       if (capture_device != NULL) {
830           /* Yes - use it. */
831           capture_opts->iface = g_strdup(capture_device);
832           /*  We don't set iface_descr here because doing so requires
833            *  capture_ui_utils.c which requires epan/prefs.c which is
834            *  probably a bit too much dependency for here...
835            */
836       } else {
837         /* No - pick the first one from the list of interfaces. */
838         if_list = get_interface_list(&err, &err_str);
839         if (if_list == NULL) {
840           switch (err) {
841
842           case CANT_GET_INTERFACE_LIST:
843               cmdarg_err("%s", err_str);
844               g_free(err_str);
845               break;
846
847           case NO_INTERFACES_FOUND:
848               cmdarg_err("There are no interfaces on which a capture can be done");
849               break;
850           }
851           return FALSE;
852         }
853         if_info = if_list->data;        /* first interface */
854         capture_opts->iface = g_strdup(if_info->name);
855         /*  We don't set iface_descr here because doing so requires
856          *  capture_ui_utils.c which requires epan/prefs.c which is
857          *  probably a bit too much dependency for here...
858          */
859         free_interface_list(if_list);
860       }
861     }
862
863     return TRUE;
864 }
865
866
867
868 #ifndef S_IFIFO
869 #define S_IFIFO _S_IFIFO
870 #endif
871 #ifndef S_ISFIFO
872 #define S_ISFIFO(mode)  (((mode) & S_IFMT) == S_IFIFO)
873 #endif
874
875 /* copied from filesystem.c */
876 static int capture_opts_test_for_fifo(const char *path)
877 {
878         struct stat statb;
879
880         if (eth_stat(path, &statb) < 0)
881                 return errno;
882
883         if (S_ISFIFO(statb.st_mode))
884                 return ESPIPE;
885         else
886                 return 0;
887 }
888
889 static gboolean capture_opts_output_to_pipe(const char *save_file, gboolean *is_pipe)
890 {
891   int err;
892
893   *is_pipe = FALSE;
894
895   if (save_file != NULL) {
896     /* We're writing to a capture file. */
897     if (strcmp(save_file, "-") == 0) {
898       /* Writing to stdout. */
899       /* XXX - should we check whether it's a pipe?  It's arguably
900          silly to do "-w - >output_file" rather than "-w output_file",
901          but by not checking we might be violating the Principle Of
902          Least Astonishment. */
903       *is_pipe = TRUE;
904     } else {
905       /* not writing to stdout, test for a FIFO (aka named pipe) */
906       err = capture_opts_test_for_fifo(save_file);
907       switch (err) {
908
909       case ENOENT:      /* it doesn't exist, so we'll be creating it,
910                            and it won't be a FIFO */
911       case 0:           /* found it, but it's not a FIFO */
912         break;
913
914       case ESPIPE:      /* it is a FIFO */
915         *is_pipe = TRUE;
916         break;
917
918       default:          /* couldn't stat it              */
919         break;          /* ignore: later attempt to open */
920                         /*  will generate a nice msg     */
921       }
922     }
923   }
924
925   return 0;
926 }
927
928 #endif /* HAVE_LIBPCAP */