From 00129b08c5e5df7639119cac812c765736a4c7c1 Mon Sep 17 00:00:00 2001 From: Felix Fietkau Date: Tue, 3 Jun 2014 22:55:37 +0200 Subject: [PATCH] dns: use compile time initialization for structs, remove unnecessary call to inet_aton Also avoids excessive stack utilization for buffer Signed-off-by: Felix Fietkau --- dns.c | 65 ++++++++++++++++++++++++++++++++--------------------------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/dns.c b/dns.c index ecfaa63..75e739d 100644 --- a/dns.c +++ b/dns.c @@ -30,6 +30,7 @@ #include #include +#include #include "announce.h" #include "util.h" @@ -67,58 +68,62 @@ dns_type_string(uint16_t type) void dns_send_question(struct uloop_fd *u, char *question, int type) { - size_t cmsg_data[( CMSG_SPACE(sizeof(struct in_pktinfo)) / sizeof(size_t)) + 1]; - unsigned char buffer[MAX_NAME_LEN]; - struct dns_header h = { 0 }; - struct dns_question q = { 0 }; - struct msghdr m = { 0 }; - struct iovec iov[3] = { {0}, {0}, {0} }; - struct sockaddr_in a = { 0 }; + static size_t cmsg_data[( CMSG_SPACE(sizeof(struct in_pktinfo)) / sizeof(size_t)) + 1]; + static unsigned char buffer[MAX_NAME_LEN]; + static struct dns_header h = { + .questions = cpu_to_be16(1), + }; + static struct dns_question q = { + .class = cpu_to_be16(1), + }; + static struct iovec iov[] = { + { + .iov_base = &h, + .iov_len = sizeof(h), + }, + { + .iov_base = buffer, + }, + { + .iov_base = &q, + .iov_len = sizeof(q), + } + }; + static struct sockaddr_in a = { + .sin_family = AF_INET, + .sin_port = htons(MCAST_PORT), + }; + static struct msghdr m = { + .msg_name = (struct sockaddr *) &a, + .msg_namelen = sizeof(a), + .msg_iov = iov, + .msg_iovlen = ARRAY_SIZE(iov), + .msg_control = cmsg_data, + .msg_controllen = CMSG_LEN(sizeof(struct in_pktinfo)), + }; struct in_pktinfo *pkti; struct cmsghdr *cmsg; - struct in_addr in; int len; - a.sin_family = AF_INET; a.sin_addr.s_addr = inet_addr(MCAST_ADDR); - a.sin_port = htons(MCAST_PORT); - - h.questions = __cpu_to_be16(1); q.type = __cpu_to_be16(type); - q.class = __cpu_to_be16(1); len = dn_comp(question, buffer, MAX_NAME_LEN, NULL, NULL); if (len < 1) return; - m.msg_name = &a; - m.msg_namelen = sizeof(struct sockaddr_in); - m.msg_iov = iov; - m.msg_iovlen = 3; + iov[1].iov_len = len; memset(cmsg_data, 0, sizeof(cmsg_data)); - m.msg_control = cmsg_data; - m.msg_controllen = CMSG_LEN(sizeof(struct in_pktinfo)); cmsg = CMSG_FIRSTHDR(&m); cmsg->cmsg_len = m.msg_controllen; cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_PKTINFO; - inet_aton(iface_ip, &in); - pkti = (struct in_pktinfo*) CMSG_DATA(cmsg); pkti->ipi_ifindex = iface_index; - iov[0].iov_base = &h; - iov[0].iov_len = sizeof(struct dns_header); - - iov[1].iov_base = buffer; - iov[1].iov_len = len; - - iov[2].iov_base = &q; - iov[2].iov_len = sizeof(struct dns_question); - if (sendmsg(u->fd, &m, 0) < 0) fprintf(stderr, "failed to send question\n"); else -- 2.25.1