From Florent.Drouin@alcatel.fr:
[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 Wireshark 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.wireshark.org 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.wireshark.org 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: Wireshark 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      * XXX - interpret as capture filter, as tcpdump and tshark do?
383      */
384     cmdarg_err("Invalid argument: %s", argv[0]);
385     arg_error = TRUE;
386   }
387
388   if (arg_error) {
389     print_usage(FALSE);
390     exit_main(1);
391   }
392
393   if (list_link_layer_types) {
394     /* We're supposed to list the link-layer types for an interface;
395        did the user also specify a capture file to be read? */
396     /* No - did they specify a ring buffer option? */
397     if (capture_opts->multi_files_on) {
398       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
399       exit_main(1);
400     }
401   } else {
402     /* No - was the ring buffer option specified and, if so, does it make
403        sense? */
404     if (capture_opts->multi_files_on) {
405       /* Ring buffer works only under certain conditions:
406          a) ring buffer does not work with temporary files;
407          b) it makes no sense to enable the ring buffer if the maximum
408             file size is set to "infinite". */
409       if (capture_opts->save_file == NULL) {
410         cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
411         capture_opts->multi_files_on = FALSE;
412       }
413       if (!capture_opts->has_autostop_filesize && !capture_opts->has_file_duration) {
414         cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
415 /* XXX - this must be redesigned as the conditions changed */
416 /*      capture_opts->multi_files_on = FALSE;*/
417       }
418     }
419   }
420
421   if (capture_opts_trim_iface(capture_opts, NULL) == FALSE) {
422         cmdarg_err("No capture interfaces available (maybe lack of privileges?).");
423     exit_main(1);
424   }
425
426   /* Let the user know what interface was chosen. */
427   /* get_interface_descriptive_name() is not available! */
428   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", capture_opts->iface);
429
430   if (list_link_layer_types) {
431     status = capture_opts_list_link_layer_types(capture_opts);
432     exit_main(status);
433   }
434
435   capture_opts_trim_snaplen(capture_opts, MIN_PACKET_SIZE);
436   capture_opts_trim_ring_num_files(capture_opts);
437
438   /* Now start the capture. */
439
440   if(capture_loop_start(capture_opts, &stats_known, &stats) == TRUE) {
441       /* capture ok */
442       exit_main(0);
443   } else {
444       /* capture failed */
445       exit_main(1);
446   }
447 }
448
449
450 static void
451 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
452                     const char *message, gpointer user_data _U_)
453 {
454   time_t curr;
455   struct tm *today;
456   const char *level;
457
458
459   /* ignore log message, if log_level isn't interesting */
460   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
461 #ifndef DEBUG_DUMPCAP
462     return;
463 #endif
464   }
465
466   /* create a "timestamp" */
467   time(&curr);
468   today = localtime(&curr);    
469
470   switch(log_level & G_LOG_LEVEL_MASK) {
471   case G_LOG_LEVEL_ERROR:
472     level = "Err ";
473     break;
474   case G_LOG_LEVEL_CRITICAL:
475     level = "Crit";
476     break;
477   case G_LOG_LEVEL_WARNING:
478     level = "Warn";
479     break;
480   case G_LOG_LEVEL_MESSAGE:
481     level = "Msg ";
482     break;
483   case G_LOG_LEVEL_INFO:
484     level = "Info";
485     break;
486   case G_LOG_LEVEL_DEBUG:
487     level = "Dbg ";
488     break;
489   default:
490     fprintf(stderr, "unknown log_level %u\n", log_level);
491     level = NULL;
492     g_assert_not_reached();
493   }
494
495   /* don't use printf (stdout), in child mode we're using stdout for the sync_pipe */
496   if(log_level & G_LOG_LEVEL_MESSAGE) {
497     /* normal user messages without additional infos */
498     fprintf(stderr, "%s\n", message);
499     fflush(stderr);
500   } else {
501     /* info/debug messages with additional infos */
502     fprintf(stderr, "%02u:%02u:%02u %8s %s %s\n",
503             today->tm_hour, today->tm_min, today->tm_sec,
504             log_domain != NULL ? log_domain : "",
505             level, message);
506     fflush(stderr);
507   }
508 }
509
510
511 /****************************************************************************************************************/
512 /* indication report routines */
513
514
515 void
516 report_packet_count(int packet_count)
517 {
518     char tmp[SP_DECISIZE+1+1];
519     static int count = 0;
520
521
522     if(capture_child) {
523         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
524         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
525         pipe_write_block(1, SP_PACKET_COUNT, tmp);
526     } else {
527         count += packet_count;
528         fprintf(stderr, "\rPackets: %u ", count);
529         /* stderr could be line buffered */
530         fflush(stderr);
531     }
532 }
533
534 void
535 report_new_capture_file(const char *filename)
536 {
537
538     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
539
540     if(capture_child) {
541         pipe_write_block(1, SP_FILE, filename);
542     }
543 }
544
545 void
546 report_cfilter_error(const char *cfilter _U_, const char *errmsg)
547 {
548
549     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
550
551     if (capture_child) {
552         pipe_write_block(1, SP_BAD_FILTER, errmsg);
553     }
554 }
555
556 void
557 report_capture_error(const char *error_msg, const char *secondary_error_msg)
558 {
559
560     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, 
561         "Primary Error: %s", error_msg);
562     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, 
563         "Secondary Error: %s", secondary_error_msg);
564
565     if(capture_child) {
566         sync_pipe_errmsg_to_parent(error_msg, secondary_error_msg);
567     }
568 }
569
570 void
571 report_packet_drops(int drops)
572 {
573     char tmp[SP_DECISIZE+1+1];
574
575
576     g_snprintf(tmp, sizeof(tmp), "%d", drops);
577     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
578
579     if(capture_child) {
580         pipe_write_block(1, SP_DROPS, tmp);
581     }
582 }
583
584
585 /****************************************************************************************************************/
586 /* signal_pipe handling */
587
588
589 #ifdef _WIN32
590 gboolean
591 signal_pipe_check_running(void)
592 {
593     /* any news from our parent (stdin)? -> just stop the capture */
594     HANDLE handle;
595     DWORD avail = 0;
596     gboolean result;
597
598
599     /* if we are running standalone, no check required */
600     if(!capture_child) {
601         return TRUE;
602     }
603
604     handle = (HANDLE) GetStdHandle(STD_INPUT_HANDLE);
605     result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
606
607     if(!result || avail > 0) {
608         /* peek failed or some bytes really available */
609         /* (if not piping from stdin this would fail) */
610         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
611             "Signal pipe: Stop capture");
612         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
613             "Signal pipe: handle: %x result: %u avail: %u", handle, result, avail);
614         return FALSE;
615     } else {
616         /* pipe ok and no bytes available */
617         return TRUE;
618     }
619 }
620 #endif
621
622
623 /****************************************************************************************************************/
624 /* Stub functions */
625
626
627 const char *netsnmp_get_version(void) { return ""; }
628