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