/* -*- Mode: C; tab-width: 4 -*- * * Copyright (c) 2002-2004 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ Change History (most recent first): $Log: dnsextd.c,v $ Revision 1.41 2005/09/24 01:10:54 cheshire Fix comment typos Revision 1.40 2005/09/07 21:54:37 ksekar dnsextd doesn't clean up on exit Close sockets before cleanup so clients can't make new requests Revision 1.39 2005/08/22 23:30:30 ksekar memory leak in dnsextd.c Revision 1.38 2005/06/29 10:03:56 cheshire Fix compile errors and warnings Revision 1.37 2005/06/27 22:12:17 ksekar dnsextd performance improvements Revision 1.36 2005/06/14 23:14:41 ksekar Unable to refresh LLQs Revision 1.35 2005/03/17 03:57:43 cheshire LEASE_OPT_SIZE is now LEASE_OPT_RDLEN; LLQ_OPT_SIZE is now LLQ_OPT_RDLEN Revision 1.34 2005/03/16 18:47:37 ksekar dnsextd doesn't clean up on exit Revision 1.33 2005/03/11 19:09:02 ksekar Fixed ZERO_LLQID macro Revision 1.32 2005/03/10 22:54:33 ksekar dnsextd leaks memory/ports Revision 1.31 2005/02/24 02:37:57 ksekar dnsextd memory management improvements Revision 1.30 2005/01/27 22:57:56 cheshire Fix compile errors on gcc4 Revision 1.29 2004/12/22 00:13:50 ksekar Change version, port, and polling interval for LLQ Revision 1.28 2004/12/17 00:30:00 ksekar dnsextd memory leak Revision 1.27 2004/12/17 00:27:32 ksekar Ignore SIGPIPE Revision 1.26 2004/12/17 00:21:33 ksekar Fixes for new CacheRecord structure with indirect name pointer Revision 1.25 2004/12/16 20:13:02 cheshire Cache memory management improvements Revision 1.24 2004/12/14 17:09:06 ksekar fixed incorrect usage instructions Revision 1.23 2004/12/06 20:24:31 ksekar dnsextd leaks sockets Revision 1.22 2004/12/03 20:20:29 ksekar dnsextd: support delivery of large records via LLQ events Revision 1.21 2004/12/03 06:11:34 ksekar clean up dnsextd arguments Revision 1.20 2004/12/01 04:27:28 cheshire Darwin patches for Solaris and Suse Don't use uint32_t, etc. -- they require stdint.h, which doesn't exist on FreeBSD 4.x, Solaris, etc. Revision 1.19 2004/12/01 01:16:29 cheshire Solaris compatibility fixes Revision 1.18 2004/11/30 23:51:06 cheshire Remove double semicolons Revision 1.17 2004/11/30 22:37:01 cheshire Update copyright dates and add "Mode: C; tab-width: 4" headers Revision 1.16 2004/11/25 02:02:28 ksekar Fixed verbose log message argument Revision 1.15 2004/11/19 02:35:02 ksekar Wide Area Security: Add LLQ-ID to events Revision 1.14 2004/11/17 06:17:58 cheshire Update comments to show correct SRV names: _dns-update._udp.. and _dns-llq._udp.. Revision 1.13 2004/11/13 02:22:36 ksekar Refresh Acks from daemon malformatted Revision 1.12 2004/11/12 01:05:01 ksekar dnsextd: daemon registers the SRV same record twice at startup Revision 1.11 2004/11/12 01:03:31 ksekar dnsextd: KnownAnswers (CacheRecords) leaked Revision 1.10 2004/11/12 00:35:28 ksekar dnsextd: uninitialized pointer can cause crash Revision 1.9 2004/11/10 20:38:17 ksekar dnsextd: allow a "fudge" in LLQ lease echo Revision 1.8 2004/11/01 17:48:14 cheshire Changed SOA serial number back to signed. RFC 1035 may describe it as "unsigned", but it's wrong. The SOA serial is a modular counter, as explained in "DNS & BIND", page 137. Since C doesn't have a modular type, we used signed, C's closest approximation. Revision 1.7 2004/10/30 00:06:58 ksekar Support Long Lived Queries in DNS Extension daemon Revision 1.6 2004/09/17 01:08:54 cheshire Renamed mDNSClientAPI.h to mDNSEmbeddedAPI.h The name "mDNSClientAPI.h" is misleading to new developers looking at this code. The interfaces declared in that file are ONLY appropriate to single-address-space embedded applications. For clients on general-purpose computers, the interfaces defined in dns_sd.h should be used. Revision 1.5 2004/09/16 00:50:54 cheshire Don't use MSG_WAITALL -- it returns "Invalid argument" on some Linux versions Revision 1.4 2004/09/14 23:27:48 cheshire Fix compile errors Revision 1.3 2004/09/02 01:39:40 cheshire For better readability, follow consistent convention that QR bit comes first, followed by OP bits Revision 1.2 2004/08/24 23:27:57 cheshire Fixes for Linux compatibility: Don't use strings.h Don't assume SIGINFO Don't try to set servaddr.sin_len on platforms that don't have sa_len Revision 1.1 2004/08/11 00:43:26 ksekar : DNS Extension daemon for DNS Update Lease */ #include "../mDNSCore/mDNSEmbeddedAPI.h" #include "../mDNSCore/DNSCommon.h" #include "../mDNSCore/mDNS.c" //!!!KRS we #include mDNS.c for the various constants defined there - we should move these to DNSCommon.h #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Compatibility workaround #ifndef AF_LOCAL #define AF_LOCAL AF_UNIX #endif // // Constants // #define LOOPBACK "127.0.0.1" #define NS_PORT 53 #define DAEMON_PORT 5352 // default, may be overridden via command line argument #define LISTENQ 128 // tcp connection backlog #define RECV_BUFLEN 9000 #define LEASETABLE_INIT_NBUCKETS 256 // initial hashtable size (doubles as table fills) #define LLQ_TABLESIZE 1024 // !!!KRS make this dynamically growable #define EXPIRATION_INTERVAL 300 // check for expired records every 5 minutes #define SRV_TTL 7200 // TTL For _dns-update SRV records // LLQ Lease bounds (seconds) #define LLQ_MIN_LEASE (15 * 60) #define LLQ_MAX_LEASE (120 * 60) #define LLQ_LEASE_FUDGE 60 // LLQ SOA poll interval (microseconds) #define LLQ_MONITOR_ERR_INTERVAL (60 * 1000000) #define LLQ_MONITOR_INTERVAL 250000 #ifdef SIGINFO #define INFO_SIGNAL SIGINFO #else #define INFO_SIGNAL SIGUSR1 #endif #define SAME_INADDR(x,y) (*((mDNSu32 *)&x) == *((mDNSu32 *)&y)) #define ZERO_LLQID(x) (!memcmp(x, "\x0\x0\x0\x0\x0\x0\x0\x0", 8)) // // Data Structures // Structs/fields that must be locked for thread safety are explicitly commented // typedef struct { struct sockaddr_in src; size_t len; DNSMessage msg; // Note: extra storage for oversized (TCP) messages goes here } PktMsg; // lease table entry typedef struct RRTableElem { struct RRTableElem *next; struct sockaddr_in cli; // client's source address long expire; // expiration time, in seconds since epoch domainname zone; // from zone field of update message domainname name; // name of the record CacheRecord rr; // last field in struct allows for allocation of oversized RRs } RRTableElem; typedef enum { RequestReceived = 0, ChallengeSent = 1, Established = 2 } LLQState; typedef struct AnswerListElem { struct AnswerListElem *next; domainname name; mDNSu16 type; CacheRecord *KnownAnswers; // All valid answers delivered to client CacheRecord *EventList; // New answers (adds/removes) to be sent to client int refcount; mDNSBool UseTCP; // Use TCP if UDP would cause truncation pthread_t tid; // Allow parallel list updates } AnswerListElem; // llq table entry typedef struct LLQEntry { struct LLQEntry *next; struct sockaddr_in cli; // clien'ts source address domainname qname; mDNSu16 qtype; mDNSu8 id[8]; LLQState state; mDNSu32 lease; // original lease, in seconds mDNSs32 expire; // expiration, absolute, in seconds since epoch AnswerListElem *AnswerList; } LLQEntry; // daemon-wide information typedef struct { // server variables - read only after initialization (no locking) struct sockaddr_in saddr; // server address domainname zone; // zone being updated int tcpsd; // listening TCP socket int udpsd; // listening UDP socket // daemon variables - read only after initialization (no locking) uDNS_AuthInfo *AuthInfo; // linked list of keys for signing deletion updates mDNSIPPort port; // listening port // lease table variables (locked via mutex after initialization) RRTableElem **table; // hashtable for records with leases pthread_mutex_t tablelock; // mutex for lease table mDNSs32 nbuckets; // buckets allocated mDNSs32 nelems; // elements in table // LLQ table variables LLQEntry *LLQTable[LLQ_TABLESIZE]; // !!!KRS change this and RRTable to use a common data structure AnswerListElem *AnswerTable[LLQ_TABLESIZE]; int AnswerTableCount; int LLQEventNotifySock; // Unix domain socket pair - update handling thread writes to EventNotifySock, which wakes int LLQEventListenSock; // the main thread listening on EventListenSock, indicating that the zone has changed } DaemonInfo; // args passed to UDP request handler thread as void* typedef struct { PktMsg pkt; struct sockaddr_in cliaddr; DaemonInfo *d; } UDPRequestArgs; // args passed to TCP request handler thread as void* typedef struct { int sd; // socket connected to client struct sockaddr_in cliaddr; DaemonInfo *d; } TCPRequestArgs; // args passed to UpdateAnswerList thread as void* typedef struct { DaemonInfo *d; AnswerListElem *a; } UpdateAnswerListArgs; // // Global Variables // // booleans to determine runtime output // read-only after initialization (no mutex protection) static mDNSBool foreground = 0; static mDNSBool verbose = 0; // globals set via signal handler (accessed exclusively by main select loop and signal handler) static mDNSBool terminate = 0; static mDNSBool dumptable = 0; // // Logging Routines // Log messages are delivered to syslog unless -f option specified // // common message logging subroutine mDNSlocal void PrintLog(const char *buffer) { if (foreground) { fprintf(stderr,"%s\n", buffer); fflush(stderr); } else { openlog("dnsextd", LOG_CONS | LOG_PERROR, LOG_DAEMON); syslog(LOG_ERR, "%s", buffer); closelog(); } } // Verbose Logging (conditional on -v option) mDNSlocal void VLog(const char *format, ...) { char buffer[512]; va_list ptr; if (!verbose) return; va_start(ptr,format); buffer[mDNS_vsnprintf((char *)buffer, sizeof(buffer), format, ptr)] = 0; va_end(ptr); PrintLog(buffer); } // Unconditional Logging mDNSlocal void Log(const char *format, ...) { char buffer[512]; va_list ptr; va_start(ptr,format); buffer[mDNS_vsnprintf((char *)buffer, sizeof(buffer), format, ptr)] = 0; va_end(ptr); PrintLog(buffer); } // Error Logging // prints message "dnsextd : - " // must be compiled w/ -D_REENTRANT for thread-safe errno usage mDNSlocal void LogErr(const char *fn, const char *operation) { char buf[512], errbuf[256]; strerror_r(errno, errbuf, sizeof(errbuf)); snprintf(buf, sizeof(buf), "%s: %s - %s", fn, operation, errbuf); PrintLog(buf); } // // Networking Utility Routines // // Convert DNS Message Header from Network to Host byte order mDNSlocal void HdrNToH(PktMsg *pkt) { // Read the integer parts which are in IETF byte-order (MSB first, LSB second) mDNSu8 *ptr = (mDNSu8 *)&pkt->msg.h.numQuestions; pkt->msg.h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]); pkt->msg.h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]); pkt->msg.h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]); pkt->msg.h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]); } // Convert DNS Message Header from Host to Network byte order mDNSlocal void HdrHToN(PktMsg *pkt) { mDNSu16 numQuestions = pkt->msg.h.numQuestions; mDNSu16 numAnswers = pkt->msg.h.numAnswers; mDNSu16 numAuthorities = pkt->msg.h.numAuthorities; mDNSu16 numAdditionals = pkt->msg.h.numAdditionals; mDNSu8 *ptr = (mDNSu8 *)&pkt->msg.h.numQuestions; // Put all the integer values in IETF byte-order (MSB first, LSB second) *ptr++ = (mDNSu8)(numQuestions >> 8); *ptr++ = (mDNSu8)(numQuestions & 0xFF); *ptr++ = (mDNSu8)(numAnswers >> 8); *ptr++ = (mDNSu8)(numAnswers & 0xFF); *ptr++ = (mDNSu8)(numAuthorities >> 8); *ptr++ = (mDNSu8)(numAuthorities & 0xFF); *ptr++ = (mDNSu8)(numAdditionals >> 8); *ptr++ = (mDNSu8)(numAdditionals & 0xFF); } // create a socket connected to nameserver // caller terminates connection via close() mDNSlocal int ConnectToServer(DaemonInfo *d) { int ntries = 0, retry = 0; while (1) { int sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { LogErr("ConnectToServer", "socket"); return -1; } if (!connect(sd, (struct sockaddr *)&d->saddr, sizeof(d->saddr))) return sd; close(sd); if (++ntries < 10) { LogErr("ConnectToServer", "connect"); Log("ConnectToServer - retrying connection"); if (!retry) retry = 500000 + random() % 500000; usleep(retry); retry *= 2; } else { Log("ConnectToServer - %d failed attempts. Aborting.", ntries); return -1; } } } // send an entire block of data over a connected socket mDNSlocal int MySend(int sd, const void *msg, int len) { int selectval, n, nsent = 0; fd_set wset; struct timeval timeout = { 3, 0 }; // until we remove all calls from main thread, keep timeout short while (nsent < len) { FD_ZERO(&wset); FD_SET(sd, &wset); selectval = select(sd+1, NULL, &wset, NULL, &timeout); if (selectval < 0) { LogErr("MySend", "select"); return -1; } if (!selectval || !FD_ISSET(sd, &wset)) { Log("MySend - timeout"); return -1; } n = send(sd, (char *)msg + nsent, len - nsent, 0); if (n < 0) { LogErr("MySend", "send"); return -1; } nsent += n; } return 0; } // Transmit a DNS message, prefixed by its length, over TCP, blocking if necessary mDNSlocal int SendTCPMsg(int sd, PktMsg *pkt) { // send the lenth, in network byte order mDNSu16 len = htons((mDNSu16)pkt->len); if (MySend(sd, &len, sizeof(len)) < 0) return -1; // send the message return MySend(sd, &pkt->msg, pkt->len); } // Receive len bytes, waiting until we have all of them. // Returns number of bytes read (which should always be the number asked for). static int my_recv(const int sd, void *const buf, const int len) { // Don't use "MSG_WAITALL"; it returns "Invalid argument" on some Linux versions; // use an explicit while() loop instead. // Also, don't try to do '+=' arithmetic on the original "void *" pointer -- // arithmetic on "void *" pointers is compiler-dependent. fd_set rset; struct timeval timeout = { 3, 0 }; // until we remove all calls from main thread, keep timeout short int selectval, remaining = len; char *ptr = (char *)buf; ssize_t num_read; while (remaining) { FD_ZERO(&rset); FD_SET(sd, &rset); selectval = select(sd+1, &rset, NULL, NULL, &timeout); if (selectval < 0) { LogErr("my_recv", "select"); return -1; } if (!selectval || !FD_ISSET(sd, &rset)) { Log("my_recv - timeout"); return -1; } num_read = recv(sd, ptr, remaining, 0); if ((num_read == 0) || (num_read < 0) || (num_read > remaining)) return -1; ptr += num_read; remaining -= num_read; } return(len); } // Return a DNS Message read off of a TCP socket, or NULL on failure // If storage is non-null, result is placed in that buffer. Otherwise, // returned value is allocated with Malloc, and contains sufficient extra // storage for a Lease OPT RR mDNSlocal PktMsg *ReadTCPMsg(int sd, PktMsg *storage) { int nread, allocsize; mDNSu16 msglen = 0; PktMsg *pkt = NULL; unsigned int srclen; nread = my_recv(sd, &msglen, sizeof(msglen)); if (nread < 0) { LogErr("ReadTCPMsg", "recv"); goto error; } msglen = ntohs(msglen); if (nread != sizeof(msglen)) { Log("Could not read length field of message"); goto error; } if (storage) { if (msglen > sizeof(storage->msg)) { Log("ReadTCPMsg: provided buffer too small."); goto error; } pkt = storage; } else { // buffer extra space to add an OPT RR if (msglen > sizeof(DNSMessage)) allocsize = sizeof(PktMsg) - sizeof(DNSMessage) + msglen; else allocsize = sizeof(PktMsg); pkt = malloc(allocsize); if (!pkt) { LogErr("ReadTCPMsg", "malloc"); goto error; } bzero(pkt, sizeof(*pkt)); } pkt->len = msglen; srclen = sizeof(pkt->src); if (getpeername(sd, (struct sockaddr *)&pkt->src, &srclen) || srclen != sizeof(pkt->src)) { LogErr("ReadTCPMsg", "getpeername"); bzero(&pkt->src, sizeof(pkt->src)); } nread = my_recv(sd, &pkt->msg, msglen); if (nread < 0) { LogErr("ReadTCPMsg", "recv"); goto error; } if (nread != msglen) { Log("Could not read entire message"); goto error; } if (pkt->len < sizeof(DNSMessageHeader)) { Log("ReadTCPMsg: Message too short (%d bytes)", pkt->len); goto error; } HdrNToH(pkt); return pkt; //!!!KRS convert to HBO here? error: if (pkt && pkt != storage) free(pkt); return NULL; } mDNSlocal int UDPServerTransaction(const DaemonInfo *d, const PktMsg *request, PktMsg *reply, mDNSBool *trunc) { fd_set rset; struct timeval timeout = { 3, 0 }; // until we remove all calls from main thread, keep timeout short int selectval, err = -1, sd = socket(AF_INET, SOCK_DGRAM, 0); *trunc = mDNSfalse; if (sd < 0) { LogErr("UDPServerTransaction", "socket"); goto end; } if (sendto(sd, (char *)&request->msg, request->len, 0, (struct sockaddr *)&d->saddr, sizeof(d->saddr)) != (int)request->len) { LogErr("UDPServerTransaction", "sendto"); goto end; } FD_ZERO(&rset); FD_SET(sd, &rset); selectval = select(sd+1, &rset, NULL, NULL, &timeout); if (selectval < 0) { LogErr("UDPServerTransaction", "select"); goto end; } if (!selectval || !FD_ISSET(sd, &rset)) { Log("UDPServerTransaction - timeout"); goto end; } reply->len = recvfrom(sd, &reply->msg, sizeof(reply->msg), 0, NULL, NULL); if ((int)reply->len < 0) { LogErr("UDPServerTransaction", "recvfrom"); goto end; } if (reply->len < sizeof(DNSMessageHeader)) { Log("UDPServerTransaction - Message too short (%d bytes)", reply->len); goto end; } if (reply->msg.h.flags.b[0] & kDNSFlag0_TC) *trunc = mDNStrue; err = 0; end: if (sd >= 0) close(sd); return err; } // // Dynamic Update Utility Routines // // Get the lease life of records in a dynamic update // returns -1 on error or if no lease present mDNSlocal mDNSs32 GetPktLease(PktMsg *pkt) { mDNSs32 lease = -1; const mDNSu8 *ptr = NULL, *end = (mDNSu8 *)&pkt->msg + pkt->len; LargeCacheRecord lcr; int i; HdrNToH(pkt); ptr = LocateAdditionals(&pkt->msg, end); if (ptr) for (i = 0; i < pkt->msg.h.numAdditionals; i++) { ptr = GetLargeResourceRecord(NULL, &pkt->msg, ptr, end, 0, kDNSRecordTypePacketAdd, &lcr); if (!ptr) { Log("Unable to read additional record"); break; } if (lcr.r.resrec.rrtype == kDNSType_OPT) { if (lcr.r.resrec.rdlength < LEASE_OPT_RDLEN) continue; if (lcr.r.resrec.rdata->u.opt.opt != kDNSOpt_Lease) continue; lease = (mDNSs32)lcr.r.resrec.rdata->u.opt.OptData.lease; break; } } HdrHToN(pkt); return lease; } // check if a request and server response complete a successful dynamic update mDNSlocal mDNSBool SuccessfulUpdateTransaction(PktMsg *request, PktMsg *reply) { char buf[32]; char *vlogmsg = NULL; // check messages if (!request || !reply) { vlogmsg = "NULL message"; goto failure; } if (request->len < sizeof(DNSMessageHeader) || reply->len < sizeof(DNSMessageHeader)) { vlogmsg = "Malformatted message"; goto failure; } // check request operation if ((request->msg.h.flags.b[0] & kDNSFlag0_QROP_Mask) != (request->msg.h.flags.b[0] & kDNSFlag0_QROP_Mask)) { vlogmsg = "Request opcode not an update"; goto failure; } // check result if ((reply->msg.h.flags.b[1] & kDNSFlag1_RC)) { vlogmsg = "Reply contains non-zero rcode"; goto failure; } if ((reply->msg.h.flags.b[0] & kDNSFlag0_QROP_Mask) != (kDNSFlag0_OP_Update | kDNSFlag0_QR_Response)) { vlogmsg = "Reply opcode not an update response"; goto failure; } VLog("Successful update from %s", inet_ntop(AF_INET, &request->src.sin_addr, buf, 32)); return mDNStrue; failure: VLog("Request %s: %s", inet_ntop(AF_INET, &request->src.sin_addr, buf, 32), vlogmsg); return mDNSfalse; } // Allocate an appropriately sized CacheRecord and copy data from original. // Name pointer in CacheRecord object is set to point to the name specified // mDNSlocal CacheRecord *CopyCacheRecord(const CacheRecord *orig, domainname *name) { CacheRecord *cr; size_t size = sizeof(*cr); if (orig->resrec.rdlength > InlineCacheRDSize) size += orig->resrec.rdlength - InlineCacheRDSize; cr = malloc(size); if (!cr) { LogErr("CopyCacheRecord", "malloc"); return NULL; } memcpy(cr, orig, size); cr->resrec.rdata = (RData*)&cr->rdatastorage; cr->resrec.name = name; return cr; } // // Lease Hashtable Utility Routines // // double hash table size // caller must lock table prior to invocation mDNSlocal void RehashTable(DaemonInfo *d) { RRTableElem *ptr, *tmp, **new; int i, bucket, newnbuckets = d->nbuckets * 2; VLog("Rehashing lease table (new size %d buckets)", newnbuckets); new = malloc(sizeof(RRTableElem *) * newnbuckets); if (!new) { LogErr("RehashTable", "malloc"); return; } bzero(new, newnbuckets * sizeof(RRTableElem *)); for (i = 0; i < d->nbuckets; i++) { ptr = d->table[i]; while (ptr) { bucket = ptr->rr.resrec.namehash % newnbuckets; tmp = ptr; ptr = ptr->next; tmp->next = new[bucket]; new[bucket] = tmp; } } d->nbuckets = newnbuckets; free(d->table); d->table = new; } // print entire contents of hashtable, invoked via SIGINFO mDNSlocal void PrintLeaseTable(DaemonInfo *d) { int i; RRTableElem *ptr; char rrbuf[80], addrbuf[16]; struct timeval now; int hr, min, sec; if (gettimeofday(&now, NULL)) { LogErr("PrintTable", "gettimeofday"); return; } if (pthread_mutex_lock(&d->tablelock)) { LogErr("PrintTable", "pthread_mutex_lock"); return; } Log("Dumping Lease Table Contents (table contains %d resource records)", d->nelems); for (i = 0; i < d->nbuckets; i++) { for (ptr = d->table[i]; ptr; ptr = ptr->next) { hr = ((ptr->expire - now.tv_sec) / 60) / 60; min = ((ptr->expire - now.tv_sec) / 60) % 60; sec = (ptr->expire - now.tv_sec) % 60; Log("Update from %s, Expires in %d:%d:%d\n\t%s", inet_ntop(AF_INET, &ptr->cli.sin_addr, addrbuf, 16), hr, min, sec, GetRRDisplayString_rdb(&ptr->rr.resrec, &ptr->rr.resrec.rdata->u, rrbuf)); } } pthread_mutex_unlock(&d->tablelock); } // // Startup SRV Registration Routines // Register _dns-update._udp/_tcp. SRV records indicating the port on which // the daemon accepts requests // // delete all RRS of a given name/type mDNSlocal mDNSu8 *putRRSetDeletion(DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit, ResourceRecord *rr) { ptr = putDomainNameAsLabels(msg, ptr, limit, rr->name); if (!ptr || ptr + 10 >= limit) return NULL; // out of space ptr[0] = (mDNSu8)(rr->rrtype >> 8); ptr[1] = (mDNSu8)(rr->rrtype & 0xFF); ptr[2] = (mDNSu8)((mDNSu16)kDNSQClass_ANY >> 8); ptr[3] = (mDNSu8)((mDNSu16)kDNSQClass_ANY & 0xFF); bzero(ptr+4, sizeof(rr->rroriginalttl) + sizeof(rr->rdlength)); // zero ttl/rdata msg->h.mDNS_numUpdates++; return ptr + 10; } mDNSlocal mDNSu8 *PutUpdateSRV(DaemonInfo *d, PktMsg *pkt, mDNSu8 *ptr, char *regtype, mDNSBool registration) { AuthRecord rr; char hostname[1024], buf[80]; mDNSu8 *end = (mDNSu8 *)&pkt->msg + sizeof(DNSMessage); mDNS_SetupResourceRecord(&rr, NULL, 0, kDNSType_SRV, SRV_TTL, kDNSRecordTypeUnique, NULL, NULL); rr.resrec.rrclass = kDNSClass_IN; rr.resrec.rdata->u.srv.priority = 0; rr.resrec.rdata->u.srv.weight = 0; rr.resrec.rdata->u.srv.port.NotAnInteger = d->port.NotAnInteger; if (!gethostname(hostname, 1024) < 0 || MakeDomainNameFromDNSNameString(&rr.resrec.rdata->u.srv.target, hostname)) rr.resrec.rdata->u.srv.target.c[0] = '\0'; MakeDomainNameFromDNSNameString(rr.resrec.name, regtype); AppendDomainName(rr.resrec.name, &d->zone); VLog("%s %s", registration ? "Registering SRV record" : "Deleting existing RRSet", GetRRDisplayString_rdb(&rr.resrec, &rr.resrec.rdata->u, buf)); if (registration) ptr = PutResourceRecord(&pkt->msg, ptr, &pkt->msg.h.mDNS_numUpdates, &rr.resrec); else ptr = putRRSetDeletion(&pkt->msg, ptr, end, &rr.resrec); return ptr; } // perform dynamic update. // specify deletion by passing false for the register parameter, otherwise register the records. mDNSlocal int UpdateSRV(DaemonInfo *d, mDNSBool registration) { int sd = -1; mDNSOpaque16 id; PktMsg pkt; mDNSu8 *ptr = pkt.msg.data; mDNSu8 *end = (mDNSu8 *)&pkt.msg + sizeof(DNSMessage); mDNSu16 nAdditHBO; // num additionas, in host byte order, required by message digest routine PktMsg *reply = NULL; int result = -1; // Initialize message id.NotAnInteger = 0; InitializeDNSMessage(&pkt.msg.h, id, UpdateReqFlags); pkt.src.sin_addr.s_addr = htonl(INADDR_ANY); // address field set solely for verbose logging in subroutines pkt.src.sin_family = AF_INET; // format message body ptr = putZone(&pkt.msg, ptr, end, &d->zone, mDNSOpaque16fromIntVal(kDNSClass_IN)); if (!ptr) goto end; ptr = PutUpdateSRV(d, &pkt, ptr, "_dns-update._udp.", registration); if (!ptr) goto end; ptr = PutUpdateSRV(d, &pkt, ptr, "_dns-update._tcp.", registration); if (!ptr) goto end; ptr = PutUpdateSRV(d, &pkt, ptr, "_dns-llq._udp.", registration); if (!ptr) goto end; nAdditHBO = pkt.msg.h.numAdditionals; HdrHToN(&pkt); if (d->AuthInfo) { ptr = DNSDigest_SignMessage(&pkt.msg, &ptr, &nAdditHBO, d->AuthInfo); if (!ptr) goto end; } pkt.len = ptr - (mDNSu8 *)&pkt.msg; // send message, receive reply sd = ConnectToServer(d); if (sd < 0) { Log("UpdateSRV: ConnectToServer failed"); goto end; } if (SendTCPMsg(sd, &pkt)) { Log("UpdateSRV: SendTCPMsg failed"); } reply = ReadTCPMsg(sd, NULL); if (!SuccessfulUpdateTransaction(&pkt, reply)) Log("SRV record registration failed with rcode %d", reply->msg.h.flags.b[1] & kDNSFlag1_RC); else result = 0; end: if (!ptr) { Log("UpdateSRV: Error constructing lease expiration update"); } if (sd >= 0) close(sd); if (reply) free(reply); return result; } // wrapper routines/macros #define ClearUpdateSRV(d) UpdateSRV(d, 0) // clear any existing records prior to registration mDNSlocal int SetUpdateSRV(DaemonInfo *d) { int err; err = ClearUpdateSRV(d); // clear any existing record if (!err) err = UpdateSRV(d, 1); return err; } // // Argument Parsing and Configuration // // read authentication information for a zone from command line argument // global optind corresponds to keyname argument on entry mDNSlocal int ReadAuthKey(int argc, char *argv[], DaemonInfo *d) { uDNS_AuthInfo *auth = NULL; unsigned char keybuf[512]; mDNSs32 keylen; auth = malloc(sizeof(*auth)); if (!auth) { perror("ReadAuthKey, malloc"); goto error; } auth->next = NULL; if (argc < optind + 1) return -1; // keyname + secret if (!MakeDomainNameFromDNSNameString(&auth->keyname, optarg)) { fprintf(stderr, "Bad key name %s", optarg); goto error; } keylen = DNSDigest_Base64ToBin(argv[optind++], keybuf, 512); if (keylen < 0) { fprintf(stderr, "Bad shared secret %s (must be base-64 encoded string)", argv[optind-1]); goto error; } DNSDigest_ConstructHMACKey(auth, keybuf, (mDNSu32)keylen); d->AuthInfo = auth; return 0; error: if (auth) free(auth); return -1; } mDNSlocal int SetPort(DaemonInfo *d, char *PortAsString) { long l; l = strtol(PortAsString, NULL, 10); // convert string to long if ((!l && errno == EINVAL) || l > 65535) return -1; // error check conversion d->port.NotAnInteger = htons((mDNSu16)l); // set to network byte order return 0; } mDNSlocal void PrintUsage(void) { fprintf(stderr, "Usage: dnsextd -z [-vf] [ -s server ] [-k keyname secret] ...\n" "Use \"dnsextd -h\" for help\n"); } mDNSlocal void PrintHelp(void) { fprintf(stderr, "\n\n"); PrintUsage(); fprintf(stderr, "dnsextd is a daemon that implements DNS extensions supporting Dynamic DNS Update Leases\n" "and Long Lived Queries, used in Wide-Area DNS Service Discovery, on behalf of name servers\n" "that do not natively support these extensions. (See dns-sd.org for more info on DNS Service\n" "Discovery, Update Leases, and Long Lived Queries.)\n\n" "dnsextd requires one argument,the zone, which is the domain for which Update Leases\n" "and Long Lived Queries are to be administered. dnsextd communicates directly with the\n" "primary master server for this zone.\n\n" "The options are as follows:\n\n" "-f Run daemon in foreground.\n\n" "-h Print help.\n\n" "-k Specify TSIG authentication key for dynamic updates from daemon to name server.\n" " -k option is followed by the name of the key, and the shared secret as a base-64\n" " encoded string. This key/secret are used by the daemon to delete resource records\n" " from the server when leases expire. Clients are responsible for signing their\n" " update requests.\n\n" "-s Specify address (IPv4 address in dotted-decimal notation) of the Primary Master\n" " name server. Defaults to loopback (127.0.0.1), i.e. daemon and name server\n" " running on the same machine.\n\n" "-v Verbose output.\n\n" ); } // Note: ProcessArgs called before process is daemonized, and therefore must open no descriptors // returns 0 (success) if program is to continue execution // output control arguments (-f, -v) do not affect this routine mDNSlocal int ProcessArgs(int argc, char *argv[], DaemonInfo *d) { int opt; struct in_addr server; if (argc < 2) goto arg_error; // defaults, may be overriden by command option d->port.NotAnInteger = htons(DAEMON_PORT); inet_pton(AF_INET, LOOPBACK, &server); // use loopback if server not explicitly specified while ((opt = getopt(argc, argv, "z:p:hfvs:k:")) != -1) { switch(opt) { case 'p': if (SetPort(d, optarg) < 0) goto arg_error; break; case 'h': PrintHelp(); return -1; case 'f': foreground = 1; break; case 'v': verbose = 1; break; case 's': if (!inet_pton(AF_INET, optarg, &server)) goto arg_error; break; case 'k': if (ReadAuthKey(argc, argv, d) < 0) goto arg_error; break; case 'z': if (!MakeDomainNameFromDNSNameString(&d->zone, optarg)) { fprintf(stderr, "Bad zone %s", optarg); goto arg_error; } break; default: goto arg_error; } } if (!d->zone.c[0]) goto arg_error; // zone is the only required argument if (d->AuthInfo) AssignDomainName(&d->AuthInfo->zone, &d->zone); // if we have a shared secret, use it for the entire zone // setup server's sockaddr bzero(&d->saddr, sizeof(d->saddr)); d->saddr.sin_addr = server; d->saddr.sin_port = htons(NS_PORT); d->saddr.sin_family = AF_INET; #ifndef NOT_HAVE_SA_LEN d->saddr.sin_len = sizeof(d->saddr); #endif return 0; arg_error: PrintUsage(); return -1; } // // Initialization Routines // // Allocate memory, initialize locks and bookkeeping variables mDNSlocal int InitLeaseTable(DaemonInfo *d) { if (pthread_mutex_init(&d->tablelock, NULL)) { LogErr("InitLeaseTable", "pthread_mutex_init"); return -1; } d->nbuckets = LEASETABLE_INIT_NBUCKETS; d->nelems = 0; d->table = malloc(sizeof(RRTableElem *) * LEASETABLE_INIT_NBUCKETS); if (!d->table) { LogErr("InitLeaseTable", "malloc"); return -1; } bzero(d->table, sizeof(RRTableElem *) * LEASETABLE_INIT_NBUCKETS); return 0; } mDNSlocal int SetupSockets(DaemonInfo *daemon) { struct sockaddr_in daddr; int sockpair[2]; // set up sockets on which we receive requests bzero(&daddr, sizeof(daddr)); daddr.sin_family = AF_INET; daddr.sin_addr.s_addr = htonl(INADDR_ANY); if (daemon->port.NotAnInteger) daddr.sin_port = daemon->port.NotAnInteger; else daddr.sin_port = htons(DAEMON_PORT); daemon->tcpsd = socket(AF_INET, SOCK_STREAM, 0); if (!daemon->tcpsd) { LogErr("SetupSockets", "socket"); return -1; } if (bind(daemon->tcpsd, (struct sockaddr *)&daddr, sizeof(daddr)) < 0) { LogErr("SetupSockets", "bind"); return -1; } if (listen(daemon->tcpsd, LISTENQ) < 0) { LogErr("SetupSockets", "listen"); return -1; } daemon->udpsd = socket(AF_INET, SOCK_DGRAM, 0); if (!daemon->udpsd) { LogErr("SetupSockets", "socket"); return -1; } if (bind(daemon->udpsd, (struct sockaddr *)&daddr, sizeof(daddr)) < 0) { LogErr("SetupSockets", "bind"); return -1; } // set up Unix domain socket pair for LLQ polling thread to signal main thread that a change to the zone occurred if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sockpair) < 0) { LogErr("SetupSockets", "socketpair"); return -1; } daemon->LLQEventListenSock = sockpair[0]; daemon->LLQEventNotifySock = sockpair[1]; return 0; } // // periodic table updates // // Delete a resource record from the nameserver via a dynamic update // sd is a socket already connected to the server mDNSlocal void DeleteOneRecord(DaemonInfo *d, CacheRecord *rr, domainname *zone, int sd) { mDNSOpaque16 id; PktMsg pkt; mDNSu8 *ptr = pkt.msg.data; mDNSu8 *end = (mDNSu8 *)&pkt.msg + sizeof(DNSMessage); mDNSu16 nAdditHBO; // num additionas, in host byte order, required by message digest routine char buf[80]; PktMsg *reply = NULL; VLog("Expiring record %s", GetRRDisplayString_rdb(&rr->resrec, &rr->resrec.rdata->u, buf)); id.NotAnInteger = 0; InitializeDNSMessage(&pkt.msg.h, id, UpdateReqFlags); ptr = putZone(&pkt.msg, ptr, end, zone, mDNSOpaque16fromIntVal(rr->resrec.rrclass)); if (!ptr) goto end; ptr = putDeletionRecord(&pkt.msg, ptr, &rr->resrec); if (!ptr) goto end; nAdditHBO = pkt.msg.h.numAdditionals; HdrHToN(&pkt); if (d->AuthInfo) { ptr = DNSDigest_SignMessage(&pkt.msg, &ptr, &nAdditHBO, d->AuthInfo); if (!ptr) goto end; } pkt.len = ptr - (mDNSu8 *)&pkt.msg; pkt.src.sin_addr.s_addr = htonl(INADDR_ANY); // address field set solely for verbose logging in subroutines pkt.src.sin_family = AF_INET; if (SendTCPMsg(sd, &pkt)) { Log("DeleteOneRecord: SendTCPMsg failed"); } reply = ReadTCPMsg(sd, NULL); if (!SuccessfulUpdateTransaction(&pkt, reply)) Log("Expiration update failed with rcode %d", reply ? reply->msg.h.flags.b[1] & kDNSFlag1_RC : -1); end: if (!ptr) { Log("DeleteOneRecord: Error constructing lease expiration update"); } if (reply) free(reply); } // iterate over table, deleting expired records (or all records if DeleteAll is true) mDNSlocal void DeleteRecords(DaemonInfo *d, mDNSBool DeleteAll) { struct timeval now; int i, sd = ConnectToServer(d); if (sd < 0) { Log("DeleteRecords: ConnectToServer failed"); return; } if (gettimeofday(&now, NULL)) { LogErr("DeleteRecords ", "gettimeofday"); return; } if (pthread_mutex_lock(&d->tablelock)) { LogErr("DeleteRecords", "pthread_mutex_lock"); return; } for (i = 0; i < d->nbuckets; i++) { RRTableElem **ptr = &d->table[i]; while (*ptr) { if (DeleteAll || (*ptr)->expire - now.tv_sec < 0) { RRTableElem *fptr; // delete record from server DeleteOneRecord(d, &(*ptr)->rr, &(*ptr)->zone, sd); fptr = *ptr; *ptr = (*ptr)->next; free(fptr); d->nelems--; } else ptr = &(*ptr)->next; } } pthread_mutex_unlock(&d->tablelock); close(sd); } // // main update request handling // // Add, delete, or refresh records in table based on contents of a successfully completed dynamic update mDNSlocal void UpdateLeaseTable(PktMsg *pkt, DaemonInfo *d, mDNSs32 lease) { RRTableElem **rptr, *tmp; int i, allocsize, bucket; LargeCacheRecord lcr; ResourceRecord *rr = &lcr.r.resrec; const mDNSu8 *ptr, *end; struct timeval time; DNSQuestion zone; char buf[80]; if (pthread_mutex_lock(&d->tablelock)) { LogErr("UpdateLeaseTable", "pthread_mutex_lock"); return; } HdrNToH(pkt); ptr = pkt->msg.data; end = (mDNSu8 *)&pkt->msg + pkt->len; ptr = getQuestion(&pkt->msg, ptr, end, 0, &zone); if (!ptr) { Log("UpdateLeaseTable: cannot read zone"); goto cleanup; } ptr = LocateAuthorities(&pkt->msg, end); if (!ptr) { Log("UpdateLeaseTable: Format error"); goto cleanup; } for (i = 0; i < pkt->msg.h.mDNS_numUpdates; i++) { mDNSBool DeleteAllRRSets = mDNSfalse, DeleteOneRRSet = mDNSfalse, DeleteOneRR = mDNSfalse; ptr = GetLargeResourceRecord(NULL, &pkt->msg, ptr, end, 0, kDNSRecordTypePacketAns, &lcr); if (!ptr) { Log("UpdateLeaseTable: GetLargeResourceRecord returned NULL"); goto cleanup; } bucket = rr->namehash % d->nbuckets; rptr = &d->table[bucket]; // handle deletions if (rr->rrtype == kDNSQType_ANY && !rr->rroriginalttl && rr->rrclass == kDNSQClass_ANY && !rr->rdlength) DeleteAllRRSets = mDNStrue; // delete all rrsets for a name else if (!rr->rroriginalttl && rr->rrclass == kDNSQClass_ANY && !rr->rdlength) DeleteOneRRSet = mDNStrue; else if (!rr->rroriginalttl && rr->rrclass == kDNSClass_NONE) DeleteOneRR = mDNStrue; if (DeleteAllRRSets || DeleteOneRRSet || DeleteOneRR) { while (*rptr) { if (SameDomainName((*rptr)->rr.resrec.name, rr->name) && (DeleteAllRRSets || (DeleteOneRRSet && (*rptr)->rr.resrec.rrtype == rr->rrtype) || (DeleteOneRR && SameResourceRecord(&(*rptr)->rr.resrec, rr)))) { tmp = *rptr; VLog("Received deletion update for %s", GetRRDisplayString_rdb(&tmp->rr.resrec, &tmp->rr.resrec.rdata->u, buf)); *rptr = (*rptr)->next; free(tmp); d->nelems--; } else rptr = &(*rptr)->next; } } else if (lease > 0) { // see if add or refresh while (*rptr && !SameResourceRecord(&(*rptr)->rr.resrec, rr)) rptr = &(*rptr)->next; if (*rptr) { // refresh if (gettimeofday(&time, NULL)) { LogErr("UpdateLeaseTable", "gettimeofday"); goto cleanup; } (*rptr)->expire = time.tv_sec + (unsigned)lease; VLog("Refreshing lease for %s", GetRRDisplayString_rdb(&lcr.r.resrec, &lcr.r.resrec.rdata->u, buf)); } else { // New record - add to table if (d->nelems > d->nbuckets) { RehashTable(d); bucket = rr->namehash % d->nbuckets; rptr = &d->table[bucket]; } if (gettimeofday(&time, NULL)) { LogErr("UpdateLeaseTable", "gettimeofday"); goto cleanup; } allocsize = sizeof(RRTableElem); if (rr->rdlength > InlineCacheRDSize) allocsize += (rr->rdlength - InlineCacheRDSize); tmp = malloc(allocsize); if (!tmp) { LogErr("UpdateLeaseTable", "malloc"); goto cleanup; } memcpy(&tmp->rr, &lcr.r, sizeof(CacheRecord) + rr->rdlength - InlineCacheRDSize); tmp->rr.resrec.rdata = (RData *)&tmp->rr.rdatastorage; AssignDomainName(&tmp->name, rr->name); tmp->rr.resrec.name = &tmp->name; tmp->expire = time.tv_sec + (unsigned)lease; tmp->cli.sin_addr = pkt->src.sin_addr; AssignDomainName(&tmp->zone, &zone.qname); tmp->next = d->table[bucket]; d->table[bucket] = tmp; d->nelems++; VLog("Adding update for %s to lease table", GetRRDisplayString_rdb(&lcr.r.resrec, &lcr.r.resrec.rdata->u, buf)); } } } cleanup: pthread_mutex_unlock(&d->tablelock); HdrHToN(pkt); } // Given a successful reply from a server, create a new reply that contains lease information // Replies are currently not signed !!!KRS change this mDNSlocal PktMsg *FormatLeaseReply(DaemonInfo *d, PktMsg *orig, mDNSu32 lease) { PktMsg *reply; mDNSu8 *ptr, *end; mDNSOpaque16 flags; (void)d; //unused reply = malloc(sizeof(*reply)); if (!reply) { LogErr("FormatLeaseReply", "malloc"); return NULL; } flags.b[0] = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update; flags.b[1] = 0; InitializeDNSMessage(&reply->msg.h, orig->msg.h.id, flags); reply->src.sin_addr.s_addr = htonl(INADDR_ANY); // unused except for log messages reply->src.sin_family = AF_INET; ptr = reply->msg.data; end = (mDNSu8 *)&reply->msg + sizeof(DNSMessage); ptr = putUpdateLease(&reply->msg, ptr, lease); if (!ptr) { Log("FormatLeaseReply: putUpdateLease failed"); free(reply); return NULL; } reply->len = ptr - (mDNSu8 *)&reply->msg; return reply; } // pkt is thread-local, not requiring locking mDNSlocal PktMsg *HandleRequest(PktMsg *pkt, DaemonInfo *d) { int sd = -1; PktMsg *reply = NULL, *LeaseReply, buf; mDNSs32 lease; char addrbuf[32], pingmsg[4]; // send msg to server, read reply if (pkt->len <= 512) { mDNSBool trunc; if (UDPServerTransaction(d, pkt, &buf, &trunc) < 0) Log("HandleRequest - UDPServerTransaction failed. Trying TCP"); else if (trunc) VLog("HandleRequest - answer truncated. Using TCP"); else reply = &buf; // success } if (!reply) { sd = ConnectToServer(d); if (sd < 0) { Log("Discarding request from %s due to connection errors", inet_ntop(AF_INET, &pkt->src.sin_addr, addrbuf, 32)); goto cleanup; } if (SendTCPMsg(sd, pkt) < 0) { Log("Couldn't relay message from %s to server. Discarding.", inet_ntop(AF_INET, &pkt->src.sin_addr, addrbuf, 32)); goto cleanup; } reply = ReadTCPMsg(sd, &buf); } // process reply if (!SuccessfulUpdateTransaction(pkt, reply)) { VLog("Message from %s not a successful update.", inet_ntop(AF_INET, &pkt->src.sin_addr, addrbuf, 32)); goto cleanup; } lease = GetPktLease(pkt); UpdateLeaseTable(pkt, d, lease); if (lease > 0) { LeaseReply = FormatLeaseReply(d, reply, lease); if (!LeaseReply) Log("HandleRequest - unable to format lease reply"); reply = LeaseReply; } // tell the main thread there was an update so it can send LLQs if (send(d->LLQEventNotifySock, pingmsg, sizeof(pingmsg), 0) != sizeof(pingmsg)) LogErr("HandleRequest", "send"); cleanup: if (sd >= 0) close(sd); if (reply == &buf) { reply = malloc(sizeof(*reply)); if (!reply) LogErr("HandleRequest", "malloc"); else { reply->len = buf.len; memcpy(&reply->msg, &buf.msg, buf.len); } } return reply; } // // LLQ Support Routines // // Set fields of an LLQ Opt Resource Record mDNSlocal void FormatLLQOpt(AuthRecord *opt, int opcode, mDNSu8 *id, mDNSs32 lease) { bzero(opt, sizeof(*opt)); mDNS_SetupResourceRecord(opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL); opt->resrec.rdlength = LLQ_OPT_RDLEN; opt->resrec.rdestimate = LLQ_OPT_RDLEN; opt->resrec.rdata->u.opt.opt = kDNSOpt_LLQ; opt->resrec.rdata->u.opt.optlen = sizeof(LLQOptData); opt->resrec.rdata->u.opt.OptData.llq.vers = kLLQ_Vers; opt->resrec.rdata->u.opt.OptData.llq.llqOp = opcode; opt->resrec.rdata->u.opt.OptData.llq.err = LLQErr_NoError; memcpy(opt->resrec.rdata->u.opt.OptData.llq.id, id, 8); opt->resrec.rdata->u.opt.OptData.llq.lease = lease; } // Calculate effective remaining lease of an LLQ mDNSlocal mDNSu32 LLQLease(LLQEntry *e) { struct timeval t; gettimeofday(&t, NULL); if (e->expire < t.tv_sec) return 0; else return e->expire - t.tv_sec; } mDNSlocal void DeleteLLQ(DaemonInfo *d, LLQEntry *e) { int bucket = DomainNameHashValue(&e->qname) % LLQ_TABLESIZE; LLQEntry **ptr = &d->LLQTable[bucket]; AnswerListElem *a = e->AnswerList; char addr[32]; inet_ntop(AF_INET, &e->cli.sin_addr, addr, 32); VLog("Deleting LLQ table entry for %##s client %s", e->qname.c, addr); if (a && !(--a->refcount) && d->AnswerTableCount >= LLQ_TABLESIZE) { // currently, generating initial answers blocks the main thread, so we keep the answer list // even if the ref count drops to zero. To prevent unbounded table growth, we free shared answers // if the ref count drops to zero AND there are more table elements than buckets // !!!KRS update this when we make the table dynamically growable CacheRecord *cr = a->KnownAnswers, *tmp; AnswerListElem **tbl = &d->AnswerTable[bucket]; while (cr) { tmp = cr; cr = cr->next; free(tmp); } while (*tbl && *tbl != a) tbl = &(*tbl)->next; if (*tbl) { *tbl = (*tbl)->next; free(a); d->AnswerTableCount--; } else Log("Error: DeleteLLQ - AnswerList not found in table"); } // remove LLQ from table, free memory while(*ptr && *ptr != e) ptr = &(*ptr)->next; if (!*ptr) { Log("Error: DeleteLLQ - LLQ not in table"); return; } *ptr = (*ptr)->next; free(e); } mDNSlocal int SendLLQ(DaemonInfo *d, PktMsg *pkt, struct sockaddr_in dst) { char addr[32]; int err = -1; HdrHToN(pkt); if (sendto(d->udpsd, &pkt->msg, pkt->len, 0, (struct sockaddr *)&dst, sizeof(dst)) != (int)pkt->len) { LogErr("DaemonInfo", "sendto"); Log("Could not send response to client %s", inet_ntop(AF_INET, &dst.sin_addr, addr, 32)); } else err = 0; HdrNToH(pkt); return err; } mDNSlocal CacheRecord *AnswerQuestion(DaemonInfo *d, AnswerListElem *e) { PktMsg q; int i, sd = -1; const mDNSu8 *ansptr; mDNSu8 *end = q.msg.data; mDNSOpaque16 id, flags = QueryFlags; PktMsg buf, *reply = NULL; LargeCacheRecord lcr; CacheRecord *AnswerList = NULL; mDNSu8 rcode; VLog("Querying server for %##s type %d", e->name.c, e->type); flags.b[0] |= kDNSFlag0_RD; // recursion desired id.NotAnInteger = 0; InitializeDNSMessage(&q.msg.h, id, flags); end = putQuestion(&q.msg, end, end + AbsoluteMaxDNSMessageData, &e->name, e->type, kDNSClass_IN); if (!end) { Log("Error: AnswerQuestion - putQuestion returned NULL"); goto end; } q.len = (int)(end - (mDNSu8 *)&q.msg); if (!e->UseTCP) { mDNSBool trunc; if (UDPServerTransaction(d, &q, &buf, &trunc) < 0) Log("AnswerQuestion %##s - UDPServerTransaction failed. Trying TCP", e->name.c); else if (trunc) { VLog("AnswerQuestion %##s - answer truncated. Using TCP", e->name.c); e->UseTCP = mDNStrue; } else reply = &buf; // success } if (!reply) { sd = ConnectToServer(d); if (sd < 0) { Log("AnswerQuestion: ConnectToServer failed"); goto end; } if (SendTCPMsg(sd, &q)) { Log("AnswerQuestion: SendTCPMsg failed"); close(sd); goto end; } reply = ReadTCPMsg(sd, NULL); close(sd); } if ((reply->msg.h.flags.b[0] & kDNSFlag0_QROP_Mask) != (kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery)) { Log("AnswerQuestion: %##s type %d - Invalid response flags from server"); goto end; } rcode = (mDNSu8)(reply->msg.h.flags.b[1] & kDNSFlag1_RC); if (rcode && rcode != kDNSFlag1_RC_NXDomain) { Log("AnswerQuestion: %##s type %d - non-zero rcode %d from server", e->name.c, e->type, rcode); goto end; } end = (mDNSu8 *)&reply->msg + reply->len; ansptr = LocateAnswers(&reply->msg, end); if (!ansptr) { Log("Error: AnswerQuestion - LocateAnswers returned NULL"); goto end; } for (i = 0; i < reply->msg.h.numAnswers; i++) { ansptr = GetLargeResourceRecord(NULL, &reply->msg, ansptr, end, 0, kDNSRecordTypePacketAns, &lcr); if (!ansptr) { Log("AnswerQuestions: GetLargeResourceRecord returned NULL"); goto end; } if (lcr.r.resrec.rrtype != e->type || lcr.r.resrec.rrclass != kDNSClass_IN || !SameDomainName(lcr.r.resrec.name, &e->name)) { Log("AnswerQuestion: response %##s type #d does not answer question %##s type #d. Discarding", lcr.r.resrec.name->c, lcr.r.resrec.rrtype, e->name.c, e->type); } else { CacheRecord *cr = CopyCacheRecord(&lcr.r, &e->name); if (!cr) { Log("Error: AnswerQuestion - CopyCacheRecord returned NULL"); goto end; } cr->next = AnswerList; AnswerList = cr; } } end: if (reply && reply != &buf) free(reply); return AnswerList; } // Routine forks a thread to set EventList to contain Add/Remove events, and deletes any removes from the KnownAnswer list mDNSlocal void *UpdateAnswerList(void *args) { CacheRecord *cr, *NewAnswers, **na, **ka; // "new answer", "known answer" DaemonInfo *d = ((UpdateAnswerListArgs *)args)->d; AnswerListElem *a = ((UpdateAnswerListArgs *)args)->a; free(args); args = NULL; // get up to date answers NewAnswers = AnswerQuestion(d, a); // first pass - mark all answers for deletion for (ka = &a->KnownAnswers; *ka; ka = &(*ka)->next) (*ka)->resrec.rroriginalttl = (unsigned)-1; // -1 means delete // second pass - mark answers pre-existent for (ka = &a->KnownAnswers; *ka; ka = &(*ka)->next) { for (na = &NewAnswers; *na; na = &(*na)->next) { if (SameResourceRecord(&(*ka)->resrec, &(*na)->resrec)) { (*ka)->resrec.rroriginalttl = 0; break; } // 0 means no change } } // third pass - add new records to Event list na = &NewAnswers; while (*na) { for (ka = &a->KnownAnswers; *ka; ka = &(*ka)->next) if (SameResourceRecord(&(*ka)->resrec, &(*na)->resrec)) break; if (!*ka) { // answer is not in list - splice from NewAnswers list, add to Event list cr = *na; *na = (*na)->next; // splice from list cr->next = a->EventList; // add spliced record to event list a->EventList = cr; cr->resrec.rroriginalttl = 1; // 1 means add } else na = &(*na)->next; } // move all the removes from the answer list to the event list ka = &a->KnownAnswers; while (*ka) { if ((*ka)->resrec.rroriginalttl == (unsigned)-1) { cr = *ka; *ka = (*ka)->next; cr->next = a->EventList; a->EventList = cr; } else ka = &(*ka)->next; } // lastly, free the remaining records (known answers) in NewAnswers list while (NewAnswers) { cr = NewAnswers; NewAnswers = NewAnswers->next; free(cr); } return NULL; } mDNSlocal void SendEvents(DaemonInfo *d, LLQEntry *e) { PktMsg response; CacheRecord *cr; mDNSu8 *end = (mDNSu8 *)&response.msg.data; mDNSOpaque16 msgID; char rrbuf[80], addrbuf[32]; AuthRecord opt; msgID.NotAnInteger = random(); if (verbose) inet_ntop(AF_INET, &e->cli.sin_addr, addrbuf, 32); InitializeDNSMessage(&response.msg.h, msgID, ResponseFlags); end = putQuestion(&response.msg, end, end + AbsoluteMaxDNSMessageData, &e->qname, e->qtype, kDNSClass_IN); if (!end) { Log("Error: SendEvents - putQuestion returned NULL"); return; } // put adds/removes in packet for (cr = e->AnswerList->EventList; cr; cr = cr->next) { if (verbose) GetRRDisplayString_rdb(&cr->resrec, &cr->resrec.rdata->u, rrbuf); VLog("%s (%s): %s", addrbuf, (mDNSs32)cr->resrec.rroriginalttl < 0 ? "Remove": "Add", rrbuf); end = PutResourceRecordTTLJumbo(&response.msg, end, &response.msg.h.numAnswers, &cr->resrec, cr->resrec.rroriginalttl); if (!end) { Log("Error: SendEvents - PutResourceRecordTTLJumbo returned NULL"); return; } } FormatLLQOpt(&opt, kLLQOp_Event, e->id, LLQLease(e)); end = PutResourceRecordTTLJumbo(&response.msg, end, &response.msg.h.numAdditionals, &opt.resrec, 0); if (!end) { Log("Error: SendEvents - PutResourceRecordTTLJumbo"); return; } response.len = (int)(end - (mDNSu8 *)&response.msg); if (SendLLQ(d, &response, e->cli) < 0) LogMsg("Error: SendEvents - SendLLQ"); } mDNSlocal void PrintLLQAnswers(DaemonInfo *d) { int i; char rrbuf[80]; Log("Printing LLQ Answer Table contents"); for (i = 0; i < LLQ_TABLESIZE; i++) { AnswerListElem *a = d->AnswerTable[i]; while(a) { int ancount = 0; const CacheRecord *rr = a->KnownAnswers; while (rr) { ancount++; rr = rr->next; } Log("%p : Question %##s; type %d; referenced by %d LLQs; %d answers:", a, a->name.c, a->type, a->refcount, ancount); for (rr = a->KnownAnswers; rr; rr = rr->next) Log("\t%s", GetRRDisplayString_rdb(&rr->resrec, &rr->resrec.rdata->u, rrbuf)); a = a->next; } } } mDNSlocal void PrintLLQTable(DaemonInfo *d) { LLQEntry *e; char addr[32]; int i; Log("Printing LLQ table contents"); for (i = 0; i < LLQ_TABLESIZE; i++) { e = d->LLQTable[i]; while(e) { char *state; switch (e->state) { case RequestReceived: state = "RequestReceived"; break; case ChallengeSent: state = "ChallengeSent"; break; case Established: state = "Established"; break; default: state = "unknown"; } inet_ntop(AF_INET, &e->cli.sin_addr, addr, 32); Log("LLQ from %s in state %s; %##s; type %d; orig lease %d; remaining lease %d; AnswerList %p)", addr, state, e->qname.c, e->qtype, e->lease, LLQLease(e), e->AnswerList); e = e->next; } } } // Send events to clients as a result of a change in the zone mDNSlocal void GenLLQEvents(DaemonInfo *d) { LLQEntry **e; int i; struct timeval t; UpdateAnswerListArgs *args; VLog("Generating LLQ Events"); gettimeofday(&t, NULL); // get all answers up to date for (i = 0; i < LLQ_TABLESIZE; i++) { AnswerListElem *a = d->AnswerTable[i]; while(a) { args = malloc(sizeof(*args)); if (!args) { LogErr("GenLLQEvents", "malloc"); return; } args->d = d; args->a = a; if (pthread_create(&a->tid, NULL, UpdateAnswerList, args) < 0) { LogErr("GenLLQEvents", "pthread_create"); return; } usleep(1); a = a->next; } } for (i = 0; i < LLQ_TABLESIZE; i++) { AnswerListElem *a = d->AnswerTable[i]; while(a) { if (pthread_join(a->tid, NULL)) LogErr("GenLLQEvents", "pthread_join"); a = a->next; } } // for each established LLQ, send events for (i = 0; i < LLQ_TABLESIZE; i++) { e = &d->LLQTable[i]; while(*e) { if ((*e)->expire < t.tv_sec) DeleteLLQ(d, *e); else { if ((*e)->state == Established && (*e)->AnswerList->EventList) SendEvents(d, *e); e = &(*e)->next; } } } // now that all LLQs are updated, we move Add events from the Event list to the Known Answer list, and free Removes for (i = 0; i < LLQ_TABLESIZE; i++) { AnswerListElem *a = d->AnswerTable[i]; while(a) { if (a->EventList) { CacheRecord *cr = a->EventList, *tmp; while (cr) { tmp = cr; cr = cr->next; if ((signed)tmp->resrec.rroriginalttl < 0) free(tmp); else { tmp->next = a->KnownAnswers; a->KnownAnswers = tmp; tmp->resrec.rroriginalttl = 0; } } a->EventList = NULL; } a = a->next; } } } mDNSlocal void SetAnswerList(DaemonInfo *d, LLQEntry *e) { int bucket = DomainNameHashValue(&e->qname) % LLQ_TABLESIZE; AnswerListElem *a = d->AnswerTable[bucket]; while (a && (a->type != e->qtype ||!SameDomainName(&a->name, &e->qname))) a = a->next; if (!a) { a = malloc(sizeof(*a)); if (!a) { LogErr("SetAnswerList", "malloc"); return; } AssignDomainName(&a->name, &e->qname); a->type = e->qtype; a->refcount = 0; a->EventList = NULL; a->UseTCP = mDNSfalse; a->next = d->AnswerTable[bucket]; d->AnswerTable[bucket] = a; d->AnswerTableCount++; a->KnownAnswers = AnswerQuestion(d, a); } e->AnswerList = a; a->refcount ++; } // Allocate LLQ entry, insert into table mDNSlocal LLQEntry *NewLLQ(DaemonInfo *d, struct sockaddr_in cli, domainname *qname, mDNSu16 qtype, mDNSu32 lease) { char addr[32]; struct timeval t; int bucket = DomainNameHashValue(qname) % LLQ_TABLESIZE; LLQEntry *e; e = malloc(sizeof(*e)); if (!e) { LogErr("NewLLQ", "malloc"); return NULL; } inet_ntop(AF_INET, &cli.sin_addr, addr, 32); VLog("Allocating LLQ entry for client %s question %##s type %d", addr, qname->c, qtype); // initialize structure e->cli = cli; AssignDomainName(&e->qname, qname); e->qtype = qtype; memset(e->id, 0, 8); e->state = RequestReceived; e->AnswerList = NULL; if (lease < LLQ_MIN_LEASE) lease = LLQ_MIN_LEASE; else if (lease > LLQ_MAX_LEASE) lease = LLQ_MIN_LEASE; gettimeofday(&t, NULL); e->expire = t.tv_sec + (int)lease; e->lease = lease; // add to table e->next = d->LLQTable[bucket]; d->LLQTable[bucket] = e; return e; } // Handle a refresh request from client mDNSlocal void LLQRefresh(DaemonInfo *d, LLQEntry *e, LLQOptData *llq, mDNSOpaque16 msgID) { AuthRecord opt; PktMsg ack; mDNSu8 *end = (mDNSu8 *)&ack.msg.data; char addr[32]; inet_ntop(AF_INET, &e->cli.sin_addr, addr, 32); VLog("%s LLQ for %##s from %s", llq->lease ? "Refreshing" : "Deleting", e->qname.c, addr); if (llq->lease) { struct timeval t; if (llq->lease < LLQ_MIN_LEASE) llq->lease = LLQ_MIN_LEASE; else if (llq->lease > LLQ_MAX_LEASE) llq->lease = LLQ_MIN_LEASE; gettimeofday(&t, NULL); e->expire = t.tv_sec + llq->lease; } ack.src.sin_addr.s_addr = 0; // unused InitializeDNSMessage(&ack.msg.h, msgID, ResponseFlags); end = putQuestion(&ack.msg, end, end + AbsoluteMaxDNSMessageData, &e->qname, e->qtype, kDNSClass_IN); if (!end) { Log("Error: putQuestion"); return; } FormatLLQOpt(&opt, kLLQOp_Refresh, e->id, llq->lease ? LLQLease(e) : 0); end = PutResourceRecordTTLJumbo(&ack.msg, end, &ack.msg.h.numAdditionals, &opt.resrec, 0); if (!end) { Log("Error: PutResourceRecordTTLJumbo"); return; } ack.len = (int)(end - (mDNSu8 *)&ack.msg); if (SendLLQ(d, &ack, e->cli)) Log("Error: LLQRefresh"); if (llq->lease) e->state = Established; else DeleteLLQ(d, e); } // Complete handshake with Ack an initial answers mDNSlocal void LLQCompleteHandshake(DaemonInfo *d, LLQEntry *e, LLQOptData *llq, mDNSOpaque16 msgID) { char addr[32]; CacheRecord *ptr; AuthRecord opt; PktMsg ack; mDNSu8 *end = (mDNSu8 *)&ack.msg.data; char rrbuf[80], addrbuf[32]; inet_ntop(AF_INET, &e->cli.sin_addr, addr, 32); if (memcmp(llq->id, e->id, 8) || llq->vers != kLLQ_Vers || llq->llqOp != kLLQOp_Setup || llq->err != LLQErr_NoError || llq->lease > e->lease + LLQ_LEASE_FUDGE || llq->lease < e->lease - LLQ_LEASE_FUDGE) { Log("Incorrect challenge response from %s", addr); return; } if (e->state == Established) VLog("Retransmitting LLQ ack + answers for %##s", e->qname.c); else VLog("Delivering LLQ ack + answers for %##s", e->qname.c); // format ack + answers ack.src.sin_addr.s_addr = 0; // unused InitializeDNSMessage(&ack.msg.h, msgID, ResponseFlags); end = putQuestion(&ack.msg, end, end + AbsoluteMaxDNSMessageData, &e->qname, e->qtype, kDNSClass_IN); if (!end) { Log("Error: putQuestion"); return; } if (e->state != Established) { SetAnswerList(d, e); e->state = Established; } if (verbose) inet_ntop(AF_INET, &e->cli.sin_addr, addrbuf, 32); for (ptr = e->AnswerList->KnownAnswers; ptr; ptr = ptr->next) { if (verbose) GetRRDisplayString_rdb(&ptr->resrec, &ptr->resrec.rdata->u, rrbuf); VLog("%s Intitial Answer - %s", addr, rrbuf); end = PutResourceRecordTTLJumbo(&ack.msg, end, &ack.msg.h.numAnswers, &ptr->resrec, 1); if (!end) { Log("Error: PutResourceRecordTTLJumbo"); return; } } FormatLLQOpt(&opt, kLLQOp_Setup, e->id, LLQLease(e)); end = PutResourceRecordTTLJumbo(&ack.msg, end, &ack.msg.h.numAdditionals, &opt.resrec, 0); if (!end) { Log("Error: PutResourceRecordTTLJumbo"); return; } ack.len = (int)(end - (mDNSu8 *)&ack.msg); if (SendLLQ(d, &ack, e->cli)) Log("Error: LLQCompleteHandshake"); } mDNSlocal void LLQSetupChallenge(DaemonInfo *d, LLQEntry *e, LLQOptData *llq, mDNSOpaque16 msgID) { struct timeval t; mDNSu32 randval; PktMsg challenge; mDNSu8 *end = challenge.msg.data; AuthRecord opt; if (e->state == ChallengeSent) VLog("Retransmitting LLQ setup challenge for %##s", e->qname.c); else VLog("Sending LLQ setup challenge for %##s", e->qname.c); if (!ZERO_LLQID(llq->id)) { Log("Error: LLQSetupChallenge - nonzero ID"); return; } // server bug if (llq->llqOp != kLLQOp_Setup) { Log("LLQSetupChallenge - incorrrect operation from client"); return; } // client error if (ZERO_LLQID(e->id)) // don't regenerate random ID for retransmissions { // construct ID