blob: fd214acd8ce6385a017d9341b2c02fe10e7786a5 [file] [log] [blame]
/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2003-2006 Apple Computer, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_WIN32)
#include <process.h>
#define usleep(X) Sleep(((X)+999)/1000)
#else
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include "mDNSEmbeddedAPI.h"
#include "DNSCommon.h"
#include "uDNS.h"
#include "uds_daemon.h"
#ifdef __ANDROID__
#include "cutils/sockets.h"
#endif
// Normally we append search domains only for queries with a single label that are not
// fully qualified. This can be overridden to apply search domains for queries (that are
// not fully qualified) with any number of labels e.g., moon, moon.cs, moon.cs.be, etc.
mDNSBool AlwaysAppendSearchDomains = mDNSfalse;
// Apple-specific functionality, not required for other platforms
#if APPLE_OSX_mDNSResponder
#include <sys/ucred.h>
#ifndef PID_FILE
#define PID_FILE ""
#endif
#endif
#if APPLE_OSX_mDNSResponder
#include <WebFilterDNS/WebFilterDNS.h>
#if ! NO_WCF
int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
// Do we really need to define a macro for "if"?
#define CHECK_WCF_FUNCTION(X) if (X)
#endif // ! NO_WCF
#else
#define NO_WCF 1
#endif // APPLE_OSX_mDNSResponder
// User IDs 0-500 are system-wide processes, not actual users in the usual sense
// User IDs for real user accounts start at 501 and count up from there
#define SystemUID(X) ((X) <= 500)
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - Types and Data Structures
#endif
typedef enum
{
t_uninitialized,
t_morecoming,
t_complete,
t_error,
t_terminated
} transfer_state;
typedef struct request_state request_state;
typedef void (*req_termination_fn)(request_state *request);
typedef struct registered_record_entry
{
struct registered_record_entry *next;
mDNSu32 key;
client_context_t regrec_client_context;
request_state *request;
mDNSBool external_advertise;
mDNSInterfaceID origInterfaceID;
AuthRecord *rr; // Pointer to variable-sized AuthRecord (Why a pointer? Why not just embed it here?)
} registered_record_entry;
// A single registered service: ServiceRecordSet + bookkeeping
// Note that we duplicate some fields from parent service_info object
// to facilitate cleanup, when instances and parent may be deallocated at different times.
typedef struct service_instance
{
struct service_instance *next;
request_state *request;
AuthRecord *subtypes;
mDNSBool renameonmemfree; // Set on config change when we deregister original name
mDNSBool clientnotified; // Has client been notified of successful registration yet?
mDNSBool default_local; // is this the "local." from an empty-string registration?
mDNSBool external_advertise; // is this is being advertised externally?
domainname domain;
ServiceRecordSet srs; // note -- variable-sized object -- must be last field in struct
} service_instance;
// for multi-domain default browsing
typedef struct browser_t
{
struct browser_t *next;
domainname domain;
DNSQuestion q;
} browser_t;
struct request_state
{
request_state *next;
request_state *primary; // If this operation is on a shared socket, pointer to primary
// request_state for the original DNSServiceCreateConnection() operation
dnssd_sock_t sd;
dnssd_sock_t errsd;
mDNSu32 uid;
void * platform_data;
// Note: On a shared connection these fields in the primary structure, including hdr, are re-used
// for each new request. This is because, until we've read the ipc_msg_hdr to find out what the
// operation is, we don't know if we're going to need to allocate a new request_state or not.
transfer_state ts;
mDNSu32 hdr_bytes; // bytes of header already read
ipc_msg_hdr hdr;
mDNSu32 data_bytes; // bytes of message data already read
char *msgbuf; // pointer to data storage to pass to free()
const char *msgptr; // pointer to data to be read from (may be modified)
char *msgend; // pointer to byte after last byte of message
// reply, termination, error, and client context info
int no_reply; // don't send asynchronous replies to client
mDNSs32 time_blocked; // record time of a blocked client
int unresponsiveness_reports;
struct reply_state *replies; // corresponding (active) reply list
req_termination_fn terminate;
DNSServiceFlags flags;
union
{
registered_record_entry *reg_recs; // list of registrations for a connection-oriented request
struct
{
mDNSInterfaceID interface_id;
mDNSBool default_domain;
mDNSBool ForceMCast;
domainname regtype;
browser_t *browsers;
} browser;
struct
{
mDNSInterfaceID InterfaceID;
mDNSu16 txtlen;
void *txtdata;
mDNSIPPort port;
domainlabel name;
char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
domainname type;
mDNSBool default_domain;
domainname host;
mDNSBool autoname; // Set if this name is tied to the Computer Name
mDNSBool autorename; // Set if this client wants us to automatically rename on conflict
mDNSBool allowremotequery; // Respond to unicast queries from outside the local link?
int num_subtypes;
service_instance *instances;
} servicereg;
struct
{
mDNSInterfaceID interface_id;
mDNSu32 flags;
mDNSu32 protocol;
DNSQuestion q4;
DNSQuestion *q42;
DNSQuestion q6;
DNSQuestion *q62;
} addrinfo;
struct
{
mDNSIPPort ReqExt; // External port we originally requested, for logging purposes
NATTraversalInfo NATinfo;
} pm;
struct
{
#if 0
DNSServiceFlags flags;
#endif
DNSQuestion q_all;
DNSQuestion q_default;
} enumeration;
struct
{
DNSQuestion q;
DNSQuestion *q2;
} queryrecord;
struct
{
DNSQuestion qtxt;
DNSQuestion qsrv;
const ResourceRecord *txt;
const ResourceRecord *srv;
mDNSs32 ReportTime;
mDNSBool external_advertise;
} resolve;
} u;
};
// struct physically sits between ipc message header and call-specific fields in the message buffer
typedef struct
{
DNSServiceFlags flags; // Note: This field is in NETWORK byte order
mDNSu32 ifi; // Note: This field is in NETWORK byte order
DNSServiceErrorType error; // Note: This field is in NETWORK byte order
} reply_hdr;
typedef struct reply_state
{
struct reply_state *next; // If there are multiple unsent replies
mDNSu32 totallen;
mDNSu32 nwriten;
ipc_msg_hdr mhdr[1];
reply_hdr rhdr[1];
} reply_state;
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - Globals
#endif
// globals
mDNSexport mDNS mDNSStorage;
mDNSexport const char ProgramName[] = "mDNSResponder";
static dnssd_sock_t listenfd = dnssd_InvalidSocket;
static request_state *all_requests = NULL;
// Note asymmetry here between registration and browsing.
// For service registrations we only automatically register in domains that explicitly appear in local configuration data
// (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
// For service browsing we also learn automatic browsing domains from the network, so for that case we have:
// 1. SCPrefBrowseDomains (local configuration data)
// 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
// 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
// By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
mDNSexport DNameListElem *AutoRegistrationDomains; // Domains where we automatically register for empty-string registrations
static DNameListElem *SCPrefBrowseDomains; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
static ARListElem *LocalDomainEnumRecords; // List of locally-generated PTR records to augment those we learn from the network
mDNSexport DNameListElem *AutoBrowseDomains; // List created from those local-only PTR records plus records we get from the network
#define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
// n get_string() calls w/o buffer overrun
// initialization, setup/teardown functions
// If a platform specifies its own PID file name, we use that
#ifndef PID_FILE
#define PID_FILE "/var/run/mDNSResponder.pid"
#endif
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - General Utility Functions
#endif
mDNSlocal void FatalError(char *errmsg)
{
LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
*(volatile long*)0 = 0; // On OS X abort() doesn't generate a crash log, but writing to zero does
abort(); // On platforms where writing to zero doesn't generate an exception, abort instead
}
mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
{
mDNSu32 ret;
char *data = (char*) &ret;
put_uint32(l, &data);
return ret;
}
// hack to search-replace perror's to LogMsg's
mDNSlocal void my_perror(char *errmsg)
{
LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
}
mDNSlocal void abort_request(request_state *req)
{
if (req->terminate == (req_termination_fn)~0)
{ LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
// First stop whatever mDNSCore operation we were doing
// If this is actually a shared connection operation, then its req->terminate function will scan
// the all_requests list and terminate any subbordinate operations sharing this file descriptor
if (req->terminate) req->terminate(req);
if (!dnssd_SocketValid(req->sd))
{ LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req, req->sd); return; }
// Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
if (!req->primary)
{
if (req->errsd != req->sd) LogOperation("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
else LogOperation("%3d: Removing FD", req->sd);
udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data); // Note: This also closes file descriptor req->sd for us
if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
while (req->replies) // free pending replies
{
reply_state *ptr = req->replies;
req->replies = req->replies->next;
freeL("reply_state (abort)", ptr);
}
}
// Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
#if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
// Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
// for detecting when the memory for an object is inadvertently freed while the object is still on some list
req->sd = req->errsd = -2;
#else
req->sd = req->errsd = dnssd_InvalidSocket;
#endif
// We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
req->terminate = (req_termination_fn)~0;
}
mDNSlocal void AbortUnlinkAndFree(request_state *req)
{
request_state **p = &all_requests;
abort_request(req);
while (*p && *p != req) p=&(*p)->next;
if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
}
mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
{
reply_state *reply;
if ((unsigned)datalen < sizeof(reply_hdr))
{
LogMsg("ERROR: create_reply - data length less than length of required fields");
return NULL;
}
reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
if (!reply) FatalError("ERROR: malloc");
reply->next = mDNSNULL;
reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
reply->nwriten = 0;
reply->mhdr->version = VERSION;
reply->mhdr->datalen = (mDNSu32)datalen;
reply->mhdr->ipc_flags = 0;
reply->mhdr->op = op;
reply->mhdr->client_context = request->hdr.client_context;
reply->mhdr->reg_index = 0;
return reply;
}
// Append a reply to the list in a request object
// If our request is sharing a connection, then we append our reply_state onto the primary's list
mDNSlocal void append_reply(request_state *req, reply_state *rep)
{
request_state *r = req->primary ? req->primary : req;
reply_state **ptr = &r->replies;
while (*ptr) ptr = &(*ptr)->next;
*ptr = rep;
rep->next = NULL;
}
// Generates a response message giving name, type, domain, plus interface index,
// suitable for a browse result or service registration result.
// On successful completion rep is set to point to a malloc'd reply_state struct
mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
{
domainlabel name;
domainname type, dom;
*rep = NULL;
if (!DeconstructServiceName(servicename, &name, &type, &dom))
return kDNSServiceErr_Invalid;
else
{
char namestr[MAX_DOMAIN_LABEL+1];
char typestr[MAX_ESCAPED_DOMAIN_NAME];
char domstr [MAX_ESCAPED_DOMAIN_NAME];
int len;
char *data;
ConvertDomainLabelToCString_unescaped(&name, namestr);
ConvertDomainNameToCString(&type, typestr);
ConvertDomainNameToCString(&dom, domstr);
// Calculate reply data length
len = sizeof(DNSServiceFlags);
len += sizeof(mDNSu32); // if index
len += sizeof(DNSServiceErrorType);
len += (int) (strlen(namestr) + 1);
len += (int) (strlen(typestr) + 1);
len += (int) (strlen(domstr) + 1);
// Build reply header
*rep = create_reply(op, len, request);
(*rep)->rhdr->flags = dnssd_htonl(flags);
(*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
(*rep)->rhdr->error = dnssd_htonl(err);
// Build reply body
data = (char *)&(*rep)->rhdr[1];
put_string(namestr, &data);
put_string(typestr, &data);
put_string(domstr, &data);
return mStatus_NoError;
}
}
// Special support to enable the DNSServiceBrowse call made by Bonjour Browser
// Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
mDNSlocal void GenerateBonjourBrowserResponse(const domainname *const servicename, const mDNSInterfaceID id,
request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
{
char namestr[MAX_DOMAIN_LABEL+1];
char typestr[MAX_ESCAPED_DOMAIN_NAME];
static const char domstr[] = ".";
int len;
char *data;
*rep = NULL;
// 1. Put first label in namestr
ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
// 2. Put second label and "local" into typestr
mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
// Calculate reply data length
len = sizeof(DNSServiceFlags);
len += sizeof(mDNSu32); // if index
len += sizeof(DNSServiceErrorType);
len += (int) (strlen(namestr) + 1);
len += (int) (strlen(typestr) + 1);
len += (int) (strlen(domstr) + 1);
// Build reply header
*rep = create_reply(op, len, request);
(*rep)->rhdr->flags = dnssd_htonl(flags);
(*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
(*rep)->rhdr->error = dnssd_htonl(err);
// Build reply body
data = (char *)&(*rep)->rhdr[1];
put_string(namestr, &data);
put_string(typestr, &data);
put_string(domstr, &data);
}
// Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
// Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
// (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
{
DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
char name[256];
int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
mDNSu16 type = get_uint16(&request->msgptr, request->msgend);
mDNSu16 class = get_uint16(&request->msgptr, request->msgend);
mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
mDNSu32 ttl = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
int storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
AuthRecord *rr;
mDNSInterfaceID InterfaceID;
AuthRecType artype;
request->flags = flags;
if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
if (validate_flags &&
!((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
!((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
{
LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
return NULL;
}
rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
if (!rr) FatalError("ERROR: malloc");
InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
if (InterfaceID == mDNSInterface_LocalOnly)
artype = AuthRecordLocalOnly;
else if (InterfaceID == mDNSInterface_P2P)
artype = AuthRecordP2P;
else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
artype = AuthRecordAnyIncludeP2P;
else
artype = AuthRecordAny;
mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
(mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
{
LogMsg("ERROR: bad name: %s", name);
freeL("AuthRecord/read_rr_from_ipc_msg", rr);
return NULL;
}
if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
rr->resrec.rrclass = class;
rr->resrec.rdlength = rdlen;
rr->resrec.rdata->MaxRDLength = rdlen;
mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
if (GetTTL) rr->resrec.rroriginalttl = ttl;
rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
return rr;
}
mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
{
domainlabel n;
domainname d, t;
if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
return 0;
}
mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
{
int n = send(s, ptr, len, 0);
// On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
// (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
// If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
if (n < len)
LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
}
#if 0
mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
{
const DNameListElem *delem = mDNSNULL;
int bestDelta = -1; // the delta of the best match, lower is better
int dLabels = 0;
mDNSBool allow = mDNSfalse;
if (SystemUID(request->uid)) return mDNStrue;
dLabels = CountLabels(d);
for (delem = doms; delem; delem = delem->next)
{
if (delem->uid)
{
int delemLabels = CountLabels(&delem->name);
int delta = dLabels - delemLabels;
if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
{
bestDelta = delta;
allow = (allow || (delem->uid == request->uid));
}
}
}
return bestDelta == -1 ? mDNStrue : allow;
}
#endif
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - external helpers
#endif
mDNSlocal void external_start_advertising_helper(service_instance *const instance)
{
AuthRecord *st = instance->subtypes;
ExtraResourceRecord *e;
int i;
if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
{
LogInfo("external_start_advertising_helper: Not registering service with port number zero");
return;
}
#if APPLE_OSX_mDNSResponder
// Update packet filter if p2p interface already exists, otherwise,
// if will be updated when we get the KEV_DL_IF_ATTACHED event for
// the interface. Called here since we don't call external_start_advertising_service()
// with the SRV record when advertising a service.
mDNSInitPacketFilter();
#endif // APPLE_OSX_mDNSResponder
if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
external_start_advertising_service(&st[i].resrec);
external_start_advertising_service(&instance->srs.RR_PTR.resrec);
external_start_advertising_service(&instance->srs.RR_TXT.resrec);
for (e = instance->srs.Extras; e; e = e->next)
external_start_advertising_service(&e->r.resrec);
instance->external_advertise = mDNStrue;
}
mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
{
AuthRecord *st = instance->subtypes;
ExtraResourceRecord *e;
int i;
if (!instance->external_advertise) return;
LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
external_stop_advertising_service(&st[i].resrec);
external_stop_advertising_service(&instance->srs.RR_PTR.resrec);
external_stop_advertising_service(&instance->srs.RR_TXT.resrec);
for (e = instance->srs.Extras; e; e = e->next)
external_stop_advertising_service(&e->r.resrec);
instance->external_advertise = mDNSfalse;
}
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceRegister
#endif
mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
{
ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
(void)m; // Unused
if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
LogInfo(" FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
if (rr->resrec.rdata != &rr->rdatastorage)
freeL("Extra RData", rr->resrec.rdata);
freeL("ExtraResourceRecord/FreeExtraRR", extra);
}
mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
{
ExtraResourceRecord *e = srv->srs.Extras, *tmp;
external_stop_advertising_helper(srv);
// clear pointers from parent struct
if (srv->request)
{
service_instance **p = &srv->request->u.servicereg.instances;
while (*p)
{
if (*p == srv) { *p = (*p)->next; break; }
p = &(*p)->next;
}
}
while (e)
{
e->r.RecordContext = e;
tmp = e;
e = e->next;
FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
}
if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
if (srv->subtypes) { freeL("ServiceSubTypes", srv->subtypes); srv->subtypes = NULL; }
freeL("service_instance", srv);
}
// Count how many other service records we have locally with the same name, but different rdata.
// For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
// the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
mDNSexport int CountPeerRegistrations(mDNS *const m, ServiceRecordSet *const srs)
{
int count = 0;
ResourceRecord *r = &srs->RR_SRV.resrec;
AuthRecord *rr;
for (rr = m->ResourceRecords; rr; rr=rr->next)
if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
count++;
verbosedebugf("%d peer registrations for %##s", count, r->name->c);
return(count);
}
mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
{
int count = 0;
AuthRecord *rr;
for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
if (rr->resrec.rrtype == kDNSType_SRV &&
mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
SameDomainName(rr->resrec.name, srv))
count++;
return(count);
}
mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
{
reply_state *rep;
service_instance *instance = srs->ServiceContext;
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
}
// service registration callback performs three duties - frees memory for deregistered services,
// handles name conflicts, and delivers completed registration information to the client
mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
{
mStatus err;
mDNSBool SuppressError = mDNSfalse;
service_instance *instance;
reply_state *rep;
(void)m; // Unused
if (!srs) { LogMsg("regservice_callback: srs is NULL %d", result); return; }
instance = srs->ServiceContext;
if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
// don't send errors up to client for wide-area, empty-string registrations
if (instance->request &&
instance->request->u.servicereg.default_domain &&
!instance->default_local)
SuppressError = mDNStrue;
if (mDNS_LoggingEnabled)
{
const char *const fmt =
(result == mStatus_NoError) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
(result == mStatus_MemFree) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
(result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
"%s DNSServiceRegister(%##s, %u) %s %d";
char prefix[16] = "---:";
if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
SuppressError ? "suppressed error" : "CALLBACK", result);
}
if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
if (result == mStatus_NoError)
{
if (instance->request->u.servicereg.allowremotequery)
{
ExtraResourceRecord *e;
srs->RR_ADV.AllowRemoteQuery = mDNStrue;
srs->RR_PTR.AllowRemoteQuery = mDNStrue;
srs->RR_SRV.AllowRemoteQuery = mDNStrue;
srs->RR_TXT.AllowRemoteQuery = mDNStrue;
for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
}
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
if (instance->request->u.servicereg.InterfaceID == mDNSInterface_P2P || (!instance->request->u.servicereg.InterfaceID && SameDomainName(&instance->domain, &localdomain) && (instance->request->flags & kDNSServiceFlagsIncludeP2P)))
{
LogInfo("regservice_callback: calling external_start_advertising_helper()");
external_start_advertising_helper(instance);
}
if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
RecordUpdatedNiceLabel(m, 0); // Successfully got new name, tell user immediately
}
else if (result == mStatus_MemFree)
{
if (instance->request && instance->renameonmemfree)
{
external_stop_advertising_helper(instance);
instance->renameonmemfree = 0;
err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
// error should never happen - safest to log and continue
}
else
unlink_and_free_service_instance(instance);
}
else if (result == mStatus_NameConflict)
{
if (instance->request->u.servicereg.autorename)
{
external_stop_advertising_helper(instance);
if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
{
// On conflict for an autoname service, rename and reregister *all* autoname services
IncrementLabelSuffix(&m->nicelabel, mDNStrue);
mDNS_ConfigChanged(m); // Will call back into udsserver_handle_configchange()
}
else // On conflict for a non-autoname service, rename and reregister just that one service
{
if (instance->clientnotified) SendServiceRemovalNotification(srs);
mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
}
}
else
{
if (!SuppressError)
{
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
}
unlink_and_free_service_instance(instance);
}
}
else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
{
if (!SuppressError)
{
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
}
}
}
mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
{
(void)m; // Unused
if (!rr->RecordContext) // parent struct already freed by termination callback
{
if (result == mStatus_NoError)
LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
else
{
if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
// We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
// If the record has been updated, we need to free the rdata. Everytime we call mDNS_Update, it calls update_callback
// with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
// to free the latest rdata for which the update_callback was never called with.
if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
freeL("AuthRecord/regrecord_callback", rr);
}
}
else
{
registered_record_entry *re = rr->RecordContext;
request_state *request = re->request;
if (mDNS_LoggingEnabled)
{
char *fmt = (result == mStatus_NoError) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
(result == mStatus_MemFree) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
(result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
"%3d: DNSServiceRegisterRecord(%u %s) %d";
LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
}
if (result != mStatus_MemFree)
{
int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
reply_state *reply = create_reply(reg_record_reply_op, len, request);
reply->mhdr->client_context = re->regrec_client_context;
reply->rhdr->flags = dnssd_htonl(0);
reply->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
reply->rhdr->error = dnssd_htonl(result);
append_reply(request, reply);
}
if (result)
{
// unlink from list, free memory
registered_record_entry **ptr = &request->u.reg_recs;
while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
*ptr = (*ptr)->next;
freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
freeL("registered_record_entry regrecord_callback", re);
}
else
{
if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
if (re->origInterfaceID == mDNSInterface_P2P || (!re->origInterfaceID && IsLocalDomain(&rr->namestorage) && (request->flags & kDNSServiceFlagsIncludeP2P)))
{
LogInfo("regrecord_callback: calling external_start_advertising_service");
external_start_advertising_service(&rr->resrec);
re->external_advertise = mDNStrue;
}
}
}
}
mDNSlocal void connection_termination(request_state *request)
{
// When terminating a shared connection, we need to scan the all_requests list
// and terminate any subbordinate operations sharing this file descriptor
request_state **req = &all_requests;
LogOperation("%3d: DNSServiceCreateConnection STOP", request->sd);
while (*req)
{
if ((*req)->primary == request)
{
// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
request_state *tmp = *req;
if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp, tmp->sd);
if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
abort_request(tmp);
*req = tmp->next;
freeL("request_state/connection_termination", tmp);
}
else
req = &(*req)->next;
}
while (request->u.reg_recs)
{
registered_record_entry *ptr = request->u.reg_recs;
LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec));
request->u.reg_recs = request->u.reg_recs->next;
ptr->rr->RecordContext = NULL;
if (ptr->external_advertise)
{
ptr->external_advertise = mDNSfalse;
external_stop_advertising_service(&ptr->rr->resrec);
}
mDNS_Deregister(&mDNSStorage, ptr->rr); // Will free ptr->rr for us
freeL("registered_record_entry/connection_termination", ptr);
}
}
mDNSlocal void handle_cancel_request(request_state *request)
{
request_state **req = &all_requests;
LogOperation("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
while (*req)
{
if ((*req)->primary == request &&
(*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
(*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
{
// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
request_state *tmp = *req;
abort_request(tmp);
*req = tmp->next;
freeL("request_state/handle_cancel_request", tmp);
}
else
req = &(*req)->next;
}
}
mDNSlocal mStatus handle_regrecord_request(request_state *request)
{
mStatus err = mStatus_BadParamErr;
AuthRecord *rr = read_rr_from_ipc_msg(request, 1, 1);
if (rr)
{
registered_record_entry *re;
// Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
// clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
rr->resrec.rrtype == kDNSType_CNAME))
{
freeL("AuthRecord/handle_regrecord_request", rr);
return (mStatus_BadParamErr);
}
// allocate registration entry, link into list
re = mallocL("registered_record_entry", sizeof(registered_record_entry));
if (!re) FatalError("ERROR: malloc");
re->key = request->hdr.reg_index;
re->rr = rr;
re->regrec_client_context = request->hdr.client_context;
re->request = request;
re->external_advertise = mDNSfalse;
rr->RecordContext = re;
rr->RecordCallback = regrecord_callback;
re->origInterfaceID = rr->resrec.InterfaceID;
if (rr->resrec.InterfaceID == mDNSInterface_P2P) rr->resrec.InterfaceID = mDNSInterface_Any;
#if 0
if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError);
#endif
if (rr->resrec.rroriginalttl == 0)
rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);
LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec));
err = mDNS_Register(&mDNSStorage, rr);
if (err)
{
LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec), err);
freeL("registered_record_entry", re);
freeL("registered_record_entry/AuthRecord", rr);
}
else
{
re->next = request->u.reg_recs;
request->u.reg_recs = re;
}
}
return(err);
}
mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);
mDNSlocal void regservice_termination_callback(request_state *request)
{
if (!request) { LogMsg("regservice_termination_callback context is NULL"); return; }
while (request->u.servicereg.instances)
{
service_instance *p = request->u.servicereg.instances;
request->u.servicereg.instances = request->u.servicereg.instances->next;
// only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP",
request->sd, p->srs.RR_SRV.resrec.name->c, mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port));
external_stop_advertising_helper(p);
// Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
// We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
// request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
// We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
// because by then we might have already freed p
p->request = NULL;
if (mDNS_DeregisterService(&mDNSStorage, &p->srs)) unlink_and_free_service_instance(p);
// Don't touch service_instance *p after this -- it's likely to have been freed already
}
if (request->u.servicereg.txtdata)
{ freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
if (request->u.servicereg.autoname)
{
// Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
request->u.servicereg.autoname = mDNSfalse;
UpdateDeviceInfoRecord(&mDNSStorage);
}
}
mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
{
request_state *req;
for (req = all_requests; req; req = req->next)
if (req->primary == request &&
req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
return(request);
}
mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl)
{
ServiceRecordSet *srs = &instance->srs;
mStatus result;
int size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord)); // OK if oversized rdata not zero'd
extra->r.resrec.rrtype = rrtype;
extra->r.rdatastorage.MaxRDLength = (mDNSu16) size;
extra->r.resrec.rdlength = rdlen;
mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen);
result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl,
(request->flags & kDNSServiceFlagsIncludeP2P) ? 1: 0);
if (result) { freeL("ExtraResourceRecord/add_record_to_service", extra); return result; }
extra->ClientID = request->hdr.reg_index;
if (instance->external_advertise && (instance->request->u.servicereg.InterfaceID == mDNSInterface_P2P || (!instance->request->u.servicereg.InterfaceID && SameDomainName(&instance->domain, &localdomain) && (instance->request->flags & kDNSServiceFlagsIncludeP2P))))
{
LogInfo("add_record_to_service: calling external_start_advertising_service");
external_start_advertising_service(&extra->r.resrec);
}
return result;
}
mDNSlocal mStatus handle_add_request(request_state *request)
{
service_instance *i;
mStatus result = mStatus_UnknownErr;
DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);
mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend);
mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
if (!ttl) ttl = DefaultTTLforRRType(rrtype);
(void)flags; // Unused
if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
// If this is a shared connection, check if the operation actually applies to a subordinate request_state object
if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
if (request->terminate != regservice_termination_callback)
{ LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
// For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
// in the application. See radar://9165807.
if (mDNSIPPortIsZero(request->u.servicereg.port))
{ LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d)", request->sd, flags,
(request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen);
for (i = request->u.servicereg.instances; i; i = i->next)
{
result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
if (result && i->default_local) break;
else result = mStatus_NoError; // suppress non-local default errors
}
return(result);
}
mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
{
mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
(void)m; // Unused
// There are three cases.
//
// 1. We have updated the primary TXT record of the service
// 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
// 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
//
// external_advertise is set if we have advertised at least once during the initial addition
// of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
// checks during the first time and hence we don't do any checks here
if (external_advertise)
{
ResourceRecord ext = rr->resrec;
if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
SetNewRData(&ext, oldrd, oldrdlen);
external_stop_advertising_service(&ext);
LogInfo("update_callback: calling external_start_advertising_service");
external_start_advertising_service(&rr->resrec);
}
exit:
if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
}
mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl, const mDNSBool *const external_advertise)
{
mStatus result;
const int rdsize = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
RData *newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize);
if (!newrd) FatalError("ERROR: malloc");
newrd->MaxRDLength = (mDNSu16) rdsize;
mDNSPlatformMemCopy(&newrd->u, rdata, rdlen);
// BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
// since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
// Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }
if (external_advertise) rr->UpdateContext = (void *)external_advertise;
result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback);
if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, rr)); freeL("RData/update_record", newrd); }
return result;
}
mDNSlocal mStatus handle_update_request(request_state *request)
{
const ipc_msg_hdr *const hdr = &request->hdr;
mStatus result = mStatus_BadReferenceErr;
service_instance *i;
AuthRecord *rr = NULL;
// get the message data
DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend); // flags unused
mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
(void)flags; // Unused
if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
// If this is a shared connection, check if the operation actually applies to a subordinate request_state object
if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
if (request->terminate == connection_termination)
{
// update an individually registered record
registered_record_entry *reptr;
for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
{
if (reptr->key == hdr->reg_index)
{
result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise);
LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)",
request->sd, reptr->rr->resrec.name->c, reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>");
goto end;
}
}
result = mStatus_BadReferenceErr;
goto end;
}
if (request->terminate != regservice_termination_callback)
{ LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
// For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
if (mDNSIPPortIsZero(request->u.servicereg.port))
{ LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
// update the saved off TXT data for the service
if (hdr->reg_index == TXT_RECORD_INDEX)
{
if (request->u.servicereg.txtdata)
{ freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
if (rdlen > 0)
{
request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
}
request->u.servicereg.txtlen = rdlen;
}
// update a record from a service record set
for (i = request->u.servicereg.instances; i; i = i->next)
{
if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
else
{
ExtraResourceRecord *e;
for (e = i->srs.Extras; e; e = e->next)
if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
}
if (!rr) { result = mStatus_BadReferenceErr; goto end; }
result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise);
if (result && i->default_local) goto end;
else result = mStatus_NoError; // suppress non-local default errors
}
end:
if (request->terminate == regservice_termination_callback)
LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request->sd,
(request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>");
return(result);
}
// remove a resource record registered via DNSServiceRegisterRecord()
mDNSlocal mStatus remove_record(request_state *request)
{
mStatus err = mStatus_UnknownErr;
registered_record_entry *e, **ptr = &request->u.reg_recs;
while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
e = *ptr;
*ptr = e->next; // unlink
LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec));
e->rr->RecordContext = NULL;
if (e->external_advertise)
{
external_stop_advertising_service(&e->rr->resrec);
e->external_advertise = mDNSfalse;
}
err = mDNS_Deregister(&mDNSStorage, e->rr); // Will free e->rr for us; we're responsible for freeing e
if (err)
{
LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
freeL("registered_record_entry AuthRecord remove_record", e->rr);
}
freeL("registered_record_entry remove_record", e);
return err;
}
mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
{
mStatus err = mStatus_BadReferenceErr;
ExtraResourceRecord *ptr;
for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
{
if (ptr->ClientID == request->hdr.reg_index) // found match
{
*rrtype = ptr->r.resrec.rrtype;
if (serv->external_advertise) external_stop_advertising_service(&ptr->r.resrec);
err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
break;
}
}
return err;
}
mDNSlocal mStatus handle_removerecord_request(request_state *request)
{
mStatus err = mStatus_BadReferenceErr;
get_flags(&request->msgptr, request->msgend); // flags unused
if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
// If this is a shared connection, check if the operation actually applies to a subordinate request_state object
if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
if (request->terminate == connection_termination)
err = remove_record(request); // remove individually registered record
else if (request->terminate != regservice_termination_callback)
{ LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
else
{
service_instance *i;
mDNSu16 rrtype = 0;
LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request->sd,
(request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
rrtype ? DNSTypeName(rrtype) : "<NONE>");
for (i = request->u.servicereg.instances; i; i = i->next)
{
err = remove_extra(request, i, &rrtype);
if (err && i->default_local) break;
else err = mStatus_NoError; // suppress non-local default errors
}
}
return(err);
}
// If there's a comma followed by another character,
// FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
// Otherwise, it returns a pointer to the final nul at the end of the string
mDNSlocal char *FindFirstSubType(char *p)
{
while (*p)
{
if (p[0] == '\\' && p[1]) p += 2;
else if (p[0] == ',' && p[1]) { *p++ = 0; return(p); }
else p++;
}
return(p);
}
// If there's a comma followed by another character,
// FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
// If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
// Otherwise, it returns a pointer to the final nul at the end of the string
mDNSlocal char *FindNextSubType(char *p)
{
while (*p)
{
if (p[0] == '\\' && p[1]) // If escape character
p += 2; // ignore following character
else if (p[0] == ',') // If we found a comma
{
if (p[1]) *p++ = 0;
return(p);
}
else if (p[0] == '.')
return(mDNSNULL);
else p++;
}
return(p);
}
// Returns -1 if illegal subtype found
mDNSexport mDNSs32 ChopSubTypes(char *regtype)
{
mDNSs32 NumSubTypes = 0;
char *stp = FindFirstSubType(regtype);
while (stp && *stp) // If we found a comma...
{
if (*stp == ',') return(-1);
NumSubTypes++;
stp = FindNextSubType(stp);
}
if (!stp) return(-1);
return(NumSubTypes);
}
mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p)
{
AuthRecord *st = mDNSNULL;
if (NumSubTypes)
{
mDNSs32 i;
st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
if (!st) return(mDNSNULL);
for (i = 0; i < NumSubTypes; i++)
{
mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
while (*p) p++;
p++;
if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
{ freeL("ServiceSubTypes", st); return(mDNSNULL); }
}
}
return(st);
}
mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
{
service_instance **ptr, *instance;
const int extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
mStatus result;
mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;
mDNSu32 regFlags = 0;
if (interfaceID == mDNSInterface_P2P)
{
interfaceID = mDNSInterface_Any;
regFlags |= regFlagIncludeP2P;
}
else if (request->flags & kDNSServiceFlagsIncludeP2P)
regFlags |= regFlagIncludeP2P;
// client guarantees that record names are unique
if (request->flags & kDNSServiceFlagsForce)
regFlags |= regFlagKnownUnique;
// If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
// registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
// registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
// (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
// currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;
for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
{
if (SameDomainName(&(*ptr)->domain, domain))
{
LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
return mStatus_AlreadyRegistered;
}
}
if (mDNSStorage.KnownBugs & mDNS_KnownBug_LimitedIPv6)
{
// Special-case hack: On Mac OS X 10.6.x and earlier we don't advertise SMB service in AutoTunnel domains,
// because AutoTunnel services have to support IPv6, and in Mac OS X 10.6.x the SMB server does not.
// <rdar://problem/5482322> BTMM: Don't advertise SMB with BTMM because it doesn't support IPv6
if (SameDomainName(&request->u.servicereg.type, (const domainname *) "\x4" "_smb" "\x4" "_tcp"))
{
DomainAuthInfo *AuthInfo = GetAuthInfoForName(&mDNSStorage, domain);
if (AuthInfo && AuthInfo->AutoTunnel) return(kDNSServiceErr_Unsupported);
}
}
instance = mallocL("service_instance", sizeof(*instance) + extra_size);
if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
instance->next = mDNSNULL;
instance->request = request;
instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string);
instance->renameonmemfree = 0;
instance->clientnotified = mDNSfalse;
instance->default_local = (request->u.servicereg.default_domain && DomainIsLocal);
instance->external_advertise = mDNSfalse;
AssignDomainName(&instance->domain, domain);
if (request->u.servicereg.num_subtypes && !instance->subtypes)
{ unlink_and_free_service_instance(instance); instance = NULL; FatalError("ERROR: malloc"); }
result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
&request->u.servicereg.name, &request->u.servicereg.type, domain,
request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
request->u.servicereg.port,
request->u.servicereg.txtdata, request->u.servicereg.txtlen,
instance->subtypes, request->u.servicereg.num_subtypes,
interfaceID, regservice_callback, instance, regFlags);
if (!result)
{
*ptr = instance; // Append this to the end of our request->u.servicereg.instances list
LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED",
instance->request->sd, instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
}
else
{
LogMsg("register_service_instance %#s.%##s%##s error %d",
&request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
unlink_and_free_service_instance(instance);
}
return result;
}
mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
{
request_state *request;
#if APPLE_OSX_mDNSResponder
machserver_automatic_registration_domain_changed(&d->name, add);
#endif // APPLE_OSX_mDNSResponder
LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
for (request = all_requests; request; request = request->next)
{
if (request->terminate != regservice_termination_callback) continue;
if (!request->u.servicereg.default_domain) continue;
if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
{
service_instance **ptr = &request->u.servicereg.instances;
while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
if (add)
{
// If we don't already have this domain in our list for this registration, add it now
if (!*ptr) register_service_instance(request, &d->name);
else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
}
else
{
// Normally we should not fail to find the specified instance
// One case where this can happen is if a uDNS update fails for some reason,
// and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
if (!*ptr)
LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
&d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
else
{
DNameListElem *p;
for (p = AutoRegistrationDomains; p; p=p->next)
if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
if (SameDomainName(&d->name, &p->name)) break;
if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
else
{
mStatus err;
service_instance *si = *ptr;
*ptr = si->next;
if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
// Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
// Otherwise what can happen is this: While our mDNS_DeregisterService is in the
// process of completing asynchronously, the client cancels the entire operation, so
// regservice_termination_callback then runs through the whole list deregistering each
// instance, clearing the backpointers, and then disposing the parent request_state object.
// However, because this service_instance isn't in the list any more, regservice_termination_callback
// has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
// completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
// a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
si->request = NULL;
err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
}
}
}
}
}
}
mDNSlocal mStatus handle_regservice_request(request_state *request)
{
char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
domainname d, srv;
mStatus err;
const char *msgTXTData;
DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
if (interfaceIndex && !InterfaceID)
{ LogMsg("ERROR: handle_regservice_request - Couldn't find interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); }
if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
{ LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
request->flags = flags;
request->u.servicereg.InterfaceID = InterfaceID;
request->u.servicereg.instances = NULL;
request->u.servicereg.txtlen = 0;
request->u.servicereg.txtdata = NULL;
mDNSPlatformStrLCopy(request->u.servicereg.type_as_string, type_as_string, sizeof(request->u.servicereg.type_as_string));
if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
else
{
request->u.servicereg.port.b[0] = *request->msgptr++;
request->u.servicereg.port.b[1] = *request->msgptr++;
}
request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);
if (!request->msgptr)
{
LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd);
return(mStatus_BadParamErr);
}
if (request->u.servicereg.txtlen)
{
request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
}
// Check for sub-types after the service type
request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string); // Note: Modifies regtype string to remove trailing subtypes
if (request->u.servicereg.num_subtypes < 0)
{ LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); }
// Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
{ LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); }
if (!name[0])
{
request->u.servicereg.name = mDNSStorage.nicelabel;
request->u.servicereg.autoname = mDNStrue;
}
else
{
// If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
{
int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
name[newlen] = 0;
}
if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
{ LogMsg("ERROR: handle_regservice_request - name bad %s", name); return(mStatus_BadParamErr); }
request->u.servicereg.autoname = mDNSfalse;
}
if (*domain)
{
request->u.servicereg.default_domain = mDNSfalse;
if (!MakeDomainNameFromDNSNameString(&d, domain))
{ LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); return(mStatus_BadParamErr); }
}
else
{
request->u.servicereg.default_domain = mDNStrue;
MakeDomainNameFromDNSNameString(&d, "local.");
}
if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
{
LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); return(mStatus_BadParamErr);
}
if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
{ LogMsg("ERROR: handle_regservice_request - host bad %s", host); return(mStatus_BadParamErr); }
request->u.servicereg.autorename = (flags & kDNSServiceFlagsNoAutoRename ) == 0;
request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
// Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
// a port number of zero. When two instances of the protected client are allowed to run on one
// machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
if (!mDNSIPPortIsZero(request->u.servicereg.port))
{
int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
if (count)
LogMsg("Client application registered %d identical instances of service %##s port %u.",
count+1, srv.c, mDNSVal16(request->u.servicereg.port));
}
LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START",
request->sd, flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host, mDNSVal16(request->u.servicereg.port));
// We need to unconditionally set request->terminate, because even if we didn't successfully
// start any registrations right now, subsequent configuration changes may cause successful
// registrations to be added, and we'll need to cancel them before freeing this memory.
// We also need to set request->terminate first, before adding additional service instances,
// because the uds_validatelists uses the request->terminate function pointer to determine
// what kind of request this is, and therefore what kind of list validation is required.
request->terminate = regservice_termination_callback;
err = register_service_instance(request, &d);
#if 0
err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
#endif
if (!err)
{
if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
if (!*domain)
{
DNameListElem *ptr;
// Note that we don't report errors for non-local, non-explicit domains
for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
register_service_instance(request, &ptr->name);
}
}
return(err);
}
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceBrowse
#endif
mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
{
const DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
request_state *req = question->QuestionContext;
reply_state *rep;
(void)m; // Unused
if (answer->rrtype != kDNSType_PTR)
{ LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
{
if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
{
// Special support to enable the DNSServiceBrowse call made by Bonjour Browser
// Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
GenerateBonjourBrowserResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
goto bonjourbrowserhack;
}
LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
req->sd, answer->name->c, answer->rdata->u.name.c);
return;
}
bonjourbrowserhack:
LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "Add" : "Rmv",
mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
append_reply(req, rep);
}
mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
{
browser_t *b, *p;
mStatus err;
for (p = info->u.browser.browsers; p; p = p->next)
{
if (SameDomainName(&p->domain, d))
{ debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
}
b = mallocL("browser_t", sizeof(*b));
if (!b) return mStatus_NoMemoryErr;
AssignDomainName(&b->domain, d);
err = mDNS_StartBrowse(&mDNSStorage, &b->q,
&info->u.browser.regtype, d, info->u.browser.interface_id, info->u.browser.ForceMCast, FoundInstance, info);
if (err)
{
LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
freeL("browser_t/add_domain_to_browser", b);
}
else
{
b->next = info->u.browser.browsers;
info->u.browser.browsers = b;
LogOperation("%3d: DNSServiceBrowse(%##s) START", info->sd, b->q.qname.c);
if (info->u.browser.interface_id == mDNSInterface_P2P || (!info->u.browser.interface_id && SameDomainName(&b->domain, &localdomain) && (info->flags & kDNSServiceFlagsIncludeP2P)))
{
domainname tmp;
ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
LogInfo("add_domain_to_browser: calling external_start_browsing_for_service()");
external_start_browsing_for_service(&mDNSStorage, &tmp, kDNSType_PTR);
}
}
return err;
}
mDNSlocal void browse_termination_callback(request_state *info)
{
while (info->u.browser.browsers)
{
browser_t *ptr = info->u.browser.browsers;
if (info->u.browser.interface_id == mDNSInterface_P2P || (!info->u.browser.interface_id && SameDomainName(&ptr->domain, &localdomain) && (info->flags & kDNSServiceFlagsIncludeP2P)))
{
domainname tmp;
ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
external_stop_browsing_for_service(&mDNSStorage, &tmp, kDNSType_PTR);
}
info->u.browser.browsers = ptr->next;
LogOperation("%3d: DNSServiceBrowse(%##s) STOP", info->sd, ptr->q.qname.c);
mDNS_StopBrowse(&mDNSStorage, &ptr->q); // no need to error-check result
freeL("browser_t/browse_termination_callback", ptr);
}
}
mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
{
request_state *request;
debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
#if APPLE_OSX_mDNSResponder
machserver_automatic_browse_domain_changed(&d->name, add);
#endif // APPLE_OSX_mDNSResponder
for (request = all_requests; request; request = request->next)
{
if (request->terminate != browse_termination_callback) continue; // Not a browse operation
if (!request->u.browser.default_domain) continue; // Not an auto-browse operation
if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
{
browser_t **ptr = &request->u.browser.browsers;
while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
if (add)
{
// If we don't already have this domain in our list for this browse operation, add it now
if (!*ptr) add_domain_to_browser(request, &d->name);
else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
}
else
{
if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
else
{
DNameListElem *p;
for (p = AutoBrowseDomains; p; p=p->next)
if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
if (SameDomainName(&d->name, &p->name)) break;
if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
else
{
browser_t *rem = *ptr;
*ptr = (*ptr)->next;
mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
}
}
}
}
}
}
mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
{
(void)m; // unused
if (result == mStatus_MemFree)
{
// On shutdown, mDNS_Close automatically deregisters all records
// Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
// from the LocalDomainEnumRecords list, we do this here before we free the memory.
// (This should actually no longer be necessary, now that we do the proper cleanup in
// udsserver_exit. To confirm this, we'll log an error message if we do find a record that
// hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
ARListElem **ptr = &LocalDomainEnumRecords;
while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
mDNSPlatformMemFree(rr->RecordContext);
}
}
// RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
// "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
// We may want to turn the common code into a subroutine.
mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
{
// allocate/register legacy and non-legacy _browse PTR record
mStatus err;
ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
debugf("Incrementing %s refcount for %##s",
(type == mDNS_DomainTypeBrowse ) ? "browse domain " :
(type == mDNS_DomainTypeRegistration ) ? "registration dom" :
(type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
AppendDNSNameString (&ptr->ar.namestorage, "local");
AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
err = mDNS_Register(m, &ptr->ar);
if (err)
{
LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
mDNSPlatformMemFree(ptr);
}
else
{
ptr->next = LocalDomainEnumRecords;
LocalDomainEnumRecords = ptr;
}
}
mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
{
ARListElem **ptr = &LocalDomainEnumRecords;
domainname lhs; // left-hand side of PTR, for comparison
debugf("Decrementing %s refcount for %##s",
(type == mDNS_DomainTypeBrowse ) ? "browse domain " :
(type == mDNS_DomainTypeRegistration ) ? "registration dom" :
(type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
AppendDNSNameString (&lhs, "local");
while (*ptr)
{
if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
{
ARListElem *rem = *ptr;
*ptr = (*ptr)->next;
mDNS_Deregister(m, &rem->ar);
return;
}
else ptr = &(*ptr)->next;
}
}
mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
{
DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
if (!new) { LogMsg("ERROR: malloc"); return; }
AssignDomainName(&new->name, name);
new->uid = uid;
new->next = AutoBrowseDomains;
AutoBrowseDomains = new;
udsserver_automatic_browse_domain_changed(new, mDNStrue);
}
mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
{
DNameListElem **p = &AutoBrowseDomains;
while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
else
{
DNameListElem *ptr = *p;
*p = ptr->next;
udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
mDNSPlatformMemFree(ptr);
}
}
mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
{
DNameListElem *d;
for (d = browseDomains; d; d = d->next)
{
if (add)
{
RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
AddAutoBrowseDomain(d->uid, &d->name);
}
else
{
DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
RmvAutoBrowseDomain(d->uid, &d->name);
}
}
}
mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
{
int num_autoname = 0;
request_state *req;
for (req = all_requests; req; req = req->next)
if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname)
num_autoname++;
// If DeviceInfo record is currently registered, see if we need to deregister it
if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
{
LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
mDNS_Deregister(m, &m->DeviceInfo);
}
// If DeviceInfo record is not currently registered, see if we need to register it
if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
if (num_autoname > 0)
{
mDNSu8 len = m->HIHardware.c[0] < 255 - 6 ? m->HIHardware.c[0] : 255 - 6;
mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 1, "model=", 6);
mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 7, m->HIHardware.c + 1, len);
m->DeviceInfo.resrec.rdata->u.data[0] = 6 + len; // "model=" plus the device string
m->DeviceInfo.resrec.rdlength = 7 + len; // One extra for the length byte at the start of the string
LogOperation("UpdateDeviceInfoRecord Register %##s", m->DeviceInfo.resrec.name);
mDNS_Register(m, &m->DeviceInfo);
}
}
mDNSexport void udsserver_handle_configchange(mDNS *const m)
{
request_state *req;
service_instance *ptr;
DNameListElem *RegDomains = NULL;
DNameListElem *BrowseDomains = NULL;
DNameListElem *p;
UpdateDeviceInfoRecord(m);
// For autoname services, see if the default service name has changed, necessitating an automatic update
for (req = all_requests; req; req = req->next)
if (req->terminate == regservice_termination_callback)
if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
{
req->u.servicereg.name = m->nicelabel;
for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
{
ptr->renameonmemfree = 1;
if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
regservice_callback(m, &ptr->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
}
}
// Let the platform layer get the current DNS information
mDNS_Lock(m);
mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains);
mDNS_Unlock(m);
// Any automatic registration domains are also implicitly automatic browsing domains
if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue); // Add the new list first
if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse); // Then clear the old list
// Add any new domains not already in our AutoRegistrationDomains list
for (p=RegDomains; p; p=p->next)
{
DNameListElem **pp = &AutoRegistrationDomains;
while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
if (!*pp) // If not found in our existing list, this is a new default registration domain
{
RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
udsserver_default_reg_domain_changed(p, mDNStrue);
}
else // else found same domainname in both old and new lists, so no change, just delete old copy
{
DNameListElem *del = *pp;
*pp = (*pp)->next;
mDNSPlatformMemFree(del);
}
}
// Delete any domains in our old AutoRegistrationDomains list that are now gone
while (AutoRegistrationDomains)
{
DNameListElem *del = AutoRegistrationDomains;
AutoRegistrationDomains = AutoRegistrationDomains->next; // Cut record from list FIRST,
DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
udsserver_default_reg_domain_changed(del, mDNSfalse); // before calling udsserver_default_reg_domain_changed()
mDNSPlatformMemFree(del);
}
// Now we have our new updated automatic registration domain list
AutoRegistrationDomains = RegDomains;
// Add new browse domains to internal list
if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
// Remove old browse domains from internal list
if (SCPrefBrowseDomains)
{
SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
while (SCPrefBrowseDomains)
{
DNameListElem *fptr = SCPrefBrowseDomains;
SCPrefBrowseDomains = SCPrefBrowseDomains->next;
mDNSPlatformMemFree(fptr);
}
}
// Replace the old browse domains array with the new array
SCPrefBrowseDomains = BrowseDomains;
}
mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
{
(void)m; // unused;
(void)q; // unused
LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
else RmvAutoBrowseDomain(0, &answer->rdata->u.name);
}
mDNSlocal mStatus handle_sethost_request(request_state *request)
{
get_flags(&request->msgptr, request->msgend);
char hostName[MAX_DOMAIN_LABEL];
int len = 0;
if (get_string(&request->msgptr, request->msgend, hostName,
MAX_DOMAIN_LABEL) < 0) return (mStatus_BadParamErr);
LogOperation("%3d: DNSSetHostname(%X, %d, nonstr ) START",
request->sd, request->flags);
// if we start using this as a callback for notification when the
// hostname changes we may need to cleanup from it
// request->terminate = sethost_termination_callback;
if(hostName[0] == 0) return mStatus_BadParamErr;
while (len < MAX_DOMAIN_LABEL && hostName[len+1]
&& hostName[len+1] != '.') len++;
strncpy(&(mDNSStorage.nicelabel.c[1]), hostName, len);
mDNSStorage.nicelabel.c[0] = len;
strncpy(&(mDNSStorage.hostlabel.c[1]), hostName, len);
mDNSStorage.hostlabel.c[0] = len;
mDNS_SetFQDN(&mDNSStorage);
return mStatus_NoError;
}
mDNSlocal mStatus handle_browse_request(request_state *request)
{
char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
domainname typedn, d, temp;
mDNSs32 NumSubTypes;
mStatus err = mStatus_NoError;
DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
if (domain[0] == '\0') uDNS_SetupSearchDomains(&mDNSStorage, UDNS_START_WAB_QUERY);
request->flags = flags;
typedn.c[0] = 0;
NumSubTypes = ChopSubTypes(regtype); // Note: Modifies regtype string to remove trailing subtypes
if (NumSubTypes < 0 || NumSubTypes > 1) return(mStatus_BadParamErr);
if (NumSubTypes == 1 && !AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1)) return(mStatus_BadParamErr);
if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
// For over-long service types, we only allow domain "local"
if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrLCopy(domain, "local.", sizeof(domain));
// Set up browser info
request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
request->u.browser.interface_id = InterfaceID;
AssignDomainName(&request->u.browser.regtype, &typedn);
request->u.browser.default_domain = !domain[0];
request->u.browser.browsers = NULL;
LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START",
request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain);
// We need to unconditionally set request->terminate, because even if we didn't successfully
// start any browses right now, subsequent configuration changes may cause successful
// browses to be added, and we'll need to cancel them before freeing this memory.
request->terminate = browse_termination_callback;
if (domain[0])
{
if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
err = add_domain_to_browser(request, &d);
#if 0
err = AuthorizedDomain(request, &d, AutoBrowseDomains) ? add_domain_to_browser(request, &d) : mStatus_NoError;
#endif
}
else
{
DNameListElem *sdom;
for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
{
err = add_domain_to_browser(request, &sdom->name);
if (err)
{
if (SameDomainName(&sdom->name, &localdomain)) break;
else err = mStatus_NoError; // suppress errors for non-local "default" domains
}
}
}
return(err);
}
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceResolve
#endif
mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
{
size_t len = 0;
char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME];
char *data;
reply_state *rep;
request_state *req = question->QuestionContext;
(void)m; // Unused
LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req->sd, question->qname.c, AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
if (!AddRecord)
{
if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
return;
}
if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
if (!req->u.resolve.txt || !req->u.resolve.srv) return; // only deliver result to client if we have both answers
ConvertDomainNameToCString(answer->name, fullname);
ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
// calculate reply length
len += sizeof(DNSServiceFlags);
len += sizeof(mDNSu32); // interface index
len += sizeof(DNSServiceErrorType);
len += strlen(fullname) + 1;
len += strlen(target) + 1;
len += 2 * sizeof(mDNSu16); // port, txtLen
len += req->u.resolve.txt->rdlength;
// allocate/init reply header
rep = create_reply(resolve_reply_op, len, req);
rep->rhdr->flags = dnssd_htonl(0);
rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
rep->rhdr->error = dnssd_htonl(kDNSServiceErr_NoError);
data = (char *)&rep->rhdr[1];
// write reply data to message
put_string(fullname, &data);
put_string(target, &data);
*data++ = req->u.resolve.srv->rdata->u.srv.port.b[0];
*data++ = req->u.resolve.srv->rdata->u.srv.port.b[1];
put_uint16(req->u.resolve.txt->rdlength, &data);
put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
append_reply(req, rep);
}
mDNSlocal void resolve_termination_callback(request_state *request)
{
LogOperation("%3d: DNSServiceResolve(%##s) STOP", request->sd, request->u.resolve.qtxt.qname.c);
mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
if (request->u.resolve.external_advertise) external_stop_resolving_service(&request->u.resolve.qsrv.qname);
}
mDNSlocal mStatus handle_resolve_request(request_state *request)
{
char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
domainname fqdn;
mStatus err;
// extract the data from the message
DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
mDNSInterfaceID InterfaceID;
mDNSBool wasP2P = (interfaceIndex == kDNSServiceInterfaceIndexP2P);
request->flags = flags;
if (wasP2P) interfaceIndex = kDNSServiceInterfaceIndexAny;
InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
if (interfaceIndex && !InterfaceID)
{ LogMsg("ERROR: handle_resolve_request bad interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); }
if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
{ LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
{ LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
// format questions
request->u.resolve.qsrv.InterfaceID = InterfaceID;
request->u.resolve.qsrv.Target = zeroAddr;
AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
request->u.resolve.qsrv.qtype = kDNSType_SRV;
request->u.resolve.qsrv.qclass = kDNSClass_IN;
request->u.resolve.qsrv.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;