2 * This program is is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or (at
5 * your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * @brief Capture, filter, and generate statistics for RADIUS traffic
22 * @copyright 2013 Arran Cudbard-Bell <a.cudbardb@freeradius.org>
23 * @copyright 2006 The FreeRADIUS server project
24 * @copyright 2006 Nicolas Baradakis <nicolas.baradakis@cegetel.net>
32 #include <freeradius-devel/libradius.h>
33 #include <freeradius-devel/event.h>
35 #include <freeradius-devel/radpaths.h>
36 #include <freeradius-devel/conf.h>
37 #include <freeradius-devel/pcap.h>
38 #include <freeradius-devel/radsniff.h>
40 #ifdef HAVE_COLLECTDC_H
41 # include <collectd/client.h>
44 #define RS_ASSERT(_x) if (!(_x) && !fr_assert(_x)) exit(1)
47 static struct timeval start_pcap = {0, 0};
48 static char timestr[50];
50 static rbtree_t *request_tree = NULL;
51 static rbtree_t *link_tree = NULL;
52 static fr_event_list_t *events;
55 static int self_pipe[2] = {-1, -1}; //!< Signals from sig handlers
57 typedef int (*rbcmp)(void const *, void const *);
59 static char const *radsniff_version = "radsniff version " RADIUSD_VERSION_STRING
60 #ifdef RADIUSD_VERSION_COMMIT
61 " (git #" STRINGIFY(RADIUSD_VERSION_COMMIT) ")"
63 ", built on " __DATE__ " at " __TIME__;
65 static int rs_useful_codes[] = {
66 PW_CODE_ACCESS_REQUEST, //!< RFC2865 - Authentication request
67 PW_CODE_ACCESS_ACCEPT, //!< RFC2865 - Access-Accept
68 PW_CODE_ACCESS_REJECT, //!< RFC2865 - Access-Reject
69 PW_CODE_ACCOUNTING_REQUEST, //!< RFC2866 - Accounting-Request
70 PW_CODE_ACCOUNTING_RESPONSE, //!< RFC2866 - Accounting-Response
71 PW_CODE_ACCESS_CHALLENGE, //!< RFC2865 - Access-Challenge
72 PW_CODE_STATUS_SERVER, //!< RFC2865/RFC5997 - Status Server (request)
73 PW_CODE_STATUS_CLIENT, //!< RFC2865/RFC5997 - Status Server (response)
74 PW_CODE_DISCONNECT_REQUEST, //!< RFC3575/RFC5176 - Disconnect-Request
75 PW_CODE_DISCONNECT_ACK, //!< RFC3575/RFC5176 - Disconnect-Ack (positive)
76 PW_CODE_DISCONNECT_NAK, //!< RFC3575/RFC5176 - Disconnect-Nak (not willing to perform)
77 PW_CODE_COA_REQUEST, //!< RFC3575/RFC5176 - CoA-Request
78 PW_CODE_COA_ACK, //!< RFC3575/RFC5176 - CoA-Ack (positive)
79 PW_CODE_COA_NAK, //!< RFC3575/RFC5176 - CoA-Nak (not willing to perform)
82 static const FR_NAME_NUMBER rs_events[] = {
83 { "received", RS_NORMAL },
86 { "noreq", RS_UNLINKED },
87 { "reused", RS_REUSED },
88 { "error", RS_ERROR },
92 static void NEVER_RETURNS usage(int status);
94 /** Fork and kill the parent process, writing out our PID
96 * @param pidfile the PID file to write our PID to
98 static void rs_daemonize(char const *pidfile)
118 * Continue as the child.
121 /* Create a new SID for the child process */
128 * Change the current working directory. This prevents the current
129 * directory from being locked; hence not being able to remove it.
131 if ((chdir("/")) < 0) {
136 * And write it AFTER we've forked, so that we write the
139 fp = fopen(pidfile, "w");
141 fprintf(fp, "%d\n", (int) sid);
144 ERROR("Failed creating PID file %s: %s", pidfile, fr_syserror(errno));
149 * Close stdout and stderr if they've not been redirected.
151 if (isatty(fileno(stdout))) {
152 if (!freopen("/dev/null", "w", stdout)) {
157 if (isatty(fileno(stderr))) {
158 if (!freopen("/dev/null", "w", stderr)) {
165 static void rs_tv_sub(struct timeval const *end, struct timeval const *start, struct timeval *elapsed)
167 elapsed->tv_sec = end->tv_sec - start->tv_sec;
168 if (elapsed->tv_sec > 0) {
170 elapsed->tv_usec = USEC;
172 elapsed->tv_usec = 0;
174 elapsed->tv_usec += end->tv_usec;
175 elapsed->tv_usec -= start->tv_usec;
177 if (elapsed->tv_usec >= USEC) {
178 elapsed->tv_usec -= USEC;
183 static void rs_tv_add_ms(struct timeval const *start, unsigned long interval, struct timeval *result) {
184 result->tv_sec = start->tv_sec + (interval / 1000);
185 result->tv_usec = start->tv_usec + ((interval % 1000) * 1000);
187 if (result->tv_usec > USEC) {
188 result->tv_usec -= USEC;
193 static void rs_time_print(char *out, size_t len, struct timeval const *t)
200 gettimeofday(&now, NULL);
204 ret = strftime(out, len, "%Y-%m-%d %H:%M:%S", localtime(&t->tv_sec));
212 while (usec < 100000) usec *= 10;
213 snprintf(out + ret, len - ret, ".%i", usec);
215 snprintf(out + ret, len - ret, ".000000");
219 static size_t rs_prints_csv(char *out, size_t outlen, char const *in, size_t inlen)
221 char const *start = out;
222 uint8_t const *str = (uint8_t const *) in;
236 while ((inlen > 0) && (outlen > 2)) {
238 * Escape double quotes with... MORE DOUBLE QUOTES!
246 * Safe chars which require no escaping
248 if ((*str == '\r') || (*str == '\n') || ((*str >= '\x20') && (*str <= '\x7E'))) {
257 * Everything else is dropped
267 static void rs_packet_print_csv_header(void)
273 ssize_t len, s = sizeof(buffer);
275 len = strlcpy(p, "\"Status\",\"Count\",\"Time\",\"Latency\",\"Type\",\"Interface\","
276 "\"Src IP\",\"Src Port\",\"Dst IP\",\"Dst Port\",\"ID\",", s);
282 for (i = 0; i < conf->list_da_num; i++) {
289 for (in = conf->list_da[i]->name; *in; in++) {
305 fprintf(stdout , "%s\n", buffer);
308 static void rs_packet_print_csv(uint64_t count, rs_status_t status, fr_pcap_t *handle, RADIUS_PACKET *packet,
309 UNUSED struct timeval *elapsed, struct timeval *latency, UNUSED bool response,
312 char const *status_str;
316 char src[INET6_ADDRSTRLEN];
317 char dst[INET6_ADDRSTRLEN];
319 ssize_t len, s = sizeof(buffer);
321 inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr, src, sizeof(src));
322 inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr, dst, sizeof(dst));
324 status_str = fr_int2str(rs_events, status, NULL);
325 RS_ASSERT(status_str);
327 len = snprintf(p, s, "%s,%" PRIu64 ",%s,", status_str, count, timestr);
334 len = snprintf(p, s, "%u.%03u,",
335 (unsigned int) latency->tv_sec, ((unsigned int) latency->tv_usec / 1000));
346 /* Status, Type, Interface, Src, Src port, Dst, Dst port, ID */
347 if (is_radius_code(packet->code)) {
348 len = snprintf(p, s, "%s,%s,%s,%i,%s,%i,%i,", fr_packet_codes[packet->code], handle->name,
349 src, packet->src_port, dst, packet->dst_port, packet->id);
351 len = snprintf(p, s, "%u,%s,%s,%i,%s,%i,%i,", packet->code, handle->name,
352 src, packet->src_port, dst, packet->dst_port, packet->id);
363 for (i = 0; i < conf->list_da_num; i++) {
364 vp = fr_pair_find_by_da(packet->vps, conf->list_da[i], TAG_ANY);
365 if (vp && (vp->vp_length > 0)) {
366 if (conf->list_da[i]->type == PW_TYPE_STRING) {
371 len = rs_prints_csv(p, s, vp->vp_strvalue, vp->vp_length);
380 len = vp_prints_value(p, s, vp, 0);
392 s -= conf->list_da_num;
395 memset(p, ',', conf->list_da_num);
396 p += conf->list_da_num;
400 fprintf(stdout , "%s\n", buffer);
403 static void rs_packet_print_fancy(uint64_t count, rs_status_t status, fr_pcap_t *handle, RADIUS_PACKET *packet,
404 struct timeval *elapsed, struct timeval *latency, bool response, bool body)
409 char src[INET6_ADDRSTRLEN];
410 char dst[INET6_ADDRSTRLEN];
412 ssize_t len, s = sizeof(buffer);
414 inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr, src, sizeof(src));
415 inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr, dst, sizeof(dst));
417 /* Only print out status str if something's not right */
418 if (status != RS_NORMAL) {
419 char const *status_str;
421 status_str = fr_int2str(rs_events, status, NULL);
422 RS_ASSERT(status_str);
424 len = snprintf(p, s, "** %s ** ", status_str);
430 if (is_radius_code(packet->code)) {
431 len = snprintf(p, s, "%s Id %i %s:%s:%d %s %s:%i ",
432 fr_packet_codes[packet->code],
435 response ? dst : src,
436 response ? packet->dst_port : packet->src_port,
437 response ? "<-" : "->",
438 response ? src : dst ,
439 response ? packet->src_port : packet->dst_port);
441 len = snprintf(p, s, "%u Id %i %s:%s:%i %s %s:%i ",
445 response ? dst : src,
446 response ? packet->dst_port : packet->src_port,
447 response ? "<-" : "->",
448 response ? src : dst ,
449 response ? packet->src_port : packet->dst_port);
456 len = snprintf(p, s, "+%u.%03u ",
457 (unsigned int) elapsed->tv_sec, ((unsigned int) elapsed->tv_usec / 1000));
464 len = snprintf(p, s, "+%u.%03u ",
465 (unsigned int) latency->tv_sec, ((unsigned int) latency->tv_usec / 1000));
473 RIDEBUG("%s", buffer);
477 * Print out verbose HEX output
479 if (conf->print_packet && (fr_debug_lvl > 3)) {
480 rad_print_hex(packet);
483 if (conf->print_packet && (fr_debug_lvl > 1)) {
484 char vector[(AUTH_VECTOR_LEN * 2) + 1];
487 fr_pair_list_sort(&packet->vps, fr_pair_cmp_by_da_tag);
488 vp_printlist(fr_log_fp, packet->vps);
491 fr_bin2hex(vector, packet->vector, AUTH_VECTOR_LEN);
492 INFO("\tAuthenticator-Field = 0x%s", vector);
497 static inline void rs_packet_print(rs_request_t *request, uint64_t count, rs_status_t status, fr_pcap_t *handle,
498 RADIUS_PACKET *packet, struct timeval *elapsed, struct timeval *latency,
499 bool response, bool body)
501 if (!conf->logger) return;
503 if (request) request->logged = true;
504 conf->logger(count, status, handle, packet, elapsed, latency, response, body);
507 static void rs_stats_print(rs_latency_t *stats, PW_CODE code)
510 bool have_rt = false;
512 for (i = 0; i <= RS_RETRANSMIT_MAX; i++) {
513 if (stats->interval.rt[i]) {
518 if (!stats->interval.received && !have_rt && !stats->interval.reused) {
522 if (stats->interval.received || stats->interval.linked) {
523 INFO("%s counters:", fr_packet_codes[code]);
524 if (stats->interval.received > 0) {
525 INFO("\tTotal : %.3lf/s" , stats->interval.received);
529 if (stats->interval.linked > 0) {
530 INFO("\tLinked : %.3lf/s", stats->interval.linked);
531 INFO("\tUnlinked : %.3lf/s", stats->interval.unlinked);
532 INFO("%s latency:", fr_packet_codes[code]);
533 INFO("\tHigh : %.3lfms", stats->interval.latency_high);
534 INFO("\tLow : %.3lfms", stats->interval.latency_low);
535 INFO("\tAverage : %.3lfms", stats->interval.latency_average);
536 INFO("\tMA : %.3lfms", stats->latency_smoothed);
539 if (have_rt || stats->interval.lost || stats->interval.reused) {
540 INFO("%s retransmits & loss:", fr_packet_codes[code]);
542 if (stats->interval.lost) {
543 INFO("\tLost : %.3lf/s", stats->interval.lost);
546 if (stats->interval.reused) {
547 INFO("\tID Reused : %.3lf/s", stats->interval.reused);
550 for (i = 0; i <= RS_RETRANSMIT_MAX; i++) {
551 if (!stats->interval.rt[i]) {
555 if (i != RS_RETRANSMIT_MAX) {
556 INFO("\tRT (%i) : %.3lf/s", i, stats->interval.rt[i]);
558 INFO("\tRT (%i+) : %.3lf/s", i, stats->interval.rt[i]);
564 /** Query libpcap to see if it dropped any packets
566 * We need to check to see if libpcap dropped any packets and if it did, we need to stop stats output for long
567 * enough for inaccurate statistics to be cleared out.
569 * @param in pcap handle to check.
570 * @param interval time between checks (used for debug output)
571 * @return 0, no drops, -1 we couldn't check, -2 dropped because of buffer exhaustion, -3 dropped because of NIC.
573 static int rs_check_pcap_drop(fr_pcap_t *in, int interval) {
575 struct pcap_stat pstats;
577 if (pcap_stats(in->handle, &pstats) != 0) {
578 ERROR("%s failed retrieving pcap stats: %s", in->name, pcap_geterr(in->handle));
582 INFO("\t%s%*s: %.3lf/s", in->name, (int) (10 - strlen(in->name)), "",
583 ((double) (pstats.ps_recv - in->pstats.ps_recv)) / interval);
585 if (pstats.ps_drop - in->pstats.ps_drop > 0) {
586 ERROR("%s dropped %i packets: Buffer exhaustion", in->name, pstats.ps_drop - in->pstats.ps_drop);
590 if (pstats.ps_ifdrop - in->pstats.ps_ifdrop > 0) {
591 ERROR("%s dropped %i packets: Interface", in->name, pstats.ps_ifdrop - in->pstats.ps_ifdrop);
600 /** Update smoothed average
603 static void rs_stats_process_latency(rs_latency_t *stats)
606 * If we didn't link any packets during this interval, we don't have a value to return.
607 * returning 0 is misleading as it would be like saying the latency had dropped to 0.
608 * We instead set NaN which libcollectd converts to a 'U' or unknown value.
610 * This will cause gaps in graphs, but is completely legitimate as we are missing data.
611 * This is unfortunately an effect of being just a passive observer.
613 if (stats->interval.linked_total == 0) {
614 double unk = strtod("NAN()", (char **) NULL);
616 stats->interval.latency_average = unk;
617 stats->interval.latency_high = unk;
618 stats->interval.latency_low = unk;
621 * We've not yet been able to determine latency, so latency_smoothed is also NaN
623 if (stats->latency_smoothed_count == 0) {
624 stats->latency_smoothed = unk;
629 if (stats->interval.linked_total && stats->interval.latency_total) {
630 stats->interval.latency_average = (stats->interval.latency_total / stats->interval.linked_total);
633 if (isnan(stats->latency_smoothed)) {
634 stats->latency_smoothed = 0;
636 if (stats->interval.latency_average > 0) {
637 stats->latency_smoothed_count++;
638 stats->latency_smoothed += ((stats->interval.latency_average - stats->latency_smoothed) /
639 ((stats->latency_smoothed_count < 100) ? stats->latency_smoothed_count : 100));
643 static void rs_stats_process_counters(rs_latency_t *stats)
647 stats->interval.received = ((long double) stats->interval.received_total) / conf->stats.interval;
648 stats->interval.linked = ((long double) stats->interval.linked_total) / conf->stats.interval;
649 stats->interval.unlinked = ((long double) stats->interval.unlinked_total) / conf->stats.interval;
650 stats->interval.reused = ((long double) stats->interval.reused_total) / conf->stats.interval;
651 stats->interval.lost = ((long double) stats->interval.lost_total) / conf->stats.interval;
653 for (i = 0; i < RS_RETRANSMIT_MAX; i++) {
654 stats->interval.rt[i] = ((long double) stats->interval.rt_total[i]) / conf->stats.interval;
658 /** Process stats for a single interval
661 static void rs_stats_process(void *ctx)
664 size_t rs_codes_len = (sizeof(rs_useful_codes) / sizeof(*rs_useful_codes));
666 rs_update_t *this = ctx;
667 rs_stats_t *stats = this->stats;
670 gettimeofday(&now, NULL);
674 INFO("######### Stats Iteration %i #########", stats->intervals);
677 * Verify that none of the pcap handles have dropped packets.
679 INFO("Interface capture rate:");
680 for (in_p = this->in;
683 if (rs_check_pcap_drop(in_p, conf->stats.interval) < 0) {
684 ERROR("Muting stats for the next %i milliseconds", conf->stats.timeout);
686 rs_tv_add_ms(&now, conf->stats.timeout, &stats->quiet);
691 if ((stats->quiet.tv_sec + (stats->quiet.tv_usec / 1000000.0)) -
692 (now.tv_sec + (now.tv_usec / 1000000.0)) > 0) {
693 INFO("Stats muted because of warmup, or previous error");
698 * Latency stats need a bit more work to calculate the SMA.
700 * No further work is required for codes.
702 for (i = 0; i < rs_codes_len; i++) {
703 rs_stats_process_latency(&stats->exchange[rs_useful_codes[i]]);
704 rs_stats_process_counters(&stats->exchange[rs_useful_codes[i]]);
705 if (fr_debug_lvl > 0) {
706 rs_stats_print(&stats->exchange[rs_useful_codes[i]], rs_useful_codes[i]);
710 #ifdef HAVE_COLLECTDC_H
712 * Update stats in collectd using the complex structures we
713 * initialised earlier.
715 if ((conf->stats.out == RS_STATS_OUT_COLLECTD) && conf->stats.handle) {
716 rs_stats_collectd_do_stats(conf, conf->stats.tmpl, &now);
722 * Rinse and repeat...
724 for (i = 0; i < rs_codes_len; i++) {
725 memset(&stats->exchange[rs_useful_codes[i]].interval, 0,
726 sizeof(stats->exchange[rs_useful_codes[i]].interval));
730 static fr_event_t *event;
732 now.tv_sec += conf->stats.interval;
735 if (!fr_event_insert(this->list, rs_stats_process, ctx, &now, &event)) {
736 ERROR("Failed inserting stats interval event");
742 /** Update latency statistics for request/response and forwarded packets
745 static void rs_stats_update_latency(rs_latency_t *stats, struct timeval *latency)
749 stats->interval.linked_total++;
750 /* More useful is this in milliseconds */
751 lint = (latency->tv_sec + (latency->tv_usec / 1000000.0)) * 1000;
752 if (lint > stats->interval.latency_high) {
753 stats->interval.latency_high = lint;
755 if (!stats->interval.latency_low || (lint < stats->interval.latency_low)) {
756 stats->interval.latency_low = lint;
758 stats->interval.latency_total += lint;
762 /** Copy a subset of attributes from one list into the other
764 * Should be O(n) if all the attributes exist. List must be pre-sorted.
766 static int rs_get_pairs(TALLOC_CTX *ctx, VALUE_PAIR **out, VALUE_PAIR *vps, DICT_ATTR const *da[], int num)
768 vp_cursor_t list_cursor, out_cursor;
769 VALUE_PAIR *match, *last_match, *copy;
775 fr_cursor_init(&list_cursor, &last_match);
776 fr_cursor_init(&out_cursor, out);
777 for (i = 0; i < num; i++) {
778 match = fr_cursor_next_by_da(&list_cursor, da[i], TAG_ANY);
780 fr_cursor_init(&list_cursor, &last_match);
785 copy = fr_pair_copy(ctx, match);
787 fr_pair_list_free(out);
790 fr_cursor_insert(&out_cursor, copy);
794 } while ((match = fr_cursor_next_by_da(&list_cursor, da[i], TAG_ANY)));
800 static int _request_free(rs_request_t *request)
805 * If were attempting to cleanup the request, and it's no longer in the request_tree
806 * something has gone very badly wrong.
808 if (request->in_request_tree) {
809 ret = rbtree_deletebydata(request_tree, request);
813 if (request->in_link_tree) {
814 ret = rbtree_deletebydata(link_tree, request);
818 if (request->event) {
819 ret = fr_event_delete(events, &request->event);
823 rad_free(&request->packet);
824 rad_free(&request->expect);
825 rad_free(&request->linked);
830 static void rs_packet_cleanup(rs_request_t *request)
833 RADIUS_PACKET *packet = request->packet;
834 uint64_t count = request->id;
836 RS_ASSERT(request->stats_req);
837 RS_ASSERT(!request->rt_rsp || request->stats_rsp);
841 * Don't pollute stats or print spurious messages as radsniff closes.
844 talloc_free(request);
848 if (RIDEBUG_ENABLED()) {
849 rs_time_print(timestr, sizeof(timestr), &request->when);
853 * Were at packet cleanup time which is when the packet was received + timeout
854 * and it's not been linked with a forwarded packet or a response.
856 * We now count it as lost.
858 if (!request->silent_cleanup) {
859 if (!request->linked) {
860 if (!request->stats_req) return;
862 request->stats_req->interval.lost_total++;
864 if (conf->event_flags & RS_LOST) {
865 /* @fixme We should use flags in the request to indicate whether it's been dumped
866 * to a PCAP file or logged yet, this simplifies the body logging logic */
867 rs_packet_print(request, request->id, RS_LOST, request->in, packet, NULL, NULL, false,
868 conf->filter_response_vps || !(conf->event_flags & RS_NORMAL));
872 if ((request->in->type == PCAP_INTERFACE_IN) && request->logged) {
873 RDEBUG("Cleaning up request packet ID %i", request->expect->id);
878 * Now the request is done, we can update the retransmission stats
880 if (request->rt_req > RS_RETRANSMIT_MAX) {
881 request->stats_req->interval.rt_total[RS_RETRANSMIT_MAX]++;
883 request->stats_req->interval.rt_total[request->rt_req]++;
886 if (request->rt_rsp) {
887 if (request->rt_rsp > RS_RETRANSMIT_MAX) {
888 request->stats_rsp->interval.rt_total[RS_RETRANSMIT_MAX]++;
890 request->stats_rsp->interval.rt_total[request->rt_rsp]++;
894 talloc_free(request);
897 static void _rs_event(void *ctx)
899 rs_request_t *request = talloc_get_type_abort(ctx, rs_request_t);
900 request->event = NULL;
901 rs_packet_cleanup(request);
904 /** Wrapper around fr_packet_cmp to strip off the outer request struct
907 static int rs_packet_cmp(rs_request_t const *a, rs_request_t const *b)
909 return fr_packet_cmp(a->expect, b->expect);
912 static inline int rs_response_to_pcap(rs_event_t *event, rs_request_t *request, struct pcap_pkthdr const *header,
915 if (!event->out) return 0;
918 * If we're filtering by response then the requests then the capture buffer
919 * associated with the request should contain buffered request packets.
921 if (conf->filter_response && request) {
925 * Record the current position in the header
927 start = request->capture_p;
930 * Buffer hasn't looped set capture_p to the start of the buffer
932 if (!start->header) request->capture_p = request->capture;
935 * If where capture_p points to, has a header set, write out the
936 * packet to the PCAP file, looping over the buffer until we
937 * hit our start point.
939 if (request->capture_p->header) do {
940 pcap_dump((void *)event->out->dumper, request->capture_p->header,
941 request->capture_p->data);
942 TALLOC_FREE(request->capture_p->header);
943 TALLOC_FREE(request->capture_p->data);
945 /* Reset the pointer to the start of the circular buffer */
946 if (request->capture_p++ >=
948 sizeof(request->capture) / sizeof(*request->capture))) {
949 request->capture_p = request->capture;
951 } while (request->capture_p != start);
955 * Now log the response
957 pcap_dump((void *)event->out->dumper, header, data);
962 static inline int rs_request_to_pcap(rs_event_t *event, rs_request_t *request, struct pcap_pkthdr const *header,
965 if (!event->out) return 0;
968 * If we're filtering by response, then we need to wait to write out the requests
970 if (conf->filter_response) {
971 /* Free the old capture */
972 if (request->capture_p->header) {
973 talloc_free(request->capture_p->header);
974 TALLOC_FREE(request->capture_p->data);
977 if (!(request->capture_p->header = talloc(request, struct pcap_pkthdr))) return -1;
978 if (!(request->capture_p->data = talloc_array(request, uint8_t, header->caplen))) {
979 TALLOC_FREE(request->capture_p->header);
982 memcpy(request->capture_p->header, header, sizeof(struct pcap_pkthdr));
983 memcpy(request->capture_p->data, data, header->caplen);
985 /* Reset the pointer to the start of the circular buffer */
986 if (++request->capture_p >=
988 sizeof(request->capture) / sizeof(*request->capture))) {
989 request->capture_p = request->capture;
994 pcap_dump((void *)event->out->dumper, header, data);
999 /* This is the same as immediately scheduling the cleanup event */
1000 #define RS_CLEANUP_NOW(_x, _s)\
1002 _x->silent_cleanup = _s;\
1003 _x->when = header->ts;\
1004 rs_packet_cleanup(_x);\
1008 static void rs_packet_process(uint64_t count, rs_event_t *event, struct pcap_pkthdr const *header, uint8_t const *data)
1010 rs_stats_t *stats = event->stats;
1011 struct timeval elapsed = {0, 0};
1012 struct timeval latency;
1015 * Pointers into the packet data we just received
1018 uint8_t const *p = data;
1020 ip_header_t const *ip = NULL; /* The IP header */
1021 ip_header6_t const *ip6 = NULL; /* The IPv6 header */
1022 udp_header_t const *udp; /* The UDP header */
1023 uint8_t version; /* IP header version */
1024 bool response; /* Was it a response code */
1026 decode_fail_t reason; /* Why we failed decoding the packet */
1027 static uint64_t captured = 0;
1029 rs_status_t status = RS_NORMAL; /* Any special conditions (RTX, Unlinked, ID-Reused) */
1030 RADIUS_PACKET *current; /* Current packet were processing */
1031 rs_request_t *original = NULL;
1033 rs_request_t search;
1035 memset(&search, 0, sizeof(search));
1037 if (!start_pcap.tv_sec) {
1038 start_pcap = header->ts;
1041 if (RIDEBUG_ENABLED()) {
1042 rs_time_print(timestr, sizeof(timestr), &header->ts);
1045 len = fr_link_layer_offset(data, header->caplen, event->in->link_layer);
1047 REDEBUG("Failed determining link layer header offset");
1052 version = (p[0] & 0xf0) >> 4;
1055 ip = (ip_header_t const *)p;
1056 len = (0x0f & ip->ip_vhl) * 4; /* ip_hl specifies length in 32bit words */
1061 ip6 = (ip_header6_t const *)p;
1062 p += sizeof(ip_header6_t);
1067 REDEBUG("IP version invalid %i", version);
1072 * End of variable length bits, do basic check now to see if packet looks long enough
1074 len = (p - data) + sizeof(udp_header_t) + sizeof(radius_packet_t); /* length value */
1075 if ((size_t) len > header->caplen) {
1076 REDEBUG("Packet too small, we require at least %zu bytes, captured %i bytes",
1077 (size_t) len, header->caplen);
1082 * UDP header validation.
1084 udp = (udp_header_t const *)p;
1089 udp_len = ntohs(udp->len);
1090 diff = udp_len - (header->caplen - (p - data));
1091 /* Truncated data */
1093 REDEBUG("Packet too small by %zi bytes, UDP header + Payload should be %hu bytes",
1098 else if (diff < 0) {
1099 REDEBUG("Packet too big by %zi bytes, UDP header + Payload should be %hu bytes",
1100 diff * -1, udp_len);
1104 if ((version == 4) && conf->verify_udp_checksum) {
1107 expected = fr_udp_checksum((uint8_t const *) udp, ntohs(udp->len), udp->checksum,
1108 ip->ip_src, ip->ip_dst);
1109 if (udp->checksum != expected) {
1110 REDEBUG("UDP checksum invalid, packet: 0x%04hx calculated: 0x%04hx",
1111 ntohs(udp->checksum), ntohs(expected));
1112 /* Not a fatal error */
1115 p += sizeof(udp_header_t);
1118 * With artificial talloc memory limits there's a good chance we can
1119 * recover once some requests timeout, so make an effort to deal
1120 * with allocation failures gracefully.
1122 current = rad_alloc(conf, false);
1124 REDEBUG("Failed allocating memory to hold decoded packet");
1125 rs_tv_add_ms(&header->ts, conf->stats.timeout, &stats->quiet);
1129 current->timestamp = header->ts;
1130 current->data_len = header->caplen - (p - data);
1131 memcpy(¤t->data, &p, sizeof(current->data));
1134 * Populate IP/UDP fields from PCAP data
1137 current->src_ipaddr.af = AF_INET;
1138 current->src_ipaddr.ipaddr.ip4addr.s_addr = ip->ip_src.s_addr;
1140 current->dst_ipaddr.af = AF_INET;
1141 current->dst_ipaddr.ipaddr.ip4addr.s_addr = ip->ip_dst.s_addr;
1143 current->src_ipaddr.af = AF_INET6;
1144 memcpy(current->src_ipaddr.ipaddr.ip6addr.s6_addr, ip6->ip_src.s6_addr,
1145 sizeof(current->src_ipaddr.ipaddr.ip6addr.s6_addr));
1147 current->dst_ipaddr.af = AF_INET6;
1148 memcpy(current->dst_ipaddr.ipaddr.ip6addr.s6_addr, ip6->ip_dst.s6_addr,
1149 sizeof(current->dst_ipaddr.ipaddr.ip6addr.s6_addr));
1152 current->src_port = ntohs(udp->src);
1153 current->dst_port = ntohs(udp->dst);
1155 if (!rad_packet_ok(current, 0, &reason)) {
1156 REDEBUG("%s", fr_strerror());
1157 if (conf->event_flags & RS_ERROR) {
1158 rs_packet_print(NULL, count, RS_ERROR, event->in, current, &elapsed, NULL, false, false);
1165 switch (current->code) {
1166 case PW_CODE_ACCOUNTING_RESPONSE:
1167 case PW_CODE_ACCESS_REJECT:
1168 case PW_CODE_ACCESS_ACCEPT:
1169 case PW_CODE_ACCESS_CHALLENGE:
1170 case PW_CODE_COA_NAK:
1171 case PW_CODE_COA_ACK:
1172 case PW_CODE_DISCONNECT_NAK:
1173 case PW_CODE_DISCONNECT_ACK:
1174 case PW_CODE_STATUS_CLIENT:
1176 /* look for a matching request and use it for decoding */
1177 search.expect = current;
1178 original = rbtree_finddata(request_tree, &search);
1181 * Verify this code is allowed
1183 if (conf->filter_response_code && (conf->filter_response_code != current->code)) {
1185 RDEBUG2("Response dropped by filter");
1188 /* We now need to cleanup the original request too */
1190 RS_CLEANUP_NOW(original, true);
1196 * Only decode attributes if we want to print them or filter on them
1197 * rad_packet_ok does checks to verify the packet is actually valid.
1199 if (conf->decode_attrs) {
1201 FILE *log_fp = fr_log_fp;
1204 ret = rad_decode(current, original ? original->expect : NULL, conf->radius_secret);
1208 REDEBUG("Failed decoding");
1214 * Check if we've managed to link it to a request
1218 * Now verify the packet passes the attribute filter
1220 if (conf->filter_response_vps) {
1221 fr_pair_list_sort(¤t->vps, fr_pair_cmp_by_da_tag);
1222 if (!fr_pair_validate_relaxed(NULL, conf->filter_response_vps, current->vps)) {
1228 * Is this a retransmission?
1230 if (original->linked) {
1234 rad_free(&original->linked);
1235 fr_event_delete(event->list, &original->event);
1237 * ...nope it's the first response to a request.
1240 original->stats_rsp = &stats->exchange[current->code];
1244 * Insert a callback to remove the request and response
1245 * from the tree after the timeout period.
1246 * The delay is so we can detect retransmissions.
1248 original->linked = talloc_steal(original, current);
1249 rs_tv_add_ms(&header->ts, conf->stats.timeout, &original->when);
1250 if (!fr_event_insert(event->list, _rs_event, original, &original->when,
1251 &original->event)) {
1252 REDEBUG("Failed inserting new event");
1254 * Delete the original request/event, it's no longer valid
1257 talloc_free(original);
1261 * No request seen, or request was dropped by attribute filter
1265 * If conf->filter_request_vps are set assume the original request was dropped,
1266 * the alternative is maintaining another 'filter', but that adds
1267 * complexity, reduces max capture rate, and is generally a PITA.
1269 if (conf->filter_request) {
1271 RDEBUG2("Original request dropped by filter");
1275 status = RS_UNLINKED;
1276 stats->exchange[current->code].interval.unlinked_total++;
1279 rs_response_to_pcap(event, original, header, data);
1284 case PW_CODE_ACCOUNTING_REQUEST:
1285 case PW_CODE_ACCESS_REQUEST:
1286 case PW_CODE_COA_REQUEST:
1287 case PW_CODE_DISCONNECT_REQUEST:
1288 case PW_CODE_STATUS_SERVER:
1291 * Verify this code is allowed
1293 if (conf->filter_request_code && (conf->filter_request_code != current->code)) {
1296 RDEBUG2("Request dropped by filter");
1303 * Only decode attributes if we want to print them or filter on them
1304 * rad_packet_ok does checks to verify the packet is actually valid.
1306 if (conf->decode_attrs) {
1308 FILE *log_fp = fr_log_fp;
1311 ret = rad_decode(current, NULL, conf->radius_secret);
1316 REDEBUG("Failed decoding");
1320 fr_pair_list_sort(¤t->vps, fr_pair_cmp_by_da_tag);
1324 * Save the request for later matching
1326 search.expect = rad_alloc_reply(current, current);
1327 if (!search.expect) {
1328 REDEBUG("Failed allocating memory to hold expected reply");
1329 rs_tv_add_ms(&header->ts, conf->stats.timeout, &stats->quiet);
1333 search.expect->code = current->code;
1335 if ((conf->link_da_num > 0) && current->vps) {
1337 ret = rs_get_pairs(current, &search.link_vps, current->vps, conf->link_da,
1340 ERROR("Failed extracting RTX linking pairs from request");
1347 * If we have linking attributes set, attempt to find a request in the linking tree.
1349 if (search.link_vps) {
1350 rs_request_t *tuple;
1352 original = rbtree_finddata(link_tree, &search);
1353 tuple = rbtree_finddata(request_tree, &search);
1356 * If the packet we matched using attributes is not the same
1357 * as the packet in the request tree, then we need to clean up
1358 * the packet in the request tree.
1360 if (tuple && (original != tuple)) {
1361 RS_CLEANUP_NOW(tuple, true);
1364 * Detect duplicates using the normal 5-tuple of src/dst ips/ports id
1367 original = rbtree_finddata(request_tree, &search);
1368 if (original && (memcmp(original->expect->vector, current->vector,
1369 sizeof(original->expect->vector)) != 0)) {
1371 * ID reused before the request timed out (which may be an issue)...
1373 if (!original->linked) {
1375 stats->exchange[current->code].interval.reused_total++;
1376 /* Occurs regularly downstream of proxy servers (so don't complain) */
1377 RS_CLEANUP_NOW(original, true);
1379 * ...and before we saw a response (which may be a bigger issue).
1382 RS_CLEANUP_NOW(original, false);
1384 /* else it's a proper RTX with the same src/dst id authenticator/nonce */
1389 * Now verify the packet passes the attribute filter
1391 if (conf->filter_request_vps) {
1392 if (!fr_pair_validate_relaxed(NULL, conf->filter_request_vps, current->vps)) {
1398 * Is this a retransmission?
1404 rad_free(&original->packet);
1406 /* We may of seen the response, but it may of been lost upstream */
1407 rad_free(&original->linked);
1409 original->packet = talloc_steal(original, current);
1411 /* Request may need to be reinserted as the 5 tuple of the response may of changed */
1412 if (rs_packet_cmp(original, &search) != 0) {
1413 rbtree_deletebydata(request_tree, original);
1416 rad_free(&original->expect);
1417 original->expect = talloc_steal(original, search.expect);
1419 /* Disarm the timer for the cleanup event for the original request */
1420 fr_event_delete(event->list, &original->event);
1422 * ...nope it's a new request.
1425 original = talloc_zero(conf, rs_request_t);
1426 talloc_set_destructor(original, _request_free);
1428 original->id = count;
1429 original->in = event->in;
1430 original->stats_req = &stats->exchange[current->code];
1432 /* Set the packet pointer to the start of the buffer*/
1433 original->capture_p = original->capture;
1435 original->packet = talloc_steal(original, current);
1436 original->expect = talloc_steal(original, search.expect);
1438 if (search.link_vps) {
1443 for (vp = fr_cursor_init(&cursor, &search.link_vps);
1445 vp = fr_cursor_next(&cursor)) {
1446 fr_pair_steal(original, search.link_vps);
1448 original->link_vps = search.link_vps;
1450 /* We should never have conflicts */
1451 ret = rbtree_insert(link_tree, original);
1453 original->in_link_tree = true;
1457 * Special case for when were filtering by response,
1458 * we never count any requests as lost, because we
1459 * don't know what the response to that request would
1462 if (conf->filter_response_vps) {
1463 original->silent_cleanup = true;
1467 if (!original->in_request_tree) {
1470 /* We should never have conflicts */
1471 ret = rbtree_insert(request_tree, original);
1473 original->in_request_tree = true;
1477 * Insert a callback to remove the request from the tree
1479 original->packet->timestamp = header->ts;
1480 rs_tv_add_ms(&header->ts, conf->stats.timeout, &original->when);
1481 if (!fr_event_insert(event->list, _rs_event, original,
1482 &original->when, &original->event)) {
1483 REDEBUG("Failed inserting new event");
1485 talloc_free(original);
1488 rs_request_to_pcap(event, original, header, data);
1494 REDEBUG("Unsupported code %i", current->code);
1500 rs_tv_sub(&header->ts, &start_pcap, &elapsed);
1503 * Increase received count
1505 stats->exchange[current->code].interval.received_total++;
1508 * It's a linked response
1510 if (original && original->linked) {
1511 rs_tv_sub(¤t->timestamp, &original->packet->timestamp, &latency);
1514 * Update stats for both the request and response types.
1516 * This isn't useful for things like Access-Requests, but will be useful for
1517 * CoA and Disconnect Messages, as we get the average latency across both
1520 * It also justifies allocating PW_CODE_MAX instances of rs_latency_t.
1522 rs_stats_update_latency(&stats->exchange[current->code], &latency);
1523 rs_stats_update_latency(&stats->exchange[original->expect->code], &latency);
1526 * Were filtering on response, now print out the full data from the request
1528 if (conf->filter_response && RIDEBUG_ENABLED() && (conf->event_flags & RS_NORMAL)) {
1529 rs_time_print(timestr, sizeof(timestr), &original->packet->timestamp);
1530 rs_tv_sub(&original->packet->timestamp, &start_pcap, &elapsed);
1531 rs_packet_print(original, original->id, RS_NORMAL, original->in,
1532 original->packet, &elapsed, NULL, false, true);
1533 rs_tv_sub(&header->ts, &start_pcap, &elapsed);
1534 rs_time_print(timestr, sizeof(timestr), &header->ts);
1537 if (conf->event_flags & status) {
1538 rs_packet_print(original, count, status, event->in, current,
1539 &elapsed, &latency, response, true);
1542 * It's the original request
1544 * If were filtering on responses we can only indicate we received it on response, or timeout.
1546 } else if (!conf->filter_response && (conf->event_flags & status)) {
1547 rs_packet_print(original, original ? original->id : count, status, event->in,
1548 current, &elapsed, NULL, response, true);
1554 * If it's a unlinked response, we need to free it explicitly, as it will
1555 * not be done by the event queue.
1557 if (response && !original) {
1563 * We've hit our capture limit, break out of the event loop
1565 if ((conf->limit > 0) && (captured >= conf->limit)) {
1566 INFO("Captured %" PRIu64 " packets, exiting...", captured);
1567 fr_event_loop_exit(events, 1);
1571 static void rs_got_packet(fr_event_list_t *el, int fd, void *ctx)
1573 static uint64_t count = 0; /* Packets seen */
1574 rs_event_t *event = ctx;
1575 pcap_t *handle = event->in->handle;
1579 const uint8_t *data;
1580 struct pcap_pkthdr *header;
1583 * Consume entire capture, interleaving not currently possible
1585 if ((event->in->type == PCAP_FILE_IN) || (event->in->type == PCAP_STDIO_IN)) {
1586 while (!fr_event_loop_exiting(el)) {
1589 ret = pcap_next_ex(handle, &header, &data);
1591 /* No more packets available at this time */
1595 DEBUG("Done reading packets (%s)", event->in->name);
1596 fr_event_fd_delete(events, 0, fd);
1598 /* Signal pipe takes one slot which is why this is == 1 */
1599 if (fr_event_list_num_fds(events) == 1) {
1600 fr_event_loop_exit(events, 1);
1606 ERROR("Error requesting next packet, got (%i): %s", ret, pcap_geterr(handle));
1612 } while (fr_event_run(el, &now) == 1);
1615 rs_packet_process(count, event, header, data);
1621 * Consume multiple packets from the capture buffer.
1622 * We occasionally need to yield to allow events to run.
1624 for (i = 0; i < RS_FORCE_YIELD; i++) {
1625 ret = pcap_next_ex(handle, &header, &data);
1627 /* No more packets available at this time */
1631 ERROR("Error requesting next packet, got (%i): %s", ret, pcap_geterr(handle));
1636 rs_packet_process(count, event, header, data);
1640 static void _rs_event_status(struct timeval *wake)
1642 if (wake && ((wake->tv_sec != 0) || (wake->tv_usec >= 100000))) {
1643 DEBUG2("Waking up in %d.%01u seconds.", (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
1645 if (RIDEBUG_ENABLED()) {
1646 rs_time_print(timestr, sizeof(timestr), wake);
1651 /** Compare requests using packet info and lists of attributes
1654 static int rs_rtx_cmp(rs_request_t const *a, rs_request_t const *b)
1658 RS_ASSERT(a->link_vps);
1659 RS_ASSERT(b->link_vps);
1661 rcode = (int) a->expect->code - (int) b->expect->code;
1662 if (rcode != 0) return rcode;
1664 rcode = a->expect->sockfd - b->expect->sockfd;
1665 if (rcode != 0) return rcode;
1667 rcode = fr_ipaddr_cmp(&a->expect->src_ipaddr, &b->expect->src_ipaddr);
1668 if (rcode != 0) return rcode;
1670 rcode = fr_ipaddr_cmp(&a->expect->dst_ipaddr, &b->expect->dst_ipaddr);
1671 if (rcode != 0) return rcode;
1673 return fr_pair_list_cmp(a->link_vps, b->link_vps);
1676 static int rs_build_dict_list(DICT_ATTR const **out, size_t len, char *list)
1682 while ((tok = strsep(&p, "\t ,")) != NULL) {
1683 DICT_ATTR const *da;
1684 if ((*tok == '\t') || (*tok == ' ') || (*tok == '\0')) {
1689 ERROR("Too many attributes, maximum allowed is %zu", len);
1693 da = dict_attrbyname(tok);
1695 ERROR("Error parsing attribute name \"%s\"", tok);
1704 * This allows efficient list comparisons later
1706 if (i > 1) fr_quick_sort((void const **)out, 0, i - 1, fr_pointer_cmp);
1711 static int rs_build_filter(VALUE_PAIR **out, char const *filter)
1717 code = fr_pair_list_afrom_str(conf, filter, out);
1718 if (code == T_INVALID) {
1719 ERROR("Invalid RADIUS filter \"%s\" (%s)", filter, fr_strerror());
1724 ERROR("Empty RADIUS filter '%s'", filter);
1728 for (vp = fr_cursor_init(&cursor, out);
1730 vp = fr_cursor_next(&cursor)) {
1732 * xlat expansion isn't supported here
1734 if (vp->type == VT_XLAT) {
1736 vp->vp_strvalue = vp->value.xlat;
1737 vp->vp_length = talloc_array_length(vp->vp_strvalue) - 1;
1742 * This allows efficient list comparisons later
1744 fr_pair_list_sort(out, fr_pair_cmp_by_da_tag);
1749 static int rs_build_event_flags(int *flags, FR_NAME_NUMBER const *map, char *list)
1755 while ((tok = strsep(&p, "\t ,")) != NULL) {
1758 if ((*tok == '\t') || (*tok == ' ') || (*tok == '\0')) {
1762 *flags |= flag = fr_str2int(map, tok, -1);
1764 ERROR("Invalid flag \"%s\"", tok);
1774 /** Callback for when the request is removed from the request tree
1776 * @param request being removed.
1778 static void _unmark_request(void *request)
1780 rs_request_t *this = request;
1781 this->in_request_tree = false;
1784 /** Callback for when the request is removed from the link tree
1786 * @param request being removed.
1788 static void _unmark_link(void *request)
1790 rs_request_t *this = request;
1791 this->in_link_tree = false;
1794 #ifdef HAVE_COLLECTDC_H
1795 /** Re-open the collectd socket
1798 static void rs_collectd_reopen(void *ctx)
1800 fr_event_list_t *list = ctx;
1801 static fr_event_t *event;
1802 struct timeval now, when;
1804 if (rs_stats_collectd_open(conf) == 0) {
1805 DEBUG2("Stats output socket (re)opened");
1809 ERROR("Will attempt to re-establish connection in %i ms", RS_SOCKET_REOPEN_DELAY);
1811 gettimeofday(&now, NULL);
1812 rs_tv_add_ms(&now, RS_SOCKET_REOPEN_DELAY, &when);
1813 if (!fr_event_insert(list, rs_collectd_reopen, list, &when, &event)) {
1814 ERROR("Failed inserting re-open event");
1820 /** Write the last signal to the signal pipe
1824 static void rs_signal_self(int sig)
1826 if (write(self_pipe[1], &sig, sizeof(sig)) < 0) {
1827 ERROR("Failed writing signal %s to pipe: %s", strsignal(sig), fr_syserror(errno));
1832 /** Read the last signal from the signal pipe
1835 static void rs_signal_action(
1836 #ifndef HAVE_COLLECTDC_H
1839 fr_event_list_t *list, int fd, UNUSED void *ctx)
1844 ret = read(fd, &sig, sizeof(sig));
1846 ERROR("Failed reading signal from pipe: %s", fr_syserror(errno));
1850 if (ret != sizeof(sig)) {
1851 ERROR("Failed reading signal from pipe: "
1852 "Expected signal to be %zu bytes but only read %zu byes", sizeof(sig), ret);
1857 #ifdef HAVE_COLLECTDC_H
1859 rs_collectd_reopen(list);
1866 DEBUG2("Signalling event loop to exit");
1867 fr_event_loop_exit(events, 1);
1871 ERROR("Unhandled signal %s", strsignal(sig));
1876 static void NEVER_RETURNS usage(int status)
1878 FILE *output = status ? stderr : stdout;
1879 fprintf(output, "Usage: radsniff [options][stats options] -- [pcap files]\n");
1880 fprintf(output, "options:\n");
1881 fprintf(output, " -a List all interfaces available for capture.\n");
1882 fprintf(output, " -c <count> Number of packets to capture.\n");
1883 fprintf(output, " -C Enable UDP checksum validation.\n");
1884 fprintf(output, " -d <directory> Set dictionary directory.\n");
1885 fprintf(output, " -d <raddb> Set configuration directory (defaults to " RADDBDIR ").\n");
1886 fprintf(output, " -D <dictdir> Set main dictionary directory (defaults to " DICTDIR ").\n");
1887 fprintf(output, " -e <event>[,<event>] Only log requests with these event flags.\n");
1888 fprintf(output, " Event may be one of the following:\n");
1889 fprintf(output, " - received - a request or response.\n");
1890 fprintf(output, " - norsp - seen for a request.\n");
1891 fprintf(output, " - rtx - of a request that we've seen before.\n");
1892 fprintf(output, " - noreq - could be matched with the response.\n");
1893 fprintf(output, " - reused - ID too soon.\n");
1894 fprintf(output, " - error - decoding the packet.\n");
1895 fprintf(output, " -f <filter> PCAP filter (default is 'udp port <port> or <port + 1> or 3799')\n");
1896 fprintf(output, " -h This help message.\n");
1897 fprintf(output, " -i <interface> Capture packets from interface (defaults to all if supported).\n");
1898 fprintf(output, " -I <file> Read packets from file (overrides input of -F).\n");
1899 fprintf(output, " -l <attr>[,<attr>] Output packet sig and a list of attributes.\n");
1900 fprintf(output, " -L <attr>[,<attr>] Detect retransmissions using these attributes to link requests.\n");
1901 fprintf(output, " -m Don't put interface(s) into promiscuous mode.\n");
1902 fprintf(output, " -p <port> Filter packets by port (default is 1812).\n");
1903 fprintf(output, " -P <pidfile> Daemonize and write out <pidfile>.\n");
1904 fprintf(output, " -q Print less debugging information.\n");
1905 fprintf(output, " -r <filter> RADIUS attribute request filter.\n");
1906 fprintf(output, " -R <filter> RADIUS attribute response filter.\n");
1907 fprintf(output, " -s <secret> RADIUS secret.\n");
1908 fprintf(output, " -S Write PCAP data to stdout.\n");
1909 fprintf(output, " -v Show program version information.\n");
1910 fprintf(output, " -w <file> Write output packets to file.\n");
1911 fprintf(output, " -x Print more debugging information.\n");
1912 fprintf(output, "stats options:\n");
1913 fprintf(output, " -W <interval> Periodically write out statistics every <interval> seconds.\n");
1914 fprintf(output, " -T <timeout> How many milliseconds before the request is counted as lost "
1915 "(defaults to %i).\n", RS_DEFAULT_TIMEOUT);
1916 #ifdef HAVE_COLLECTDC_H
1917 fprintf(output, " -N <prefix> The instance name passed to the collectd plugin.\n");
1918 fprintf(output, " -O <server> Write statistics to this collectd server.\n");
1923 int main(int argc, char *argv[])
1925 fr_pcap_t *in = NULL, *in_p;
1926 fr_pcap_t **in_head = ∈
1927 fr_pcap_t *out = NULL;
1929 int ret = 1; /* Exit status */
1931 char errbuf[PCAP_ERRBUF_SIZE]; /* Error buffer */
1937 char const *radius_dir = RADDBDIR;
1938 char const *dict_dir = DICTDIR;
1946 * Useful if using radsniff as a long running stats daemon
1949 if (fr_fault_setup(getenv("PANIC_ACTION"), argv[0]) < 0) {
1950 fr_perror("radsniff");
1955 talloc_set_log_stderr();
1957 conf = talloc_zero(NULL, rs_t);
1961 * We don't really want probes taking down machines
1963 #ifdef HAVE_TALLOC_SET_MEMLIMIT
1965 * @fixme causes hang in talloc steal
1967 //talloc_set_memlimit(conf, 524288000); /* 50 MB */
1973 conf->print_packet = true;
1975 conf->promiscuous = true;
1976 #ifdef HAVE_COLLECTDC_H
1977 conf->stats.prefix = RS_DEFAULT_PREFIX;
1979 conf->radius_secret = RS_DEFAULT_SECRET;
1980 conf->logger = NULL;
1982 #ifdef HAVE_COLLECTDC_H
1983 conf->stats.prefix = RS_DEFAULT_PREFIX;
1989 while ((opt = getopt(argc, argv, "ab:c:Cd:D:e:Ff:hi:I:l:L:mp:P:qr:R:s:Svw:xXW:T:P:N:O:")) != EOF) {
1993 pcap_if_t *all_devices = NULL;
1996 if (pcap_findalldevs(&all_devices, errbuf) < 0) {
1997 ERROR("Error getting available capture devices: %s", errbuf);
2002 for (dev_p = all_devices;
2004 dev_p = dev_p->next) {
2005 INFO("%i.%s", i++, dev_p->name);
2011 /* super secret option */
2013 conf->buffer_pkts = atoi(optarg);
2014 if (conf->buffer_pkts == 0) {
2015 ERROR("Invalid buffer length \"%s\"", optarg);
2021 conf->limit = atoi(optarg);
2022 if (conf->limit == 0) {
2023 ERROR("Invalid number of packets \"%s\"", optarg);
2030 conf->verify_udp_checksum = true;
2034 radius_dir = optarg;
2042 if (rs_build_event_flags((int *) &conf->event_flags, rs_events, optarg) < 0) {
2048 conf->pcap_filter = optarg;
2052 usage(0); /* never returns */
2055 *in_head = fr_pcap_init(conf, optarg, PCAP_INTERFACE_IN);
2056 if (!*in_head) goto finish;
2057 in_head = &(*in_head)->next;
2058 conf->from_dev = true;
2062 *in_head = fr_pcap_init(conf, optarg, PCAP_FILE_IN);
2066 in_head = &(*in_head)->next;
2067 conf->from_file = true;
2071 conf->list_attributes = optarg;
2075 conf->link_attributes = optarg;
2079 conf->promiscuous = false;
2083 port = atoi(optarg);
2087 conf->daemonize = true;
2088 conf->pidfile = optarg;
2092 if (fr_debug_lvl > 0) {
2098 conf->filter_request = optarg;
2102 conf->filter_response = optarg;
2106 conf->radius_secret = optarg;
2110 conf->to_stdout = true;
2114 #ifdef HAVE_COLLECTDC_H
2115 INFO("%s, %s, collectdclient version %s", radsniff_version, pcap_lib_version(),
2116 lcc_version_string());
2118 INFO("%s %s", radsniff_version, pcap_lib_version());
2123 out = fr_pcap_init(conf, optarg, PCAP_FILE_OUT);
2125 ERROR("Failed creating pcap file \"%s\"", optarg);
2128 conf->to_file = true;
2137 conf->stats.interval = atoi(optarg);
2138 conf->print_packet = false;
2139 if (conf->stats.interval <= 0) {
2140 ERROR("Stats interval must be > 0");
2146 conf->stats.timeout = atoi(optarg);
2147 if (conf->stats.timeout <= 0) {
2148 ERROR("Timeout value must be > 0");
2153 #ifdef HAVE_COLLECTDC_H
2155 conf->stats.prefix = optarg;
2159 conf->stats.collectd = optarg;
2160 conf->stats.out = RS_STATS_OUT_COLLECTD;
2169 * Mismatch between the binary and the libraries it depends on
2171 if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
2172 fr_perror("radsniff");
2176 /* Useful for file globbing */
2177 while (optind < argc) {
2178 *in_head = fr_pcap_init(conf, argv[optind], PCAP_FILE_IN);
2182 in_head = &(*in_head)->next;
2183 conf->from_file = true;
2187 /* Is stdin not a tty? If so it's probably a pipe */
2188 if (!isatty(fileno(stdin))) {
2189 conf->from_stdin = true;
2192 /* What's the point in specifying -F ?! */
2193 if (conf->from_stdin && conf->from_file && conf->to_file) {
2197 /* Can't read from both... */
2198 if (conf->from_file && conf->from_dev) {
2202 /* Reading from file overrides stdin */
2203 if (conf->from_stdin && (conf->from_file || conf->from_dev)) {
2204 conf->from_stdin = false;
2207 /* Writing to file overrides stdout */
2208 if (conf->to_file && conf->to_stdout) {
2209 conf->to_stdout = false;
2212 if (conf->to_stdout) {
2213 out = fr_pcap_init(conf, "stdout", PCAP_STDIO_OUT);
2219 if (conf->from_stdin) {
2220 *in_head = fr_pcap_init(conf, "stdin", PCAP_STDIO_IN);
2224 in_head = &(*in_head)->next;
2227 if (conf->stats.interval && !conf->stats.out) {
2228 conf->stats.out = RS_STATS_OUT_STDIO;
2231 if (conf->stats.timeout == 0) {
2232 conf->stats.timeout = RS_DEFAULT_TIMEOUT;
2236 * If were writing pcap data, or CSV to stdout we *really* don't want to send
2237 * logging there as well.
2239 if (conf->to_stdout || conf->list_attributes) {
2243 if (conf->list_attributes) {
2244 conf->logger = rs_packet_print_csv;
2245 } else if (fr_debug_lvl > 0) {
2246 conf->logger = rs_packet_print_fancy;
2249 #if !defined(HAVE_PCAP_FOPEN_OFFLINE) || !defined(HAVE_PCAP_DUMP_FOPEN)
2250 if (conf->from_stdin || conf->to_stdout) {
2251 ERROR("PCAP streams not supported");
2256 if (!conf->pcap_filter) {
2257 snprintf(buffer, sizeof(buffer), "udp port %d or %d or %d",
2258 port, port + 1, 3799);
2259 conf->pcap_filter = buffer;
2262 if (dict_init(dict_dir, RADIUS_DICTIONARY) < 0) {
2263 fr_perror("radsniff");
2268 if (dict_read(radius_dir, RADIUS_DICTIONARY) == -1) {
2269 fr_perror("radsniff");
2274 fr_strerror(); /* Clear out any non-fatal errors */
2276 if (conf->list_attributes) {
2277 conf->list_da_num = rs_build_dict_list(conf->list_da, sizeof(conf->list_da) / sizeof(*conf->list_da),
2278 conf->list_attributes);
2279 if (conf->list_da_num < 0) {
2282 rs_packet_print_csv_header();
2285 if (conf->link_attributes) {
2286 conf->link_da_num = rs_build_dict_list(conf->link_da, sizeof(conf->link_da) / sizeof(*conf->link_da),
2287 conf->link_attributes);
2288 if (conf->link_da_num < 0) {
2292 link_tree = rbtree_create(conf, (rbcmp) rs_rtx_cmp, _unmark_link, 0);
2294 ERROR("Failed creating RTX tree");
2299 if (conf->filter_request) {
2303 if (rs_build_filter(&conf->filter_request_vps, conf->filter_request) < 0) {
2307 fr_cursor_init(&cursor, &conf->filter_request_vps);
2308 type = fr_cursor_next_by_num(&cursor, PW_PACKET_TYPE, 0, TAG_ANY);
2310 fr_cursor_remove(&cursor);
2311 conf->filter_request_code = type->vp_integer;
2316 if (conf->filter_response) {
2320 if (rs_build_filter(&conf->filter_response_vps, conf->filter_response) < 0) {
2324 fr_cursor_init(&cursor, &conf->filter_response_vps);
2325 type = fr_cursor_next_by_num(&cursor, PW_PACKET_TYPE, 0, TAG_ANY);
2327 fr_cursor_remove(&cursor);
2328 conf->filter_response_code = type->vp_integer;
2334 * Default to logging and capturing all events
2336 if (conf->event_flags == 0) {
2337 DEBUG("Logging all events");
2338 memset(&conf->event_flags, 0xff, sizeof(conf->event_flags));
2342 * If we need to list attributes, link requests using attributes, filter attributes
2343 * or print the packet contents, we need to decode the attributes.
2345 * But, if were just logging requests, or graphing packets, we don't need to decode
2348 if (conf->list_da_num || conf->link_da_num || conf->filter_response_vps || conf->filter_request_vps ||
2349 conf->print_packet) {
2350 conf->decode_attrs = true;
2354 * Setup the request tree
2356 request_tree = rbtree_create(conf, (rbcmp) rs_packet_cmp, _unmark_request, 0);
2357 if (!request_tree) {
2358 ERROR("Failed creating request tree");
2363 * Get the default capture device
2365 if (!conf->from_stdin && !conf->from_file && !conf->from_dev) {
2366 pcap_if_t *all_devices; /* List of all devices libpcap can listen on */
2369 if (pcap_findalldevs(&all_devices, errbuf) < 0) {
2370 ERROR("Error getting available capture devices: %s", errbuf);
2375 ERROR("No capture files specified and no live interfaces available");
2380 for (dev_p = all_devices;
2382 dev_p = dev_p->next) {
2385 /* Don't use the any devices, it's horribly broken */
2386 if (!strcmp(dev_p->name, "any")) continue;
2388 link_layer = fr_pcap_if_link_layer(errbuf, dev_p);
2389 if (link_layer < 0) {
2390 DEBUG2("Skipping %s: %s", dev_p->name, errbuf);
2394 if (!fr_link_layer_supported(link_layer)) {
2395 DEBUG2("Skipping %s: datalink type %s not supported",
2396 dev_p->name, pcap_datalink_val_to_name(link_layer));
2400 *in_head = fr_pcap_init(conf, dev_p->name, PCAP_INTERFACE_IN);
2401 in_head = &(*in_head)->next;
2403 conf->from_auto = true;
2404 conf->from_dev = true;
2405 INFO("Defaulting to capture on all interfaces");
2409 * Print captures values which will be used
2411 if (fr_debug_lvl > 2) {
2412 DEBUG2("Sniffing with options:");
2413 if (conf->from_dev) {
2414 char *buff = fr_pcap_device_names(conf, in, ' ');
2415 DEBUG2(" Device(s) : [%s]", buff);
2419 DEBUG2(" Writing to : [%s]", out->name);
2421 if (conf->limit > 0) {
2422 DEBUG2(" Capture limit (packets) : [%" PRIu64 "]", conf->limit);
2424 DEBUG2(" PCAP filter : [%s]", conf->pcap_filter);
2425 DEBUG2(" RADIUS secret : [%s]", conf->radius_secret);
2427 if (conf->filter_request_code) {
2428 DEBUG2(" RADIUS request code : [%s]", fr_packet_codes[conf->filter_request_code]);
2431 if (conf->filter_request_vps){
2432 DEBUG2(" RADIUS request filter :");
2433 vp_printlist(fr_log_fp, conf->filter_request_vps);
2436 if (conf->filter_response_code) {
2437 DEBUG2(" RADIUS response code : [%s]", fr_packet_codes[conf->filter_response_code]);
2440 if (conf->filter_response_vps){
2441 DEBUG2(" RADIUS response filter :");
2442 vp_printlist(fr_log_fp, conf->filter_response_vps);
2447 * Setup collectd templates
2449 #ifdef HAVE_COLLECTDC_H
2450 if (conf->stats.out == RS_STATS_OUT_COLLECTD) {
2452 rs_stats_tmpl_t *tmpl, **next;
2454 if (rs_stats_collectd_open(conf) < 0) {
2458 next = &conf->stats.tmpl;
2460 for (i = 0; i < (sizeof(rs_useful_codes) / sizeof(*rs_useful_codes)); i++) {
2461 tmpl = rs_stats_collectd_init_latency(conf, next, conf, "exchanged",
2462 &stats.exchange[rs_useful_codes[i]],
2463 rs_useful_codes[i]);
2465 ERROR("Error allocating memory for stats template");
2468 next = &(tmpl->next);
2474 * This actually opens the capture interfaces/files (we just allocated the memory earlier)
2478 fr_pcap_t **tmp_p = &tmp;
2482 in_p = in_p->next) {
2483 in_p->promiscuous = conf->promiscuous;
2484 in_p->buffer_pkts = conf->buffer_pkts;
2485 if (fr_pcap_open(in_p) < 0) {
2486 ERROR("Failed opening pcap handle (%s): %s", in_p->name, fr_strerror());
2487 if (conf->from_auto || (in_p->type == PCAP_FILE_IN)) {
2494 if (!fr_link_layer_supported(in_p->link_layer)) {
2495 ERROR("Failed opening pcap handle (%s): Datalink type %s not supported",
2496 in_p->name, pcap_datalink_val_to_name(in_p->link_layer));
2500 if (conf->pcap_filter) {
2501 if (fr_pcap_apply_filter(in_p, conf->pcap_filter) < 0) {
2502 ERROR("Failed applying filter");
2508 tmp_p = &(in_p->next);
2514 ERROR("No PCAP sources available");
2518 /* Clear any irrelevant errors */
2523 * Open our output interface (if we have one);
2526 out->link_layer = -1; /* Infer output link type from input */
2530 in_p = in_p->next) {
2531 if (out->link_layer < 0) {
2532 out->link_layer = in_p->link_layer;
2536 if (out->link_layer != in_p->link_layer) {
2537 ERROR("Asked to write to output file, but inputs do not have the same link type");
2543 RS_ASSERT(out->link_layer >= 0);
2545 if (fr_pcap_open(out) < 0) {
2546 ERROR("Failed opening pcap output (%s): %s", out->name, fr_strerror());
2552 * Setup and enter the main event loop. Who needs libev when you can roll your own...
2560 memset(&stats, 0, sizeof(stats));
2561 memset(&update, 0, sizeof(update));
2563 events = fr_event_list_create(conf, _rs_event_status);
2570 * Initialise the signal handler pipe
2572 if (pipe(self_pipe) < 0) {
2573 ERROR("Couldn't open signal pipe: %s", fr_syserror(errno));
2577 if (!fr_event_fd_insert(events, 0, self_pipe[0], rs_signal_action, events)) {
2578 ERROR("Failed inserting signal pipe descriptor: %s", fr_strerror());
2583 * Now add fd's for each of the pcap sessions we opened
2587 in_p = in_p->next) {
2590 event = talloc_zero(events, rs_event_t);
2591 event->list = events;
2594 event->stats = &stats;
2596 if (!fr_event_fd_insert(events, 0, in_p->fd, rs_got_packet, event)) {
2597 ERROR("Failed inserting file descriptor");
2602 buff = fr_pcap_device_names(conf, in, ' ');
2603 DEBUG("Sniffing on (%s)", buff);
2606 gettimeofday(&now, NULL);
2609 * Insert our stats processor
2611 if (conf->stats.interval) {
2612 static fr_event_t *event;
2614 update.list = events;
2615 update.stats = &stats;
2618 now.tv_sec += conf->stats.interval;
2620 if (!fr_event_insert(events, rs_stats_process, (void *) &update, &now, &event)) {
2621 ERROR("Failed inserting stats event");
2624 INFO("Muting stats for the next %i milliseconds (warmup)", conf->stats.timeout);
2625 rs_tv_add_ms(&now, conf->stats.timeout, &stats.quiet);
2631 * Do this as late as possible so we can return an error code if something went wrong.
2633 if (conf->daemonize) {
2634 rs_daemonize(conf->pidfile);
2638 * Setup signal handlers so we always exit gracefully, ensuring output buffers are always
2641 fr_set_signal(SIGPIPE, rs_signal_self);
2642 fr_set_signal(SIGINT, rs_signal_self);
2643 fr_set_signal(SIGTERM, rs_signal_self);
2645 fr_set_signal(SIGQUIT, rs_signal_self);
2648 fr_event_loop(events); /* Enter the main event loop */
2650 DEBUG("Done sniffing");
2657 * Free all the things! This also closes all the sockets and file descriptors
2661 if (conf->daemonize) {
2662 unlink(conf->pidfile);