2 * icmpdnd - ICMP Domain Name responder daemon for Linux
3 * Copyright (C) 2005 Fredrik Tolf <fredrik@dolda2000.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include <sys/socket.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <netinet/ip.h>
30 #include <sys/types.h>
55 #define ICMP_NAMEREQ 37
56 #define ICMP_NAMEREP 38
60 size_t filldn(char *dst)
66 if(gethostname(namebuf, sizeof(namebuf)) < 0) {
67 perror("gethostname");
72 if(getdomainname(namebuf + hl, sizeof(namebuf) - hl) < 0) {
73 perror("getdomainname");
76 if(strlen(namebuf + hl) != 0) {
84 while((p2 = strchr(p, '.')) != NULL) {
87 memcpy(dp, p, p2 - p);
96 void cksum(void *hdr, size_t len)
103 ih = (struct icmphdr *)hdr;
104 cb = (u_int8_t *)hdr;
107 for(i = 0; i < (len & ~1); i += 2) {
126 cb = (u_int8_t *)&ih->checksum;
127 cb[0] = ~(u_int8_t)b1;
128 cb[1] = ~(u_int8_t)b2;
131 int main(int argc, char **argv)
134 int c, s, namelen, datalen;
136 unsigned char buf[65536];
137 struct sockaddr_in name;
141 time_t curtime, lasterr;
145 while((c = getopt(argc, argv, "nht:")) != -1) {
157 fprintf(stderr, "usage: icmpdnd [-n]");
158 exit((c == 'h')?0:1);
162 if((s = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
163 perror("could not create raw socket");
170 openlog("icmpdnd", LOG_PID, LOG_DAEMON);
175 namelen = sizeof(name);
176 ret = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&name, &namelen);
178 curtime = time(NULL);
182 syslog(LOG_ERR, "error in receiving datagram: %m");
183 if(lasterr == curtime) {
184 syslog(LOG_CRIT, "exiting due to repeated errors");
190 if(ret < sizeof(iphdr) + sizeof(req))
192 memcpy(&iphdr, buf, sizeof(iphdr));
193 memcpy(&req, buf + sizeof(iphdr), sizeof(req));
194 if(iphdr.protocol != IPPROTO_ICMP)
196 if(req.type != ICMP_NAMEREQ)
198 rep.type = ICMP_NAMEREP;
202 rep.ttl = htonl(ttl);
203 memcpy(buf, &rep, sizeof(rep));
204 datalen = filldn(buf + sizeof(rep));
206 cksum(buf, datalen + sizeof(rep));
208 /* XXX: The correct source address needs to be filled in from
209 * the request's destination address. */
210 ret = sendto(s, buf, datalen + sizeof(rep), 0, (struct sockaddr *)&name, namelen);
212 syslog(LOG_WARNING, "error in sending reply: %m");