softflowd.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. /*
  2. * Copyright 2002 Damien Miller <djm@mindrot.org> All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  14. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  15. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  16. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  18. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  19. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  20. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  21. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  22. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. /* $Id: softflowd.c,v 1.93 2006/11/02 06:23:29 djm Exp $ */
  25. /*
  26. * This is software implementation of Cisco's NetFlow(tm) traffic
  27. * reporting system. It operates by listening (via libpcap) on a
  28. * promiscuous interface and tracking traffic flows.
  29. *
  30. * Traffic flows are recorded by source/destination/protocol IP address or, in the
  31. * case of TCP and UDP, by src_addr:src_port/dest_addr:dest_port/protocol
  32. *
  33. * Flows expire automatically after a period of inactivity (default: 1 hour)
  34. * They may also be evicted (in order of age) in situations where there are
  35. * more flows than slots available.
  36. *
  37. * Netflow version 1 compatible packets are sent to a specified target
  38. * host upon flow expiry.
  39. *
  40. * As this implementation watches traffic promiscuously, it is likely to
  41. * place significant load on hosts or gateways on which it is installed.
  42. */
  43. #include "common.h"
  44. #include "sys-tree.h"
  45. #include "convtime.h"
  46. #include "softflowd.h"
  47. #include "treetype.h"
  48. #include "log.h"
  49. #include <pcap.h>
  50. RCSID("$Id: softflowd.c,v 1.93 2006/11/02 06:23:29 djm Exp $");
  51. /* Global variables */
  52. static int verbose_flag = 0; /* Debugging flag */
  53. /* Signal handler flags */
  54. static volatile int graceful_shutdown_request = 0;
  55. /* Context for libpcap callback functions */
  56. struct CB_CTXT {
  57. struct FLOWTRACK *ft;
  58. int linktype;
  59. int fatal;
  60. int want_v6;
  61. };
  62. /* Describes a datalink header and how to extract v4/v6 frames from it */
  63. struct DATALINK {
  64. int dlt; /* BPF datalink type */
  65. int skiplen; /* Number of bytes to skip datalink header */
  66. int ft_off; /* Datalink frametype offset */
  67. int ft_len; /* Datalink frametype length */
  68. int ft_is_be; /* Set if frametype is big-endian */
  69. u_int32_t ft_mask; /* Mask applied to frametype */
  70. u_int32_t ft_v4; /* IPv4 frametype */
  71. u_int32_t ft_v6; /* IPv6 frametype */
  72. };
  73. /* Datalink types that we know about */
  74. static const struct DATALINK lt[] = {
  75. { DLT_EN10MB, 14, 12, 2, 1, 0xffffffff, 0x0800, 0x86dd },
  76. { DLT_PPP, 5, 3, 2, 1, 0xffffffff, 0x0021, 0x0057 },
  77. #ifdef DLT_LINUX_SLL
  78. { DLT_LINUX_SLL,16, 14, 2, 1, 0xffffffff, 0x0800, 0x86dd },
  79. #endif
  80. { DLT_RAW, 0, 0, 1, 1, 0x000000f0, 0x0040, 0x0060 },
  81. { DLT_NULL, 4, 0, 4, 0, 0xffffffff, AF_INET, AF_INET6 },
  82. #ifdef DLT_LOOP
  83. { DLT_LOOP, 4, 0, 4, 1, 0xffffffff, AF_INET, AF_INET6 },
  84. #endif
  85. { -1, -1, -1, -1, -1, 0x00000000, 0xffff, 0xffff },
  86. };
  87. /* Netflow send functions */
  88. typedef int (netflow_send_func_t)(struct FLOW **, int, int, u_int64_t *,
  89. struct timeval *, int);
  90. struct NETFLOW_SENDER {
  91. int version;
  92. netflow_send_func_t *func;
  93. int v6_capable;
  94. };
  95. /* Array of NetFlow export function that we know of. NB. nf[0] is default */
  96. static const struct NETFLOW_SENDER nf[] = {
  97. { 5, send_netflow_v5, 0 },
  98. { 1, send_netflow_v1, 0 },
  99. { 9, send_netflow_v9, 1 },
  100. { -1, NULL, 0 },
  101. };
  102. /* Describes a location where we send NetFlow packets to */
  103. struct NETFLOW_TARGET {
  104. int fd;
  105. const struct NETFLOW_SENDER *dialect;
  106. };
  107. /* Signal handlers */
  108. static void sighand_graceful_shutdown(int signum)
  109. {
  110. graceful_shutdown_request = signum;
  111. }
  112. static void sighand_other(int signum)
  113. {
  114. /* XXX: this may not be completely safe */
  115. logit(LOG_WARNING, "Exiting immediately on unexpected signal %d", signum);
  116. _exit(0);
  117. }
  118. /*
  119. * This is the flow comparison function.
  120. */
  121. static int
  122. flow_compare(struct FLOW *a, struct FLOW *b)
  123. {
  124. /* Be careful to avoid signed vs unsigned issues here */
  125. int r;
  126. if (a->af != b->af)
  127. return (a->af > b->af ? 1 : -1);
  128. if ((r = memcmp(&a->addr[0], &b->addr[0], sizeof(a->addr[0]))) != 0)
  129. return (r > 0 ? 1 : -1);
  130. if ((r = memcmp(&a->addr[1], &b->addr[1], sizeof(a->addr[1]))) != 0)
  131. return (r > 0 ? 1 : -1);
  132. #ifdef notyet
  133. if (a->ip6_flowlabel[0] != 0 && b->ip6_flowlabel[0] != 0 &&
  134. a->ip6_flowlabel[0] != b->ip6_flowlabel[0])
  135. return (a->ip6_flowlabel[0] > b->ip6_flowlabel[0] ? 1 : -1);
  136. if (a->ip6_flowlabel[1] != 0 && b->ip6_flowlabel[1] != 0 &&
  137. a->ip6_flowlabel[1] != b->ip6_flowlabel[1])
  138. return (a->ip6_flowlabel[1] > b->ip6_flowlabel[1] ? 1 : -1);
  139. #endif
  140. if (a->protocol != b->protocol)
  141. return (a->protocol > b->protocol ? 1 : -1);
  142. if (a->port[0] != b->port[0])
  143. return (ntohs(a->port[0]) > ntohs(b->port[0]) ? 1 : -1);
  144. if (a->port[1] != b->port[1])
  145. return (ntohs(a->port[1]) > ntohs(b->port[1]) ? 1 : -1);
  146. return (0);
  147. }
  148. /* Generate functions for flow tree */
  149. FLOW_PROTOTYPE(FLOWS, FLOW, trp, flow_compare);
  150. FLOW_GENERATE(FLOWS, FLOW, trp, flow_compare);
  151. /*
  152. * This is the expiry comparison function.
  153. */
  154. static int
  155. expiry_compare(struct EXPIRY *a, struct EXPIRY *b)
  156. {
  157. if (a->expires_at != b->expires_at)
  158. return (a->expires_at > b->expires_at ? 1 : -1);
  159. /* Make expiry entries unique by comparing flow sequence */
  160. if (a->flow->flow_seq != b->flow->flow_seq)
  161. return (a->flow->flow_seq > b->flow->flow_seq ? 1 : -1);
  162. return (0);
  163. }
  164. /* Generate functions for flow tree */
  165. EXPIRY_PROTOTYPE(EXPIRIES, EXPIRY, trp, expiry_compare);
  166. EXPIRY_GENERATE(EXPIRIES, EXPIRY, trp, expiry_compare);
  167. #if 0
  168. /* Dump a packet */
  169. static void
  170. dump_packet(const u_int8_t *p, int len)
  171. {
  172. char buf[1024], tmp[3];
  173. int i;
  174. for (*buf = '\0', i = 0; i < len; i++) {
  175. snprintf(tmp, sizeof(tmp), "%02x%s", p[i], i % 2 ? " " : "");
  176. if (strlcat(buf, tmp, sizeof(buf) - 4) >= sizeof(buf) - 4) {
  177. strlcat(buf, "...", sizeof(buf));
  178. break;
  179. }
  180. }
  181. logit(LOG_INFO, "packet len %d: %s", len, buf);
  182. }
  183. #endif
  184. /* Format a time in an ISOish format */
  185. static const char *
  186. format_time(time_t t)
  187. {
  188. struct tm *tm;
  189. static char buf[20];
  190. tm = localtime(&t);
  191. strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", tm);
  192. return (buf);
  193. }
  194. /* Format a flow in a verbose and ugly way */
  195. static const char *
  196. format_flow(struct FLOW *flow)
  197. {
  198. char addr1[64], addr2[64], stime[20], ftime[20];
  199. static char buf[1024];
  200. inet_ntop(flow->af, &flow->addr[0], addr1, sizeof(addr1));
  201. inet_ntop(flow->af, &flow->addr[1], addr2, sizeof(addr2));
  202. snprintf(stime, sizeof(ftime), "%s",
  203. format_time(flow->flow_start.tv_sec));
  204. snprintf(ftime, sizeof(ftime), "%s",
  205. format_time(flow->flow_last.tv_sec));
  206. snprintf(buf, sizeof(buf), "seq:%llu [%s]:%hu <> [%s]:%hu proto:%u "
  207. "octets>:%u packets>:%u octets<:%u packets<:%u "
  208. "start:%s.%03ld finish:%s.%03ld tcp>:%02x tcp<:%02x "
  209. "flowlabel>:%08x flowlabel<:%08x ",
  210. flow->flow_seq,
  211. addr1, ntohs(flow->port[0]), addr2, ntohs(flow->port[1]),
  212. (int)flow->protocol,
  213. flow->octets[0], flow->packets[0],
  214. flow->octets[1], flow->packets[1],
  215. stime, (flow->flow_start.tv_usec + 500) / 1000,
  216. ftime, (flow->flow_last.tv_usec + 500) / 1000,
  217. flow->tcp_flags[0], flow->tcp_flags[1],
  218. flow->ip6_flowlabel[0], flow->ip6_flowlabel[1]);
  219. return (buf);
  220. }
  221. /* Format a flow in a brief way */
  222. static const char *
  223. format_flow_brief(struct FLOW *flow)
  224. {
  225. char addr1[64], addr2[64];
  226. static char buf[1024];
  227. inet_ntop(flow->af, &flow->addr[0], addr1, sizeof(addr1));
  228. inet_ntop(flow->af, &flow->addr[1], addr2, sizeof(addr2));
  229. snprintf(buf, sizeof(buf),
  230. "seq:%llu [%s]:%hu <> [%s]:%hu proto:%u",
  231. flow->flow_seq,
  232. addr1, ntohs(flow->port[0]), addr2, ntohs(flow->port[1]),
  233. (int)flow->protocol);
  234. return (buf);
  235. }
  236. /* Fill in transport-layer (tcp/udp) portions of flow record */
  237. static int
  238. transport_to_flowrec(struct FLOW *flow, const u_int8_t *pkt,
  239. const size_t caplen, int isfrag, int protocol, int ndx)
  240. {
  241. const struct tcphdr *tcp = (const struct tcphdr *)pkt;
  242. const struct udphdr *udp = (const struct udphdr *)pkt;
  243. const struct icmp *icmp = (const struct icmp *)pkt;
  244. /*
  245. * XXX to keep flow in proper canonical format, it may be necessary
  246. * to swap the array slots based on the order of the port numbers
  247. * does this matter in practice??? I don't think so - return flows will
  248. * always match, because of their symmetrical addr/ports
  249. */
  250. switch (protocol) {
  251. case IPPROTO_TCP:
  252. /* Check for runt packet, but don't error out on short frags */
  253. if (caplen < sizeof(*tcp))
  254. return (isfrag ? 0 : 1);
  255. flow->port[ndx] = tcp->th_sport;
  256. flow->port[ndx ^ 1] = tcp->th_dport;
  257. flow->tcp_flags[ndx] |= tcp->th_flags;
  258. break;
  259. case IPPROTO_UDP:
  260. /* Check for runt packet, but don't error out on short frags */
  261. if (caplen < sizeof(*udp))
  262. return (isfrag ? 0 : 1);
  263. flow->port[ndx] = udp->uh_sport;
  264. flow->port[ndx ^ 1] = udp->uh_dport;
  265. break;
  266. case IPPROTO_ICMP:
  267. /*
  268. * Encode ICMP type * 256 + code into dest port like
  269. * Cisco routers
  270. */
  271. flow->port[ndx] = 0;
  272. flow->port[ndx ^ 1] = htons(icmp->icmp_type * 256 +
  273. icmp->icmp_code);
  274. break;
  275. }
  276. return (0);
  277. }
  278. /* Convert a IPv4 packet to a partial flow record (used for comparison) */
  279. static int
  280. ipv4_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, size_t caplen,
  281. size_t len, int *isfrag, int af)
  282. {
  283. const struct ip *ip = (const struct ip *)pkt;
  284. int ndx;
  285. if (caplen < 20 || caplen < ip->ip_hl * 4)
  286. return (-1); /* Runt packet */
  287. if (ip->ip_v != 4)
  288. return (-1); /* Unsupported IP version */
  289. /* Prepare to store flow in canonical format */
  290. ndx = memcmp(&ip->ip_src, &ip->ip_dst, sizeof(ip->ip_src)) > 0 ? 1 : 0;
  291. flow->af = af;
  292. flow->addr[ndx].v4 = ip->ip_src;
  293. flow->addr[ndx ^ 1].v4 = ip->ip_dst;
  294. flow->protocol = ip->ip_p;
  295. flow->octets[ndx] = len;
  296. flow->packets[ndx] = 1;
  297. *isfrag = (ntohs(ip->ip_off) & (IP_OFFMASK|IP_MF)) ? 1 : 0;
  298. /* Don't try to examine higher level headers if not first fragment */
  299. if (*isfrag && (ntohs(ip->ip_off) & IP_OFFMASK) != 0)
  300. return (0);
  301. return (transport_to_flowrec(flow, pkt + (ip->ip_hl * 4),
  302. caplen - (ip->ip_hl * 4), *isfrag, ip->ip_p, ndx));
  303. }
  304. /* Convert a IPv6 packet to a partial flow record (used for comparison) */
  305. static int
  306. ipv6_to_flowrec(struct FLOW *flow, const u_int8_t *pkt, size_t caplen,
  307. size_t len, int *isfrag, int af)
  308. {
  309. const struct ip6_hdr *ip6 = (const struct ip6_hdr *)pkt;
  310. const struct ip6_ext *eh6;
  311. const struct ip6_frag *fh6;
  312. int ndx, nxt;
  313. if (caplen < sizeof(*ip6))
  314. return (-1); /* Runt packet */
  315. if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION)
  316. return (-1); /* Unsupported IPv6 version */
  317. /* Prepare to store flow in canonical format */
  318. ndx = memcmp(&ip6->ip6_src, &ip6->ip6_dst,
  319. sizeof(ip6->ip6_src)) > 0 ? 1 : 0;
  320. flow->af = af;
  321. flow->ip6_flowlabel[ndx] = ip6->ip6_flow & IPV6_FLOWLABEL_MASK;
  322. flow->addr[ndx].v6 = ip6->ip6_src;
  323. flow->addr[ndx ^ 1].v6 = ip6->ip6_dst;
  324. flow->octets[ndx] = len;
  325. flow->packets[ndx] = 1;
  326. *isfrag = 0;
  327. nxt = ip6->ip6_nxt;
  328. pkt += sizeof(*ip6);
  329. caplen -= sizeof(*ip6);
  330. /* Now loop through headers, looking for transport header */
  331. for (;;) {
  332. eh6 = (const struct ip6_ext *)pkt;
  333. if (nxt == IPPROTO_HOPOPTS ||
  334. nxt == IPPROTO_ROUTING ||
  335. nxt == IPPROTO_DSTOPTS) {
  336. if (caplen < sizeof(*eh6) ||
  337. caplen < (eh6->ip6e_len + 1) << 3)
  338. return (1); /* Runt */
  339. nxt = eh6->ip6e_nxt;
  340. pkt += (eh6->ip6e_len + 1) << 3;
  341. caplen -= (eh6->ip6e_len + 1) << 3;
  342. } else if (nxt == IPPROTO_FRAGMENT) {
  343. *isfrag = 1;
  344. fh6 = (const struct ip6_frag *)eh6;
  345. if (caplen < sizeof(*fh6))
  346. return (1); /* Runt */
  347. /*
  348. * Don't try to examine higher level headers if
  349. * not first fragment
  350. */
  351. if ((fh6->ip6f_offlg & IP6F_OFF_MASK) != 0)
  352. return (0);
  353. nxt = fh6->ip6f_nxt;
  354. pkt += sizeof(*fh6);
  355. caplen -= sizeof(*fh6);
  356. } else
  357. break;
  358. }
  359. flow->protocol = nxt;
  360. return (transport_to_flowrec(flow, pkt, caplen, *isfrag, nxt, ndx));
  361. }
  362. static void
  363. flow_update_expiry(struct FLOWTRACK *ft, struct FLOW *flow)
  364. {
  365. EXPIRY_REMOVE(EXPIRIES, &ft->expiries, flow->expiry);
  366. /* Flows over 2Gb traffic */
  367. if (flow->octets[0] > (1U << 31) || flow->octets[1] > (1U << 31)) {
  368. flow->expiry->expires_at = 0;
  369. flow->expiry->reason = R_OVERBYTES;
  370. goto out;
  371. }
  372. /* Flows over maximum life seconds */
  373. if (ft->maximum_lifetime != 0 &&
  374. flow->flow_last.tv_sec - flow->flow_start.tv_sec >
  375. ft->maximum_lifetime) {
  376. flow->expiry->expires_at = 0;
  377. flow->expiry->reason = R_MAXLIFE;
  378. goto out;
  379. }
  380. if (flow->protocol == IPPROTO_TCP) {
  381. /* Reset TCP flows */
  382. if (ft->tcp_rst_timeout != 0 &&
  383. ((flow->tcp_flags[0] & TH_RST) ||
  384. (flow->tcp_flags[1] & TH_RST))) {
  385. flow->expiry->expires_at = flow->flow_last.tv_sec +
  386. ft->tcp_rst_timeout;
  387. flow->expiry->reason = R_TCP_RST;
  388. goto out;
  389. }
  390. /* Finished TCP flows */
  391. if (ft->tcp_fin_timeout != 0 &&
  392. ((flow->tcp_flags[0] & TH_FIN) &&
  393. (flow->tcp_flags[1] & TH_FIN))) {
  394. flow->expiry->expires_at = flow->flow_last.tv_sec +
  395. ft->tcp_fin_timeout;
  396. flow->expiry->reason = R_TCP_FIN;
  397. goto out;
  398. }
  399. /* TCP flows */
  400. if (ft->tcp_timeout != 0) {
  401. flow->expiry->expires_at = flow->flow_last.tv_sec +
  402. ft->tcp_timeout;
  403. flow->expiry->reason = R_TCP;
  404. goto out;
  405. }
  406. }
  407. if (ft->udp_timeout != 0 && flow->protocol == IPPROTO_UDP) {
  408. /* UDP flows */
  409. flow->expiry->expires_at = flow->flow_last.tv_sec +
  410. ft->udp_timeout;
  411. flow->expiry->reason = R_UDP;
  412. goto out;
  413. }
  414. if (ft->icmp_timeout != 0 &&
  415. ((flow->af == AF_INET && flow->protocol == IPPROTO_ICMP) ||
  416. ((flow->af == AF_INET6 && flow->protocol == IPPROTO_ICMPV6)))) {
  417. /* ICMP flows */
  418. flow->expiry->expires_at = flow->flow_last.tv_sec +
  419. ft->icmp_timeout;
  420. flow->expiry->reason = R_ICMP;
  421. goto out;
  422. }
  423. /* Everything else */
  424. flow->expiry->expires_at = flow->flow_last.tv_sec +
  425. ft->general_timeout;
  426. flow->expiry->reason = R_GENERAL;
  427. out:
  428. if (ft->maximum_lifetime != 0 && flow->expiry->expires_at != 0) {
  429. flow->expiry->expires_at = MIN(flow->expiry->expires_at,
  430. flow->flow_start.tv_sec + ft->maximum_lifetime);
  431. }
  432. EXPIRY_INSERT(EXPIRIES, &ft->expiries, flow->expiry);
  433. }
  434. /* Return values from process_packet */
  435. #define PP_OK 0
  436. #define PP_BAD_PACKET -2
  437. #define PP_MALLOC_FAIL -3
  438. /*
  439. * Main per-packet processing function. Take a packet (provided by
  440. * libpcap) and attempt to find a matching flow. If no such flow exists,
  441. * then create one.
  442. *
  443. * Also marks flows for fast expiry, based on flow or packet attributes
  444. * (the actual expiry is performed elsewhere)
  445. */
  446. static int
  447. process_packet(struct FLOWTRACK *ft, const u_int8_t *pkt, int af,
  448. const u_int32_t caplen, const u_int32_t len,
  449. const struct timeval *received_time)
  450. {
  451. struct FLOW tmp, *flow;
  452. int frag;
  453. ft->total_packets++;
  454. /* Convert the IP packet to a flow identity */
  455. memset(&tmp, 0, sizeof(tmp));
  456. switch (af) {
  457. case AF_INET:
  458. if (ipv4_to_flowrec(&tmp, pkt, caplen, len, &frag, af) == -1)
  459. goto bad;
  460. break;
  461. case AF_INET6:
  462. if (ipv6_to_flowrec(&tmp, pkt, caplen, len, &frag, af) == -1)
  463. goto bad;
  464. break;
  465. default:
  466. bad:
  467. ft->bad_packets++;
  468. return (PP_BAD_PACKET);
  469. }
  470. if (frag)
  471. ft->frag_packets++;
  472. /* Zero out bits of the flow that aren't relevant to tracking level */
  473. switch (ft->track_level) {
  474. case TRACK_IP_ONLY:
  475. tmp.protocol = 0;
  476. /* FALLTHROUGH */
  477. case TRACK_IP_PROTO:
  478. tmp.port[0] = tmp.port[1] = 0;
  479. tmp.tcp_flags[0] = tmp.tcp_flags[1] = 0;
  480. /* FALLTHROUGH */
  481. case TRACK_FULL:
  482. break;
  483. }
  484. /* If a matching flow does not exist, create and insert one */
  485. if ((flow = FLOW_FIND(FLOWS, &ft->flows, &tmp)) == NULL) {
  486. /* Allocate and fill in the flow */
  487. if ((flow = malloc(sizeof(*flow))) == NULL) {
  488. logit(LOG_ERR, "process_packet: flow malloc(%u) fail",
  489. sizeof(*flow));
  490. return (PP_MALLOC_FAIL);
  491. }
  492. memcpy(flow, &tmp, sizeof(*flow));
  493. memcpy(&flow->flow_start, received_time,
  494. sizeof(flow->flow_start));
  495. flow->flow_seq = ft->next_flow_seq++;
  496. FLOW_INSERT(FLOWS, &ft->flows, flow);
  497. /* Allocate and fill in the associated expiry event */
  498. if ((flow->expiry = malloc(sizeof(*flow->expiry))) == NULL) {
  499. logit(LOG_ERR, "process_packet: expiry malloc(%u) fail",
  500. sizeof(*flow->expiry));
  501. return (PP_MALLOC_FAIL);
  502. }
  503. flow->expiry->flow = flow;
  504. /* Must be non-zero (0 means expire immediately) */
  505. flow->expiry->expires_at = 1;
  506. flow->expiry->reason = R_GENERAL;
  507. EXPIRY_INSERT(EXPIRIES, &ft->expiries, flow->expiry);
  508. ft->num_flows++;
  509. if (verbose_flag)
  510. logit(LOG_DEBUG, "ADD FLOW %s", format_flow_brief(flow));
  511. } else {
  512. /* Update flow statistics */
  513. flow->packets[0] += tmp.packets[0];
  514. flow->octets[0] += tmp.octets[0];
  515. flow->tcp_flags[0] |= tmp.tcp_flags[0];
  516. flow->packets[1] += tmp.packets[1];
  517. flow->octets[1] += tmp.octets[1];
  518. flow->tcp_flags[1] |= tmp.tcp_flags[1];
  519. }
  520. memcpy(&flow->flow_last, received_time, sizeof(flow->flow_last));
  521. if (flow->expiry->expires_at != 0)
  522. flow_update_expiry(ft, flow);
  523. return (PP_OK);
  524. }
  525. /*
  526. * Subtract two timevals. Returns (t1 - t2) in milliseconds.
  527. */
  528. u_int32_t
  529. timeval_sub_ms(const struct timeval *t1, const struct timeval *t2)
  530. {
  531. struct timeval res;
  532. res.tv_sec = t1->tv_sec - t2->tv_sec;
  533. res.tv_usec = t1->tv_usec - t2->tv_usec;
  534. if (res.tv_usec < 0) {
  535. res.tv_usec += 1000000L;
  536. res.tv_sec--;
  537. }
  538. return ((u_int32_t)res.tv_sec * 1000 + (u_int32_t)res.tv_usec / 1000);
  539. }
  540. static void
  541. update_statistic(struct STATISTIC *s, double new, double n)
  542. {
  543. if (n == 1.0) {
  544. s->min = s->mean = s->max = new;
  545. return;
  546. }
  547. s->min = MIN(s->min, new);
  548. s->max = MAX(s->max, new);
  549. s->mean = s->mean + ((new - s->mean) / n);
  550. }
  551. /* Update global statistics */
  552. static void
  553. update_statistics(struct FLOWTRACK *ft, struct FLOW *flow)
  554. {
  555. double tmp;
  556. static double n = 1.0;
  557. ft->flows_expired++;
  558. ft->flows_pp[flow->protocol % 256]++;
  559. tmp = (double)flow->flow_last.tv_sec +
  560. ((double)flow->flow_last.tv_usec / 1000000.0);
  561. tmp -= (double)flow->flow_start.tv_sec +
  562. ((double)flow->flow_start.tv_usec / 1000000.0);
  563. if (tmp < 0.0)
  564. tmp = 0.0;
  565. update_statistic(&ft->duration, tmp, n);
  566. update_statistic(&ft->duration_pp[flow->protocol], tmp,
  567. (double)ft->flows_pp[flow->protocol % 256]);
  568. tmp = flow->octets[0] + flow->octets[1];
  569. update_statistic(&ft->octets, tmp, n);
  570. ft->octets_pp[flow->protocol % 256] += tmp;
  571. tmp = flow->packets[0] + flow->packets[1];
  572. update_statistic(&ft->packets, tmp, n);
  573. ft->packets_pp[flow->protocol % 256] += tmp;
  574. n++;
  575. }
  576. static void
  577. update_expiry_stats(struct FLOWTRACK *ft, struct EXPIRY *e)
  578. {
  579. switch (e->reason) {
  580. case R_GENERAL:
  581. ft->expired_general++;
  582. break;
  583. case R_TCP:
  584. ft->expired_tcp++;
  585. break;
  586. case R_TCP_RST:
  587. ft->expired_tcp_rst++;
  588. break;
  589. case R_TCP_FIN:
  590. ft->expired_tcp_fin++;
  591. break;
  592. case R_UDP:
  593. ft->expired_udp++;
  594. break;
  595. case R_ICMP:
  596. ft->expired_icmp++;
  597. break;
  598. case R_MAXLIFE:
  599. ft->expired_maxlife++;
  600. break;
  601. case R_OVERBYTES:
  602. ft->expired_overbytes++;
  603. break;
  604. case R_OVERFLOWS:
  605. ft->expired_maxflows++;
  606. break;
  607. case R_FLUSH:
  608. ft->expired_flush++;
  609. break;
  610. }
  611. }
  612. /* How long before the next expiry event in millisecond */
  613. static int
  614. next_expire(struct FLOWTRACK *ft)
  615. {
  616. struct EXPIRY *expiry;
  617. struct timeval now;
  618. u_int32_t expires_at, ret, fudge;
  619. gettimeofday(&now, NULL);
  620. if ((expiry = EXPIRY_MIN(EXPIRIES, &ft->expiries)) == NULL)
  621. return (-1); /* indefinite */
  622. expires_at = expiry->expires_at;
  623. /* Don't cluster urgent expiries */
  624. if (expires_at == 0 && (expiry->reason == R_OVERBYTES ||
  625. expiry->reason == R_OVERFLOWS || expiry->reason == R_FLUSH))
  626. return (0); /* Now */
  627. /* Cluster expiries by expiry_interval */
  628. if (ft->expiry_interval > 1) {
  629. if ((fudge = expires_at % ft->expiry_interval) > 0)
  630. expires_at += ft->expiry_interval - fudge;
  631. }
  632. if (expires_at < now.tv_sec)
  633. return (0); /* Now */
  634. ret = 999 + (expires_at - now.tv_sec) * 1000;
  635. return (ret);
  636. }
  637. /*
  638. * Scan the tree of expiry events and process expired flows. If zap_all
  639. * is set, then forcibly expire all flows.
  640. */
  641. #define CE_EXPIRE_NORMAL 0 /* Normal expiry processing */
  642. #define CE_EXPIRE_ALL -1 /* Expire all flows immediately */
  643. #define CE_EXPIRE_FORCED 1 /* Only expire force-expired flows */
  644. static int
  645. check_expired(struct FLOWTRACK *ft, struct NETFLOW_TARGET *target, int ex)
  646. {
  647. struct FLOW **expired_flows, **oldexp;
  648. int num_expired, i, r;
  649. struct timeval now;
  650. struct EXPIRY *expiry, *nexpiry;
  651. gettimeofday(&now, NULL);
  652. r = 0;
  653. num_expired = 0;
  654. expired_flows = NULL;
  655. if (verbose_flag)
  656. logit(LOG_DEBUG, "Starting expiry scan: mode %d", ex);
  657. for(expiry = EXPIRY_MIN(EXPIRIES, &ft->expiries);
  658. expiry != NULL;
  659. expiry = nexpiry) {
  660. nexpiry = EXPIRY_NEXT(EXPIRIES, &ft->expiries, expiry);
  661. if ((expiry->expires_at == 0) || (ex == CE_EXPIRE_ALL) ||
  662. (ex != CE_EXPIRE_FORCED &&
  663. (expiry->expires_at < now.tv_sec))) {
  664. /* Flow has expired */
  665. if (ft->maximum_lifetime != 0 &&
  666. expiry->flow->flow_last.tv_sec -
  667. expiry->flow->flow_start.tv_sec >=
  668. ft->maximum_lifetime)
  669. expiry->reason = R_MAXLIFE;
  670. if (verbose_flag)
  671. logit(LOG_DEBUG,
  672. "Queuing flow seq:%llu (%p) for expiry "
  673. "reason %d", expiry->flow->flow_seq,
  674. expiry->flow, expiry->reason);
  675. /* Add to array of expired flows */
  676. oldexp = expired_flows;
  677. expired_flows = realloc(expired_flows,
  678. sizeof(*expired_flows) * (num_expired + 1));
  679. /* Don't fatal on realloc failures */
  680. if (expired_flows == NULL)
  681. expired_flows = oldexp;
  682. else {
  683. expired_flows[num_expired] = expiry->flow;
  684. num_expired++;
  685. }
  686. if (ex == CE_EXPIRE_ALL)
  687. expiry->reason = R_FLUSH;
  688. update_expiry_stats(ft, expiry);
  689. /* Remove from flow tree, destroy expiry event */
  690. FLOW_REMOVE(FLOWS, &ft->flows, expiry->flow);
  691. EXPIRY_REMOVE(EXPIRIES, &ft->expiries, expiry);
  692. expiry->flow->expiry = NULL;
  693. free(expiry);
  694. ft->num_flows--;
  695. }
  696. }
  697. if (verbose_flag)
  698. logit(LOG_DEBUG, "Finished scan %d flow(s) to be evicted", num_expired);
  699. /* Processing for expired flows */
  700. if (num_expired > 0) {
  701. if (target != NULL && target->fd != -1) {
  702. r = target->dialect->func(expired_flows, num_expired,
  703. target->fd, &ft->flows_exported,
  704. &ft->system_boot_time, verbose_flag);
  705. if (verbose_flag)
  706. logit(LOG_DEBUG, "sent %d netflow packets", r);
  707. if (r > 0) {
  708. ft->packets_sent += r;
  709. /* XXX what if r < num_expired * 2 ? */
  710. } else {
  711. ft->flows_dropped += num_expired * 2;
  712. }
  713. }
  714. for (i = 0; i < num_expired; i++) {
  715. if (verbose_flag) {
  716. logit(LOG_DEBUG, "EXPIRED: %s (%p)",
  717. format_flow(expired_flows[i]),
  718. expired_flows[i]);
  719. }
  720. update_statistics(ft, expired_flows[i]);
  721. free(expired_flows[i]);
  722. }
  723. free(expired_flows);
  724. }
  725. return (r == -1 ? -1 : num_expired);
  726. }
  727. /*
  728. * Force expiry of num_to_expire flows (e.g. when flow table overfull)
  729. */
  730. static void
  731. force_expire(struct FLOWTRACK *ft, u_int32_t num_to_expire)
  732. {
  733. struct EXPIRY *expiry, **expiryv;
  734. int i;
  735. /* XXX move all overflow processing here (maybe) */
  736. if (verbose_flag)
  737. logit(LOG_INFO, "Forcing expiry of %d flows",
  738. num_to_expire);
  739. /*
  740. * Do this in two steps, as it is dangerous to change a key on
  741. * a tree entry without first removing it and then re-adding it.
  742. * It is even worse when this has to be done during a FOREACH :)
  743. * To get around this, we make a list of expired flows and _then_
  744. * alter them
  745. */
  746. if ((expiryv = calloc(num_to_expire, sizeof(*expiryv))) == NULL) {
  747. /*
  748. * On malloc failure, expire ALL flows. I assume that
  749. * setting all the keys in a tree to the same value is
  750. * safe.
  751. */
  752. logit(LOG_ERR, "Out of memory while expiring flows - "
  753. "all flows expired");
  754. EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) {
  755. expiry->expires_at = 0;
  756. expiry->reason = R_OVERFLOWS;
  757. ft->flows_force_expired++;
  758. }
  759. return;
  760. }
  761. /* Make the list of flows to expire */
  762. i = 0;
  763. EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) {
  764. if (i >= num_to_expire)
  765. break;
  766. expiryv[i++] = expiry;
  767. }
  768. if (i < num_to_expire) {
  769. logit(LOG_ERR, "Needed to expire %d flows, "
  770. "but only %d active", num_to_expire, i);
  771. num_to_expire = i;
  772. }
  773. for(i = 0; i < num_to_expire; i++) {
  774. EXPIRY_REMOVE(EXPIRIES, &ft->expiries, expiryv[i]);
  775. expiryv[i]->expires_at = 0;
  776. expiryv[i]->reason = R_OVERFLOWS;
  777. EXPIRY_INSERT(EXPIRIES, &ft->expiries, expiryv[i]);
  778. }
  779. ft->flows_force_expired += num_to_expire;
  780. free(expiryv);
  781. /* XXX - this is overcomplicated, perhaps use a separate queue */
  782. }
  783. /* Delete all flows that we know about without processing */
  784. static int
  785. delete_all_flows(struct FLOWTRACK *ft)
  786. {
  787. struct FLOW *flow, *nflow;
  788. int i;
  789. i = 0;
  790. for(flow = FLOW_MIN(FLOWS, &ft->flows); flow != NULL; flow = nflow) {
  791. nflow = FLOW_NEXT(FLOWS, &ft->flows, flow);
  792. FLOW_REMOVE(FLOWS, &ft->flows, flow);
  793. EXPIRY_REMOVE(EXPIRIES, &ft->expiries, flow->expiry);
  794. free(flow->expiry);
  795. ft->num_flows--;
  796. free(flow);
  797. i++;
  798. }
  799. return (i);
  800. }
  801. /*
  802. * Log our current status.
  803. * Includes summary counters and (in verbose mode) the list of current flows
  804. * and the tree of expiry events.
  805. */
  806. static int
  807. statistics(struct FLOWTRACK *ft, FILE *out, pcap_t *pcap)
  808. {
  809. int i;
  810. struct protoent *pe;
  811. char proto[32];
  812. struct pcap_stat ps;
  813. fprintf(out, "Number of active flows: %d\n", ft->num_flows);
  814. fprintf(out, "Packets processed: %llu\n", ft->total_packets);
  815. fprintf(out, "Fragments: %llu\n", ft->frag_packets);
  816. fprintf(out, "Ignored packets: %llu (%llu non-IP, %llu too short)\n",
  817. ft->non_ip_packets + ft->bad_packets, ft->non_ip_packets, ft->bad_packets);
  818. fprintf(out, "Flows expired: %llu (%llu forced)\n",
  819. ft->flows_expired, ft->flows_force_expired);
  820. fprintf(out, "Flows exported: %llu in %llu packets (%llu failures)\n",
  821. ft->flows_exported, ft->packets_sent, ft->flows_dropped);
  822. if (pcap_stats(pcap, &ps) == 0) {
  823. fprintf(out, "Packets received by libpcap: %lu\n",
  824. (unsigned long)ps.ps_recv);
  825. fprintf(out, "Packets dropped by libpcap: %lu\n",
  826. (unsigned long)ps.ps_drop);
  827. fprintf(out, "Packets dropped by interface: %lu\n",
  828. (unsigned long)ps.ps_ifdrop);
  829. }
  830. fprintf(out, "\n");
  831. if (ft->flows_expired != 0) {
  832. fprintf(out, "Expired flow statistics: minimum average maximum\n");
  833. fprintf(out, " Flow bytes: %12.0f %12.0f %12.0f\n",
  834. ft->octets.min, ft->octets.mean, ft->octets.max);
  835. fprintf(out, " Flow packets: %12.0f %12.0f %12.0f\n",
  836. ft->packets.min, ft->packets.mean, ft->packets.max);
  837. fprintf(out, " Duration: %12.2fs %12.2fs %12.2fs\n",
  838. ft->duration.min, ft->duration.mean, ft->duration.max);
  839. fprintf(out, "\n");
  840. fprintf(out, "Expired flow reasons:\n");
  841. fprintf(out, " tcp = %9llu tcp.rst = %9llu tcp.fin = %9llu\n",
  842. ft->expired_tcp, ft->expired_tcp_rst, ft->expired_tcp_fin);
  843. fprintf(out, " udp = %9llu icmp = %9llu general = %9llu\n",
  844. ft->expired_udp, ft->expired_icmp, ft->expired_general);
  845. fprintf(out, " maxlife = %9llu\n", ft->expired_maxlife);
  846. fprintf(out, " over 2Gb = %9llu\n", ft->expired_overbytes);
  847. fprintf(out, " maxflows = %9llu\n", ft->expired_maxflows);
  848. fprintf(out, " flushed = %9llu\n", ft->expired_flush);
  849. fprintf(out, "\n");
  850. fprintf(out, "Per-protocol statistics: Octets Packets Avg Life Max Life\n");
  851. for(i = 0; i < 256; i++) {
  852. if (ft->packets_pp[i]) {
  853. pe = getprotobynumber(i);
  854. snprintf(proto, sizeof(proto), "%s (%d)",
  855. pe != NULL ? pe->p_name : "Unknown", i);
  856. fprintf(out,
  857. " %17s: %14llu %12llu %8.2fs %10.2fs\n",
  858. proto,
  859. ft->octets_pp[i],
  860. ft->packets_pp[i],
  861. ft->duration_pp[i].mean,
  862. ft->duration_pp[i].max);
  863. }
  864. }
  865. }
  866. return (0);
  867. }
  868. static void
  869. dump_flows(struct FLOWTRACK *ft, FILE *out)
  870. {
  871. struct EXPIRY *expiry;
  872. time_t now;
  873. now = time(NULL);
  874. EXPIRY_FOREACH(expiry, EXPIRIES, &ft->expiries) {
  875. fprintf(out, "ACTIVE %s\n", format_flow(expiry->flow));
  876. if ((long int) expiry->expires_at - now < 0) {
  877. fprintf(out,
  878. "EXPIRY EVENT for flow %llu now%s\n",
  879. expiry->flow->flow_seq,
  880. expiry->expires_at == 0 ? " (FORCED)": "");
  881. } else {
  882. fprintf(out,
  883. "EXPIRY EVENT for flow %llu in %ld seconds\n",
  884. expiry->flow->flow_seq,
  885. (long int) expiry->expires_at - now);
  886. }
  887. fprintf(out, "\n");
  888. }
  889. }
  890. /*
  891. * Figure out how many bytes to skip from front of packet to get past
  892. * datalink headers. If pkt is specified, also check whether determine
  893. * whether or not it is one that we are interested in (IPv4 or IPv6 for now)
  894. *
  895. * Returns number of bytes to skip or -1 to indicate that entire
  896. * packet should be skipped
  897. */
  898. static int
  899. datalink_check(int linktype, const u_int8_t *pkt, u_int32_t caplen, int *af)
  900. {
  901. int i, j;
  902. u_int32_t frametype;
  903. static const struct DATALINK *dl = NULL;
  904. /* Try to cache last used linktype */
  905. if (dl == NULL || dl->dlt != linktype) {
  906. for (i = 0; lt[i].dlt != linktype && lt[i].dlt != -1; i++)
  907. ;
  908. dl = &lt[i];
  909. }
  910. if (dl->dlt == -1 || pkt == NULL)
  911. return (dl->dlt);
  912. if (caplen <= dl->skiplen)
  913. return (-1);
  914. /* Suck out the frametype */
  915. frametype = 0;
  916. if (dl->ft_is_be) {
  917. for (j = 0; j < dl->ft_len; j++) {
  918. frametype <<= 8;
  919. frametype |= pkt[j + dl->ft_off];
  920. }
  921. } else {
  922. for (j = dl->ft_len - 1; j >= 0 ; j--) {
  923. frametype <<= 8;
  924. frametype |= pkt[j + dl->ft_off];
  925. }
  926. }
  927. frametype &= dl->ft_mask;
  928. if (frametype == dl->ft_v4)
  929. *af = AF_INET;
  930. else if (frametype == dl->ft_v6)
  931. *af = AF_INET6;
  932. else
  933. return (-1);
  934. return (dl->skiplen);
  935. }
  936. /*
  937. * Per-packet callback function from libpcap. Pass the packet (if it is IP)
  938. * sans datalink headers to process_packet.
  939. */
  940. static void
  941. flow_cb(u_char *user_data, const struct pcap_pkthdr* phdr,
  942. const u_char *pkt)
  943. {
  944. int s, af;
  945. struct CB_CTXT *cb_ctxt = (struct CB_CTXT *)user_data;
  946. struct timeval tv;
  947. s = datalink_check(cb_ctxt->linktype, pkt, phdr->caplen, &af);
  948. if (s < 0 || (!cb_ctxt->want_v6 && af == AF_INET6)) {
  949. cb_ctxt->ft->non_ip_packets++;
  950. } else {
  951. tv.tv_sec = phdr->ts.tv_sec;
  952. tv.tv_usec = phdr->ts.tv_usec;
  953. if (process_packet(cb_ctxt->ft, pkt + s, af,
  954. phdr->caplen - s, phdr->len - s, &tv) == PP_MALLOC_FAIL)
  955. cb_ctxt->fatal = 1;
  956. }
  957. }
  958. static void
  959. print_timeouts(struct FLOWTRACK *ft, FILE *out)
  960. {
  961. fprintf(out, " TCP timeout: %ds\n", ft->tcp_timeout);
  962. fprintf(out, " TCP post-RST timeout: %ds\n", ft->tcp_rst_timeout);
  963. fprintf(out, " TCP post-FIN timeout: %ds\n", ft->tcp_fin_timeout);
  964. fprintf(out, " UDP timeout: %ds\n", ft->udp_timeout);
  965. fprintf(out, " ICMP timeout: %ds\n", ft->icmp_timeout);
  966. fprintf(out, " General timeout: %ds\n", ft->general_timeout);
  967. fprintf(out, " Maximum lifetime: %ds\n", ft->maximum_lifetime);
  968. fprintf(out, " Expiry interval: %ds\n", ft->expiry_interval);
  969. }
  970. static int
  971. accept_control(int lsock, struct NETFLOW_TARGET *target, struct FLOWTRACK *ft,
  972. pcap_t *pcap, int *exit_request, int *stop_collection_flag)
  973. {
  974. unsigned char buf[64], *p;
  975. FILE *ctlf;
  976. int fd, ret;
  977. if ((fd = accept(lsock, NULL, NULL)) == -1) {
  978. logit(LOG_ERR, "ctl accept: %s - exiting",
  979. strerror(errno));
  980. return(-1);
  981. }
  982. if ((ctlf = fdopen(fd, "r+")) == NULL) {
  983. logit(LOG_ERR, "fdopen: %s - exiting\n",
  984. strerror(errno));
  985. close(fd);
  986. return (-1);
  987. }
  988. setlinebuf(ctlf);
  989. if (fgets(buf, sizeof(buf), ctlf) == NULL) {
  990. logit(LOG_ERR, "Control socket yielded no data");
  991. return (0);
  992. }
  993. if ((p = strchr(buf, '\n')) != NULL)
  994. *p = '\0';
  995. if (verbose_flag)
  996. logit(LOG_DEBUG, "Control socket \"%s\"", buf);
  997. /* XXX - use dispatch table */
  998. ret = -1;
  999. if (strcmp(buf, "help") == 0) {
  1000. fprintf(ctlf, "Valid control words are:\n");
  1001. fprintf(ctlf, "\tdebug+ debug- delete-all dump-flows exit "
  1002. "expire-all\n");
  1003. fprintf(ctlf, "\tshutdown start-gather statistics stop-gather "
  1004. "timeouts\n");
  1005. fprintf(ctlf, "\tsend-template\n");
  1006. ret = 0;
  1007. } else if (strcmp(buf, "shutdown") == 0) {
  1008. fprintf(ctlf, "softflowd[%u]: Shutting down gracefully...\n", getpid());
  1009. graceful_shutdown_request = 1;
  1010. ret = 1;
  1011. } else if (strcmp(buf, "exit") == 0) {
  1012. fprintf(ctlf, "softflowd[%u]: Exiting now...\n", getpid());
  1013. *exit_request = 1;
  1014. ret = 1;
  1015. } else if (strcmp(buf, "expire-all") == 0) {
  1016. netflow9_resend_template();
  1017. fprintf(ctlf, "softflowd[%u]: Expired %d flows.\n", getpid(),
  1018. check_expired(ft, target, CE_EXPIRE_ALL));
  1019. ret = 0;
  1020. } else if (strcmp(buf, "send-template") == 0) {
  1021. netflow9_resend_template();
  1022. fprintf(ctlf, "softflowd[%u]: Template will be sent at "
  1023. "next flow export\n", getpid());
  1024. ret = 0;
  1025. } else if (strcmp(buf, "delete-all") == 0) {
  1026. fprintf(ctlf, "softflowd[%u]: Deleted %d flows.\n", getpid(),
  1027. delete_all_flows(ft));
  1028. ret = 0;
  1029. } else if (strcmp(buf, "statistics") == 0) {
  1030. fprintf(ctlf, "softflowd[%u]: Accumulated statistics:\n",
  1031. getpid());
  1032. statistics(ft, ctlf, pcap);
  1033. ret = 0;
  1034. } else if (strcmp(buf, "debug+") == 0) {
  1035. fprintf(ctlf, "softflowd[%u]: Debug level increased.\n",
  1036. getpid());
  1037. verbose_flag = 1;
  1038. ret = 0;
  1039. } else if (strcmp(buf, "debug-") == 0) {
  1040. fprintf(ctlf, "softflowd[%u]: Debug level decreased.\n",
  1041. getpid());
  1042. verbose_flag = 0;
  1043. ret = 0;
  1044. } else if (strcmp(buf, "stop-gather") == 0) {
  1045. fprintf(ctlf, "softflowd[%u]: Data collection stopped.\n",
  1046. getpid());
  1047. *stop_collection_flag = 1;
  1048. ret = 0;
  1049. } else if (strcmp(buf, "start-gather") == 0) {
  1050. fprintf(ctlf, "softflowd[%u]: Data collection resumed.\n",
  1051. getpid());
  1052. *stop_collection_flag = 0;
  1053. ret = 0;
  1054. } else if (strcmp(buf, "dump-flows") == 0) {
  1055. fprintf(ctlf, "softflowd[%u]: Dumping flow data:\n",
  1056. getpid());
  1057. dump_flows(ft, ctlf);
  1058. ret = 0;
  1059. } else if (strcmp(buf, "timeouts") == 0) {
  1060. fprintf(ctlf, "softflowd[%u]: Printing timeouts:\n",
  1061. getpid());
  1062. print_timeouts(ft, ctlf);
  1063. ret = 0;
  1064. } else {
  1065. fprintf(ctlf, "Unknown control commmand \"%s\"\n", buf);
  1066. ret = 0;
  1067. }
  1068. fclose(ctlf);
  1069. close(fd);
  1070. return (ret);
  1071. }
  1072. static int
  1073. connsock(struct sockaddr_storage *addr, socklen_t len, int hoplimit)
  1074. {
  1075. int s;
  1076. unsigned int h6;
  1077. unsigned char h4;
  1078. struct sockaddr_in *in4 = (struct sockaddr_in *)addr;
  1079. struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)addr;
  1080. if ((s = socket(addr->ss_family, SOCK_DGRAM, 0)) == -1) {
  1081. fprintf(stderr, "socket() error: %s\n",
  1082. strerror(errno));
  1083. exit(1);
  1084. }
  1085. if (connect(s, (struct sockaddr*)addr, len) == -1) {
  1086. fprintf(stderr, "connect() error: %s\n",
  1087. strerror(errno));
  1088. exit(1);
  1089. }
  1090. switch (addr->ss_family) {
  1091. case AF_INET:
  1092. /* Default to link-local TTL for multicast addresses */
  1093. if (hoplimit == -1 && IN_MULTICAST(in4->sin_addr.s_addr))
  1094. hoplimit = 1;
  1095. if (hoplimit == -1)
  1096. break;
  1097. h4 = hoplimit;
  1098. if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
  1099. &h4, sizeof(h4)) == -1) {
  1100. fprintf(stderr, "setsockopt(IP_MULTICAST_TTL, "
  1101. "%u): %s\n", h4, strerror(errno));
  1102. exit(1);
  1103. }
  1104. break;
  1105. case AF_INET6:
  1106. /* Default to link-local hoplimit for multicast addresses */
  1107. if (hoplimit == -1 && IN6_IS_ADDR_MULTICAST(&in6->sin6_addr))
  1108. hoplimit = 1;
  1109. if (hoplimit == -1)
  1110. break;
  1111. h6 = hoplimit;
  1112. if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
  1113. &h6, sizeof(h6)) == -1) {
  1114. fprintf(stderr, "setsockopt(IPV6_MULTICAST_HOPS, %u): "
  1115. "%s\n", h6, strerror(errno));
  1116. exit(1);
  1117. }
  1118. }
  1119. return(s);
  1120. }
  1121. static int
  1122. unix_listener(const char *path)
  1123. {
  1124. struct sockaddr_un addr;
  1125. socklen_t addrlen;
  1126. int s;
  1127. memset(&addr, '\0', sizeof(addr));
  1128. addr.sun_family = AF_UNIX;
  1129. if (strlcpy(addr.sun_path, path, sizeof(addr.sun_path)) >=
  1130. sizeof(addr.sun_path)) {
  1131. fprintf(stderr, "control socket path too long\n");
  1132. exit(1);
  1133. }
  1134. addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
  1135. addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(path) + 1;
  1136. #ifdef SOCK_HAS_LEN
  1137. addr.sun_len = addrlen;
  1138. #endif
  1139. if ((s = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
  1140. fprintf(stderr, "unix domain socket() error: %s\n",
  1141. strerror(errno));
  1142. exit(1);
  1143. }
  1144. unlink(path);
  1145. if (bind(s, (struct sockaddr*)&addr, addrlen) == -1) {
  1146. fprintf(stderr, "unix domain bind(\"%s\") error: %s\n",
  1147. addr.sun_path, strerror(errno));
  1148. exit(1);
  1149. }
  1150. if (listen(s, 64) == -1) {
  1151. fprintf(stderr, "unix domain listen() error: %s\n",
  1152. strerror(errno));
  1153. exit(1);
  1154. }
  1155. return (s);
  1156. }
  1157. static void
  1158. setup_packet_capture(struct pcap **pcap, int *linktype,
  1159. char *dev, char *capfile, char *bpf_prog, int need_v6)
  1160. {
  1161. char ebuf[PCAP_ERRBUF_SIZE];
  1162. struct bpf_program prog_c;
  1163. u_int32_t bpf_mask, bpf_net;
  1164. /* Open pcap */
  1165. if (dev != NULL) {
  1166. if ((*pcap = pcap_open_live(dev,
  1167. need_v6 ? LIBPCAP_SNAPLEN_V6 : LIBPCAP_SNAPLEN_V4,
  1168. 1, 0, ebuf)) == NULL) {
  1169. fprintf(stderr, "pcap_open_live: %s\n", ebuf);
  1170. exit(1);
  1171. }
  1172. if (pcap_lookupnet(dev, &bpf_net, &bpf_mask, ebuf) == -1)
  1173. bpf_net = bpf_mask = 0;
  1174. } else {
  1175. if ((*pcap = pcap_open_offline(capfile, ebuf)) == NULL) {
  1176. fprintf(stderr, "pcap_open_offline(%s): %s\n",
  1177. capfile, ebuf);
  1178. exit(1);
  1179. }
  1180. bpf_net = bpf_mask = 0;
  1181. }
  1182. *linktype = pcap_datalink(*pcap);
  1183. if (datalink_check(*linktype, NULL, 0, NULL) == -1) {
  1184. fprintf(stderr, "Unsupported datalink type %d\n", *linktype);
  1185. exit(1);
  1186. }
  1187. /* Attach BPF filter, if specified */
  1188. if (bpf_prog != NULL) {
  1189. if (pcap_compile(*pcap, &prog_c, bpf_prog, 1, bpf_mask) == -1) {
  1190. fprintf(stderr, "pcap_compile(\"%s\"): %s\n",
  1191. bpf_prog, pcap_geterr(*pcap));
  1192. exit(1);
  1193. }
  1194. if (pcap_setfilter(*pcap, &prog_c) == -1) {
  1195. fprintf(stderr, "pcap_setfilter: %s\n",
  1196. pcap_geterr(*pcap));
  1197. exit(1);
  1198. }
  1199. }
  1200. #ifdef BIOCLOCK
  1201. /*
  1202. * If we are reading from an device (not a file), then
  1203. * lock the underlying BPF device to prevent changes in the
  1204. * unprivileged child
  1205. */
  1206. if (dev != NULL && ioctl(pcap_fileno(*pcap), BIOCLOCK) < 0) {
  1207. fprintf(stderr, "ioctl(BIOCLOCK) failed: %s\n",
  1208. strerror(errno));
  1209. exit(1);
  1210. }
  1211. #endif
  1212. }
  1213. static void
  1214. init_flowtrack(struct FLOWTRACK *ft)
  1215. {
  1216. /* Set up flow-tracking structure */
  1217. memset(ft, '\0', sizeof(*ft));
  1218. ft->next_flow_seq = 1;
  1219. FLOW_INIT(&ft->flows);
  1220. EXPIRY_INIT(&ft->expiries);
  1221. ft->track_level = TRACK_FULL;
  1222. ft->tcp_timeout = DEFAULT_TCP_TIMEOUT;
  1223. ft->tcp_rst_timeout = DEFAULT_TCP_RST_TIMEOUT;
  1224. ft->tcp_fin_timeout = DEFAULT_TCP_FIN_TIMEOUT;
  1225. ft->udp_timeout = DEFAULT_UDP_TIMEOUT;
  1226. ft->icmp_timeout = DEFAULT_ICMP_TIMEOUT;
  1227. ft->general_timeout = DEFAULT_GENERAL_TIMEOUT;
  1228. ft->maximum_lifetime = DEFAULT_MAXIMUM_LIFETIME;
  1229. ft->expiry_interval = DEFAULT_EXPIRY_INTERVAL;
  1230. }
  1231. static char *
  1232. argv_join(int argc, char **argv)
  1233. {
  1234. int i;
  1235. size_t ret_len;
  1236. char *ret;
  1237. ret_len = 0;
  1238. ret = NULL;
  1239. for (i = 0; i < argc; i++) {
  1240. ret_len += strlen(argv[i]);
  1241. if ((ret = realloc(ret, ret_len + 2)) == NULL) {
  1242. fprintf(stderr, "Memory allocation failed.\n");
  1243. exit(1);
  1244. }
  1245. if (i == 0)
  1246. ret[0] = '\0';
  1247. else {
  1248. ret_len++; /* Make room for ' ' */
  1249. strlcat(ret, " ", ret_len + 1);
  1250. }
  1251. strlcat(ret, argv[i], ret_len + 1);
  1252. }
  1253. return (ret);
  1254. }
  1255. /* Display commandline usage information */
  1256. static void
  1257. usage(void)
  1258. {
  1259. fprintf(stderr, "Usage: %s [options] [bpf_program]\n", PROGNAME);
  1260. fprintf(stderr, "This is %s version %s. Valid commandline options:\n", PROGNAME, PROGVER);
  1261. fprintf(stderr, " -i interface Specify interface to listen on\n");
  1262. fprintf(stderr, " -r pcap_file Specify packet capture file to read\n");
  1263. fprintf(stderr, " -t timeout=time Specify named timeout\n");
  1264. fprintf(stderr, " -m max_flows Specify maximum number of flows to track (default %d)\n", DEFAULT_MAX_FLOWS);
  1265. fprintf(stderr, " -n host:port Send Cisco NetFlow(tm)-compatible packets to host:port\n");
  1266. fprintf(stderr, " -p pidfile Record pid in specified file (default: %s)\n", DEFAULT_PIDFILE);
  1267. fprintf(stderr, " -c pidfile Location of control socket (default: %s)\n", DEFAULT_CTLSOCK);
  1268. fprintf(stderr, " -v 1|5|9 NetFlow export packet version\n");
  1269. fprintf(stderr, " -L hoplimit Set TTL/hoplimit for export datagrams\n");
  1270. fprintf(stderr, " -T full|proto|ip Set flow tracking level (default: full)\n");
  1271. fprintf(stderr, " -6 Track IPv6 flows, regardless of whether selected \n"
  1272. " NetFlow export protocol supports it\n");
  1273. fprintf(stderr, " -d Don't daemonise\n");
  1274. fprintf(stderr, " -D Debug mode: don't daemonise + verbosity + track v6 flows\n");
  1275. fprintf(stderr, " -h Display this help\n");
  1276. fprintf(stderr, "\n");
  1277. fprintf(stderr, "Valid timeout names and default values:\n");
  1278. fprintf(stderr, " tcp (default %6d)", DEFAULT_TCP_TIMEOUT);
  1279. fprintf(stderr, " tcp.rst (default %6d)", DEFAULT_TCP_RST_TIMEOUT);
  1280. fprintf(stderr, " tcp.fin (default %6d)\n", DEFAULT_TCP_FIN_TIMEOUT);
  1281. fprintf(stderr, " udp (default %6d)", DEFAULT_UDP_TIMEOUT);
  1282. fprintf(stderr, " icmp (default %6d)", DEFAULT_ICMP_TIMEOUT);
  1283. fprintf(stderr, " general (default %6d)\n", DEFAULT_GENERAL_TIMEOUT);
  1284. fprintf(stderr, " maxlife (default %6d)", DEFAULT_MAXIMUM_LIFETIME);
  1285. fprintf(stderr, " expint (default %6d)\n", DEFAULT_EXPIRY_INTERVAL);
  1286. fprintf(stderr, "\n");
  1287. }
  1288. static void
  1289. set_timeout(struct FLOWTRACK *ft, const char *to_spec)
  1290. {
  1291. char *name, *value;
  1292. int timeout;
  1293. if ((name = strdup(to_spec)) == NULL) {
  1294. fprintf(stderr, "Out of memory\n");
  1295. exit(1);
  1296. }
  1297. if ((value = strchr(name, '=')) == NULL ||
  1298. *(++value) == '\0') {
  1299. fprintf(stderr, "Invalid -t option \"%s\".\n", name);
  1300. usage();
  1301. exit(1);
  1302. }
  1303. *(value - 1) = '\0';
  1304. timeout = convtime(value);
  1305. if (timeout < 0) {
  1306. fprintf(stderr, "Invalid -t timeout.\n");
  1307. usage();
  1308. exit(1);
  1309. }
  1310. if (strcmp(name, "tcp") == 0)
  1311. ft->tcp_timeout = timeout;
  1312. else if (strcmp(name, "tcp.rst") == 0)
  1313. ft->tcp_rst_timeout = timeout;
  1314. else if (strcmp(name, "tcp.fin") == 0)
  1315. ft->tcp_fin_timeout = timeout;
  1316. else if (strcmp(name, "udp") == 0)
  1317. ft->udp_timeout = timeout;
  1318. else if (strcmp(name, "icmp") == 0)
  1319. ft->icmp_timeout = timeout;
  1320. else if (strcmp(name, "general") == 0)
  1321. ft->general_timeout = timeout;
  1322. else if (strcmp(name, "maxlife") == 0)
  1323. ft->maximum_lifetime = timeout;
  1324. else if (strcmp(name, "expint") == 0)
  1325. ft->expiry_interval = timeout;
  1326. else {
  1327. fprintf(stderr, "Invalid -t name.\n");
  1328. usage();
  1329. exit(1);
  1330. }
  1331. if (ft->general_timeout == 0) {
  1332. fprintf(stderr, "\"general\" flow timeout must be "
  1333. "greater than zero\n");
  1334. exit(1);
  1335. }
  1336. free(name);
  1337. }
  1338. static void
  1339. parse_hostport(const char *s, struct sockaddr *addr, socklen_t *len)
  1340. {
  1341. char *orig, *host, *port;
  1342. struct addrinfo hints, *res;
  1343. int herr;
  1344. if ((host = orig = strdup(s)) == NULL) {
  1345. fprintf(stderr, "Out of memory\n");
  1346. exit(1);
  1347. }
  1348. if ((port = strrchr(host, ':')) == NULL ||
  1349. *(++port) == '\0' || *host == '\0') {
  1350. fprintf(stderr, "Invalid -n argument.\n");
  1351. usage();
  1352. exit(1);
  1353. }
  1354. *(port - 1) = '\0';
  1355. /* Accept [host]:port for numeric IPv6 addresses */
  1356. if (*host == '[' && *(port - 2) == ']') {
  1357. host++;
  1358. *(port - 2) = '\0';
  1359. }
  1360. memset(&hints, '\0', sizeof(hints));
  1361. hints.ai_socktype = SOCK_DGRAM;
  1362. if ((herr = getaddrinfo(host, port, &hints, &res)) == -1) {
  1363. fprintf(stderr, "Address lookup failed: %s\n",
  1364. gai_strerror(herr));
  1365. exit(1);
  1366. }
  1367. if (res == NULL || res->ai_addr == NULL) {
  1368. fprintf(stderr, "No addresses found for [%s]:%s\n", host, port);
  1369. exit(1);
  1370. }
  1371. if (res->ai_addrlen > *len) {
  1372. fprintf(stderr, "Address too long\n");
  1373. exit(1);
  1374. }
  1375. memcpy(addr, res->ai_addr, res->ai_addrlen);
  1376. free(orig);
  1377. *len = res->ai_addrlen;
  1378. }
  1379. /*
  1380. * Drop privileges and chroot, will exit on failure
  1381. */
  1382. static void
  1383. drop_privs(void)
  1384. {
  1385. struct passwd *pw;
  1386. if ((pw = getpwnam(PRIVDROP_USER)) == NULL) {
  1387. logit(LOG_ERR, "Unable to find unprivileged user \"%s\"",
  1388. PRIVDROP_USER);
  1389. exit(1);
  1390. }
  1391. if (chdir(PRIVDROP_CHROOT_DIR) != 0) {
  1392. logit(LOG_ERR, "Unable to chdir to chroot directory \"%s\": %s",
  1393. PRIVDROP_CHROOT_DIR, strerror(errno));
  1394. exit(1);
  1395. }
  1396. if (chroot(PRIVDROP_CHROOT_DIR) != 0) {
  1397. logit(LOG_ERR, "Unable to chroot to directory \"%s\": %s",
  1398. PRIVDROP_CHROOT_DIR, strerror(errno));
  1399. exit(1);
  1400. }
  1401. if (chdir("/") != 0) {
  1402. logit(LOG_ERR, "Unable to chdir to chroot root: %s",
  1403. strerror(errno));
  1404. exit(1);
  1405. }
  1406. if (setgroups(1, &pw->pw_gid) != 0) {
  1407. logit(LOG_ERR, "Couldn't setgroups (%u): %s",
  1408. (unsigned int)pw->pw_gid, strerror(errno));
  1409. exit(1);
  1410. }
  1411. #if defined(HAVE_SETRESGID)
  1412. if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
  1413. #elif defined(HAVE_SETREGID)
  1414. if (setregid(pw->pw_gid, pw->pw_gid) == -1) {
  1415. #else
  1416. if (setegid(pw->pw_gid) == -1 || setgid(pw->pw_gid) == -1) {
  1417. #endif
  1418. logit(LOG_ERR, "Couldn't set gid (%u): %s",
  1419. (unsigned int)pw->pw_gid, strerror(errno));
  1420. exit(1);
  1421. }
  1422. #if defined(HAVE_SETRESUID)
  1423. if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
  1424. #elif defined(HAVE_SETREUID)
  1425. if (setreuid(pw->pw_uid, pw->pw_uid) == -1) {
  1426. #else
  1427. if (seteuid(pw->pw_uid) == -1 || setuid(pw->pw_uid) == -1) {
  1428. #endif
  1429. logit(LOG_ERR, "Couldn't set uid (%u): %s",
  1430. (unsigned int)pw->pw_uid, strerror(errno));
  1431. exit(1);
  1432. }
  1433. }
  1434. int
  1435. main(int argc, char **argv)
  1436. {
  1437. char *dev, *capfile, *bpf_prog, dest_addr[256], dest_serv[256];
  1438. const char *pidfile_path, *ctlsock_path;
  1439. extern char *optarg;
  1440. extern int optind;
  1441. int ch, dontfork_flag, linktype, ctlsock, i, r, err, always_v6;
  1442. int max_flows, stop_collection_flag, exit_request, hoplimit;
  1443. pcap_t *pcap = NULL;
  1444. struct sockaddr_storage dest;
  1445. struct FLOWTRACK flowtrack;
  1446. socklen_t dest_len;
  1447. struct NETFLOW_TARGET target;
  1448. struct CB_CTXT cb_ctxt;
  1449. struct pollfd pl[2];
  1450. closefrom(STDERR_FILENO + 1);
  1451. init_flowtrack(&flowtrack);
  1452. memset(&dest, '\0', sizeof(dest));
  1453. memset(&target, '\0', sizeof(target));
  1454. target.fd = -1;
  1455. target.dialect = &nf[0];
  1456. hoplimit = -1;
  1457. bpf_prog = NULL;
  1458. ctlsock = -1;
  1459. dev = capfile = NULL;
  1460. max_flows = DEFAULT_MAX_FLOWS;
  1461. pidfile_path = DEFAULT_PIDFILE;
  1462. ctlsock_path = DEFAULT_CTLSOCK;
  1463. dontfork_flag = 0;
  1464. always_v6 = 0;
  1465. while ((ch = getopt(argc, argv, "6hdDL:T:i:r:f:t:n:m:p:c:v:")) != -1) {
  1466. switch (ch) {
  1467. case '6':
  1468. always_v6 = 1;
  1469. break;
  1470. case 'h':
  1471. usage();
  1472. return (0);
  1473. case 'D':
  1474. verbose_flag = 1;
  1475. always_v6 = 1;
  1476. /* FALLTHROUGH */
  1477. case 'd':
  1478. dontfork_flag = 1;
  1479. break;
  1480. case 'i':
  1481. if (capfile != NULL || dev != NULL) {
  1482. fprintf(stderr, "Packet source already specified.\n\n");
  1483. usage();
  1484. exit(1);
  1485. }
  1486. dev = optarg;
  1487. break;
  1488. case 'r':
  1489. if (capfile != NULL || dev != NULL) {
  1490. fprintf(stderr, "Packet source already specified.\n\n");
  1491. usage();
  1492. exit(1);
  1493. }
  1494. capfile = optarg;
  1495. dontfork_flag = 1;
  1496. ctlsock_path = NULL;
  1497. break;
  1498. case 't':
  1499. /* Will exit on failure */
  1500. set_timeout(&flowtrack, optarg);
  1501. break;
  1502. case 'T':
  1503. if (strcasecmp(optarg, "full") == 0)
  1504. flowtrack.track_level = TRACK_FULL;
  1505. else if (strcasecmp(optarg, "proto") == 0)
  1506. flowtrack.track_level = TRACK_IP_PROTO;
  1507. else if (strcasecmp(optarg, "ip") == 0)
  1508. flowtrack.track_level = TRACK_IP_ONLY;
  1509. else {
  1510. fprintf(stderr, "Unknown flow tracking level\n");
  1511. usage();
  1512. exit(1);
  1513. }
  1514. break;
  1515. case 'L':
  1516. hoplimit = atoi(optarg);
  1517. if (hoplimit < 0 || hoplimit > 255) {
  1518. fprintf(stderr, "Invalid hop limit\n\n");
  1519. usage();
  1520. exit(1);
  1521. }
  1522. break;
  1523. case 'm':
  1524. if ((max_flows = atoi(optarg)) < 0) {
  1525. fprintf(stderr, "Invalid maximum flows\n\n");
  1526. usage();
  1527. exit(1);
  1528. }
  1529. break;
  1530. case 'n':
  1531. /* Will exit on failure */
  1532. dest_len = sizeof(dest);
  1533. parse_hostport(optarg, (struct sockaddr *)&dest,
  1534. &dest_len);
  1535. break;
  1536. case 'p':
  1537. pidfile_path = optarg;
  1538. break;
  1539. case 'c':
  1540. if (strcmp(optarg, "none") == 0)
  1541. ctlsock_path = NULL;
  1542. else
  1543. ctlsock_path = optarg;
  1544. break;
  1545. case 'v':
  1546. for(i = 0, r = atoi(optarg); nf[i].version != -1; i++) {
  1547. if (nf[i].version == r)
  1548. break;
  1549. }
  1550. if (nf[i].version == -1) {
  1551. fprintf(stderr, "Invalid NetFlow version\n");
  1552. exit(1);
  1553. }
  1554. target.dialect = &nf[i];
  1555. break;
  1556. default:
  1557. fprintf(stderr, "Invalid commandline option.\n");
  1558. usage();
  1559. exit(1);
  1560. }
  1561. }
  1562. if (capfile == NULL && dev == NULL) {
  1563. fprintf(stderr, "-i or -r option not specified.\n");
  1564. usage();
  1565. exit(1);
  1566. }
  1567. /* join remaining arguments (if any) into bpf program */
  1568. bpf_prog = argv_join(argc - optind, argv + optind);
  1569. /* Will exit on failure */
  1570. setup_packet_capture(&pcap, &linktype, dev, capfile, bpf_prog,
  1571. target.dialect->v6_capable || always_v6);
  1572. /* Netflow send socket */
  1573. if (dest.ss_family != 0) {
  1574. if ((err = getnameinfo((struct sockaddr *)&dest,
  1575. dest_len, dest_addr, sizeof(dest_addr),
  1576. dest_serv, sizeof(dest_serv), NI_NUMERICHOST)) == -1) {
  1577. fprintf(stderr, "getnameinfo: %d\n", err);
  1578. exit(1);
  1579. }
  1580. target.fd = connsock(&dest, dest_len, hoplimit);
  1581. }
  1582. /* Control socket */
  1583. if (ctlsock_path != NULL)
  1584. ctlsock = unix_listener(ctlsock_path); /* Will exit on fail */
  1585. if (dontfork_flag) {
  1586. loginit(PROGNAME, 1);
  1587. } else {
  1588. FILE *pidfile;
  1589. daemon(0, 0);
  1590. loginit(PROGNAME, 0);
  1591. if ((pidfile = fopen(pidfile_path, "w")) == NULL) {
  1592. fprintf(stderr, "Couldn't open pidfile %s: %s\n",
  1593. pidfile_path, strerror(errno));
  1594. exit(1);
  1595. }
  1596. fprintf(pidfile, "%u\n", getpid());
  1597. fclose(pidfile);
  1598. signal(SIGINT, sighand_graceful_shutdown);
  1599. signal(SIGTERM, sighand_graceful_shutdown);
  1600. signal(SIGSEGV, sighand_other);
  1601. setprotoent(1);
  1602. drop_privs();
  1603. }
  1604. logit(LOG_NOTICE, "%s v%s starting data collection",
  1605. PROGNAME, PROGVER);
  1606. if (dest.ss_family != 0) {
  1607. logit(LOG_NOTICE, "Exporting flows to [%s]:%s",
  1608. dest_addr, dest_serv);
  1609. }
  1610. /* Main processing loop */
  1611. gettimeofday(&flowtrack.system_boot_time, NULL);
  1612. stop_collection_flag = 0;
  1613. memset(&cb_ctxt, '\0', sizeof(cb_ctxt));
  1614. cb_ctxt.ft = &flowtrack;
  1615. cb_ctxt.linktype = linktype;
  1616. cb_ctxt.want_v6 = target.dialect->v6_capable || always_v6;
  1617. while (!graceful_shutdown_request) {
  1618. /*
  1619. * Silly libpcap's timeout function doesn't work, so we
  1620. * do it here (only if we are reading live)
  1621. */
  1622. r = 0;
  1623. if (capfile == NULL) {
  1624. memset(pl, '\0', sizeof(pl));
  1625. /* This can only be set via the control socket */
  1626. if (!stop_collection_flag) {
  1627. pl[0].events = POLLIN|POLLERR|POLLHUP;
  1628. pl[0].fd = pcap_fileno(pcap);
  1629. }
  1630. if (ctlsock != -1) {
  1631. pl[1].fd = ctlsock;
  1632. pl[1].events = POLLIN|POLLERR|POLLHUP;
  1633. }
  1634. r = poll(pl, (ctlsock == -1) ? 1 : 2,
  1635. next_expire(&flowtrack));
  1636. if (r == -1 && errno != EINTR) {
  1637. logit(LOG_ERR, "Exiting on poll: %s",
  1638. strerror(errno));
  1639. break;
  1640. }
  1641. }
  1642. /* Accept connection on control socket if present */
  1643. if (ctlsock != -1 && pl[1].revents != 0) {
  1644. if (accept_control(ctlsock, &target, &flowtrack, pcap,
  1645. &exit_request, &stop_collection_flag) != 0)
  1646. break;
  1647. }
  1648. /* If we have data, run it through libpcap */
  1649. if (!stop_collection_flag &&
  1650. (capfile != NULL || pl[0].revents != 0)) {
  1651. r = pcap_dispatch(pcap, max_flows, flow_cb, (void*)&cb_ctxt);
  1652. if (r == -1) {
  1653. logit(LOG_ERR, "Exiting on pcap_dispatch: %s",
  1654. pcap_geterr(pcap));
  1655. break;
  1656. } else if (r == 0) {
  1657. logit(LOG_NOTICE, "Shutting down after pcap EOF");
  1658. graceful_shutdown_request = 1;
  1659. break;
  1660. }
  1661. }
  1662. r = 0;
  1663. /* Fatal error from per-packet functions */
  1664. if (cb_ctxt.fatal) {
  1665. logit(LOG_WARNING, "Fatal error - exiting immediately");
  1666. break;
  1667. }
  1668. /*
  1669. * Expiry processing happens every recheck_rate seconds
  1670. * or whenever we have exceeded the maximum number of active
  1671. * flows
  1672. */
  1673. if (flowtrack.num_flows > max_flows ||
  1674. next_expire(&flowtrack) == 0) {
  1675. expiry_check:
  1676. /*
  1677. * If we are reading from a capture file, we never
  1678. * expire flows based on time - instead we only
  1679. * expire flows when the flow table is full.
  1680. */
  1681. if (check_expired(&flowtrack, &target,
  1682. capfile == NULL ? CE_EXPIRE_NORMAL : CE_EXPIRE_FORCED) < 0)
  1683. logit(LOG_WARNING, "Unable to export flows");
  1684. /*
  1685. * If we are over max_flows, force-expire the oldest
  1686. * out first and immediately reprocess to evict them
  1687. */
  1688. if (flowtrack.num_flows > max_flows) {
  1689. force_expire(&flowtrack, flowtrack.num_flows - max_flows);
  1690. goto expiry_check;
  1691. }
  1692. }
  1693. }
  1694. /* Flags set by signal handlers or control socket */
  1695. if (graceful_shutdown_request) {
  1696. logit(LOG_WARNING, "Shutting down on user request");
  1697. check_expired(&flowtrack, &target, CE_EXPIRE_ALL);
  1698. } else if (exit_request)
  1699. logit(LOG_WARNING, "Exiting immediately on user request");
  1700. else
  1701. logit(LOG_ERR, "Exiting immediately on internal error");
  1702. if (capfile != NULL && dontfork_flag)
  1703. statistics(&flowtrack, stdout, pcap);
  1704. pcap_close(pcap);
  1705. if (target.fd != -1)
  1706. close(target.fd);
  1707. unlink(pidfile_path);
  1708. if (ctlsock_path != NULL)
  1709. unlink(ctlsock_path);
  1710. return(r == 0 ? 0 : 1);
  1711. }