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