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