fix a bug if capturing into named files is used
[obnox/wireshark/wip.git] / capture.c
1 /* capture.c
2  * Routines for packet capture windows
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 /* With MSVC and a libethereal.dll this file needs to import some variables 
26    in a special way. Therefore _NEED_VAR_IMPORT_ is defined. */
27 #define _NEED_VAR_IMPORT_
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #ifdef HAVE_LIBPCAP
34
35 #include <stdlib.h>
36 #include <string.h>
37 #include <ctype.h>
38
39 #ifdef HAVE_FCNTL_H
40 #include <fcntl.h>
41 #endif
42
43 #ifdef HAVE_IO_H
44 # include <io.h>
45 #endif
46
47 #include <signal.h>
48 #include <errno.h>
49
50 #include <pcap.h>
51
52 #include <glib.h>
53
54 #include <epan/packet.h>
55 #include <epan/dfilter/dfilter.h>
56 #include "file.h"
57 #include "capture.h"
58 #include "capture_sync.h"
59 #include "capture_ui_utils.h"
60 #include "util.h"
61 #include "pcap-util.h"
62 #include "alert_box.h"
63 #include "simple_dialog.h"
64 #include <epan/prefs.h>
65 #include "conditions.h"
66 #include "ringbuffer.h"
67
68 #ifdef _WIN32
69 #include "capture-wpcap.h"
70 #endif
71 #include "ui_util.h"
72
73
74 /* Win32 needs the O_BINARY flag for open() */
75 #ifndef O_BINARY
76 #define O_BINARY        0
77 #endif
78
79 static gboolean normal_do_capture(capture_options *capture_opts, gboolean is_tempfile);
80 static void stop_capture_signal_handler(int signo);
81
82
83 void
84 capture_opts_init(capture_options *capture_opts, void *cfile)
85 {
86   capture_opts->cf                      = cfile;
87   capture_opts->cfilter                     = g_strdup("");
88   capture_opts->iface                   = NULL;
89 #ifdef _WIN32
90   capture_opts->buffer_size             = 1;                /* 1 MB */
91 #endif
92   capture_opts->has_snaplen             = FALSE;
93   capture_opts->snaplen                 = MIN_PACKET_SIZE;
94   capture_opts->promisc_mode            = TRUE;
95   capture_opts->linktype                = -1;               /* the default linktype */
96   capture_opts->capture_child           = FALSE;
97   capture_opts->save_file               = NULL;
98   capture_opts->save_file_fd            = -1;
99   capture_opts->sync_mode               = TRUE;
100   capture_opts->show_info               = TRUE;
101   capture_opts->quit_after_cap          = FALSE;
102
103   capture_opts->multi_files_on          = FALSE;
104   capture_opts->has_file_duration       = FALSE;
105   capture_opts->file_duration           = 60;               /* 1 min */
106   capture_opts->has_ring_num_files      = TRUE;
107   capture_opts->ring_num_files          = 2;
108
109   capture_opts->has_autostop_files      = FALSE;
110   capture_opts->autostop_files          = 1;
111   capture_opts->has_autostop_packets    = FALSE;
112   capture_opts->autostop_packets        = 1;
113   capture_opts->has_autostop_filesize   = FALSE;
114   capture_opts->autostop_filesize       = 1024 * 1024;      /* 1 MB */
115   capture_opts->has_autostop_duration   = FALSE;
116   capture_opts->autostop_duration       = 60;               /* 1 min */
117
118 }
119
120 static int
121 get_natural_int(const char *string, const char *name)
122 {
123   long number;
124   char *p;
125
126   number = strtol(string, &p, 10);
127   if (p == string || *p != '\0') {
128     fprintf(stderr, "ethereal: The specified %s \"%s\" isn't a decimal number\n",
129             name, string);
130     exit(1);
131   }
132   if (number < 0) {
133     fprintf(stderr, "ethereal: The specified %s \"%s\" is a negative number\n",
134             name, string);
135     exit(1);
136   }
137   if (number > INT_MAX) {
138     fprintf(stderr, "ethereal: The specified %s \"%s\" is too large (greater than %d)\n",
139             name, string, INT_MAX);
140     exit(1);
141   }
142   return number;
143 }
144
145
146 static int
147 get_positive_int(const char *string, const char *name)
148 {
149   long number;
150
151   number = get_natural_int(string, name);
152
153   if (number == 0) {
154     fprintf(stderr, "ethereal: The specified %s is zero\n",
155             name);
156     exit(1);
157   }
158
159   return number;
160 }
161
162
163 /*
164  * Given a string of the form "<autostop criterion>:<value>", as might appear
165  * as an argument to a "-a" option, parse it and set the criterion in
166  * question.  Return an indication of whether it succeeded or failed
167  * in some fashion.
168  */
169 static gboolean
170 set_autostop_criterion(capture_options *capture_opts, const char *autostoparg)
171 {
172   gchar *p, *colonp;
173
174   colonp = strchr(autostoparg, ':');
175   if (colonp == NULL)
176     return FALSE;
177
178   p = colonp;
179   *p++ = '\0';
180
181   /*
182    * Skip over any white space (there probably won't be any, but
183    * as we allow it in the preferences file, we might as well
184    * allow it here).
185    */
186   while (isspace((guchar)*p))
187     p++;
188   if (*p == '\0') {
189     /*
190      * Put the colon back, so if our caller uses, in an
191      * error message, the string they passed us, the message
192      * looks correct.
193      */
194     *colonp = ':';
195     return FALSE;
196   }
197   if (strcmp(autostoparg,"duration") == 0) {
198     capture_opts->has_autostop_duration = TRUE;
199     capture_opts->autostop_duration = get_positive_int(p,"autostop duration");
200   } else if (strcmp(autostoparg,"filesize") == 0) {
201     capture_opts->has_autostop_filesize = TRUE;
202     capture_opts->autostop_filesize = get_positive_int(p,"autostop filesize");
203   } else {
204     return FALSE;
205   }
206   *colonp = ':'; /* put the colon back */
207   return TRUE;
208 }
209
210 /*
211  * Given a string of the form "<ring buffer file>:<duration>", as might appear
212  * as an argument to a "-b" option, parse it and set the arguments in
213  * question.  Return an indication of whether it succeeded or failed
214  * in some fashion.
215  */
216 static gboolean
217 get_ring_arguments(capture_options *capture_opts, const char *arg)
218 {
219   gchar *p = NULL, *colonp;
220
221   colonp = strchr(arg, ':');
222
223   if (colonp != NULL) {
224     p = colonp;
225     *p++ = '\0';
226   }
227
228   capture_opts->ring_num_files = 
229     get_natural_int(arg, "number of ring buffer files");
230
231   if (colonp == NULL)
232     return TRUE;
233
234   /*
235    * Skip over any white space (there probably won't be any, but
236    * as we allow it in the preferences file, we might as well
237    * allow it here).
238    */
239   while (isspace((guchar)*p))
240     p++;
241   if (*p == '\0') {
242     /*
243      * Put the colon back, so if our caller uses, in an
244      * error message, the string they passed us, the message
245      * looks correct.
246      */
247     *colonp = ':';
248     return FALSE;
249   }
250
251   capture_opts->has_file_duration = TRUE;
252   capture_opts->file_duration = get_positive_int(p,
253                                                       "ring buffer duration");
254
255   *colonp = ':';        /* put the colon back */
256   return TRUE;
257 }
258
259
260 void
261 capture_opt_add(capture_options *capture_opts, int opt, const char *optarg, gboolean *start_capture)
262 {
263 #ifdef _WIN32
264     int i;
265 #endif
266
267     switch(opt) {
268     case 'a':        /* autostop criteria */
269         if (set_autostop_criterion(capture_opts, optarg) == FALSE) {
270           fprintf(stderr, "ethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
271           exit(1);
272         }
273         break;
274     case 'b':        /* Ringbuffer option */
275         capture_opts->multi_files_on = TRUE;
276         capture_opts->has_ring_num_files = TRUE;
277         if (get_ring_arguments(capture_opts, optarg) == FALSE) {
278           fprintf(stderr, "ethereal: Invalid or unknown -b arg \"%s\"\n", optarg);
279           exit(1);
280         }
281         break;
282     case 'c':        /* Capture xxx packets */
283         capture_opts->has_autostop_packets = TRUE;
284         capture_opts->autostop_packets = get_positive_int(optarg, "packet count");
285         break;
286     case 'f':        /* capture filter */
287         if (capture_opts->cfilter)
288             g_free(capture_opts->cfilter);
289         capture_opts->cfilter = g_strdup(optarg);
290         break;
291     case 'H':        /* Hide capture info dialog box */
292         capture_opts->show_info = FALSE;
293         break;
294     case 'i':        /* Use interface xxx */
295         capture_opts->iface = g_strdup(optarg);
296         break;
297     case 'k':        /* Start capture immediately */
298         *start_capture = TRUE;
299         break;
300     /*case 'l':*/    /* Automatic scrolling in live capture mode */
301     case 'p':        /* Don't capture in promiscuous mode */
302         capture_opts->promisc_mode = FALSE;
303         break;
304     case 'Q':        /* Quit after capture (just capture to file) */
305         capture_opts->quit_after_cap  = TRUE;
306         *start_capture   = TRUE;  /*** -Q implies -k !! ***/
307         break;
308     case 's':        /* Set the snapshot (capture) length */
309         capture_opts->has_snaplen = TRUE;
310         capture_opts->snaplen = get_positive_int(optarg, "snapshot length");
311         break;
312     case 'S':        /* "Sync" mode: used for following file ala tail -f */
313         capture_opts->sync_mode = TRUE;
314         break;
315     case 'w':        /* Write to capture file xxx */
316         capture_opts->save_file = g_strdup(optarg);
317             break;
318     case 'W':        /* Write to capture file FD xxx */
319         capture_opts->save_file_fd = atoi(optarg);
320         break;
321     case 'y':        /* Set the pcap data link type */
322 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
323         capture_opts->linktype = pcap_datalink_name_to_val(optarg);
324         if (capture_opts->linktype == -1) {
325           fprintf(stderr, "ethereal: The specified data link type \"%s\" isn't valid\n",
326                   optarg);
327           exit(1);
328         }
329 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
330         /* XXX - just treat it as a number */
331         capture_opts->linktype = get_natural_int(optarg, "data link type");
332 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
333         break;
334 #ifdef _WIN32
335       /* Hidden option supporting Sync mode */
336     case 'Z':        /* Write to pipe FD XXX */
337         /* associate stdout with pipe */
338         i = atoi(optarg);
339         if (dup2(i, 1) < 0) {
340           fprintf(stderr, "Unable to dup pipe handle\n");
341           exit(1);
342         }
343         break;
344 #endif /* _WIN32 */
345     default:
346         /* the caller is responsible to send us only the right opt's */
347         g_assert_not_reached();
348     }
349 }
350
351 /* open the output file (temporary/specified name/ringbuffer) and close the old one */
352 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
353 static gboolean
354 capture_open_output(capture_options *capture_opts, gboolean *is_tempfile) {
355   char tmpname[128+1];
356   gchar *capfile_name;
357
358
359   if (capture_opts->save_file != NULL) {
360     /* If the Sync option is set, we return to the caller while the capture
361      * is in progress.  Therefore we need to take a copy of save_file in
362      * case the caller destroys it after we return.
363      */
364     capfile_name = g_strdup(capture_opts->save_file);
365     if (capture_opts->multi_files_on) {
366       /* ringbuffer is enabled */
367       capture_opts->save_file_fd = ringbuf_init(capfile_name,
368           (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
369     } else {
370       /* Try to open/create the specified file for use as a capture buffer. */
371       capture_opts->save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
372                                 0600);
373     }
374     *is_tempfile = FALSE;
375   } else {
376     /* Choose a random name for the temporary capture buffer */
377     capture_opts->save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
378     capfile_name = g_strdup(tmpname);
379     *is_tempfile = TRUE;
380   }
381
382   /* did we fail to open the output file? */
383   if (capture_opts->save_file_fd == -1) {
384     if (is_tempfile) {
385       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
386         "The temporary file to which the capture would be saved (\"%s\")"
387         "could not be opened: %s.", capfile_name, strerror(errno));
388     } else {
389       if (capture_opts->multi_files_on) {
390         ringbuf_error_cleanup();
391       }
392       open_failure_alert_box(capfile_name, errno, TRUE);
393     }
394     g_free(capfile_name);
395     return FALSE;
396   }
397
398   /* close the old file */
399   cf_close(capture_opts->cf);
400   if(capture_opts->save_file != NULL) {
401     g_free(capture_opts->save_file);
402   }
403   capture_opts->save_file = capfile_name;
404   /* capture_opts.save_file is "g_free"ed later, which is equivalent to
405      "g_free(capfile_name)". */
406
407   return TRUE;
408 }
409
410
411 /* Open a specified file, or create a temporary file, and start a capture
412    to the file in question.  */
413 /* Returns TRUE if the capture starts successfully, FALSE otherwise. */
414 gboolean
415 do_capture(capture_options *capture_opts)
416 {
417   gboolean is_tempfile;
418   gboolean ret;
419
420   /* open the output file (temporary/specified name/ringbuffer) and close the old one */
421   if(!capture_open_output(capture_opts, &is_tempfile)) {
422     return FALSE;
423   }
424
425   if (capture_opts->sync_mode) {        
426     /* sync mode: do the capture in a child process */
427     ret = sync_pipe_do_capture(capture_opts, is_tempfile);
428     /* capture is still running */
429     cf_callback_invoke(cf_cb_live_capture_started, capture_opts);
430   } else {
431     /* normal mode: do the capture synchronously */
432     cf_callback_invoke(cf_cb_live_capture_started, capture_opts);
433     ret = normal_do_capture(capture_opts, is_tempfile);
434     /* capture is finished here */
435   }
436
437   return ret;
438 }
439
440
441 /* start a normal capture session */
442 static gboolean
443 normal_do_capture(capture_options *capture_opts, gboolean is_tempfile)
444 {
445     int capture_succeeded;
446     gboolean stats_known;
447     struct pcap_stat stats;
448     int err;
449
450     /* Not sync mode. */
451     capture_succeeded = capture_start(capture_opts, &stats_known, &stats);
452     if (capture_opts->quit_after_cap) {
453       /* DON'T unlink the save file.  Presumably someone wants it. */
454         main_window_exit();
455     }
456     if (!capture_succeeded) {
457       /* We didn't succeed in doing the capture, so we don't have a save
458          file. */
459       if (capture_opts->multi_files_on) {
460         ringbuf_free();
461       } else {
462         g_free(capture_opts->save_file);
463       }
464       capture_opts->save_file = NULL;
465       return FALSE;
466     }
467     /* Capture succeeded; attempt to read in the capture file. */
468     if (cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err) != CF_OK) {
469       /* We're not doing a capture any more, so we don't have a save
470          file. */
471       if (capture_opts->multi_files_on) {
472         ringbuf_free();
473       } else {
474         g_free(capture_opts->save_file);
475       }
476       capture_opts->save_file = NULL;
477       return FALSE;
478     }
479
480     /* Set the read filter to NULL. */
481     cf_set_rfcode(capture_opts->cf, NULL);
482
483     /* Get the packet-drop statistics.
484
485        XXX - there are currently no packet-drop statistics stored
486        in libpcap captures, and that's what we're reading.
487
488        At some point, we will add support in Wiretap to return
489        packet-drop statistics for capture file formats that store it,
490        and will make "cf_read()" get those statistics from Wiretap.
491        We clear the statistics (marking them as "not known") in
492        "cf_open()", and "cf_read()" will only fetch them and mark
493        them as known if Wiretap supplies them, so if we get the
494        statistics now, after calling "cf_open()" but before calling
495        "cf_read()", the values we store will be used by "cf_read()".
496
497        If a future libpcap capture file format stores the statistics,
498        we'll put them into the capture file that we write, and will
499        thus not have to set them here - "cf_read()" will get them from
500        the file and use them. */
501     if (stats_known) {
502       cf_set_drops_known(capture_opts->cf, TRUE);
503
504       /* XXX - on some systems, libpcap doesn't bother filling in
505          "ps_ifdrop" - it doesn't even set it to zero - so we don't
506          bother looking at it.
507
508          Ideally, libpcap would have an interface that gave us
509          several statistics - perhaps including various interface
510          error statistics - and would tell us which of them it
511          supplies, allowing us to display only the ones it does. */
512       cf_set_drops(capture_opts->cf, stats.ps_drop);
513     }
514     switch (cf_read(capture_opts->cf)) {
515
516     case CF_READ_OK:
517     case CF_READ_ERROR:
518       /* Just because we got an error, that doesn't mean we were unable
519          to read any of the file; we handle what we could get from the
520          file. */
521       break;
522
523     case CF_READ_ABORTED:
524       /* Exit by leaving the main loop, so that any quit functions
525          we registered get called. */
526       main_window_nested_quit();
527       return FALSE;
528     }
529
530     /* We're not doing a capture any more, so we don't have a save
531        file. */
532     if (capture_opts->multi_files_on) {
533       ringbuf_free();
534     } else {
535       g_free(capture_opts->save_file);
536     }
537     capture_opts->save_file = NULL;
538
539     /* if we didn't captured even a single packet, close the file again */
540     if(cf_packet_count(capture_opts->cf) == 0) {
541       simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK, 
542       "%sNo packets captured!%s\n\n"
543       "As no data was captured, closing the %scapture file!",
544       simple_dialog_primary_start(), simple_dialog_primary_end(),
545       (cf_is_tempfile(capture_opts->cf)) ? "temporary " : "");
546       cf_close(capture_opts->cf);
547     }
548   return TRUE;
549 }
550
551
552 static void
553 stop_capture_signal_handler(int signo _U_)
554 {
555   capture_loop_stop();
556 }
557
558
559 int  
560 capture_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
561 {
562 #ifndef _WIN32
563   /*
564    * Catch SIGUSR1, so that we exit cleanly if the parent process
565    * kills us with it due to the user selecting "Capture->Stop".
566    */
567   if (capture_opts->capture_child)
568     signal(SIGUSR1, stop_capture_signal_handler);
569 #endif
570
571   return capture_loop_start(capture_opts, stats_known, stats);
572 }
573
574 void
575 capture_stop(capture_options *capture_opts)
576 {
577
578   if (capture_opts->sync_mode) {        
579     sync_pipe_stop(capture_opts);
580   }
581     
582   capture_loop_stop();
583 }
584
585 void
586 capture_kill_child(capture_options *capture_opts)
587 {
588   if (capture_opts->sync_mode) {        
589     sync_pipe_kill(capture_opts);
590   }
591 }
592
593
594 #endif /* HAVE_LIBPCAP */