From Paul Moore:
[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         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, "\n");
119   fprintf(output, "Stop conditions:\n");
120   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
121   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
122   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
123   fprintf(output, "                              files:NUM - stop after NUM files\n");
124   /*fprintf(output, "\n");*/
125   fprintf(output, "Output (files):\n");
126   fprintf(output, "  -w <filename>            name of file to save (def: tempfile)\n");
127   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
128   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
129   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
130   /*fprintf(output, "\n");*/
131   fprintf(output, "Miscellaneous:\n");
132   fprintf(output, "  -v                       print version information and exit\n");
133   fprintf(output, "  -h                       display this help and exit\n");
134   fprintf(output, "\n");
135   fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
136   fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
137   fprintf(output, "\n");
138   fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
139 }
140
141 static void
142 show_version(GString *comp_info_str, GString *runtime_info_str)
143 {
144
145   printf(
146         "Dumpcap " VERSION "%s\n"
147         "\n"
148         "%s\n"
149         "%s\n"
150         "%s\n"
151         "See http://www.wireshark.org for more information.\n",
152         svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
153 }
154
155 /*
156  * Report an error in command-line arguments.
157  */
158 void
159 cmdarg_err(const char *fmt, ...)
160 {
161   va_list ap;
162
163   if(capture_child) {
164     /* XXX - convert to g_log */
165   } else {
166     va_start(ap, fmt);
167     fprintf(stderr, "dumpcap: ");
168     vfprintf(stderr, fmt, ap);
169     fprintf(stderr, "\n");
170     va_end(ap);
171   }
172 }
173
174 /*
175  * Report additional information for an error in command-line arguments.
176  */
177 void
178 cmdarg_err_cont(const char *fmt, ...)
179 {
180   va_list ap;
181
182   if(capture_child) {
183     /* XXX - convert to g_log */
184   } else {
185     va_start(ap, fmt);
186     vfprintf(stderr, fmt, ap);
187     fprintf(stderr, "\n");
188     va_end(ap);
189   }
190 }
191
192
193 #ifdef _WIN32
194 BOOL WINAPI ConsoleCtrlHandlerRoutine(DWORD dwCtrlType)
195 {
196     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
197         "Console: Control signal");
198     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
199         "Console: Control signal, CtrlType: %u", dwCtrlType);
200
201     /* Keep capture running if we're a service and a user logs off */
202     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
203         capture_loop_stop();
204         return TRUE;
205     } else {
206         return FALSE;
207     }
208 }
209 #endif
210
211 void exit_main(int status)
212 {
213 #ifdef _WIN32
214   /* Shutdown windows sockets */
215   WSACleanup();
216
217   /* can be helpful for debugging */
218 #ifdef DEBUG_DUMPCAP
219   printf("Press any key\n");
220   _getch();
221 #endif
222
223 #endif /* _WIN32 */
224
225   exit(status);
226 }
227
228
229 /* And now our feature presentation... [ fade to music ] */
230 int
231 main(int argc, char *argv[])
232 {
233   int                  opt;
234   extern char         *optarg;
235   gboolean             arg_error = FALSE;
236
237 #ifdef _WIN32
238   WSADATA              wsaData;
239 #endif  /* _WIN32 */
240
241   gboolean             start_capture = TRUE;
242   gboolean             stats_known;
243   struct pcap_stat     stats;
244   GLogLevelFlags       log_flags;
245   gboolean             list_link_layer_types = FALSE;
246   int                  status;
247
248 #define OPTSTRING_INIT "a:b:c:Df:hi:Lps:vw:y:Z"
249
250 #ifdef _WIN32
251 #define OPTSTRING_WIN32 "B:"
252 #else
253 #define OPTSTRING_WIN32 ""
254 #endif  /* _WIN32 */
255
256   char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
257     OPTSTRING_INIT OPTSTRING_WIN32;
258
259 #ifdef _WIN32
260   /* Load wpcap if possible. Do this before collecting the run-time version information */
261   load_wpcap();
262
263   /* ... and also load the packet.dll from wpcap */
264   /* XXX - currently not required, may change later. */
265   /*wpcap_packet_load();*/
266
267   /* Start windows sockets */
268   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
269
270   /* Set handler for Ctrl+C key */
271   SetConsoleCtrlHandler(&ConsoleCtrlHandlerRoutine, TRUE);
272 #endif  /* _WIN32 */
273
274
275   /* the default_log_handler will use stdout, which makes trouble in */
276   /* capture child mode, as it uses stdout for it's sync_pipe */
277   /* so do the filtering in the console_log_handler and not here */
278   log_flags = 
279                     G_LOG_LEVEL_ERROR|
280                     G_LOG_LEVEL_CRITICAL|
281                     G_LOG_LEVEL_WARNING|
282                     G_LOG_LEVEL_MESSAGE|
283                     G_LOG_LEVEL_INFO|
284                     G_LOG_LEVEL_DEBUG|
285                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
286
287   g_log_set_handler(NULL,
288                     log_flags,
289                     console_log_handler, NULL /* user_data */);
290   g_log_set_handler(LOG_DOMAIN_MAIN,
291                     log_flags,
292                     console_log_handler, NULL /* user_data */);
293   g_log_set_handler(LOG_DOMAIN_CAPTURE,
294                     log_flags,
295             console_log_handler, NULL /* user_data */);
296   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
297                     log_flags,
298             console_log_handler, NULL /* user_data */);
299
300   /* Set the initial values in the capture_opts. This might be overwritten 
301      by the command line parameters. */
302   capture_opts_init(capture_opts, NULL);
303
304   /* Default to capturing the entire packet. */
305   capture_opts->snaplen             = WTAP_MAX_PACKET_SIZE;
306
307   /* We always save to a file - if no file was specified, we save to a
308      temporary file. */
309   capture_opts->saving_to_file      = TRUE;
310   capture_opts->has_ring_num_files  = TRUE;
311
312   /* Now get our args */
313   while ((opt = getopt(argc, argv, optstring)) != -1) {
314     switch (opt) {
315       case 'h':        /* Print help and exit */
316         print_usage(TRUE);
317         exit_main(0);
318         break;
319       case 'v':        /* Show version and exit */
320       {
321         GString             *comp_info_str;
322         GString             *runtime_info_str;
323         /* Assemble the compile-time version information string */
324         comp_info_str = g_string_new("Compiled with ");
325         get_compiled_version_info(comp_info_str, NULL);
326
327         /* Assemble the run-time version information string */
328         runtime_info_str = g_string_new("Running ");
329         get_runtime_version_info(runtime_info_str, NULL);               
330         show_version(comp_info_str, runtime_info_str);
331         g_string_free(comp_info_str, TRUE);
332         g_string_free(runtime_info_str, TRUE);
333         exit_main(0);
334         break;
335       }
336       /*** capture option specific ***/
337       case 'a':        /* autostop criteria */
338       case 'b':        /* Ringbuffer option */
339       case 'c':        /* Capture x packets */
340       case 'f':        /* capture filter */
341       case 'i':        /* Use interface x */
342       case 'p':        /* Don't capture in promiscuous mode */
343       case 's':        /* Set the snapshot (capture) length */
344       case 'w':        /* Write to capture file x */
345       case 'y':        /* Set the pcap data link type */
346 #ifdef _WIN32
347       case 'B':        /* Buffer size */
348 #endif /* _WIN32 */
349         status = capture_opts_add_opt(capture_opts, opt, optarg, &start_capture);
350         if(status != 0) {
351             exit_main(status);
352         }
353         break;
354       /*** hidden option: Wireshark child mode (using binary output messages) ***/
355       case 'Z':
356           capture_child = TRUE;
357 #ifdef _WIN32
358           /* set output pipe to binary mode, to avoid ugly text conversions */
359                   _setmode(1, O_BINARY);
360 #endif
361           break;
362
363       /*** all non capture option specific ***/
364       case 'D':        /* Print a list of capture devices and exit */
365         status = capture_opts_list_interfaces();
366         exit_main(status);
367         break;
368       case 'L':        /* Print list of link-layer types and exit */
369         list_link_layer_types = TRUE;
370         break;
371       default:
372       case '?':        /* Bad flag - print usage message */
373         cmdarg_err("Invalid Option: %s", argv[optind-1]);
374         arg_error = TRUE;
375         break;
376     }
377   }
378   argc -= optind;
379   argv += optind;
380   if (argc >= 1) {
381       /* user specified file name as regular command-line argument */
382       /* XXX - use it as the capture file name (or something else)? */
383     argc--;
384     argv++;
385   }
386
387   if (argc != 0) {
388     /*
389      * Extra command line arguments were specified; complain.
390      * XXX - interpret as capture filter, as tcpdump and tshark do?
391      */
392     cmdarg_err("Invalid argument: %s", argv[0]);
393     arg_error = TRUE;
394   }
395
396   if (arg_error) {
397     print_usage(FALSE);
398     exit_main(1);
399   }
400
401   if (list_link_layer_types) {
402     /* We're supposed to list the link-layer types for an interface;
403        did the user also specify a capture file to be read? */
404     /* No - did they specify a ring buffer option? */
405     if (capture_opts->multi_files_on) {
406       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
407       exit_main(1);
408     }
409   } else {
410     /* No - was the ring buffer option specified and, if so, does it make
411        sense? */
412     if (capture_opts->multi_files_on) {
413       /* Ring buffer works only under certain conditions:
414          a) ring buffer does not work with temporary files;
415          b) it makes no sense to enable the ring buffer if the maximum
416             file size is set to "infinite". */
417       if (capture_opts->save_file == NULL) {
418         cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
419         capture_opts->multi_files_on = FALSE;
420       }
421       if (!capture_opts->has_autostop_filesize && !capture_opts->has_file_duration) {
422         cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
423 /* XXX - this must be redesigned as the conditions changed */
424 /*      capture_opts->multi_files_on = FALSE;*/
425       }
426     }
427   }
428
429   if (capture_opts_trim_iface(capture_opts, NULL) == FALSE) {
430         cmdarg_err("No capture interfaces available (maybe lack of privileges?).");
431     exit_main(1);
432   }
433
434   /* Let the user know what interface was chosen. */
435   /* get_interface_descriptive_name() is not available! */
436   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", capture_opts->iface);
437
438   if (list_link_layer_types) {
439     status = capture_opts_list_link_layer_types(capture_opts);
440     exit_main(status);
441   }
442
443   capture_opts_trim_snaplen(capture_opts, MIN_PACKET_SIZE);
444   capture_opts_trim_ring_num_files(capture_opts);
445
446   /* Now start the capture. */
447
448   if(capture_loop_start(capture_opts, &stats_known, &stats) == TRUE) {
449       /* capture ok */
450       exit_main(0);
451   } else {
452       /* capture failed */
453       exit_main(1);
454   }
455 }
456
457
458 static void
459 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
460                     const char *message, gpointer user_data _U_)
461 {
462   time_t curr;
463   struct tm *today;
464   const char *level;
465
466
467   /* ignore log message, if log_level isn't interesting */
468   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
469 #ifndef DEBUG_DUMPCAP
470     return;
471 #endif
472   }
473
474   /* create a "timestamp" */
475   time(&curr);
476   today = localtime(&curr);    
477
478   switch(log_level & G_LOG_LEVEL_MASK) {
479   case G_LOG_LEVEL_ERROR:
480     level = "Err ";
481     break;
482   case G_LOG_LEVEL_CRITICAL:
483     level = "Crit";
484     break;
485   case G_LOG_LEVEL_WARNING:
486     level = "Warn";
487     break;
488   case G_LOG_LEVEL_MESSAGE:
489     level = "Msg ";
490     break;
491   case G_LOG_LEVEL_INFO:
492     level = "Info";
493     break;
494   case G_LOG_LEVEL_DEBUG:
495     level = "Dbg ";
496     break;
497   default:
498     fprintf(stderr, "unknown log_level %u\n", log_level);
499     level = NULL;
500     g_assert_not_reached();
501   }
502
503   /* don't use printf (stdout), in child mode we're using stdout for the sync_pipe */
504   if(log_level & G_LOG_LEVEL_MESSAGE) {
505     /* normal user messages without additional infos */
506     fprintf(stderr, "%s\n", message);
507     fflush(stderr);
508   } else {
509     /* info/debug messages with additional infos */
510     fprintf(stderr, "%02u:%02u:%02u %8s %s %s\n",
511             today->tm_hour, today->tm_min, today->tm_sec,
512             log_domain != NULL ? log_domain : "",
513             level, message);
514     fflush(stderr);
515   }
516 }
517
518
519 /****************************************************************************************************************/
520 /* indication report routines */
521
522
523 void
524 report_packet_count(int packet_count)
525 {
526     char tmp[SP_DECISIZE+1+1];
527     static int count = 0;
528
529
530     if(capture_child) {
531         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
532         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
533         pipe_write_block(1, SP_PACKET_COUNT, tmp);
534     } else {
535         count += packet_count;
536         fprintf(stderr, "\rPackets: %u ", count);
537         /* stderr could be line buffered */
538         fflush(stderr);
539     }
540 }
541
542 void
543 report_new_capture_file(const char *filename)
544 {
545
546     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
547
548     if(capture_child) {
549         pipe_write_block(1, SP_FILE, filename);
550     }
551 }
552
553 void
554 report_cfilter_error(const char *cfilter _U_, const char *errmsg)
555 {
556
557     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
558
559     if (capture_child) {
560         pipe_write_block(1, SP_BAD_FILTER, errmsg);
561     }
562 }
563
564 void
565 report_capture_error(const char *error_msg, const char *secondary_error_msg)
566 {
567
568     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, 
569         "Primary Error: %s", error_msg);
570     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, 
571         "Secondary Error: %s", secondary_error_msg);
572
573     if(capture_child) {
574         sync_pipe_errmsg_to_parent(error_msg, secondary_error_msg);
575     }
576 }
577
578 void
579 report_packet_drops(int drops)
580 {
581     char tmp[SP_DECISIZE+1+1];
582
583
584     g_snprintf(tmp, sizeof(tmp), "%d", drops);
585     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
586
587     if(capture_child) {
588         pipe_write_block(1, SP_DROPS, tmp);
589     }
590 }
591
592
593 /****************************************************************************************************************/
594 /* signal_pipe handling */
595
596
597 #ifdef _WIN32
598 gboolean
599 signal_pipe_check_running(void)
600 {
601     /* any news from our parent (stdin)? -> just stop the capture */
602     HANDLE handle;
603     DWORD avail = 0;
604     gboolean result;
605
606
607     /* if we are running standalone, no check required */
608     if(!capture_child) {
609         return TRUE;
610     }
611
612     handle = (HANDLE) GetStdHandle(STD_INPUT_HANDLE);
613     result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
614
615     if(!result || avail > 0) {
616         /* peek failed or some bytes really available */
617         /* (if not piping from stdin this would fail) */
618         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
619             "Signal pipe: Stop capture");
620         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
621             "Signal pipe: handle: %x result: %u avail: %u", handle, result, avail);
622         return FALSE;
623     } else {
624         /* pipe ok and no bytes available */
625         return TRUE;
626     }
627 }
628 #endif
629
630
631 /****************************************************************************************************************/
632 /* Stub functions */
633
634
635 const char *netsnmp_get_version(void) { return ""; }
636