#include <mach/mach.h>
#include <mach/mach_error.h>
#include <servers/bootstrap.h>
#include <sys/types.h>
#include <unistd.h>
#include <paths.h>
#include <fcntl.h>
#include <pwd.h>
#include <SystemConfiguration/SCPreferencesSetSpecific.h>
#include "DNSServiceDiscoveryRequestServer.h"
#include "DNSServiceDiscoveryReply.h"
#include "DNSCommon.h"
#include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
#include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h
#include "GenLinkedList.h"
#include <DNSServiceDiscovery/DNSServiceDiscovery.h>
#define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
#define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
#define LOCAL_DEFAULT_REG 1 // empty string means register in the local domain
#define DEFAULT_REG_DOMAIN "apple.com." // used if the above flag is turned off
static mDNS_PlatformSupport PlatformStorage;
#define RR_CACHE_SIZE ((16*1024) / sizeof(CacheRecord))
static CacheEntity rrcachestorage[RR_CACHE_SIZE];
static const char kmDNSBootstrapName[] = "com.apple.mDNSResponderRestart";
static mach_port_t client_death_port = MACH_PORT_NULL;
static mach_port_t signal_port = MACH_PORT_NULL;
static mach_port_t server_priv_port = MACH_PORT_NULL;
#define MDNS_MM_TIMEOUT 250
static int restarting_via_mach_init = 0;
static int started_via_launchdaemon = 0;
static int OSXVers;
typedef struct DNSServiceDomainEnumeration_struct DNSServiceDomainEnumeration;
struct DNSServiceDomainEnumeration_struct
{
DNSServiceDomainEnumeration *next;
mach_port_t ClientMachPort;
DNSQuestion dom; DNSQuestion def; };
typedef struct DNSServiceBrowserResult_struct DNSServiceBrowserResult;
struct DNSServiceBrowserResult_struct
{
DNSServiceBrowserResult *next;
int resultType;
domainname result;
};
typedef struct DNSServiceBrowser_struct DNSServiceBrowser;
typedef struct DNSServiceBrowserQuestion
{
struct DNSServiceBrowserQuestion *next;
DNSQuestion q;
domainname domain;
} DNSServiceBrowserQuestion;
struct DNSServiceBrowser_struct
{
DNSServiceBrowser *next;
mach_port_t ClientMachPort;
DNSServiceBrowserQuestion *qlist;
DNSServiceBrowserResult *results;
mDNSs32 lastsuccess;
mDNSBool DefaultDomain; domainname type; };
typedef struct DNSServiceResolver_struct DNSServiceResolver;
struct DNSServiceResolver_struct
{
DNSServiceResolver *next;
mach_port_t ClientMachPort;
ServiceInfoQuery q;
ServiceInfo i;
mDNSs32 ReportTime;
};
typedef struct ServiceInstance
{
struct ServiceInstance *next;
mach_port_t ClientMachPort;
mDNSBool autoname; mDNSBool autorename; domainlabel name;
domainname domain;
ServiceRecordSet srs;
} ServiceInstance;
typedef struct DNSServiceRegistration
{
struct DNSServiceRegistration *next;
mach_port_t ClientMachPort;
mDNSBool DefaultDomain;
mDNSBool autoname;
size_t rdsize;
int NumSubTypes;
char regtype[MAX_ESCAPED_DOMAIN_NAME]; domainlabel name; domainname type;
mDNSIPPort port;
unsigned char txtinfo[1024];
size_t txt_len;
uint32_t NextRef;
ServiceInstance *regs;
} DNSServiceRegistration;
static DNSServiceDomainEnumeration *DNSServiceDomainEnumerationList = NULL;
static DNSServiceBrowser *DNSServiceBrowserList = NULL;
static DNSServiceResolver *DNSServiceResolverList = NULL;
static DNSServiceRegistration *DNSServiceRegistrationList = NULL;
#if MACOSX_MDNS_MALLOC_DEBUGGING
char _malloc_options[] = "AXZ";
mDNSexport void LogMemCorruption(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);
LogMsg("!!!! %s !!!!", buffer);
NotifyOfElusiveBug("Memory Corruption", 0, buffer);
}
mDNSlocal void validatelists(mDNS *const m)
{
DNSServiceDomainEnumeration *e;
for (e = DNSServiceDomainEnumerationList; e; e=e->next)
if (e->ClientMachPort == 0 || e->ClientMachPort == (mach_port_t)~0)
LogMemCorruption("DNSServiceDomainEnumerationList: %p is garbage (%X)", e, e->ClientMachPort);
DNSServiceBrowser *b;
for (b = DNSServiceBrowserList; b; b=b->next)
if (b->ClientMachPort == 0 || b->ClientMachPort == (mach_port_t)~0)
LogMemCorruption("DNSServiceBrowserList: %p is garbage (%X)", b, b->ClientMachPort);
DNSServiceResolver *l;
for (l = DNSServiceResolverList; l; l=l->next)
if (l->ClientMachPort == 0 || l->ClientMachPort == (mach_port_t)~0)
LogMemCorruption("DNSServiceResolverList: %p is garbage (%X)", l, l->ClientMachPort);
DNSServiceRegistration *r;
for (r = DNSServiceRegistrationList; r; r=r->next)
if (r->ClientMachPort == 0 || r->ClientMachPort == (mach_port_t)~0)
LogMemCorruption("DNSServiceRegistrationList: %p is garbage (%X)", r, r->ClientMachPort);
uds_validatelists();
AuthRecord *rr;
for (rr = m->ResourceRecords; rr; rr=rr->next)
{
if (rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
if (rr->resrec.name != &rr->namestorage)
LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
}
for (rr = m->DuplicateRecords; rr; rr=rr->next)
if (rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
DNSQuestion *q;
for (q = m->Questions; q; q=q->next)
if (q->ThisQInterval == (mDNSs32)~0)
LogMemCorruption("Questions list: %p is garbage (%lX)", q, q->ThisQInterval);
CacheGroup *cg;
CacheRecord *cr;
mDNSu32 slot;
FORALL_CACHERECORDS(slot, cg, cr)
if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF)
LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, rr, rr->resrec.RecordType);
NetworkInterfaceInfoOSX *i;
for (i = m->p->InterfaceList; i; i = i->next)
if (!i->ifa_name)
LogMemCorruption("InterfaceList: %p is garbage", i);
for (q = m->uDNS_info.ActiveQueries; q; q=q->next)
if (*(long*)q == (mDNSs32)~0)
LogMemCorruption("uDNS_info.ActiveQueries: %p is garbage (%lX)", q, *(long*)q);
ServiceRecordSet *s;
for (s = m->uDNS_info.ServiceRegistrations; s; s=s->next)
if (s->next == (ServiceRecordSet*)~0)
LogMemCorruption("uDNS_info.ServiceRegistrations: %p is garbage (%lX)", s, s->next);
for (rr = m->uDNS_info.RecordRegistrations; rr; rr=rr->next)
{
if (rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
LogMemCorruption("uDNS_info.RecordRegistrations: %p is garbage (%X)", rr, rr->resrec.RecordType);
if (rr->resrec.name != &rr->namestorage)
LogMemCorruption("uDNS_info.RecordRegistrations: %p name %p does not point to namestorage %p %##s",
rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
}
NATTraversalInfo *n;
for (n = m->uDNS_info.NATTraversals; n; n=n->next)
if (n->op > 2) LogMemCorruption("uDNS_info.NATTraversals: %p is garbage", n);
for (n = m->uDNS_info.LLQNatInfo; n; n=n->next)
if (n->op > 2) LogMemCorruption("uDNS_info.LLQNatInfo: %p is garbage", n);
}
void *mallocL(char *msg, unsigned int size)
{
unsigned long *mem = malloc(size+8);
if (!mem)
{
LogMsg("malloc( %s : %d ) failed", msg, size);
return(NULL);
}
else
{
LogMalloc("malloc( %s : %lu ) = %p", msg, size, &mem[2]);
mem[0] = 0xDEAD1234;
mem[1] = size;
memset(&mem[2], 0xFF, size);
validatelists(&mDNSStorage);
return(&mem[2]);
}
}
void freeL(char *msg, void *x)
{
if (!x)
LogMsg("free( %s @ NULL )!", msg);
else
{
unsigned long *mem = ((unsigned long *)x) - 2;
if (mem[0] != 0xDEAD1234)
{ LogMsg("free( %s @ %p ) !!!! NOT ALLOCATED !!!!", msg, &mem[2]); return; }
if (mem[1] > 24000)
{ LogMsg("free( %s : %ld @ %p) too big!", msg, mem[1], &mem[2]); return; }
LogMalloc("free( %s : %ld @ %p)", msg, mem[1], &mem[2]);
memset(mem, 0xFF, mem[1]+8);
validatelists(&mDNSStorage);
free(mem);
}
}
#endif
mDNSlocal void FreeServiceInstance(ServiceInstance *x)
{
ServiceRecordSet *s = &x->srs;
ExtraResourceRecord *e = x->srs.Extras, *tmp;
while(e)
{
e->r.RecordContext = e;
tmp = e;
e = e->next;
FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
}
if (s->RR_TXT.resrec.rdata != &s->RR_TXT.rdatastorage)
freeL("TXT RData", s->RR_TXT.resrec.rdata);
if (s->SubTypes) freeL("ServiceSubTypes", s->SubTypes);
freeL("ServiceInstance", x);
}
mDNSlocal void AbortClient(mach_port_t ClientMachPort, void *m)
{
DNSServiceDomainEnumeration **e = &DNSServiceDomainEnumerationList;
DNSServiceBrowser **b = &DNSServiceBrowserList;
DNSServiceResolver **l = &DNSServiceResolverList;
DNSServiceRegistration **r = &DNSServiceRegistrationList;
while (*e && (*e)->ClientMachPort != ClientMachPort) e = &(*e)->next;
if (*e)
{
DNSServiceDomainEnumeration *x = *e;
*e = (*e)->next;
if (m && m != x)
LogMsg("%5d: DNSServiceDomainEnumeration(%##s) STOP; WARNING m %p != x %p", ClientMachPort, x->dom.qname.c, m, x);
else LogOperation("%5d: DNSServiceDomainEnumeration(%##s) STOP", ClientMachPort, x->dom.qname.c);
mDNS_StopGetDomains(&mDNSStorage, &x->dom);
mDNS_StopGetDomains(&mDNSStorage, &x->def);
freeL("DNSServiceDomainEnumeration", x);
return;
}
while (*b && (*b)->ClientMachPort != ClientMachPort) b = &(*b)->next;
if (*b)
{
DNSServiceBrowser *x = *b;
DNSServiceBrowserQuestion *freePtr, *qptr = x->qlist;
*b = (*b)->next;
while (qptr)
{
if (m && m != x)
LogMsg("%5d: DNSServiceBrowse(%##s) STOP; WARNING m %p != x %p", ClientMachPort, qptr->q.qname.c, m, x);
else LogOperation("%5d: DNSServiceBrowse(%##s) STOP", ClientMachPort, qptr->q.qname.c);
mDNS_StopBrowse(&mDNSStorage, &qptr->q);
freePtr = qptr;
qptr = qptr->next;
freeL("DNSServiceBrowserQuestion", freePtr);
}
while (x->results)
{
DNSServiceBrowserResult *r = x->results;
x->results = x->results->next;
freeL("DNSServiceBrowserResult", r);
}
freeL("DNSServiceBrowser", x);
return;
}
while (*l && (*l)->ClientMachPort != ClientMachPort) l = &(*l)->next;
if (*l)
{
DNSServiceResolver *x = *l;
*l = (*l)->next;
if (m && m != x)
LogMsg("%5d: DNSServiceResolve(%##s) STOP; WARNING m %p != x %p", ClientMachPort, x->i.name.c, m, x);
else LogOperation("%5d: DNSServiceResolve(%##s) STOP", ClientMachPort, x->i.name.c);
mDNS_StopResolveService(&mDNSStorage, &x->q);
freeL("DNSServiceResolver", x);
return;
}
while (*r && (*r)->ClientMachPort != ClientMachPort) r = &(*r)->next;
if (*r)
{
ServiceInstance *si = NULL;
DNSServiceRegistration *x = *r;
*r = (*r)->next;
si = x->regs;
while (si)
{
ServiceInstance *instance = si;
si = si->next;
instance->autorename = mDNSfalse;
if (m && m != x) LogMsg("%5d: DNSServiceRegistration(%##s, %u) STOP; WARNING m %p != x %p", ClientMachPort, instance->srs.RR_SRV.resrec.name->c, SRS_PORT(&instance->srs), m, x);
else LogOperation("%5d: DNSServiceRegistration(%##s, %u) STOP", ClientMachPort, instance->srs.RR_SRV.resrec.name->c, SRS_PORT(&instance->srs));
if (mDNS_DeregisterService(&mDNSStorage, &instance->srs)) FreeServiceInstance(instance); }
x->regs = NULL;
freeL("DNSServiceRegistration", x);
return;
}
LogMsg("%5d: died or deallocated, but no record of client can be found!", ClientMachPort);
}
#define AbortBlockedClient(C,MSG,M) AbortClientWithLogMessage((C), "stopped accepting Mach messages", " (" MSG ")", (M))
mDNSlocal void AbortClientWithLogMessage(mach_port_t c, char *reason, char *msg, void *m)
{
DNSServiceDomainEnumeration *e = DNSServiceDomainEnumerationList;
DNSServiceBrowser *b = DNSServiceBrowserList;
DNSServiceResolver *l = DNSServiceResolverList;
DNSServiceRegistration *r = DNSServiceRegistrationList;
DNSServiceBrowserQuestion *qptr;
while (e && e->ClientMachPort != c) e = e->next;
while (b && b->ClientMachPort != c) b = b->next;
while (l && l->ClientMachPort != c) l = l->next;
while (r && r->ClientMachPort != c) r = r->next;
if (e) LogMsg("%5d: DomainEnumeration(%##s) %s%s", c, e->dom.qname.c, reason, msg);
else if (b)
{
for (qptr = b->qlist; qptr; qptr = qptr->next)
LogMsg("%5d: Browser(%##s) %s%s", c, qptr->q.qname.c, reason, msg);
}
else if (l) LogMsg("%5d: Resolver(%##s) %s%s", c, l->i.name.c, reason, msg);
else if (r)
{
ServiceInstance *si;
for (si = r->regs; si; si = si->next)
LogMsg("%5d: Registration(%##s) %s%s", c, si->srs.RR_SRV.resrec.name->c, reason, msg);
}
else LogMsg("%5d: (%s) %s, but no record of client can be found!", c, reason, msg);
AbortClient(c, m);
}
mDNSlocal mDNSBool CheckForExistingClient(mach_port_t c)
{
DNSServiceDomainEnumeration *e = DNSServiceDomainEnumerationList;
DNSServiceBrowser *b = DNSServiceBrowserList;
DNSServiceResolver *l = DNSServiceResolverList;
DNSServiceRegistration *r = DNSServiceRegistrationList;
DNSServiceBrowserQuestion *qptr;
while (e && e->ClientMachPort != c) e = e->next;
while (b && b->ClientMachPort != c) b = b->next;
while (l && l->ClientMachPort != c) l = l->next;
while (r && r->ClientMachPort != c) r = r->next;
if (e) LogMsg("%5d: DomainEnumeration(%##s) already exists!", c, e->dom.qname.c);
if (b)
{
for (qptr = b->qlist; qptr; qptr = qptr->next)
LogMsg("%5d: Browser(%##s) already exists!", c, qptr->q.qname.c);
}
if (l) LogMsg("%5d: Resolver(%##s) already exists!", c, l->i.name.c);
if (r) LogMsg("%5d: Registration(%##s) already exists!", c, r->regs ? r->regs->srs.RR_SRV.resrec.name->c : NULL);
return(e || b || l || r);
}
mDNSlocal void ClientDeathCallback(CFMachPortRef unusedport, void *voidmsg, CFIndex size, void *info)
{
mach_msg_header_t *msg = (mach_msg_header_t *)voidmsg;
(void)unusedport; (void)size; (void)info; if (msg->msgh_id == MACH_NOTIFY_DEAD_NAME)
{
const mach_dead_name_notification_t *const deathMessage = (mach_dead_name_notification_t *)msg;
AbortClient(deathMessage->not_port, NULL);
mach_port_destroy(mach_task_self(), deathMessage->not_port);
}
}
mDNSlocal void EnableDeathNotificationForClient(mach_port_t ClientMachPort, void *m)
{
mach_port_t prev;
kern_return_t r = mach_port_request_notification(mach_task_self(), ClientMachPort, MACH_NOTIFY_DEAD_NAME, 0,
client_death_port, MACH_MSG_TYPE_MAKE_SEND_ONCE, &prev);
if (r != KERN_SUCCESS)
AbortClientWithLogMessage(ClientMachPort, "died/deallocated before we could enable death notification", "", m);
}
mDNSlocal void DomainEnumFound(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, mDNSBool AddRecord)
{
kern_return_t status;
#pragma unused(m)
char buffer[MAX_ESCAPED_DOMAIN_NAME];
DNSServiceDomainEnumerationReplyResultType rt;
DNSServiceDomainEnumeration *x = (DNSServiceDomainEnumeration *)question->QuestionContext;
debugf("DomainEnumFound: %##s PTR %##s", answer->name->c, answer->rdata->u.name.c);
if (answer->rrtype != kDNSType_PTR) return;
if (!x) { debugf("DomainEnumFound: DNSServiceDomainEnumeration is NULL"); return; }
if (AddRecord)
{
if (question == &x->dom) rt = DNSServiceDomainEnumerationReplyAddDomain;
else rt = DNSServiceDomainEnumerationReplyAddDomainDefault;
}
else
{
if (question == &x->dom) rt = DNSServiceDomainEnumerationReplyRemoveDomain;
else return;
}
LogOperation("%5d: DNSServiceDomainEnumeration(%##s) %##s %s",
x->ClientMachPort, x->dom.qname.c, answer->rdata->u.name.c,
!AddRecord ? "RemoveDomain" :
question == &x->dom ? "AddDomain" : "AddDomainDefault");
ConvertDomainNameToCString(&answer->rdata->u.name, buffer);
status = DNSServiceDomainEnumerationReply_rpc(x->ClientMachPort, rt, buffer, 0, MDNS_MM_TIMEOUT);
if (status == MACH_SEND_TIMED_OUT)
AbortBlockedClient(x->ClientMachPort, "enumeration", x);
}
mDNSexport kern_return_t provide_DNSServiceDomainEnumerationCreate_rpc(mach_port_t unusedserver, mach_port_t client,
int regDom)
{
(void)unusedserver; mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
mDNS_DomainType dt1 = regDom ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse;
mDNS_DomainType dt2 = regDom ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
DNSServiceDomainEnumeration *x = mallocL("DNSServiceDomainEnumeration", sizeof(*x));
if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
x->ClientMachPort = client;
x->next = DNSServiceDomainEnumerationList;
DNSServiceDomainEnumerationList = x;
verbosedebugf("%5d: Enumerate %s Domains", client, regDom ? "Registration" : "Browsing");
err = mDNS_GetDomains(&mDNSStorage, &x->dom, dt1, NULL, mDNSInterface_LocalOnly, DomainEnumFound, x);
if (!err) err = mDNS_GetDomains(&mDNSStorage, &x->def, dt2, NULL, mDNSInterface_LocalOnly, DomainEnumFound, x);
if (err) { AbortClient(client, x); errormsg = "mDNS_GetDomains"; goto fail; }
LogOperation("%5d: DNSServiceDomainEnumeration(%##s) START", client, x->dom.qname.c);
EnableDeathNotificationForClient(client, x);
return(mStatus_NoError);
fail:
LogMsg("%5d: DNSServiceDomainEnumeration(%d) failed: %s (%ld)", client, regDom, errormsg, err);
return(err);
}
mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, mDNSBool AddRecord)
{
(void)m;
if (answer->rrtype != kDNSType_PTR)
{ LogMsg("FoundInstance: Should not be called with rrtype %d (not a PTR record)", answer->rrtype); return; }
domainlabel name;
domainname type, domain;
if (!DeconstructServiceName(&answer->rdata->u.name, &name, &type, &domain))
{
LogMsg("FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
answer->name->c, answer->rdata->u.name.c);
return;
}
DNSServiceBrowserResult *x = mallocL("DNSServiceBrowserResult", sizeof(*x));
if (!x) { LogMsg("FoundInstance: Failed to allocate memory for result %##s", answer->rdata->u.name.c); return; }
verbosedebugf("FoundInstance: %s %##s", AddRecord ? "Add" : "Rmv", answer->rdata->u.name.c);
AssignDomainName(&x->result, &answer->rdata->u.name);
if (AddRecord)
x->resultType = DNSServiceBrowserReplyAddInstance;
else x->resultType = DNSServiceBrowserReplyRemoveInstance;
x->next = NULL;
DNSServiceBrowser *browser = (DNSServiceBrowser *)question->QuestionContext;
DNSServiceBrowserResult **p = &browser->results;
while (*p) p = &(*p)->next;
*p = x;
}
mDNSlocal mStatus AddDomainToBrowser(DNSServiceBrowser *browser, const domainname *d)
{
mStatus err = mStatus_NoError;
DNSServiceBrowserQuestion *ptr, *question = NULL;
for (ptr = browser->qlist; ptr; ptr = ptr->next)
{
if (SameDomainName(&ptr->q.qname, d))
{ debugf("Domain %##s already contained in browser", d->c); return mStatus_AlreadyRegistered; }
}
question = mallocL("DNSServiceBrowserQuestion", sizeof(DNSServiceBrowserQuestion));
if (!question) { LogMsg("Error: malloc"); return mStatus_NoMemoryErr; }
AssignDomainName(&question->domain, d);
question->next = browser->qlist;
browser->qlist = question;
LogOperation("%5d: DNSServiceBrowse(%##s%##s) START", browser->ClientMachPort, browser->type.c, d->c);
err = mDNS_StartBrowse(&mDNSStorage, &question->q, &browser->type, d, mDNSInterface_Any, mDNSfalse, FoundInstance, browser);
if (err) LogMsg("Error: AddDomainToBrowser: mDNS_StartBrowse %d", err);
return err;
}
mDNSexport void DefaultBrowseDomainChanged(const domainname *d, mDNSBool add)
{
DNSServiceBrowser *ptr;
debugf("DefaultBrowseDomainChanged: %s default browse domain %##s", add ? "Adding" : "Removing", d->c);
for (ptr = DNSServiceBrowserList; ptr; ptr = ptr->next)
{
if (ptr->DefaultDomain)
{
if (add)
{
mStatus err = AddDomainToBrowser(ptr, d);
if (err && err != mStatus_AlreadyRegistered) LogMsg("Default browse in domain %##s for client %5d failed. Continuing", d, ptr->ClientMachPort);
}
else
{
DNSServiceBrowserQuestion **q = &ptr->qlist;
while (*q)
{
if (SameDomainName(&(*q)->domain, d))
{
DNSServiceBrowserQuestion *remove = *q;
*q = (*q)->next;
if (remove->q.LongLived)
{
CacheRecord *ka = remove->q.uDNS_info.knownAnswers;
while (ka) { remove->q.QuestionCallback(&mDNSStorage, &remove->q, &ka->resrec, mDNSfalse); ka = ka->next; }
}
mDNS_StopBrowse(&mDNSStorage, &remove->q);
freeL("DNSServiceBrowserQuestion", remove );
return;
}
q = &(*q)->next;
}
LogMsg("Requested removal of default domain %##s not in client %5d's list", d->c, ptr->ClientMachPort);
}
}
}
}
mDNSexport kern_return_t provide_DNSServiceBrowserCreate_rpc(mach_port_t unusedserver, mach_port_t client,
DNSCString regtype, DNSCString domain)
{
(void)unusedserver; mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
DNameListElem *SearchDomains = NULL, *sdPtr;
if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
domainname t, d;
t.c[0] = 0;
mDNSs32 NumSubTypes = ChopSubTypes(regtype); if (NumSubTypes < 0 || NumSubTypes > 1) { errormsg = "Bad Service SubType"; goto badparam; }
if (NumSubTypes == 1 && !AppendDNSNameString(&t, regtype + strlen(regtype) + 1))
{ errormsg = "Bad Service SubType"; goto badparam; }
if (!regtype[0] || !AppendDNSNameString(&t, regtype)) { errormsg = "Illegal regtype"; goto badparam; }
domainname temp;
if (!MakeDomainNameFromDNSNameString(&temp, regtype)) { errormsg = "Illegal regtype"; goto badparam; }
if (temp.c[0] > 15 && (!domain || domain[0] == 0)) domain = "local.";
DNSServiceBrowser *x = mallocL("DNSServiceBrowser", sizeof(*x));
if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
AssignDomainName(&x->type, &t);
x->ClientMachPort = client;
x->results = NULL;
x->lastsuccess = 0;
x->qlist = NULL;
x->next = DNSServiceBrowserList;
DNSServiceBrowserList = x;
if (domain[0])
{
x->DefaultDomain = mDNSfalse;
if (!MakeDomainNameFromDNSNameString(&d, domain)) { errormsg = "Illegal domain"; goto badparam; }
err = AddDomainToBrowser(x, &d);
if (err) { AbortClient(client, x); errormsg = "AddDomainToBrowser"; goto fail; }
}
else
{
x->DefaultDomain = mDNStrue;
SearchDomains = mDNSPlatformGetSearchDomainList();
if (!SearchDomains) { AbortClient(client, x); errormsg = "GetSearchDomainList"; goto fail; }
for (sdPtr = SearchDomains; sdPtr; sdPtr = sdPtr->next)
{
err = AddDomainToBrowser(x, &sdPtr->name);
if (err)
{
if (!SameDomainName(&localdomain, &sdPtr->name))
LogMsg("Default browse in domain %##s failed. Continuing", sdPtr->name.c);
else { AbortClient(client, x); errormsg = "AddDomainToBrowser"; goto fail; }
}
}
}
EnableDeathNotificationForClient(client, x);
mDNS_FreeDNameList(SearchDomains);
return(mStatus_NoError);
badparam:
err = mStatus_BadParamErr;
fail:
LogMsg("%5d: DNSServiceBrowse(\"%s\", \"%s\") failed: %s (%ld)", client, regtype, domain, errormsg, err);
if (SearchDomains) mDNS_FreeDNameList(SearchDomains);
return(err);
}
mDNSlocal void FoundInstanceInfo(mDNS *const m, ServiceInfoQuery *query)
{
kern_return_t status;
DNSServiceResolver *x = (DNSServiceResolver *)query->ServiceInfoQueryContext;
NetworkInterfaceInfoOSX *ifx = (NetworkInterfaceInfoOSX *)query->info->InterfaceID;
if (query->info->InterfaceID == mDNSInterface_LocalOnly) ifx = mDNSNULL;
struct sockaddr_storage interface;
struct sockaddr_storage address;
char cstring[1024];
int i, pstrlen = query->info->TXTinfo[0];
(void)m;
if (query->info->TXTlen > sizeof(cstring)) return;
bzero(&interface, sizeof(interface));
bzero(&address, sizeof(address));
if (ifx && ifx->ifinfo.ip.type == mDNSAddrType_IPv4)
{
struct sockaddr_in *sin = (struct sockaddr_in*)&interface;
sin->sin_len = sizeof(*sin);
sin->sin_family = AF_INET;
sin->sin_port = 0;
sin->sin_addr.s_addr = ifx->ifinfo.ip.ip.v4.NotAnInteger;
}
else if (ifx && ifx->ifinfo.ip.type == mDNSAddrType_IPv6)
{
struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&interface;
sin6->sin6_len = sizeof(*sin6);
sin6->sin6_family = AF_INET6;
sin6->sin6_flowinfo = 0;
sin6->sin6_port = 0;
sin6->sin6_addr = *(struct in6_addr*)&ifx->ifinfo.ip.ip.v6;
sin6->sin6_scope_id = ifx->scope_id;
}
if (query->info->ip.type == mDNSAddrType_IPv4)
{
struct sockaddr_in *sin = (struct sockaddr_in*)&address;
sin->sin_len = sizeof(*sin);
sin->sin_family = AF_INET;
sin->sin_port = query->info->port.NotAnInteger;
sin->sin_addr.s_addr = query->info->ip.ip.v4.NotAnInteger;
}
else
{
struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&address;
sin6->sin6_len = sizeof(*sin6);
sin6->sin6_family = AF_INET6;
sin6->sin6_port = query->info->port.NotAnInteger;
sin6->sin6_flowinfo = 0;
sin6->sin6_addr = *(struct in6_addr*)&query->info->ip.ip.v6;
sin6->sin6_scope_id = ifx ? ifx->scope_id : 0;
}
for (i=1; i<query->info->TXTlen; i++)
{
if (--pstrlen >= 0)
cstring[i-1] = query->info->TXTinfo[i];
else
{
cstring[i-1] = 1;
pstrlen = query->info->TXTinfo[i];
}
}
cstring[i-1] = 0;
LogOperation("%5d: DNSServiceResolver(%##s) -> %#a:%u", x->ClientMachPort,
x->i.name.c, &query->info->ip, mDNSVal16(query->info->port));
status = DNSServiceResolverReply_rpc(x->ClientMachPort,
(char*)&interface, (char*)&address, cstring, 0, MDNS_MM_TIMEOUT);
if (status == MACH_SEND_TIMED_OUT)
AbortBlockedClient(x->ClientMachPort, "resolve", x);
}
mDNSexport kern_return_t provide_DNSServiceResolverResolve_rpc(mach_port_t unusedserver, mach_port_t client,
DNSCString name, DNSCString regtype, DNSCString domain)
{
(void)unusedserver; mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
domainlabel n;
domainname t, d, srv;
if (!name[0] || !MakeDomainLabelFromLiteralString(&n, name)) { errormsg = "Bad Instance Name"; goto badparam; }
if (!regtype[0] || !MakeDomainNameFromDNSNameString(&t, regtype)) { errormsg = "Bad Service Type"; goto badparam; }
if (!domain[0] || !MakeDomainNameFromDNSNameString(&d, domain)) { errormsg = "Bad Domain"; goto badparam; }
if (!ConstructServiceName(&srv, &n, &t, &d)) { errormsg = "Bad Name"; goto badparam; }
DNSServiceResolver *x = mallocL("DNSServiceResolver", sizeof(*x));
if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
x->ClientMachPort = client;
x->i.InterfaceID = mDNSInterface_Any;
x->i.name = srv;
x->ReportTime = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
x->next = DNSServiceResolverList;
DNSServiceResolverList = x;
LogOperation("%5d: DNSServiceResolve(%##s) START", client, x->i.name.c);
err = mDNS_StartResolveService(&mDNSStorage, &x->q, &x->i, FoundInstanceInfo, x);
if (err) { AbortClient(client, x); errormsg = "mDNS_StartResolveService"; goto fail; }
EnableDeathNotificationForClient(client, x);
return(mStatus_NoError);
badparam:
err = mStatus_BadParamErr;
fail:
LogMsg("%5d: DNSServiceResolve(\"%s\", \"%s\", \"%s\") failed: %s (%ld)", client, name, regtype, domain, errormsg, err);
return(err);
}
mDNSexport void RecordUpdatedNiceLabel(mDNS *const m, mDNSs32 delay)
{
m->p->NotifyUser = NonZeroTime(m->timenow + delay);
}
mDNSlocal void RegCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
{
ServiceInstance *si = (ServiceInstance*)srs->ServiceContext;
if (result == mStatus_NoError)
{
kern_return_t status;
LogOperation("%5d: DNSServiceRegistration(%##s, %u) Name Registered", si->ClientMachPort, srs->RR_SRV.resrec.name->c, SRS_PORT(srs));
status = DNSServiceRegistrationReply_rpc(si->ClientMachPort, result, MDNS_MM_TIMEOUT);
if (status == MACH_SEND_TIMED_OUT)
AbortBlockedClient(si->ClientMachPort, "registration success", si);
if (si->autoname && CountPeerRegistrations(m, srs) == 0)
RecordUpdatedNiceLabel(m, 0); }
else if (result == mStatus_NameConflict)
{
LogOperation("%5d: DNSServiceRegistration(%##s, %u) Name Conflict", si->ClientMachPort, srs->RR_SRV.resrec.name->c, SRS_PORT(srs));
if (si->autoname && CountPeerRegistrations(m, srs) == 0)
{
IncrementLabelSuffix(&m->nicelabel, mDNStrue);
m->MainCallback(m, mStatus_ConfigChanged);
}
else if (si->autoname)
{
mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
return;
}
else
{
kern_return_t status = DNSServiceRegistrationReply_rpc(si->ClientMachPort, result, MDNS_MM_TIMEOUT);
if (status == MACH_SEND_TIMED_OUT)
AbortBlockedClient(si->ClientMachPort, "registration conflict", NULL);
}
}
else if (result == mStatus_MemFree)
{
if (si->autorename)
{
debugf("RegCallback renaming %#s to %#s", si->name.c, m->nicelabel.c);
si->autorename = mDNSfalse;
si->name = m->nicelabel;
mDNS_RenameAndReregisterService(m, srs, &si->name);
}
else
{
DNSServiceRegistration *r;
for (r = DNSServiceRegistrationList; r; r = r->next)
{
ServiceInstance *sp = r->regs, *prev = NULL;
while (sp)
{
if (sp == si)
{
LogMsg("RegCallback: %##s Still in DNSServiceRegistration list; removing now", srs->RR_SRV.resrec.name->c);
if (prev) prev->next = sp->next;
else r->regs = sp->next;
break;
}
prev = sp;
sp = sp->next;
}
}
FreeServiceInstance(si);
}
}
else if (result != mStatus_NATTraversal)
LogMsg("%5d: DNSServiceRegistration(%##s, %u) Unknown Result %ld", si->ClientMachPort, srs->RR_SRV.resrec.name->c, SRS_PORT(srs), result);
}
mDNSlocal mStatus AddServiceInstance(DNSServiceRegistration *x, const domainname *domain)
{
mStatus err = 0;
ServiceInstance *si = NULL;
AuthRecord *SubTypes = NULL;
for (si = x->regs; si; si = si->next)
{
if (SameDomainName(&si->domain, domain))
{ LogMsg("Requested addition of domain %##s already in list", domain->c); return mStatus_AlreadyRegistered; }
}
SubTypes = AllocateSubTypes(x->NumSubTypes, x->regtype);
if (x->NumSubTypes && !SubTypes) return mStatus_NoMemoryErr;
si = mallocL("ServiceInstance", sizeof(*si) - sizeof(RDataBody) + x->rdsize);
if (!si) return mStatus_NoMemoryErr;
si->ClientMachPort = x->ClientMachPort;
si->autorename = mDNSfalse;
si->autoname = x->autoname;
si->name = x->autoname ? mDNSStorage.nicelabel : x->name;
si->domain = *domain;
err = mDNS_RegisterService(&mDNSStorage, &si->srs, &si->name, &x->type, domain, NULL, x->port, x->txtinfo, x->txt_len, SubTypes, x->NumSubTypes, mDNSInterface_Any, RegCallback, si);
if (!err)
{
si->next = x->regs;
x->regs = si;
}
else
{
LogMsg("Error %d for registration of service in domain %##s", err, domain->c);
freeL("ServiceInstance", si);
}
return err;
}
mDNSexport void DefaultRegDomainChanged(const domainname *d, mDNSBool add)
{
DNSServiceRegistration *reg;
for (reg = DNSServiceRegistrationList; reg; reg = reg->next)
{
if (reg->DefaultDomain)
{
if (add)
{
AddServiceInstance(reg, d);
}
else
{
ServiceInstance *si = reg->regs, *prev = NULL;
while (si)
{
if (SameDomainName(&si->domain, d))
{
if (prev) prev->next = si->next;
else reg->regs = si->next;
if (mDNS_DeregisterService(&mDNSStorage, &si->srs))
FreeServiceInstance(si); break;
}
prev = si;
si = si->next;
}
if (!si) debugf("Requested removal of default domain %##s not in client %5d's list", d, reg->ClientMachPort); }
}
}
}
mDNSexport kern_return_t provide_DNSServiceRegistrationCreate_rpc(mach_port_t unusedserver, mach_port_t client,
DNSCString name, DNSCString regtype, DNSCString domain, IPPort IpPort, DNSCString txtRecord)
{
(void)unusedserver; mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
mDNSIPPort port;
port.b[0] = IpPort.bytes[2];
port.b[1] = IpPort.bytes[3];
if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
size_t reglen = strlen(regtype) + 1;
if (reglen > MAX_ESCAPED_DOMAIN_NAME) { errormsg = "reglen too long"; goto badparam; }
mDNSs32 NumSubTypes = ChopSubTypes(regtype); if (NumSubTypes < 0) { errormsg = "Bad Service SubType"; goto badparam; }
domainlabel n;
domainname t, d;
domainname srv;
if (!name[0]) n = mDNSStorage.nicelabel;
else if (!MakeDomainLabelFromLiteralString(&n, name)) { errormsg = "Bad Instance Name"; goto badparam; }
if (!regtype[0] || !MakeDomainNameFromDNSNameString(&t, regtype)) { errormsg = "Bad Service Type"; goto badparam; }
if (!MakeDomainNameFromDNSNameString(&d, *domain ? domain : "local.")) { errormsg = "Bad Domain"; goto badparam; }
if (!ConstructServiceName(&srv, &n, &t, &d)) { errormsg = "Bad Name"; goto badparam; }
unsigned char txtinfo[1024] = "";
unsigned int data_len = 0;
unsigned int size = sizeof(RDataBody);
unsigned char *pstring = &txtinfo[data_len];
char *ptr = txtRecord;
while (*ptr)
{
if (++data_len >= sizeof(txtinfo)) { errormsg = "TXT record too long"; goto badtxt; }
if (*ptr == 1) {
pstring = &txtinfo[data_len];
pstring[0] = 0;
ptr++;
}
else
{
if (pstring[0] == 255) { errormsg = "TXT record invalid (component longer than 255)"; goto badtxt; }
pstring[++pstring[0]] = *ptr++;
}
}
data_len++;
if (size < data_len)
size = data_len;
if (port.NotAnInteger)
{
int count = CountExistingRegistrations(&srv, port);
if (count)
LogMsg("%5d: Client application registered %d identical instances of service %##s port %u.",
client, count+1, srv.c, mDNSVal16(port));
}
DNSServiceRegistration *x = mallocL("DNSServiceRegistration", sizeof(*x));
if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
bzero(x, sizeof(*x));
x->ClientMachPort = client;
x->DefaultDomain = !domain[0];
x->autoname = (!name[0]);
x->rdsize = size;
x->NumSubTypes = NumSubTypes;
memcpy(x->regtype, regtype, reglen);
x->name = n;
x->type = t;
x->port = port;
memcpy(x->txtinfo, txtinfo, 1024);
x->txt_len = data_len;
x->NextRef = 0;
x->regs = NULL;
x->next = DNSServiceRegistrationList;
DNSServiceRegistrationList = x;
LogOperation("%5d: DNSServiceRegistration(\"%s\", \"%s\", \"%s\", %u) START",
x->ClientMachPort, name, regtype, domain, mDNSVal16(port));
err = AddServiceInstance(x, &d);
if (err) { AbortClient(client, x); errormsg = "mDNS_RegisterService"; goto fail; }
if (x->DefaultDomain)
{
DNameListElem *ptr, *regdomains = mDNSPlatformGetRegDomainList();
for (ptr = regdomains; ptr; ptr = ptr->next)
AddServiceInstance(x, &ptr->name);
mDNS_FreeDNameList(regdomains);
}
EnableDeathNotificationForClient(client, x);
return(mStatus_NoError);
badtxt:
LogMsg("%5d: TXT record: %.100s...", client, txtRecord);
badparam:
err = mStatus_BadParamErr;
fail:
LogMsg("%5d: DNSServiceRegister(\"%s\", \"%s\", \"%s\", %d) failed: %s (%ld)",
client, name, regtype, domain, mDNSVal16(port), errormsg, err);
return(err);
}
mDNSlocal CFUserNotificationRef gNotification = NULL;
mDNSlocal CFRunLoopSourceRef gNotificationRLS = NULL;
mDNSlocal domainlabel gNotificationPrefHostLabel; mDNSlocal domainlabel gNotificationPrefNiceLabel;
mDNSlocal domainlabel gNotificationUserHostLabel; mDNSlocal domainlabel gNotificationUserNiceLabel;
mDNSlocal void NotificationCallBackDismissed(CFUserNotificationRef userNotification, CFOptionFlags responseFlags)
{
(void)responseFlags; if (userNotification != gNotification) LogMsg("NotificationCallBackDismissed: Wrong CFUserNotificationRef");
if (gNotificationRLS)
{
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), gNotificationRLS, kCFRunLoopDefaultMode);
CFRelease(gNotificationRLS);
gNotificationRLS = NULL;
CFRelease(gNotification);
gNotification = NULL;
}
gNotificationUserHostLabel = gNotificationPrefHostLabel;
gNotificationUserNiceLabel = gNotificationPrefNiceLabel;
}
mDNSlocal void ShowNameConflictNotification(CFStringRef header, CFStringRef subtext)
{
CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (!dictionary) return;
CFDictionarySetValue(dictionary, kCFUserNotificationAlertHeaderKey, header);
CFDictionarySetValue(dictionary, kCFUserNotificationAlertMessageKey, subtext);
CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, CFSTR("/System/Library/CoreServices/mDNSResponder.bundle"), kCFURLPOSIXPathStyle, true);
if (urlRef) { CFDictionarySetValue(dictionary, kCFUserNotificationLocalizationURLKey, urlRef); CFRelease(urlRef); }
if (gNotification) CFUserNotificationUpdate(gNotification, 0, kCFUserNotificationCautionAlertLevel, dictionary);
else {
SInt32 error;
gNotification = CFUserNotificationCreate(NULL, 0, kCFUserNotificationCautionAlertLevel, &error, dictionary);
if (!gNotification) { LogMsg("ShowNameConflictNotification: CFUserNotificationRef"); return; }
gNotificationRLS = CFUserNotificationCreateRunLoopSource(NULL, gNotification, NotificationCallBackDismissed, 0);
if (!gNotificationRLS) { LogMsg("ShowNameConflictNotification: RLS"); CFRelease(gNotification); gNotification = NULL; return; }
CFRunLoopAddSource(CFRunLoopGetCurrent(), gNotificationRLS, kCFRunLoopDefaultMode);
}
CFRelease(dictionary);
}
mDNSlocal void RecordUpdatedName(const mDNS *const m, const domainlabel *const olddl, const domainlabel *const newdl,
const char *const msg, const char *const suffix, const CFStringRef subtext)
{
char oldname[MAX_DOMAIN_LABEL+1];
char newname[MAX_DOMAIN_LABEL+1];
ConvertDomainLabelToCString_unescaped(olddl, oldname);
ConvertDomainLabelToCString_unescaped(newdl, newname);
const CFStringRef cfoldname = CFStringCreateWithCString(NULL, oldname, kCFStringEncodingUTF8);
const CFStringRef cfnewname = CFStringCreateWithCString(NULL, newname, kCFStringEncodingUTF8);
const CFStringRef f1 = CFStringCreateWithCString(NULL, " “%@%s” ", kCFStringEncodingUTF8);
const CFStringRef f2 = CFStringCreateWithCString(NULL, " “%@%s” ", kCFStringEncodingUTF8);
const SCPreferencesRef session = SCPreferencesCreate(NULL, CFSTR("mDNSResponder"), NULL);
if (!cfoldname || !cfnewname || !f1 || !f2 || !session || !SCPreferencesLock(session, 0)) LogMsg("RecordUpdatedName: ERROR: Couldn't create SCPreferences session");
else
{
const CFStringRef s0 = CFStringCreateWithCString(NULL, msg, kCFStringEncodingUTF8);
const CFStringRef s1 = CFStringCreateWithFormat(NULL, NULL, f1, cfoldname, suffix);
const CFStringRef s2 = CFStringCreateWithFormat(NULL, NULL, f2, cfnewname, suffix);
const CFMutableStringRef alertHeader =
(OSXVers < 8) ? CFStringCreateMutable(NULL, 0) : (CFMutableStringRef)CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
Boolean result;
if (newdl == &gNotificationPrefHostLabel) result = SCPreferencesSetLocalHostName(session, cfnewname);
else result = SCPreferencesSetComputerName(session, cfnewname, kCFStringEncodingUTF8);
if (!result || !SCPreferencesCommitChanges(session) || !SCPreferencesApplyChanges(session) || !s0 || !s1 || !s2 || !alertHeader)
LogMsg("RecordUpdatedName: ERROR: Couldn't update SCPreferences");
else if (m->p->NotifyUser)
{
uid_t uid;
gid_t gid;
CFStringRef userName = SCDynamicStoreCopyConsoleUser(NULL, &uid, &gid);
if (userName)
{
CFRelease(userName);
typedef void CFStringAppendFN(CFMutableStringRef theString, CFStringRef appendedString);
CFStringAppendFN *const append = (OSXVers < 8) ? &CFStringAppend : (CFStringAppendFN*)&CFArrayAppendValue;
append(alertHeader, s0);
append(alertHeader, s1);
append(alertHeader, CFSTR("is already in use on this network."));
append(alertHeader, CFSTR(" "));
append(alertHeader, CFSTR("The name has been changed to"));
append(alertHeader, s2);
append(alertHeader, CFSTR("automatically."));
ShowNameConflictNotification(alertHeader, subtext);
}
}
if (s0) CFRelease(s0);
if (s1) CFRelease(s1);
if (s2) CFRelease(s2);
if (alertHeader) CFRelease(alertHeader);
SCPreferencesUnlock(session);
}
if (cfoldname) CFRelease(cfoldname);
if (cfnewname) CFRelease(cfnewname);
if (f1) CFRelease(f1);
if (f2) CFRelease(f2);
if (session) CFRelease(session);
}
mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
{
(void)m; if (result == mStatus_NoError)
{
RecordUpdatedNiceLabel(m, mDNSPlatformOneSecond);
}
else if (result == mStatus_ConfigChanged)
{
if (!SameDomainLabel(m->p->userhostlabel.c, gNotificationPrefHostLabel.c) ||
!SameDomainLabel(m->p->usernicelabel.c, gNotificationPrefNiceLabel.c))
{
gNotificationUserHostLabel = gNotificationPrefHostLabel = m->p->userhostlabel;
gNotificationUserNiceLabel = gNotificationPrefNiceLabel = m->p->usernicelabel;
if (gNotificationRLS) CFUserNotificationCancel(gNotification);
}
DNSServiceRegistration *r;
for (r = DNSServiceRegistrationList; r; r=r->next)
if (r->autoname)
{
ServiceInstance *si;
for (si = r->regs; si; si = si->next)
{
if (!SameDomainLabel(si->name.c, m->nicelabel.c))
{
debugf("NetworkChanged renaming %##s to %#s", si->srs.RR_SRV.resrec.name->c, m->nicelabel.c);
si->autorename = mDNStrue;
if (mDNS_DeregisterService(m, &si->srs)) RegCallback(m, &si->srs, mStatus_MemFree);
}
}
}
udsserver_handle_configchange();
}
else if (result == mStatus_GrowCache)
{
CacheEntity *storage = mallocL("mStatus_GrowCache", sizeof(CacheEntity) * RR_CACHE_SIZE);
if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
}
}
mDNSexport kern_return_t provide_DNSServiceRegistrationAddRecord_rpc(mach_port_t unusedserver, mach_port_t client,
int type, const char *data, mach_msg_type_number_t data_len, uint32_t ttl, natural_t *reference)
{
uint32_t id;
mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
DNSServiceRegistration *x = DNSServiceRegistrationList;
if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
ServiceInstance *si;
size_t size;
(void)unusedserver; while (x && x->ClientMachPort != client) x = x->next;
if (!x) { err = mStatus_BadReferenceErr; errormsg = "No such client"; goto fail; }
if (data_len > 8192) { err = mStatus_BadParamErr; errormsg = "data_len > 8K"; goto fail; }
if (data_len > sizeof(RDataBody)) size = data_len;
else size = sizeof(RDataBody);
id = x->NextRef++;
*reference = (natural_t)id;
for (si = x->regs; si; si = si->next)
{
ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
if (!extra) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
extra->r.resrec.rrtype = type;
extra->r.rdatastorage.MaxRDLength = size;
extra->r.resrec.rdlength = data_len;
memcpy(&extra->r.rdatastorage.u.data, data, data_len);
LogOperation("%5d: DNSServiceRegistrationAddRecord(%##s, type %d, length %d) REF %p",
client, si->srs.RR_SRV.resrec.name->c, type, data_len, extra);
err = mDNS_AddRecordToService(&mDNSStorage, &si->srs, extra, &extra->r.rdatastorage, ttl);
if (err)
{
freeL("Extra Resource Record", extra);
errormsg = "mDNS_AddRecordToService";
goto fail;
}
extra->ClientID = id;
}
return mStatus_NoError;
fail:
LogMsg("%5d: DNSServiceRegistrationAddRecord(%##s, type %d, length %d) failed: %s (%ld)", client, x->name.c, type, data_len, errormsg, err);
return mStatus_UnknownErr;
}
mDNSlocal void UpdateCallback(mDNS *const m, AuthRecord *const rr, RData *OldRData)
{
(void)m; if (OldRData != &rr->rdatastorage)
freeL("Old RData", OldRData);
}
mDNSlocal mStatus UpdateRecord(ServiceRecordSet *srs, mach_port_t client, AuthRecord *rr, const char *data, mach_msg_type_number_t data_len, uint32_t ttl)
{
mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
domainname *name = (domainname *)"";
name = srs->RR_SRV.resrec.name;
unsigned int size = sizeof(RDataBody);
if (size < data_len)
size = data_len;
RData *newrdata = mallocL("RData", sizeof(*newrdata) - sizeof(RDataBody) + size);
if (!newrdata) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
newrdata->MaxRDLength = size;
memcpy(&newrdata->u, data, data_len);
if (rr->resrec.rrtype == kDNSType_TXT && data_len == 0) { data_len = 1; newrdata->u.txt.c[0] = 0; }
LogOperation("%5d: DNSServiceRegistrationUpdateRecord(%##s, new length %d)",
client, srs->RR_SRV.resrec.name->c, data_len);
err = mDNS_Update(&mDNSStorage, rr, ttl, data_len, newrdata, UpdateCallback);
if (err)
{
errormsg = "mDNS_Update";
freeL("RData", newrdata);
return err;
}
return(mStatus_NoError);
fail:
LogMsg("%5d: DNSServiceRegistrationUpdateRecord(%##s, %d) failed: %s (%ld)", client, name->c, data_len, errormsg, err);
return(err);
}
mDNSexport kern_return_t provide_DNSServiceRegistrationUpdateRecord_rpc(mach_port_t unusedserver, mach_port_t client,
natural_t reference, const char *data, mach_msg_type_number_t data_len, uint32_t ttl)
{
mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
domainname *name = (domainname *)"";
ServiceInstance *si;
(void)unusedserver; if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
DNSServiceRegistration *x = DNSServiceRegistrationList;
while (x && x->ClientMachPort != client) x = x->next;
if (!x) { err = mStatus_BadReferenceErr; errormsg = "No such client"; goto fail; }
if (data_len > 8192) { err = mStatus_BadParamErr; errormsg = "data_len > 8K"; goto fail; }
for (si = x->regs; si; si = si->next)
{
AuthRecord *r = NULL;
if (!reference) r = &si->srs.RR_TXT;
else
{
ExtraResourceRecord *ptr;
for (ptr = si->srs.Extras; ptr; ptr = ptr->next)
{
if ((natural_t)ptr->ClientID == reference)
{ r = &ptr->r; break; }
}
if (!r) { err = mStatus_BadReferenceErr; errormsg = "No such record"; goto fail; }
}
err = UpdateRecord(&si->srs, client, r, data, data_len, ttl);
if (err) goto fail; }
return mStatus_NoError;
fail:
LogMsg("%5d: DNSServiceRegistrationUpdateRecord(%##s, %X, %d) failed: %s (%ld)", client, name->c, reference, data_len, errormsg, err);
return(err);
}
mDNSlocal mStatus RemoveRecord(ServiceRecordSet *srs, ExtraResourceRecord *extra, mach_port_t client)
{
domainname *name = srs->RR_SRV.resrec.name;
mStatus err = mStatus_NoError;
LogOperation("%5d: DNSServiceRegistrationRemoveRecord(%##s)", client, srs->RR_SRV.resrec.name->c);
err = mDNS_RemoveRecordFromService(&mDNSStorage, srs, extra, FreeExtraRR, extra);
if (err) LogMsg("%5d: DNSServiceRegistrationRemoveRecord (%##s) failed: %d", client, name->c, err);
return err;
}
mDNSexport kern_return_t provide_DNSServiceRegistrationRemoveRecord_rpc(mach_port_t unusedserver, mach_port_t client,
natural_t reference)
{
(void)unusedserver; mStatus err = mStatus_NoError;
const char *errormsg = "Unknown";
if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
DNSServiceRegistration *x = DNSServiceRegistrationList;
ServiceInstance *si;
while (x && x->ClientMachPort != client) x = x->next;
if (!x) { err = mStatus_BadReferenceErr; errormsg = "No such client"; goto fail; }
for (si = x->regs; si; si = si->next)
{
ExtraResourceRecord *e;
for (e = si->srs.Extras; e; e = e->next)
{
if ((natural_t)e->ClientID == reference)
{
err = RemoveRecord(&si->srs, e, client);
break;
}
}
if (!e) { err = mStatus_BadReferenceErr; errormsg = "No such reference"; goto fail; }
}
return mStatus_NoError;
fail:
LogMsg("%5d: DNSServiceRegistrationRemoveRecord(%X) failed: %s (%ld)", client, reference, errormsg, err);
return(err);
}
mDNSlocal void DNSserverCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
{
mig_reply_error_t *request = msg;
mig_reply_error_t *reply;
mach_msg_return_t mr;
int options;
(void)port; (void)size; (void)info;
reply = CFAllocatorAllocate(NULL, provide_DNSServiceDiscoveryRequest_subsystem.maxsize, 0);
(void) DNSServiceDiscoveryRequest_server(&request->Head, &reply->Head);
if (!(reply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) && (reply->RetCode != KERN_SUCCESS))
{
if (reply->RetCode == MIG_NO_REPLY)
{
CFAllocatorDeallocate(NULL, reply);
return;
}
request->Head.msgh_remote_port = MACH_PORT_NULL;
mach_msg_destroy(&request->Head);
}
if (reply->Head.msgh_remote_port == MACH_PORT_NULL)
{
if (reply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX)
mach_msg_destroy(&reply->Head);
CFAllocatorDeallocate(NULL, reply);
return;
}
options = MACH_SEND_MSG;
if (MACH_MSGH_BITS_REMOTE(reply->Head.msgh_bits) == MACH_MSG_TYPE_MOVE_SEND_ONCE)
options |= MACH_SEND_TIMEOUT;
mr = mach_msg(&reply->Head,
options,
reply->Head.msgh_size,
0,
MACH_PORT_NULL,
MACH_MSG_TIMEOUT_NONE,
MACH_PORT_NULL);
switch (mr)
{
case MACH_SEND_INVALID_DEST:
case MACH_SEND_TIMED_OUT:
mach_msg_destroy(&reply->Head);
break;
default :
break;
}
CFAllocatorDeallocate(NULL, reply);
}
mDNSlocal kern_return_t registerBootstrapService()
{
kern_return_t status;
mach_port_t service_send_port, service_rcv_port;
debugf("Registering Bootstrap Service");
status = bootstrap_check_in(bootstrap_port, (char*)kmDNSBootstrapName, &service_rcv_port);
if (status == KERN_SUCCESS)
{
server_priv_port = bootstrap_port;
restarting_via_mach_init = TRUE;
}
else if (status == BOOTSTRAP_UNKNOWN_SERVICE)
{
status = bootstrap_create_server(bootstrap_port, "/usr/sbin/mDNSResponder", getuid(),
FALSE , &server_priv_port);
if (status != KERN_SUCCESS) return status;
status = bootstrap_create_service(server_priv_port, (char*)kmDNSBootstrapName, &service_send_port);
if (status != KERN_SUCCESS)
{
mach_port_deallocate(mach_task_self(), server_priv_port);
return status;
}
status = bootstrap_check_in(server_priv_port, (char*)kmDNSBootstrapName, &service_rcv_port);
if (status != KERN_SUCCESS)
{
mach_port_deallocate(mach_task_self(), server_priv_port);
mach_port_deallocate(mach_task_self(), service_send_port);
return status;
}
assert(service_send_port == service_rcv_port);
}
mach_port_destroy(mach_task_self(), service_rcv_port);
return status;
}
mDNSlocal kern_return_t destroyBootstrapService()
{
debugf("Destroying Bootstrap Service");
return bootstrap_register(server_priv_port, (char*)kmDNSBootstrapName, MACH_PORT_NULL);
}
mDNSlocal void ExitCallback(int signal)
{
LogMsgIdent(mDNSResponderVersionString, "stopping");
debugf("ExitCallback");
if (!mDNS_DebugMode && !started_via_launchdaemon && signal != SIGHUP)
destroyBootstrapService();
debugf("ExitCallback: Aborting MIG clients");
while (DNSServiceDomainEnumerationList)
AbortClient(DNSServiceDomainEnumerationList->ClientMachPort, DNSServiceDomainEnumerationList);
while (DNSServiceBrowserList)
AbortClient(DNSServiceBrowserList ->ClientMachPort, DNSServiceBrowserList);
while (DNSServiceResolverList)
AbortClient(DNSServiceResolverList ->ClientMachPort, DNSServiceResolverList);
while (DNSServiceRegistrationList)
AbortClient(DNSServiceRegistrationList ->ClientMachPort, DNSServiceRegistrationList);
debugf("ExitCallback: mDNS_Close");
mDNS_Close(&mDNSStorage);
if (udsserver_exit() < 0) LogMsg("ExitCallback: udsserver_exit failed");
exit(0);
}
mDNSlocal void HandleSIG(int signal)
{
debugf(" ");
debugf("HandleSIG %d", signal);
mach_msg_header_t header;
header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND, 0);
header.msgh_remote_port = signal_port;
header.msgh_local_port = MACH_PORT_NULL;
header.msgh_size = sizeof(header);
header.msgh_id = signal;
if (mach_msg_send(&header) != MACH_MSG_SUCCESS)
{
LogMsg("HandleSIG %d: mach_msg_send failed", signal);
if (signal == SIGHUP || signal == SIGTERM || signal == SIGINT) exit(-1);
}
}
mDNSlocal void INFOCallback(void)
{
mDNSs32 utc = mDNSPlatformUTC();
DNSServiceDomainEnumeration *e;
DNSServiceBrowser *b;
DNSServiceResolver *l;
DNSServiceRegistration *r;
NetworkInterfaceInfoOSX *i;
DNSServer *s;
LogMsgIdent(mDNSResponderVersionString, "---- BEGIN STATE LOG ----");
udsserver_info(&mDNSStorage);
for (e = DNSServiceDomainEnumerationList; e; e=e->next)
LogMsgNoIdent("%5d: Mach DomainEnumeration %##s", e->ClientMachPort, e->dom.qname.c);
for (b = DNSServiceBrowserList; b; b=b->next)
{
DNSServiceBrowserQuestion *qptr;
for (qptr = b->qlist; qptr; qptr = qptr->next)
LogMsgNoIdent("%5d: Mach ServiceBrowse %##s", b->ClientMachPort, qptr->q.qname.c);
}
for (l = DNSServiceResolverList; l; l=l->next)
LogMsgNoIdent("%5d: Mach ServiceResolve %##s", l->ClientMachPort, l->i.name.c);
for (r = DNSServiceRegistrationList; r; r=r->next)
{
ServiceInstance *si;
for (si = r->regs; si; si = si->next)
LogMsgNoIdent("%5d: Mach ServiceInstance %##s %u", si->ClientMachPort, si->srs.RR_SRV.resrec.name->c, mDNSVal16(si->srs.RR_SRV.resrec.rdata->u.srv.port));
}
for (i = mDNSStorage.p->InterfaceList; i; i = i->next)
{
if (!i->Exists)
LogMsgNoIdent("Interface: %s %5s(%lu) %.6a DORMANT %d",
i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifa_name, i->scope_id, &i->BSSID, utc - i->LastSeen);
else
LogMsgNoIdent("Interface: %s %5s(%lu) %.6a %s %s %2d %s %2d InterfaceID %p %s %s %#a",
i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifa_name, i->scope_id, &i->BSSID,
i->ifinfo.InterfaceActive ? "Active" : " ",
i->ifinfo.IPv4Available ? "v4" : " ", i->ss.sktv4,
i->ifinfo.IPv6Available ? "v6" : " ", i->ss.sktv6,
i->ifinfo.InterfaceID,
i->ifinfo.Advertise ? "Adv" : " ",
i->ifinfo.McastTxRx ? "TxRx" : " ",
&i->ifinfo.ip);
}
for (s = mDNSStorage.uDNS_info.Servers; s; s = s->next)
LogMsgNoIdent("DNS Server %#a %##s", &s->addr, s->domain.c);
LogMsgIdent(mDNSResponderVersionString, "---- END STATE LOG ----");
}
mDNSlocal void SignalCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
{
(void)port; (void)size; (void)info; mach_msg_header_t *m = (mach_msg_header_t *)msg;
switch(m->msgh_id)
{
case SIGHUP:
case SIGINT:
case SIGTERM: ExitCallback(m->msgh_id); break;
case SIGINFO: INFOCallback(); break;
case SIGUSR1: LogMsg("SIGUSR1: Simulate Network Configuration Change Event");
mDNSMacOSXNetworkChanged(&mDNSStorage); break;
default: LogMsg("SignalCallback: Unknown signal %d", m->msgh_id); break;
}
}
mDNSlocal kern_return_t mDNSDaemonInitialize(void)
{
mStatus err;
CFMachPortRef d_port = CFMachPortCreate(NULL, ClientDeathCallback, NULL, NULL);
CFMachPortRef s_port = CFMachPortCreate(NULL, DNSserverCallback, NULL, NULL);
CFMachPortRef i_port = CFMachPortCreate(NULL, SignalCallback, NULL, NULL);
mach_port_t m_port = CFMachPortGetPort(s_port);
char *MachServerName = OSXVers < 7 ? "DNSServiceDiscoveryServer" : "com.apple.mDNSResponder";
kern_return_t status = bootstrap_register(bootstrap_port, MachServerName, m_port);
CFRunLoopSourceRef d_rls = CFMachPortCreateRunLoopSource(NULL, d_port, 0);
CFRunLoopSourceRef s_rls = CFMachPortCreateRunLoopSource(NULL, s_port, 0);
CFRunLoopSourceRef i_rls = CFMachPortCreateRunLoopSource(NULL, i_port, 0);
if (status)
{
if (status == 1103)
LogMsg("Bootstrap_register failed(): A copy of the daemon is apparently already running");
else
LogMsg("Bootstrap_register failed(): %s %d", mach_error_string(status), status);
return(status);
}
err = mDNS_Init(&mDNSStorage, &PlatformStorage,
rrcachestorage, RR_CACHE_SIZE,
mDNS_Init_AdvertiseLocalAddresses,
mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
if (err) { LogMsg("Daemon start: mDNS_Init failed %ld", err); return(err); }
gNotificationUserHostLabel = gNotificationPrefHostLabel = PlatformStorage.userhostlabel;
gNotificationUserNiceLabel = gNotificationPrefNiceLabel = PlatformStorage.usernicelabel;
client_death_port = CFMachPortGetPort(d_port);
signal_port = CFMachPortGetPort(i_port);
CFRunLoopAddSource(CFRunLoopGetCurrent(), d_rls, kCFRunLoopDefaultMode);
CFRunLoopAddSource(CFRunLoopGetCurrent(), s_rls, kCFRunLoopDefaultMode);
CFRunLoopAddSource(CFRunLoopGetCurrent(), i_rls, kCFRunLoopDefaultMode);
CFRelease(d_rls);
CFRelease(s_rls);
CFRelease(i_rls);
if (mDNS_DebugMode) printf("Service registered with Mach Port %d\n", m_port);
return(err);
}
mDNSlocal mDNSs32 mDNSDaemonIdle(mDNS *const m)
{
mDNSs32 now = mDNS_TimeNow(m);
if (m->p->NetworkChanged && now - m->p->NetworkChanged >= 0) mDNSMacOSXNetworkChanged(m);
mDNSs32 nextevent = mDNS_Execute(m);
if (m->p->NetworkChanged)
if (nextevent - m->p->NetworkChanged > 0)
nextevent = m->p->NetworkChanged;
DNSServiceBrowser *b = DNSServiceBrowserList;
while (b)
{
DNSServiceBrowser *x = b;
b = b->next;
if (x->results) {
while (x->results)
{
DNSServiceBrowserResult *const r = x->results;
domainlabel name;
domainname type, domain;
DeconstructServiceName(&r->result, &name, &type, &domain); char cname[MAX_DOMAIN_LABEL+1]; char ctype[MAX_ESCAPED_DOMAIN_NAME];
char cdom [MAX_ESCAPED_DOMAIN_NAME];
ConvertDomainLabelToCString_unescaped(&name, cname);
ConvertDomainNameToCString(&type, ctype);
ConvertDomainNameToCString(&domain, cdom);
DNSServiceDiscoveryReplyFlags flags = (r->next) ? DNSServiceDiscoverReplyFlagsMoreComing : 0;
kern_return_t status = DNSServiceBrowserReply_rpc(x->ClientMachPort, r->resultType, cname, ctype, cdom, flags, 1);
if (status == MACH_SEND_TIMED_OUT)
{
if (nextevent - now > mDNSPlatformOneSecond)
nextevent = now + mDNSPlatformOneSecond;
break;
}
else
{
x->lastsuccess = now;
x->results = x->results->next;
freeL("DNSServiceBrowserResult", r);
}
}
if (now - x->lastsuccess >= 60 * mDNSPlatformOneSecond)
AbortBlockedClient(x->ClientMachPort, "browse", x);
}
}
DNSServiceResolver *l;
for (l = DNSServiceResolverList; l; l=l->next)
if (l->ReportTime && now - l->ReportTime >= 0)
{
l->ReportTime = 0;
LogMsgNoIdent("Client application bug: DNSServiceResolver(%##s) active for over two minutes. "
"This places considerable burden on the network.", l->i.name.c);
}
if (m->p->NotifyUser)
{
if (m->p->NotifyUser - now < 0)
{
if (!SameDomainLabel(m->p->usernicelabel.c, m->nicelabel.c))
{
LogMsg("Updating Computer Name from \"%#s\" to \"%#s\"", m->p->usernicelabel.c, m->nicelabel.c);
gNotificationPrefNiceLabel = m->p->usernicelabel = m->nicelabel;
RecordUpdatedName(m, &gNotificationUserNiceLabel, &gNotificationPrefNiceLabel, "The name of your computer", "",
CFSTR("To change the name of your computer, open System Preferences and click Sharing. "
"Then type the name in the Computer Name field."));
m->p->NotifyUser = 0;
}
if (!SameDomainLabel(m->p->userhostlabel.c, m->hostlabel.c))
{
LogMsg("Updating Local Hostname from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
gNotificationPrefHostLabel = m->p->userhostlabel = m->hostlabel;
RecordUpdatedName(m, &gNotificationUserHostLabel, &gNotificationPrefHostLabel, "This computer’s local hostname", ".local",
CFSTR("To change the local hostname, open System Preferences and click Sharing. "
"Then click Edit and type the name in the Local Hostname field."));
}
m->p->NotifyUser = 0;
}
else
if (nextevent - m->p->NotifyUser > 0)
nextevent = m->p->NotifyUser;
}
return(nextevent);
}
mDNSlocal void ShowTaskSchedulingError(mDNS *const m)
{
mDNS_Lock(m);
LogMsg("Task Scheduling Error: Continuously busy for more than a second");
if (m->NewQuestions && (!m->NewQuestions->DelayAnswering || m->timenow - m->NewQuestions->DelayAnswering >= 0))
LogMsg("Task Scheduling Error: NewQuestion %##s (%s)",
m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
if (m->NewLocalOnlyQuestions)
LogMsg("Task Scheduling Error: NewLocalOnlyQuestions %##s (%s)",
m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
if (m->NewLocalRecords && LocalRecordReady(m->NewLocalRecords))
LogMsg("Task Scheduling Error: NewLocalRecords %s", ARDisplayString(m, m->NewLocalRecords));
if (m->SuppressSending && m->timenow - m->SuppressSending >= 0)
LogMsg("Task Scheduling Error: m->SuppressSending %d", m->timenow - m->SuppressSending);
#ifndef UNICAST_DISABLED
if (m->timenow - m->uDNS_info.nextevent >= 0)
LogMsg("Task Scheduling Error: m->uDNS_info.nextevent %d", m->timenow - m->uDNS_info.nextevent);
#endif
if (m->timenow - m->NextCacheCheck >= 0)
LogMsg("Task Scheduling Error: m->NextCacheCheck %d", m->timenow - m->NextCacheCheck);
if (m->timenow - m->NextScheduledQuery >= 0)
LogMsg("Task Scheduling Error: m->NextScheduledQuery %d", m->timenow - m->NextScheduledQuery);
if (m->timenow - m->NextScheduledProbe >= 0)
LogMsg("Task Scheduling Error: m->NextScheduledProbe %d", m->timenow - m->NextScheduledProbe);
if (m->timenow - m->NextScheduledResponse >= 0)
LogMsg("Task Scheduling Error: m->NextScheduledResponse %d", m->timenow - m->NextScheduledResponse);
mDNS_Unlock(&mDNSStorage);
}
mDNSexport int main(int argc, char **argv)
{
int i;
kern_return_t status;
for (i=1; i<argc; i++)
{
if (!strcmp(argv[i], "-d")) mDNS_DebugMode = mDNStrue;
if (!strcmp(argv[i], "-launchdaemon")) started_via_launchdaemon = mDNStrue;
}
signal(SIGHUP, HandleSIG); signal(SIGINT, HandleSIG); signal(SIGPIPE, SIG_IGN ); signal(SIGTERM, HandleSIG); signal(SIGINFO, HandleSIG); signal(SIGUSR1, HandleSIG);
if (!mDNS_DebugMode && !started_via_launchdaemon)
{
registerBootstrapService();
if (!restarting_via_mach_init) exit(0); int fd = open(_PATH_DEVNULL, O_RDWR, 0);
if (fd < 0) LogMsg("open(_PATH_DEVNULL, O_RDWR, 0) failed errno %d (%s)", errno, strerror(errno));
else
{
if (fd != STDIN_FILENO) if (dup2(fd, STDIN_FILENO) < 0) LogMsg("dup2(fd, STDIN_FILENO) failed errno %d (%s)", errno, strerror(errno));
if (fd != STDOUT_FILENO) if (dup2(fd, STDOUT_FILENO) < 0) LogMsg("dup2(fd, STDOUT_FILENO) failed errno %d (%s)", errno, strerror(errno));
if (fd != STDERR_FILENO) if (dup2(fd, STDERR_FILENO) < 0) LogMsg("dup2(fd, STDERR_FILENO) failed errno %d (%s)", errno, strerror(errno));
if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO) (void)close(fd);
}
}
status = udsserver_init();
if (status) { LogMsg("Daemon start: udsserver_init failed"); goto exit; }
LogMsgIdent(mDNSResponderVersionString, "starting");
OSXVers = mDNSMacOSXSystemBuildNumber(NULL);
status = mDNSDaemonInitialize();
#if CAN_UPDATE_DYNAMIC_STORE_WITHOUT_BEING_ROOT
const struct passwd *pw = getpwnam("nobody");
if (pw != NULL)
setuid(pw->pw_uid);
else
setuid(-2); #endif
if (status == 0)
{
LogOperation("Starting time value 0x%08lX (%ld)", (mDNSu32)mDNSStorage.timenow_last, mDNSStorage.timenow_last);
int numevents = 0;
int RunLoopStatus = kCFRunLoopRunTimedOut;
while (RunLoopStatus == kCFRunLoopRunTimedOut)
{
mDNSs32 nextevent = mDNSDaemonIdle(&mDNSStorage);
nextevent = udsserver_idle(nextevent);
mDNSs32 ticks = nextevent - mDNS_TimeNow(&mDNSStorage);
static mDNSs32 RepeatedBusy = 0; if (ticks > 1)
RepeatedBusy = 0;
else
{
ticks = 1;
if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
}
CFAbsoluteTime interval = (CFAbsoluteTime)ticks / (CFAbsoluteTime)mDNSPlatformOneSecond;
verbosedebugf("main: Handled %d events; now sleeping for %d ticks", numevents, ticks);
numevents = 0;
RunLoopStatus = CFRunLoopRunInMode(kCFRunLoopDefaultMode, interval, true);
while (RunLoopStatus == kCFRunLoopRunHandledSource)
{
numevents++;
RunLoopStatus = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, true);
}
}
LogMsg("ERROR: CFRunLoopRun Exiting.");
mDNS_Close(&mDNSStorage);
}
LogMsgIdent(mDNSResponderVersionString, "exiting");
exit:
if (!mDNS_DebugMode && !started_via_launchdaemon) destroyBootstrapService();
return(status);
}
struct CFSocketEventSource
{
udsEventCallback Callback;
void *Context;
int fd;
struct CFSocketEventSource *Next;
CFSocketRef cfs;
CFRunLoopSourceRef RLS;
};
typedef struct CFSocketEventSource CFSocketEventSource;
static GenLinkedList gEventSources;
mDNSlocal void cf_callback(CFSocketRef s, CFSocketCallBackType t, CFDataRef dr, const void *c, void *i)
{
(void)s; (void)t; (void)dr; (void)c; CFSocketEventSource *source = (CFSocketEventSource*) i;
source->Callback(source->Context);
}
mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context)
{
CFSocketEventSource *newSource;
CFSocketContext cfContext = { 0, NULL, NULL, NULL, NULL };
if (gEventSources.LinkOffset == 0)
InitLinkedList(&gEventSources, offsetof(CFSocketEventSource, Next));
if (fd >= FD_SETSIZE || fd < 0)
return mStatus_UnsupportedErr;
if (callback == NULL)
return mStatus_BadParamErr;
newSource = (CFSocketEventSource*) calloc(1, sizeof *newSource);
if (NULL == newSource)
return mStatus_NoMemoryErr;
newSource->Callback = callback;
newSource->Context = context;
newSource->fd = fd;
cfContext.info = newSource;
if ( NULL != (newSource->cfs = CFSocketCreateWithNative(kCFAllocatorDefault, fd, kCFSocketReadCallBack,
cf_callback, &cfContext)) &&
NULL != (newSource->RLS = CFSocketCreateRunLoopSource(kCFAllocatorDefault, newSource->cfs, 0)))
{
CFRunLoopAddSource(CFRunLoopGetCurrent(), newSource->RLS, kCFRunLoopDefaultMode);
AddToTail(&gEventSources, newSource);
}
else
{
if (newSource->cfs)
{
CFSocketInvalidate(newSource->cfs); CFRelease(newSource->cfs);
}
return mStatus_NoMemoryErr;
}
return mStatus_NoError;
}
mStatus udsSupportRemoveFDFromEventLoop(int fd) {
CFSocketEventSource *iSource;
for (iSource=(CFSocketEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
{
if (fd == iSource->fd)
{
RemoveFromList(&gEventSources, iSource);
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), iSource->RLS, kCFRunLoopDefaultMode);
CFRunLoopSourceInvalidate(iSource->RLS);
CFRelease(iSource->RLS);
CFSocketInvalidate(iSource->cfs); CFRelease(iSource->cfs);
free(iSource);
return mStatus_NoError;
}
}
return mStatus_NoSuchNameErr;
}
const char *__crashreporter_info__ = mDNSResponderVersionString;
asm(".desc ___crashreporter_info__, 0x10");
mDNSexport const char mDNSResponderVersionString[] = STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";