tcpdump.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644
  1. /*
  2. * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
  3. * The Regents of the University of California. All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that: (1) source code distributions
  7. * retain the above copyright notice and this paragraph in its entirety, (2)
  8. * distributions including binary code include the above copyright notice and
  9. * this paragraph in its entirety in the documentation or other materials
  10. * provided with the distribution, and (3) all advertising materials mentioning
  11. * features or use of this software display the following acknowledgement:
  12. * ``This product includes software developed by the University of California,
  13. * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
  14. * the University nor the names of its contributors may be used to endorse
  15. * or promote products derived from this software without specific prior
  16. * written permission.
  17. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
  18. * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
  19. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  20. *
  21. * Support for splitting captures into multiple files with a maximum
  22. * file size:
  23. *
  24. * Copyright (c) 2001
  25. * Seth Webster <swebster@sst.ll.mit.edu>
  26. */
  27. #ifndef lint
  28. static const char copyright[] _U_ =
  29. "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
  30. The Regents of the University of California. All rights reserved.\n";
  31. #endif
  32. /*
  33. * tcpdump - dump traffic on a network
  34. *
  35. * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
  36. * Mercilessly hacked and occasionally improved since then via the
  37. * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
  38. */
  39. #ifdef HAVE_CONFIG_H
  40. #include "config.h"
  41. #endif
  42. /*
  43. * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on
  44. * 0.8. That means it has pcap_findalldevs() but the header doesn't
  45. * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs().
  46. */
  47. #ifdef HAVE_PCAP_FINDALLDEVS
  48. #ifndef HAVE_PCAP_IF_T
  49. #undef HAVE_PCAP_FINDALLDEVS
  50. #endif
  51. #endif
  52. #include <netdissect-stdinc.h>
  53. #include <sys/stat.h>
  54. #ifdef HAVE_FCNTL_H
  55. #include <fcntl.h>
  56. #endif
  57. #ifdef HAVE_LIBCRYPTO
  58. #include <openssl/crypto.h>
  59. #endif
  60. #ifdef HAVE_GETOPT_LONG
  61. #include <getopt.h>
  62. #else
  63. #include "getopt_long.h"
  64. #endif
  65. /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
  66. * to compile if <pcap.h> has already been included; including the headers
  67. * in the opposite order works fine.
  68. */
  69. #ifdef HAVE_CAPSICUM
  70. #include <sys/capability.h>
  71. #include <sys/ioccom.h>
  72. #include <net/bpf.h>
  73. #include <libgen.h>
  74. #endif /* HAVE_CAPSICUM */
  75. #include <pcap.h>
  76. #include <signal.h>
  77. #include <stdio.h>
  78. #include <stdarg.h>
  79. #include <stdlib.h>
  80. #include <string.h>
  81. #include <limits.h>
  82. #ifndef _WIN32
  83. #include <sys/wait.h>
  84. #include <sys/resource.h>
  85. #include <pwd.h>
  86. #include <grp.h>
  87. #endif /* _WIN32 */
  88. /* capabilities convenience library */
  89. /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
  90. * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
  91. * Thus, the later tests are done only on HAVE_LIBCAP_NG.
  92. */
  93. #ifdef HAVE_LIBCAP_NG
  94. #ifdef HAVE_CAP_NG_H
  95. #include <cap-ng.h>
  96. #else
  97. #undef HAVE_LIBCAP_NG
  98. #endif /* HAVE_CAP_NG_H */
  99. #endif /* HAVE_LIBCAP_NG */
  100. #include "netdissect.h"
  101. #include "interface.h"
  102. #include "addrtoname.h"
  103. #include "machdep.h"
  104. #include "setsignal.h"
  105. #include "gmt2local.h"
  106. #include "pcap-missing.h"
  107. #include "ascii_strcasecmp.h"
  108. #include "print.h"
  109. #ifndef PATH_MAX
  110. #define PATH_MAX 1024
  111. #endif
  112. #ifdef SIGINFO
  113. #define SIGNAL_REQ_INFO SIGINFO
  114. #elif SIGUSR1
  115. #define SIGNAL_REQ_INFO SIGUSR1
  116. #endif
  117. static int Bflag; /* buffer size */
  118. static long Cflag; /* rotate dump files after this many bytes */
  119. static int Cflag_count; /* Keep track of which file number we're writing */
  120. static int Dflag; /* list available devices and exit */
  121. /*
  122. * This is exported because, in some versions of libpcap, if libpcap
  123. * is built with optimizer debugging code (which is *NOT* the default
  124. * configuration!), the library *imports*(!) a variable named dflag,
  125. * under the expectation that tcpdump is exporting it, to govern
  126. * how much debugging information to print when optimizing
  127. * the generated BPF code.
  128. *
  129. * This is a horrible hack; newer versions of libpcap don't import
  130. * dflag but, instead, *if* built with optimizer debugging code,
  131. * *export* a routine to set that flag.
  132. */
  133. int dflag; /* print filter code */
  134. static int Gflag; /* rotate dump files after this many seconds */
  135. static int Gflag_count; /* number of files created with Gflag rotation */
  136. static time_t Gflag_time; /* The last time_t the dump file was rotated. */
  137. static int Lflag; /* list available data link types and exit */
  138. static int Iflag; /* rfmon (monitor) mode */
  139. #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
  140. static int Jflag; /* list available time stamp types */
  141. #endif
  142. static int jflag = -1; /* packet time stamp source */
  143. static int pflag; /* don't go promiscuous */
  144. #ifdef HAVE_PCAP_SETDIRECTION
  145. static int Qflag = -1; /* restrict captured packet by send/receive direction */
  146. #endif
  147. static int Uflag; /* "unbuffered" output of dump files */
  148. static int Wflag; /* recycle output files after this number of files */
  149. static int WflagChars;
  150. static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
  151. static int immediate_mode;
  152. static int infodelay;
  153. static int infoprint;
  154. char *program_name;
  155. /* Forwards */
  156. static void error(FORMAT_STRING(const char *), ...) NORETURN PRINTFLIKE(1, 2);
  157. static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
  158. static void exit_tcpdump(int) NORETURN;
  159. static RETSIGTYPE cleanup(int);
  160. static RETSIGTYPE child_cleanup(int);
  161. static void print_version(void);
  162. static void print_usage(void);
  163. static void show_tstamp_types_and_exit(pcap_t *, const char *device) NORETURN;
  164. static void show_dlts_and_exit(pcap_t *, const char *device) NORETURN;
  165. #ifdef HAVE_PCAP_FINDALLDEVS
  166. static void show_devices_and_exit (void) NORETURN;
  167. #endif
  168. static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
  169. static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
  170. static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
  171. static void droproot(const char *, const char *);
  172. #ifdef SIGNAL_REQ_INFO
  173. RETSIGTYPE requestinfo(int);
  174. #endif
  175. #if defined(USE_WIN32_MM_TIMER)
  176. #include <MMsystem.h>
  177. static UINT timer_id;
  178. static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
  179. #elif defined(HAVE_ALARM)
  180. static void verbose_stats_dump(int sig);
  181. #endif
  182. static void info(int);
  183. static u_int packets_captured;
  184. #ifdef HAVE_PCAP_FINDALLDEVS
  185. static const struct tok status_flags[] = {
  186. #ifdef PCAP_IF_UP
  187. { PCAP_IF_UP, "Up" },
  188. #endif
  189. #ifdef PCAP_IF_RUNNING
  190. { PCAP_IF_RUNNING, "Running" },
  191. #endif
  192. { PCAP_IF_LOOPBACK, "Loopback" },
  193. { 0, NULL }
  194. };
  195. #endif
  196. static pcap_t *pd;
  197. static int supports_monitor_mode;
  198. extern int optind;
  199. extern int opterr;
  200. extern char *optarg;
  201. struct dump_info {
  202. char *WFileName;
  203. char *CurrentFileName;
  204. pcap_t *pd;
  205. pcap_dumper_t *p;
  206. #ifdef HAVE_CAPSICUM
  207. int dirfd;
  208. #endif
  209. };
  210. #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
  211. /*
  212. * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
  213. * by any libpcap header, because it's a special hack, only available if
  214. * libpcap was configured to include it, and only intended for use by
  215. * libpcap developers trying to debug the parser for filter expressions).
  216. */
  217. #ifdef _WIN32
  218. __declspec(dllimport)
  219. #else /* _WIN32 */
  220. extern
  221. #endif /* _WIN32 */
  222. void pcap_set_parser_debug(int);
  223. #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
  224. /*
  225. * We don't have pcap_set_parser_debug() in libpcap, but we do have
  226. * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
  227. * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
  228. */
  229. static void
  230. pcap_set_parser_debug(int value)
  231. {
  232. #ifdef HAVE_PCAP_DEBUG
  233. extern int pcap_debug;
  234. pcap_debug = value;
  235. #else /* HAVE_PCAP_DEBUG */
  236. extern int yydebug;
  237. yydebug = value;
  238. #endif /* HAVE_PCAP_DEBUG */
  239. }
  240. #define HAVE_PCAP_SET_PARSER_DEBUG
  241. #endif
  242. #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
  243. /*
  244. * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
  245. * by any libpcap header, because it's a special hack, only available if
  246. * libpcap was configured to include it, and only intended for use by
  247. * libpcap developers trying to debug the optimizer for filter expressions).
  248. */
  249. #ifdef _WIN32
  250. __declspec(dllimport)
  251. #else /* _WIN32 */
  252. extern
  253. #endif /* _WIN32 */
  254. void pcap_set_optimizer_debug(int);
  255. #endif
  256. /* VARARGS */
  257. static void
  258. error(const char *fmt, ...)
  259. {
  260. va_list ap;
  261. (void)fprintf(stderr, "%s: ", program_name);
  262. va_start(ap, fmt);
  263. (void)vfprintf(stderr, fmt, ap);
  264. va_end(ap);
  265. if (*fmt) {
  266. fmt += strlen(fmt);
  267. if (fmt[-1] != '\n')
  268. (void)fputc('\n', stderr);
  269. }
  270. exit_tcpdump(1);
  271. /* NOTREACHED */
  272. }
  273. /* VARARGS */
  274. static void
  275. warning(const char *fmt, ...)
  276. {
  277. va_list ap;
  278. (void)fprintf(stderr, "%s: WARNING: ", program_name);
  279. va_start(ap, fmt);
  280. (void)vfprintf(stderr, fmt, ap);
  281. va_end(ap);
  282. if (*fmt) {
  283. fmt += strlen(fmt);
  284. if (fmt[-1] != '\n')
  285. (void)fputc('\n', stderr);
  286. }
  287. }
  288. static void
  289. exit_tcpdump(int status)
  290. {
  291. nd_cleanup();
  292. exit(status);
  293. }
  294. #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
  295. static void
  296. show_tstamp_types_and_exit(pcap_t *pc, const char *device)
  297. {
  298. int n_tstamp_types;
  299. int *tstamp_types = 0;
  300. const char *tstamp_type_name;
  301. int i;
  302. n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types);
  303. if (n_tstamp_types < 0)
  304. error("%s", pcap_geterr(pc));
  305. if (n_tstamp_types == 0) {
  306. fprintf(stderr, "Time stamp type cannot be set for %s\n",
  307. device);
  308. exit_tcpdump(0);
  309. }
  310. fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
  311. device);
  312. for (i = 0; i < n_tstamp_types; i++) {
  313. tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
  314. if (tstamp_type_name != NULL) {
  315. (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
  316. pcap_tstamp_type_val_to_description(tstamp_types[i]));
  317. } else {
  318. (void) fprintf(stderr, " %d\n", tstamp_types[i]);
  319. }
  320. }
  321. pcap_free_tstamp_types(tstamp_types);
  322. exit_tcpdump(0);
  323. }
  324. #endif
  325. static void
  326. show_dlts_and_exit(pcap_t *pc, const char *device)
  327. {
  328. int n_dlts, i;
  329. int *dlts = 0;
  330. const char *dlt_name;
  331. n_dlts = pcap_list_datalinks(pc, &dlts);
  332. if (n_dlts < 0)
  333. error("%s", pcap_geterr(pc));
  334. else if (n_dlts == 0 || !dlts)
  335. error("No data link types.");
  336. /*
  337. * If the interface is known to support monitor mode, indicate
  338. * whether these are the data link types available when not in
  339. * monitor mode, if -I wasn't specified, or when in monitor mode,
  340. * when -I was specified (the link-layer types available in
  341. * monitor mode might be different from the ones available when
  342. * not in monitor mode).
  343. */
  344. if (supports_monitor_mode)
  345. (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
  346. device,
  347. Iflag ? "when in monitor mode" : "when not in monitor mode");
  348. else
  349. (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
  350. device);
  351. for (i = 0; i < n_dlts; i++) {
  352. dlt_name = pcap_datalink_val_to_name(dlts[i]);
  353. if (dlt_name != NULL) {
  354. (void) fprintf(stderr, " %s (%s)", dlt_name,
  355. pcap_datalink_val_to_description(dlts[i]));
  356. /*
  357. * OK, does tcpdump handle that type?
  358. */
  359. if (!has_printer(dlts[i]))
  360. (void) fprintf(stderr, " (printing not supported)");
  361. fprintf(stderr, "\n");
  362. } else {
  363. (void) fprintf(stderr, " DLT %d (printing not supported)\n",
  364. dlts[i]);
  365. }
  366. }
  367. #ifdef HAVE_PCAP_FREE_DATALINKS
  368. pcap_free_datalinks(dlts);
  369. #endif
  370. exit_tcpdump(0);
  371. }
  372. #ifdef HAVE_PCAP_FINDALLDEVS
  373. static void
  374. show_devices_and_exit (void)
  375. {
  376. pcap_if_t *dev, *devlist;
  377. char ebuf[PCAP_ERRBUF_SIZE];
  378. int i;
  379. if (pcap_findalldevs(&devlist, ebuf) < 0)
  380. error("%s", ebuf);
  381. for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
  382. printf("%d.%s", i+1, dev->name);
  383. if (dev->description != NULL)
  384. printf(" (%s)", dev->description);
  385. if (dev->flags != 0)
  386. printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
  387. printf("\n");
  388. }
  389. pcap_freealldevs(devlist);
  390. exit_tcpdump(0);
  391. }
  392. #endif /* HAVE_PCAP_FINDALLDEVS */
  393. /*
  394. * Short options.
  395. *
  396. * Note that there we use all letters for short options except for g, k,
  397. * o, and P, and those are used by other versions of tcpdump, and we should
  398. * only use them for the same purposes that the other versions of tcpdump
  399. * use them:
  400. *
  401. * OS X tcpdump uses -g to force non--v output for IP to be on one
  402. * line, making it more "g"repable;
  403. *
  404. * OS X tcpdump uses -k to specify that packet comments in pcap-ng files
  405. * should be printed;
  406. *
  407. * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
  408. * for hosts sending TCP SYN packets;
  409. *
  410. * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
  411. * than pcap files.
  412. *
  413. * OS X tcpdump also uses -Q to specify expressions that match packet
  414. * metadata, including but not limited to the packet direction.
  415. * The expression syntax is different from a simple "in|out|inout",
  416. * and those expressions aren't accepted by OS X tcpdump, but the
  417. * equivalents would be "in" = "dir=in", "out" = "dir=out", and
  418. * "inout" = "dir=in or dir=out", and the parser could conceivably
  419. * special-case "in", "out", and "inout" as expressions for backwards
  420. * compatibility, so all is not (yet) lost.
  421. */
  422. /*
  423. * Set up flags that might or might not be supported depending on the
  424. * version of libpcap we're using.
  425. */
  426. #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
  427. #define B_FLAG "B:"
  428. #define B_FLAG_USAGE " [ -B size ]"
  429. #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
  430. #define B_FLAG
  431. #define B_FLAG_USAGE
  432. #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
  433. #ifdef HAVE_PCAP_CREATE
  434. #define I_FLAG "I"
  435. #else /* HAVE_PCAP_CREATE */
  436. #define I_FLAG
  437. #endif /* HAVE_PCAP_CREATE */
  438. #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
  439. #define j_FLAG "j:"
  440. #define j_FLAG_USAGE " [ -j tstamptype ]"
  441. #define J_FLAG "J"
  442. #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
  443. #define j_FLAG
  444. #define j_FLAG_USAGE
  445. #define J_FLAG
  446. #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
  447. #ifdef HAVE_PCAP_FINDALLDEVS
  448. #define D_FLAG "D"
  449. #else
  450. #define D_FLAG
  451. #endif
  452. #ifdef HAVE_PCAP_DUMP_FLUSH
  453. #define U_FLAG "U"
  454. #else
  455. #define U_FLAG
  456. #endif
  457. #ifdef HAVE_PCAP_SETDIRECTION
  458. #define Q_FLAG "Q:"
  459. #else
  460. #define Q_FLAG
  461. #endif
  462. #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#"
  463. /*
  464. * Long options.
  465. *
  466. * We do not currently have long options corresponding to all short
  467. * options; we should probably pick appropriate option names for them.
  468. *
  469. * However, the short options where the number of times the option is
  470. * specified matters, such as -v and -d and -t, should probably not
  471. * just map to a long option, as saying
  472. *
  473. * tcpdump --verbose --verbose
  474. *
  475. * doesn't make sense; it should be --verbosity={N} or something such
  476. * as that.
  477. *
  478. * For long options with no corresponding short options, we define values
  479. * outside the range of ASCII graphic characters, make that the last
  480. * component of the entry for the long option, and have a case for that
  481. * option in the switch statement.
  482. */
  483. #define OPTION_VERSION 128
  484. #define OPTION_TSTAMP_PRECISION 129
  485. #define OPTION_IMMEDIATE_MODE 130
  486. static const struct option longopts[] = {
  487. #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
  488. { "buffer-size", required_argument, NULL, 'B' },
  489. #endif
  490. { "list-interfaces", no_argument, NULL, 'D' },
  491. { "help", no_argument, NULL, 'h' },
  492. { "interface", required_argument, NULL, 'i' },
  493. #ifdef HAVE_PCAP_CREATE
  494. { "monitor-mode", no_argument, NULL, 'I' },
  495. #endif
  496. #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
  497. { "time-stamp-type", required_argument, NULL, 'j' },
  498. { "list-time-stamp-types", no_argument, NULL, 'J' },
  499. #endif
  500. #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
  501. { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
  502. #endif
  503. { "dont-verify-checksums", no_argument, NULL, 'K' },
  504. { "list-data-link-types", no_argument, NULL, 'L' },
  505. { "no-optimize", no_argument, NULL, 'O' },
  506. { "no-promiscuous-mode", no_argument, NULL, 'p' },
  507. #ifdef HAVE_PCAP_SETDIRECTION
  508. { "direction", required_argument, NULL, 'Q' },
  509. #endif
  510. { "snapshot-length", required_argument, NULL, 's' },
  511. { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
  512. #ifdef HAVE_PCAP_DUMP_FLUSH
  513. { "packet-buffered", no_argument, NULL, 'U' },
  514. #endif
  515. { "linktype", required_argument, NULL, 'y' },
  516. #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
  517. { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
  518. #endif
  519. #ifdef HAVE_PCAP_SET_PARSER_DEBUG
  520. { "debug-filter-parser", no_argument, NULL, 'Y' },
  521. #endif
  522. { "relinquish-privileges", required_argument, NULL, 'Z' },
  523. { "number", no_argument, NULL, '#' },
  524. { "version", no_argument, NULL, OPTION_VERSION },
  525. { NULL, 0, NULL, 0 }
  526. };
  527. #ifndef _WIN32
  528. /* Drop root privileges and chroot if necessary */
  529. static void
  530. droproot(const char *username, const char *chroot_dir)
  531. {
  532. struct passwd *pw = NULL;
  533. if (chroot_dir && !username) {
  534. fprintf(stderr, "%s: Chroot without dropping root is insecure\n",
  535. program_name);
  536. exit_tcpdump(1);
  537. }
  538. pw = getpwnam(username);
  539. if (pw) {
  540. if (chroot_dir) {
  541. if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
  542. fprintf(stderr, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
  543. program_name, chroot_dir, pcap_strerror(errno));
  544. exit_tcpdump(1);
  545. }
  546. }
  547. #ifdef HAVE_LIBCAP_NG
  548. {
  549. int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
  550. if (ret < 0) {
  551. fprintf(stderr, "error : ret %d\n", ret);
  552. } else {
  553. fprintf(stderr, "dropped privs to %s\n", username);
  554. }
  555. }
  556. #else
  557. if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
  558. setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
  559. fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
  560. program_name, username,
  561. (unsigned long)pw->pw_uid,
  562. (unsigned long)pw->pw_gid,
  563. pcap_strerror(errno));
  564. exit_tcpdump(1);
  565. }
  566. else {
  567. fprintf(stderr, "dropped privs to %s\n", username);
  568. }
  569. #endif /* HAVE_LIBCAP_NG */
  570. }
  571. else {
  572. fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
  573. program_name, username);
  574. exit_tcpdump(1);
  575. }
  576. #ifdef HAVE_LIBCAP_NG
  577. /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
  578. capng_updatev(
  579. CAPNG_DROP,
  580. CAPNG_EFFECTIVE | CAPNG_PERMITTED,
  581. CAP_SETUID,
  582. CAP_SETGID,
  583. CAP_SYS_CHROOT,
  584. -1);
  585. capng_apply(CAPNG_SELECT_BOTH);
  586. #endif /* HAVE_LIBCAP_NG */
  587. }
  588. #endif /* _WIN32 */
  589. static int
  590. getWflagChars(int x)
  591. {
  592. int c = 0;
  593. x -= 1;
  594. while (x > 0) {
  595. c += 1;
  596. x /= 10;
  597. }
  598. return c;
  599. }
  600. static void
  601. MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
  602. {
  603. char *filename = malloc(PATH_MAX + 1);
  604. if (filename == NULL)
  605. error("Makefilename: malloc");
  606. /* Process with strftime if Gflag is set. */
  607. if (Gflag != 0) {
  608. struct tm *local_tm;
  609. /* Convert Gflag_time to a usable format */
  610. if ((local_tm = localtime(&Gflag_time)) == NULL) {
  611. error("MakeTimedFilename: localtime");
  612. }
  613. /* There's no good way to detect an error in strftime since a return
  614. * value of 0 isn't necessarily failure.
  615. */
  616. strftime(filename, PATH_MAX, orig_name, local_tm);
  617. } else {
  618. strncpy(filename, orig_name, PATH_MAX);
  619. }
  620. if (cnt == 0 && max_chars == 0)
  621. strncpy(buffer, filename, PATH_MAX + 1);
  622. else
  623. if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
  624. /* Report an error if the filename is too large */
  625. error("too many output files or filename is too long (> %d)", PATH_MAX);
  626. free(filename);
  627. }
  628. static char *
  629. get_next_file(FILE *VFile, char *ptr)
  630. {
  631. char *ret;
  632. ret = fgets(ptr, PATH_MAX, VFile);
  633. if (!ret)
  634. return NULL;
  635. if (ptr[strlen(ptr) - 1] == '\n')
  636. ptr[strlen(ptr) - 1] = '\0';
  637. return ret;
  638. }
  639. #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
  640. static int
  641. tstamp_precision_from_string(const char *precision)
  642. {
  643. if (strncmp(precision, "nano", strlen("nano")) == 0)
  644. return PCAP_TSTAMP_PRECISION_NANO;
  645. if (strncmp(precision, "micro", strlen("micro")) == 0)
  646. return PCAP_TSTAMP_PRECISION_MICRO;
  647. return -EINVAL;
  648. }
  649. static const char *
  650. tstamp_precision_to_string(int precision)
  651. {
  652. switch (precision) {
  653. case PCAP_TSTAMP_PRECISION_MICRO:
  654. return "micro";
  655. case PCAP_TSTAMP_PRECISION_NANO:
  656. return "nano";
  657. default:
  658. return "unknown";
  659. }
  660. }
  661. #endif
  662. #ifdef HAVE_CAPSICUM
  663. /*
  664. * Ensure that, on a dump file's descriptor, we have all the rights
  665. * necessary to make the standard I/O library work with an fdopen()ed
  666. * FILE * from that descriptor.
  667. *
  668. * A long time ago, in a galaxy far far away, AT&T decided that, instead
  669. * of providing separate APIs for getting and setting the FD_ flags on a
  670. * descriptor, getting and setting the O_ flags on a descriptor, and
  671. * locking files, they'd throw them all into a kitchen-sink fcntl() call
  672. * along the lines of ioctl(), the fact that ioctl() operations are
  673. * largely specific to particular character devices but fcntl() operations
  674. * are either generic to all descriptors or generic to all descriptors for
  675. * regular files nonwithstanding.
  676. *
  677. * The Capsicum people decided that fine-grained control of descriptor
  678. * operations was required, so that you need to grant permission for
  679. * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
  680. * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
  681. * collection of things, so there are *individual* fcntls for which
  682. * permission needs to be granted.
  683. *
  684. * The FreeBSD standard I/O people implemented some optimizations that
  685. * requires that the standard I/O routines be able to determine whether
  686. * the descriptor for the FILE * is open append-only or not; as that
  687. * descriptor could have come from an open() rather than an fopen(),
  688. * that requires that it be able to do an F_GETFL fcntl() to read
  689. * the O_ flags.
  690. *
  691. * Tcpdump uses ftell() to determine how much data has been written
  692. * to a file in order to, when used with -C, determine when it's time
  693. * to rotate capture files. ftell() therefore needs to do an lseek()
  694. * to find out the file offset and must, thanks to the aforementioned
  695. * optimization, also know whether the descriptor is open append-only
  696. * or not.
  697. *
  698. * The net result of all the above is that we need to grant CAP_SEEK,
  699. * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
  700. *
  701. * Perhaps this is the universe's way of saying that either
  702. *
  703. * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
  704. * using it, so that Capsicum-capable tcpdump wouldn't need to do
  705. * an fdopen()
  706. *
  707. * or
  708. *
  709. * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
  710. * I/O library that knows what rights are needed by the standard
  711. * I/O library, based on the open mode, and assigns them, perhaps
  712. * with an additional argument indicating, for example, whether
  713. * seeking should be allowed, so that tcpdump doesn't need to know
  714. * what the standard I/O library happens to require this week.
  715. */
  716. static void
  717. set_dumper_capsicum_rights(pcap_dumper_t *p)
  718. {
  719. int fd = fileno(pcap_dump_file(p));
  720. cap_rights_t rights;
  721. cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
  722. if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
  723. error("unable to limit dump descriptor");
  724. }
  725. if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
  726. error("unable to limit dump descriptor fcntls");
  727. }
  728. }
  729. #endif
  730. /*
  731. * Copy arg vector into a new buffer, concatenating arguments with spaces.
  732. */
  733. static char *
  734. copy_argv(register char **argv)
  735. {
  736. register char **p;
  737. register u_int len = 0;
  738. char *buf;
  739. char *src, *dst;
  740. p = argv;
  741. if (*p == NULL)
  742. return 0;
  743. while (*p)
  744. len += strlen(*p++) + 1;
  745. buf = (char *)malloc(len);
  746. if (buf == NULL)
  747. error("copy_argv: malloc");
  748. p = argv;
  749. dst = buf;
  750. while ((src = *p++) != NULL) {
  751. while ((*dst++ = *src++) != '\0')
  752. ;
  753. dst[-1] = ' ';
  754. }
  755. dst[-1] = '\0';
  756. return buf;
  757. }
  758. /*
  759. * On Windows, we need to open the file in binary mode, so that
  760. * we get all the bytes specified by the size we get from "fstat()".
  761. * On UNIX, that's not necessary. O_BINARY is defined on Windows;
  762. * we define it as 0 if it's not defined, so it does nothing.
  763. */
  764. #ifndef O_BINARY
  765. #define O_BINARY 0
  766. #endif
  767. static char *
  768. read_infile(char *fname)
  769. {
  770. register int i, fd, cc;
  771. register char *cp;
  772. struct stat buf;
  773. fd = open(fname, O_RDONLY|O_BINARY);
  774. if (fd < 0)
  775. error("can't open %s: %s", fname, pcap_strerror(errno));
  776. if (fstat(fd, &buf) < 0)
  777. error("can't stat %s: %s", fname, pcap_strerror(errno));
  778. cp = malloc((u_int)buf.st_size + 1);
  779. if (cp == NULL)
  780. error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
  781. fname, pcap_strerror(errno));
  782. cc = read(fd, cp, (u_int)buf.st_size);
  783. if (cc < 0)
  784. error("read %s: %s", fname, pcap_strerror(errno));
  785. if (cc != buf.st_size)
  786. error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
  787. close(fd);
  788. /* replace "# comment" with spaces */
  789. for (i = 0; i < cc; i++) {
  790. if (cp[i] == '#')
  791. while (i < cc && cp[i] != '\n')
  792. cp[i++] = ' ';
  793. }
  794. cp[cc] = '\0';
  795. return (cp);
  796. }
  797. #ifdef HAVE_PCAP_FINDALLDEVS
  798. static long
  799. parse_interface_number(const char *device)
  800. {
  801. long devnum;
  802. char *end;
  803. devnum = strtol(device, &end, 10);
  804. if (device != end && *end == '\0') {
  805. /*
  806. * It's all-numeric, but is it a valid number?
  807. */
  808. if (devnum <= 0) {
  809. /*
  810. * No, it's not an ordinal.
  811. */
  812. error("Invalid adapter index");
  813. }
  814. return (devnum);
  815. } else {
  816. /*
  817. * It's not all-numeric; return -1, so our caller
  818. * knows that.
  819. */
  820. return (-1);
  821. }
  822. }
  823. static char *
  824. find_interface_by_number(long devnum)
  825. {
  826. pcap_if_t *dev, *devlist;
  827. long i;
  828. char ebuf[PCAP_ERRBUF_SIZE];
  829. char *device;
  830. if (pcap_findalldevs(&devlist, ebuf) < 0)
  831. error("%s", ebuf);
  832. /*
  833. * Look for the devnum-th entry in the list of devices (1-based).
  834. */
  835. for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
  836. i++, dev = dev->next)
  837. ;
  838. if (dev == NULL)
  839. error("Invalid adapter index");
  840. device = strdup(dev->name);
  841. pcap_freealldevs(devlist);
  842. return (device);
  843. }
  844. #endif
  845. static pcap_t *
  846. open_interface(const char *device, netdissect_options *ndo, char *ebuf)
  847. {
  848. pcap_t *pc;
  849. #ifdef HAVE_PCAP_CREATE
  850. int status;
  851. char *cp;
  852. #endif
  853. #ifdef HAVE_PCAP_CREATE
  854. pc = pcap_create(device, ebuf);
  855. if (pc == NULL) {
  856. /*
  857. * If this failed with "No such device", that means
  858. * the interface doesn't exist; return NULL, so that
  859. * the caller can see whether the device name is
  860. * actually an interface index.
  861. */
  862. if (strstr(ebuf, "No such device") != NULL)
  863. return (NULL);
  864. error("%s", ebuf);
  865. }
  866. #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
  867. if (Jflag)
  868. show_tstamp_types_and_exit(pc, device);
  869. #endif
  870. #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
  871. status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
  872. if (status != 0)
  873. error("%s: Can't set %ssecond time stamp precision: %s",
  874. device,
  875. tstamp_precision_to_string(ndo->ndo_tstamp_precision),
  876. pcap_statustostr(status));
  877. #endif
  878. #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
  879. if (immediate_mode) {
  880. status = pcap_set_immediate_mode(pc, 1);
  881. if (status != 0)
  882. error("%s: Can't set immediate mode: %s",
  883. device,
  884. pcap_statustostr(status));
  885. }
  886. #endif
  887. /*
  888. * Is this an interface that supports monitor mode?
  889. */
  890. if (pcap_can_set_rfmon(pc) == 1)
  891. supports_monitor_mode = 1;
  892. else
  893. supports_monitor_mode = 0;
  894. status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
  895. if (status != 0)
  896. error("%s: Can't set snapshot length: %s",
  897. device, pcap_statustostr(status));
  898. status = pcap_set_promisc(pc, !pflag);
  899. if (status != 0)
  900. error("%s: Can't set promiscuous mode: %s",
  901. device, pcap_statustostr(status));
  902. if (Iflag) {
  903. status = pcap_set_rfmon(pc, 1);
  904. if (status != 0)
  905. error("%s: Can't set monitor mode: %s",
  906. device, pcap_statustostr(status));
  907. }
  908. status = pcap_set_timeout(pc, 1000);
  909. if (status != 0)
  910. error("%s: pcap_set_timeout failed: %s",
  911. device, pcap_statustostr(status));
  912. if (Bflag != 0) {
  913. status = pcap_set_buffer_size(pc, Bflag);
  914. if (status != 0)
  915. error("%s: Can't set buffer size: %s",
  916. device, pcap_statustostr(status));
  917. }
  918. #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
  919. if (jflag != -1) {
  920. status = pcap_set_tstamp_type(pc, jflag);
  921. if (status < 0)
  922. error("%s: Can't set time stamp type: %s",
  923. device, pcap_statustostr(status));
  924. }
  925. #endif
  926. status = pcap_activate(pc);
  927. if (status < 0) {
  928. /*
  929. * pcap_activate() failed.
  930. */
  931. cp = pcap_geterr(pc);
  932. if (status == PCAP_ERROR)
  933. error("%s", cp);
  934. else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
  935. /*
  936. * Return an error for our caller to handle.
  937. */
  938. snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
  939. device, pcap_statustostr(status), cp);
  940. pcap_close(pc);
  941. return (NULL);
  942. } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
  943. error("%s: %s\n(%s)", device,
  944. pcap_statustostr(status), cp);
  945. else
  946. error("%s: %s", device,
  947. pcap_statustostr(status));
  948. } else if (status > 0) {
  949. /*
  950. * pcap_activate() succeeded, but it's warning us
  951. * of a problem it had.
  952. */
  953. cp = pcap_geterr(pc);
  954. if (status == PCAP_WARNING)
  955. warning("%s", cp);
  956. else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
  957. *cp != '\0')
  958. warning("%s: %s\n(%s)", device,
  959. pcap_statustostr(status), cp);
  960. else
  961. warning("%s: %s", device,
  962. pcap_statustostr(status));
  963. }
  964. #ifdef HAVE_PCAP_SETDIRECTION
  965. if (Qflag != -1) {
  966. status = pcap_setdirection(pc, Qflag);
  967. if (status != 0)
  968. error("%s: pcap_setdirection() failed: %s",
  969. device, pcap_geterr(pc));
  970. }
  971. #endif /* HAVE_PCAP_SETDIRECTION */
  972. #else /* HAVE_PCAP_CREATE */
  973. *ebuf = '\0';
  974. pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000, ebuf);
  975. if (pc == NULL) {
  976. /*
  977. * If this failed with "No such device", that means
  978. * the interface doesn't exist; return NULL, so that
  979. * the caller can see whether the device name is
  980. * actually an interface index.
  981. */
  982. if (strstr(ebuf, "No such device") != NULL)
  983. return (NULL);
  984. error("%s", ebuf);
  985. }
  986. if (*ebuf)
  987. warning("%s", ebuf);
  988. #endif /* HAVE_PCAP_CREATE */
  989. return (pc);
  990. }
  991. int
  992. main(int argc, char **argv)
  993. {
  994. register int cnt, op, i;
  995. bpf_u_int32 localnet =0 , netmask = 0;
  996. int timezone_offset = 0;
  997. register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
  998. pcap_handler callback;
  999. int dlt;
  1000. const char *dlt_name;
  1001. struct bpf_program fcode;
  1002. #ifndef _WIN32
  1003. RETSIGTYPE (*oldhandler)(int);
  1004. #endif
  1005. struct dump_info dumpinfo;
  1006. u_char *pcap_userdata;
  1007. char ebuf[PCAP_ERRBUF_SIZE];
  1008. char VFileLine[PATH_MAX + 1];
  1009. char *username = NULL;
  1010. char *chroot_dir = NULL;
  1011. char *ret = NULL;
  1012. char *end;
  1013. #ifdef HAVE_PCAP_FINDALLDEVS
  1014. pcap_if_t *devlist;
  1015. long devnum;
  1016. #endif
  1017. int status;
  1018. FILE *VFile;
  1019. #ifdef HAVE_CAPSICUM
  1020. cap_rights_t rights;
  1021. int cansandbox;
  1022. #endif /* HAVE_CAPSICUM */
  1023. int Oflag = 1; /* run filter code optimizer */
  1024. int yflag_dlt = -1;
  1025. const char *yflag_dlt_name = NULL;
  1026. netdissect_options Ndo;
  1027. netdissect_options *ndo = &Ndo;
  1028. /*
  1029. * Initialize the netdissect code.
  1030. */
  1031. if (nd_init(ebuf, sizeof ebuf) == -1)
  1032. error("%s", ebuf);
  1033. memset(ndo, 0, sizeof(*ndo));
  1034. ndo_set_function_pointers(ndo);
  1035. ndo->ndo_snaplen = DEFAULT_SNAPLEN;
  1036. cnt = -1;
  1037. device = NULL;
  1038. infile = NULL;
  1039. RFileName = NULL;
  1040. VFileName = NULL;
  1041. VFile = NULL;
  1042. WFileName = NULL;
  1043. dlt = -1;
  1044. if ((cp = strrchr(argv[0], '/')) != NULL)
  1045. ndo->program_name = program_name = cp + 1;
  1046. else
  1047. ndo->program_name = program_name = argv[0];
  1048. #ifdef _WIN32
  1049. if (pcap_wsockinit() != 0)
  1050. error("Attempting to initialize Winsock failed");
  1051. #endif /* _WIN32 */
  1052. /*
  1053. * On platforms where the CPU doesn't support unaligned loads,
  1054. * force unaligned accesses to abort with SIGBUS, rather than
  1055. * being fixed up (slowly) by the OS kernel; on those platforms,
  1056. * misaligned accesses are bugs, and we want tcpdump to crash so
  1057. * that the bugs are reported.
  1058. */
  1059. if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
  1060. error("%s", ebuf);
  1061. while (
  1062. (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
  1063. switch (op) {
  1064. case 'a':
  1065. /* compatibility for old -a */
  1066. break;
  1067. case 'A':
  1068. ++ndo->ndo_Aflag;
  1069. break;
  1070. case 'b':
  1071. ++ndo->ndo_bflag;
  1072. break;
  1073. #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
  1074. case 'B':
  1075. Bflag = atoi(optarg)*1024;
  1076. if (Bflag <= 0)
  1077. error("invalid packet buffer size %s", optarg);
  1078. break;
  1079. #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
  1080. case 'c':
  1081. cnt = atoi(optarg);
  1082. if (cnt <= 0)
  1083. error("invalid packet count %s", optarg);
  1084. break;
  1085. case 'C':
  1086. Cflag = atoi(optarg) * 1000000;
  1087. if (Cflag <= 0)
  1088. error("invalid file size %s", optarg);
  1089. break;
  1090. case 'd':
  1091. ++dflag;
  1092. break;
  1093. case 'D':
  1094. Dflag++;
  1095. break;
  1096. case 'L':
  1097. Lflag++;
  1098. break;
  1099. case 'e':
  1100. ++ndo->ndo_eflag;
  1101. break;
  1102. case 'E':
  1103. #ifndef HAVE_LIBCRYPTO
  1104. warning("crypto code not compiled in");
  1105. #endif
  1106. ndo->ndo_espsecret = optarg;
  1107. break;
  1108. case 'f':
  1109. ++ndo->ndo_fflag;
  1110. break;
  1111. case 'F':
  1112. infile = optarg;
  1113. break;
  1114. case 'G':
  1115. Gflag = atoi(optarg);
  1116. if (Gflag < 0)
  1117. error("invalid number of seconds %s", optarg);
  1118. /* We will create one file initially. */
  1119. Gflag_count = 0;
  1120. /* Grab the current time for rotation use. */
  1121. if ((Gflag_time = time(NULL)) == (time_t)-1) {
  1122. error("main: can't get current time: %s",
  1123. pcap_strerror(errno));
  1124. }
  1125. break;
  1126. case 'h':
  1127. print_usage();
  1128. exit_tcpdump(0);
  1129. break;
  1130. case 'H':
  1131. ++ndo->ndo_Hflag;
  1132. break;
  1133. case 'i':
  1134. device = optarg;
  1135. break;
  1136. #ifdef HAVE_PCAP_CREATE
  1137. case 'I':
  1138. ++Iflag;
  1139. break;
  1140. #endif /* HAVE_PCAP_CREATE */
  1141. #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
  1142. case 'j':
  1143. jflag = pcap_tstamp_type_name_to_val(optarg);
  1144. if (jflag < 0)
  1145. error("invalid time stamp type %s", optarg);
  1146. break;
  1147. case 'J':
  1148. Jflag++;
  1149. break;
  1150. #endif
  1151. case 'l':
  1152. #ifdef _WIN32
  1153. /*
  1154. * _IOLBF is the same as _IOFBF in Microsoft's C
  1155. * libraries; the only alternative they offer
  1156. * is _IONBF.
  1157. *
  1158. * XXX - this should really be checking for MSVC++,
  1159. * not _WIN32, if, for example, MinGW has its own
  1160. * C library that is more UNIX-compatible.
  1161. */
  1162. setvbuf(stdout, NULL, _IONBF, 0);
  1163. #else /* _WIN32 */
  1164. #ifdef HAVE_SETLINEBUF
  1165. setlinebuf(stdout);
  1166. #else
  1167. setvbuf(stdout, NULL, _IOLBF, 0);
  1168. #endif
  1169. #endif /* _WIN32 */
  1170. break;
  1171. case 'K':
  1172. ++ndo->ndo_Kflag;
  1173. break;
  1174. case 'm':
  1175. if (nd_have_smi_support()) {
  1176. if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1)
  1177. error("%s", ebuf);
  1178. } else {
  1179. (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
  1180. program_name, optarg);
  1181. (void)fprintf(stderr, "(no libsmi support)\n");
  1182. }
  1183. break;
  1184. case 'M':
  1185. /* TCP-MD5 shared secret */
  1186. #ifndef HAVE_LIBCRYPTO
  1187. warning("crypto code not compiled in");
  1188. #endif
  1189. ndo->ndo_sigsecret = optarg;
  1190. break;
  1191. case 'n':
  1192. ++ndo->ndo_nflag;
  1193. break;
  1194. case 'N':
  1195. ++ndo->ndo_Nflag;
  1196. break;
  1197. case 'O':
  1198. Oflag = 0;
  1199. break;
  1200. case 'p':
  1201. ++pflag;
  1202. break;
  1203. case 'q':
  1204. ++ndo->ndo_qflag;
  1205. ++ndo->ndo_suppress_default_print;
  1206. break;
  1207. #ifdef HAVE_PCAP_SETDIRECTION
  1208. case 'Q':
  1209. if (ascii_strcasecmp(optarg, "in") == 0)
  1210. Qflag = PCAP_D_IN;
  1211. else if (ascii_strcasecmp(optarg, "out") == 0)
  1212. Qflag = PCAP_D_OUT;
  1213. else if (ascii_strcasecmp(optarg, "inout") == 0)
  1214. Qflag = PCAP_D_INOUT;
  1215. else
  1216. error("unknown capture direction `%s'", optarg);
  1217. break;
  1218. #endif /* HAVE_PCAP_SETDIRECTION */
  1219. case 'r':
  1220. RFileName = optarg;
  1221. break;
  1222. case 's':
  1223. ndo->ndo_snaplen = strtol(optarg, &end, 0);
  1224. if (optarg == end || *end != '\0'
  1225. || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
  1226. error("invalid snaplen %s", optarg);
  1227. else if (ndo->ndo_snaplen == 0)
  1228. ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
  1229. break;
  1230. case 'S':
  1231. ++ndo->ndo_Sflag;
  1232. break;
  1233. case 't':
  1234. ++ndo->ndo_tflag;
  1235. break;
  1236. case 'T':
  1237. if (ascii_strcasecmp(optarg, "vat") == 0)
  1238. ndo->ndo_packettype = PT_VAT;
  1239. else if (ascii_strcasecmp(optarg, "wb") == 0)
  1240. ndo->ndo_packettype = PT_WB;
  1241. else if (ascii_strcasecmp(optarg, "rpc") == 0)
  1242. ndo->ndo_packettype = PT_RPC;
  1243. else if (ascii_strcasecmp(optarg, "rtp") == 0)
  1244. ndo->ndo_packettype = PT_RTP;
  1245. else if (ascii_strcasecmp(optarg, "rtcp") == 0)
  1246. ndo->ndo_packettype = PT_RTCP;
  1247. else if (ascii_strcasecmp(optarg, "snmp") == 0)
  1248. ndo->ndo_packettype = PT_SNMP;
  1249. else if (ascii_strcasecmp(optarg, "cnfp") == 0)
  1250. ndo->ndo_packettype = PT_CNFP;
  1251. else if (ascii_strcasecmp(optarg, "tftp") == 0)
  1252. ndo->ndo_packettype = PT_TFTP;
  1253. else if (ascii_strcasecmp(optarg, "aodv") == 0)
  1254. ndo->ndo_packettype = PT_AODV;
  1255. else if (ascii_strcasecmp(optarg, "carp") == 0)
  1256. ndo->ndo_packettype = PT_CARP;
  1257. else if (ascii_strcasecmp(optarg, "radius") == 0)
  1258. ndo->ndo_packettype = PT_RADIUS;
  1259. else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
  1260. ndo->ndo_packettype = PT_ZMTP1;
  1261. else if (ascii_strcasecmp(optarg, "vxlan") == 0)
  1262. ndo->ndo_packettype = PT_VXLAN;
  1263. else if (ascii_strcasecmp(optarg, "pgm") == 0)
  1264. ndo->ndo_packettype = PT_PGM;
  1265. else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
  1266. ndo->ndo_packettype = PT_PGM_ZMTP1;
  1267. else if (ascii_strcasecmp(optarg, "lmp") == 0)
  1268. ndo->ndo_packettype = PT_LMP;
  1269. else if (ascii_strcasecmp(optarg, "resp") == 0)
  1270. ndo->ndo_packettype = PT_RESP;
  1271. else
  1272. error("unknown packet type `%s'", optarg);
  1273. break;
  1274. case 'u':
  1275. ++ndo->ndo_uflag;
  1276. break;
  1277. #ifdef HAVE_PCAP_DUMP_FLUSH
  1278. case 'U':
  1279. ++Uflag;
  1280. break;
  1281. #endif
  1282. case 'v':
  1283. ++ndo->ndo_vflag;
  1284. break;
  1285. case 'V':
  1286. VFileName = optarg;
  1287. break;
  1288. case 'w':
  1289. WFileName = optarg;
  1290. break;
  1291. case 'W':
  1292. Wflag = atoi(optarg);
  1293. if (Wflag <= 0)
  1294. error("invalid number of output files %s", optarg);
  1295. WflagChars = getWflagChars(Wflag);
  1296. break;
  1297. case 'x':
  1298. ++ndo->ndo_xflag;
  1299. ++ndo->ndo_suppress_default_print;
  1300. break;
  1301. case 'X':
  1302. ++ndo->ndo_Xflag;
  1303. ++ndo->ndo_suppress_default_print;
  1304. break;
  1305. case 'y':
  1306. yflag_dlt_name = optarg;
  1307. yflag_dlt =
  1308. pcap_datalink_name_to_val(yflag_dlt_name);
  1309. if (yflag_dlt < 0)
  1310. error("invalid data link type %s", yflag_dlt_name);
  1311. break;
  1312. #ifdef HAVE_PCAP_SET_PARSER_DEBUG
  1313. case 'Y':
  1314. {
  1315. /* Undocumented flag */
  1316. pcap_set_parser_debug(1);
  1317. }
  1318. break;
  1319. #endif
  1320. case 'z':
  1321. zflag = optarg;
  1322. break;
  1323. case 'Z':
  1324. username = optarg;
  1325. break;
  1326. case '#':
  1327. ndo->ndo_packet_number = 1;
  1328. break;
  1329. case OPTION_VERSION:
  1330. print_version();
  1331. exit_tcpdump(0);
  1332. break;
  1333. #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
  1334. case OPTION_TSTAMP_PRECISION:
  1335. ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
  1336. if (ndo->ndo_tstamp_precision < 0)
  1337. error("unsupported time stamp precision");
  1338. break;
  1339. #endif
  1340. #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
  1341. case OPTION_IMMEDIATE_MODE:
  1342. immediate_mode = 1;
  1343. break;
  1344. #endif
  1345. default:
  1346. print_usage();
  1347. exit_tcpdump(1);
  1348. /* NOTREACHED */
  1349. }
  1350. #ifdef HAVE_PCAP_FINDALLDEVS
  1351. if (Dflag)
  1352. show_devices_and_exit();
  1353. #endif
  1354. switch (ndo->ndo_tflag) {
  1355. case 0: /* Default */
  1356. case 4: /* Default + Date*/
  1357. timezone_offset = gmt2local(0);
  1358. break;
  1359. case 1: /* No time stamp */
  1360. case 2: /* Unix timeval style */
  1361. case 3: /* Microseconds since previous packet */
  1362. case 5: /* Microseconds since first packet */
  1363. break;
  1364. default: /* Not supported */
  1365. error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
  1366. break;
  1367. }
  1368. if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
  1369. error("-f can not be used with -V or -r");
  1370. if (VFileName != NULL && RFileName != NULL)
  1371. error("-V and -r are mutually exclusive.");
  1372. #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
  1373. /*
  1374. * If we're printing dissected packets to the standard output
  1375. * rather than saving raw packets to a file, and the standard
  1376. * output is a terminal, use immediate mode, as the user's
  1377. * probably expecting to see packets pop up immediately.
  1378. */
  1379. if (WFileName == NULL && isatty(1))
  1380. immediate_mode = 1;
  1381. #endif
  1382. #ifdef WITH_CHROOT
  1383. /* if run as root, prepare for chrooting */
  1384. if (getuid() == 0 || geteuid() == 0) {
  1385. /* future extensibility for cmd-line arguments */
  1386. if (!chroot_dir)
  1387. chroot_dir = WITH_CHROOT;
  1388. }
  1389. #endif
  1390. #ifdef WITH_USER
  1391. /* if run as root, prepare for dropping root privileges */
  1392. if (getuid() == 0 || geteuid() == 0) {
  1393. /* Run with '-Z root' to restore old behaviour */
  1394. if (!username)
  1395. username = WITH_USER;
  1396. }
  1397. #endif
  1398. if (RFileName != NULL || VFileName != NULL) {
  1399. /*
  1400. * If RFileName is non-null, it's the pathname of a
  1401. * savefile to read. If VFileName is non-null, it's
  1402. * the pathname of a file containing a list of pathnames
  1403. * (one per line) of savefiles to read.
  1404. *
  1405. * In either case, we're reading a savefile, not doing
  1406. * a live capture.
  1407. */
  1408. #ifndef _WIN32
  1409. /*
  1410. * We don't need network access, so relinquish any set-UID
  1411. * or set-GID privileges we have (if any).
  1412. *
  1413. * We do *not* want set-UID privileges when opening a
  1414. * trace file, as that might let the user read other
  1415. * people's trace files (especially if we're set-UID
  1416. * root).
  1417. */
  1418. if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
  1419. fprintf(stderr, "Warning: setgid/setuid failed !\n");
  1420. #endif /* _WIN32 */
  1421. if (VFileName != NULL) {
  1422. if (VFileName[0] == '-' && VFileName[1] == '\0')
  1423. VFile = stdin;
  1424. else
  1425. VFile = fopen(VFileName, "r");
  1426. if (VFile == NULL)
  1427. error("Unable to open file: %s\n", pcap_strerror(errno));
  1428. ret = get_next_file(VFile, VFileLine);
  1429. if (!ret)
  1430. error("Nothing in %s\n", VFileName);
  1431. RFileName = VFileLine;
  1432. }
  1433. #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
  1434. pd = pcap_open_offline_with_tstamp_precision(RFileName,
  1435. ndo->ndo_tstamp_precision, ebuf);
  1436. #else
  1437. pd = pcap_open_offline(RFileName, ebuf);
  1438. #endif
  1439. if (pd == NULL)
  1440. error("%s", ebuf);
  1441. #ifdef HAVE_CAPSICUM
  1442. cap_rights_init(&rights, CAP_READ);
  1443. if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
  1444. errno != ENOSYS) {
  1445. error("unable to limit pcap descriptor");
  1446. }
  1447. #endif
  1448. dlt = pcap_datalink(pd);
  1449. dlt_name = pcap_datalink_val_to_name(dlt);
  1450. if (dlt_name == NULL) {
  1451. fprintf(stderr, "reading from file %s, link-type %u\n",
  1452. RFileName, dlt);
  1453. } else {
  1454. fprintf(stderr,
  1455. "reading from file %s, link-type %s (%s)\n",
  1456. RFileName, dlt_name,
  1457. pcap_datalink_val_to_description(dlt));
  1458. }
  1459. } else {
  1460. /*
  1461. * We're doing a live capture.
  1462. */
  1463. if (device == NULL) {
  1464. /*
  1465. * No interface was specified. Pick one.
  1466. */
  1467. #ifdef HAVE_PCAP_FINDALLDEVS
  1468. /*
  1469. * Find the list of interfaces, and pick
  1470. * the first interface.
  1471. */
  1472. if (pcap_findalldevs(&devlist, ebuf) >= 0 &&
  1473. devlist != NULL) {
  1474. device = strdup(devlist->name);
  1475. pcap_freealldevs(devlist);
  1476. }
  1477. #else /* HAVE_PCAP_FINDALLDEVS */
  1478. /*
  1479. * Use whatever interface pcap_lookupdev()
  1480. * chooses.
  1481. */
  1482. device = pcap_lookupdev(ebuf);
  1483. #endif
  1484. if (device == NULL)
  1485. error("%s", ebuf);
  1486. }
  1487. /*
  1488. * Try to open the interface with the specified name.
  1489. */
  1490. pd = open_interface(device, ndo, ebuf);
  1491. if (pd == NULL) {
  1492. /*
  1493. * That failed. If we can get a list of
  1494. * interfaces, and the interface name
  1495. * is purely numeric, try to use it as
  1496. * a 1-based index in the list of
  1497. * interfaces.
  1498. */
  1499. #ifdef HAVE_PCAP_FINDALLDEVS
  1500. devnum = parse_interface_number(device);
  1501. if (devnum == -1) {
  1502. /*
  1503. * It's not a number; just report
  1504. * the open error and fail.
  1505. */
  1506. error("%s", ebuf);
  1507. }
  1508. /*
  1509. * OK, it's a number; try to find the
  1510. * interface with that index, and try
  1511. * to open it.
  1512. *
  1513. * find_interface_by_number() exits if it
  1514. * couldn't be found.
  1515. */
  1516. device = find_interface_by_number(devnum);
  1517. pd = open_interface(device, ndo, ebuf);
  1518. if (pd == NULL)
  1519. error("%s", ebuf);
  1520. #else /* HAVE_PCAP_FINDALLDEVS */
  1521. /*
  1522. * We can't get a list of interfaces; just
  1523. * fail.
  1524. */
  1525. error("%s", ebuf);
  1526. #endif /* HAVE_PCAP_FINDALLDEVS */
  1527. }
  1528. /*
  1529. * Let user own process after socket has been opened.
  1530. */
  1531. #ifndef _WIN32
  1532. if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
  1533. fprintf(stderr, "Warning: setgid/setuid failed !\n");
  1534. #endif /* _WIN32 */
  1535. #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
  1536. if(Bflag != 0)
  1537. if(pcap_setbuff(pd, Bflag)==-1){
  1538. error("%s", pcap_geterr(pd));
  1539. }
  1540. #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
  1541. if (Lflag)
  1542. show_dlts_and_exit(pd, device);
  1543. if (yflag_dlt >= 0) {
  1544. #ifdef HAVE_PCAP_SET_DATALINK
  1545. if (pcap_set_datalink(pd, yflag_dlt) < 0)
  1546. error("%s", pcap_geterr(pd));
  1547. #else
  1548. /*
  1549. * We don't actually support changing the
  1550. * data link type, so we only let them
  1551. * set it to what it already is.
  1552. */
  1553. if (yflag_dlt != pcap_datalink(pd)) {
  1554. error("%s is not one of the DLTs supported by this device\n",
  1555. yflag_dlt_name);
  1556. }
  1557. #endif
  1558. (void)fprintf(stderr, "%s: data link type %s\n",
  1559. program_name, yflag_dlt_name);
  1560. (void)fflush(stderr);
  1561. }
  1562. i = pcap_snapshot(pd);
  1563. if (ndo->ndo_snaplen < i) {
  1564. warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
  1565. ndo->ndo_snaplen = i;
  1566. }
  1567. if(ndo->ndo_fflag != 0) {
  1568. if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
  1569. warning("foreign (-f) flag used but: %s", ebuf);
  1570. }
  1571. }
  1572. }
  1573. if (infile)
  1574. cmdbuf = read_infile(infile);
  1575. else
  1576. cmdbuf = copy_argv(&argv[optind]);
  1577. #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
  1578. pcap_set_optimizer_debug(dflag);
  1579. #endif
  1580. if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
  1581. error("%s", pcap_geterr(pd));
  1582. if (dflag) {
  1583. bpf_dump(&fcode, dflag);
  1584. pcap_close(pd);
  1585. free(cmdbuf);
  1586. pcap_freecode(&fcode);
  1587. exit_tcpdump(0);
  1588. }
  1589. init_print(ndo, localnet, netmask, timezone_offset);
  1590. #ifndef _WIN32
  1591. (void)setsignal(SIGPIPE, cleanup);
  1592. (void)setsignal(SIGTERM, cleanup);
  1593. (void)setsignal(SIGINT, cleanup);
  1594. #endif /* _WIN32 */
  1595. #if defined(HAVE_FORK) || defined(HAVE_VFORK)
  1596. (void)setsignal(SIGCHLD, child_cleanup);
  1597. #endif
  1598. /* Cooperate with nohup(1) */
  1599. #ifndef _WIN32
  1600. if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
  1601. (void)setsignal(SIGHUP, oldhandler);
  1602. #endif /* _WIN32 */
  1603. #ifndef _WIN32
  1604. /*
  1605. * If a user name was specified with "-Z", attempt to switch to
  1606. * that user's UID. This would probably be used with sudo,
  1607. * to allow tcpdump to be run in a special restricted
  1608. * account (if you just want to allow users to open capture
  1609. * devices, and can't just give users that permission,
  1610. * you'd make tcpdump set-UID or set-GID).
  1611. *
  1612. * Tcpdump doesn't necessarily write only to one savefile;
  1613. * the general only way to allow a -Z instance to write to
  1614. * savefiles as the user under whose UID it's run, rather
  1615. * than as the user specified with -Z, would thus be to switch
  1616. * to the original user ID before opening a capture file and
  1617. * then switch back to the -Z user ID after opening the savefile.
  1618. * Switching to the -Z user ID only after opening the first
  1619. * savefile doesn't handle the general case.
  1620. */
  1621. if (getuid() == 0 || geteuid() == 0) {
  1622. #ifdef HAVE_LIBCAP_NG
  1623. /* Initialize capng */
  1624. capng_clear(CAPNG_SELECT_BOTH);
  1625. if (username) {
  1626. capng_updatev(
  1627. CAPNG_ADD,
  1628. CAPNG_PERMITTED | CAPNG_EFFECTIVE,
  1629. CAP_SETUID,
  1630. CAP_SETGID,
  1631. -1);
  1632. }
  1633. if (chroot_dir) {
  1634. capng_update(
  1635. CAPNG_ADD,
  1636. CAPNG_PERMITTED | CAPNG_EFFECTIVE,
  1637. CAP_SYS_CHROOT
  1638. );
  1639. }
  1640. if (WFileName) {
  1641. capng_update(
  1642. CAPNG_ADD,
  1643. CAPNG_PERMITTED | CAPNG_EFFECTIVE,
  1644. CAP_DAC_OVERRIDE
  1645. );
  1646. }
  1647. capng_apply(CAPNG_SELECT_BOTH);
  1648. #endif /* HAVE_LIBCAP_NG */
  1649. if (username || chroot_dir)
  1650. droproot(username, chroot_dir);
  1651. }
  1652. #endif /* _WIN32 */
  1653. if (pcap_setfilter(pd, &fcode) < 0)
  1654. error("%s", pcap_geterr(pd));
  1655. #ifdef HAVE_CAPSICUM
  1656. if (RFileName == NULL && VFileName == NULL) {
  1657. static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
  1658. /*
  1659. * The various libpcap devices use a combination of
  1660. * read (bpf), ioctl (bpf, netmap), poll (netmap)
  1661. * so we add the relevant access rights.
  1662. */
  1663. cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
  1664. if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
  1665. errno != ENOSYS) {
  1666. error("unable to limit pcap descriptor");
  1667. }
  1668. if (cap_ioctls_limit(pcap_fileno(pd), cmds,
  1669. sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
  1670. error("unable to limit ioctls on pcap descriptor");
  1671. }
  1672. }
  1673. #endif
  1674. if (WFileName) {
  1675. pcap_dumper_t *p;
  1676. /* Do not exceed the default PATH_MAX for files. */
  1677. dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
  1678. if (dumpinfo.CurrentFileName == NULL)
  1679. error("malloc of dumpinfo.CurrentFileName");
  1680. /* We do not need numbering for dumpfiles if Cflag isn't set. */
  1681. if (Cflag != 0)
  1682. MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
  1683. else
  1684. MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
  1685. p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
  1686. #ifdef HAVE_LIBCAP_NG
  1687. /* Give up CAP_DAC_OVERRIDE capability.
  1688. * Only allow it to be restored if the -C or -G flag have been
  1689. * set since we may need to create more files later on.
  1690. */
  1691. capng_update(
  1692. CAPNG_DROP,
  1693. (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
  1694. | CAPNG_EFFECTIVE,
  1695. CAP_DAC_OVERRIDE
  1696. );
  1697. capng_apply(CAPNG_SELECT_BOTH);
  1698. #endif /* HAVE_LIBCAP_NG */
  1699. if (p == NULL)
  1700. error("%s", pcap_geterr(pd));
  1701. #ifdef HAVE_CAPSICUM
  1702. set_dumper_capsicum_rights(p);
  1703. #endif
  1704. if (Cflag != 0 || Gflag != 0) {
  1705. #ifdef HAVE_CAPSICUM
  1706. dumpinfo.WFileName = strdup(basename(WFileName));
  1707. if (dumpinfo.WFileName == NULL) {
  1708. error("Unable to allocate memory for file %s",
  1709. WFileName);
  1710. }
  1711. dumpinfo.dirfd = open(dirname(WFileName),
  1712. O_DIRECTORY | O_RDONLY);
  1713. if (dumpinfo.dirfd < 0) {
  1714. error("unable to open directory %s",
  1715. dirname(WFileName));
  1716. }
  1717. cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
  1718. CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
  1719. if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
  1720. errno != ENOSYS) {
  1721. error("unable to limit directory rights");
  1722. }
  1723. if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
  1724. errno != ENOSYS) {
  1725. error("unable to limit dump descriptor fcntls");
  1726. }
  1727. #else /* !HAVE_CAPSICUM */
  1728. dumpinfo.WFileName = WFileName;
  1729. #endif
  1730. callback = dump_packet_and_trunc;
  1731. dumpinfo.pd = pd;
  1732. dumpinfo.p = p;
  1733. pcap_userdata = (u_char *)&dumpinfo;
  1734. } else {
  1735. callback = dump_packet;
  1736. pcap_userdata = (u_char *)p;
  1737. }
  1738. #ifdef HAVE_PCAP_DUMP_FLUSH
  1739. if (Uflag)
  1740. pcap_dump_flush(p);
  1741. #endif
  1742. } else {
  1743. dlt = pcap_datalink(pd);
  1744. ndo->ndo_if_printer = get_if_printer(ndo, dlt);
  1745. callback = print_packet;
  1746. pcap_userdata = (u_char *)ndo;
  1747. }
  1748. #ifdef SIGNAL_REQ_INFO
  1749. /*
  1750. * We can't get statistics when reading from a file rather
  1751. * than capturing from a device.
  1752. */
  1753. if (RFileName == NULL)
  1754. (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
  1755. #endif
  1756. if (ndo->ndo_vflag > 0 && WFileName) {
  1757. /*
  1758. * When capturing to a file, "-v" means tcpdump should,
  1759. * every 10 seconds, "v"erbosely report the number of
  1760. * packets captured.
  1761. */
  1762. #ifdef USE_WIN32_MM_TIMER
  1763. /* call verbose_stats_dump() each 1000 +/-100msec */
  1764. timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
  1765. setvbuf(stderr, NULL, _IONBF, 0);
  1766. #elif defined(HAVE_ALARM)
  1767. (void)setsignal(SIGALRM, verbose_stats_dump);
  1768. alarm(1);
  1769. #endif
  1770. }
  1771. if (RFileName == NULL) {
  1772. /*
  1773. * Live capture (if -V was specified, we set RFileName
  1774. * to a file from the -V file). Print a message to
  1775. * the standard error on UN*X.
  1776. */
  1777. if (!ndo->ndo_vflag && !WFileName) {
  1778. (void)fprintf(stderr,
  1779. "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
  1780. program_name);
  1781. } else
  1782. (void)fprintf(stderr, "%s: ", program_name);
  1783. dlt = pcap_datalink(pd);
  1784. dlt_name = pcap_datalink_val_to_name(dlt);
  1785. if (dlt_name == NULL) {
  1786. (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
  1787. device, dlt, ndo->ndo_snaplen);
  1788. } else {
  1789. (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
  1790. device, dlt_name,
  1791. pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
  1792. }
  1793. (void)fflush(stderr);
  1794. }
  1795. #ifdef HAVE_CAPSICUM
  1796. cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL);
  1797. if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
  1798. error("unable to enter the capability mode");
  1799. #endif /* HAVE_CAPSICUM */
  1800. do {
  1801. status = pcap_loop(pd, cnt, callback, pcap_userdata);
  1802. if (WFileName == NULL) {
  1803. /*
  1804. * We're printing packets. Flush the printed output,
  1805. * so it doesn't get intermingled with error output.
  1806. */
  1807. if (status == -2) {
  1808. /*
  1809. * We got interrupted, so perhaps we didn't
  1810. * manage to finish a line we were printing.
  1811. * Print an extra newline, just in case.
  1812. */
  1813. putchar('\n');
  1814. }
  1815. (void)fflush(stdout);
  1816. }
  1817. if (status == -2) {
  1818. /*
  1819. * We got interrupted. If we are reading multiple
  1820. * files (via -V) set these so that we stop.
  1821. */
  1822. VFileName = NULL;
  1823. ret = NULL;
  1824. }
  1825. if (status == -1) {
  1826. /*
  1827. * Error. Report it.
  1828. */
  1829. (void)fprintf(stderr, "%s: pcap_loop: %s\n",
  1830. program_name, pcap_geterr(pd));
  1831. }
  1832. if (RFileName == NULL) {
  1833. /*
  1834. * We're doing a live capture. Report the capture
  1835. * statistics.
  1836. */
  1837. info(1);
  1838. }
  1839. pcap_close(pd);
  1840. if (VFileName != NULL) {
  1841. ret = get_next_file(VFile, VFileLine);
  1842. if (ret) {
  1843. int new_dlt;
  1844. RFileName = VFileLine;
  1845. pd = pcap_open_offline(RFileName, ebuf);
  1846. if (pd == NULL)
  1847. error("%s", ebuf);
  1848. #ifdef HAVE_CAPSICUM
  1849. cap_rights_init(&rights, CAP_READ);
  1850. if (cap_rights_limit(fileno(pcap_file(pd)),
  1851. &rights) < 0 && errno != ENOSYS) {
  1852. error("unable to limit pcap descriptor");
  1853. }
  1854. #endif
  1855. new_dlt = pcap_datalink(pd);
  1856. if (new_dlt != dlt) {
  1857. /*
  1858. * The new file has a different
  1859. * link-layer header type from the
  1860. * previous one.
  1861. */
  1862. if (WFileName != NULL) {
  1863. /*
  1864. * We're writing raw packets
  1865. * that match the filter to
  1866. * a pcap file. pcap files
  1867. * don't support multiple
  1868. * different link-layer
  1869. * header types, so we fail
  1870. * here.
  1871. */
  1872. error("%s: new dlt does not match original", RFileName);
  1873. }
  1874. /*
  1875. * We're printing the decoded packets;
  1876. * switch to the new DLT.
  1877. *
  1878. * To do that, we need to change
  1879. * the printer, change the DLT name,
  1880. * and recompile the filter with
  1881. * the new DLT.
  1882. */
  1883. dlt = new_dlt;
  1884. ndo->ndo_if_printer = get_if_printer(ndo, dlt);
  1885. if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
  1886. error("%s", pcap_geterr(pd));
  1887. }
  1888. /*
  1889. * Set the filter on the new file.
  1890. */
  1891. if (pcap_setfilter(pd, &fcode) < 0)
  1892. error("%s", pcap_geterr(pd));
  1893. /*
  1894. * Report the new file.
  1895. */
  1896. dlt_name = pcap_datalink_val_to_name(dlt);
  1897. if (dlt_name == NULL) {
  1898. fprintf(stderr, "reading from file %s, link-type %u\n",
  1899. RFileName, dlt);
  1900. } else {
  1901. fprintf(stderr,
  1902. "reading from file %s, link-type %s (%s)\n",
  1903. RFileName, dlt_name,
  1904. pcap_datalink_val_to_description(dlt));
  1905. }
  1906. }
  1907. }
  1908. }
  1909. while (ret != NULL);
  1910. free(cmdbuf);
  1911. pcap_freecode(&fcode);
  1912. exit_tcpdump(status == -1 ? 1 : 0);
  1913. }
  1914. /* make a clean exit on interrupts */
  1915. static RETSIGTYPE
  1916. cleanup(int signo _U_)
  1917. {
  1918. #ifdef USE_WIN32_MM_TIMER
  1919. if (timer_id)
  1920. timeKillEvent(timer_id);
  1921. timer_id = 0;
  1922. #elif defined(HAVE_ALARM)
  1923. alarm(0);
  1924. #endif
  1925. #ifdef HAVE_PCAP_BREAKLOOP
  1926. /*
  1927. * We have "pcap_breakloop()"; use it, so that we do as little
  1928. * as possible in the signal handler (it's probably not safe
  1929. * to do anything with standard I/O streams in a signal handler -
  1930. * the ANSI C standard doesn't say it is).
  1931. */
  1932. pcap_breakloop(pd);
  1933. #else
  1934. /*
  1935. * We don't have "pcap_breakloop()"; this isn't safe, but
  1936. * it's the best we can do. Print the summary if we're
  1937. * not reading from a savefile - i.e., if we're doing a
  1938. * live capture - and exit.
  1939. */
  1940. if (pd != NULL && pcap_file(pd) == NULL) {
  1941. /*
  1942. * We got interrupted, so perhaps we didn't
  1943. * manage to finish a line we were printing.
  1944. * Print an extra newline, just in case.
  1945. */
  1946. putchar('\n');
  1947. (void)fflush(stdout);
  1948. info(1);
  1949. }
  1950. exit_tcpdump(0);
  1951. #endif
  1952. }
  1953. /*
  1954. On windows, we do not use a fork, so we do not care less about
  1955. waiting a child processes to die
  1956. */
  1957. #if defined(HAVE_FORK) || defined(HAVE_VFORK)
  1958. static RETSIGTYPE
  1959. child_cleanup(int signo _U_)
  1960. {
  1961. wait(NULL);
  1962. }
  1963. #endif /* HAVE_FORK && HAVE_VFORK */
  1964. static void
  1965. info(register int verbose)
  1966. {
  1967. struct pcap_stat stats;
  1968. /*
  1969. * Older versions of libpcap didn't set ps_ifdrop on some
  1970. * platforms; initialize it to 0 to handle that.
  1971. */
  1972. stats.ps_ifdrop = 0;
  1973. if (pcap_stats(pd, &stats) < 0) {
  1974. (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
  1975. infoprint = 0;
  1976. return;
  1977. }
  1978. if (!verbose)
  1979. fprintf(stderr, "%s: ", program_name);
  1980. (void)fprintf(stderr, "%u packet%s captured", packets_captured,
  1981. PLURAL_SUFFIX(packets_captured));
  1982. if (!verbose)
  1983. fputs(", ", stderr);
  1984. else
  1985. putc('\n', stderr);
  1986. (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
  1987. PLURAL_SUFFIX(stats.ps_recv));
  1988. if (!verbose)
  1989. fputs(", ", stderr);
  1990. else
  1991. putc('\n', stderr);
  1992. (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
  1993. PLURAL_SUFFIX(stats.ps_drop));
  1994. if (stats.ps_ifdrop != 0) {
  1995. if (!verbose)
  1996. fputs(", ", stderr);
  1997. else
  1998. putc('\n', stderr);
  1999. (void)fprintf(stderr, "%u packet%s dropped by interface\n",
  2000. stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
  2001. } else
  2002. putc('\n', stderr);
  2003. infoprint = 0;
  2004. }
  2005. #if defined(HAVE_FORK) || defined(HAVE_VFORK)
  2006. #ifdef HAVE_FORK
  2007. #define fork_subprocess() fork()
  2008. #else
  2009. #define fork_subprocess() vfork()
  2010. #endif
  2011. static void
  2012. compress_savefile(const char *filename)
  2013. {
  2014. pid_t child;
  2015. child = fork_subprocess();
  2016. if (child == -1) {
  2017. fprintf(stderr,
  2018. "compress_savefile: fork failed: %s\n",
  2019. pcap_strerror(errno));
  2020. return;
  2021. }
  2022. if (child != 0) {
  2023. /* Parent process. */
  2024. return;
  2025. }
  2026. /*
  2027. * Child process.
  2028. * Set to lowest priority so that this doesn't disturb the capture.
  2029. */
  2030. #ifdef NZERO
  2031. setpriority(PRIO_PROCESS, 0, NZERO - 1);
  2032. #else
  2033. setpriority(PRIO_PROCESS, 0, 19);
  2034. #endif
  2035. if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
  2036. fprintf(stderr,
  2037. "compress_savefile: execlp(%s, %s) failed: %s\n",
  2038. zflag,
  2039. filename,
  2040. pcap_strerror(errno));
  2041. #ifdef HAVE_FORK
  2042. exit(1);
  2043. #else
  2044. _exit(1);
  2045. #endif
  2046. }
  2047. #else /* HAVE_FORK && HAVE_VFORK */
  2048. static void
  2049. compress_savefile(const char *filename)
  2050. {
  2051. fprintf(stderr,
  2052. "compress_savefile failed. Functionality not implemented under your system\n");
  2053. }
  2054. #endif /* HAVE_FORK && HAVE_VFORK */
  2055. static void
  2056. dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
  2057. {
  2058. struct dump_info *dump_info;
  2059. ++packets_captured;
  2060. ++infodelay;
  2061. dump_info = (struct dump_info *)user;
  2062. /*
  2063. * XXX - this won't force the file to rotate on the specified time
  2064. * boundary, but it will rotate on the first packet received after the
  2065. * specified Gflag number of seconds. Note: if a Gflag time boundary
  2066. * and a Cflag size boundary coincide, the time rotation will occur
  2067. * first thereby cancelling the Cflag boundary (since the file should
  2068. * be 0).
  2069. */
  2070. if (Gflag != 0) {
  2071. /* Check if it is time to rotate */
  2072. time_t t;
  2073. /* Get the current time */
  2074. if ((t = time(NULL)) == (time_t)-1) {
  2075. error("dump_and_trunc_packet: can't get current_time: %s",
  2076. pcap_strerror(errno));
  2077. }
  2078. /* If the time is greater than the specified window, rotate */
  2079. if (t - Gflag_time >= Gflag) {
  2080. #ifdef HAVE_CAPSICUM
  2081. FILE *fp;
  2082. int fd;
  2083. #endif
  2084. /* Update the Gflag_time */
  2085. Gflag_time = t;
  2086. /* Update Gflag_count */
  2087. Gflag_count++;
  2088. /*
  2089. * Close the current file and open a new one.
  2090. */
  2091. pcap_dump_close(dump_info->p);
  2092. /*
  2093. * Compress the file we just closed, if the user asked for it
  2094. */
  2095. if (zflag != NULL)
  2096. compress_savefile(dump_info->CurrentFileName);
  2097. /*
  2098. * Check to see if we've exceeded the Wflag (when
  2099. * not using Cflag).
  2100. */
  2101. if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
  2102. (void)fprintf(stderr, "Maximum file limit reached: %d\n",
  2103. Wflag);
  2104. info(1);
  2105. exit_tcpdump(0);
  2106. /* NOTREACHED */
  2107. }
  2108. if (dump_info->CurrentFileName != NULL)
  2109. free(dump_info->CurrentFileName);
  2110. /* Allocate space for max filename + \0. */
  2111. dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
  2112. if (dump_info->CurrentFileName == NULL)
  2113. error("dump_packet_and_trunc: malloc");
  2114. /*
  2115. * Gflag was set otherwise we wouldn't be here. Reset the count
  2116. * so multiple files would end with 1,2,3 in the filename.
  2117. * The counting is handled with the -C flow after this.
  2118. */
  2119. Cflag_count = 0;
  2120. /*
  2121. * This is always the first file in the Cflag
  2122. * rotation: e.g. 0
  2123. * We also don't need numbering if Cflag is not set.
  2124. */
  2125. if (Cflag != 0)
  2126. MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
  2127. WflagChars);
  2128. else
  2129. MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
  2130. #ifdef HAVE_LIBCAP_NG
  2131. capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
  2132. capng_apply(CAPNG_SELECT_BOTH);
  2133. #endif /* HAVE_LIBCAP_NG */
  2134. #ifdef HAVE_CAPSICUM
  2135. fd = openat(dump_info->dirfd,
  2136. dump_info->CurrentFileName,
  2137. O_CREAT | O_WRONLY | O_TRUNC, 0644);
  2138. if (fd < 0) {
  2139. error("unable to open file %s",
  2140. dump_info->CurrentFileName);
  2141. }
  2142. fp = fdopen(fd, "w");
  2143. if (fp == NULL) {
  2144. error("unable to fdopen file %s",
  2145. dump_info->CurrentFileName);
  2146. }
  2147. dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
  2148. #else /* !HAVE_CAPSICUM */
  2149. dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
  2150. #endif
  2151. #ifdef HAVE_LIBCAP_NG
  2152. capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
  2153. capng_apply(CAPNG_SELECT_BOTH);
  2154. #endif /* HAVE_LIBCAP_NG */
  2155. if (dump_info->p == NULL)
  2156. error("%s", pcap_geterr(pd));
  2157. #ifdef HAVE_CAPSICUM
  2158. set_dumper_capsicum_rights(dump_info->p);
  2159. #endif
  2160. }
  2161. }
  2162. /*
  2163. * XXX - this won't prevent capture files from getting
  2164. * larger than Cflag - the last packet written to the
  2165. * file could put it over Cflag.
  2166. */
  2167. if (Cflag != 0) {
  2168. long size = pcap_dump_ftell(dump_info->p);
  2169. if (size == -1)
  2170. error("ftell fails on output file");
  2171. if (size > Cflag) {
  2172. #ifdef HAVE_CAPSICUM
  2173. FILE *fp;
  2174. int fd;
  2175. #endif
  2176. /*
  2177. * Close the current file and open a new one.
  2178. */
  2179. pcap_dump_close(dump_info->p);
  2180. /*
  2181. * Compress the file we just closed, if the user
  2182. * asked for it.
  2183. */
  2184. if (zflag != NULL)
  2185. compress_savefile(dump_info->CurrentFileName);
  2186. Cflag_count++;
  2187. if (Wflag > 0) {
  2188. if (Cflag_count >= Wflag)
  2189. Cflag_count = 0;
  2190. }
  2191. if (dump_info->CurrentFileName != NULL)
  2192. free(dump_info->CurrentFileName);
  2193. dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
  2194. if (dump_info->CurrentFileName == NULL)
  2195. error("dump_packet_and_trunc: malloc");
  2196. MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
  2197. #ifdef HAVE_LIBCAP_NG
  2198. capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
  2199. capng_apply(CAPNG_SELECT_BOTH);
  2200. #endif /* HAVE_LIBCAP_NG */
  2201. #ifdef HAVE_CAPSICUM
  2202. fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
  2203. O_CREAT | O_WRONLY | O_TRUNC, 0644);
  2204. if (fd < 0) {
  2205. error("unable to open file %s",
  2206. dump_info->CurrentFileName);
  2207. }
  2208. fp = fdopen(fd, "w");
  2209. if (fp == NULL) {
  2210. error("unable to fdopen file %s",
  2211. dump_info->CurrentFileName);
  2212. }
  2213. dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
  2214. #else /* !HAVE_CAPSICUM */
  2215. dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
  2216. #endif
  2217. #ifdef HAVE_LIBCAP_NG
  2218. capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
  2219. capng_apply(CAPNG_SELECT_BOTH);
  2220. #endif /* HAVE_LIBCAP_NG */
  2221. if (dump_info->p == NULL)
  2222. error("%s", pcap_geterr(pd));
  2223. #ifdef HAVE_CAPSICUM
  2224. set_dumper_capsicum_rights(dump_info->p);
  2225. #endif
  2226. }
  2227. }
  2228. pcap_dump((u_char *)dump_info->p, h, sp);
  2229. #ifdef HAVE_PCAP_DUMP_FLUSH
  2230. if (Uflag)
  2231. pcap_dump_flush(dump_info->p);
  2232. #endif
  2233. --infodelay;
  2234. if (infoprint)
  2235. info(0);
  2236. }
  2237. static void
  2238. dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
  2239. {
  2240. ++packets_captured;
  2241. ++infodelay;
  2242. pcap_dump(user, h, sp);
  2243. #ifdef HAVE_PCAP_DUMP_FLUSH
  2244. if (Uflag)
  2245. pcap_dump_flush((pcap_dumper_t *)user);
  2246. #endif
  2247. --infodelay;
  2248. if (infoprint)
  2249. info(0);
  2250. }
  2251. static void
  2252. print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
  2253. {
  2254. ++packets_captured;
  2255. ++infodelay;
  2256. pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
  2257. --infodelay;
  2258. if (infoprint)
  2259. info(0);
  2260. }
  2261. #ifdef _WIN32
  2262. /*
  2263. * XXX - there should really be libpcap calls to get the version
  2264. * number as a string (the string would be generated from #defines
  2265. * at run time, so that it's not generated from string constants
  2266. * in the library, as, on many UNIX systems, those constants would
  2267. * be statically linked into the application executable image, and
  2268. * would thus reflect the version of libpcap on the system on
  2269. * which the application was *linked*, not the system on which it's
  2270. * *running*.
  2271. *
  2272. * That routine should be documented, unlike the "version[]"
  2273. * string, so that UNIX vendors providing their own libpcaps
  2274. * don't omit it (as a couple of vendors have...).
  2275. *
  2276. * Packet.dll should perhaps also export a routine to return the
  2277. * version number of the Packet.dll code, to supply the
  2278. * "Wpcap_version" information on Windows.
  2279. */
  2280. char WDversion[]="current-git.tcpdump.org";
  2281. #if !defined(HAVE_GENERATED_VERSION)
  2282. char version[]="current-git.tcpdump.org";
  2283. #endif
  2284. char pcap_version[]="current-git.tcpdump.org";
  2285. char Wpcap_version[]="3.1";
  2286. #endif
  2287. #ifdef SIGNAL_REQ_INFO
  2288. RETSIGTYPE requestinfo(int signo _U_)
  2289. {
  2290. if (infodelay)
  2291. ++infoprint;
  2292. else
  2293. info(0);
  2294. }
  2295. #endif
  2296. /*
  2297. * Called once each second in verbose mode while dumping to file
  2298. */
  2299. #ifdef USE_WIN32_MM_TIMER
  2300. void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
  2301. DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
  2302. {
  2303. if (infodelay == 0)
  2304. fprintf(stderr, "Got %u\r", packets_captured);
  2305. }
  2306. #elif defined(HAVE_ALARM)
  2307. static void verbose_stats_dump(int sig _U_)
  2308. {
  2309. if (infodelay == 0)
  2310. fprintf(stderr, "Got %u\r", packets_captured);
  2311. alarm(1);
  2312. }
  2313. #endif
  2314. USES_APPLE_DEPRECATED_API
  2315. static void
  2316. print_version(void)
  2317. {
  2318. extern char version[];
  2319. #ifndef HAVE_PCAP_LIB_VERSION
  2320. #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
  2321. extern char pcap_version[];
  2322. #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
  2323. static char pcap_version[] = "unknown";
  2324. #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
  2325. #endif /* HAVE_PCAP_LIB_VERSION */
  2326. const char *smi_version_string;
  2327. #ifdef HAVE_PCAP_LIB_VERSION
  2328. #ifdef _WIN32
  2329. (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
  2330. #else /* _WIN32 */
  2331. (void)fprintf(stderr, "%s version %s\n", program_name, version);
  2332. #endif /* _WIN32 */
  2333. (void)fprintf(stderr, "%s\n",pcap_lib_version());
  2334. #else /* HAVE_PCAP_LIB_VERSION */
  2335. #ifdef _WIN32
  2336. (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
  2337. (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
  2338. #else /* _WIN32 */
  2339. (void)fprintf(stderr, "%s version %s\n", program_name, version);
  2340. (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
  2341. #endif /* _WIN32 */
  2342. #endif /* HAVE_PCAP_LIB_VERSION */
  2343. #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
  2344. (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
  2345. #endif
  2346. smi_version_string = nd_smi_version_string();
  2347. if (smi_version_string != NULL)
  2348. (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
  2349. #if defined(__SANITIZE_ADDRESS__)
  2350. (void)fprintf (stderr, "Compiled with AddressSanitizer/GCC.\n");
  2351. #elif defined(__has_feature)
  2352. # if __has_feature(address_sanitizer)
  2353. (void)fprintf (stderr, "Compiled with AddressSanitizer/CLang.\n");
  2354. # endif
  2355. #endif /* __SANITIZE_ADDRESS__ or __has_feature */
  2356. }
  2357. USES_APPLE_RST
  2358. static void
  2359. print_usage(void)
  2360. {
  2361. print_version();
  2362. (void)fprintf(stderr,
  2363. "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
  2364. (void)fprintf(stderr,
  2365. "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
  2366. (void)fprintf(stderr,
  2367. "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
  2368. #ifdef HAVE_PCAP_SETDIRECTION
  2369. (void)fprintf(stderr,
  2370. "\t\t[ -Q in|out|inout ]\n");
  2371. #endif
  2372. (void)fprintf(stderr,
  2373. "\t\t[ -r file ] [ -s snaplen ] ");
  2374. #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
  2375. (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
  2376. (void)fprintf(stderr,
  2377. "\t\t");
  2378. #endif
  2379. #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
  2380. (void)fprintf(stderr, "[ --immediate-mode ] ");
  2381. #endif
  2382. (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
  2383. (void)fprintf(stderr,
  2384. "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
  2385. (void)fprintf(stderr,
  2386. "\t\t[ -Z user ] [ expression ]\n");
  2387. }
  2388. /*
  2389. * Local Variables:
  2390. * c-style: whitesmith
  2391. * c-basic-offset: 8
  2392. * End:
  2393. */