1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2015 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 #define usleep(X) Sleep(((X)+999)/1000)
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
27 #include <sys/resource.h>
33 #include "mDNSEmbeddedAPI.h"
34 #include "DNSCommon.h"
36 #include "uds_daemon.h"
37 #include "dns_sd_internal.h"
39 // Normally we append search domains only for queries with a single label that are not
40 // fully qualified. This can be overridden to apply search domains for queries (that are
41 // not fully qualified) with any number of labels e.g., moon, moon.cs, moon.cs.be, etc.
42 mDNSBool AlwaysAppendSearchDomains = mDNSfalse;
44 // Apple-specific functionality, not required for other platforms
45 #if APPLE_OSX_mDNSResponder
46 #include <sys/ucred.h>
53 #include <sys/un.h> // for LOCAL_PEEREPID
54 #include <sys/socket.h> // for getsockopt
55 #include <sys/proc_info.h> // for struct proc_bsdshortinfo
56 #include <libproc.h> // for proc_pidinfo()
57 #endif //LOCAL_PEEREPID
63 #if APPLE_OSX_mDNSResponder
64 #include <WebFilterDNS/WebFilterDNS.h>
69 int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
70 int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
71 int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
73 // Do we really need to define a macro for "if"?
74 #define CHECK_WCF_FUNCTION(X) if (X)
79 #endif // APPLE_OSX_mDNSResponder
81 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
82 // User IDs for real user accounts start at 501 and count up from there
83 #define SystemUID(X) ((X) <= 500)
85 #define MAX_ANONYMOUS_DATA 256
87 // ***************************************************************************
88 #if COMPILER_LIKES_PRAGMA_MARK
90 #pragma mark - Globals
94 mDNSexport mDNS mDNSStorage;
95 mDNSexport const char ProgramName[] = "mDNSResponder";
97 #if defined(USE_TCP_LOOPBACK)
98 static char* boundPath = NULL;
100 static char* boundPath = MDNS_UDS_SERVERPATH;
103 #define MDNS_UDS_SERVERPATH_DEBUG "/var/tmp/mDNSResponder"
105 static dnssd_sock_t listenfd = dnssd_InvalidSocket;
106 static request_state *all_requests = NULL;
107 #ifdef LOCAL_PEEREPID
108 struct proc_bsdshortinfo proc;
109 #endif //LOCAL_PEEREPID
110 mDNSlocal void set_peer_pid(request_state *request);
111 mDNSlocal void LogMcastClientInfo(request_state *req);
112 mDNSlocal void GetMcastClients(request_state *req);
113 static mDNSu32 mcount; // tracks the current active mcast operations for McastLogging
114 static mDNSu32 i_mcount; // sets mcount when McastLogging is enabled(PROF signal is sent)
115 static mDNSu32 n_mrecords; // tracks the current active mcast records for McastLogging
116 static mDNSu32 n_mquests; // tracks the current active mcast questions for McastLogging
119 #if TARGET_OS_EMBEDDED
120 mDNSu32 curr_num_regservices = 0;
121 mDNSu32 max_num_regservices = 0;
125 // Note asymmetry here between registration and browsing.
126 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
127 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
128 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
129 // 1. SCPrefBrowseDomains (local configuration data)
130 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
131 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
132 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
134 mDNSexport DNameListElem *AutoRegistrationDomains; // Domains where we automatically register for empty-string registrations
136 static DNameListElem *SCPrefBrowseDomains; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
137 static ARListElem *LocalDomainEnumRecords; // List of locally-generated PTR records to augment those we learn from the network
138 mDNSexport DNameListElem *AutoBrowseDomains; // List created from those local-only PTR records plus records we get from the network
140 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
141 // n get_string() calls w/o buffer overrun
142 // initialization, setup/teardown functions
144 // If a platform specifies its own PID file name, we use that
146 #define PID_FILE "/var/run/mDNSResponder.pid"
149 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen);
151 // ***************************************************************************
152 #if COMPILER_LIKES_PRAGMA_MARK
154 #pragma mark - General Utility Functions
157 mDNSlocal void FatalError(char *errmsg)
159 LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
163 mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
166 char *data = (char*) &ret;
167 put_uint32(l, &data);
171 // hack to search-replace perror's to LogMsg's
172 mDNSlocal void my_perror(char *errmsg)
174 LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
177 // Throttled version of my_perror: Logs once every 250 msgs
178 mDNSlocal void my_throttled_perror(char *err_msg)
180 static int uds_throttle_count = 0;
181 if ((uds_throttle_count++ % 250) == 0)
185 // LogMcastQuestion/LogMcastQ should be called after the DNSQuestion struct is initialized(especially for q->TargetQID)
186 // Hence all calls are made after mDNS_StartQuery()/mDNS_StopQuery()/mDNS_StopBrowse() is called.
187 mDNSlocal void LogMcastQuestion(const DNSQuestion *const q, request_state *req, q_state status)
189 if (mDNSOpaque16IsZero(q->TargetQID)) // Check for Mcast Query
191 mDNSBool mflag = mDNSfalse;
192 if (status == q_start)
201 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Question" : "-Question", q->qname.c, DNSTypeName(q->qtype),
202 q->InterfaceID == mDNSInterface_LocalOnly ? "lo" :
203 q->InterfaceID == mDNSInterface_P2P ? "p2p" :
204 q->InterfaceID == mDNSInterface_BLE ? "BLE" :
205 q->InterfaceID == mDNSInterface_Any ? "any" : InterfaceNameForID(&mDNSStorage, q->InterfaceID),
206 req->process_id, req->pid_name);
207 LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
212 // LogMcastService/LogMcastS should be called after the AuthRecord struct is initialized
213 // Hence all calls are made after mDNS_Register()/ just before mDNS_Deregister()
214 mDNSlocal void LogMcastService(const AuthRecord *const ar, request_state *req, reg_state status)
216 if (!AuthRecord_uDNS(ar)) // Check for Mcast Service
218 mDNSBool mflag = mDNSfalse;
219 if (status == reg_start)
228 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Service" : "-Service", ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype),
229 ar->resrec.InterfaceID == mDNSInterface_LocalOnly ? "lo" :
230 ar->resrec.InterfaceID == mDNSInterface_P2P ? "p2p" :
231 ar->resrec.InterfaceID == mDNSInterface_BLE ? "BLE" :
232 ar->resrec.InterfaceID == mDNSInterface_Any ? "all" : InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID),
233 req->process_id, req->pid_name);
234 LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
239 // For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
240 mDNSexport void LogMcastStateInfo(mDNSBool mflag, mDNSBool start, mDNSBool mstatelog)
242 mDNS *const m = &mDNSStorage;
247 LogMcastNoIdent("<None>");
251 request_state *req, *r;
252 for (req = all_requests; req; req=req->next)
254 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
256 for (r = all_requests; r && r != req; r=r->next)
257 if (r == req->primary)
260 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
261 GetMcastClients(req);
264 LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords, n_mquests);
265 n_mrecords = n_mquests = 0; // Reset the values
270 static mDNSu32 i_mpktnum;
274 // mcount is initialized to 0 when the PROF signal is sent since mcount could have
275 // wrong value if MulticastLogging is disabled and then re-enabled
276 LogMcastNoIdent("--- START MCAST STATE LOG ---");
280 LogMcastNoIdent("<None>");
284 request_state *req, *r;
285 for (req = all_requests; req; req=req->next)
287 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
289 for (r = all_requests; r && r != req; r=r->next)
290 if (r == req->primary)
292 LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req->sd);
294 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
295 LogMcastClientInfo(req);
298 if(!mcount) // To initially set mcount
303 i_mpktnum = m->MPktNum;
304 LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount, i_mpktnum);
307 LogMcastNoIdent("--- MCOUNT[%d]: CMPKTNUM[%d] - IMPKTNUM[%d] = [%d]PKTS ---", mcount, m->MPktNum, i_mpktnum, (m->MPktNum - i_mpktnum));
308 LogMcastNoIdent("--- END MCAST STATE LOG ---");
312 mDNSlocal void abort_request(request_state *req)
314 if (req->terminate == (req_termination_fn) ~0)
315 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
317 // First stop whatever mDNSCore operation we were doing
318 // If this is actually a shared connection operation, then its req->terminate function will scan
319 // the all_requests list and terminate any subbordinate operations sharing this file descriptor
320 if (req->terminate) req->terminate(req);
322 if (!dnssd_SocketValid(req->sd))
323 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req, req->sd); return; }
325 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
328 if (req->errsd != req->sd) LogOperation("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
329 else LogOperation("%3d: Removing FD", req->sd);
330 udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data); // Note: This also closes file descriptor req->sd for us
331 if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
333 while (req->replies) // free pending replies
335 reply_state *ptr = req->replies;
336 req->replies = req->replies->next;
337 freeL("reply_state (abort)", ptr);
341 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
342 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
343 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
344 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
345 req->sd = req->errsd = -2;
347 req->sd = req->errsd = dnssd_InvalidSocket;
349 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
350 req->terminate = (req_termination_fn) ~0;
354 mDNSexport void SetDebugBoundPath(void)
356 #if !defined(USE_TCP_LOOPBACK)
357 boundPath = MDNS_UDS_SERVERPATH_DEBUG;
361 mDNSexport int IsDebugSocketInUse(void)
363 #if !defined(USE_TCP_LOOPBACK)
364 return !strcmp(boundPath, MDNS_UDS_SERVERPATH_DEBUG);
371 mDNSlocal void AbortUnlinkAndFree(request_state *req)
373 request_state **p = &all_requests;
375 while (*p && *p != req) p=&(*p)->next;
376 if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
377 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
380 mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
384 if ((unsigned)datalen < sizeof(reply_hdr))
386 LogMsg("ERROR: create_reply - data length less than length of required fields");
390 reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
391 if (!reply) FatalError("ERROR: malloc");
393 reply->next = mDNSNULL;
394 reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
397 reply->mhdr->version = VERSION;
398 reply->mhdr->datalen = (mDNSu32)datalen;
399 reply->mhdr->ipc_flags = 0;
400 reply->mhdr->op = op;
401 reply->mhdr->client_context = request->hdr.client_context;
402 reply->mhdr->reg_index = 0;
407 // Append a reply to the list in a request object
408 // If our request is sharing a connection, then we append our reply_state onto the primary's list
409 // If the request does not want asynchronous replies, then the reply is freed instead of being appended to any list.
410 mDNSlocal void append_reply(request_state *req, reply_state *rep)
417 freeL("reply_state/append_reply", rep);
421 r = req->primary ? req->primary : req;
423 while (*ptr) ptr = &(*ptr)->next;
428 // Generates a response message giving name, type, domain, plus interface index,
429 // suitable for a browse result or service registration result.
430 // On successful completion rep is set to point to a malloc'd reply_state struct
431 mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
432 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
435 domainname type, dom;
437 if (!DeconstructServiceName(servicename, &name, &type, &dom))
438 return kDNSServiceErr_Invalid;
441 char namestr[MAX_DOMAIN_LABEL+1];
442 char typestr[MAX_ESCAPED_DOMAIN_NAME];
443 char domstr [MAX_ESCAPED_DOMAIN_NAME];
447 ConvertDomainLabelToCString_unescaped(&name, namestr);
448 ConvertDomainNameToCString(&type, typestr);
449 ConvertDomainNameToCString(&dom, domstr);
451 // Calculate reply data length
452 len = sizeof(DNSServiceFlags);
453 len += sizeof(mDNSu32); // if index
454 len += sizeof(DNSServiceErrorType);
455 len += (int) (strlen(namestr) + 1);
456 len += (int) (strlen(typestr) + 1);
457 len += (int) (strlen(domstr) + 1);
459 // Build reply header
460 *rep = create_reply(op, len, request);
461 (*rep)->rhdr->flags = dnssd_htonl(flags);
462 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
463 (*rep)->rhdr->error = dnssd_htonl(err);
466 data = (char *)&(*rep)->rhdr[1];
467 put_string(namestr, &data);
468 put_string(typestr, &data);
469 put_string(domstr, &data);
471 return mStatus_NoError;
475 mDNSlocal void GenerateBrowseReply(const domainname *const servicename, const mDNSInterfaceID id,
476 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
478 char namestr[MAX_DOMAIN_LABEL+1];
479 char typestr[MAX_ESCAPED_DOMAIN_NAME];
480 static const char domstr[] = ".";
486 // 1. Put first label in namestr
487 ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
489 // 2. Put second label and "local" into typestr
490 mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
492 // Calculate reply data length
493 len = sizeof(DNSServiceFlags);
494 len += sizeof(mDNSu32); // if index
495 len += sizeof(DNSServiceErrorType);
496 len += (int) (strlen(namestr) + 1);
497 len += (int) (strlen(typestr) + 1);
498 len += (int) (strlen(domstr) + 1);
500 // Build reply header
501 *rep = create_reply(op, len, request);
502 (*rep)->rhdr->flags = dnssd_htonl(flags);
503 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
504 (*rep)->rhdr->error = dnssd_htonl(err);
507 data = (char *)&(*rep)->rhdr[1];
508 put_string(namestr, &data);
509 put_string(typestr, &data);
510 put_string(domstr, &data);
513 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
514 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
515 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
516 mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
518 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
519 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
521 int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
522 mDNSu16 type = get_uint16(&request->msgptr, request->msgend);
523 mDNSu16 class = get_uint16(&request->msgptr, request->msgend);
524 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
525 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
526 mDNSu32 ttl = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
527 size_t storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
529 mDNSInterfaceID InterfaceID;
532 request->flags = flags;
533 request->interfaceIndex = interfaceIndex;
535 if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
537 if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
539 if (validate_flags &&
540 !((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
541 !((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
543 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
547 rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
548 if (!rr) FatalError("ERROR: malloc");
550 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
551 if (InterfaceID == mDNSInterface_LocalOnly)
552 artype = AuthRecordLocalOnly;
553 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
554 artype = AuthRecordP2P;
555 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
556 && (flags & kDNSServiceFlagsIncludeAWDL))
557 artype = AuthRecordAnyIncludeAWDLandP2P;
558 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
559 artype = AuthRecordAnyIncludeP2P;
560 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
561 artype = AuthRecordAnyIncludeAWDL;
563 artype = AuthRecordAny;
565 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
566 (mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
568 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
570 LogMsg("ERROR: bad name: %s", name);
571 freeL("AuthRecord/read_rr_from_ipc_msg", rr);
575 if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
576 rr->resrec.rrclass = class;
577 rr->resrec.rdlength = rdlen;
578 rr->resrec.rdata->MaxRDLength = rdlen;
579 mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
580 if (GetTTL) rr->resrec.rroriginalttl = ttl;
581 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
582 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
586 mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
591 if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
592 if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
593 if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
594 if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
598 mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
600 int n = send(s, ptr, len, 0);
601 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
602 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
603 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
605 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
606 s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
610 mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
612 const DNameListElem *delem = mDNSNULL;
613 int bestDelta = -1; // the delta of the best match, lower is better
615 mDNSBool allow = mDNSfalse;
617 if (SystemUID(request->uid)) return mDNStrue;
619 dLabels = CountLabels(d);
620 for (delem = doms; delem; delem = delem->next)
624 int delemLabels = CountLabels(&delem->name);
625 int delta = dLabels - delemLabels;
626 if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
629 allow = (allow || (delem->uid == request->uid));
634 return bestDelta == -1 ? mDNStrue : allow;
638 // ***************************************************************************
639 #if COMPILER_LIKES_PRAGMA_MARK
641 #pragma mark - external helpers
644 mDNSexport mDNSBool callExternalHelpers(mDNSInterfaceID InterfaceID, const domainname *const domain, DNSServiceFlags flags)
646 #if APPLE_OSX_mDNSResponder
648 // Only call D2D layer routines if request applies to a D2D interface and the domain is "local".
649 if ( (((InterfaceID == mDNSInterface_Any) && (flags & (kDNSServiceFlagsIncludeP2P | kDNSServiceFlagsIncludeAWDL | kDNSServiceFlagsAutoTrigger)))
650 || mDNSPlatformInterfaceIsD2D(InterfaceID) || (InterfaceID == mDNSInterface_BLE))
651 && IsLocalDomain(domain))
664 #endif // APPLE_OSX_mDNSResponder
667 mDNSlocal void external_start_advertising_helper(service_instance *const instance)
669 AuthRecord *st = instance->subtypes;
670 ExtraResourceRecord *e;
673 if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
675 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
679 if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
681 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
682 external_start_advertising_service(&st[i].resrec, instance->request->flags);
684 external_start_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
685 external_start_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
687 external_start_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
689 for (e = instance->srs.Extras; e; e = e->next)
690 external_start_advertising_service(&e->r.resrec, instance->request->flags);
692 instance->external_advertise = mDNStrue;
695 mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
697 AuthRecord *st = instance->subtypes;
698 ExtraResourceRecord *e;
701 if (!instance->external_advertise) return;
703 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
705 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
706 external_stop_advertising_service(&st[i].resrec, instance->request->flags);
708 external_stop_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
709 external_stop_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
710 external_stop_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
712 for (e = instance->srs.Extras; e; e = e->next)
713 external_stop_advertising_service(&e->r.resrec, instance->request->flags);
715 instance->external_advertise = mDNSfalse;
718 // ***************************************************************************
719 #if COMPILER_LIKES_PRAGMA_MARK
721 #pragma mark - DNSServiceRegister
724 mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
726 ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
729 if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
731 LogInfo(" FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
733 if (rr->resrec.rdata != &rr->rdatastorage)
734 freeL("Extra RData", rr->resrec.rdata);
735 freeL("ExtraResourceRecord/FreeExtraRR", extra);
738 mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
740 ExtraResourceRecord *e = srv->srs.Extras, *tmp;
742 external_stop_advertising_helper(srv);
744 // clear pointers from parent struct
747 service_instance **p = &srv->request->u.servicereg.instances;
750 if (*p == srv) { *p = (*p)->next; break; }
757 e->r.RecordContext = e;
760 FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
763 if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
764 freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
768 freeL("ServiceSubTypes", srv->subtypes);
769 srv->subtypes = NULL;
771 if (srv->srs.AnonData)
773 freeL("Anonymous", (void *)srv->srs.AnonData);
774 srv->srs.AnonData = NULL;
776 freeL("service_instance", srv);
779 // Count how many other service records we have locally with the same name, but different rdata.
780 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
781 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
782 mDNSexport int CountPeerRegistrations(ServiceRecordSet *const srs)
785 ResourceRecord *r = &srs->RR_SRV.resrec;
788 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
789 if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
792 verbosedebugf("%d peer registrations for %##s", count, r->name->c);
796 mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
800 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
801 if (rr->resrec.rrtype == kDNSType_SRV &&
802 mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
803 SameDomainName(rr->resrec.name, srv))
808 mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
811 service_instance *instance = srs->ServiceContext;
812 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
813 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
814 else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
817 // service registration callback performs three duties - frees memory for deregistered services,
818 // handles name conflicts, and delivers completed registration information to the client
819 mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
822 mDNSBool SuppressError = mDNSfalse;
823 service_instance *instance;
827 if (!srs) { LogMsg("regservice_callback: srs is NULL %d", result); return; }
829 instance = srs->ServiceContext;
830 if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
832 // don't send errors up to client for wide-area, empty-string registrations
833 if (instance->request &&
834 instance->request->u.servicereg.default_domain &&
835 !instance->default_local)
836 SuppressError = mDNStrue;
838 if (mDNS_LoggingEnabled)
840 const char *const fmt =
841 (result == mStatus_NoError) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
842 (result == mStatus_MemFree) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
843 (result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
844 "%s DNSServiceRegister(%##s, %u) %s %d";
845 char prefix[16] = "---:";
846 if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
847 LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
848 SuppressError ? "suppressed error" : "CALLBACK", result);
851 if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
853 if (result == mStatus_NoError)
855 if (instance->request->u.servicereg.allowremotequery)
857 ExtraResourceRecord *e;
858 srs->RR_ADV.AllowRemoteQuery = mDNStrue;
859 srs->RR_PTR.AllowRemoteQuery = mDNStrue;
860 srs->RR_SRV.AllowRemoteQuery = mDNStrue;
861 srs->RR_TXT.AllowRemoteQuery = mDNStrue;
862 for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
865 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
866 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
867 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
869 if (callExternalHelpers(instance->request->u.servicereg.InterfaceID, &instance->domain, instance->request->flags))
871 LogInfo("regservice_callback: calling external_start_advertising_helper()");
872 external_start_advertising_helper(instance);
874 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
875 RecordUpdatedNiceLabel(0); // Successfully got new name, tell user immediately
877 else if (result == mStatus_MemFree)
879 #if TARGET_OS_EMBEDDED
880 curr_num_regservices--;
882 if (instance->request && instance->renameonmemfree)
884 external_stop_advertising_helper(instance);
885 instance->renameonmemfree = 0;
886 err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
887 if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
888 // error should never happen - safest to log and continue
891 unlink_and_free_service_instance(instance);
893 else if (result == mStatus_NameConflict)
895 if (instance->request->u.servicereg.autorename)
897 external_stop_advertising_helper(instance);
898 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
900 // On conflict for an autoname service, rename and reregister *all* autoname services
901 IncrementLabelSuffix(&m->nicelabel, mDNStrue);
902 mDNS_ConfigChanged(m); // Will call back into udsserver_handle_configchange()
904 else // On conflict for a non-autoname service, rename and reregister just that one service
906 if (instance->clientnotified) SendServiceRemovalNotification(srs);
907 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
914 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
915 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
916 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
918 unlink_and_free_service_instance(instance);
921 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
925 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
926 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
927 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
932 mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
935 if (!rr->RecordContext) // parent struct already freed by termination callback
937 if (result == mStatus_NoError)
938 LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
941 if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
943 // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
944 // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
945 // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
946 // to free the latest rdata for which the update_callback was never called with.
947 if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
948 freeL("AuthRecord/regrecord_callback", rr);
953 registered_record_entry *re = rr->RecordContext;
954 request_state *request = re->request;
956 if (mDNS_LoggingEnabled)
958 char *fmt = (result == mStatus_NoError) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
959 (result == mStatus_MemFree) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
960 (result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
961 "%3d: DNSServiceRegisterRecord(%u %s) %d";
962 LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
965 if (result != mStatus_MemFree)
967 int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
968 reply_state *reply = create_reply(reg_record_reply_op, len, request);
969 reply->mhdr->client_context = re->regrec_client_context;
970 reply->rhdr->flags = dnssd_htonl(0);
971 reply->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
972 reply->rhdr->error = dnssd_htonl(result);
973 append_reply(request, reply);
978 // If this is a callback to a keepalive record, do not free it.
979 if (result == mStatus_BadStateErr)
981 LogInfo("regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.");
985 // unlink from list, free memory
986 registered_record_entry **ptr = &request->u.reg_recs;
987 while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
988 if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
990 freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
991 freeL("registered_record_entry regrecord_callback", re);
996 if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
998 if (callExternalHelpers(re->origInterfaceID, &rr->namestorage, request->flags))
1000 LogInfo("regrecord_callback: calling external_start_advertising_service");
1001 external_start_advertising_service(&rr->resrec, request->flags);
1002 re->external_advertise = mDNStrue;
1008 // set_peer_pid() is called after mem is allocated for each new request in NewRequest()
1009 // This accounts for 2 places (connect_callback, request_callback)
1010 mDNSlocal void set_peer_pid(request_state *request)
1012 pid_t p = (pid_t) -1;
1013 socklen_t len = sizeof(p);
1014 request->pid_name[0] = '\0';
1015 request->process_id = -1;
1016 #ifdef LOCAL_PEEREPID
1017 if (request->sd < 0)
1019 // to extract the effective pid value
1020 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &p, &len) != 0)
1022 // to extract the process name from the pid value
1023 if (proc_pidinfo(p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
1025 mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
1026 request->process_id = p;
1027 debugf("set_peer_pid: Client PEEREPID is %d %s", p, request->pid_name);
1028 #else // !LOCAL_PEEREPID
1030 LogInfo("set_peer_pid: Not Supported on this version of OS");
1031 if (request->sd < 0)
1033 #endif // LOCAL_PEEREPID
1036 mDNSlocal void connection_termination(request_state *request)
1038 // When terminating a shared connection, we need to scan the all_requests list
1039 // and terminate any subbordinate operations sharing this file descriptor
1040 request_state **req = &all_requests;
1042 LogOperation("%3d: DNSServiceCreateConnection STOP PID[%d](%s)", request->sd, request->process_id, request->pid_name);
1046 if ((*req)->primary == request)
1048 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1049 request_state *tmp = *req;
1050 if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp, tmp->sd);
1051 if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
1054 freeL("request_state/connection_termination", tmp);
1057 req = &(*req)->next;
1060 while (request->u.reg_recs)
1062 registered_record_entry *ptr = request->u.reg_recs;
1063 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP PID[%d](%s)", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec), request->process_id, request->pid_name);
1064 request->u.reg_recs = request->u.reg_recs->next;
1065 ptr->rr->RecordContext = NULL;
1066 if (ptr->external_advertise)
1068 ptr->external_advertise = mDNSfalse;
1069 external_stop_advertising_service(&ptr->rr->resrec, request->flags);
1071 LogMcastS(ptr->rr, request, reg_stop);
1072 mDNS_Deregister(&mDNSStorage, ptr->rr); // Will free ptr->rr for us
1073 freeL("registered_record_entry/connection_termination", ptr);
1077 mDNSlocal void handle_cancel_request(request_state *request)
1079 request_state **req = &all_requests;
1080 LogOperation("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
1083 if ((*req)->primary == request &&
1084 (*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1085 (*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
1087 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1088 request_state *tmp = *req;
1091 freeL("request_state/handle_cancel_request", tmp);
1094 req = &(*req)->next;
1098 mDNSlocal mStatus handle_regrecord_request(request_state *request)
1100 mStatus err = mStatus_BadParamErr;
1103 if (request->terminate != connection_termination)
1104 { LogMsg("%3d: DNSServiceRegisterRecord(not a shared connection ref)", request->sd); return(err); }
1106 rr = read_rr_from_ipc_msg(request, 1, 1);
1109 registered_record_entry *re;
1110 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1111 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1112 if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
1113 rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
1114 rr->resrec.rrtype == kDNSType_CNAME))
1116 freeL("AuthRecord/handle_regrecord_request", rr);
1117 return (mStatus_BadParamErr);
1119 // allocate registration entry, link into list
1120 re = mallocL("registered_record_entry", sizeof(registered_record_entry));
1122 FatalError("ERROR: malloc");
1123 re->key = request->hdr.reg_index;
1125 re->regrec_client_context = request->hdr.client_context;
1126 re->request = request;
1127 re->external_advertise = mDNSfalse;
1128 rr->RecordContext = re;
1129 rr->RecordCallback = regrecord_callback;
1131 re->origInterfaceID = rr->resrec.InterfaceID;
1132 if (rr->resrec.InterfaceID == mDNSInterface_P2P)
1133 rr->resrec.InterfaceID = mDNSInterface_Any;
1135 if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError);
1137 if (rr->resrec.rroriginalttl == 0)
1138 rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);
1140 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START PID[%d](%s)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec),
1141 request->process_id, request->pid_name);
1143 err = mDNS_Register(&mDNSStorage, rr);
1146 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec), err);
1147 freeL("registered_record_entry", re);
1148 freeL("registered_record_entry/AuthRecord", rr);
1152 LogMcastS(rr, request, reg_start);
1153 re->next = request->u.reg_recs;
1154 request->u.reg_recs = re;
1160 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);
1162 mDNSlocal void regservice_termination_callback(request_state *request)
1166 LogMsg("regservice_termination_callback context is NULL");
1169 while (request->u.servicereg.instances)
1171 service_instance *p = request->u.servicereg.instances;
1172 request->u.servicereg.instances = request->u.servicereg.instances->next;
1173 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1174 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP PID[%d](%s)", request->sd, p->srs.RR_SRV.resrec.name->c,
1175 mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port), request->process_id, request->pid_name);
1177 external_stop_advertising_helper(p);
1179 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1180 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1181 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1182 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1183 // because by then we might have already freed p
1185 LogMcastS(&p->srs.RR_SRV, request, reg_stop);
1186 if (mDNS_DeregisterService(&mDNSStorage, &p->srs))
1188 unlink_and_free_service_instance(p);
1189 // Don't touch service_instance *p after this -- it's likely to have been freed already
1192 if (request->u.servicereg.txtdata)
1194 freeL("service_info txtdata", request->u.servicereg.txtdata);
1195 request->u.servicereg.txtdata = NULL;
1197 if (request->u.servicereg.autoname)
1199 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1200 request->u.servicereg.autoname = mDNSfalse;
1201 UpdateDeviceInfoRecord(&mDNSStorage);
1205 mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
1208 for (req = all_requests; req; req = req->next)
1209 if (req->primary == request &&
1210 req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1211 req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
1215 mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl)
1217 ServiceRecordSet *srs = &instance->srs;
1219 size_t size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1220 ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
1221 if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1223 mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord)); // OK if oversized rdata not zero'd
1224 extra->r.resrec.rrtype = rrtype;
1225 extra->r.rdatastorage.MaxRDLength = (mDNSu16) size;
1226 extra->r.resrec.rdlength = rdlen;
1227 mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen);
1228 // use InterfaceID value from DNSServiceRegister() call that created the original service
1229 extra->r.resrec.InterfaceID = request->u.servicereg.InterfaceID;
1231 result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl, request->flags);
1234 freeL("ExtraResourceRecord/add_record_to_service", extra);
1237 LogMcastS(&srs->RR_PTR, request, reg_start);
1239 extra->ClientID = request->hdr.reg_index;
1240 if ( instance->external_advertise
1241 && callExternalHelpers(request->u.servicereg.InterfaceID, &instance->domain, request->flags))
1243 LogInfo("add_record_to_service: calling external_start_advertising_service");
1244 external_start_advertising_service(&extra->r.resrec, request->flags);
1249 mDNSlocal mStatus handle_add_request(request_state *request)
1251 service_instance *i;
1252 mStatus result = mStatus_UnknownErr;
1253 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);
1254 mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend);
1255 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1256 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1257 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1258 if (!ttl) ttl = DefaultTTLforRRType(rrtype);
1259 (void)flags; // Unused
1261 if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1263 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1264 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1266 if (request->terminate != regservice_termination_callback)
1267 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1269 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1270 // in the application. See radar://9165807.
1271 if (mDNSIPPortIsZero(request->u.servicereg.port))
1272 { LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1274 LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d) PID[%d](%s)", request->sd, flags,
1275 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen,
1276 request->process_id, request->pid_name);
1278 for (i = request->u.servicereg.instances; i; i = i->next)
1280 result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
1281 if (result && i->default_local) break;
1282 else result = mStatus_NoError; // suppress non-local default errors
1288 mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
1290 mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
1293 // There are three cases.
1295 // 1. We have updated the primary TXT record of the service
1296 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1297 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1299 // external_advertise is set if we have advertised at least once during the initial addition
1300 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1301 // checks during the first time and hence we don't do any checks here
1302 if (external_advertise)
1304 ResourceRecord ext = rr->resrec;
1305 DNSServiceFlags flags = deriveD2DFlagsFromAuthRecType(rr->ARType);
1307 if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
1308 SetNewRData(&ext, oldrd, oldrdlen);
1309 external_stop_advertising_service(&ext, flags);
1310 LogInfo("update_callback: calling external_start_advertising_service");
1311 external_start_advertising_service(&rr->resrec, flags);
1314 if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
1317 mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl, const mDNSBool *const external_advertise)
1320 const size_t rdsize = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1321 RData *newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize);
1322 if (!newrd) FatalError("ERROR: malloc");
1323 newrd->MaxRDLength = (mDNSu16) rdsize;
1324 mDNSPlatformMemCopy(&newrd->u, rdata, rdlen);
1326 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1327 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1328 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1329 if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }
1331 if (external_advertise) rr->UpdateContext = (void *)external_advertise;
1333 result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback);
1334 if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, rr)); freeL("RData/update_record", newrd); }
1338 mDNSlocal mStatus handle_update_request(request_state *request)
1340 const ipc_msg_hdr *const hdr = &request->hdr;
1341 mStatus result = mStatus_BadReferenceErr;
1342 service_instance *i;
1343 AuthRecord *rr = NULL;
1345 // get the message data
1346 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend); // flags unused
1347 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1348 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1349 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1350 (void)flags; // Unused
1352 if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1354 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1355 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1357 if (request->terminate == connection_termination)
1359 // update an individually registered record
1360 registered_record_entry *reptr;
1361 for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
1363 if (reptr->key == hdr->reg_index)
1365 result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise);
1366 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)",
1367 request->sd, reptr->rr->resrec.name->c, reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>",
1368 request->process_id, request->pid_name);
1372 result = mStatus_BadReferenceErr;
1376 if (request->terminate != regservice_termination_callback)
1377 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1379 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1380 if (mDNSIPPortIsZero(request->u.servicereg.port))
1381 { LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1383 // update the saved off TXT data for the service
1384 if (hdr->reg_index == TXT_RECORD_INDEX)
1386 if (request->u.servicereg.txtdata)
1387 { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
1390 request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
1391 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
1392 mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
1394 request->u.servicereg.txtlen = rdlen;
1397 // update a record from a service record set
1398 for (i = request->u.servicereg.instances; i; i = i->next)
1400 if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
1403 ExtraResourceRecord *e;
1404 for (e = i->srs.Extras; e; e = e->next)
1405 if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
1408 if (!rr) { result = mStatus_BadReferenceErr; goto end; }
1409 result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise);
1410 if (result && i->default_local) goto end;
1411 else result = mStatus_NoError; // suppress non-local default errors
1415 if (request->terminate == regservice_termination_callback)
1416 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)", request->sd,
1417 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1418 rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>",
1419 request->process_id, request->pid_name);
1424 // remove a resource record registered via DNSServiceRegisterRecord()
1425 mDNSlocal mStatus remove_record(request_state *request)
1427 mStatus err = mStatus_UnknownErr;
1428 registered_record_entry *e, **ptr = &request->u.reg_recs;
1430 while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
1431 if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
1433 *ptr = e->next; // unlink
1435 LogOperation("%3d: DNSServiceRemoveRecord(%u %s) PID[%d](%s)",
1436 request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec), request->process_id, request->pid_name);
1437 e->rr->RecordContext = NULL;
1438 if (e->external_advertise)
1440 external_stop_advertising_service(&e->rr->resrec, request->flags);
1441 e->external_advertise = mDNSfalse;
1443 LogMcastS(e->rr, request, reg_stop);
1444 err = mDNS_Deregister(&mDNSStorage, e->rr); // Will free e->rr for us; we're responsible for freeing e
1447 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
1448 freeL("registered_record_entry AuthRecord remove_record", e->rr);
1450 freeL("registered_record_entry remove_record", e);
1454 mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
1456 mStatus err = mStatus_BadReferenceErr;
1457 ExtraResourceRecord *ptr;
1459 for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
1461 if (ptr->ClientID == request->hdr.reg_index) // found match
1463 *rrtype = ptr->r.resrec.rrtype;
1464 if (serv->external_advertise) external_stop_advertising_service(&ptr->r.resrec, request->flags);
1465 err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
1472 mDNSlocal mStatus handle_removerecord_request(request_state *request)
1474 mStatus err = mStatus_BadReferenceErr;
1475 get_flags(&request->msgptr, request->msgend); // flags unused
1477 if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1479 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1480 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1482 if (request->terminate == connection_termination)
1483 err = remove_record(request); // remove individually registered record
1484 else if (request->terminate != regservice_termination_callback)
1485 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1488 service_instance *i;
1490 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s) PID[%d](%s)", request->sd,
1491 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1492 rrtype ? DNSTypeName(rrtype) : "<NONE>", request->process_id, request->pid_name);
1493 for (i = request->u.servicereg.instances; i; i = i->next)
1495 err = remove_extra(request, i, &rrtype);
1496 if (err && i->default_local) break;
1497 else err = mStatus_NoError; // suppress non-local default errors
1504 // If there's a comma followed by another character,
1505 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1506 // Otherwise, it returns a pointer to the final nul at the end of the string
1507 mDNSlocal char *FindFirstSubType(char *p, char **AnonData)
1511 if (p[0] == '\\' && p[1])
1515 else if (p[0] == ',' && p[1])
1520 else if (p[0] == ':' && p[1])
1533 // If there's a comma followed by another character,
1534 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1535 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1536 // Otherwise, it returns a pointer to the final nul at the end of the string
1537 mDNSlocal char *FindNextSubType(char *p)
1541 if (p[0] == '\\' && p[1]) // If escape character
1542 p += 2; // ignore following character
1543 else if (p[0] == ',') // If we found a comma
1548 else if (p[0] == '.')
1555 // Returns -1 if illegal subtype found
1556 mDNSexport mDNSs32 ChopSubTypes(char *regtype, char **AnonData)
1558 mDNSs32 NumSubTypes = 0;
1559 char *stp = FindFirstSubType(regtype, AnonData);
1560 while (stp && *stp) // If we found a comma...
1562 if (*stp == ',') return(-1);
1564 stp = FindNextSubType(stp);
1566 if (!stp) return(-1);
1567 return(NumSubTypes);
1570 mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p, char **AnonData)
1572 AuthRecord *st = mDNSNULL;
1574 // "p" is pointing at the regtype e.g., _http._tcp followed by ":<AnonData>" indicated
1575 // by AnonData being non-NULL which is in turn follwed by ",<SubTypes>" indicated by
1576 // NumSubTypes being non-zero. We need to skip the initial regtype to get to the actual
1577 // data that we want. When we come here, ChopSubTypes has null terminated like this e.g.,
1579 // _http._tcp<NULL><AnonData><NULL><SubType1><NULL><SubType2><NULL> etc.
1581 // 1. If we have Anonymous data and subtypes, skip the regtype (e.g., "_http._tcp")
1582 // to get the AnonData and then skip the AnonData to get to the SubType.
1584 // 2. If we have only SubTypes, skip the regtype to get to the SubType data.
1586 // 3. If we have only AnonData, skip the regtype to get to the AnonData.
1588 // 4. If we don't have AnonData or NumStypes, it is a noop.
1598 len = strlen(p) + 1;
1599 *AnonData = mallocL("Anonymous", len);
1604 mDNSPlatformMemCopy(*AnonData, p, len);
1609 st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
1610 if (!st) return(mDNSNULL);
1611 for (i = 0; i < NumSubTypes; i++)
1613 mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
1614 // First time through we skip the regtype or AnonData. Subsequently, the
1615 // previous subtype.
1618 if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
1620 freeL("ServiceSubTypes", st);
1621 if (AnonData && *AnonData)
1622 freeL("AnonymousData", *AnonData);
1627 // If NumSubTypes is zero and AnonData is non-NULL, we still return NULL but AnonData has been
1628 // initialized. The caller knows how to handle this.
1632 mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
1634 service_instance **ptr, *instance;
1635 size_t extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
1636 const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
1638 mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;
1640 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1641 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1642 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1643 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1644 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1645 if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;
1647 for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
1649 if (SameDomainName(&(*ptr)->domain, domain))
1651 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1652 domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
1653 return mStatus_AlreadyRegistered;
1657 instance = mallocL("service_instance", sizeof(*instance) + extra_size);
1658 if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1660 instance->next = mDNSNULL;
1661 instance->request = request;
1662 instance->renameonmemfree = 0;
1663 instance->clientnotified = mDNSfalse;
1664 instance->default_local = (request->u.servicereg.default_domain && DomainIsLocal);
1665 instance->external_advertise = mDNSfalse;
1666 AssignDomainName(&instance->domain, domain);
1668 instance->srs.AnonData = mDNSNULL;
1669 if (!request->u.servicereg.AnonData)
1671 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, mDNSNULL);
1675 char *AnonData = mDNSNULL;
1676 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, &AnonData);
1678 instance->srs.AnonData = (const mDNSu8 *)AnonData;
1681 if (request->u.servicereg.num_subtypes && !instance->subtypes)
1683 unlink_and_free_service_instance(instance);
1685 FatalError("ERROR: malloc");
1688 result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
1689 &request->u.servicereg.name, &request->u.servicereg.type, domain,
1690 request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
1691 request->u.servicereg.port,
1692 request->u.servicereg.txtdata, request->u.servicereg.txtlen,
1693 instance->subtypes, request->u.servicereg.num_subtypes,
1694 interfaceID, regservice_callback, instance, request->flags);
1698 *ptr = instance; // Append this to the end of our request->u.servicereg.instances list
1699 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance->request->sd,
1700 instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
1701 LogMcastS(&instance->srs.RR_SRV, request, reg_start);
1705 LogMsg("register_service_instance %#s.%##s%##s error %d",
1706 &request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
1707 unlink_and_free_service_instance(instance);
1713 mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
1715 request_state *request;
1717 LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
1718 for (request = all_requests; request; request = request->next)
1720 if (request->terminate != regservice_termination_callback) continue;
1721 if (!request->u.servicereg.default_domain) continue;
1722 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1724 service_instance **ptr = &request->u.servicereg.instances;
1725 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1728 // If we don't already have this domain in our list for this registration, add it now
1729 if (!*ptr) register_service_instance(request, &d->name);
1730 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
1734 // Normally we should not fail to find the specified instance
1735 // One case where this can happen is if a uDNS update fails for some reason,
1736 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1738 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1739 &d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
1743 for (p = AutoRegistrationDomains; p; p=p->next)
1744 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1745 if (SameDomainName(&d->name, &p->name)) break;
1746 if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
1750 service_instance *si = *ptr;
1752 if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
1753 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1754 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1755 // process of completing asynchronously, the client cancels the entire operation, so
1756 // regservice_termination_callback then runs through the whole list deregistering each
1757 // instance, clearing the backpointers, and then disposing the parent request_state object.
1758 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1759 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1760 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1761 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1763 err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
1764 if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
1772 // Don't allow normal and anonymous registration to coexist.
1773 mDNSlocal mDNSBool CheckForMixedRegistrations(domainname *regtype, domainname *domain, mDNSBool AnonData)
1775 request_state *request;
1777 // We only care about local domains where the anonymous extension is
1779 if (!SameDomainName(domain, (const domainname *) "\x5" "local"))
1784 for (request = all_requests; request; request = request->next)
1786 service_instance *ptr;
1788 if (request->terminate != regservice_termination_callback) continue;
1789 for (ptr = request->u.servicereg.instances; ptr ; ptr = ptr->next)
1791 if (!SameDomainName(&ptr->domain, (const domainname *)"\x5" "local") ||
1792 !SameDomainName(&request->u.servicereg.type, regtype))
1797 // If we are about to register a anonymous registraion, we dont't want to
1798 // allow the regular ones and vice versa.
1801 if (!ptr->srs.AnonData)
1803 LogMsg("CheckForMixedRegistrations: Normal registration already exists for %##s", regtype->c);
1809 // Allow multiple regular registrations
1810 if (ptr->srs.AnonData)
1812 LogMsg("CheckForMixedRegistrations: Anonymous registration already exists for %##s", regtype->c);
1821 // Returns true if the interfaceIndex value matches one of the pre-defined
1822 // special values listed in the switch statement below.
1823 mDNSlocal mDNSBool PreDefinedInterfaceIndex(mDNSu32 interfaceIndex)
1825 switch(interfaceIndex)
1827 case kDNSServiceInterfaceIndexAny:
1828 case kDNSServiceInterfaceIndexLocalOnly:
1829 case kDNSServiceInterfaceIndexUnicast:
1830 case kDNSServiceInterfaceIndexP2P:
1831 case kDNSServiceInterfaceIndexBLE:
1838 mDNSlocal mStatus handle_regservice_request(request_state *request)
1840 char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1841 char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
1842 char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
1845 char *AnonData = mDNSNULL;
1846 const char *msgTXTData;
1848 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
1849 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
1850 mDNSInterfaceID InterfaceID;
1852 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
1853 // kDNSServiceFlagsIncludeP2P flag set.
1854 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
1856 LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
1857 flags |= kDNSServiceFlagsIncludeP2P;
1858 interfaceIndex = kDNSServiceInterfaceIndexAny;
1861 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
1863 // The registration is scoped to a specific interface index, but the
1864 // interface is not currently in our list.
1865 if (interfaceIndex && !InterfaceID)
1867 // If it's one of the specially defined inteface index values, just return an error.
1868 if (PreDefinedInterfaceIndex(interfaceIndex))
1870 LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex);
1871 return(mStatus_BadParamErr);
1874 // Otherwise, use the specified interface index value and the registration will
1875 // be applied to that interface when it comes up.
1876 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
1877 LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex);
1880 if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
1881 get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1882 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1883 get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
1884 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
1886 request->flags = flags;
1887 request->interfaceIndex = interfaceIndex;
1888 request->u.servicereg.InterfaceID = InterfaceID;
1889 request->u.servicereg.instances = NULL;
1890 request->u.servicereg.txtlen = 0;
1891 request->u.servicereg.txtdata = NULL;
1892 mDNSPlatformStrLCopy(request->u.servicereg.type_as_string, type_as_string, sizeof(request->u.servicereg.type_as_string));
1894 if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
1897 request->u.servicereg.port.b[0] = *request->msgptr++;
1898 request->u.servicereg.port.b[1] = *request->msgptr++;
1901 request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
1902 msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);
1904 if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1906 if (request->u.servicereg.txtlen)
1908 request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
1909 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
1910 mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
1913 // Check for sub-types after the service type
1914 request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
1915 if (request->u.servicereg.num_subtypes < 0)
1917 LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string);
1922 int AnonDataLen = strlen(AnonData);
1923 if (AnonDataLen > MAX_ANONYMOUS_DATA)
1925 LogMsg("ERROR: handle_regservice_request: AnonDataLen %d", AnonDataLen);
1928 request->u.servicereg.AnonData = mDNStrue;
1932 request->u.servicereg.AnonData = mDNSfalse;
1935 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1936 if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
1937 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); goto bad_param; }
1941 request->u.servicereg.name = mDNSStorage.nicelabel;
1942 request->u.servicereg.autoname = mDNStrue;
1946 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1947 if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
1949 int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
1952 if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
1953 { LogMsg("ERROR: handle_regservice_request - name bad %s", name); goto bad_param; }
1954 request->u.servicereg.autoname = mDNSfalse;
1959 request->u.servicereg.default_domain = mDNSfalse;
1960 if (!MakeDomainNameFromDNSNameString(&d, domain))
1961 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); goto bad_param; }
1965 request->u.servicereg.default_domain = mDNStrue;
1966 MakeDomainNameFromDNSNameString(&d, "local.");
1969 // We don't allow the anonymous and the regular ones to coexist
1970 if (!CheckForMixedRegistrations(&request->u.servicereg.type, &d, request->u.servicereg.AnonData)) { goto bad_param; }
1972 if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
1974 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1975 request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); goto bad_param;
1978 if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
1979 { LogMsg("ERROR: handle_regservice_request - host bad %s", host); goto bad_param; }
1980 request->u.servicereg.autorename = (flags & kDNSServiceFlagsNoAutoRename ) == 0;
1981 request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
1983 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1984 // a port number of zero. When two instances of the protected client are allowed to run on one
1985 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1986 if (!mDNSIPPortIsZero(request->u.servicereg.port))
1988 int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
1990 LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request->process_id,
1991 request->pid_name, count+1, srv.c, mDNSVal16(request->u.servicereg.port));
1994 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
1995 // Determine if this request should be promoted to use BLE triggered feature.
1996 if (shouldUseBLE(InterfaceID, 0, &request->u.servicereg.type, &d))
1998 request->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
1999 LogInfo("handle_regservice_request: registration promoted to use kDNSServiceFlagsAutoTrigger");
2001 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2003 LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START PID[%d](%s)",
2004 request->sd, request->flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host,
2005 mDNSVal16(request->u.servicereg.port), request->process_id, request->pid_name);
2007 // We need to unconditionally set request->terminate, because even if we didn't successfully
2008 // start any registrations right now, subsequent configuration changes may cause successful
2009 // registrations to be added, and we'll need to cancel them before freeing this memory.
2010 // We also need to set request->terminate first, before adding additional service instances,
2011 // because the uds_validatelists uses the request->terminate function pointer to determine
2012 // what kind of request this is, and therefore what kind of list validation is required.
2013 request->terminate = regservice_termination_callback;
2015 err = register_service_instance(request, &d);
2017 #if TARGET_OS_EMBEDDED
2018 ++curr_num_regservices;
2019 if (curr_num_regservices > max_num_regservices)
2020 max_num_regservices = curr_num_regservices;
2024 err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
2028 if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
2033 // Note that we don't report errors for non-local, non-explicit domains
2034 for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
2035 if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
2036 register_service_instance(request, &ptr->name);
2043 freeL("handle_regservice_request (txtdata)", request->u.servicereg.txtdata);
2044 request->u.servicereg.txtdata = NULL;
2045 return mStatus_BadParamErr;
2048 // ***************************************************************************
2049 #if COMPILER_LIKES_PRAGMA_MARK
2051 #pragma mark - DNSServiceBrowse
2054 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2056 DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
2057 request_state *req = question->QuestionContext;
2061 if (answer->rrtype != kDNSType_PTR)
2062 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
2064 if (mDNSOpaque16IsZero(question->TargetQID) && (question->BrowseThreshold > 0) && (question->CurrentAnswers >= question->BrowseThreshold))
2066 flags |= kDNSServiceFlagsThresholdReached;
2069 // if returning a negative answer, then use question's name in reply
2070 if (answer->RecordType == kDNSRecordTypePacketNegative)
2072 GenerateBrowseReply(&question->qname, answer->InterfaceID, req, &rep, browse_reply_op, flags, kDNSServiceErr_NoSuchRecord);
2076 if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
2078 if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
2080 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2081 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2082 GenerateBrowseReply(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
2086 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2087 req->sd, answer->name->c, answer->rdata->u.name.c);
2093 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s interface %d: %s",
2094 req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV",
2095 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2097 append_reply(req, rep);
2100 mDNSlocal void SetQuestionPolicy(DNSQuestion *q, request_state *req)
2103 // The policy is either based on pid or UUID. Pass a zero pid
2104 // to the "core" if the UUID is valid. If we always pass the pid,
2105 // then the "core" needs to determine whether the uuid is valid
2106 // by examining all the 16 bytes at the time of the policy
2107 // check and also when setting the delegate socket option. Also, it
2108 // requires that we zero out the uuid wherever the question is
2109 // initialized to make sure that it is not interpreted as valid.
2110 // To prevent these intrusive changes, just pass a zero pid to indicate
2111 // that pid is not valid when uuid is valid. In future if we need the
2112 // pid in the question, we will reevaluate this strategy.
2115 mDNSPlatformMemCopy(q->uuid, req->uuid, UUID_SIZE);
2120 q->pid = req->process_id;
2123 //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
2126 mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
2131 for (p = info->u.browser.browsers; p; p = p->next)
2133 if (SameDomainName(&p->domain, d))
2134 { debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
2137 b = mallocL("browser_t", sizeof(*b));
2138 if (!b) return mStatus_NoMemoryErr;
2139 mDNSPlatformMemZero(b, sizeof(*b));
2140 AssignDomainName(&b->domain, d);
2141 SetQuestionPolicy(&b->q, info);
2142 err = mDNS_StartBrowse(&mDNSStorage, &b->q, &info->u.browser.regtype, d, info->u.browser.AnonData, info->u.browser.interface_id, info->flags,
2143 info->u.browser.ForceMCast, (info->flags & kDNSServiceFlagsBackgroundTrafficClass) != 0, FoundInstance, info);
2146 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
2147 freeL("browser_t/add_domain_to_browser", b);
2151 b->next = info->u.browser.browsers;
2152 info->u.browser.browsers = b;
2154 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2155 // Determine if this request should be promoted to use BLE triggered discovery.
2156 if (shouldUseBLE(info->u.browser.interface_id, 0, &info->u.browser.regtype, (domainname *) d))
2158 info->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2159 b->q.flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2160 LogInfo("add_domain_to_browser: request promoted to use kDNSServiceFlagsAutoTrigger");
2162 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2164 LogMcastQ(&b->q, info, q_start);
2165 if (callExternalHelpers(info->u.browser.interface_id, &b->domain, info->flags))
2168 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
2169 LogInfo("add_domain_to_browser: calling external_start_browsing_for_service()");
2170 external_start_browsing_for_service(info->u.browser.interface_id, &tmp, kDNSType_PTR, info->flags);
2176 mDNSlocal void browse_termination_callback(request_state *info)
2178 if (info->u.browser.default_domain)
2180 // Stop the domain enumeration queries to discover the WAB legacy browse domains
2181 LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info->sd, info->process_id, info->pid_name);
2182 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2184 if (info->u.browser.AnonData)
2185 freeL("Anonymous", (void *)info->u.browser.AnonData);
2186 while (info->u.browser.browsers)
2188 browser_t *ptr = info->u.browser.browsers;
2190 if (callExternalHelpers(ptr->q.InterfaceID, &ptr->domain, ptr->q.flags))
2193 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
2194 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2195 external_stop_browsing_for_service(ptr->q.InterfaceID, &tmp, kDNSType_PTR, ptr->q.flags);
2198 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\") STOP PID[%d](%s)",
2199 info->sd, info->flags, info->interfaceIndex, ptr->q.qname.c, info->process_id, info->pid_name);
2201 info->u.browser.browsers = ptr->next;
2202 mDNS_StopBrowse(&mDNSStorage, &ptr->q); // no need to error-check result
2203 LogMcastQ(&ptr->q, info, q_stop);
2204 freeL("browser_t/browse_termination_callback", ptr);
2208 mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
2210 request_state *request;
2211 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
2213 for (request = all_requests; request; request = request->next)
2215 if (request->terminate != browse_termination_callback) continue; // Not a browse operation
2216 if (!request->u.browser.default_domain) continue; // Not an auto-browse operation
2217 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
2219 browser_t **ptr = &request->u.browser.browsers;
2220 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
2223 // If we don't already have this domain in our list for this browse operation, add it now
2224 if (!*ptr) add_domain_to_browser(request, &d->name);
2225 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
2229 if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
2233 for (p = AutoBrowseDomains; p; p=p->next)
2234 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
2235 if (SameDomainName(&d->name, &p->name)) break;
2236 if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
2239 browser_t *rem = *ptr;
2240 *ptr = (*ptr)->next;
2241 mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
2242 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
2250 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
2253 if (result == mStatus_MemFree)
2255 // On shutdown, mDNS_Close automatically deregisters all records
2256 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2257 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2258 // (This should actually no longer be necessary, now that we do the proper cleanup in
2259 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2260 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2261 ARListElem **ptr = &LocalDomainEnumRecords;
2262 while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
2263 if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
2264 mDNSPlatformMemFree(rr->RecordContext);
2268 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2269 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2270 // We may want to turn the common code into a subroutine.
2272 mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2274 // allocate/register legacy and non-legacy _browse PTR record
2276 ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
2278 debugf("Incrementing %s refcount for %##s",
2279 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2280 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2281 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2283 mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
2284 MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
2285 AppendDNSNameString (&ptr->ar.namestorage, "local");
2286 AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
2287 err = mDNS_Register(m, &ptr->ar);
2290 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
2291 mDNSPlatformMemFree(ptr);
2295 ptr->next = LocalDomainEnumRecords;
2296 LocalDomainEnumRecords = ptr;
2300 mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2302 ARListElem **ptr = &LocalDomainEnumRecords;
2303 domainname lhs; // left-hand side of PTR, for comparison
2305 debugf("Decrementing %s refcount for %##s",
2306 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2307 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2308 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2310 MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
2311 AppendDNSNameString (&lhs, "local");
2315 if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
2317 ARListElem *rem = *ptr;
2318 *ptr = (*ptr)->next;
2319 mDNS_Deregister(m, &rem->ar);
2322 else ptr = &(*ptr)->next;
2326 mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2328 DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
2329 if (!new) { LogMsg("ERROR: malloc"); return; }
2330 AssignDomainName(&new->name, name);
2332 new->next = AutoBrowseDomains;
2333 AutoBrowseDomains = new;
2334 udsserver_automatic_browse_domain_changed(new, mDNStrue);
2337 mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2339 DNameListElem **p = &AutoBrowseDomains;
2340 while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
2341 if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
2344 DNameListElem *ptr = *p;
2346 udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
2347 mDNSPlatformMemFree(ptr);
2351 mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
2354 for (d = browseDomains; d; d = d->next)
2358 RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2359 AddAutoBrowseDomain(d->uid, &d->name);
2363 DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2364 RmvAutoBrowseDomain(d->uid, &d->name);
2369 #if APPLE_OSX_mDNSResponder
2371 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2373 int num_autoname = 0;
2376 // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2377 for (req = all_requests; req; req = req->next)
2379 if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname && req->interfaceIndex != kDNSServiceInterfaceIndexLocalOnly)
2383 // If DeviceInfo record is currently registered, see if we need to deregister it
2384 if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
2385 if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
2387 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
2388 mDNS_Deregister(m, &m->DeviceInfo);
2391 // If DeviceInfo record is not currently registered, see if we need to register it
2392 if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
2393 if (num_autoname > 0)
2395 mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
2396 ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
2397 m->DeviceInfo.resrec.rdlength = initializeDeviceInfoTXT(m, m->DeviceInfo.resrec.rdata->u.data);
2398 LogOperation("UpdateDeviceInfoRecord Register %##s", m->DeviceInfo.resrec.name);
2399 mDNS_Register(m, &m->DeviceInfo);
2402 #else // APPLE_OSX_mDNSResponder
2403 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2407 #endif // APPLE_OSX_mDNSResponder
2409 mDNSexport void udsserver_handle_configchange(mDNS *const m)
2412 service_instance *ptr;
2413 DNameListElem *RegDomains = NULL;
2414 DNameListElem *BrowseDomains = NULL;
2417 UpdateDeviceInfoRecord(m);
2419 // For autoname services, see if the default service name has changed, necessitating an automatic update
2420 for (req = all_requests; req; req = req->next)
2421 if (req->terminate == regservice_termination_callback)
2422 if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
2424 req->u.servicereg.name = m->nicelabel;
2425 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
2427 ptr->renameonmemfree = 1;
2428 if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
2429 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
2430 if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
2431 regservice_callback(m, &ptr->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
2435 // Let the platform layer get the current DNS information
2437 mDNSPlatformSetDNSConfig(mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains, mDNSfalse);
2440 // Any automatic registration domains are also implicitly automatic browsing domains
2441 if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue); // Add the new list first
2442 if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse); // Then clear the old list
2444 // Add any new domains not already in our AutoRegistrationDomains list
2445 for (p=RegDomains; p; p=p->next)
2447 DNameListElem **pp = &AutoRegistrationDomains;
2448 while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
2449 if (!*pp) // If not found in our existing list, this is a new default registration domain
2451 RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
2452 udsserver_default_reg_domain_changed(p, mDNStrue);
2454 else // else found same domainname in both old and new lists, so no change, just delete old copy
2456 DNameListElem *del = *pp;
2458 mDNSPlatformMemFree(del);
2462 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2463 while (AutoRegistrationDomains)
2465 DNameListElem *del = AutoRegistrationDomains;
2466 AutoRegistrationDomains = AutoRegistrationDomains->next; // Cut record from list FIRST,
2467 DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
2468 udsserver_default_reg_domain_changed(del, mDNSfalse); // before calling udsserver_default_reg_domain_changed()
2469 mDNSPlatformMemFree(del);
2472 // Now we have our new updated automatic registration domain list
2473 AutoRegistrationDomains = RegDomains;
2475 // Add new browse domains to internal list
2476 if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
2478 // Remove old browse domains from internal list
2479 if (SCPrefBrowseDomains)
2481 SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
2482 while (SCPrefBrowseDomains)
2484 DNameListElem *fptr = SCPrefBrowseDomains;
2485 SCPrefBrowseDomains = SCPrefBrowseDomains->next;
2486 mDNSPlatformMemFree(fptr);
2490 // Replace the old browse domains array with the new array
2491 SCPrefBrowseDomains = BrowseDomains;
2494 mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
2499 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2500 AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
2502 if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
2503 else RmvAutoBrowseDomain(0, &answer->rdata->u.name);
2506 mDNSlocal mStatus handle_browse_request(request_state *request)
2508 char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2509 domainname typedn, d, temp;
2510 mDNSs32 NumSubTypes;
2511 char *AnonData = mDNSNULL;
2512 mStatus err = mStatus_NoError;
2515 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2516 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2517 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2519 // The browse is scoped to a specific interface index, but the
2520 // interface is not currently in our list.
2521 if (interfaceIndex && !InterfaceID)
2523 // If it's one of the specially defined inteface index values, just return an error.
2524 if (PreDefinedInterfaceIndex(interfaceIndex))
2526 LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex);
2527 return(mStatus_BadParamErr);
2530 // Otherwise, use the specified interface index value and the browse will
2531 // be applied to that interface when it comes up.
2532 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2533 LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex);
2536 if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2537 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
2539 if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2541 request->flags = flags;
2542 request->interfaceIndex = interfaceIndex;
2544 NumSubTypes = ChopSubTypes(regtype, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
2545 if (NumSubTypes < 0 || NumSubTypes > 1)
2546 return(mStatus_BadParamErr);
2550 AnonDataLen = strlen(AnonData);
2551 if (AnonDataLen > MAX_ANONYMOUS_DATA)
2553 LogMsg("handle_browse_request: AnonDataLen %d", AnonDataLen);
2554 return(mStatus_BadParamErr);
2556 // Account for the null byte
2559 if (NumSubTypes == 1)
2561 if (!AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1 + AnonDataLen))
2562 return(mStatus_BadParamErr);
2565 if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
2567 if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
2568 // For over-long service types, we only allow domain "local"
2569 if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrLCopy(domain, "local.", sizeof(domain));
2571 // Set up browser info
2572 request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
2573 request->u.browser.interface_id = InterfaceID;
2574 AssignDomainName(&request->u.browser.regtype, &typedn);
2575 request->u.browser.default_domain = !domain[0];
2576 request->u.browser.browsers = NULL;
2578 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START PID[%d](%s)",
2579 request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain, request->process_id, request->pid_name);
2581 if (request->u.browser.default_domain)
2583 // Start the domain enumeration queries to discover the WAB browse domains
2584 LogInfo("%3d: DNSServiceBrowse Start WAB PID[%d](%s)", request->sd, request->process_id, request->pid_name);
2585 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2587 request->u.browser.AnonData = mDNSNULL;
2590 int len = strlen(AnonData) + 1;
2591 request->u.browser.AnonData = mallocL("Anonymous", len);
2592 if (!request->u.browser.AnonData)
2593 return mStatus_NoMemoryErr;
2595 mDNSPlatformMemCopy((void *)request->u.browser.AnonData, AnonData, len);
2597 // We need to unconditionally set request->terminate, because even if we didn't successfully
2598 // start any browses right now, subsequent configuration changes may cause successful
2599 // browses to be added, and we'll need to cancel them before freeing this memory.
2600 request->terminate = browse_termination_callback;
2604 if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
2605 err = add_domain_to_browser(request, &d);
2609 DNameListElem *sdom;
2610 for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
2611 if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
2613 err = add_domain_to_browser(request, &sdom->name);
2616 if (SameDomainName(&sdom->name, &localdomain)) break;
2617 else err = mStatus_NoError; // suppress errors for non-local "default" domains
2625 // ***************************************************************************
2626 #if COMPILER_LIKES_PRAGMA_MARK
2628 #pragma mark - DNSServiceResolve
2631 mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2634 char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME] = "0";
2637 request_state *req = question->QuestionContext;
2638 const DNSServiceErrorType error =
2639 (answer->RecordType == kDNSRecordTypePacketNegative) ? kDNSServiceErr_NoSuchRecord : kDNSServiceErr_NoError;
2642 LogOperation("%3d: DNSServiceResolve(%##s) %s interface %d: %s",
2643 req->sd, question->qname.c, AddRecord ? "ADD" : "RMV",
2644 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2648 if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
2649 if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
2653 if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
2654 if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
2656 if (!req->u.resolve.txt || !req->u.resolve.srv) return; // only deliver result to client if we have both answers
2658 ConvertDomainNameToCString(answer->name, fullname);
2660 if (answer->RecordType != kDNSRecordTypePacketNegative)
2661 ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
2663 // calculate reply length
2664 len += sizeof(DNSServiceFlags);
2665 len += sizeof(mDNSu32); // interface index
2666 len += sizeof(DNSServiceErrorType);
2667 len += strlen(fullname) + 1;
2668 len += strlen(target) + 1;
2669 len += 2 * sizeof(mDNSu16); // port, txtLen
2670 len += req->u.resolve.txt->rdlength;
2672 // allocate/init reply header
2673 rep = create_reply(resolve_reply_op, len, req);
2674 rep->rhdr->flags = dnssd_htonl(0);
2675 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
2676 rep->rhdr->error = dnssd_htonl(error);
2678 data = (char *)&rep->rhdr[1];
2680 // write reply data to message
2681 put_string(fullname, &data);
2682 put_string(target, &data);
2683 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[0];
2684 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[1];
2685 put_uint16(req->u.resolve.txt->rdlength, &data);
2686 put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
2688 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
2689 append_reply(req, rep);
2692 mDNSlocal void resolve_termination_callback(request_state *request)
2694 LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") STOP PID[%d](%s)",
2695 request->sd, request->flags, request->interfaceIndex, request->u.resolve.qtxt.qname.c, request->process_id, request->pid_name);
2696 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
2697 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2698 LogMcastQ(&request->u.resolve.qsrv, request, q_stop);
2699 if (request->u.resolve.external_advertise)
2700 external_stop_resolving_service(request->u.resolve.qsrv.InterfaceID, &request->u.resolve.qsrv.qname, request->flags);
2703 mDNSlocal mStatus handle_resolve_request(request_state *request)
2705 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2709 // extract the data from the message
2710 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2711 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2712 mDNSInterfaceID InterfaceID;
2714 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2715 // flag set so that the resolve will run over P2P interfaces that are not yet created.
2716 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
2718 LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2719 flags |= kDNSServiceFlagsIncludeP2P;
2720 interfaceIndex = kDNSServiceInterfaceIndexAny;
2723 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2725 // The operation is scoped to a specific interface index, but the
2726 // interface is not currently in our list.
2727 if (interfaceIndex && !InterfaceID)
2729 // If it's one of the specially defined inteface index values, just return an error.
2730 if (PreDefinedInterfaceIndex(interfaceIndex))
2732 LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex);
2733 return(mStatus_BadParamErr);
2736 // Otherwise, use the specified interface index value and the operation will
2737 // be applied to that interface when it comes up.
2738 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2739 LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex);
2742 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
2743 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2744 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
2745 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2747 if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2749 if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
2750 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
2752 mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
2754 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2755 // Determine if this request should be promoted to use BLE triggered discovery.
2756 if (shouldUseBLE(InterfaceID, 0, (domainname *)SkipLeadingLabels(&fqdn, 1), &fqdn))
2758 flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2759 LogInfo("handle_resolve_request: request promoted to use kDNSServiceFlagsAutoTrigger");
2761 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2763 request->flags = flags;
2764 request->interfaceIndex = interfaceIndex;
2767 request->u.resolve.qsrv.InterfaceID = InterfaceID;
2768 request->u.resolve.qsrv.flags = flags;
2769 request->u.resolve.qsrv.Target = zeroAddr;
2770 AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
2771 request->u.resolve.qsrv.qtype = kDNSType_SRV;
2772 request->u.resolve.qsrv.qclass = kDNSClass_IN;
2773 request->u.resolve.qsrv.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2774 request->u.resolve.qsrv.ExpectUnique = mDNStrue;
2775 request->u.resolve.qsrv.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2776 request->u.resolve.qsrv.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2777 request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
2778 request->u.resolve.qsrv.SearchListIndex = 0;
2779 request->u.resolve.qsrv.AppendSearchDomains = 0;
2780 request->u.resolve.qsrv.RetryWithSearchDomains = mDNSfalse;
2781 request->u.resolve.qsrv.TimeoutQuestion = 0;
2782 request->u.resolve.qsrv.WakeOnResolve = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
2783 request->u.resolve.qsrv.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2784 request->u.resolve.qsrv.ValidationRequired = 0;
2785 request->u.resolve.qsrv.ValidatingResponse = 0;
2786 request->u.resolve.qsrv.ProxyQuestion = 0;
2787 request->u.resolve.qsrv.qnameOrig = mDNSNULL;
2788 request->u.resolve.qsrv.AnonInfo = mDNSNULL;
2789 request->u.resolve.qsrv.pid = request->process_id;
2790 request->u.resolve.qsrv.euid = request->uid;
2791 request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
2792 request->u.resolve.qsrv.QuestionContext = request;
2794 request->u.resolve.qtxt.InterfaceID = InterfaceID;
2795 request->u.resolve.qtxt.flags = flags;
2796 request->u.resolve.qtxt.Target = zeroAddr;
2797 AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn);
2798 request->u.resolve.qtxt.qtype = kDNSType_TXT;
2799 request->u.resolve.qtxt.qclass = kDNSClass_IN;
2800 request->u.resolve.qtxt.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2801 request->u.resolve.qtxt.ExpectUnique = mDNStrue;
2802 request->u.resolve.qtxt.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2803 request->u.resolve.qtxt.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2804 request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
2805 request->u.resolve.qtxt.SearchListIndex = 0;
2806 request->u.resolve.qtxt.AppendSearchDomains = 0;
2807 request->u.resolve.qtxt.RetryWithSearchDomains = mDNSfalse;
2808 request->u.resolve.qtxt.TimeoutQuestion = 0;
2809 request->u.resolve.qtxt.WakeOnResolve = 0;
2810 request->u.resolve.qtxt.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2811 request->u.resolve.qtxt.ValidationRequired = 0;
2812 request->u.resolve.qtxt.ValidatingResponse = 0;
2813 request->u.resolve.qtxt.ProxyQuestion = 0;
2814 request->u.resolve.qtxt.qnameOrig = mDNSNULL;
2815 request->u.resolve.qtxt.AnonInfo = mDNSNULL;
2816 request->u.resolve.qtxt.pid = request->process_id;
2817 request->u.resolve.qtxt.euid = request->uid;
2818 request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
2819 request->u.resolve.qtxt.QuestionContext = request;
2821 request->u.resolve.ReportTime = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
2823 request->u.resolve.external_advertise = mDNSfalse;
2826 if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains)) return(mStatus_NoError);
2829 // ask the questions
2830 LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") START PID[%d](%s)", request->sd, flags, interfaceIndex,
2831 request->u.resolve.qsrv.qname.c, request->process_id, request->pid_name);
2833 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);
2837 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
2840 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2844 request->terminate = resolve_termination_callback;
2845 LogMcastQ(&request->u.resolve.qsrv, request, q_start);
2846 if (callExternalHelpers(InterfaceID, &fqdn, flags))
2848 request->u.resolve.external_advertise = mDNStrue;
2849 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2850 external_start_resolving_service(InterfaceID, &fqdn, flags);
2858 // ***************************************************************************
2859 #if COMPILER_LIKES_PRAGMA_MARK
2861 #pragma mark - DNSServiceQueryRecord
2864 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2865 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2866 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2867 // the mDNSCore operation if the client dies or closes its socket.
2869 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2870 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2871 // Returns 0 when there are no more search domains and the caller should reissue the query
2872 mDNSlocal int AppendNewSearchDomain(DNSQuestion *question)
2877 // Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2878 // the domains and should try the single label query directly on the wire.
2879 if (question->SearchListIndex == -1)
2881 LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question->qname.c, DNSTypeName(question->qtype));
2885 if (!question->AppendSearchDomains)
2887 LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question->qname.c, DNSTypeName(question->qtype));
2891 // Save the original name, before we modify them below.
2892 if (!question->qnameOrig)
2894 question->qnameOrig = mallocL("AppendNewSearchDomain", sizeof(domainname));
2895 if (!question->qnameOrig) { LogMsg("AppendNewSearchDomain: ERROR!! malloc failure"); return -1; }
2896 question->qnameOrig->c[0] = 0;
2897 AssignDomainName(question->qnameOrig, &question->qname);
2898 LogInfo("AppendSearchDomain: qnameOrig %##s", question->qnameOrig->c);
2901 sd = uDNS_GetNextSearchDomain(question->InterfaceID, &question->SearchListIndex, !question->AppendLocalSearchDomains);
2902 // We use -1 to indicate that we have searched all the domains and should try the single label
2903 // query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2904 if (question->SearchListIndex == -1)
2906 LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2910 // Not a common case. Perhaps, we should try the next search domain if it exceeds ?
2911 if (sd && (DomainNameLength(question->qnameOrig) + DomainNameLength(sd)) > MAX_DOMAIN_NAME)
2913 LogMsg("AppendNewSearchDomain: ERROR!! exceeding max domain length for %##s (%s) SearchDomain %##s length %d, Question name length %d", question->qnameOrig->c, DNSTypeName(question->qtype), sd->c, DomainNameLength(question->qnameOrig), DomainNameLength(sd));
2917 // if there are no more search domains and we have already tried this question
2918 // without appending search domains, then we are done.
2919 if (!sd && !ApplySearchDomainsFirst(question))
2921 LogInfo("AppendNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question->qname.c, DNSTypeName(question->qtype));
2925 // Stop the question before changing the name as negative cache entries could be pointing at this question.
2926 // Even if we don't change the question in the case of returning 0, the caller is going to restart the
2928 err = mDNS_StopQuery(&mDNSStorage, question);
2929 if (err) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question->qname.c, DNSTypeName(question->qtype), (int)err); }
2931 AssignDomainName(&question->qname, question->qnameOrig);
2934 AppendDomainName(&question->qname, sd);
2935 LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question->qname.c, question->SearchListIndex);
2939 // Try the question as single label
2940 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question->qname.c, DNSTypeName(question->qtype));
2944 #if APPLE_OSX_mDNSResponder
2946 mDNSlocal mDNSBool DomainInSearchList(const domainname *domain, mDNSBool excludeLocal)
2948 const SearchListElem *s;
2951 qcount = CountLabels(domain);
2952 for (s=SearchList; s; s=s->next)
2954 if (excludeLocal && SameDomainName(&s->domain, &localdomain))
2956 scount = CountLabels(&s->domain);
2957 if (qcount >= scount)
2959 // Note: When qcount == scount, we do a complete match of the domain
2960 // which is expected by the callers.
2961 const domainname *d = SkipLeadingLabels(domain, (qcount - scount));
2962 if (SameDomainName(&s->domain, d))
2971 // The caller already checks that this is a dotlocal question.
2972 mDNSlocal mDNSBool ShouldDeliverNegativeResponse(DNSQuestion *question)
2976 // If the question matches the search domain exactly or the search domain is a
2977 // subdomain of the question, it is most likely a valid unicast domain and hence
2978 // don't suppress negative responses.
2980 // If the user has configured ".local" as a search domain, we don't want
2981 // to deliver a negative response for names ending in ".local" as that would
2982 // prevent bonjour discovery. Passing mDNStrue for the last argument excludes
2983 // ".local" search domains.
2984 if (DomainInSearchList(&question->qname, mDNStrue))
2986 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) in SearchList", question->qname.c, DNSTypeName(question->qtype));
2990 // Deliver negative response for A/AAAA if there was a positive response for AAAA/A respectively.
2991 if (question->qtype != kDNSType_A && question->qtype != kDNSType_AAAA)
2993 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) not answering local question with negative unicast response",
2994 question->qname.c, DNSTypeName(question->qtype));
2997 qtype = (question->qtype == kDNSType_A ? kDNSType_AAAA : kDNSType_A);
2998 if (!mDNS_CheckForCacheRecord(&mDNSStorage, question, qtype))
3000 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) not answering local question with negative unicast response"
3001 " (can't find positive record)", question->qname.c, DNSTypeName(question->qtype));
3004 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) answering local with negative unicast response (found positive record)",
3005 question->qname.c, DNSTypeName(question->qtype));
3009 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
3011 mDNSlocal mStatus SendAdditionalQuery(DNSQuestion *q, request_state *request, mStatus err)
3013 #ifndef UNICAST_DISABLED
3014 extern domainname ActiveDirectoryPrimaryDomain;
3015 DNSQuestion **question2;
3016 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
3017 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
3019 question2 = mDNSNULL;
3020 if (request->hdr.op == query_request)
3021 question2 = &request->u.queryrecord.q2;
3022 else if (request->hdr.op == addrinfo_request)
3024 if (q->qtype == kDNSType_A)
3025 question2 = &request->u.addrinfo.q42;
3026 else if (q->qtype == kDNSType_AAAA)
3027 question2 = &request->u.addrinfo.q62;
3031 LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3032 return mStatus_BadParamErr;
3035 // Sanity check: If we already sent an additonal query, we don't need to send one more.
3037 // 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
3038 // is called to see whether a unicast query should be sent or not.
3040 // 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
3041 // was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
3042 // send the additional query.
3044 // Thus, it should not be called more than once.
3047 LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q->qname.c, DNSTypeName(q->qtype));
3051 if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
3052 if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q))
3055 int labels = CountLabels(&q->qname);
3056 q2 = mallocL("DNSQuestion", sizeof(DNSQuestion));
3057 if (!q2) FatalError("ERROR: SendAdditionalQuery malloc");
3060 q2->InterfaceID = mDNSInterface_Unicast;
3061 q2->ExpectUnique = mDNStrue;
3062 // Always set the QuestionContext to indicate that this question should be stopped
3063 // before freeing. Don't rely on "q".
3064 q2->QuestionContext = request;
3065 // If the query starts as a single label e.g., somehost, and we have search domains with .local,
3066 // queryrecord_result_callback calls this function when .local is appended to "somehost".
3067 // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
3068 // "somehost". We need to copy that information so that when we retry with a different search
3069 // domain e.g., mycompany.local, we get "somehost.mycompany.local".
3072 (*question2)->qnameOrig = mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
3073 if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!! malloc failure"); return mStatus_NoMemoryErr; }
3074 (*question2)->qnameOrig->c[0] = 0;
3075 AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
3076 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
3078 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
3079 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
3080 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
3081 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
3082 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
3083 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
3084 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
3085 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
3086 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
3087 // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
3088 // of those, we don't want do the SOA check for the local
3089 if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname, mDNSfalse))
3091 AssignDomainName(&q2->qname, &localdomain);
3092 q2->qtype = kDNSType_SOA;
3093 q2->LongLived = mDNSfalse;
3094 q2->ForceMCast = mDNSfalse;
3095 q2->ReturnIntermed = mDNStrue;
3096 // Don't append search domains for the .local SOA query
3097 q2->AppendSearchDomains = 0;
3098 q2->AppendLocalSearchDomains = 0;
3099 q2->RetryWithSearchDomains = mDNSfalse;
3100 q2->SearchListIndex = 0;
3101 q2->TimeoutQuestion = 0;
3102 q2->AnonInfo = mDNSNULL;
3103 q2->pid = request->process_id;
3104 q2->euid = request->uid;
3106 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
3107 err = mDNS_StartQuery(&mDNSStorage, q2);
3108 if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
3111 #else // !UNICAST_DISABLED
3116 return mStatus_NoError;
3117 #endif // !UNICAST_DISABLED
3119 #endif // APPLE_OSX_mDNSResponder
3121 // This function tries to append a search domain if valid and possible. If so, returns true.
3122 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(DNSQuestion *question, request_state *req, QC_result AddRecord)
3125 // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
3126 // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
3127 // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
3128 // RetryWithSearchDomains which may or may not be set.
3130 // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
3131 // is a valid question for appending search domains, retry by appending domains
3133 if ((AddRecord != QC_suppressed) && question->SearchListIndex != -1 && question->AppendSearchDomains)
3135 question->RetryWithSearchDomains = 0;
3136 result = AppendNewSearchDomain(question);
3137 // As long as the result is either zero or 1, we retry the question. If we exahaust the search
3138 // domains (result is zero) we try the original query (as it was before appending the search
3139 // domains) as such on the wire as a last resort if we have not tried them before. For queries
3140 // with more than one label, we have already tried them before appending search domains and
3141 // hence don't retry again
3145 err = mDNS_StartQuery(&mDNSStorage, question);
3148 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
3149 // If the result was zero, it meant that there are no search domains and we just retried the question
3150 // as a single label and we should not retry with search domains anymore.
3151 if (!result) question->SearchListIndex = -1;
3156 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3157 // We have already stopped the query and could not restart. Reset the appropriate pointers
3158 // so that we don't call stop again when the question terminates
3159 question->QuestionContext = mDNSNULL;
3165 LogInfo("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, AddRecord, question->SearchListIndex, question->AppendSearchDomains);
3170 mDNSlocal void queryrecord_result_reply(mDNS *const m, request_state *req, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord,
3171 DNSServiceErrorType error)
3173 char name[MAX_ESCAPED_DOMAIN_NAME];
3175 DNSServiceFlags flags = 0;
3179 ConvertDomainNameToCString(answer->name, name);
3181 LogOperation("%3d: %s(%##s, %s) RESULT %s interface %d: %s", req->sd,
3182 req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
3183 question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV",
3184 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
3186 len = sizeof(DNSServiceFlags); // calculate reply data length
3187 len += sizeof(mDNSu32); // interface index
3188 len += sizeof(DNSServiceErrorType);
3189 len += strlen(name) + 1;
3190 len += 3 * sizeof(mDNSu16); // type, class, rdlen
3191 len += answer->rdlength;
3192 len += sizeof(mDNSu32); // TTL
3194 rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
3197 flags |= kDNSServiceFlagsAdd;
3198 if (question->ValidationStatus != 0)
3200 error = kDNSServiceErr_NoError;
3201 if (question->ValidationRequired && question->ValidationState == DNSSECValDone)
3203 switch (question->ValidationStatus) //Set the dnssec flags to be passed on to the Apps here
3206 flags |= kDNSServiceFlagsSecure;
3208 case DNSSEC_Insecure:
3209 flags |= kDNSServiceFlagsInsecure;
3211 case DNSSEC_Indeterminate:
3212 flags |= kDNSServiceFlagsIndeterminate;
3215 flags |= kDNSServiceFlagsBogus;
3218 LogMsg("queryrecord_result_reply unknown status %d for %##s", question->ValidationStatus, question->qname.c);
3223 rep->rhdr->flags = dnssd_htonl(flags);
3224 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
3225 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
3226 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
3227 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
3228 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
3229 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
3230 // should not have existed to answer this question if the corresponding interface is not valid.
3231 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
3232 rep->rhdr->error = dnssd_htonl(error);
3234 data = (char *)&rep->rhdr[1];
3236 put_string(name, &data);
3237 put_uint16(answer->rrtype, &data);
3238 put_uint16(answer->rrclass, &data);
3239 put_uint16(answer->rdlength, &data);
3240 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
3241 // function just does a blind memory copy without regard to structures that may have holes in them.
3242 if (answer->rdlength)
3243 if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
3244 LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
3245 data += answer->rdlength;
3246 put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
3248 append_reply(req, rep);
3249 // Stop the question, if we just timed out
3250 if (error == kDNSServiceErr_Timeout)
3252 mDNS_StopQuery(m, question);
3253 // Reset the pointers so that we don't call stop on termination
3254 question->QuestionContext = mDNSNULL;
3256 else if ((AddRecord == QC_add) && req->hdr.op == addrinfo_request)
3258 // Note: We count all answers including LocalOnly e.g., /etc/hosts. If we
3259 // exclude that, v4ans/v6ans will be zero and we would wrongly think that
3260 // we did not answer questions and setup the status to deliver triggers.
3261 if (question->qtype == kDNSType_A)
3262 req->u.addrinfo.v4ans = 1;
3263 if (question->qtype == kDNSType_AAAA)
3264 req->u.addrinfo.v6ans = 1;
3266 else if ((AddRecord == QC_add) && req->hdr.op == query_request)
3268 if (question->qtype == kDNSType_A || question->qtype == kDNSType_AAAA)
3269 req->u.queryrecord.ans = 1;
3272 #if APPLE_OSX_mDNSResponder
3274 CHECK_WCF_FUNCTION(WCFIsServerRunning)
3277 socklen_t xucredlen = sizeof(x);
3279 if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
3281 if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
3282 (x.cr_version == XUCRED_VERSION))
3284 struct sockaddr_storage addr;
3286 if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
3288 if (answer->rrtype == kDNSType_A)
3290 struct sockaddr_in *const sin = (struct sockaddr_in *)&addr;
3292 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3293 // sin->sin_addr.s_addr = answer->rdata->u.ipv4.NotAnInteger;
3294 if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(mDNSv4Addr)), answer))
3295 LogMsg("queryrecord_result_reply: WCF AF_INET putRData failed");
3298 addr.ss_len = sizeof (struct sockaddr_in);
3299 addr.ss_family = AF_INET;
3302 else if (answer->rrtype == kDNSType_AAAA)
3304 struct sockaddr_in6 *const sin6 = (struct sockaddr_in6 *)&addr;
3305 sin6->sin6_port = 0;
3306 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3307 // sin6->sin6_addr.__u6_addr.__u6_addr32[0] = answer->rdata->u.ipv6.l[0];
3308 // sin6->sin6_addr.__u6_addr.__u6_addr32[1] = answer->rdata->u.ipv6.l[1];
3309 // sin6->sin6_addr.__u6_addr.__u6_addr32[2] = answer->rdata->u.ipv6.l[2];
3310 // sin6->sin6_addr.__u6_addr.__u6_addr32[3] = answer->rdata->u.ipv6.l[3];
3311 if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(mDNSv6Addr)), answer))
3312 LogMsg("queryrecord_result_reply: WCF AF_INET6 putRData failed");
3315 addr.ss_len = sizeof (struct sockaddr_in6);
3316 addr.ss_family = AF_INET6;
3321 debugf("queryrecord_result_reply: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
3322 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3324 WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
3328 else if (answer->rrtype == kDNSType_CNAME)
3331 char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
3332 if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
3333 LogMsg("queryrecord_result_reply: WCF CNAME putRData failed");
3336 ConvertDomainNameToCString(&cname, cname_cstr);
3337 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3339 WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
3344 else my_perror("queryrecord_result_reply: ERROR: getsockopt LOCAL_PEERCRED");
3351 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
3353 request_state *req = question->QuestionContext;
3354 DNSServiceErrorType error = kDNSServiceErr_NoError;
3355 DNSQuestion *q = mDNSNULL;
3357 #if APPLE_OSX_mDNSResponder
3359 // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
3360 // get any callbacks from the core after this.
3363 LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3366 if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
3367 q = &req->u.queryrecord.q;
3368 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
3369 q = &req->u.addrinfo.q4;
3370 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
3371 q = &req->u.addrinfo.q6;
3373 if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
3376 domainname *orig = question->qnameOrig;
3378 LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
3379 mDNS_StopQuery(m, question);
3380 question->QuestionContext = mDNSNULL;
3382 // We got a negative response for the SOA record indicating that .local does not exist.
3383 // But we might have other search domains (that does not end in .local) that can be
3384 // appended to this question. In that case, we want to retry the question. Otherwise,
3385 // we don't want to try this question as unicast.
3386 if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
3388 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
3392 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
3394 // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
3395 // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
3396 // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
3397 // SendAdditionalQuery as to how qnameOrig gets initialized.
3399 question->InterfaceID = mDNSInterface_Unicast;
3400 question->ExpectUnique = mDNStrue;
3401 question->qnameOrig = orig;
3403 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
3405 // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
3406 // Hence, we need to set it explicitly here.
3407 question->QuestionContext = req;
3408 err = mDNS_StartQuery(m, question);
3409 if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3411 // If we got a positive response to local SOA, then try the .local question as unicast
3412 if (answer->RecordType != kDNSRecordTypePacketNegative) return;
3414 // Fall through and get the next search domain. The question is pointing at .local
3415 // and we don't want to try that. Try the next search domain. Don't try with local
3416 // search domains for the unicast question anymore.
3418 // Note: we started the question above which will be stopped immediately (never sent on the wire)
3419 // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
3420 // question has already started.
3421 question->AppendLocalSearchDomains = 0;
3424 if (q && AddRecord && AddRecord != QC_dnssec && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
3426 // If we get a negative response to the unicast query that we sent above, retry after appending search domains
3427 // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
3428 // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
3429 // To keep things simple, we handle unicast ".local" separately here.
3430 LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3431 if (RetryQuestionWithSearchDomains(question, req, AddRecord))
3433 if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
3435 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
3436 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
3437 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
3438 // in the list. We leave it disabled so that it does not hit the wire.
3439 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3440 question->ThisQInterval = 0;
3443 // If we are here it means that either "question" is not "q2" OR we got a positive response for "q2" OR we have no more search
3444 // domains to append for "q2". In all cases, fall through and deliver the response
3446 #endif // APPLE_OSX_mDNSResponder
3448 // If a query is being suppressed for some reason, we don't have to do any other
3451 // Note: We don't check for "SuppressQuery" and instead use QC_suppressed because
3452 // the "core" needs to temporarily turn off SuppressQuery to answer this query.
3453 if (AddRecord == QC_suppressed)
3455 LogInfo("queryrecord_result_callback: Suppressed question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3456 queryrecord_result_reply(m, req, question, answer, AddRecord, kDNSServiceErr_NoSuchRecord);
3460 if (answer->RecordType == kDNSRecordTypePacketNegative)
3462 // If this question needs to be timed out and we have reached the stop time, mark
3463 // the error as timeout. It is possible that we might get a negative response from an
3464 // external DNS server at the same time when this question reaches its stop time. We
3465 // can't tell the difference as there is no indication in the callback. This should
3466 // be okay as we will be timing out this query anyway.
3468 if (question->TimeoutQuestion)
3470 if ((m->timenow - question->StopTime) >= 0)
3472 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3473 error = kDNSServiceErr_Timeout;
3477 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
3478 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
3479 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
3480 // server is going to assert that pretty much every single multicast name doesn't exist.
3482 // If we are timing out this query, we need to deliver the negative answer to the application
3483 if (error != kDNSServiceErr_Timeout)
3485 if (!answer->InterfaceID && IsLocalDomain(answer->name))
3487 // Sanity check: "q" will be set only if "question" is the .local unicast query.
3490 LogMsg("queryrecord_result_callback: ERROR!! answering multicast question %s with unicast cache record",
3491 RRDisplayString(m, answer));
3494 #if APPLE_OSX_mDNSResponder
3495 if (!ShouldDeliverNegativeResponse(question))
3499 #endif // APPLE_OSX_mDNSResponder
3500 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with negative unicast response", question->qname.c,
3501 DNSTypeName(question->qtype));
3503 error = kDNSServiceErr_NoSuchRecord;
3506 // If we get a negative answer, try appending search domains. Don't append search domains
3507 // - if we are timing out this question
3508 // - if the negative response was received as a result of a multicast query
3509 // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
3510 // - if this response is forced e.g., dnssec validation result
3511 if (error != kDNSServiceErr_Timeout)
3513 if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord && AddRecord != QC_dnssec)
3515 // If the original question did not end in .local, we did not send an SOA query
3516 // to figure out whether we should send an additional unicast query or not. If we just
3517 // appended .local, we need to see if we need to send an additional query. This should
3518 // normally happen just once because after we append .local, we ignore all negative
3519 // responses for .local above.
3520 LogInfo("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3521 if (RetryQuestionWithSearchDomains(question, req, AddRecord))
3523 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
3524 // be anywhere in the search domain list.
3525 #if APPLE_OSX_mDNSResponder
3526 mStatus err = mStatus_NoError;
3527 err = SendAdditionalQuery(question, req, err);
3528 if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
3529 #endif // APPLE_OSX_mDNSResponder
3534 queryrecord_result_reply(m, req, question, answer, AddRecord, error);
3537 mDNSlocal void queryrecord_termination_callback(request_state *request)
3539 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) STOP PID[%d](%s)",
3540 request->sd, request->flags, request->interfaceIndex, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype), request->process_id, request->pid_name);
3541 if (request->u.queryrecord.q.QuestionContext)
3543 mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q); // no need to error check
3544 LogMcastQ(&request->u.queryrecord.q, request, q_stop);
3545 request->u.queryrecord.q.QuestionContext = mDNSNULL;
3549 DNSQuestion *question = &request->u.queryrecord.q;
3550 LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3553 if (request->u.queryrecord.q.qnameOrig)
3555 freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
3556 request->u.queryrecord.q.qnameOrig = mDNSNULL;
3559 if (callExternalHelpers(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->u.queryrecord.q.flags))
3561 LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
3562 external_stop_browsing_for_service(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->u.queryrecord.q.qtype, request->u.queryrecord.q.flags);
3564 if (request->u.queryrecord.q2)
3566 if (request->u.queryrecord.q2->QuestionContext)
3568 LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
3569 mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
3570 LogMcastQ(request->u.queryrecord.q2, request, q_stop);
3574 DNSQuestion *question = request->u.queryrecord.q2;
3575 LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3577 if (request->u.queryrecord.q2->qnameOrig)
3579 LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
3580 freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
3581 request->u.queryrecord.q2->qnameOrig = mDNSNULL;
3583 freeL("queryrecord Q2", request->u.queryrecord.q2);
3584 request->u.queryrecord.q2 = mDNSNULL;
3586 #if APPLE_OSX_mDNSResponder
3588 if (request->u.queryrecord.ans)
3590 DNSQuestion *v4q, *v6q;
3591 // If we are receiving poisitive answers, provide the hint to the
3593 v4q = v6q = mDNSNULL;
3594 if (request->u.queryrecord.q.qtype == kDNSType_A)
3595 v4q = &request->u.queryrecord.q;
3596 else if (request->u.queryrecord.q.qtype == kDNSType_AAAA)
3597 v6q = &request->u.queryrecord.q;
3598 mDNSPlatformTriggerDNSRetry(v4q, v6q);
3601 #endif // APPLE_OSX_mDNSResponder
3604 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
3606 DNSQuestion *const q = &request->u.queryrecord.q;
3609 mDNSu16 rrtype, rrclass;
3612 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3613 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3614 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3616 // The request is scoped to a specific interface index, but the
3617 // interface is not currently in our list.
3618 if (interfaceIndex && !InterfaceID)
3620 if (interfaceIndex > 1)
3621 LogMsg("handle_queryrecord_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
3622 interfaceIndex, request->process_id, request->pid_name);
3623 // If it's one of the specially defined inteface index values, just return an error.
3624 // Also, caller should return an error immediately if lo0 (index 1) is not configured
3625 // into the current active interfaces. See background in Radar 21967160.
3626 if (PreDefinedInterfaceIndex(interfaceIndex) || interfaceIndex == 1)
3628 LogInfo("handle_queryrecord_request: bad interfaceIndex %d", interfaceIndex);
3629 return(mStatus_BadParamErr);
3632 // Otherwise, use the specified interface index value and the request will
3633 // be applied to that interface when it comes up.
3634 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
3635 LogInfo("handle_queryrecord_request: query pending for interface index %d", interfaceIndex);
3638 if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
3639 rrtype = get_uint16(&request->msgptr, request->msgend);
3640 rrclass = get_uint16(&request->msgptr, request->msgend);
3642 if (!request->msgptr)
3643 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3645 request->flags = flags;
3646 request->interfaceIndex = interfaceIndex;
3647 mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
3649 q->InterfaceID = InterfaceID;
3651 q->Target = zeroAddr;
3652 if (!MakeDomainNameFromDNSNameString(&q->qname, name)) return(mStatus_BadParamErr);
3654 if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains)) return (mStatus_NoError);
3657 q->qclass = rrclass;
3658 q->LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
3659 q->ExpectUnique = mDNSfalse;
3660 q->ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
3661 q->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3662 q->SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
3663 q->TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
3664 q->WakeOnResolve = 0;
3665 q->UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
3666 if ((flags & kDNSServiceFlagsValidate) != 0)
3667 q->ValidationRequired = DNSSEC_VALIDATION_SECURE;
3668 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
3669 q->ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
3670 q->ValidatingResponse = 0;
3671 q->ProxyQuestion = 0;
3672 q->AnonInfo = mDNSNULL;
3673 q->QuestionCallback = queryrecord_result_callback;
3674 q->QuestionContext = request;
3675 q->SearchListIndex = 0;
3678 q->DNSSECAuthInfo = mDNSNULL;
3679 q->DAIFreeCallback = mDNSNULL;
3681 //Turn off dnssec validation for local domains and Question Types: RRSIG/ANY(ANY Type is not supported yet)
3682 if ((IsLocalDomain(&q->qname)) || (q->qtype == kDNSServiceType_RRSIG) || (q->qtype == kDNSServiceType_ANY))
3683 q->ValidationRequired = 0;
3685 // Don't append search domains for fully qualified domain names including queries
3686 // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3687 // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3688 // append search domains or not. So, we record that information in AppendSearchDomains.
3690 // We append search domains only for queries that are a single label. If overriden using command line
3691 // argument "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
3692 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
3694 nameLen = strlen(name);
3695 if ((!(q->ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(q->ValidationRequired == DNSSEC_VALIDATION_INSECURE))
3696 && (rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && ((nameLen == 0) || (name[nameLen - 1] != '.')) &&
3697 (AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3699 q->AppendSearchDomains = 1;
3700 q->AppendLocalSearchDomains = 1;
3704 q->AppendSearchDomains = 0;
3705 q->AppendLocalSearchDomains = 0;
3708 // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3709 // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3710 // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3712 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3713 q->qnameOrig = mDNSNULL;
3714 SetQuestionPolicy(q, request);
3716 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3717 // Determine if this request should be promoted to use BLE triggered discovery.
3718 if (shouldUseBLE(InterfaceID, rrtype, (domainname *)SkipLeadingLabels(&q->qname, 1), &q->qname))
3720 q->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
3721 request->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
3722 LogInfo("handle_queryrecord_request: request promoted to use kDNSServiceFlagsAutoTrigger");
3724 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3726 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START PID[%d](%s)",
3727 request->sd, request->flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype), request->process_id, request->pid_name);
3728 err = mDNS_StartQuery(&mDNSStorage, q);
3732 LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3736 request->terminate = queryrecord_termination_callback;
3737 LogMcastQ(q, request, q_start);
3738 if (callExternalHelpers(q->InterfaceID, &q->qname, q->flags))
3740 LogInfo("handle_queryrecord_request: calling external_start_browsing_for_service()");
3741 external_start_browsing_for_service(q->InterfaceID, &q->qname, q->qtype, q->flags);
3745 #if APPLE_OSX_mDNSResponder
3746 err = SendAdditionalQuery(q, request, err);
3747 #endif // APPLE_OSX_mDNSResponder
3752 // ***************************************************************************
3753 #if COMPILER_LIKES_PRAGMA_MARK
3755 #pragma mark - DNSServiceEnumerateDomains
3758 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3759 const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3765 len = sizeof(DNSServiceFlags);
3766 len += sizeof(mDNSu32);
3767 len += sizeof(DNSServiceErrorType);
3768 len += strlen(domain) + 1;
3770 reply = create_reply(enumeration_reply_op, len, request);
3771 reply->rhdr->flags = dnssd_htonl(flags);
3772 reply->rhdr->ifi = dnssd_htonl(ifi);
3773 reply->rhdr->error = dnssd_htonl(err);
3774 data = (char *)&reply->rhdr[1];
3775 put_string(domain, &data);
3779 mDNSlocal void enum_termination_callback(request_state *request)
3781 // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3782 if (request->u.enumeration.flags & kDNSServiceFlagsRegistrationDomains)
3784 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3785 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3789 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3790 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
3791 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_autoall);
3793 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3794 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3797 mDNSlocal void enum_result_callback(mDNS *const m,
3798 DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3800 char domain[MAX_ESCAPED_DOMAIN_NAME];
3801 request_state *request = question->QuestionContext;
3802 DNSServiceFlags flags = 0;
3806 if (answer->rrtype != kDNSType_PTR) return;
3809 if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3812 // We only return add/remove events for the browse and registration lists
3813 // For the default browse and registration answers, we only give an "ADD" event
3814 if (question == &request->u.enumeration.q_default && !AddRecord) return;
3818 flags |= kDNSServiceFlagsAdd;
3819 if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3822 ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3823 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3824 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3825 // network, so we just pass kDNSServiceInterfaceIndexAny
3826 reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3827 if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3829 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "ADD" : "RMV", domain);
3831 append_reply(request, reply);
3834 mDNSlocal mStatus handle_enum_request(request_state *request)
3837 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3838 DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3839 mDNS_DomainType t_all = reg ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse;
3840 mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3841 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3842 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3843 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3845 if (!request->msgptr)
3846 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3848 request->flags = flags;
3849 request->interfaceIndex = interfaceIndex;
3851 // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
3852 request->u.enumeration.flags = reg;
3854 // enumeration requires multiple questions, so we must link all the context pointers so that
3855 // necessary context can be reached from the callbacks
3856 request->u.enumeration.q_all.QuestionContext = request;
3857 request->u.enumeration.q_default.QuestionContext = request;
3858 if (!reg) request->u.enumeration.q_autoall.QuestionContext = request;
3860 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3861 if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
3864 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
3865 (flags & kDNSServiceFlagsBrowseDomains ) ? "kDNSServiceFlagsBrowseDomains" :
3866 (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3867 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
3870 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
3871 if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3874 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_autoall, mDNS_DomainTypeBrowseAutomatic, NULL, InterfaceID, enum_result_callback, request);
3877 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3878 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3881 if (!err) request->terminate = enum_termination_callback;
3885 // Start the domain enumeration queries to discover the WAB Browse/Registration domains
3888 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3889 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3893 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3894 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
3901 // ***************************************************************************
3902 #if COMPILER_LIKES_PRAGMA_MARK
3904 #pragma mark - DNSServiceReconfirmRecord & Misc
3907 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
3909 mStatus status = mStatus_BadParamErr;
3910 AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
3913 status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
3915 (status == mStatus_NoError) ?
3916 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated PID[%d](%s)" :
3917 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed PID[%d](%s) status %d",
3918 request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
3919 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse),
3920 request->process_id, request->pid_name, status);
3921 freeL("AuthRecord/handle_reconfirm_request", rr);
3926 #if APPLE_OSX_mDNSResponder
3928 mDNSlocal mStatus handle_release_request(request_state *request)
3931 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
3932 domainname instance;
3934 // extract the data from the message
3935 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3937 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
3938 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3939 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
3941 LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
3942 return(mStatus_BadParamErr);
3945 if (!request->msgptr)
3947 LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request->sd);
3948 return(mStatus_BadParamErr);
3951 if (build_domainname_from_strings(&instance, name, regtype, domain) < 0)
3953 LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name, regtype, domain);
3954 return(mStatus_BadParamErr);
3957 LogOperation("%3d: PeerConnectionRelease(%X %##s) START PID[%d](%s)",
3958 request->sd, flags, instance.c, request->process_id, request->pid_name);
3960 external_connection_release(&instance);
3964 #else // APPLE_OSX_mDNSResponder
3966 mDNSlocal mStatus handle_release_request(request_state *request)
3969 return mStatus_UnsupportedErr;
3972 #endif // APPLE_OSX_mDNSResponder
3974 mDNSlocal mStatus handle_setdomain_request(request_state *request)
3976 char domainstr[MAX_ESCAPED_DOMAIN_NAME];
3978 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3979 (void)flags; // Unused
3980 if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3981 !MakeDomainNameFromDNSNameString(&domain, domainstr))
3982 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3984 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
3985 return(mStatus_NoError);
3988 typedef packedstruct
3993 } DaemonVersionReply;
3995 mDNSlocal void handle_getproperty_request(request_state *request)
3997 const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
3999 if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
4001 LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
4002 if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
4004 DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
4005 send_all(request->sd, (const char *)&x, sizeof(x));
4010 // If we didn't recogize the requested property name, return BadParamErr
4011 send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
4014 #ifdef APPLE_OSX_mDNSResponder
4015 // The caller can specify either the pid or the uuid. If the pid is not specified,
4016 // update the effective uuid. Don't overwrite the pid which is used for debugging
4017 // purposes and initialized when the socket is opened.
4018 mDNSlocal void handle_connection_delegate_request(request_state *request)
4023 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4024 request->sd, request->process_id, request->pid_name);
4025 request->terminate = connection_termination;
4028 pid = get_uint32(&request->msgptr, request->msgend);
4029 #ifdef LOCAL_PEEREPID
4033 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &request->process_id, &len) != 0)
4035 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno, strerror(errno));
4038 // to extract the process name from the pid value
4039 if (proc_pidinfo(request->process_id, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
4041 mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
4042 debugf("handle_connection_delegate_request: process id %d, name %s", request->process_id, request->pid_name);
4045 #ifdef LOCAL_PEEREUUID
4049 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREUUID, request->uuid, &len) != 0)
4051 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno, strerror(errno));
4054 request->validUUID = mDNStrue;
4059 mDNSlocal void handle_connection_delegate_request(request_state *request)
4065 typedef packedstruct
4071 mDNSlocal void handle_getpid_request(request_state *request)
4073 const request_state *req;
4075 mDNSu16 srcport = get_uint16(&request->msgptr, request->msgend);
4076 const DNSQuestion *q = NULL;
4079 LogMsg("%3d: DNSServiceGetPID START", request->sd);
4081 for (req = all_requests; req; req=req->next)
4083 if (req->hdr.op == query_request)
4084 q = &req->u.queryrecord.q;
4085 else if (req->hdr.op == addrinfo_request)
4086 q = &req->u.addrinfo.q4;
4087 else if (req->hdr.op == addrinfo_request)
4088 q = &req->u.addrinfo.q6;
4090 if (q && q->LocalSocket != NULL)
4092 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4093 if (port == srcport)
4095 pid = req->process_id;
4096 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s] question %##s", htons(srcport), pid, req->pid_name, q->qname.c);
4101 // If we cannot find in the client requests, look to see if this was
4102 // started by mDNSResponder.
4105 for (q = mDNSStorage.Questions; q; q = q->next)
4107 if (q && q->LocalSocket != NULL)
4109 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4110 if (port == srcport)
4112 #if APPLE_OSX_mDNSResponder
4114 #endif // APPLE_OSX_mDNSResponder
4115 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s], question %##s", htons(srcport), pid, "_mDNSResponder", q->qname.c);
4124 send_all(request->sd, (const char *)&pi, sizeof(PIDInfo));
4125 LogMsg("%3d: DNSServiceGetPID STOP", request->sd);
4128 // ***************************************************************************
4129 #if COMPILER_LIKES_PRAGMA_MARK
4131 #pragma mark - DNSServiceNATPortMappingCreate
4134 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
4136 mDNSlocal void port_mapping_termination_callback(request_state *request)
4138 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](%s)", request->sd,
4139 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4140 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4141 request->process_id, request->pid_name);
4142 mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4145 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
4146 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
4148 request_state *request = (request_state *)n->clientContext;
4153 if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
4155 // calculate reply data length
4156 replyLen = sizeof(DNSServiceFlags);
4157 replyLen += 3 * sizeof(mDNSu32); // if index + addr + ttl
4158 replyLen += sizeof(DNSServiceErrorType);
4159 replyLen += 2 * sizeof(mDNSu16); // Internal Port + External Port
4160 replyLen += sizeof(mDNSu8); // protocol
4162 rep = create_reply(port_mapping_reply_op, replyLen, request);
4164 rep->rhdr->flags = dnssd_htonl(0);
4165 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
4166 rep->rhdr->error = dnssd_htonl(n->Result);
4168 data = (char *)&rep->rhdr[1];
4170 *data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
4171 *data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
4172 *data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
4173 *data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
4174 *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
4175 *data++ = request->u.pm.NATinfo.IntPort.b[0];
4176 *data++ = request->u.pm.NATinfo.IntPort.b[1];
4177 *data++ = request->u.pm.NATinfo.ExternalPort.b[0];
4178 *data++ = request->u.pm.NATinfo.ExternalPort.b[1];
4179 put_uint32(request->u.pm.NATinfo.Lifetime, &data);
4181 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
4182 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4183 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4184 &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
4186 append_reply(request, rep);
4189 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
4192 mStatus err = mStatus_NoError;
4194 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4195 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4196 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4197 mDNSu8 protocol = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
4198 (void)flags; // Unused
4199 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
4200 if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
4203 request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
4204 request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
4205 request->u.pm.ReqExt.b[0] = *request->msgptr++;
4206 request->u.pm.ReqExt.b[1] = *request->msgptr++;
4207 ttl = get_uint32(&request->msgptr, request->msgend);
4210 if (!request->msgptr)
4211 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4213 if (protocol == 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
4215 if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
4219 if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
4220 if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
4223 request->flags = flags;
4224 request->interfaceIndex = interfaceIndex;
4225 request->u.pm.NATinfo.Protocol = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
4226 // u.pm.NATinfo.IntPort = already set above
4227 request->u.pm.NATinfo.RequestedPort = request->u.pm.ReqExt;
4228 request->u.pm.NATinfo.NATLease = ttl;
4229 request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
4230 request->u.pm.NATinfo.clientContext = request;
4232 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](%s)", request->sd,
4233 protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4234 request->process_id, request->pid_name);
4235 err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4236 if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
4237 else request->terminate = port_mapping_termination_callback;
4242 // ***************************************************************************
4243 #if COMPILER_LIKES_PRAGMA_MARK
4245 #pragma mark - DNSServiceGetAddrInfo
4248 mDNSlocal void addrinfo_termination_callback(request_state *request)
4250 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP PID[%d](%s)", request->sd, request->u.addrinfo.q4.qname.c,
4251 request->process_id, request->pid_name);
4253 if (request->u.addrinfo.q4.QuestionContext)
4255 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
4256 LogMcastQ(&request->u.addrinfo.q4, request, q_stop);
4257 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4259 if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, request->flags))
4261 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for kDNSServiceType_A record");
4262 external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, kDNSServiceType_A, request->flags);
4265 if (request->u.addrinfo.q4.qnameOrig)
4267 freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
4268 request->u.addrinfo.q4.qnameOrig = mDNSNULL;
4270 if (request->u.addrinfo.q42)
4272 if (request->u.addrinfo.q42->QuestionContext)
4274 LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
4275 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
4276 LogMcastQ(request->u.addrinfo.q42, request, q_stop);
4278 if (request->u.addrinfo.q42->qnameOrig)
4280 LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
4281 freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
4282 request->u.addrinfo.q42->qnameOrig = mDNSNULL;
4284 freeL("addrinfo Q42", request->u.addrinfo.q42);
4285 request->u.addrinfo.q42 = mDNSNULL;
4288 if (request->u.addrinfo.q6.QuestionContext)
4290 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4291 LogMcastQ(&request->u.addrinfo.q6, request, q_stop);
4292 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4294 if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, request->flags))
4296 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for kDNSServiceType_AAAA record");
4297 external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, kDNSServiceType_AAAA, request->flags);
4300 if (request->u.addrinfo.q6.qnameOrig)
4302 freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
4303 request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4305 if (request->u.addrinfo.q62)
4307 if (request->u.addrinfo.q62->QuestionContext)
4309 LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
4310 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
4311 LogMcastQ(request->u.addrinfo.q62, request, q_stop);
4313 if (request->u.addrinfo.q62->qnameOrig)
4315 LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
4316 freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
4317 request->u.addrinfo.q62->qnameOrig = mDNSNULL;
4319 freeL("addrinfo Q62", request->u.addrinfo.q62);
4320 request->u.addrinfo.q62 = mDNSNULL;
4322 #if APPLE_OSX_mDNSResponder
4324 DNSQuestion *v4q, *v6q;
4325 v4q = v6q = mDNSNULL;
4326 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
4328 // If we are not delivering answers, we may be timing out prematurely.
4329 // Note down the current state so that we know to retry when we see a
4330 // valid response again.
4331 if (request->u.addrinfo.q4.TimeoutQuestion && !request->u.addrinfo.v4ans)
4333 mDNSPlatformUpdateDNSStatus(&request->u.addrinfo.q4);
4335 // If we have a v4 answer and if we timed out prematurely before, provide
4336 // a trigger to the upper layer so that it can retry questions if needed.
4337 if (request->u.addrinfo.v4ans)
4338 v4q = &request->u.addrinfo.q4;
4340 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4342 if (request->u.addrinfo.q6.TimeoutQuestion && !request->u.addrinfo.v6ans)
4344 mDNSPlatformUpdateDNSStatus(&request->u.addrinfo.q6);
4346 if (request->u.addrinfo.v6ans)
4347 v6q = &request->u.addrinfo.q6;
4349 mDNSPlatformTriggerDNSRetry(v4q, v6q);
4351 #endif // APPLE_OSX_mDNSResponder
4354 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
4360 mDNSs32 serviceIndex = -1; // default unscoped value for ServiceID is -1
4361 mDNSInterfaceID InterfaceID;
4363 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4365 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4367 if (flags & kDNSServiceFlagsServiceIndex)
4369 // NOTE: kDNSServiceFlagsServiceIndex flag can only be set for DNSServiceGetAddrInfo()
4370 LogInfo("DNSServiceGetAddrInfo: kDNSServiceFlagsServiceIndex is SET by the client");
4371 // if kDNSServiceFlagsServiceIndex is SET,
4372 // interpret the interfaceID as the serviceId and set the interfaceID to 0.
4373 serviceIndex = interfaceIndex;
4377 mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
4379 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4381 // The request is scoped to a specific interface index, but the
4382 // interface is not currently in our list.
4383 if (interfaceIndex && !InterfaceID)
4385 if (interfaceIndex > 1)
4386 LogMsg("handle_addrinfo_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
4387 interfaceIndex, request->process_id, request->pid_name);
4388 // If it's one of the specially defined inteface index values, just return an error.
4389 if (PreDefinedInterfaceIndex(interfaceIndex))
4391 LogInfo("handle_addrinfo_request: bad interfaceIndex %d", interfaceIndex);
4392 return(mStatus_BadParamErr);
4395 // Otherwise, use the specified interface index value and the request will
4396 // be applied to that interface when it comes up.
4397 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
4398 LogInfo("handle_addrinfo_request: query pending for interface index %d", interfaceIndex);
4401 request->flags = flags;
4402 request->interfaceIndex = interfaceIndex;
4403 request->u.addrinfo.interface_id = InterfaceID;
4404 request->u.addrinfo.flags = flags;
4405 request->u.addrinfo.protocol = get_uint32(&request->msgptr, request->msgend);
4407 if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
4409 if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
4411 if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4413 if (!MakeDomainNameFromDNSNameString(&d, hostname))
4414 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
4417 if (!AuthorizedDomain(request, &d, AutoBrowseDomains)) return (mStatus_NoError);
4420 if (!request->u.addrinfo.protocol)
4422 flags |= kDNSServiceFlagsSuppressUnusable;
4423 request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
4426 request->u.addrinfo.q4.InterfaceID = request->u.addrinfo.q6.InterfaceID = request->u.addrinfo.interface_id;
4427 request->u.addrinfo.q4.ServiceID = request->u.addrinfo.q6.ServiceID = serviceIndex;
4428 request->u.addrinfo.q4.flags = request->u.addrinfo.q6.flags = flags;
4429 request->u.addrinfo.q4.Target = request->u.addrinfo.q6.Target = zeroAddr;
4430 request->u.addrinfo.q4.qname = request->u.addrinfo.q6.qname = d;
4431 request->u.addrinfo.q4.qclass = request->u.addrinfo.q6.qclass = kDNSServiceClass_IN;
4432 request->u.addrinfo.q4.LongLived = request->u.addrinfo.q6.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
4433 request->u.addrinfo.q4.ExpectUnique = request->u.addrinfo.q6.ExpectUnique = mDNSfalse;
4434 request->u.addrinfo.q4.ForceMCast = request->u.addrinfo.q6.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
4435 request->u.addrinfo.q4.ReturnIntermed = request->u.addrinfo.q6.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
4436 request->u.addrinfo.q4.SuppressUnusable = request->u.addrinfo.q6.SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
4437 request->u.addrinfo.q4.TimeoutQuestion = request->u.addrinfo.q6.TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
4438 request->u.addrinfo.q4.WakeOnResolve = request->u.addrinfo.q6.WakeOnResolve = 0;
4439 request->u.addrinfo.q4.UseBackgroundTrafficClass = request->u.addrinfo.q6.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
4440 if ((flags & kDNSServiceFlagsValidate) != 0)
4441 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE;
4442 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
4443 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
4444 request->u.addrinfo.q4.ValidatingResponse = request->u.addrinfo.q6.ValidatingResponse = 0;
4445 request->u.addrinfo.q4.ProxyQuestion = request->u.addrinfo.q6.ProxyQuestion = 0;
4446 request->u.addrinfo.q4.qnameOrig = request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4447 request->u.addrinfo.q4.AnonInfo = request->u.addrinfo.q6.AnonInfo = mDNSNULL;
4449 SetQuestionPolicy(&request->u.addrinfo.q4, request);
4450 SetQuestionPolicy(&request->u.addrinfo.q6, request);
4452 request->u.addrinfo.q4.StopTime = request->u.addrinfo.q6.StopTime = 0;
4454 request->u.addrinfo.q4.DNSSECAuthInfo = request->u.addrinfo.q6.DNSSECAuthInfo = mDNSNULL;
4455 request->u.addrinfo.q4.DAIFreeCallback = request->u.addrinfo.q6.DAIFreeCallback = mDNSNULL;
4457 //Turn off dnssec validation for local domains
4458 if (IsLocalDomain(&d))
4459 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = 0;
4461 hostnameLen = strlen(hostname);
4463 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START PID[%d](%s)",
4464 request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c, request->process_id, request->pid_name);
4466 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4468 request->u.addrinfo.q6.qtype = kDNSServiceType_AAAA;
4469 request->u.addrinfo.q6.SearchListIndex = 0;
4470 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set
4471 if ((!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4472 && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4474 request->u.addrinfo.q6.AppendSearchDomains = 1;
4475 request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
4479 request->u.addrinfo.q6.AppendSearchDomains = 0;
4480 request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
4482 request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
4483 request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
4484 request->u.addrinfo.q6.QuestionContext = request;
4485 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
4486 if (err != mStatus_NoError)
4488 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4489 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4491 #if APPLE_OSX_mDNSResponder
4492 err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
4493 #endif // APPLE_OSX_mDNSResponder
4496 request->terminate = addrinfo_termination_callback;
4497 LogMcastQ(&request->u.addrinfo.q6, request, q_start);
4498 if (callExternalHelpers(InterfaceID, &d, flags))
4500 LogInfo("handle_addrinfo_request: calling external_start_browsing_for_service() for kDNSServiceType_AAAA record");
4501 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags);
4506 if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4))
4508 request->u.addrinfo.q4.qtype = kDNSServiceType_A;
4509 request->u.addrinfo.q4.SearchListIndex = 0;
4511 // We append search domains only for queries that are a single label. If overriden using cmd line arg
4512 // "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
4513 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
4515 if ((!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4516 && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4518 request->u.addrinfo.q4.AppendSearchDomains = 1;
4519 request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
4523 request->u.addrinfo.q4.AppendSearchDomains = 0;
4524 request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
4526 request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
4527 request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
4528 request->u.addrinfo.q4.QuestionContext = request;
4529 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
4530 if (err != mStatus_NoError)
4532 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4533 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4534 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4536 // If we started a query for IPv6, we need to cancel it
4537 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4538 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4540 if (callExternalHelpers(InterfaceID, &d, flags))
4542 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for kDNSServiceType_AAAA record");
4543 external_stop_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags);
4547 #if APPLE_OSX_mDNSResponder
4548 err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
4549 #endif // APPLE_OSX_mDNSResponder
4552 request->terminate = addrinfo_termination_callback;
4553 LogMcastQ(&request->u.addrinfo.q4, request, q_start);
4554 if (callExternalHelpers(InterfaceID, &d, flags))
4556 LogInfo("handle_addrinfo_request: calling external_start_browsing_for_service() for kDNSServiceType_A record");
4557 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_A, flags);
4565 // ***************************************************************************
4566 #if COMPILER_LIKES_PRAGMA_MARK
4568 #pragma mark - Main Request Handler etc.
4571 mDNSlocal request_state *NewRequest(void)
4573 request_state **p = &all_requests;
4576 *p = mallocL("request_state", sizeof(request_state));
4578 FatalError("ERROR: malloc");
4579 mDNSPlatformMemZero(*p, sizeof(request_state));
4583 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
4584 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
4585 mDNSlocal void read_msg(request_state *req)
4587 if (req->ts == t_terminated || req->ts == t_error)
4588 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
4590 if (req->ts == t_complete) // this must be death or something is wrong
4592 char buf[4]; // dummy for death notification
4593 int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
4594 if (!nread) { req->ts = t_terminated; return; }
4595 if (nread < 0) goto rerror;
4596 LogMsg("%3d: ERROR: read data from a completed request", req->sd);
4601 if (req->ts != t_morecoming)
4602 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
4604 if (req->hdr_bytes < sizeof(ipc_msg_hdr))
4606 mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
4607 int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
4608 if (nread == 0) { req->ts = t_terminated; return; }
4609 if (nread < 0) goto rerror;
4610 req->hdr_bytes += nread;
4611 if (req->hdr_bytes > sizeof(ipc_msg_hdr))
4612 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
4614 // only read data if header is complete
4615 if (req->hdr_bytes == sizeof(ipc_msg_hdr))
4617 ConvertHeaderBytes(&req->hdr);
4618 if (req->hdr.version != VERSION)
4619 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
4621 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
4622 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
4623 // for other overhead, this means any message above 70kB is definitely bogus.
4624 if (req->hdr.datalen > 70000)
4625 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
4626 req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
4627 if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
4628 req->msgptr = req->msgbuf;
4629 req->msgend = req->msgbuf + req->hdr.datalen;
4630 mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
4634 // If our header is complete, but we're still needing more body data, then try to read it now
4635 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
4636 // Any time we need to get the error return socket we know we'll have at least one data byte
4637 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
4638 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
4640 mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
4642 #if !defined(_WIN32)
4643 struct iovec vec = { req->msgbuf + req->data_bytes, nleft }; // Tell recvmsg where we want the bytes put
4645 struct cmsghdr *cmsg;
4646 char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
4648 msg.msg_namelen = 0;
4651 msg.msg_control = cbuf;
4652 msg.msg_controllen = sizeof(cbuf);
4654 nread = recvmsg(req->sd, &msg, 0);
4656 nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
4658 if (nread == 0) { req->ts = t_terminated; return; }
4659 if (nread < 0) goto rerror;
4660 req->data_bytes += nread;
4661 if (req->data_bytes > req->hdr.datalen)
4662 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
4663 #if !defined(_WIN32)
4664 cmsg = CMSG_FIRSTHDR(&msg);
4665 #if DEBUG_64BIT_SCM_RIGHTS
4666 LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf), sizeof(cbuf), SOL_SOCKET, SCM_RIGHTS);
4667 LogMsg("%3d: Got %d %d %d %d", req->sd, msg.msg_controllen, cmsg ? cmsg->cmsg_len : -1, cmsg ? cmsg->cmsg_level : -1, cmsg ? cmsg->cmsg_type : -1);
4668 #endif // DEBUG_64BIT_SCM_RIGHTS
4669 if (cmsg && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
4671 #if APPLE_OSX_mDNSResponder
4672 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
4673 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
4674 // and it's convenient to repurpose the existing fd-passing code here for that task
4675 if (req->hdr.op == send_bpf)
4677 dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4678 LogOperation("%3d: Got len %d, BPF %d", req->sd, cmsg->cmsg_len, x);
4679 mDNSPlatformReceiveBPF_fd(x);
4682 #endif // APPLE_OSX_mDNSResponder
4683 req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4684 #if DEBUG_64BIT_SCM_RIGHTS
4685 LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
4686 #endif // DEBUG_64BIT_SCM_RIGHTS
4687 if (req->data_bytes < req->hdr.datalen)
4689 LogMsg("%3d: Client(PID [%d](%s)) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
4690 req->sd, req->process_id, req->pid_name, req->errsd, req->data_bytes, req->hdr.datalen);
4698 // If our header and data are both complete, see if we need to make our separate error return socket
4699 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
4701 if (req->terminate && req->hdr.op != cancel_request)
4703 dnssd_sockaddr_t cliaddr;
4704 #if defined(USE_TCP_LOOPBACK)
4707 port.b[0] = req->msgptr[0];
4708 port.b[1] = req->msgptr[1];
4710 cliaddr.sin_family = AF_INET;
4711 cliaddr.sin_port = port.NotAnInteger;
4712 cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4714 char ctrl_path[MAX_CTLPATH];
4715 get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH); // path is first element in message buffer
4716 mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
4717 cliaddr.sun_family = AF_LOCAL;
4718 mDNSPlatformStrLCopy(cliaddr.sun_path, ctrl_path, sizeof(cliaddr.sun_path));
4719 // If the error return path UDS name is empty string, that tells us
4720 // that this is a new version of the library that's going to pass us
4721 // the error return path socket via sendmsg/recvmsg
4722 if (ctrl_path[0] == 0)
4724 if (req->errsd == req->sd)
4725 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
4730 req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
4731 if (!dnssd_SocketValid(req->errsd))
4733 my_throttled_perror("ERROR: socket");
4738 if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
4740 #if !defined(USE_TCP_LOOPBACK)
4742 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
4743 req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4744 if (stat(cliaddr.sun_path, &sb) < 0)
4745 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4747 LogMsg("%3d: read_msg: file “%s” mode %o (octal) uid %d gid %d", req->sd, cliaddr.sun_path, sb.st_mode, sb.st_uid, sb.st_gid);
4753 #if !defined(USE_TCP_LOOPBACK)
4756 LogOperation("%3d: Result code socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
4758 if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
4760 if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
4763 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
4764 req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4770 req->ts = t_complete;
4776 if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
4777 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4781 mDNSlocal mStatus handle_client_request(request_state *req)
4783 mStatus err = mStatus_NoError;
4786 // These are all operations that have their own first-class request_state object
4787 case connection_request:
4788 LogOperation("%3d: DNSServiceCreateConnection START PID[%d](%s)",
4789 req->sd, req->process_id, req->pid_name);
4790 req->terminate = connection_termination;
4792 case connection_delegate_request:
4793 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4794 req->sd, req->process_id, req->pid_name);
4795 req->terminate = connection_termination;
4796 handle_connection_delegate_request(req);
4798 case resolve_request: err = handle_resolve_request (req); break;
4799 case query_request: err = handle_queryrecord_request (req); break;
4800 case browse_request: err = handle_browse_request (req); break;
4801 case reg_service_request: err = handle_regservice_request (req); break;
4802 case enumeration_request: err = handle_enum_request (req); break;
4803 case reconfirm_record_request: err = handle_reconfirm_request (req); break;
4804 case setdomain_request: err = handle_setdomain_request (req); break;
4805 case getproperty_request: handle_getproperty_request (req); break;
4806 case getpid_request: handle_getpid_request (req); break;
4807 case port_mapping_request: err = handle_port_mapping_request(req); break;
4808 case addrinfo_request: err = handle_addrinfo_request (req); break;
4809 case send_bpf: /* Do nothing for send_bpf */ break;
4811 // These are all operations that work with an existing request_state object
4812 case reg_record_request: err = handle_regrecord_request (req); break;
4813 case add_record_request: err = handle_add_request (req); break;
4814 case update_record_request: err = handle_update_request (req); break;
4815 case remove_record_request: err = handle_removerecord_request(req); break;
4816 case cancel_request: handle_cancel_request (req); break;
4817 case release_request: err = handle_release_request (req); break;
4818 default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
4819 req->sd, req->hdr.op, req->process_id, req->pid_name);
4820 err = mStatus_BadParamErr;
4827 #define RecordOrientedOp(X) \
4828 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
4830 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
4831 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
4833 mDNSlocal void request_callback(int fd, short filter, void *info)
4836 request_state *req = info;
4837 mDNSs32 min_size = sizeof(DNSServiceFlags);
4839 (void)filter; // Unused
4844 if (req->ts == t_morecoming)
4846 if (req->ts == t_terminated || req->ts == t_error)
4848 AbortUnlinkAndFree(req);
4851 if (req->ts != t_complete)
4853 LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req->ts, req->process_id, req->pid_name);
4854 AbortUnlinkAndFree(req);
4858 switch(req->hdr.op) // Interface + other data
4860 case connection_request: min_size = 0; break;
4861 case connection_delegate_request: min_size = 4; /* pid */ break;
4862 case reg_service_request: min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
4863 case add_record_request: min_size += 4 /* type, rdlen */ + 4 /* ttl */; break;
4864 case update_record_request: min_size += 2 /* rdlen */ + 4 /* ttl */; break;
4865 case remove_record_request: break;
4866 case browse_request: min_size += sizeof(mDNSu32) + 2 /* type, domain */; break;
4867 case resolve_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4868 case query_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 4 /* type, class*/; break;
4869 case enumeration_request: min_size += sizeof(mDNSu32); break;
4870 case reg_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
4871 case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */; break;
4872 case setdomain_request: min_size += 1 /* domain */; break;
4873 case getproperty_request: min_size = 2; break;
4874 case getpid_request: min_size = 2; break;
4875 case port_mapping_request: min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
4876 case addrinfo_request: min_size += sizeof(mDNSu32) + 4 /* v4/v6 */ + 1 /* hostname */; break;
4877 case send_bpf: // Same as cancel_request below
4878 case cancel_request: min_size = 0; break;
4879 case release_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4880 default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
4881 req->hdr.op, req->process_id, req->pid_name);
4882 min_size = -1; break;
4885 if ((mDNSs32)req->data_bytes < min_size)
4887 LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
4888 req->data_bytes, req->hdr.op, min_size, req->process_id, req->pid_name);
4889 AbortUnlinkAndFree(req);
4892 if (LightweightOp(req->hdr.op) && !req->terminate)
4894 LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
4895 req->hdr.op, req->process_id, req->pid_name);
4896 AbortUnlinkAndFree(req);
4900 // If req->terminate is already set, this means this operation is sharing an existing connection
4901 if (req->terminate && !LightweightOp(req->hdr.op))
4903 request_state *newreq = NewRequest();
4904 newreq->primary = req;
4905 newreq->sd = req->sd;
4906 newreq->errsd = req->errsd;
4907 newreq->uid = req->uid;
4908 newreq->hdr = req->hdr;
4909 newreq->msgbuf = req->msgbuf;
4910 newreq->msgptr = req->msgptr;
4911 newreq->msgend = req->msgend;
4912 // if the parent request is a delegate connection, copy the
4916 newreq->validUUID = mDNStrue;
4917 mDNSPlatformMemCopy(newreq->uuid, req->uuid, UUID_SIZE);
4921 if (req->process_id)
4923 newreq->process_id = req->process_id;
4924 mDNSPlatformStrLCopy(newreq->pid_name, req->pid_name, (mDNSu32)sizeof(newreq->pid_name));
4928 set_peer_pid(newreq);
4934 // Check if the request wants no asynchronous replies.
4935 if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
4937 // If we're shutting down, don't allow new client requests
4938 // We do allow "cancel" and "getproperty" during shutdown
4939 if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
4940 err = mStatus_ServiceNotRunning;
4942 err = handle_client_request(req);
4944 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
4945 if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
4947 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
4948 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
4949 if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf && req->hdr.op != getpid_request)
4951 const mStatus err_netorder = dnssd_htonl(err);
4952 send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
4953 if (req->errsd != req->sd)
4955 LogOperation("%3d: Result code socket %d closed %08X %08X (%d)",
4956 req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
4957 dnssd_close(req->errsd);
4958 req->errsd = req->sd;
4959 // Also need to reset the parent's errsd, if this is a subordinate operation
4960 if (req->primary) req->primary->errsd = req->primary->sd;
4964 // Reset ready to accept the next req on this pipe
4965 if (req->primary) req = req->primary;
4966 req->ts = t_morecoming;
4968 req->data_bytes = 0;
4969 req->msgbuf = mDNSNULL;
4970 req->msgptr = mDNSNULL;
4975 mDNSlocal void connect_callback(int fd, short filter, void *info)
4977 dnssd_sockaddr_t cliaddr;
4978 dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
4979 dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
4980 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
4981 unsigned long optval = 1;
4984 (void)filter; // Unused
4985 (void)info; // Unused
4987 if (!dnssd_SocketValid(sd))
4989 if (dnssd_errno != dnssd_EWOULDBLOCK)
4990 my_throttled_perror("ERROR: accept");
4995 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
4996 if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
4997 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
5001 if (ioctlsocket(sd, FIONBIO, &optval) != 0)
5003 if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
5006 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
5012 request_state *request = NewRequest();
5013 request->ts = t_morecoming;
5015 request->errsd = sd;
5016 set_peer_pid(request);
5017 #if APPLE_OSX_mDNSResponder
5019 socklen_t xucredlen = sizeof(x);
5020 if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION)
5021 request->uid = x.cr_uid; // save the effective userid of the client
5023 my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
5025 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
5026 #endif // APPLE_OSX_mDNSResponder
5027 LogOperation("%3d: connect_callback: Adding FD for uid %u", request->sd, request->uid);
5028 udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
5032 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
5034 #if defined(SO_NP_EXTENSIONS)
5035 struct so_np_extensions sonpx;
5036 socklen_t optlen = sizeof(struct so_np_extensions);
5037 sonpx.npx_flags = SONPX_SETOPTSHUT;
5038 sonpx.npx_mask = SONPX_SETOPTSHUT;
5039 if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
5040 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
5043 // SEH: do we even need to do this on windows?
5044 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
5046 if (ioctlsocket(skt, FIONBIO, &opt) != 0)
5048 if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
5051 my_perror("ERROR: could not set listen socket to non-blocking mode");
5055 if (listen(skt, LISTENQ) != 0)
5057 my_perror("ERROR: could not listen on listen socket");
5061 if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
5063 my_perror("ERROR: could not add listen socket to event loop");
5068 LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
5069 mDNSStorage.uds_listener_skt = skt;
5074 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
5076 dnssd_sockaddr_t laddr;
5080 LogInfo("udsserver_init: %d %d", _DNS_SD_H, mDNSStorage.mDNS_plat);
5082 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
5085 FILE *fp = fopen(PID_FILE, "w");
5088 fprintf(fp, "%d\n", getpid());
5095 for (i = 0; i < count; i++)
5096 if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
5101 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
5102 if (!dnssd_SocketValid(listenfd))
5104 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
5108 mDNSPlatformMemZero(&laddr, sizeof(laddr));
5110 #if defined(USE_TCP_LOOPBACK)
5112 laddr.sin_family = AF_INET;
5113 laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
5114 laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
5115 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5118 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5124 mode_t mask = umask(0);
5125 unlink(boundPath); // OK if this fails
5126 laddr.sun_family = AF_LOCAL;
5127 #ifndef NOT_HAVE_SA_LEN
5128 // According to Stevens (section 3.2), there is no portable way to
5129 // determine whether sa_len is defined on a particular platform.
5130 laddr.sun_len = sizeof(struct sockaddr_un);
5132 if (strlen(boundPath) >= sizeof(laddr.sun_path))
5134 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
5137 mDNSPlatformStrLCopy(laddr.sun_path, boundPath, sizeof(laddr.sun_path));
5138 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5142 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5148 if (!uds_socket_setup(listenfd)) goto error;
5151 #if !defined(PLATFORM_NO_RLIMIT)
5153 // Set maximum number of open file descriptors
5154 #define MIN_OPENFILES 10240
5155 struct rlimit maxfds, newfds;
5157 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
5158 // you have to get and set rlimits once before getrlimit will return sensible values
5159 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5160 if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5162 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5163 newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
5164 newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
5165 if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
5166 if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5168 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5169 debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
5170 debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
5174 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
5175 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
5176 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
5177 mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
5178 mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
5180 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
5181 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
5182 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
5183 AddAutoBrowseDomain(0, &localdomain);
5185 udsserver_handle_configchange(&mDNSStorage);
5190 my_perror("ERROR: udsserver_init");
5194 mDNSexport int udsserver_exit(void)
5196 // Cancel all outstanding client requests
5197 while (all_requests) AbortUnlinkAndFree(all_requests);
5199 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
5200 // created in udsserver_init, and others we created as a result of reading local configuration data
5201 while (LocalDomainEnumRecords)
5203 ARListElem *rem = LocalDomainEnumRecords;
5204 LocalDomainEnumRecords = LocalDomainEnumRecords->next;
5205 mDNS_Deregister(&mDNSStorage, &rem->ar);
5208 // If the launching environment created no listening socket,
5209 // that means we created it ourselves, so we should clean it up on exit
5210 if (dnssd_SocketValid(listenfd))
5212 dnssd_close(listenfd);
5213 #if !defined(USE_TCP_LOOPBACK)
5214 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
5215 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
5216 // It would be nice if we could find a solution to this problem
5217 if (unlink(boundPath))
5218 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
5222 if (PID_FILE[0]) unlink(PID_FILE);
5227 mDNSlocal void LogClientInfo(request_state *req)
5231 mDNS_snprintf(prefix, sizeof(prefix), " -> ");
5233 mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
5235 if (!req->terminate)
5236 LogMsgNoIdent("%s No operation yet on this socket", prefix);
5237 else if (req->terminate == connection_termination)
5239 int num_records = 0, num_ops = 0;
5240 const registered_record_entry *p;
5242 for (p = req->u.reg_recs; p; p=p->next) num_records++;
5243 for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
5244 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
5245 prefix, num_records, num_records != 1 ? "s" : "", num_ops, num_ops != 1 ? "s" : "",
5246 req->process_id, req->pid_name);
5247 for (p = req->u.reg_recs; p; p=p->next)
5248 LogMsgNoIdent(" -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
5249 req->flags, req->interfaceIndex, p->key, ARDisplayString(&mDNSStorage, p->rr), req->process_id, req->pid_name);
5250 for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(r);
5252 else if (req->terminate == regservice_termination_callback)
5254 service_instance *ptr;
5256 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5257 LogMsgNoIdent("%s DNSServiceRegister 0x%08X %2d %##s%s %u/%u PID[%d](%s)",
5258 (ptr == req->u.servicereg.instances) ? prefix : " ", req->flags, req->interfaceIndex, ptr->srs.RR_SRV.resrec.name->c,
5259 AnonDataToString(ptr->srs.AnonData, 0, anonstr, sizeof(anonstr)), mDNSVal16(req->u.servicereg.port),
5260 SRS_PORT(&ptr->srs), req->process_id, req->pid_name);
5262 else if (req->terminate == browse_termination_callback)
5266 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5267 LogMsgNoIdent("%s DNSServiceBrowse 0x%08X %2d %##s%s PID[%d](%s)",
5268 (blist == req->u.browser.browsers) ? prefix : " ", req->flags, req->interfaceIndex, blist->q.qname.c,
5269 AnonDataToString(req->u.browser.AnonData, 0, anonstr, sizeof(anonstr)), req->process_id, req->pid_name);
5271 else if (req->terminate == resolve_termination_callback)
5272 LogMsgNoIdent("%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
5273 prefix, req->flags, req->interfaceIndex, req->u.resolve.qsrv.qname.c, req->process_id, req->pid_name);
5274 else if (req->terminate == queryrecord_termination_callback)
5275 LogMsgNoIdent("%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
5276 prefix, req->flags, req->interfaceIndex, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype), req->process_id, req->pid_name);
5277 else if (req->terminate == enum_termination_callback)
5278 LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
5279 prefix, req->flags, req->interfaceIndex, req->u.enumeration.q_all.qname.c, req->process_id, req->pid_name);
5280 else if (req->terminate == port_mapping_termination_callback)
5281 LogMsgNoIdent("%s DNSServiceNATPortMapping 0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
5284 req->interfaceIndex,
5285 req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : " ",
5286 req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : " ",
5287 mDNSVal16(req->u.pm.NATinfo.IntPort),
5288 mDNSVal16(req->u.pm.ReqExt),
5289 &req->u.pm.NATinfo.ExternalAddress,
5290 mDNSVal16(req->u.pm.NATinfo.ExternalPort),
5291 req->u.pm.NATinfo.NATLease,
5292 req->u.pm.NATinfo.Lifetime,
5293 req->process_id, req->pid_name);
5294 else if (req->terminate == addrinfo_termination_callback)
5295 LogMsgNoIdent("%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
5296 prefix, req->flags, req->interfaceIndex,
5297 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5298 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5299 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name);
5301 LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
5304 mDNSlocal void GetMcastClients(request_state *req)
5306 if (req->terminate == connection_termination)
5308 int num_records = 0, num_ops = 0;
5309 const registered_record_entry *p;
5311 for (p = req->u.reg_recs; p; p=p->next)
5313 for (r = req->next; r; r=r->next)
5314 if (r->primary == req)
5316 for (p = req->u.reg_recs; p; p=p->next)
5318 if (!AuthRecord_uDNS(p->rr))
5321 for (r = req->next; r; r=r->next)
5322 if (r->primary == req)
5325 else if (req->terminate == regservice_termination_callback)
5327 service_instance *ptr;
5328 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5330 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5334 else if (req->terminate == browse_termination_callback)
5337 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5339 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5343 else if (req->terminate == resolve_termination_callback)
5345 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5348 else if (req->terminate == queryrecord_termination_callback)
5350 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5353 else if (req->terminate == addrinfo_termination_callback)
5355 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5365 mDNSlocal void LogMcastClientInfo(request_state *req)
5367 if (!req->terminate)
5368 LogMcastNoIdent("No operation yet on this socket");
5369 else if (req->terminate == connection_termination)
5371 int num_records = 0, num_ops = 0;
5372 const registered_record_entry *p;
5374 for (p = req->u.reg_recs; p; p=p->next)
5376 for (r = req->next; r; r=r->next)
5377 if (r->primary == req)
5379 for (p = req->u.reg_recs; p; p=p->next)
5381 if (!AuthRecord_uDNS(p->rr))
5382 LogMcastNoIdent("R: -> DNSServiceRegisterRecord: %##s %s PID[%d](%s)", p->rr->resrec.name->c,
5383 DNSTypeName(p->rr->resrec.rrtype), req->process_id, req->pid_name, i_mcount++);
5385 for (r = req->next; r; r=r->next)
5386 if (r->primary == req)
5387 LogMcastClientInfo(r);
5389 else if (req->terminate == regservice_termination_callback)
5391 service_instance *ptr;
5392 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5394 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5395 LogMcastNoIdent("R: DNSServiceRegister: %##s %u/%u PID[%d](%s)", ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port),
5396 SRS_PORT(&ptr->srs), req->process_id, req->pid_name, i_mcount++);
5399 else if (req->terminate == browse_termination_callback)
5402 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5404 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5405 LogMcastNoIdent("Q: DNSServiceBrowse %##s %s PID[%d](%s)", blist->q.qname.c, DNSTypeName(blist->q.qtype),
5406 req->process_id, req->pid_name, i_mcount++);
5409 else if (req->terminate == resolve_termination_callback)
5411 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5412 LogMcastNoIdent("Q: DNSServiceResolve %##s %s PID[%d](%s)", req->u.resolve.qsrv.qname.c, DNSTypeName(req->u.resolve.qsrv.qtype),
5413 req->process_id, req->pid_name, i_mcount++);
5415 else if (req->terminate == queryrecord_termination_callback)
5417 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5418 LogMcastNoIdent("Q: DNSServiceQueryRecord %##s %s PID[%d](%s)", req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype),
5419 req->process_id, req->pid_name, i_mcount++);
5421 else if (req->terminate == addrinfo_termination_callback)
5423 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5424 LogMcastNoIdent("Q: DNSServiceGetAddrInfo %s%s %##s PID[%d](%s)",
5425 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5426 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5427 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name, i_mcount++);
5436 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
5440 case kDNSRecordTypeUnregistered: return ("Unregistered ");
5441 case kDNSRecordTypeDeregistering: return ("Deregistering");
5442 case kDNSRecordTypeUnique: return ("Unique ");
5443 case kDNSRecordTypeAdvisory: return ("Advisory ");
5444 case kDNSRecordTypeShared: return ("Shared ");
5445 case kDNSRecordTypeVerified: return ("Verified ");
5446 case kDNSRecordTypeKnownUnique: return ("KnownUnique ");
5447 default: return("Unknown");
5451 mDNSlocal int LogEtcHosts(mDNS *const m)
5453 mDNSBool showheader = mDNStrue;
5454 const AuthRecord *ar;
5459 mDNSBool truncated = 0;
5461 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5463 if (m->rrauth.rrauth_hash[slot]) authslot++;
5464 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5465 for (ar = ag->members; ar; ar = ar->next)
5467 if (ar->RecordCallback != FreeEtcHosts) continue;
5468 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5470 // Print a maximum of 50 records
5471 if (count++ >= 50) { truncated = mDNStrue; continue; }
5472 if (ar->ARType == AuthRecordLocalOnly)
5474 if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
5475 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5478 mDNSu32 scopeid = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
5479 LogMsgNoIdent(" %s %u %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
5485 if (showheader) LogMsgNoIdent("<None>");
5486 else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
5490 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
5492 mDNSBool showheader = mDNStrue;
5493 const AuthRecord *ar;
5497 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5499 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5500 for (ar = ag->members; ar; ar = ar->next)
5502 if (ar->RecordCallback == FreeEtcHosts) continue;
5503 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5505 // Print a maximum of 400 records
5506 if (ar->ARType == AuthRecordLocalOnly)
5507 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5508 else if (ar->ARType == AuthRecordP2P)
5510 if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5511 LogMsgNoIdent(" %s BLE %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5513 LogMsgNoIdent(" %s PP %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5518 if (showheader) LogMsgNoIdent("<None>");
5521 mDNSlocal char *AnonInfoToString(AnonymousInfo *ai, char *anonstr, int anstrlen)
5524 if (ai && ai->AnonData)
5526 return (AnonDataToString(ai->AnonData, ai->AnonDataLen, anonstr, anstrlen));
5531 mDNSlocal void LogOneAuthRecord(const AuthRecord *ar, mDNSs32 now, const char *const ifname)
5534 if (AuthRecord_uDNS(ar))
5536 LogMsgNoIdent("%7d %7d %7d %-7s %4d %s %s",
5537 ar->ThisAPInterval / mDNSPlatformOneSecond,
5538 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5539 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5542 ar->AllowRemoteQuery ? "☠" : " ",
5543 ARDisplayString(&mDNSStorage, ar));
5547 LogMsgNoIdent("%7d %7d %7d %-7s 0x%02X %s %s%s",
5548 ar->ThisAPInterval / mDNSPlatformOneSecond,
5549 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5550 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5551 ifname ? ifname : "ALL",
5552 ar->resrec.RecordType,
5553 ar->AllowRemoteQuery ? "☠" : " ",
5554 ARDisplayString(&mDNSStorage, ar), AnonInfoToString(ar->resrec.AnonInfo, anstr, sizeof(anstr)));
5558 mDNSlocal void LogAuthRecords(const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
5560 mDNSBool showheader = mDNStrue;
5561 const AuthRecord *ar;
5562 OwnerOptData owner = zeroOwner;
5563 for (ar = ResourceRecords; ar; ar=ar->next)
5565 const char *const ifname = InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID);
5566 if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
5568 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" Int Next Expire if State"); }
5569 if (proxy) (*proxy)++;
5570 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
5573 if (owner.password.l[0])
5574 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
5575 else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
5576 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner.HMAC, &owner.IMAC, owner.seq);
5578 LogMsgNoIdent("Proxying for %.6a seq %d", &owner.HMAC, owner.seq);
5580 if (AuthRecord_uDNS(ar))
5582 LogOneAuthRecord(ar, now, ifname);
5584 else if (ar->ARType == AuthRecordLocalOnly)
5586 LogMsgNoIdent(" LO %s", ARDisplayString(&mDNSStorage, ar));
5588 else if (ar->ARType == AuthRecordP2P)
5590 if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5591 LogMsgNoIdent(" BLE %s", ARDisplayString(&mDNSStorage, ar));
5593 LogMsgNoIdent(" PP %s", ARDisplayString(&mDNSStorage, ar));
5597 LogOneAuthRecord(ar, now, ifname);
5598 if (ar->resrec.AnonInfo)
5600 ResourceRecord *nsec3 = ar->resrec.AnonInfo->nsec3RR;
5601 // We just print the values from the AuthRecord to keep it nicely aligned though
5602 // all we want here is the nsec3 information.
5603 LogMsgNoIdent("%7d %7d %7d %7s %s",
5604 ar->ThisAPInterval / mDNSPlatformOneSecond,
5605 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5606 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5607 ifname ? ifname : "ALL",
5608 RRDisplayString(&mDNSStorage, nsec3));
5613 if (showheader) LogMsgNoIdent("<None>");
5616 mDNSlocal void PrintOneCacheRecord(const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5618 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5620 cr->CRActiveQuestion ? "*" : " ",
5622 ifname ? ifname : "-U-",
5623 (cr->resrec.RecordType == kDNSRecordTypePacketNegative) ? "-" :
5624 (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5625 DNSTypeName(cr->resrec.rrtype),
5626 CRDisplayString(&mDNSStorage, cr));
5630 mDNSlocal void PrintCachedRecords(const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5636 // The records that are cached under the main cache record like nsec, soa don't have
5637 // their own lifetime. If the main cache record expires, they also expire.
5640 PrintOneCacheRecord(nsec, slot, remain, ifname, CacheUsed);
5646 PrintOneCacheRecord(soa, slot, remain, ifname, CacheUsed);
5648 if (cr->resrec.AnonInfo)
5650 ResourceRecord *nsec3 = cr->resrec.AnonInfo->nsec3RR;
5651 // Even though it is a resource record, we print the sameway
5652 // as a cache record so that it aligns properly.
5655 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5659 ifname ? ifname : "-U-",
5660 (nsec3->RecordType == kDNSRecordTypePacketNegative) ? "-" :
5661 (nsec3->RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5662 DNSTypeName(nsec3->rrtype),
5663 RRDisplayString(&mDNSStorage, nsec3));
5668 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen)
5676 // If the caller is lazy to compute the length, we do it for them.
5678 len = strlen((const char *)ad);
5682 // Print the anondata within brackets. Hence, we need space for two
5683 // brackets and a NULL byte.
5684 if (len > (adstrlen - 3))
5688 mDNSPlatformMemCopy(adstr, ad, len);
5696 mDNSexport void LogMDNSStatistics(mDNS *const m)
5698 LogMsgNoIdent("--- MDNS Statistics ---");
5700 LogMsgNoIdent("Name Conflicts %u", m->mDNSStats.NameConflicts);
5701 LogMsgNoIdent("KnownUnique Name Conflicts %u", m->mDNSStats.KnownUniqueNameConflicts);
5702 LogMsgNoIdent("Duplicate Query Suppressions %u", m->mDNSStats.DupQuerySuppressions);
5703 LogMsgNoIdent("KA Suppressions %u", m->mDNSStats.KnownAnswerSuppressions);
5704 LogMsgNoIdent("KA Multiple Packets %u", m->mDNSStats.KnownAnswerMultiplePkts);
5705 LogMsgNoIdent("Poof Cache Deletions %u", m->mDNSStats.PoofCacheDeletions);
5706 LogMsgNoIdent("--------------------------------");
5708 LogMsgNoIdent("Multicast packets Sent %u", m->MulticastPacketsSent);
5709 LogMsgNoIdent("Multicast packets Received %u", m->MPktNum);
5710 LogMsgNoIdent("Remote Subnet packets %u", m->RemoteSubnet);
5711 LogMsgNoIdent("QU questions received %u", m->mDNSStats.UnicastBitInQueries);
5712 LogMsgNoIdent("Normal multicast questions %u", m->mDNSStats.NormalQueries);
5713 LogMsgNoIdent("Answers for questions %u", m->mDNSStats.MatchingAnswersForQueries);
5714 LogMsgNoIdent("Unicast responses %u", m->mDNSStats.UnicastResponses);
5715 LogMsgNoIdent("Multicast responses %u", m->mDNSStats.MulticastResponses);
5716 LogMsgNoIdent("Unicast response Demotions %u", m->mDNSStats.UnicastDemotedToMulticast);
5717 LogMsgNoIdent("--------------------------------");
5719 LogMsgNoIdent("Sleeps %u", m->mDNSStats.Sleeps);
5720 LogMsgNoIdent("Wakeups %u", m->mDNSStats.Wakes);
5721 LogMsgNoIdent("Interface UP events %u", m->mDNSStats.InterfaceUp);
5722 LogMsgNoIdent("Interface UP Flap events %u", m->mDNSStats.InterfaceUpFlap);
5723 LogMsgNoIdent("Interface Down events %u", m->mDNSStats.InterfaceDown);
5724 LogMsgNoIdent("Interface DownFlap events %u", m->mDNSStats.InterfaceDownFlap);
5725 LogMsgNoIdent("Cache refresh queries %u", m->mDNSStats.CacheRefreshQueries);
5726 LogMsgNoIdent("Cache refreshed %u", m->mDNSStats.CacheRefreshed);
5727 LogMsgNoIdent("Wakeup on Resolves %u", m->mDNSStats.WakeOnResolves);
5730 mDNSexport void udsserver_info()
5732 mDNS *const m = &mDNSStorage;
5733 const mDNSs32 now = mDNS_TimeNow(m);
5734 mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
5735 int ProxyA = 0, ProxyD = 0;
5736 mDNSu32 groupCount = 0;
5737 mDNSu32 mcastRecordCount = 0;
5738 mDNSu32 ucastRecordCount = 0;
5739 const CacheGroup *cg;
5740 const CacheRecord *cr;
5741 const DNSQuestion *q;
5742 const DNameListElem *d;
5743 const SearchListElem *s;
5745 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
5747 LogMsgNoIdent("------------ Cache -------------");
5748 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
5749 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5751 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
5753 groupCount++; // Count one cache entity for the CacheGroup object
5754 for (cr = cg->members; cr; cr=cr->next)
5756 const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
5758 mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
5759 mDNSu32 *const countPtr = InterfaceID ? &mcastRecordCount : &ucastRecordCount;
5760 if (!InterfaceID && cr->resrec.rDNSServer && cr->resrec.rDNSServer->scoped)
5761 InterfaceID = cr->resrec.rDNSServer->interface;
5762 ifname = InterfaceNameForID(m, InterfaceID);
5763 if (cr->CRActiveQuestion) CacheActive++;
5764 PrintOneCacheRecord(cr, slot, remain, ifname, countPtr);
5765 PrintCachedRecords(cr, slot, remain, ifname, countPtr);
5770 CacheUsed = groupCount + mcastRecordCount + ucastRecordCount;
5771 if (m->rrcache_totalused != CacheUsed)
5772 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
5773 if (m->rrcache_active != CacheActive)
5774 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
5775 LogMsgNoIdent("Cache size %u entities; %u in use (%u group, %u multicast, %u unicast); %u referenced by active questions",
5776 m->rrcache_size, CacheUsed, groupCount, mcastRecordCount, ucastRecordCount, CacheActive);
5778 LogMsgNoIdent("--------- Auth Records ---------");
5779 LogAuthRecords(now, m->ResourceRecords, mDNSNULL);
5781 LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
5782 LogLocalOnlyAuthRecords(m);
5784 LogMsgNoIdent("--------- /etc/hosts ---------");
5787 LogMsgNoIdent("------ Duplicate Records -------");
5788 LogAuthRecords(now, m->DuplicateRecords, mDNSNULL);
5790 LogMsgNoIdent("----- Auth Records Proxied -----");
5791 LogAuthRecords(now, m->ResourceRecords, &ProxyA);
5793 LogMsgNoIdent("-- Duplicate Records Proxied ---");
5794 LogAuthRecords(now, m->DuplicateRecords, &ProxyD);
5796 LogMsgNoIdent("---------- Questions -----------");
5797 if (!m->Questions) LogMsgNoIdent("<None>");
5803 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
5804 for (q = m->Questions; q; q=q->next)
5806 mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
5807 mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
5808 char *ifname = InterfaceNameForID(m, q->InterfaceID);
5810 if (q->ThisQInterval) CacheActive++;
5811 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s%s",
5813 ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
5814 mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
5815 PrivateQuery(q) ? "P" : q->ValidationRequired ? "V" : q->ValidatingResponse ? "R" : " ",
5816 q->CurrentAnswers, q->validDNSServers.l[3], q->validDNSServers.l[2], q->validDNSServers.l[1],
5817 q->validDNSServers.l[0], q, q->DuplicateOf,
5818 q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c,
5819 AnonInfoToString(q->AnonInfo, anonstr, sizeof(anonstr)),
5820 q->DuplicateOf ? " (dup)" : "");
5822 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
5825 LogMsgNoIdent("----- LocalOnly, P2P Questions -----");
5826 if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
5827 else for (q = m->LocalOnlyQuestions; q; q=q->next)
5828 LogMsgNoIdent(" %3s %5d %-6s%##s%s",
5829 q->InterfaceID == mDNSInterface_LocalOnly ? "LO ": q->InterfaceID == mDNSInterface_BLE ? "BLE": "P2P",
5830 q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
5832 LogMsgNoIdent("---- Active UDS Client Requests ----");
5833 if (!all_requests) LogMsgNoIdent("<None>");
5836 request_state *req, *r;
5837 for (req = all_requests; req; req=req->next)
5839 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
5841 for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
5842 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
5844 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
5850 LogMsgNoIdent("-------- NAT Traversals --------");
5851 LogMsgNoIdent("ExtAddress %.4a Retry %d Interval %d",
5853 m->retryGetAddr ? (m->retryGetAddr - now) / mDNSPlatformOneSecond : 0,
5854 m->retryIntervalGetAddr / mDNSPlatformOneSecond);
5855 if (m->NATTraversals)
5857 const NATTraversalInfo *nat;
5858 for (nat = m->NATTraversals; nat; nat=nat->next)
5860 LogMsgNoIdent("%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
5862 nat->Protocol ? (nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP") : "ADD",
5863 mDNSVal16(nat->IntPort),
5864 (nat->lastSuccessfulProtocol == NATTProtocolNone ? "None " :
5865 nat->lastSuccessfulProtocol == NATTProtocolNATPMP ? "NAT-PMP " :
5866 nat->lastSuccessfulProtocol == NATTProtocolUPNPIGD ? "UPnP/IGD" :
5867 nat->lastSuccessfulProtocol == NATTProtocolPCP ? "PCP " :
5868 /* else */ "Unknown " ),
5870 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5871 nat->retryInterval / mDNSPlatformOneSecond,
5872 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5873 &nat->NewAddress, mDNSVal16(nat->RequestedPort),
5874 &nat->ExternalAddress, mDNSVal16(nat->ExternalPort));
5878 LogMsgNoIdent("--------- AuthInfoList ---------");
5879 if (!m->AuthInfoList) LogMsgNoIdent("<None>");
5882 const DomainAuthInfo *a;
5883 for (a = m->AuthInfoList; a; a = a->next)
5885 LogMsgNoIdent("%##s %##s %##s %d %d %.16a%s",
5886 a->domain.c, a->keyname.c,
5887 a->hostname.c, (a->port.b[0] << 8 | a->port.b[1]),
5888 (a->deltime ? (a->deltime - now) : 0),
5889 &a->AutoTunnelInnerAddress, a->AutoTunnel ? " AutoTunnel" : "");
5893 #if APPLE_OSX_mDNSResponder
5894 LogMsgNoIdent("--------- TunnelClients --------");
5895 if (!m->TunnelClients) LogMsgNoIdent("<None>");
5898 const ClientTunnel *c;
5899 for (c = m->TunnelClients; c; c = c->next)
5900 LogMsgNoIdent("%##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
5901 c->dstname.c, &c->loc_inner, &c->loc_outer, &c->loc_outer6, &c->rmt_inner, &c->rmt_outer, mDNSVal16(c->rmt_outer_port), &c->rmt_outer6, c->q.ThisQInterval);
5903 #endif // APPLE_OSX_mDNSResponder
5905 LogMsgNoIdent("---------- Misc State ----------");
5907 LogMsgNoIdent("PrimaryMAC: %.6a", &m->PrimaryMAC);
5909 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
5911 m->SleepState == SleepState_Awake ? "Awake" :
5912 m->SleepState == SleepState_Transferring ? "Transferring" :
5913 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?",
5916 if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
5917 #ifndef SPC_DISABLED
5918 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
5920 if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
5921 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
5923 LogMsgNoIdent("------ Auto Browse Domains -----");
5924 if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
5925 else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5927 LogMsgNoIdent("--- Auto Registration Domains --");
5928 if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
5929 else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5931 LogMsgNoIdent("--- Search Domains --");
5932 if (!SearchList) LogMsgNoIdent("<None>");
5935 for (s=SearchList; s; s=s->next)
5937 char *ifname = InterfaceNameForID(m, s->InterfaceID);
5938 LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
5941 LogInfo("--- Trust Anchors ---");
5942 if (!m->TrustAnchors)
5949 mDNSu8 fromTimeBuf[64];
5950 mDNSu8 untilTimeBuf[64];
5952 for (ta=m->TrustAnchors; ta; ta=ta->next)
5954 mDNSPlatformFormatTime((unsigned long)ta->validFrom, fromTimeBuf, sizeof(fromTimeBuf));
5955 mDNSPlatformFormatTime((unsigned long)ta->validUntil, untilTimeBuf, sizeof(untilTimeBuf));
5956 LogInfo("%##s %d %d %d %d %s %s", ta->zone.c, ta->rds.keyTag,
5957 ta->rds.alg, ta->rds.digestType, ta->digestLen, fromTimeBuf, untilTimeBuf);
5961 LogInfo("--- DNSSEC Statistics ---");
5963 LogMsgNoIdent("Unicast Cache size %u", m->rrcache_totalused_unicast);
5964 LogInfo("DNSSEC Cache size %u", m->DNSSECStats.TotalMemUsed);
5965 if (m->rrcache_totalused_unicast)
5966 LogInfo("DNSSEC usage percentage %u", ((unsigned long)(m->DNSSECStats.TotalMemUsed * 100))/m->rrcache_totalused_unicast);
5967 LogInfo("DNSSEC Extra Packets (0 to 2) %u", m->DNSSECStats.ExtraPackets0);
5968 LogInfo("DNSSEC Extra Packets (3 to 6) %u", m->DNSSECStats.ExtraPackets3);
5969 LogInfo("DNSSEC Extra Packets (7 to 9) %u", m->DNSSECStats.ExtraPackets7);
5970 LogInfo("DNSSEC Extra Packets ( >= 10) %u", m->DNSSECStats.ExtraPackets10);
5972 LogInfo("DNSSEC Latency (0 to 4ms) %u", m->DNSSECStats.Latency0);
5973 LogInfo("DNSSEC Latency (4 to 9ms) %u", m->DNSSECStats.Latency5);
5974 LogInfo("DNSSEC Latency (10 to 19ms) %u", m->DNSSECStats.Latency10);
5975 LogInfo("DNSSEC Latency (20 to 49ms) %u", m->DNSSECStats.Latency20);
5976 LogInfo("DNSSEC Latency (50 to 99ms) %u", m->DNSSECStats.Latency50);
5977 LogInfo("DNSSEC Latency ( >=100ms) %u", m->DNSSECStats.Latency100);
5979 LogInfo("DNSSEC Secure Status %u", m->DNSSECStats.SecureStatus);
5980 LogInfo("DNSSEC Insecure Status %u", m->DNSSECStats.InsecureStatus);
5981 LogInfo("DNSSEC Indeterminate Status %u", m->DNSSECStats.IndeterminateStatus);
5982 LogInfo("DNSSEC Bogus Status %u", m->DNSSECStats.BogusStatus);
5983 LogInfo("DNSSEC NoResponse Status %u", m->DNSSECStats.NoResponseStatus);
5984 LogInfo("DNSSEC Probes sent %u", m->DNSSECStats.NumProbesSent);
5985 LogInfo("DNSSEC Msg Size (<=1024) %u", m->DNSSECStats.MsgSize0);
5986 LogInfo("DNSSEC Msg Size (<=2048) %u", m->DNSSECStats.MsgSize1);
5987 LogInfo("DNSSEC Msg Size (> 2048) %u", m->DNSSECStats.MsgSize2);
5989 LogMDNSStatistics(m);
5991 LogMsgNoIdent("---- Task Scheduling Timers ----");
5993 #if BONJOUR_ON_DEMAND
5994 LogMsgNoIdent("BonjourEnabled %d", m->BonjourEnabled);
5995 #endif // BONJOUR_ON_DEMAND
5997 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5998 LogMsgNoIdent("EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery);
5999 LogMsgNoIdent("DefaultToBLETriggered %d", DefaultToBLETriggered);
6000 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
6002 if (!m->NewQuestions)
6003 LogMsgNoIdent("NewQuestion <NONE>");
6005 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
6006 m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
6007 m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
6009 if (!m->NewLocalOnlyQuestions)
6010 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
6012 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
6013 m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
6015 if (!m->NewLocalRecords)
6016 LogMsgNoIdent("NewLocalRecords <NONE>");
6018 LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
6020 LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
6021 LogMsgNoIdent("LocalRemoveEvents%s", m->LocalRemoveEvents ? "" : " <NONE>");
6022 LogMsgNoIdent("m->AutoTunnelRelayAddr %.16a", &m->AutoTunnelRelayAddr);
6023 LogMsgNoIdent("m->WABBrowseQueriesCount %d", m->WABBrowseQueriesCount);
6024 LogMsgNoIdent("m->WABLBrowseQueriesCount %d", m->WABLBrowseQueriesCount);
6025 LogMsgNoIdent("m->WABRegQueriesCount %d", m->WABRegQueriesCount);
6026 LogMsgNoIdent("m->AutoTargetServices %d", m->AutoTargetServices);
6028 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
6029 LogMsgNoIdent("m->timenow %08X %11d", now, now);
6030 LogMsgNoIdent("m->timenow_adjust %08X %11d", m->timenow_adjust, m->timenow_adjust);
6031 LogTimer("m->NextScheduledEvent ", m->NextScheduledEvent);
6033 #ifndef UNICAST_DISABLED
6034 LogTimer("m->NextuDNSEvent ", m->NextuDNSEvent);
6035 LogTimer("m->NextSRVUpdate ", m->NextSRVUpdate);
6036 LogTimer("m->NextScheduledNATOp ", m->NextScheduledNATOp);
6037 LogTimer("m->retryGetAddr ", m->retryGetAddr);
6040 LogTimer("m->NextCacheCheck ", m->NextCacheCheck);
6041 LogTimer("m->NextScheduledSPS ", m->NextScheduledSPS);
6042 LogTimer("m->NextScheduledKA ", m->NextScheduledKA);
6044 #if BONJOUR_ON_DEMAND
6045 LogTimer("m->NextBonjourDisableTime ", m->NextBonjourDisableTime);
6046 #endif // BONJOUR_ON_DEMAND
6048 LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
6049 LogTimer("m->DelaySleep ", m->DelaySleep);
6051 LogTimer("m->NextScheduledQuery ", m->NextScheduledQuery);
6052 LogTimer("m->NextScheduledProbe ", m->NextScheduledProbe);
6053 LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
6055 LogTimer("m->SuppressSending ", m->SuppressSending);
6056 LogTimer("m->SuppressProbes ", m->SuppressProbes);
6057 LogTimer("m->ProbeFailTime ", m->ProbeFailTime);
6058 LogTimer("m->DelaySleep ", m->DelaySleep);
6059 LogTimer("m->SleepLimit ", m->SleepLimit);
6060 LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
6063 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6064 mDNSexport void uds_validatelists(void)
6066 const request_state *req, *p;
6067 for (req = all_requests; req; req=req->next)
6069 if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
6070 LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
6072 if (req->primary == req)
6073 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
6075 if (req->primary && req->replies)
6076 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
6077 req, req->sd, req->primary && req->replies);
6081 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
6082 else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
6083 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
6086 for (rep = req->replies; rep; rep=rep->next)
6087 if (rep->next == (reply_state *)~0)
6088 LogMemCorruption("UDS req->replies: %p is garbage", rep);
6090 if (req->terminate == connection_termination)
6092 registered_record_entry *r;
6093 for (r = req->u.reg_recs; r; r=r->next)
6094 if (r->next == (registered_record_entry *)~0)
6095 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
6097 else if (req->terminate == regservice_termination_callback)
6099 service_instance *s;
6100 for (s = req->u.servicereg.instances; s; s=s->next)
6101 if (s->next == (service_instance *)~0)
6102 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
6104 else if (req->terminate == browse_termination_callback)
6107 for (b = req->u.browser.browsers; b; b=b->next)
6108 if (b->next == (browser_t *)~0)
6109 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
6114 for (d = SCPrefBrowseDomains; d; d=d->next)
6115 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6116 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6119 for (b = LocalDomainEnumRecords; b; b=b->next)
6120 if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
6121 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
6123 for (d = AutoBrowseDomains; d; d=d->next)
6124 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6125 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6127 for (d = AutoRegistrationDomains; d; d=d->next)
6128 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6129 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
6131 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6133 mDNSlocal int send_msg(request_state *const req)
6135 reply_state *const rep = req->replies; // Send the first waiting reply
6138 ConvertHeaderBytes(rep->mhdr);
6139 nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
6140 ConvertHeaderBytes(rep->mhdr);
6144 if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
6147 #if !defined(PLATFORM_NO_EPIPE)
6148 if (dnssd_errno == EPIPE)
6149 return(req->ts = t_terminated);
6153 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
6154 rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
6159 rep->nwriten += nwriten;
6160 return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
6163 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
6165 mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
6166 request_state **req = &all_requests;
6170 request_state *const r = *req;
6172 if (r->terminate == resolve_termination_callback)
6173 if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
6175 r->u.resolve.ReportTime = 0;
6176 // if client received results and resolve still active
6177 if (r->u.resolve.txt && r->u.resolve.srv)
6178 LogMsgNoIdent("Client application PID[%d](%s) has received results for DNSServiceResolve(%##s) yet remains active over two minutes.", r->process_id, r->pid_name, r->u.resolve.qsrv.qname.c);
6181 // Note: Only primary req's have reply lists, not subordinate req's.
6182 while (r->replies) // Send queued replies
6184 transfer_state result;
6185 if (r->replies->next)
6186 r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
6187 result = send_msg(r); // Returns t_morecoming if buffer full because client is not reading
6188 if (result == t_complete)
6190 reply_state *fptr = r->replies;
6191 r->replies = r->replies->next;
6192 freeL("reply_state/udsserver_idle", fptr);
6193 r->time_blocked = 0; // reset failure counter after successful send
6194 r->unresponsiveness_reports = 0;
6197 else if (result == t_terminated)
6199 LogInfo("%3d: Could not write data to client PID[%d](%s) because connection is terminated by the client", r->sd, r->process_id, r->pid_name);
6202 else if (result == t_error)
6204 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r->sd, r->process_id, r->pid_name);
6211 if (r->replies) // If we failed to send everything, check our time_blocked timer
6213 if (nextevent - now > mDNSPlatformOneSecond)
6214 nextevent = now + mDNSPlatformOneSecond;
6216 if (mDNSStorage.SleepState != SleepState_Awake)
6217 r->time_blocked = 0;
6218 else if (!r->time_blocked)
6219 r->time_blocked = NonZeroTime(now);
6220 else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
6223 struct reply_state *x = r->replies;
6229 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
6230 r->sd, r->process_id, r->pid_name, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
6231 if (++r->unresponsiveness_reports >= 60)
6233 LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r->sd, r->process_id, r->pid_name);
6240 if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
6242 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
6244 freeL("request_state/udsserver_idle", r);
6252 struct CompileTimeAssertionChecks_uds_daemon
6254 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
6255 // other overly-large structures instead of having a pointer to them, can inadvertently
6256 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
6257 char sizecheck_request_state [(sizeof(request_state) <= 2954) ? 1 : -1];
6258 char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <= 60) ? 1 : -1];
6259 char sizecheck_service_instance [(sizeof(service_instance) <= 6552) ? 1 : -1];
6260 char sizecheck_browser_t [(sizeof(browser_t) <= 1202) ? 1 : -1];
6261 char sizecheck_reply_hdr [(sizeof(reply_hdr) <= 12) ? 1 : -1];
6262 char sizecheck_reply_state [(sizeof(reply_state) <= 64) ? 1 : -1];
6266 #include "../unittests/uds_daemon_ut.c"