diff mbox series

[libnetfilter_queue,1/1] example: nf-queue: use pkt_buff (updated)

Message ID 20200514043547.1255-2-duncan_roe@optusnet.com.au
State Under Review
Delegated to: Pablo Neira
Headers show
Series pktbuff API updates | expand

Commit Message

Duncan Roe May 14, 2020, 4:35 a.m. UTC
- Use the 5-args pktb_setup() variant.
- Demonstrate using pktb_head_size() once in main() to set size of array
  in callback stack.
- Output 2 hex digits per character.

Signed-off-by: Duncan Roe <duncan_roe@optusnet.com.au>
---
 examples/nf-queue.c | 20 ++++++++------------
 1 file changed, 8 insertions(+), 12 deletions(-)
diff mbox series

Patch

diff --git a/examples/nf-queue.c b/examples/nf-queue.c
index f0d4c2e..1d0cba4 100644
--- a/examples/nf-queue.c
+++ b/examples/nf-queue.c
@@ -20,6 +20,7 @@ 
 #include <linux/netfilter/nfnetlink_conntrack.h>
 
 static struct mnl_socket *nl;
+static size_t sizeof_pktbuff;
 
 static void
 nfq_send_verdict(int queue_num, uint32_t id)
@@ -51,7 +52,8 @@  static int queue_cb(const struct nlmsghdr *nlh, void *data)
 {
 	struct nfqnl_msg_packet_hdr *ph = NULL;
 	struct nlattr *attr[NFQA_MAX+1] = {};
-	struct pkt_buff *pktb = data;
+	struct pkt_buff *pktb;
+	uint8_t pktbuff[sizeof_pktbuff];
 	uint32_t id = 0, skbinfo;
 	struct nfgenmsg *nfg;
 	uint8_t *payload;
@@ -74,7 +76,8 @@  static int queue_cb(const struct nlmsghdr *nlh, void *data)
 
 	plen = mnl_attr_get_payload_len(attr[NFQA_PAYLOAD]);
 
-	pktb_build_data(pktb, mnl_attr_get_payload(attr[NFQA_PAYLOAD]), plen);
+	pktb = pktb_setup(AF_INET, pktbuff, sizeof pktbuff,
+			  mnl_attr_get_payload(attr[NFQA_PAYLOAD]), plen);
 
 	skbinfo = attr[NFQA_SKB_INFO] ? ntohl(mnl_attr_get_u32(attr[NFQA_SKB_INFO])) : 0;
 
@@ -106,7 +109,7 @@  static int queue_cb(const struct nlmsghdr *nlh, void *data)
 	payload = pktb_data(pktb);
 
 	for (i = 0; i < pktb_len(pktb); i++)
-		printf("%x", payload[i] & 0xff);
+		printf("%02x", payload[i]);
 
 	printf("]\n");
 
@@ -120,7 +123,6 @@  int main(int argc, char *argv[])
 	char *buf;
 	/* largest possible packet payload, plus netlink data overhead: */
 	size_t sizeof_buf = 0xffff + (MNL_SOCKET_BUFFER_SIZE/2);
-	struct pkt_buff *pktb;
 	struct nlmsghdr *nlh;
 	int ret;
 	unsigned int portid, queue_num;
@@ -174,12 +176,7 @@  int main(int argc, char *argv[])
 	 */
 	ret = 1;
 	mnl_socket_setsockopt(nl, NETLINK_NO_ENOBUFS, &ret, sizeof(int));
-
-	pktb = pktb_alloc_head();
-	if (!pktb) {
-		perror("pktb_alloc");
-		exit(EXIT_FAILURE);
-	}
+	sizeof_pktbuff = pktb_head_size(); /* Avoid multiple calls in CB */
 
 	for (;;) {
 		ret = mnl_socket_recvfrom(nl, buf, sizeof_buf);
@@ -188,14 +185,13 @@  int main(int argc, char *argv[])
 			exit(EXIT_FAILURE);
 		}
 
-		ret = mnl_cb_run(buf, ret, 0, portid, queue_cb, pktb);
+		ret = mnl_cb_run(buf, ret, 0, portid, queue_cb, NULL);
 		if (ret < 0){
 			perror("mnl_cb_run");
 			exit(EXIT_FAILURE);
 		}
 	}
 
-	pktb_free(pktb);
 	mnl_socket_close(nl);
 
 	return 0;