9a540407c8bf6f5f8f8f99a843b8659a68f0eea3
[obnox/wireshark/wip.git] / dumpcap.c
1 /* dumpcap.c
2  *
3  * $Id$
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <stdlib.h> /* for exit() */
29 #include <glib.h>
30
31 #include <string.h>
32 #include <ctype.h>
33
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #ifdef NEED_GETOPT_H
39 #include "getopt.h"
40 #endif
41
42 #ifdef HAVE_NETDB_H
43 #include <netdb.h>
44 #endif
45
46 #include "ringbuffer.h"
47 #include "clopts_common.h"
48 #include "cmdarg_err.h"
49 #include "version_info.h"
50
51 #include <pcap.h>
52 #include "capture-pcap-util.h"
53
54 #ifdef _WIN32
55 #include "capture-wpcap.h"
56 #endif
57
58 #include "sync_pipe.h"
59
60 #include "capture.h"
61 #include "capture_loop.h"
62 #include "capture_sync.h"
63
64 #include "simple_dialog.h"
65 #include "util.h"
66 #include "log.h"
67 #include "file_util.h"
68
69
70 /*#define DEBUG_DUMPCAP*/
71
72 gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
73
74 static void
75 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
76                     const char *message, gpointer user_data _U_);
77
78 /* capture related options */
79 capture_options global_capture_opts;
80 capture_options *capture_opts = &global_capture_opts;
81
82 #if __GNUC__ >= 2
83 void exit_main(int err) __attribute__ ((noreturn));
84 #else
85 void exit_main(int err);
86 #endif
87
88
89 static void
90 print_usage(gboolean print_ver) {
91
92   FILE *output;
93
94
95   if (print_ver) {
96     output = stdout;
97     fprintf(output,
98         "Dumpcap " VERSION "%s\n"
99         "Capture network packets and dump them into a libpcap file.\n"
100         "See http://www.wireshark.org for more information.\n",
101         wireshark_svnversion);
102   } else {
103     output = stderr;
104   }
105   fprintf(output, "\nUsage: dumpcap [options] ...\n");
106   fprintf(output, "\n");
107   fprintf(output, "Capture interface:\n");
108   fprintf(output, "  -i <interface>           name or idx of interface (def: first none loopback)\n");
109   fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
110   fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
111   fprintf(output, "  -p                       don't capture in promiscuous mode\n");
112 #ifdef _WIN32
113   fprintf(output, "  -B <buffer size>         size of kernel buffer (def: 1MB)\n");
114 #endif
115   fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
116   fprintf(output, "  -D                       print list of interfaces and exit\n");
117   fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
118   fprintf(output, "  -I [l|s]                 print a detailed interface list (l) or interface statistics (s).\n");
119   fprintf(output, "\n");
120   fprintf(output, "Stop conditions:\n");
121   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
122   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
123   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
124   fprintf(output, "                              files:NUM - stop after NUM files\n");
125   /*fprintf(output, "\n");*/
126   fprintf(output, "Output (files):\n");
127   fprintf(output, "  -w <filename>            name of file to save (def: tempfile)\n");
128   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
129   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
130   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
131   /*fprintf(output, "\n");*/
132   fprintf(output, "Miscellaneous:\n");
133   fprintf(output, "  -v                       print version information and exit\n");
134   fprintf(output, "  -h                       display this help and exit\n");
135   fprintf(output, "\n");
136   fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
137   fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
138   fprintf(output, "\n");
139   fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
140 }
141
142 static void
143 show_version(GString *comp_info_str, GString *runtime_info_str)
144 {
145
146   printf(
147         "Dumpcap " VERSION "%s\n"
148         "\n"
149         "%s\n"
150         "%s\n"
151         "%s\n"
152         "See http://www.wireshark.org for more information.\n",
153         wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
154 }
155
156 /*
157  * Report an error in command-line arguments.
158  */
159 void
160 cmdarg_err(const char *fmt, ...)
161 {
162   va_list ap;
163
164   if(capture_child) {
165     /* Print a bare error */
166     va_start(ap, fmt);
167     vfprintf(stderr, fmt, ap);
168     va_end(ap);
169   } else {
170     va_start(ap, fmt);
171     fprintf(stderr, "dumpcap: ");
172     vfprintf(stderr, fmt, ap);
173     fprintf(stderr, "\n");
174     va_end(ap);
175   }
176 }
177
178 /*
179  * Report additional information for an error in command-line arguments.
180  */
181 void
182 cmdarg_err_cont(const char *fmt, ...)
183 {
184   va_list ap;
185
186   if(capture_child) {
187     /* XXX - convert to g_log */
188   } else {
189     va_start(ap, fmt);
190     vfprintf(stderr, fmt, ap);
191     fprintf(stderr, "\n");
192     va_end(ap);
193   }
194 }
195
196
197 #ifdef _WIN32
198 BOOL WINAPI ConsoleCtrlHandlerRoutine(DWORD dwCtrlType)
199 {
200     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
201         "Console: Control signal");
202     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
203         "Console: Control signal, CtrlType: %u", dwCtrlType);
204
205     /* Keep capture running if we're a service and a user logs off */
206     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
207         capture_loop_stop();
208         return TRUE;
209     } else {
210         return FALSE;
211     }
212 }
213 #endif
214
215 void exit_main(int status)
216 {
217 #ifdef _WIN32
218   /* Shutdown windows sockets */
219   WSACleanup();
220
221   /* can be helpful for debugging */
222 #ifdef DEBUG_DUMPCAP
223   printf("Press any key\n");
224   _getch();
225 #endif
226
227 #endif /* _WIN32 */
228
229   exit(status);
230 }
231
232
233 /* And now our feature presentation... [ fade to music ] */
234 int
235 main(int argc, char *argv[])
236 {
237   int                  opt;
238   extern char         *optarg;
239   gboolean             arg_error = FALSE;
240
241 #ifdef _WIN32
242   WSADATA              wsaData;
243 #endif  /* _WIN32 */
244
245   gboolean             start_capture = TRUE;
246   gboolean             stats_known;
247   struct pcap_stat     stats;
248   GLogLevelFlags       log_flags;
249   gboolean             list_link_layer_types = FALSE;
250   int                  status;
251
252 #define OPTSTRING_INIT "a:b:c:Df:hI:i:Lps:vw:y:Z"
253
254 #ifdef _WIN32
255 #define OPTSTRING_WIN32 "B:"
256 #else
257 #define OPTSTRING_WIN32 ""
258 #endif  /* _WIN32 */
259
260   char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
261     OPTSTRING_INIT OPTSTRING_WIN32;
262
263 #ifdef _WIN32
264   /* Load wpcap if possible. Do this before collecting the run-time version information */
265   load_wpcap();
266
267   /* ... and also load the packet.dll from wpcap */
268   /* XXX - currently not required, may change later. */
269   /*wpcap_packet_load();*/
270
271   /* Start windows sockets */
272   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
273
274   /* Set handler for Ctrl+C key */
275   SetConsoleCtrlHandler(&ConsoleCtrlHandlerRoutine, TRUE);
276 #endif  /* _WIN32 */
277
278
279   /* the default_log_handler will use stdout, which makes trouble in */
280   /* capture child mode, as it uses stdout for it's sync_pipe */
281   /* so do the filtering in the console_log_handler and not here */
282   log_flags =
283                     G_LOG_LEVEL_ERROR|
284                     G_LOG_LEVEL_CRITICAL|
285                     G_LOG_LEVEL_WARNING|
286                     G_LOG_LEVEL_MESSAGE|
287                     G_LOG_LEVEL_INFO|
288                     G_LOG_LEVEL_DEBUG|
289                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
290
291   g_log_set_handler(NULL,
292                     log_flags,
293                     console_log_handler, NULL /* user_data */);
294   g_log_set_handler(LOG_DOMAIN_MAIN,
295                     log_flags,
296                     console_log_handler, NULL /* user_data */);
297   g_log_set_handler(LOG_DOMAIN_CAPTURE,
298                     log_flags,
299             console_log_handler, NULL /* user_data */);
300   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
301                     log_flags,
302             console_log_handler, NULL /* user_data */);
303
304   /* Set the initial values in the capture_opts. This might be overwritten
305      by the command line parameters. */
306   capture_opts_init(capture_opts, NULL);
307
308   /* Default to capturing the entire packet. */
309   capture_opts->snaplen             = WTAP_MAX_PACKET_SIZE;
310
311   /* We always save to a file - if no file was specified, we save to a
312      temporary file. */
313   capture_opts->saving_to_file      = TRUE;
314   capture_opts->has_ring_num_files  = TRUE;
315
316   /* Now get our args */
317   while ((opt = getopt(argc, argv, optstring)) != -1) {
318     switch (opt) {
319       case 'h':        /* Print help and exit */
320         print_usage(TRUE);
321         exit_main(0);
322         break;
323       case 'v':        /* Show version and exit */
324       {
325         GString             *comp_info_str;
326         GString             *runtime_info_str;
327         /* Assemble the compile-time version information string */
328         comp_info_str = g_string_new("Compiled with ");
329         get_compiled_version_info(comp_info_str, NULL);
330
331         /* Assemble the run-time version information string */
332         runtime_info_str = g_string_new("Running ");
333         get_runtime_version_info(runtime_info_str, NULL);
334         show_version(comp_info_str, runtime_info_str);
335         g_string_free(comp_info_str, TRUE);
336         g_string_free(runtime_info_str, TRUE);
337         exit_main(0);
338         break;
339       }
340       /*** capture option specific ***/
341       case 'a':        /* autostop criteria */
342       case 'b':        /* Ringbuffer option */
343       case 'c':        /* Capture x packets */
344       case 'f':        /* capture filter */
345       case 'i':        /* Use interface x */
346       case 'p':        /* Don't capture in promiscuous mode */
347       case 's':        /* Set the snapshot (capture) length */
348       case 'w':        /* Write to capture file x */
349       case 'y':        /* Set the pcap data link type */
350 #ifdef _WIN32
351       case 'B':        /* Buffer size */
352 #endif /* _WIN32 */
353         status = capture_opts_add_opt(capture_opts, opt, optarg, &start_capture);
354         if(status != 0) {
355             exit_main(status);
356         }
357         break;
358       /*** hidden option: Wireshark child mode (using binary output messages) ***/
359       case 'Z':
360           capture_child = TRUE;
361 #ifdef _WIN32
362           /* set output pipe to binary mode, to avoid ugly text conversions */
363                   _setmode(1, O_BINARY);
364 #endif
365           break;
366
367       /*** all non capture option specific ***/
368       case 'D':        /* Print a list of capture devices and exit */
369         status = capture_opts_list_interfaces(FALSE);
370         exit_main(status);
371         break;
372       /* XXX - We might want to use 'D' for this.  Do we use GNU
373        * getopt on every platform (which supports optional arguments)? */
374       /* XXX - Implement interface stats */
375       case 'I':
376         status = capture_opts_list_interfaces(TRUE);
377         exit_main(status);
378       case 'L':        /* Print list of link-layer types and exit */
379         list_link_layer_types = TRUE;
380         break;
381       default:
382       case '?':        /* Bad flag - print usage message */
383         cmdarg_err("Invalid Option: %s", argv[optind-1]);
384         arg_error = TRUE;
385         break;
386     }
387   }
388   argc -= optind;
389   argv += optind;
390   if (argc >= 1) {
391       /* user specified file name as regular command-line argument */
392       /* XXX - use it as the capture file name (or something else)? */
393     argc--;
394     argv++;
395   }
396
397   if (argc != 0) {
398     /*
399      * Extra command line arguments were specified; complain.
400      * XXX - interpret as capture filter, as tcpdump and tshark do?
401      */
402     cmdarg_err("Invalid argument: %s", argv[0]);
403     arg_error = TRUE;
404   }
405
406   if (arg_error) {
407     print_usage(FALSE);
408     exit_main(1);
409   }
410
411   if (list_link_layer_types) {
412     /* We're supposed to list the link-layer types for an interface;
413        did the user also specify a capture file to be read? */
414     /* No - did they specify a ring buffer option? */
415     if (capture_opts->multi_files_on) {
416       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
417       exit_main(1);
418     }
419   } else {
420     /* No - was the ring buffer option specified and, if so, does it make
421        sense? */
422     if (capture_opts->multi_files_on) {
423       /* Ring buffer works only under certain conditions:
424          a) ring buffer does not work with temporary files;
425          b) it makes no sense to enable the ring buffer if the maximum
426             file size is set to "infinite". */
427       if (capture_opts->save_file == NULL) {
428         cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
429         capture_opts->multi_files_on = FALSE;
430       }
431       if (!capture_opts->has_autostop_filesize && !capture_opts->has_file_duration) {
432         cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
433 /* XXX - this must be redesigned as the conditions changed */
434 /*      capture_opts->multi_files_on = FALSE;*/
435       }
436     }
437   }
438
439   if (capture_opts_trim_iface(capture_opts, NULL) == FALSE) {
440         cmdarg_err("No capture interfaces available (maybe lack of privileges?).");
441     exit_main(1);
442   }
443
444   /* Let the user know what interface was chosen. */
445   /* get_interface_descriptive_name() is not available! */
446   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", capture_opts->iface);
447
448   if (list_link_layer_types) {
449     status = capture_opts_list_link_layer_types(capture_opts);
450     exit_main(status);
451   }
452
453   capture_opts_trim_snaplen(capture_opts, MIN_PACKET_SIZE);
454   capture_opts_trim_ring_num_files(capture_opts);
455
456   /* Now start the capture. */
457
458   if(capture_loop_start(capture_opts, &stats_known, &stats) == TRUE) {
459       /* capture ok */
460       exit_main(0);
461   } else {
462       /* capture failed */
463       exit_main(1);
464   }
465 }
466
467
468 static void
469 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
470                     const char *message, gpointer user_data _U_)
471 {
472   time_t curr;
473   struct tm *today;
474   const char *level;
475
476
477   /* ignore log message, if log_level isn't interesting */
478   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
479 #ifndef DEBUG_DUMPCAP
480     return;
481 #endif
482   }
483
484   /* create a "timestamp" */
485   time(&curr);
486   today = localtime(&curr);
487
488   switch(log_level & G_LOG_LEVEL_MASK) {
489   case G_LOG_LEVEL_ERROR:
490     level = "Err ";
491     break;
492   case G_LOG_LEVEL_CRITICAL:
493     level = "Crit";
494     break;
495   case G_LOG_LEVEL_WARNING:
496     level = "Warn";
497     break;
498   case G_LOG_LEVEL_MESSAGE:
499     level = "Msg ";
500     break;
501   case G_LOG_LEVEL_INFO:
502     level = "Info";
503     break;
504   case G_LOG_LEVEL_DEBUG:
505     level = "Dbg ";
506     break;
507   default:
508     fprintf(stderr, "unknown log_level %u\n", log_level);
509     level = NULL;
510     g_assert_not_reached();
511   }
512
513   /* don't use printf (stdout), in child mode we're using stdout for the sync_pipe */
514   if(log_level & G_LOG_LEVEL_MESSAGE) {
515     /* normal user messages without additional infos */
516     fprintf(stderr, "%s\n", message);
517     fflush(stderr);
518   } else {
519     /* info/debug messages with additional infos */
520     fprintf(stderr, "%02u:%02u:%02u %8s %s %s\n",
521             today->tm_hour, today->tm_min, today->tm_sec,
522             log_domain != NULL ? log_domain : "",
523             level, message);
524     fflush(stderr);
525   }
526 }
527
528
529 /****************************************************************************************************************/
530 /* indication report routines */
531
532
533 void
534 report_packet_count(int packet_count)
535 {
536     char tmp[SP_DECISIZE+1+1];
537     static int count = 0;
538
539     if(capture_child) {
540         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
541         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
542         pipe_write_block(1, SP_PACKET_COUNT, tmp);
543     } else {
544         count += packet_count;
545         fprintf(stderr, "\rPackets: %u ", count);
546         /* stderr could be line buffered */
547         fflush(stderr);
548     }
549 }
550
551 void
552 report_new_capture_file(const char *filename)
553 {
554     if(capture_child) {
555         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
556         pipe_write_block(1, SP_FILE, filename);
557     } else {
558         fprintf(stderr, "File: %s\n", filename);
559         /* stderr could be line buffered */
560         fflush(stderr);
561     }
562 }
563
564 void
565 report_cfilter_error(const char *cfilter, const char *errmsg)
566 {
567     if (capture_child) {
568         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
569         pipe_write_block(1, SP_BAD_FILTER, errmsg);
570     } else {
571         fprintf(stderr,
572           "Invalid capture filter: \"%s\"!\n"
573           "\n"
574           "That string isn't a valid capture filter (%s).\n"
575           "See the User's Guide for a description of the capture filter syntax.\n",
576           cfilter, errmsg);
577     }
578 }
579
580 void
581 report_capture_error(const char *error_msg, const char *secondary_error_msg)
582 {
583     if(capture_child) {
584         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
585             "Primary Error: %s", error_msg);
586         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
587             "Secondary Error: %s", secondary_error_msg);
588         sync_pipe_errmsg_to_parent(error_msg, secondary_error_msg);
589     } else {
590         fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
591     }
592 }
593
594 void
595 report_packet_drops(int drops)
596 {
597     char tmp[SP_DECISIZE+1+1];
598
599     g_snprintf(tmp, sizeof(tmp), "%d", drops);
600
601     if(capture_child) {
602         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
603         pipe_write_block(1, SP_DROPS, tmp);
604     } else {
605         fprintf(stderr, "Packets dropped: %s\n", tmp);
606         /* stderr could be line buffered */
607         fflush(stderr);
608     }
609 }
610
611
612 /****************************************************************************************************************/
613 /* signal_pipe handling */
614
615
616 #ifdef _WIN32
617 gboolean
618 signal_pipe_check_running(void)
619 {
620     /* any news from our parent (stdin)? -> just stop the capture */
621     HANDLE handle;
622     DWORD avail = 0;
623     gboolean result;
624
625
626     /* if we are running standalone, no check required */
627     if(!capture_child) {
628         return TRUE;
629     }
630
631     handle = (HANDLE) GetStdHandle(STD_INPUT_HANDLE);
632     result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
633
634     if(!result || avail > 0) {
635         /* peek failed or some bytes really available */
636         /* (if not piping from stdin this would fail) */
637         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
638             "Signal pipe: Stop capture");
639         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
640             "Signal pipe: handle: %x result: %u avail: %u", handle, result, avail);
641         return FALSE;
642     } else {
643         /* pipe ok and no bytes available */
644         return TRUE;
645     }
646 }
647 #endif
648
649
650 /****************************************************************************************************************/
651 /* Stub functions */
652
653
654 const char *netsnmp_get_version(void) { return ""; }
655