Remove uninitalized variable warning
[obnox/wireshark/wip.git] / capture_opts.c
1 /* capture_opts.c
2  * Routines for capture options setting
3  *
4  * $Id$
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
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 #include <pcap.h>
35
36 #include <glib.h>
37
38 #include <epan/packet.h>
39
40 #include "capture.h"
41 #include "capture_opts.h"
42 #include "ringbuffer.h"
43 #include "clopts_common.h"
44 #include "cmdarg_err.h"
45
46 #include "capture-pcap-util.h"
47 #include "capture_ui_utils.h"
48 #include <wiretap/file_util.h>
49
50
51 static gboolean capture_opts_output_to_pipe(const char *save_file);
52
53
54 void
55 capture_opts_init(capture_options *capture_opts, void *cfile)
56 {
57   capture_opts->cf                      = cfile;            
58   capture_opts->cfilter                     = g_strdup("");     /* No capture filter string specified */
59   capture_opts->iface                   = NULL;             /* Default is "pick the first interface" */
60 #ifdef _WIN32
61   capture_opts->buffer_size             = 1;                /* 1 MB */
62 #endif
63   capture_opts->has_snaplen             = FALSE;
64   capture_opts->snaplen                 = WTAP_MAX_PACKET_SIZE; /* snapshot length - default is
65                                                                     infinite, in effect */
66   capture_opts->promisc_mode            = TRUE;             /* promiscuous mode is the default */
67   capture_opts->linktype                = -1;               /* the default linktype */
68   capture_opts->save_file               = NULL;
69   capture_opts->real_time_mode          = TRUE;
70   capture_opts->show_info               = TRUE;
71   capture_opts->quit_after_cap          = FALSE;
72   capture_opts->restart                 = FALSE;
73
74   capture_opts->multi_files_on          = FALSE;
75   capture_opts->has_file_duration       = FALSE;
76   capture_opts->file_duration           = 60;               /* 1 min */
77   capture_opts->has_ring_num_files      = FALSE;
78   capture_opts->ring_num_files          = RINGBUFFER_MIN_NUM_FILES;
79
80   capture_opts->has_autostop_files      = FALSE;
81   capture_opts->autostop_files          = 1;
82   capture_opts->has_autostop_packets    = FALSE;            
83   capture_opts->autostop_packets        = 0;
84   capture_opts->has_autostop_filesize   = FALSE;
85   capture_opts->autostop_filesize       = 1024;             /* 1 MB */
86   capture_opts->has_autostop_duration   = FALSE;
87   capture_opts->autostop_duration       = 60;               /* 1 min */
88
89
90   capture_opts->fork_child              = -1;               /* invalid process handle */
91 #ifdef _WIN32
92   capture_opts->signal_pipe_fd          = -1;
93 #endif
94   capture_opts->state                   = CAPTURE_STOPPED;
95   capture_opts->output_to_pipe          = FALSE;
96 }
97
98
99 /* log content of capture_opts */
100 void
101 capture_opts_log(const char *log_domain, GLogLevelFlags log_level, capture_options *capture_opts) {
102     g_log(log_domain, log_level, "CAPTURE OPTIONS    :");
103     g_log(log_domain, log_level, "CFile              : 0x%p", capture_opts->cf);
104     g_log(log_domain, log_level, "Filter             : %s", capture_opts->cfilter);
105     g_log(log_domain, log_level, "Interface          : %s", capture_opts->iface);
106 #ifdef _WIN32
107     g_log(log_domain, log_level, "BufferSize         : %u (MB)", capture_opts->buffer_size);
108 #endif
109     g_log(log_domain, log_level, "SnapLen         (%u): %u", capture_opts->has_snaplen, capture_opts->snaplen);
110     g_log(log_domain, log_level, "Promisc            : %u", capture_opts->promisc_mode);
111     g_log(log_domain, log_level, "LinkType           : %d", capture_opts->linktype);
112     g_log(log_domain, log_level, "SaveFile           : %s", (capture_opts->save_file) ? capture_opts->save_file : "");
113     g_log(log_domain, log_level, "RealTimeMode       : %u", capture_opts->real_time_mode);
114     g_log(log_domain, log_level, "ShowInfo           : %u", capture_opts->show_info);
115     g_log(log_domain, log_level, "QuitAfterCap       : %u", capture_opts->quit_after_cap);
116
117     g_log(log_domain, log_level, "MultiFilesOn       : %u", capture_opts->multi_files_on);
118     g_log(log_domain, log_level, "FileDuration    (%u): %u", capture_opts->has_file_duration, capture_opts->file_duration);
119     g_log(log_domain, log_level, "RingNumFiles    (%u): %u", capture_opts->has_ring_num_files, capture_opts->ring_num_files);
120
121     g_log(log_domain, log_level, "AutostopFiles   (%u): %u", capture_opts->has_autostop_files, capture_opts->autostop_files);
122     g_log(log_domain, log_level, "AutostopPackets (%u): %u", capture_opts->has_autostop_packets, capture_opts->autostop_packets);
123     g_log(log_domain, log_level, "AutostopFilesize(%u): %u (KB)", capture_opts->has_autostop_filesize, capture_opts->autostop_filesize);
124     g_log(log_domain, log_level, "AutostopDuration(%u): %u", capture_opts->has_autostop_duration, capture_opts->autostop_duration);
125
126     g_log(log_domain, log_level, "ForkChild          : %d", capture_opts->fork_child);
127 #ifdef _WIN32
128     g_log(log_domain, log_level, "SignalPipeFd       : %d", capture_opts->signal_pipe_fd);
129 #endif
130 }
131
132 /*
133  * Given a string of the form "<autostop criterion>:<value>", as might appear
134  * as an argument to a "-a" option, parse it and set the criterion in
135  * question.  Return an indication of whether it succeeded or failed
136  * in some fashion.
137  */
138 static gboolean
139 set_autostop_criterion(capture_options *capture_opts, const char *autostoparg)
140 {
141   gchar *p, *colonp;
142
143   colonp = strchr(autostoparg, ':');
144   if (colonp == NULL)
145     return FALSE;
146
147   p = colonp;
148   *p++ = '\0';
149
150   /*
151    * Skip over any white space (there probably won't be any, but
152    * as we allow it in the preferences file, we might as well
153    * allow it here).
154    */
155   while (isspace((guchar)*p))
156     p++;
157   if (*p == '\0') {
158     /*
159      * Put the colon back, so if our caller uses, in an
160      * error message, the string they passed us, the message
161      * looks correct.
162      */
163     *colonp = ':';
164     return FALSE;
165   }
166   if (strcmp(autostoparg,"duration") == 0) {
167     capture_opts->has_autostop_duration = TRUE;
168     capture_opts->autostop_duration = get_positive_int(p,"autostop duration");
169   } else if (strcmp(autostoparg,"filesize") == 0) {
170     capture_opts->has_autostop_filesize = TRUE;
171     capture_opts->autostop_filesize = get_positive_int(p,"autostop filesize");
172   } else if (strcmp(autostoparg,"files") == 0) {
173     capture_opts->multi_files_on = TRUE;
174     capture_opts->has_autostop_files = TRUE;
175     capture_opts->autostop_files = get_positive_int(p,"autostop files");
176   } else {
177     return FALSE;
178   }
179   *colonp = ':'; /* put the colon back */
180   return TRUE;
181 }
182
183 /*
184  * Given a string of the form "<ring buffer file>:<duration>", as might appear
185  * as an argument to a "-b" option, parse it and set the arguments in
186  * question.  Return an indication of whether it succeeded or failed
187  * in some fashion.
188  */
189 static gboolean
190 get_ring_arguments(capture_options *capture_opts, const char *arg)
191 {
192   gchar *p = NULL, *colonp;
193
194   colonp = strchr(arg, ':');
195   if (colonp == NULL)
196     return TRUE;
197
198   p = colonp;
199   *p++ = '\0';
200
201   /*
202    * Skip over any white space (there probably won't be any, but
203    * as we allow it in the preferences file, we might as well
204    * allow it here).
205    */
206   while (isspace((guchar)*p))
207     p++;
208   if (*p == '\0') {
209     /*
210      * Put the colon back, so if our caller uses, in an
211      * error message, the string they passed us, the message
212      * looks correct.
213      */
214     *colonp = ':';
215     return FALSE;
216   }
217
218   if (strcmp(arg,"files") == 0) {
219     capture_opts->has_ring_num_files = TRUE;
220     capture_opts->ring_num_files = get_natural_int(p, "number of ring buffer files");
221   } else if (strcmp(arg,"filesize") == 0) {
222     capture_opts->has_autostop_filesize = TRUE;
223     capture_opts->autostop_filesize = get_positive_int(p, "ring buffer filesize");
224   } else if (strcmp(arg,"duration") == 0) {
225     capture_opts->has_file_duration = TRUE;
226     capture_opts->file_duration = get_positive_int(p, "ring buffer duration");
227   }
228
229   *colonp = ':';        /* put the colon back */
230   return TRUE;
231 }
232
233
234 #ifdef _WIN32
235 /*
236  * Given a string of the form "<pipe name>:<file descriptor>", as might appear
237  * as an argument to a "-Z" option, parse it and set the arguments in
238  * question.  Return an indication of whether it succeeded or failed
239  * in some fashion.
240  */
241 static gboolean
242 get_pipe_arguments(capture_options *capture_opts, const char *arg)
243 {
244   gchar *p = NULL, *colonp;
245   int pipe_fd;
246
247
248   colonp = strchr(arg, ':');
249   if (colonp == NULL)
250     return TRUE;
251
252   p = colonp;
253   *p++ = '\0';
254
255   /*
256    * Skip over any white space (there probably won't be any, but
257    * as we allow it in the preferences file, we might as well
258    * allow it here).
259    */
260   while (isspace((guchar)*p))
261     p++;
262   if (*p == '\0') {
263     /*
264      * Put the colon back, so if our caller uses, in an
265      * error message, the string they passed us, the message
266      * looks correct.
267      */
268     *colonp = ':';
269     return FALSE;
270   }
271
272   if (strcmp(arg,"sync") == 0) {
273     /* associate stdout with sync pipe */
274     pipe_fd = get_natural_int(p, "sync pipe file descriptor");
275     if (dup2(pipe_fd, 1) < 0) {
276       cmdarg_err("Unable to dup sync pipe handle");
277       return FALSE;
278     }
279   } else if (strcmp(arg,"signal") == 0) {
280     /* associate stdin with signal pipe */
281     pipe_fd = get_natural_int(p, "signal pipe file descriptor");
282     if (dup2(pipe_fd, 0) < 0) {
283       cmdarg_err("Unable to dup signal pipe handle");
284       return FALSE;
285     }
286     capture_opts->signal_pipe_fd = pipe_fd;
287   }
288
289   *colonp = ':';        /* put the colon back */
290   return TRUE;
291 }
292 #endif
293
294
295 void
296 capture_opts_add_iface_opt(capture_options *capture_opts, const char *optarg)
297 {
298     long        adapter_index;
299     char        *p;
300     GList       *if_list;
301     if_info_t   *if_info;
302     int         err;
303     gchar       err_str[PCAP_ERRBUF_SIZE];
304     gchar       *cant_get_if_list_errstr;
305
306
307     /*
308      * If the argument is a number, treat it as an index into the list
309      * of adapters, as printed by "tethereal -D".
310      *
311      * This should be OK on UNIX systems, as interfaces shouldn't have
312      * names that begin with digits.  It can be useful on Windows, where
313      * more than one interface can have the same name.
314      */
315     adapter_index = strtol(optarg, &p, 10);
316     if (p != NULL && *p == '\0') {
317       if (adapter_index < 0) {
318         cmdarg_err("The specified adapter index is a negative number");
319        exit(1);
320       }
321       if (adapter_index > INT_MAX) {
322         cmdarg_err("The specified adapter index is too large (greater than %d)",
323             INT_MAX);
324         exit(1);
325       }
326       if (adapter_index == 0) {
327         cmdarg_err("there is no interface with that adapter index");
328         exit(1);
329       }
330       if_list = get_interface_list(&err, err_str);
331       if (if_list == NULL) {
332         switch (err) {
333
334         case CANT_GET_INTERFACE_LIST:
335             cant_get_if_list_errstr =
336                 cant_get_if_list_error_message(err_str);
337             cmdarg_err("%s", cant_get_if_list_errstr);
338             g_free(cant_get_if_list_errstr);
339             break;
340
341         case NO_INTERFACES_FOUND:
342             cmdarg_err("There are no interfaces on which a capture can be done");
343             break;
344         }
345         exit(2);
346       }
347       if_info = g_list_nth_data(if_list, adapter_index - 1);
348       if (if_info == NULL) {
349         cmdarg_err("there is no interface with that adapter index");
350         exit(1);
351       }
352       capture_opts->iface = g_strdup(if_info->name);
353       free_interface_list(if_list);
354     } else {
355       capture_opts->iface = g_strdup(optarg);
356     }
357 }
358
359 void
360 capture_opts_add_opt(capture_options *capture_opts, int opt, const char *optarg, gboolean *start_capture)
361 {
362     switch(opt) {
363     case 'a':        /* autostop criteria */
364         if (set_autostop_criterion(capture_opts, optarg) == FALSE) {
365           cmdarg_err("Invalid or unknown -a flag \"%s\"", optarg);
366           exit(1);
367         }
368         break;
369     case 'b':        /* Ringbuffer option */
370         capture_opts->multi_files_on = TRUE;
371         if (get_ring_arguments(capture_opts, optarg) == FALSE) {
372           cmdarg_err("Invalid or unknown -b arg \"%s\"", optarg);
373           exit(1);
374         }
375         break;
376 #ifdef _WIN32
377     case 'B':        /* Buffer size */
378         capture_opts->buffer_size = get_positive_int(optarg, "buffer size");
379         break;
380 #endif
381     case 'c':        /* Capture xxx packets */
382         capture_opts->has_autostop_packets = TRUE;
383         capture_opts->autostop_packets = get_positive_int(optarg, "packet count");
384         break;
385     case 'f':        /* capture filter */
386         if (capture_opts->cfilter)
387             g_free(capture_opts->cfilter);
388         capture_opts->cfilter = g_strdup(optarg);
389         break;
390     case 'H':        /* Hide capture info dialog box */
391         capture_opts->show_info = FALSE;
392         break;
393     case 'i':        /* Use interface xxx */
394         capture_opts_add_iface_opt(capture_opts, optarg);
395         break;
396     case 'k':        /* Start capture immediately */
397         *start_capture = TRUE;
398         break;
399     /*case 'l':*/    /* Automatic scrolling in live capture mode */
400     case 'p':        /* Don't capture in promiscuous mode */
401         capture_opts->promisc_mode = FALSE;
402         break;
403     case 'Q':        /* Quit after capture (just capture to file) */
404         capture_opts->quit_after_cap  = TRUE;
405         *start_capture   = TRUE;  /*** -Q implies -k !! ***/
406         break;
407     case 's':        /* Set the snapshot (capture) length */
408         capture_opts->has_snaplen = TRUE;
409         capture_opts->snaplen = get_positive_int(optarg, "snapshot length");
410         break;
411     case 'S':        /* "Real-Time" mode: used for following file ala tail -f */
412         capture_opts->real_time_mode = TRUE;
413         break;
414     case 'w':        /* Write to capture file xxx */
415 #if defined _WIN32 && (GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 6))
416         /* since GLib 2.6, we need to convert filenames to utf8 for Win32 */
417         capture_opts->save_file = g_locale_to_utf8(optarg, -1, NULL, NULL, NULL);
418 #else
419         capture_opts->save_file = g_strdup(optarg);
420 #endif
421         capture_opts->output_to_pipe = capture_opts_output_to_pipe(capture_opts->save_file);
422             break;
423     case 'y':        /* Set the pcap data link type */
424 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
425         capture_opts->linktype = pcap_datalink_name_to_val(optarg);
426         if (capture_opts->linktype == -1) {
427           cmdarg_err("The specified data link type \"%s\" isn't valid",
428                   optarg);
429           exit(1);
430         }
431 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
432         /* XXX - just treat it as a number */
433         capture_opts->linktype = get_natural_int(optarg, "data link type");
434 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
435         break;
436 #ifdef _WIN32
437       /* Hidden option supporting Sync mode */
438     case 'Z':        /* Write to pipe FD XXX */
439        if (get_pipe_arguments(capture_opts, optarg) == FALSE) {
440           cmdarg_err("Invalid or unknown -Z flag \"%s\"", optarg);
441           exit(1);
442         }
443         break;
444 #endif /* _WIN32 */
445     default:
446         /* the caller is responsible to send us only the right opt's */
447         g_assert_not_reached();
448     }
449 }
450
451
452 void capture_opts_list_link_layer_types(capture_options *capture_opts)
453 {
454     gchar err_str[PCAP_ERRBUF_SIZE];
455     GList *lt_list, *lt_entry;
456     data_link_info_t *data_link_info;
457
458     /* Get the list of link-layer types for the capture device. */
459     lt_list = get_pcap_linktype_list(capture_opts->iface, err_str);
460     if (lt_list == NULL) {
461       if (err_str[0] != '\0') {
462         cmdarg_err("The list of data link types for the capture device could not be obtained (%s)."
463           "Please check to make sure you have sufficient permissions, and that\n"
464           "you have the proper interface or pipe specified.\n", err_str);
465       } else
466         cmdarg_err("The capture device has no data link types.");
467       exit(2);
468     }
469     cmdarg_err_cont("Data link types (use option -y to set):");
470     for (lt_entry = lt_list; lt_entry != NULL;
471          lt_entry = g_list_next(lt_entry)) {
472       data_link_info = lt_entry->data;
473       cmdarg_err_cont("  %s", data_link_info->name);
474       if (data_link_info->description != NULL)
475         cmdarg_err_cont(" (%s)", data_link_info->description);
476       else
477         cmdarg_err_cont(" (not supported)");
478       putchar('\n');
479     }
480     free_pcap_linktype_list(lt_list);
481 }
482
483
484 void capture_opts_list_interfaces()
485 {
486     GList       *if_list;
487     GList       *if_entry;
488     if_info_t   *if_info;
489     int         err;
490     gchar       err_str[PCAP_ERRBUF_SIZE];
491     gchar       *cant_get_if_list_errstr;
492     int         i;
493
494
495     if_list = get_interface_list(&err, err_str);
496     if (if_list == NULL) {
497         switch (err) {
498         case CANT_GET_INTERFACE_LIST:
499             cant_get_if_list_errstr = cant_get_if_list_error_message(err_str);
500             cmdarg_err("%s", cant_get_if_list_errstr);
501             g_free(cant_get_if_list_errstr);
502         break;
503
504         case NO_INTERFACES_FOUND:
505             cmdarg_err("There are no interfaces on which a capture can be done");
506         break;
507         }
508         exit(2);
509     }
510
511     i = 1;  /* Interface id number */
512     for (if_entry = g_list_first(if_list); if_entry != NULL;
513     if_entry = g_list_next(if_entry)) {
514         if_info = if_entry->data;
515         printf("%d. %s", i++, if_info->name);
516         if (if_info->description != NULL)
517             printf(" (%s)", if_info->description);
518         printf("\n");
519     }
520     free_interface_list(if_list);
521 }
522
523
524 void capture_opts_trim_snaplen(capture_options *capture_opts, int snaplen_min)
525 {
526   if (capture_opts->snaplen < 1)
527     capture_opts->snaplen = WTAP_MAX_PACKET_SIZE;
528   else if (capture_opts->snaplen < snaplen_min)
529     capture_opts->snaplen = snaplen_min;
530 }
531
532
533 void capture_opts_trim_ring_num_files(capture_options *capture_opts)
534 {
535   /* Check the value range of the ring_num_files parameter */
536   if (capture_opts->ring_num_files > RINGBUFFER_MAX_NUM_FILES)
537     capture_opts->ring_num_files = RINGBUFFER_MAX_NUM_FILES;
538 #if RINGBUFFER_MIN_NUM_FILES > 0
539   else if (capture_opts->ring_num_files < RINGBUFFER_MIN_NUM_FILES)
540     capture_opts->ring_num_files = RINGBUFFER_MIN_NUM_FILES;
541 #endif
542 }
543
544
545 gboolean capture_opts_trim_iface(capture_options *capture_opts, const char *capture_device)
546 {
547     GList       *if_list;
548     if_info_t   *if_info;
549     int         err;
550     gchar       err_str[PCAP_ERRBUF_SIZE];
551     gchar       *cant_get_if_list_errstr;
552
553
554     /* Did the user specify an interface to use? */
555     if (capture_opts->iface == NULL) {
556       /* No - is a default specified in the preferences file? */
557       if (capture_device != NULL) {
558           /* Yes - use it. */
559           capture_opts->iface = g_strdup(capture_device);
560       } else {
561         /* No - pick the first one from the list of interfaces. */
562         if_list = get_interface_list(&err, err_str);
563         if (if_list == NULL) {
564           switch (err) {
565
566           case CANT_GET_INTERFACE_LIST:
567               cant_get_if_list_errstr = cant_get_if_list_error_message(err_str);
568               cmdarg_err("%s", cant_get_if_list_errstr);
569               g_free(cant_get_if_list_errstr);
570               break;
571
572           case NO_INTERFACES_FOUND:
573               cmdarg_err("There are no interfaces on which a capture can be done");
574               break;
575           }
576           return FALSE;
577         }
578         if_info = if_list->data;        /* first interface */
579         capture_opts->iface = g_strdup(if_info->name);
580         free_interface_list(if_list);
581       }
582     }
583
584     return TRUE;
585 }
586
587
588
589 #ifndef S_IFIFO
590 #define S_IFIFO _S_IFIFO
591 #endif
592 #ifndef S_ISFIFO
593 #define S_ISFIFO(mode)  (((mode) & S_IFMT) == S_IFIFO)
594 #endif
595
596 /* copied from filesystem.c */
597 static int capture_opts_test_for_fifo(const char *path)
598 {
599         struct stat statb;
600
601         if (eth_stat(path, &statb) < 0)
602                 return errno;
603
604         if (S_ISFIFO(statb.st_mode))
605                 return ESPIPE;
606         else
607                 return 0;
608 }
609
610 static gboolean capture_opts_output_to_pipe(const char *save_file)
611 {
612   int err;
613
614   if (save_file != NULL) {
615     /* We're writing to a capture file. */
616     if (strcmp(save_file, "-") == 0) {
617       /* Writing to stdout. */
618       /* XXX - should we check whether it's a pipe?  It's arguably
619          silly to do "-w - >output_file" rather than "-w output_file",
620          but by not checking we might be violating the Principle Of
621          Least Astonishment. */
622       return TRUE;
623     } else {
624       /* not a capture file, test for a FIFO (aka named pipe) */
625       err = capture_opts_test_for_fifo(save_file);
626       switch (err) {
627
628       case ENOENT:      /* it doesn't exist, so we'll be creating it,
629                            and it won't be a FIFO */
630       case 0:           /* found it, but it's not a FIFO */
631         break;
632
633       case ESPIPE:      /* it is a FIFO */
634         return TRUE;
635         break;
636
637       default:          /* couldn't stat it */
638         cmdarg_err("Error testing whether capture file is a pipe: %s",
639                 strerror(errno));
640         exit(2);
641       }
642     }
643   }
644
645   return FALSE;
646 }
647
648 #endif /* HAVE_LIBPCAP */