xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSShared/uds_daemon.c (revision a92282e44f968185a6bba094d1e5fece2da819cf)
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2003-2018 Apple Inc. All rights reserved.
4  *
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17 
18 #if defined(_WIN32)
19 #include <process.h>
20 #define usleep(X) Sleep(((X)+999)/1000)
21 #else
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
26 #include <sys/time.h>
27 #include <sys/resource.h>
28 #endif
29 
30 #include <stdlib.h>
31 #include <stdio.h>
32 
33 #include "mDNSEmbeddedAPI.h"
34 #include "DNSCommon.h"
35 #include "uDNS.h"
36 #include "uds_daemon.h"
37 #include "dns_sd_internal.h"
38 
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;
43 
44 //  Control enabling ioptimistic DNS
45 mDNSBool EnableAllowExpired = mDNStrue;
46 
47 // Apple-specific functionality, not required for other platforms
48 #if APPLE_OSX_mDNSResponder
49 #include <sys/ucred.h>
50 #ifndef PID_FILE
51 #define PID_FILE ""
52 #endif
53 #endif
54 
55 #ifdef LOCAL_PEEREPID
56 #include <sys/un.h>         // for LOCAL_PEEREPID
57 #include <sys/socket.h>     // for getsockopt
58 #include <sys/proc_info.h>  // for struct proc_bsdshortinfo
59 #include <libproc.h>        // for proc_pidinfo()
60 #endif //LOCAL_PEEREPID
61 
62 #ifdef UNIT_TEST
63 #include "unittest.h"
64 #endif
65 
66 #if APPLE_OSX_mDNSResponder
67 #include <WebFilterDNS/WebFilterDNS.h>
68 #include "BLE.h"
69 
70 #if !NO_WCF
71 
72 int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
73 int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
74 int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
75 
76 // Do we really need to define a macro for "if"?
77 #define CHECK_WCF_FUNCTION(X) if (X)
78 #endif // ! NO_WCF
79 
80 #else
81 #define NO_WCF 1
82 #endif // APPLE_OSX_mDNSResponder
83 
84 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
85 // User IDs for real user accounts start at 501 and count up from there
86 #define SystemUID(X) ((X) <= 500)
87 
88 #define MAX_ANONYMOUS_DATA      256
89 
90 // ***************************************************************************
91 #if COMPILER_LIKES_PRAGMA_MARK
92 #pragma mark -
93 #pragma mark - Globals
94 #endif
95 
96 // globals
97 mDNSexport mDNS mDNSStorage;
98 mDNSexport const char ProgramName[] = "mDNSResponder";
99 
100 #if defined(USE_TCP_LOOPBACK)
101 static char* boundPath = NULL;
102 #else
103 static char* boundPath = MDNS_UDS_SERVERPATH;
104 #endif
105 #if DEBUG
106 #define MDNS_UDS_SERVERPATH_DEBUG "/var/tmp/mDNSResponder"
107 #endif
108 static dnssd_sock_t listenfd = dnssd_InvalidSocket;
109 static request_state *all_requests = NULL;
110 #ifdef LOCAL_PEEREPID
111 struct proc_bsdshortinfo proc;
112 #endif //LOCAL_PEEREPID
113 mDNSlocal void set_peer_pid(request_state *request);
114 mDNSlocal void LogMcastClientInfo(request_state *req);
115 mDNSlocal void GetMcastClients(request_state *req);
116 static mDNSu32 mcount;     // tracks the current active mcast operations for McastLogging
117 static mDNSu32 i_mcount;   // sets mcount when McastLogging is enabled(PROF signal is sent)
118 static mDNSu32 n_mrecords; // tracks the current active mcast records for McastLogging
119 static mDNSu32 n_mquests;  // tracks the current active mcast questions for McastLogging
120 
121 
122 #if TARGET_OS_EMBEDDED
123 mDNSu32 curr_num_regservices = 0;
124 mDNSu32 max_num_regservices = 0;
125 #endif
126 
127 
128 // Note asymmetry here between registration and browsing.
129 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
130 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
131 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
132 // 1. SCPrefBrowseDomains (local configuration data)
133 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
134 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
135 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
136 
137 mDNSexport DNameListElem *AutoRegistrationDomains;  // Domains where we automatically register for empty-string registrations
138 
139 static DNameListElem *SCPrefBrowseDomains;          // List of automatic browsing domains read from SCPreferences for "empty string" browsing
140 static ARListElem    *LocalDomainEnumRecords;       // List of locally-generated PTR records to augment those we learn from the network
141 mDNSexport DNameListElem *AutoBrowseDomains;        // List created from those local-only PTR records plus records we get from the network
142 
143 #define MSG_PAD_BYTES 5     // pad message buffer (read from client) with n zero'd bytes to guarantee
144                             // n get_string() calls w/o buffer overrun
145 // initialization, setup/teardown functions
146 
147 // If a platform specifies its own PID file name, we use that
148 #ifndef PID_FILE
149 #define PID_FILE "/var/run/mDNSResponder.pid"
150 #endif
151 
152 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen);
153 
154 // ***************************************************************************
155 #if COMPILER_LIKES_PRAGMA_MARK
156 #pragma mark -
157 #pragma mark - General Utility Functions
158 #endif
159 
160 mDNSlocal void FatalError(char *errmsg)
161 {
162     LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
163     abort();
164 }
165 
166 mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
167 {
168     mDNSu32 ret;
169     char *data = (char*) &ret;
170     put_uint32(l, &data);
171     return ret;
172 }
173 
174 // hack to search-replace perror's to LogMsg's
175 mDNSlocal void my_perror(char *errmsg)
176 {
177     LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
178 }
179 
180 // Throttled version of my_perror: Logs once every 250 msgs
181 mDNSlocal void my_throttled_perror(char *err_msg)
182 {
183     static int uds_throttle_count = 0;
184     if ((uds_throttle_count++ % 250) == 0)
185         my_perror(err_msg);
186 }
187 
188 // LogMcastQuestion/LogMcastQ should be called after the DNSQuestion struct is initialized(especially for q->TargetQID)
189 // Hence all calls are made after mDNS_StartQuery()/mDNS_StopQuery()/mDNS_StopBrowse() is called.
190 mDNSlocal void LogMcastQuestion(const DNSQuestion *const q, request_state *req, q_state status)
191 {
192     if (mDNSOpaque16IsZero(q->TargetQID)) // Check for Mcast Query
193     {
194         mDNSBool mflag = mDNSfalse;
195         if (status == q_start)
196         {
197             if (++mcount == 1)
198                 mflag = mDNStrue;
199         }
200         else
201         {
202             mcount--;
203         }
204         LogMcast("%s: %##s  (%s) (%s)  Client(%d)[%s]", status ? "+Question" : "-Question", q->qname.c, DNSTypeName(q->qtype),
205                  q->InterfaceID == mDNSInterface_LocalOnly ? "lo" :
206                  q->InterfaceID == mDNSInterface_P2P ? "p2p" :
207                  q->InterfaceID == mDNSInterface_BLE ? "BLE" :
208                  q->InterfaceID == mDNSInterface_Any ? "any" : InterfaceNameForID(&mDNSStorage, q->InterfaceID),
209                  req->process_id, req->pid_name);
210         LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
211     }
212     return;
213 }
214 
215 // LogMcastService/LogMcastS should be called after the AuthRecord struct is initialized
216 // Hence all calls are made after mDNS_Register()/ just before mDNS_Deregister()
217 mDNSlocal void LogMcastService(const AuthRecord *const ar, request_state *req, reg_state status)
218 {
219     if (!AuthRecord_uDNS(ar)) // Check for Mcast Service
220     {
221         mDNSBool mflag = mDNSfalse;
222         if (status == reg_start)
223         {
224             if (++mcount == 1)
225                 mflag = mDNStrue;
226         }
227         else
228         {
229             mcount--;
230         }
231         LogMcast("%s: %##s  (%s)  (%s)  Client(%d)[%s]", status ? "+Service" : "-Service", ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype),
232                  ar->resrec.InterfaceID == mDNSInterface_LocalOnly ? "lo" :
233                  ar->resrec.InterfaceID == mDNSInterface_P2P ? "p2p" :
234                  ar->resrec.InterfaceID == mDNSInterface_BLE ? "BLE" :
235                  ar->resrec.InterfaceID == mDNSInterface_Any ? "all" : InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID),
236                  req->process_id, req->pid_name);
237         LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
238     }
239     return;
240 }
241 
242 // For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
243 mDNSexport void LogMcastStateInfo(mDNSBool mflag, mDNSBool start, mDNSBool mstatelog)
244 {
245     mDNS *const m = &mDNSStorage;
246     if (!mstatelog)
247     {
248         if (!all_requests)
249         {
250             LogMcastNoIdent("<None>");
251         }
252         else
253         {
254             request_state *req, *r;
255             for (req = all_requests; req; req=req->next)
256             {
257                 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
258                 {
259                     for (r = all_requests; r && r != req; r=r->next)
260                         if (r == req->primary)
261                             goto foundpar;
262                 }
263                 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
264                 GetMcastClients(req);
265     foundpar:;
266             }
267             LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords, n_mquests);
268             n_mrecords = n_mquests = 0; // Reset the values
269         }
270     }
271     else
272     {
273         static mDNSu32 i_mpktnum;
274         i_mcount = 0;
275         if (start)
276             mcount = 0;
277         // mcount is initialized to 0 when the PROF signal is sent since mcount could have
278         // wrong value if MulticastLogging is disabled and then re-enabled
279         LogMcastNoIdent("--- START MCAST STATE LOG ---");
280         if (!all_requests)
281         {
282             mcount = 0;
283             LogMcastNoIdent("<None>");
284         }
285         else
286         {
287             request_state *req, *r;
288             for (req = all_requests; req; req=req->next)
289             {
290                 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
291                 {
292                     for (r = all_requests; r && r != req; r=r->next)
293                         if (r == req->primary)
294                             goto foundparent;
295                     LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req->sd);
296                 }
297                 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
298                 LogMcastClientInfo(req);
299     foundparent:;
300             }
301             if(!mcount) // To initially set mcount
302                 mcount = i_mcount;
303         }
304         if (mcount == 0)
305         {
306             i_mpktnum = m->MPktNum;
307             LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount, i_mpktnum);
308         }
309         if (mflag)
310             LogMcastNoIdent("--- MCOUNT[%d]: CMPKTNUM[%d] - IMPKTNUM[%d] = [%d]PKTS ---", mcount, m->MPktNum, i_mpktnum, (m->MPktNum - i_mpktnum));
311         LogMcastNoIdent("--- END MCAST STATE LOG ---");
312     }
313 }
314 
315 mDNSlocal void abort_request(request_state *req)
316 {
317     if (req->terminate == (req_termination_fn) ~0)
318     { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
319 
320     // First stop whatever mDNSCore operation we were doing
321     // If this is actually a shared connection operation, then its req->terminate function will scan
322     // the all_requests list and terminate any subbordinate operations sharing this file descriptor
323     if (req->terminate) req->terminate(req);
324 
325     if (!dnssd_SocketValid(req->sd))
326     { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d",     req, req->sd);        return; }
327 
328     // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
329     if (!req->primary)
330     {
331         if (req->errsd != req->sd) LogDebug("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
332         else LogDebug("%3d: Removing FD", req->sd);
333         udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data);       // Note: This also closes file descriptor req->sd for us
334         if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
335 
336         while (req->replies)    // free pending replies
337         {
338             reply_state *ptr = req->replies;
339             req->replies = req->replies->next;
340             freeL("reply_state (abort)", ptr);
341         }
342     }
343 
344     // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
345 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
346     // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
347     // for detecting when the memory for an object is inadvertently freed while the object is still on some list
348     req->sd = req->errsd = -2;
349 #else
350     req->sd = req->errsd = dnssd_InvalidSocket;
351 #endif
352     // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
353     req->terminate = (req_termination_fn) ~0;
354 }
355 
356 #if DEBUG
357 mDNSexport void SetDebugBoundPath(void)
358 {
359 #if !defined(USE_TCP_LOOPBACK)
360     boundPath = MDNS_UDS_SERVERPATH_DEBUG;
361 #endif
362 }
363 
364 mDNSexport int IsDebugSocketInUse(void)
365 {
366 #if !defined(USE_TCP_LOOPBACK)
367     return !strcmp(boundPath, MDNS_UDS_SERVERPATH_DEBUG);
368 #else
369     return mDNSfalse;
370 #endif
371 }
372 #endif
373 
374 mDNSlocal void AbortUnlinkAndFree(request_state *req)
375 {
376     request_state **p = &all_requests;
377     abort_request(req);
378     while (*p && *p != req) p=&(*p)->next;
379     if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
380     else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
381 }
382 
383 mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
384 {
385     reply_state *reply;
386 
387     if ((unsigned)datalen < sizeof(reply_hdr))
388     {
389         LogMsg("ERROR: create_reply - data length less than length of required fields");
390         return NULL;
391     }
392 
393     reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
394     if (!reply) FatalError("ERROR: malloc");
395 
396     reply->next     = mDNSNULL;
397     reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
398     reply->nwriten  = 0;
399 
400     reply->mhdr->version        = VERSION;
401     reply->mhdr->datalen        = (mDNSu32)datalen;
402     reply->mhdr->ipc_flags      = 0;
403     reply->mhdr->op             = op;
404     reply->mhdr->client_context = request->hdr.client_context;
405     reply->mhdr->reg_index      = 0;
406 
407     return reply;
408 }
409 
410 // Append a reply to the list in a request object
411 // If our request is sharing a connection, then we append our reply_state onto the primary's list
412 // If the request does not want asynchronous replies, then the reply is freed instead of being appended to any list.
413 mDNSlocal void append_reply(request_state *req, reply_state *rep)
414 {
415     request_state *r;
416     reply_state **ptr;
417 
418     if (req->no_reply)
419     {
420         freeL("reply_state/append_reply", rep);
421         return;
422     }
423 
424     r = req->primary ? req->primary : req;
425     ptr = &r->replies;
426     while (*ptr) ptr = &(*ptr)->next;
427     *ptr = rep;
428     rep->next = NULL;
429 }
430 
431 // Generates a response message giving name, type, domain, plus interface index,
432 // suitable for a browse result or service registration result.
433 // On successful completion rep is set to point to a malloc'd reply_state struct
434 mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
435                                       request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
436 {
437     domainlabel name;
438     domainname type, dom;
439     *rep = NULL;
440     if (!DeconstructServiceName(servicename, &name, &type, &dom))
441         return kDNSServiceErr_Invalid;
442     else
443     {
444         char namestr[MAX_DOMAIN_LABEL+1];
445         char typestr[MAX_ESCAPED_DOMAIN_NAME];
446         char domstr [MAX_ESCAPED_DOMAIN_NAME];
447         int len;
448         char *data;
449 
450         ConvertDomainLabelToCString_unescaped(&name, namestr);
451         ConvertDomainNameToCString(&type, typestr);
452         ConvertDomainNameToCString(&dom, domstr);
453 
454         // Calculate reply data length
455         len = sizeof(DNSServiceFlags);
456         len += sizeof(mDNSu32);  // if index
457         len += sizeof(DNSServiceErrorType);
458         len += (int) (strlen(namestr) + 1);
459         len += (int) (strlen(typestr) + 1);
460         len += (int) (strlen(domstr) + 1);
461 
462         // Build reply header
463         *rep = create_reply(op, len, request);
464         (*rep)->rhdr->flags = dnssd_htonl(flags);
465         (*rep)->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
466         (*rep)->rhdr->error = dnssd_htonl(err);
467 
468         // Build reply body
469         data = (char *)&(*rep)->rhdr[1];
470         put_string(namestr, &data);
471         put_string(typestr, &data);
472         put_string(domstr, &data);
473 
474         return mStatus_NoError;
475     }
476 }
477 
478 mDNSlocal void GenerateBrowseReply(const domainname *const servicename, const mDNSInterfaceID id,
479                                               request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
480 {
481     char namestr[MAX_DOMAIN_LABEL+1];
482     char typestr[MAX_ESCAPED_DOMAIN_NAME];
483     static const char domstr[] = ".";
484     int len;
485     char *data;
486 
487     *rep = NULL;
488 
489     // 1. Put first label in namestr
490     ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
491 
492     // 2. Put second label and "local" into typestr
493     mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
494 
495     // Calculate reply data length
496     len = sizeof(DNSServiceFlags);
497     len += sizeof(mDNSu32);  // if index
498     len += sizeof(DNSServiceErrorType);
499     len += (int) (strlen(namestr) + 1);
500     len += (int) (strlen(typestr) + 1);
501     len += (int) (strlen(domstr) + 1);
502 
503     // Build reply header
504     *rep = create_reply(op, len, request);
505     (*rep)->rhdr->flags = dnssd_htonl(flags);
506     (*rep)->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
507     (*rep)->rhdr->error = dnssd_htonl(err);
508 
509     // Build reply body
510     data = (char *)&(*rep)->rhdr[1];
511     put_string(namestr, &data);
512     put_string(typestr, &data);
513     put_string(domstr, &data);
514 }
515 
516 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
517 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
518 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
519 mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
520 {
521     DNSServiceFlags flags  = get_flags(&request->msgptr, request->msgend);
522     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
523     char name[256];
524     int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
525     mDNSu16 type    = get_uint16(&request->msgptr, request->msgend);
526     mDNSu16     class   = get_uint16(&request->msgptr, request->msgend);
527     mDNSu16 rdlen   = get_uint16(&request->msgptr, request->msgend);
528     const char *rdata   = get_rdata (&request->msgptr, request->msgend, rdlen);
529     mDNSu32 ttl   = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
530     size_t storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
531     AuthRecord *rr;
532     mDNSInterfaceID InterfaceID;
533     AuthRecType artype;
534 
535     request->flags = flags;
536     request->interfaceIndex = interfaceIndex;
537 
538     if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
539 
540     if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
541 
542     if (validate_flags &&
543         !((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
544         !((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
545     {
546         LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
547         return NULL;
548     }
549 
550     rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
551     if (!rr) FatalError("ERROR: malloc");
552 
553     InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
554     if (InterfaceID == mDNSInterface_LocalOnly)
555         artype = AuthRecordLocalOnly;
556     else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
557         artype = AuthRecordP2P;
558     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
559             && (flags & kDNSServiceFlagsIncludeAWDL))
560         artype = AuthRecordAnyIncludeAWDLandP2P;
561     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
562         artype = AuthRecordAnyIncludeP2P;
563     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
564         artype = AuthRecordAnyIncludeAWDL;
565     else
566         artype = AuthRecordAny;
567 
568     mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
569                              (mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
570 
571     if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
572     {
573         LogMsg("ERROR: bad name: %s", name);
574         freeL("AuthRecord/read_rr_from_ipc_msg", rr);
575         return NULL;
576     }
577 
578     if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
579     rr->resrec.rrclass = class;
580     rr->resrec.rdlength = rdlen;
581     rr->resrec.rdata->MaxRDLength = rdlen;
582     mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
583     if (GetTTL) rr->resrec.rroriginalttl = ttl;
584     rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
585     SetNewRData(&rr->resrec, mDNSNULL, 0);  // Sets rr->rdatahash for us
586     return rr;
587 }
588 
589 mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
590 {
591     domainlabel n;
592     domainname d, t;
593 
594     if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
595     if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
596     if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
597     if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
598     return 0;
599 }
600 
601 mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
602 {
603     int n = send(s, ptr, len, 0);
604     // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
605     // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
606     // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
607     if (n < len)
608         LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
609                s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
610 }
611 
612 #if 0
613 mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
614 {
615     const DNameListElem   *delem = mDNSNULL;
616     int bestDelta   = -1;                           // the delta of the best match, lower is better
617     int dLabels     = 0;
618     mDNSBool allow       = mDNSfalse;
619 
620     if (SystemUID(request->uid)) return mDNStrue;
621 
622     dLabels = CountLabels(d);
623     for (delem = doms; delem; delem = delem->next)
624     {
625         if (delem->uid)
626         {
627             int delemLabels = CountLabels(&delem->name);
628             int delta       = dLabels - delemLabels;
629             if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
630             {
631                 bestDelta = delta;
632                 allow = (allow || (delem->uid == request->uid));
633             }
634         }
635     }
636 
637     return bestDelta == -1 ? mDNStrue : allow;
638 }
639 #endif
640 
641 // ***************************************************************************
642 #if COMPILER_LIKES_PRAGMA_MARK
643 #pragma mark -
644 #pragma mark - external helpers
645 #endif
646 
647 mDNSexport mDNSBool callExternalHelpers(mDNSInterfaceID InterfaceID, const domainname *const domain, DNSServiceFlags flags)
648 {
649 #if APPLE_OSX_mDNSResponder
650 
651     // Only call D2D layer routines if request applies to a D2D interface and the domain is "local".
652     if (    (((InterfaceID == mDNSInterface_Any) && (flags & (kDNSServiceFlagsIncludeP2P | kDNSServiceFlagsIncludeAWDL | kDNSServiceFlagsAutoTrigger)))
653             || mDNSPlatformInterfaceIsD2D(InterfaceID) || (InterfaceID == mDNSInterface_BLE))
654         && IsLocalDomain(domain))
655     {
656         return mDNStrue;
657     }
658     else
659         return mDNSfalse;
660 
661 #else
662     (void) InterfaceID;
663     (void) domain;
664     (void) flags;
665 
666     return mDNSfalse;
667 #endif  // APPLE_OSX_mDNSResponder
668 }
669 
670 mDNSlocal void external_start_advertising_helper(service_instance *const instance)
671 {
672     AuthRecord *st = instance->subtypes;
673     ExtraResourceRecord *e;
674     int i;
675 
676     if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
677     {
678         LogInfo("external_start_advertising_helper: Not registering service with port number zero");
679         return;
680     }
681 
682     if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
683 
684     for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
685         external_start_advertising_service(&st[i].resrec, instance->request->flags);
686 
687     external_start_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
688     external_start_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
689 
690     external_start_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
691 
692     for (e = instance->srs.Extras; e; e = e->next)
693         external_start_advertising_service(&e->r.resrec, instance->request->flags);
694 
695     instance->external_advertise = mDNStrue;
696 }
697 
698 mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
699 {
700     AuthRecord *st = instance->subtypes;
701     ExtraResourceRecord *e;
702     int i;
703 
704     if (!instance->external_advertise) return;
705 
706     LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
707 
708     for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
709         external_stop_advertising_service(&st[i].resrec, instance->request->flags);
710 
711     external_stop_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
712     external_stop_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
713     external_stop_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
714 
715     for (e = instance->srs.Extras; e; e = e->next)
716         external_stop_advertising_service(&e->r.resrec, instance->request->flags);
717 
718     instance->external_advertise = mDNSfalse;
719 }
720 
721 // ***************************************************************************
722 #if COMPILER_LIKES_PRAGMA_MARK
723 #pragma mark -
724 #pragma mark - DNSServiceRegister
725 #endif
726 
727 mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
728 {
729     ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
730     (void)m;  // Unused
731 
732     if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
733 
734     LogInfo("     FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
735 
736     if (rr->resrec.rdata != &rr->rdatastorage)
737         freeL("Extra RData", rr->resrec.rdata);
738     freeL("ExtraResourceRecord/FreeExtraRR", extra);
739 }
740 
741 mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
742 {
743     ExtraResourceRecord *e = srv->srs.Extras, *tmp;
744 
745     external_stop_advertising_helper(srv);
746 
747     // clear pointers from parent struct
748     if (srv->request)
749     {
750         service_instance **p = &srv->request->u.servicereg.instances;
751         while (*p)
752         {
753             if (*p == srv) { *p = (*p)->next; break; }
754             p = &(*p)->next;
755         }
756     }
757 
758     while (e)
759     {
760         e->r.RecordContext = e;
761         tmp = e;
762         e = e->next;
763         FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
764     }
765 
766     if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
767         freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
768 
769     if (srv->subtypes)
770     {
771         freeL("ServiceSubTypes", srv->subtypes);
772         srv->subtypes = NULL;
773     }
774     if (srv->srs.AnonData)
775     {
776         freeL("Anonymous", (void *)srv->srs.AnonData);
777         srv->srs.AnonData = NULL;
778     }
779     freeL("service_instance", srv);
780 }
781 
782 // Count how many other service records we have locally with the same name, but different rdata.
783 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
784 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
785 mDNSexport int CountPeerRegistrations(ServiceRecordSet *const srs)
786 {
787     int count = 0;
788     ResourceRecord *r = &srs->RR_SRV.resrec;
789     AuthRecord *rr;
790 
791     for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
792         if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
793             count++;
794 
795     verbosedebugf("%d peer registrations for %##s", count, r->name->c);
796     return(count);
797 }
798 
799 mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
800 {
801     int count = 0;
802     AuthRecord *rr;
803     for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
804         if (rr->resrec.rrtype == kDNSType_SRV &&
805             mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
806             SameDomainName(rr->resrec.name, srv))
807             count++;
808     return(count);
809 }
810 
811 mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
812 {
813     reply_state *rep;
814     service_instance *instance = srs->ServiceContext;
815     if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
816         LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
817     else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
818 }
819 
820 // service registration callback performs three duties - frees memory for deregistered services,
821 // handles name conflicts, and delivers completed registration information to the client
822 mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
823 {
824     mStatus err;
825     mDNSBool SuppressError = mDNSfalse;
826     service_instance *instance;
827     reply_state         *rep;
828     (void)m; // Unused
829 
830     if (!srs)      { LogMsg("regservice_callback: srs is NULL %d",                 result); return; }
831 
832     instance = srs->ServiceContext;
833     if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
834 
835     // don't send errors up to client for wide-area, empty-string registrations
836     if (instance->request &&
837         instance->request->u.servicereg.default_domain &&
838         !instance->default_local)
839         SuppressError = mDNStrue;
840 
841     if (mDNS_LoggingEnabled)
842     {
843         const char *const fmt =
844             (result == mStatus_NoError)      ? "%s DNSServiceRegister(%##s, %u) REGISTERED"    :
845             (result == mStatus_MemFree)      ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED"  :
846             (result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
847             "%s DNSServiceRegister(%##s, %u) %s %d";
848         char prefix[16] = "---:";
849         if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
850         LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
851                      SuppressError ? "suppressed error" : "CALLBACK", result);
852     }
853 
854     if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
855 
856     if (result == mStatus_NoError)
857     {
858         if (instance->request->u.servicereg.allowremotequery)
859         {
860             ExtraResourceRecord *e;
861             srs->RR_ADV.AllowRemoteQuery = mDNStrue;
862             srs->RR_PTR.AllowRemoteQuery = mDNStrue;
863             srs->RR_SRV.AllowRemoteQuery = mDNStrue;
864             srs->RR_TXT.AllowRemoteQuery = mDNStrue;
865             for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
866         }
867 
868         if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
869             LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
870         else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
871 
872         if (callExternalHelpers(instance->request->u.servicereg.InterfaceID, &instance->domain, instance->request->flags))
873         {
874             LogInfo("regservice_callback: calling external_start_advertising_helper()");
875             external_start_advertising_helper(instance);
876         }
877         if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
878             RecordUpdatedNiceLabel(0);   // Successfully got new name, tell user immediately
879     }
880     else if (result == mStatus_MemFree)
881     {
882 #if TARGET_OS_EMBEDDED
883         curr_num_regservices--;
884 #endif
885         if (instance->request && instance->renameonmemfree)
886         {
887             external_stop_advertising_helper(instance);
888             instance->renameonmemfree = 0;
889             err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
890             if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
891             // error should never happen - safest to log and continue
892         }
893         else
894             unlink_and_free_service_instance(instance);
895     }
896     else if (result == mStatus_NameConflict)
897     {
898         if (instance->request->u.servicereg.autorename)
899         {
900             external_stop_advertising_helper(instance);
901             if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
902             {
903                 // On conflict for an autoname service, rename and reregister *all* autoname services
904                 IncrementLabelSuffix(&m->nicelabel, mDNStrue);
905                 mDNS_ConfigChanged(m);  // Will call back into udsserver_handle_configchange()
906             }
907             else    // On conflict for a non-autoname service, rename and reregister just that one service
908             {
909                 if (instance->clientnotified) SendServiceRemovalNotification(srs);
910                 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
911             }
912         }
913         else
914         {
915             if (!SuppressError)
916             {
917                 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
918                     LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
919                 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
920             }
921             unlink_and_free_service_instance(instance);
922         }
923     }
924     else        // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
925     {
926         if (!SuppressError)
927         {
928             if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
929                 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
930             else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
931         }
932     }
933 }
934 
935 mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
936 {
937     (void)m; // Unused
938     if (!rr->RecordContext)     // parent struct already freed by termination callback
939     {
940         if (result == mStatus_NoError)
941             LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
942         else
943         {
944             if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
945 
946             // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
947             // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
948             // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
949             // to free the latest rdata for which the update_callback was never called with.
950             if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
951             freeL("AuthRecord/regrecord_callback", rr);
952         }
953     }
954     else
955     {
956         registered_record_entry *re = rr->RecordContext;
957         request_state *request = re->request;
958 
959         if (mDNS_LoggingEnabled)
960         {
961             char *fmt = (result == mStatus_NoError)      ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED"    :
962                         (result == mStatus_MemFree)      ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED"  :
963                         (result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
964                         "%3d: DNSServiceRegisterRecord(%u %s) %d";
965             LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
966         }
967 
968         if (result != mStatus_MemFree)
969         {
970             int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
971             reply_state *reply = create_reply(reg_record_reply_op, len, request);
972             reply->mhdr->client_context = re->regrec_client_context;
973             reply->rhdr->flags = dnssd_htonl(0);
974             reply->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
975             reply->rhdr->error = dnssd_htonl(result);
976             append_reply(request, reply);
977         }
978 
979         if (result)
980         {
981             // If this is a callback to a keepalive record, do not free it.
982             if (result == mStatus_BadStateErr)
983             {
984                 LogInfo("regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.");
985             }
986             else
987             {
988                 // unlink from list, free memory
989                 registered_record_entry **ptr = &request->u.reg_recs;
990                 while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
991                 if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
992                 *ptr = (*ptr)->next;
993                 freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
994                 freeL("registered_record_entry regrecord_callback", re);
995              }
996         }
997         else
998         {
999             if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
1000 
1001             if (callExternalHelpers(re->origInterfaceID, &rr->namestorage, request->flags))
1002             {
1003                 LogInfo("regrecord_callback: calling external_start_advertising_service");
1004                 external_start_advertising_service(&rr->resrec, request->flags);
1005                 re->external_advertise = mDNStrue;
1006             }
1007         }
1008     }
1009 }
1010 
1011 // set_peer_pid() is called after mem is allocated for each new request in NewRequest()
1012 // This accounts for 2 places (connect_callback, request_callback)
1013 mDNSlocal void set_peer_pid(request_state *request)
1014 {
1015 #ifdef LOCAL_PEEREPID
1016     pid_t           p    = (pid_t) -1;
1017     socklen_t       len  = sizeof(p);
1018 #endif
1019 
1020     request->pid_name[0] = '\0';
1021     request->process_id  = -1;
1022 #ifdef LOCAL_PEEREPID
1023     if (request->sd < 0)
1024         return;
1025     // to extract the effective pid value
1026     if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &p, &len) != 0)
1027         return;
1028     // to extract the process name from the pid value
1029     if (proc_pidinfo(p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
1030         return;
1031     mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
1032     request->process_id = p;
1033     debugf("set_peer_pid: Client PEEREPID is %d %s", p, request->pid_name);
1034 #else   // !LOCAL_PEEREPID
1035     LogInfo("set_peer_pid: Not Supported on this version of OS");
1036     if (request->sd < 0)
1037         return;
1038 #endif  // LOCAL_PEEREPID
1039 }
1040 
1041 mDNSlocal void connection_termination(request_state *request)
1042 {
1043     // When terminating a shared connection, we need to scan the all_requests list
1044     // and terminate any subbordinate operations sharing this file descriptor
1045     request_state **req = &all_requests;
1046 
1047     LogOperation("%3d: DNSServiceCreateConnection STOP PID[%d](%s)", request->sd, request->process_id, request->pid_name);
1048 
1049     while (*req)
1050     {
1051         if ((*req)->primary == request)
1052         {
1053             // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1054             request_state *tmp = *req;
1055             if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d",                  tmp, tmp->sd);
1056             if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
1057             abort_request(tmp);
1058             *req = tmp->next;
1059             freeL("request_state/connection_termination", tmp);
1060         }
1061         else
1062             req = &(*req)->next;
1063     }
1064 
1065     while (request->u.reg_recs)
1066     {
1067         registered_record_entry *ptr = request->u.reg_recs;
1068         LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP PID[%d](%s)", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec), request->process_id, request->pid_name);
1069         request->u.reg_recs = request->u.reg_recs->next;
1070         ptr->rr->RecordContext = NULL;
1071         if (ptr->external_advertise)
1072         {
1073             ptr->external_advertise = mDNSfalse;
1074             external_stop_advertising_service(&ptr->rr->resrec, request->flags);
1075         }
1076         LogMcastS(ptr->rr, request, reg_stop);
1077         mDNS_Deregister(&mDNSStorage, ptr->rr);     // Will free ptr->rr for us
1078         freeL("registered_record_entry/connection_termination", ptr);
1079     }
1080 }
1081 
1082 mDNSlocal void handle_cancel_request(request_state *request)
1083 {
1084     request_state **req = &all_requests;
1085     LogDebug("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
1086     while (*req)
1087     {
1088         if ((*req)->primary == request &&
1089             (*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1090             (*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
1091         {
1092             // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1093             request_state *tmp = *req;
1094             abort_request(tmp);
1095             *req = tmp->next;
1096             freeL("request_state/handle_cancel_request", tmp);
1097         }
1098         else
1099             req = &(*req)->next;
1100     }
1101 }
1102 
1103 mDNSlocal mStatus handle_regrecord_request(request_state *request)
1104 {
1105     mStatus err = mStatus_BadParamErr;
1106     AuthRecord *rr;
1107 
1108     if (request->terminate != connection_termination)
1109     { LogMsg("%3d: DNSServiceRegisterRecord(not a shared connection ref)", request->sd); return(err); }
1110 
1111     rr = read_rr_from_ipc_msg(request, 1, 1);
1112     if (rr)
1113     {
1114         registered_record_entry *re;
1115         // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1116         // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1117         if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
1118             rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
1119                                                    rr->resrec.rrtype == kDNSType_CNAME))
1120         {
1121             freeL("AuthRecord/handle_regrecord_request", rr);
1122             return (mStatus_BadParamErr);
1123         }
1124         // allocate registration entry, link into list
1125         re = mallocL("registered_record_entry", sizeof(registered_record_entry));
1126         if (!re)
1127             FatalError("ERROR: malloc");
1128         re->key                   = request->hdr.reg_index;
1129         re->rr                    = rr;
1130         re->regrec_client_context = request->hdr.client_context;
1131         re->request               = request;
1132         re->external_advertise    = mDNSfalse;
1133         rr->RecordContext         = re;
1134         rr->RecordCallback        = regrecord_callback;
1135 
1136         re->origInterfaceID = rr->resrec.InterfaceID;
1137         if (rr->resrec.InterfaceID == mDNSInterface_P2P)
1138             rr->resrec.InterfaceID = mDNSInterface_Any;
1139 #if 0
1140         if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError);
1141 #endif
1142         if (rr->resrec.rroriginalttl == 0)
1143             rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);
1144 
1145         LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START PID[%d](%s)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec),
1146                      request->process_id, request->pid_name);
1147 
1148         err = mDNS_Register(&mDNSStorage, rr);
1149         if (err)
1150         {
1151             LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec), err);
1152             freeL("registered_record_entry", re);
1153             freeL("registered_record_entry/AuthRecord", rr);
1154         }
1155         else
1156         {
1157             LogMcastS(rr, request, reg_start);
1158             re->next = request->u.reg_recs;
1159             request->u.reg_recs = re;
1160         }
1161     }
1162     return(err);
1163 }
1164 
1165 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);
1166 
1167 mDNSlocal void regservice_termination_callback(request_state *request)
1168 {
1169     if (!request)
1170     {
1171         LogMsg("regservice_termination_callback context is NULL");
1172         return;
1173     }
1174     while (request->u.servicereg.instances)
1175     {
1176         service_instance *p = request->u.servicereg.instances;
1177         request->u.servicereg.instances = request->u.servicereg.instances->next;
1178         // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1179         LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP PID[%d](%s)", request->sd, p->srs.RR_SRV.resrec.name->c,
1180                      mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port), request->process_id, request->pid_name);
1181 
1182         external_stop_advertising_helper(p);
1183 
1184         // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1185         // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1186         // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1187         // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1188         // because by then we might have already freed p
1189         p->request = NULL;
1190         LogMcastS(&p->srs.RR_SRV, request, reg_stop);
1191         if (mDNS_DeregisterService(&mDNSStorage, &p->srs))
1192         {
1193             unlink_and_free_service_instance(p);
1194             // Don't touch service_instance *p after this -- it's likely to have been freed already
1195         }
1196     }
1197     if (request->u.servicereg.txtdata)
1198     {
1199         freeL("service_info txtdata", request->u.servicereg.txtdata);
1200         request->u.servicereg.txtdata = NULL;
1201     }
1202     if (request->u.servicereg.autoname)
1203     {
1204         // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1205         request->u.servicereg.autoname = mDNSfalse;
1206         UpdateDeviceInfoRecord(&mDNSStorage);
1207     }
1208 }
1209 
1210 mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
1211 {
1212     request_state *req;
1213     for (req = all_requests; req; req = req->next)
1214         if (req->primary == request &&
1215             req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1216             req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
1217     return(request);
1218 }
1219 
1220 mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl)
1221 {
1222     ServiceRecordSet *srs = &instance->srs;
1223     mStatus result;
1224     size_t size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1225     ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
1226     if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1227 
1228     mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord));  // OK if oversized rdata not zero'd
1229     extra->r.resrec.rrtype = rrtype;
1230     extra->r.rdatastorage.MaxRDLength = (mDNSu16) size;
1231     extra->r.resrec.rdlength = rdlen;
1232     mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen);
1233     // use InterfaceID value from DNSServiceRegister() call that created the original service
1234     extra->r.resrec.InterfaceID = request->u.servicereg.InterfaceID;
1235 
1236     result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl, request->flags);
1237     if (result)
1238     {
1239         freeL("ExtraResourceRecord/add_record_to_service", extra);
1240         return result;
1241     }
1242     LogMcastS(&srs->RR_PTR, request, reg_start);
1243 
1244     extra->ClientID = request->hdr.reg_index;
1245     if (   instance->external_advertise
1246            && callExternalHelpers(request->u.servicereg.InterfaceID, &instance->domain, request->flags))
1247     {
1248         LogInfo("add_record_to_service: calling external_start_advertising_service");
1249         external_start_advertising_service(&extra->r.resrec, request->flags);
1250     }
1251     return result;
1252 }
1253 
1254 mDNSlocal mStatus handle_add_request(request_state *request)
1255 {
1256     service_instance *i;
1257     mStatus result = mStatus_UnknownErr;
1258     DNSServiceFlags flags  = get_flags (&request->msgptr, request->msgend);
1259     mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend);
1260     mDNSu16 rdlen  = get_uint16(&request->msgptr, request->msgend);
1261     const char     *rdata  = get_rdata (&request->msgptr, request->msgend, rdlen);
1262     mDNSu32 ttl    = get_uint32(&request->msgptr, request->msgend);
1263     if (!ttl) ttl = DefaultTTLforRRType(rrtype);
1264     (void)flags; // Unused
1265 
1266     if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1267 
1268     // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1269     if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1270 
1271     if (request->terminate != regservice_termination_callback)
1272     { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1273 
1274     // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1275     // in the application. See radar://9165807.
1276     if (mDNSIPPortIsZero(request->u.servicereg.port))
1277     { LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1278 
1279     LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d) PID[%d](%s)", request->sd, flags,
1280                  (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen,
1281                  request->process_id, request->pid_name);
1282 
1283     for (i = request->u.servicereg.instances; i; i = i->next)
1284     {
1285         result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
1286         if (result && i->default_local) break;
1287         else result = mStatus_NoError;  // suppress non-local default errors
1288     }
1289 
1290     return(result);
1291 }
1292 
1293 mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
1294 {
1295     mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
1296     (void)m; // Unused
1297 
1298     // There are three cases.
1299     //
1300     // 1. We have updated the primary TXT record of the service
1301     // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1302     // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1303     //
1304     // external_advertise is set if we have advertised at least once during the initial addition
1305     // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1306     // checks during the first time and hence we don't do any checks here
1307     if (external_advertise)
1308     {
1309         ResourceRecord ext = rr->resrec;
1310         DNSServiceFlags flags = deriveD2DFlagsFromAuthRecType(rr->ARType);
1311 
1312         if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
1313         SetNewRData(&ext, oldrd, oldrdlen);
1314         external_stop_advertising_service(&ext, flags);
1315         LogInfo("update_callback: calling external_start_advertising_service");
1316         external_start_advertising_service(&rr->resrec, flags);
1317     }
1318 exit:
1319     if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
1320 }
1321 
1322 mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl, const mDNSBool *const external_advertise)
1323 {
1324     mStatus result;
1325     const size_t rdsize = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1326     RData *newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize);
1327     if (!newrd) FatalError("ERROR: malloc");
1328     newrd->MaxRDLength = (mDNSu16) rdsize;
1329     mDNSPlatformMemCopy(&newrd->u, rdata, rdlen);
1330 
1331     // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1332     // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1333     // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1334     if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }
1335 
1336     if (external_advertise) rr->UpdateContext = (void *)external_advertise;
1337 
1338     result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback);
1339     if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, rr)); freeL("RData/update_record", newrd); }
1340     return result;
1341 }
1342 
1343 mDNSlocal mStatus handle_update_request(request_state *request)
1344 {
1345     const ipc_msg_hdr *const hdr = &request->hdr;
1346     mStatus result = mStatus_BadReferenceErr;
1347     service_instance *i;
1348     AuthRecord *rr = NULL;
1349 
1350     // get the message data
1351     DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);  // flags unused
1352     mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1353     const char     *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1354     mDNSu32 ttl   = get_uint32(&request->msgptr, request->msgend);
1355     (void)flags; // Unused
1356 
1357     if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1358 
1359     // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1360     if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1361 
1362     if (request->terminate == connection_termination)
1363     {
1364         // update an individually registered record
1365         registered_record_entry *reptr;
1366         for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
1367         {
1368             if (reptr->key == hdr->reg_index)
1369             {
1370                 result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise);
1371                 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)",
1372                              request->sd, reptr->rr->resrec.name->c, reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>",
1373                              request->process_id, request->pid_name);
1374                 goto end;
1375             }
1376         }
1377         result = mStatus_BadReferenceErr;
1378         goto end;
1379     }
1380 
1381     if (request->terminate != regservice_termination_callback)
1382     { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1383 
1384     // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1385     if (mDNSIPPortIsZero(request->u.servicereg.port))
1386     { LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1387 
1388     // update the saved off TXT data for the service
1389     if (hdr->reg_index == TXT_RECORD_INDEX)
1390     {
1391         if (request->u.servicereg.txtdata)
1392         { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
1393         if (rdlen > 0)
1394         {
1395             request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
1396             if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
1397             mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
1398         }
1399         request->u.servicereg.txtlen = rdlen;
1400     }
1401 
1402     // update a record from a service record set
1403     for (i = request->u.servicereg.instances; i; i = i->next)
1404     {
1405         if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
1406         else
1407         {
1408             ExtraResourceRecord *e;
1409             for (e = i->srs.Extras; e; e = e->next)
1410                 if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
1411         }
1412 
1413         if (!rr) { result = mStatus_BadReferenceErr; goto end; }
1414         result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise);
1415         if (result && i->default_local) goto end;
1416         else result = mStatus_NoError;  // suppress non-local default errors
1417     }
1418 
1419 end:
1420     if (request->terminate == regservice_termination_callback)
1421         LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)  PID[%d](%s)", request->sd,
1422                      (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1423                      rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>",
1424                      request->process_id, request->pid_name);
1425 
1426     return(result);
1427 }
1428 
1429 // remove a resource record registered via DNSServiceRegisterRecord()
1430 mDNSlocal mStatus remove_record(request_state *request)
1431 {
1432     mStatus err = mStatus_UnknownErr;
1433     registered_record_entry *e, **ptr = &request->u.reg_recs;
1434 
1435     while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
1436     if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
1437     e = *ptr;
1438     *ptr = e->next; // unlink
1439 
1440     LogOperation("%3d: DNSServiceRemoveRecord(%u %s)  PID[%d](%s)",
1441                 request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec), request->process_id, request->pid_name);
1442     e->rr->RecordContext = NULL;
1443     if (e->external_advertise)
1444     {
1445         external_stop_advertising_service(&e->rr->resrec, request->flags);
1446         e->external_advertise = mDNSfalse;
1447     }
1448     LogMcastS(e->rr, request, reg_stop);
1449     err = mDNS_Deregister(&mDNSStorage, e->rr);     // Will free e->rr for us; we're responsible for freeing e
1450     if (err)
1451     {
1452         LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
1453         freeL("registered_record_entry AuthRecord remove_record", e->rr);
1454     }
1455     freeL("registered_record_entry remove_record", e);
1456     return err;
1457 }
1458 
1459 mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
1460 {
1461     mStatus err = mStatus_BadReferenceErr;
1462     ExtraResourceRecord *ptr;
1463 
1464     for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
1465     {
1466         if (ptr->ClientID == request->hdr.reg_index) // found match
1467         {
1468             *rrtype = ptr->r.resrec.rrtype;
1469             if (serv->external_advertise) external_stop_advertising_service(&ptr->r.resrec, request->flags);
1470             err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
1471             break;
1472         }
1473     }
1474     return err;
1475 }
1476 
1477 mDNSlocal mStatus handle_removerecord_request(request_state *request)
1478 {
1479     mStatus err = mStatus_BadReferenceErr;
1480     get_flags(&request->msgptr, request->msgend);   // flags unused
1481 
1482     if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1483 
1484     // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1485     if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1486 
1487     if (request->terminate == connection_termination)
1488         err = remove_record(request);  // remove individually registered record
1489     else if (request->terminate != regservice_termination_callback)
1490     { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1491     else
1492     {
1493         service_instance *i;
1494         mDNSu16 rrtype = 0;
1495         LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s) PID[%d](%s)", request->sd,
1496                      (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1497                      rrtype ? DNSTypeName(rrtype) : "<NONE>", request->process_id, request->pid_name);
1498         for (i = request->u.servicereg.instances; i; i = i->next)
1499         {
1500             err = remove_extra(request, i, &rrtype);
1501             if (err && i->default_local) break;
1502             else err = mStatus_NoError;  // suppress non-local default errors
1503         }
1504     }
1505 
1506     return(err);
1507 }
1508 
1509 // If there's a comma followed by another character,
1510 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1511 // Otherwise, it returns a pointer to the final nul at the end of the string
1512 mDNSlocal char *FindFirstSubType(char *p, char **AnonData)
1513 {
1514     while (*p)
1515     {
1516         if (p[0] == '\\' && p[1])
1517         {
1518              p += 2;
1519         }
1520         else if (p[0] == ',' && p[1])
1521         {
1522             *p++ = 0;
1523             return(p);
1524         }
1525         else if (p[0] == ':' && p[1])
1526         {
1527             *p++ = 0;
1528             *AnonData = p;
1529         }
1530         else
1531         {
1532             p++;
1533         }
1534     }
1535     return(p);
1536 }
1537 
1538 // If there's a comma followed by another character,
1539 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1540 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1541 // Otherwise, it returns a pointer to the final nul at the end of the string
1542 mDNSlocal char *FindNextSubType(char *p)
1543 {
1544     while (*p)
1545     {
1546         if (p[0] == '\\' && p[1])       // If escape character
1547             p += 2;                     // ignore following character
1548         else if (p[0] == ',')           // If we found a comma
1549         {
1550             if (p[1]) *p++ = 0;
1551             return(p);
1552         }
1553         else if (p[0] == '.')
1554             return(mDNSNULL);
1555         else p++;
1556     }
1557     return(p);
1558 }
1559 
1560 // Returns -1 if illegal subtype found
1561 mDNSexport mDNSs32 ChopSubTypes(char *regtype, char **AnonData)
1562 {
1563     mDNSs32 NumSubTypes = 0;
1564     char *stp = FindFirstSubType(regtype, AnonData);
1565     while (stp && *stp)                 // If we found a comma...
1566     {
1567         if (*stp == ',') return(-1);
1568         NumSubTypes++;
1569         stp = FindNextSubType(stp);
1570     }
1571     if (!stp) return(-1);
1572     return(NumSubTypes);
1573 }
1574 
1575 mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p, char **AnonData)
1576 {
1577     AuthRecord *st = mDNSNULL;
1578     //
1579     // "p" is pointing at the regtype e.g., _http._tcp followed by ":<AnonData>" indicated
1580     // by AnonData being non-NULL which is in turn follwed by ",<SubTypes>" indicated by
1581     // NumSubTypes being non-zero. We need to skip the initial regtype to get to the actual
1582     // data that we want. When we come here, ChopSubTypes has null terminated like this e.g.,
1583     //
1584     // _http._tcp<NULL><AnonData><NULL><SubType1><NULL><SubType2><NULL> etc.
1585     //
1586     // 1. If we have Anonymous data and subtypes, skip the regtype (e.g., "_http._tcp")
1587     //    to get the AnonData and then skip the AnonData to get to the SubType.
1588     //
1589     // 2. If we have only SubTypes, skip the regtype to get to the SubType data.
1590     //
1591     // 3. If we have only AnonData, skip the regtype to get to the AnonData.
1592     //
1593     // 4. If we don't have AnonData or NumStypes, it is a noop.
1594     //
1595     if (AnonData)
1596     {
1597         int len;
1598 
1599         // Skip the regtype
1600         while (*p) p++;
1601         p++;
1602 
1603         len = strlen(p) + 1;
1604         *AnonData = mallocL("Anonymous", len);
1605         if (!(*AnonData))
1606         {
1607            return (mDNSNULL);
1608         }
1609         mDNSPlatformMemCopy(*AnonData, p, len);
1610     }
1611     if (NumSubTypes)
1612     {
1613         mDNSs32 i;
1614         st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
1615         if (!st) return(mDNSNULL);
1616         for (i = 0; i < NumSubTypes; i++)
1617         {
1618             mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
1619             // First time through we skip the regtype or AnonData. Subsequently, the
1620             // previous subtype.
1621             while (*p) p++;
1622             p++;
1623             if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
1624             {
1625                 freeL("ServiceSubTypes", st);
1626                 if (AnonData && *AnonData)
1627                     freeL("AnonymousData", *AnonData);
1628                 return(mDNSNULL);
1629             }
1630         }
1631     }
1632     // If NumSubTypes is zero and AnonData is non-NULL, we still return NULL but AnonData has been
1633     // initialized. The caller knows how to handle this.
1634     return(st);
1635 }
1636 
1637 mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
1638 {
1639     service_instance **ptr, *instance;
1640     size_t extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
1641     const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
1642     mStatus result;
1643     mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;
1644 
1645     // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1646     // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1647     // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1648     // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1649     // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1650     if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;
1651 
1652     for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
1653     {
1654         if (SameDomainName(&(*ptr)->domain, domain))
1655         {
1656             LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1657                    domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
1658             return mStatus_AlreadyRegistered;
1659         }
1660     }
1661 
1662     instance = mallocL("service_instance", sizeof(*instance) + extra_size);
1663     if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1664 
1665     instance->next                          = mDNSNULL;
1666     instance->request                       = request;
1667     instance->renameonmemfree               = 0;
1668     instance->clientnotified                = mDNSfalse;
1669     instance->default_local                 = (request->u.servicereg.default_domain && DomainIsLocal);
1670     instance->external_advertise            = mDNSfalse;
1671     AssignDomainName(&instance->domain, domain);
1672 
1673     instance->srs.AnonData = mDNSNULL;
1674     if (!request->u.servicereg.AnonData)
1675     {
1676         instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, mDNSNULL);
1677     }
1678     else
1679     {
1680         char *AnonData = mDNSNULL;
1681         instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, &AnonData);
1682         if (AnonData)
1683             instance->srs.AnonData = (const mDNSu8 *)AnonData;
1684     }
1685 
1686     if (request->u.servicereg.num_subtypes && !instance->subtypes)
1687     {
1688         unlink_and_free_service_instance(instance);
1689         instance = NULL;
1690         FatalError("ERROR: malloc");
1691     }
1692 
1693     result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
1694                                   &request->u.servicereg.name, &request->u.servicereg.type, domain,
1695                                   request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
1696                                   request->u.servicereg.port,
1697                                   mDNSNULL, request->u.servicereg.txtdata, request->u.servicereg.txtlen,
1698                                   instance->subtypes, request->u.servicereg.num_subtypes,
1699                                   interfaceID, regservice_callback, instance, request->flags);
1700 
1701     if (!result)
1702     {
1703         *ptr = instance;        // Append this to the end of our request->u.servicereg.instances list
1704         LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance->request->sd,
1705                      instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
1706         LogMcastS(&instance->srs.RR_SRV, request, reg_start);
1707     }
1708     else
1709     {
1710         LogMsg("register_service_instance %#s.%##s%##s error %d",
1711                &request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
1712         unlink_and_free_service_instance(instance);
1713     }
1714 
1715     return result;
1716 }
1717 
1718 mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
1719 {
1720     request_state *request;
1721 
1722     LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
1723     for (request = all_requests; request; request = request->next)
1724     {
1725         if (request->terminate != regservice_termination_callback) continue;
1726         if (!request->u.servicereg.default_domain) continue;
1727         if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1728         {
1729             service_instance **ptr = &request->u.servicereg.instances;
1730             while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1731             if (add)
1732             {
1733                 // If we don't already have this domain in our list for this registration, add it now
1734                 if (!*ptr) register_service_instance(request, &d->name);
1735                 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
1736             }
1737             else
1738             {
1739                 // Normally we should not fail to find the specified instance
1740                 // One case where this can happen is if a uDNS update fails for some reason,
1741                 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1742                 if (!*ptr)
1743                     LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1744                            &d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
1745                 else
1746                 {
1747                     DNameListElem *p;
1748                     for (p = AutoRegistrationDomains; p; p=p->next)
1749                         if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1750                             if (SameDomainName(&d->name, &p->name)) break;
1751                     if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
1752                     else
1753                     {
1754                         mStatus err;
1755                         service_instance *si = *ptr;
1756                         *ptr = si->next;
1757                         if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
1758                         // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1759                         // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1760                         // process of completing asynchronously, the client cancels the entire operation, so
1761                         // regservice_termination_callback then runs through the whole list deregistering each
1762                         // instance, clearing the backpointers, and then disposing the parent request_state object.
1763                         // However, because this service_instance isn't in the list any more, regservice_termination_callback
1764                         // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1765                         // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1766                         // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1767                         si->request = NULL;
1768                         err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
1769                         if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
1770                     }
1771                 }
1772             }
1773         }
1774     }
1775 }
1776 
1777 // Don't allow normal and anonymous registration to coexist.
1778 mDNSlocal mDNSBool CheckForMixedRegistrations(domainname *regtype, domainname *domain, mDNSBool AnonData)
1779 {
1780     request_state *request;
1781 
1782     // We only care about local domains where the anonymous extension is
1783     // implemented.
1784     if (!SameDomainName(domain, (const domainname *) "\x5" "local"))
1785     {
1786         return mDNStrue;
1787     }
1788 
1789     for (request = all_requests; request; request = request->next)
1790     {
1791         service_instance *ptr;
1792 
1793         if (request->terminate != regservice_termination_callback) continue;
1794         for (ptr = request->u.servicereg.instances; ptr ; ptr = ptr->next)
1795         {
1796             if (!SameDomainName(&ptr->domain, (const domainname *)"\x5" "local") ||
1797                 !SameDomainName(&request->u.servicereg.type, regtype))
1798             {
1799                 continue;
1800             }
1801 
1802             // If we are about to register a anonymous registraion, we dont't want to
1803             // allow the regular ones and vice versa.
1804             if (AnonData)
1805             {
1806                 if (!ptr->srs.AnonData)
1807                 {
1808                     LogMsg("CheckForMixedRegistrations: Normal registration already exists for %##s", regtype->c);
1809                     return mDNSfalse;
1810                 }
1811             }
1812             else
1813             {
1814                 // Allow multiple regular registrations
1815                 if (ptr->srs.AnonData)
1816                 {
1817                     LogMsg("CheckForMixedRegistrations: Anonymous registration already exists for %##s", regtype->c);
1818                     return mDNSfalse;
1819                 }
1820             }
1821         }
1822     }
1823     return mDNStrue;
1824 }
1825 
1826 // Returns true if the interfaceIndex value matches one of the pre-defined
1827 // special values listed in the switch statement below.
1828 mDNSlocal mDNSBool PreDefinedInterfaceIndex(mDNSu32 interfaceIndex)
1829 {
1830     switch(interfaceIndex)
1831     {
1832         case kDNSServiceInterfaceIndexAny:
1833         case kDNSServiceInterfaceIndexLocalOnly:
1834         case kDNSServiceInterfaceIndexUnicast:
1835         case kDNSServiceInterfaceIndexP2P:
1836         case kDNSServiceInterfaceIndexBLE:
1837             return mDNStrue;
1838         default:
1839             return mDNSfalse;
1840     }
1841 }
1842 
1843 mDNSlocal mStatus handle_regservice_request(request_state *request)
1844 {
1845     char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1846     char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
1847     char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
1848     domainname d, srv;
1849     mStatus err;
1850     char *AnonData = mDNSNULL;
1851     const char *msgTXTData;
1852 
1853     DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
1854     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
1855     mDNSInterfaceID InterfaceID;
1856 
1857     // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
1858     // kDNSServiceFlagsIncludeP2P flag set.
1859     if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
1860     {
1861         LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
1862         flags |= kDNSServiceFlagsIncludeP2P;
1863         interfaceIndex = kDNSServiceInterfaceIndexAny;
1864     }
1865 
1866     InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
1867 
1868     // The registration is scoped to a specific interface index, but the
1869     // interface is not currently in our list.
1870     if (interfaceIndex && !InterfaceID)
1871     {
1872         // If it's one of the specially defined inteface index values, just return an error.
1873         if (PreDefinedInterfaceIndex(interfaceIndex))
1874         {
1875             LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex);
1876             return(mStatus_BadParamErr);
1877         }
1878 
1879         // Otherwise, use the specified interface index value and the registration will
1880         // be applied to that interface when it comes up.
1881         InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
1882         LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex);
1883     }
1884 
1885     if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
1886         get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1887         get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1888         get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
1889     { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
1890 
1891     request->flags = flags;
1892     request->interfaceIndex = interfaceIndex;
1893     request->u.servicereg.InterfaceID = InterfaceID;
1894     request->u.servicereg.instances = NULL;
1895     request->u.servicereg.txtlen  = 0;
1896     request->u.servicereg.txtdata = NULL;
1897     mDNSPlatformStrLCopy(request->u.servicereg.type_as_string, type_as_string, sizeof(request->u.servicereg.type_as_string));
1898 
1899     if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
1900     else
1901     {
1902         request->u.servicereg.port.b[0] = *request->msgptr++;
1903         request->u.servicereg.port.b[1] = *request->msgptr++;
1904     }
1905 
1906     request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
1907     msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);
1908 
1909     if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1910 
1911     if (request->u.servicereg.txtlen)
1912     {
1913         request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
1914         if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
1915         mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
1916     }
1917 
1918     // Check for sub-types after the service type
1919     request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string, &AnonData);    // Note: Modifies regtype string to remove trailing subtypes
1920     if (request->u.servicereg.num_subtypes < 0)
1921     {
1922         LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string);
1923         goto bad_param;
1924     }
1925     if (AnonData)
1926     {
1927         int AnonDataLen = strlen(AnonData);
1928         if (AnonDataLen > MAX_ANONYMOUS_DATA)
1929         {
1930             LogMsg("ERROR: handle_regservice_request: AnonDataLen %d", AnonDataLen);
1931             goto bad_param;
1932         }
1933         request->u.servicereg.AnonData = mDNStrue;
1934     }
1935     else
1936     {
1937         request->u.servicereg.AnonData = mDNSfalse;
1938     }
1939 
1940     // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1941     if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
1942     { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); goto bad_param; }
1943 
1944     if (!name[0])
1945     {
1946         request->u.servicereg.name = mDNSStorage.nicelabel;
1947         request->u.servicereg.autoname = mDNStrue;
1948     }
1949     else
1950     {
1951         // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1952         if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
1953         {
1954             int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
1955             name[newlen] = 0;
1956         }
1957         if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
1958         { LogMsg("ERROR: handle_regservice_request - name bad %s", name); goto bad_param; }
1959         request->u.servicereg.autoname = mDNSfalse;
1960     }
1961 
1962     if (*domain)
1963     {
1964         request->u.servicereg.default_domain = mDNSfalse;
1965         if (!MakeDomainNameFromDNSNameString(&d, domain))
1966         { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); goto bad_param; }
1967     }
1968     else
1969     {
1970         request->u.servicereg.default_domain = mDNStrue;
1971         MakeDomainNameFromDNSNameString(&d, "local.");
1972     }
1973 
1974     // We don't allow the anonymous and the regular ones to coexist
1975     if (!CheckForMixedRegistrations(&request->u.servicereg.type, &d, request->u.servicereg.AnonData)) { goto bad_param; }
1976 
1977     if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
1978     {
1979         LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1980                request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); goto bad_param;
1981     }
1982 
1983     if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
1984     { LogMsg("ERROR: handle_regservice_request - host bad %s", host); goto bad_param; }
1985     request->u.servicereg.autorename       = (flags & kDNSServiceFlagsNoAutoRename    ) == 0;
1986     request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
1987 
1988     // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1989     // a port number of zero. When two instances of the protected client are allowed to run on one
1990     // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1991     if (!mDNSIPPortIsZero(request->u.servicereg.port))
1992     {
1993         int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
1994         if (count)
1995             LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request->process_id,
1996                    request->pid_name, count+1, srv.c, mDNSVal16(request->u.servicereg.port));
1997     }
1998 
1999 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2000     // Determine if this request should be promoted to use BLE triggered feature.
2001     if (shouldUseBLE(InterfaceID, 0, &request->u.servicereg.type, &d))
2002     {
2003         request->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2004         LogInfo("handle_regservice_request: registration promoted to use kDNSServiceFlagsAutoTrigger");
2005     }
2006 #endif  // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2007 
2008     LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START PID[%d](%s)",
2009                  request->sd, request->flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host,
2010                  mDNSVal16(request->u.servicereg.port), request->process_id, request->pid_name);
2011 
2012     // We need to unconditionally set request->terminate, because even if we didn't successfully
2013     // start any registrations right now, subsequent configuration changes may cause successful
2014     // registrations to be added, and we'll need to cancel them before freeing this memory.
2015     // We also need to set request->terminate first, before adding additional service instances,
2016     // because the uds_validatelists uses the request->terminate function pointer to determine
2017     // what kind of request this is, and therefore what kind of list validation is required.
2018     request->terminate = regservice_termination_callback;
2019 
2020     err = register_service_instance(request, &d);
2021 
2022 #if TARGET_OS_EMBEDDED
2023     ++curr_num_regservices;
2024     if (curr_num_regservices > max_num_regservices)
2025         max_num_regservices = curr_num_regservices;
2026 #endif
2027 
2028 #if 0
2029     err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
2030 #endif
2031     if (!err)
2032     {
2033         if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
2034 
2035         if (!*domain)
2036         {
2037             DNameListElem *ptr;
2038             // Note that we don't report errors for non-local, non-explicit domains
2039             for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
2040                 if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
2041                     register_service_instance(request, &ptr->name);
2042         }
2043     }
2044 
2045     return(err);
2046 
2047 bad_param:
2048     freeL("handle_regservice_request (txtdata)", request->u.servicereg.txtdata);
2049     request->u.servicereg.txtdata = NULL;
2050     return mStatus_BadParamErr;
2051 }
2052 
2053 // ***************************************************************************
2054 #if COMPILER_LIKES_PRAGMA_MARK
2055 #pragma mark -
2056 #pragma mark - DNSServiceBrowse
2057 #endif
2058 
2059 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2060 {
2061     DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
2062     request_state *req = question->QuestionContext;
2063     reply_state *rep;
2064     (void)m; // Unused
2065 
2066     if (answer->rrtype != kDNSType_PTR)
2067     { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
2068 
2069     if (mDNSOpaque16IsZero(question->TargetQID) && (question->BrowseThreshold > 0) && (question->CurrentAnswers >= question->BrowseThreshold))
2070     {
2071         flags |= kDNSServiceFlagsThresholdReached;
2072     }
2073 
2074     // if returning a negative answer, then use question's name in reply
2075     if (answer->RecordType == kDNSRecordTypePacketNegative)
2076     {
2077         GenerateBrowseReply(&question->qname, answer->InterfaceID, req, &rep, browse_reply_op, flags, kDNSServiceErr_NoSuchRecord);
2078         goto validReply;
2079     }
2080 
2081     if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
2082     {
2083         if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
2084         {
2085             // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2086             // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2087             GenerateBrowseReply(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
2088             goto validReply;
2089         }
2090 
2091         LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2092                req->sd, answer->name->c, answer->rdata->u.name.c);
2093         return;
2094     }
2095 
2096 validReply:
2097 
2098     LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s interface %d: %s",
2099                  req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV",
2100                  mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2101 
2102     append_reply(req, rep);
2103 }
2104 
2105 mDNSlocal void SetQuestionPolicy(DNSQuestion *q, request_state *req)
2106 {
2107     q->euid = req->uid;
2108     // The policy is either based on pid or UUID. Pass a zero pid
2109     // to the "core" if the UUID is valid. If we always pass the pid,
2110     // then the "core" needs to determine whether the uuid is valid
2111     // by examining all the 16 bytes at the time of the policy
2112     // check and also when setting the delegate socket option. Also, it
2113     // requires that we zero out the uuid wherever the question is
2114     // initialized to make sure that it is not interpreted as valid.
2115     // To prevent these intrusive changes, just pass a zero pid to indicate
2116     // that pid is not valid when uuid is valid. In future if we need the
2117     // pid in the question, we will reevaluate this strategy.
2118     if (req->validUUID)
2119     {
2120         mDNSPlatformMemCopy(q->uuid, req->uuid, UUID_SIZE);
2121         q->pid = 0;
2122     }
2123     else
2124     {
2125         q->pid = req->process_id;
2126     }
2127 
2128     //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
2129 }
2130 
2131 mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
2132 {
2133     browser_t *b, *p;
2134     mStatus err;
2135 
2136     for (p = info->u.browser.browsers; p; p = p->next)
2137     {
2138         if (SameDomainName(&p->domain, d))
2139         { debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
2140     }
2141 
2142     b = mallocL("browser_t", sizeof(*b));
2143     if (!b) return mStatus_NoMemoryErr;
2144     mDNSPlatformMemZero(b, sizeof(*b));
2145     AssignDomainName(&b->domain, d);
2146     SetQuestionPolicy(&b->q, info);
2147     err = mDNS_StartBrowse(&mDNSStorage, &b->q, &info->u.browser.regtype, d, info->u.browser.AnonData, info->u.browser.interface_id, info->flags,
2148                             info->u.browser.ForceMCast, (info->flags & kDNSServiceFlagsBackgroundTrafficClass) != 0, FoundInstance, info);
2149     if (err)
2150     {
2151         LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
2152         freeL("browser_t/add_domain_to_browser", b);
2153     }
2154     else
2155     {
2156         b->next = info->u.browser.browsers;
2157         info->u.browser.browsers = b;
2158 
2159 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2160         // Determine if this request should be promoted to use BLE triggered discovery.
2161         if (shouldUseBLE(info->u.browser.interface_id, 0, &info->u.browser.regtype, (domainname *) d))
2162         {
2163             info->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2164             b->q.flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2165             LogInfo("add_domain_to_browser: request promoted to use kDNSServiceFlagsAutoTrigger");
2166         }
2167 #endif  // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2168 
2169         LogMcastQ(&b->q, info, q_start);
2170         if (callExternalHelpers(info->u.browser.interface_id, &b->domain, info->flags))
2171         {
2172             domainname tmp;
2173             ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
2174             LogDebug("add_domain_to_browser: calling external_start_browsing_for_service()");
2175             external_start_browsing_for_service(info->u.browser.interface_id, &tmp, kDNSType_PTR, info->flags);
2176         }
2177     }
2178     return err;
2179 }
2180 
2181 mDNSlocal void browse_termination_callback(request_state *info)
2182 {
2183     if (info->u.browser.default_domain)
2184     {
2185         // Stop the domain enumeration queries to discover the WAB legacy browse domains
2186         LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info->sd, info->process_id, info->pid_name);
2187         uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2188     }
2189     if (info->u.browser.AnonData)
2190         freeL("Anonymous", (void *)info->u.browser.AnonData);
2191     while (info->u.browser.browsers)
2192     {
2193         browser_t *ptr = info->u.browser.browsers;
2194 
2195         if (callExternalHelpers(ptr->q.InterfaceID, &ptr->domain, ptr->q.flags))
2196         {
2197             domainname tmp;
2198             ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
2199             LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2200             external_stop_browsing_for_service(ptr->q.InterfaceID, &tmp, kDNSType_PTR, ptr->q.flags);
2201         }
2202 
2203         LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\") STOP PID[%d](%s)",
2204                      info->sd, info->flags, info->interfaceIndex, ptr->q.qname.c, info->process_id, info->pid_name);
2205 
2206         info->u.browser.browsers = ptr->next;
2207         mDNS_StopBrowse(&mDNSStorage, &ptr->q);  // no need to error-check result
2208         LogMcastQ(&ptr->q, info, q_stop);
2209         freeL("browser_t/browse_termination_callback", ptr);
2210     }
2211 }
2212 
2213 mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
2214 {
2215     request_state *request;
2216     debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
2217 
2218     for (request = all_requests; request; request = request->next)
2219     {
2220         if (request->terminate != browse_termination_callback) continue;    // Not a browse operation
2221         if (!request->u.browser.default_domain) continue;                   // Not an auto-browse operation
2222         if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
2223         {
2224             browser_t **ptr = &request->u.browser.browsers;
2225             while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
2226             if (add)
2227             {
2228                 // If we don't already have this domain in our list for this browse operation, add it now
2229                 if (!*ptr) add_domain_to_browser(request, &d->name);
2230                 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
2231             }
2232             else
2233             {
2234                 if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
2235                 else
2236                 {
2237                     DNameListElem *p;
2238                     for (p = AutoBrowseDomains; p; p=p->next)
2239                         if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
2240                             if (SameDomainName(&d->name, &p->name)) break;
2241                     if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
2242                     else
2243                     {
2244                         browser_t *rem = *ptr;
2245                         *ptr = (*ptr)->next;
2246                         mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
2247                         freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
2248                     }
2249                 }
2250             }
2251         }
2252     }
2253 }
2254 
2255 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
2256 {
2257     (void)m;  // unused
2258     if (result == mStatus_MemFree)
2259     {
2260         // On shutdown, mDNS_Close automatically deregisters all records
2261         // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2262         // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2263         // (This should actually no longer be necessary, now that we do the proper cleanup in
2264         // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2265         // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2266         ARListElem **ptr = &LocalDomainEnumRecords;
2267         while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
2268         if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
2269         mDNSPlatformMemFree(rr->RecordContext);
2270     }
2271 }
2272 
2273 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2274 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2275 // We may want to turn the common code into a subroutine.
2276 
2277 mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2278 {
2279     // allocate/register legacy and non-legacy _browse PTR record
2280     mStatus err;
2281     ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
2282 
2283     debugf("Incrementing %s refcount for %##s",
2284            (type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
2285            (type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
2286            (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2287 
2288     mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
2289     MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
2290     AppendDNSNameString            (&ptr->ar.namestorage, "local");
2291     AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
2292     err = mDNS_Register(m, &ptr->ar);
2293     if (err)
2294     {
2295         LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
2296         mDNSPlatformMemFree(ptr);
2297     }
2298     else
2299     {
2300         ptr->next = LocalDomainEnumRecords;
2301         LocalDomainEnumRecords = ptr;
2302     }
2303 }
2304 
2305 mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2306 {
2307     ARListElem **ptr = &LocalDomainEnumRecords;
2308     domainname lhs; // left-hand side of PTR, for comparison
2309 
2310     debugf("Decrementing %s refcount for %##s",
2311            (type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
2312            (type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
2313            (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2314 
2315     MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
2316     AppendDNSNameString            (&lhs, "local");
2317 
2318     while (*ptr)
2319     {
2320         if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
2321         {
2322             ARListElem *rem = *ptr;
2323             *ptr = (*ptr)->next;
2324             mDNS_Deregister(m, &rem->ar);
2325             return;
2326         }
2327         else ptr = &(*ptr)->next;
2328     }
2329 }
2330 
2331 mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2332 {
2333     DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
2334     if (!new) { LogMsg("ERROR: malloc"); return; }
2335     AssignDomainName(&new->name, name);
2336     new->uid = uid;
2337     new->next = AutoBrowseDomains;
2338     AutoBrowseDomains = new;
2339     udsserver_automatic_browse_domain_changed(new, mDNStrue);
2340 }
2341 
2342 mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2343 {
2344     DNameListElem **p = &AutoBrowseDomains;
2345     while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
2346     if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
2347     else
2348     {
2349         DNameListElem *ptr = *p;
2350         *p = ptr->next;
2351         udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
2352         mDNSPlatformMemFree(ptr);
2353     }
2354 }
2355 
2356 mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
2357 {
2358     DNameListElem *d;
2359     for (d = browseDomains; d; d = d->next)
2360     {
2361         if (add)
2362         {
2363             RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2364             AddAutoBrowseDomain(d->uid, &d->name);
2365         }
2366         else
2367         {
2368             DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2369             RmvAutoBrowseDomain(d->uid, &d->name);
2370         }
2371     }
2372 }
2373 
2374 #if APPLE_OSX_mDNSResponder
2375 
2376 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2377 {
2378     int num_autoname = 0;
2379     request_state *req;
2380 
2381     // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2382     for (req = all_requests; req; req = req->next)
2383     {
2384         if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname && req->interfaceIndex != kDNSServiceInterfaceIndexLocalOnly)
2385             num_autoname++;
2386     }
2387 
2388     // If DeviceInfo record is currently registered, see if we need to deregister it
2389     if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
2390         if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
2391         {
2392             LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
2393             mDNS_Deregister(m, &m->DeviceInfo);
2394         }
2395 
2396     // If DeviceInfo record is not currently registered, see if we need to register it
2397     if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
2398         if (num_autoname > 0)
2399         {
2400             mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
2401             ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
2402             m->DeviceInfo.resrec.rdlength = initializeDeviceInfoTXT(m, m->DeviceInfo.resrec.rdata->u.data);
2403             LogOperation("UpdateDeviceInfoRecord   Register %##s", m->DeviceInfo.resrec.name);
2404             mDNS_Register(m, &m->DeviceInfo);
2405         }
2406 }
2407 #else   // APPLE_OSX_mDNSResponder
2408 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2409 {
2410     (void)m; // unused
2411 }
2412 #endif  // APPLE_OSX_mDNSResponder
2413 
2414 mDNSexport void udsserver_handle_configchange(mDNS *const m)
2415 {
2416     request_state *req;
2417     service_instance *ptr;
2418     DNameListElem *RegDomains = NULL;
2419     DNameListElem *BrowseDomains = NULL;
2420     DNameListElem *p;
2421 
2422     UpdateDeviceInfoRecord(m);
2423 
2424     // For autoname services, see if the default service name has changed, necessitating an automatic update
2425     for (req = all_requests; req; req = req->next)
2426         if (req->terminate == regservice_termination_callback)
2427             if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
2428             {
2429                 req->u.servicereg.name = m->nicelabel;
2430                 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
2431                 {
2432                     ptr->renameonmemfree = 1;
2433                     if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
2434                     LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
2435                     if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
2436                         regservice_callback(m, &ptr->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
2437                 }
2438             }
2439 
2440     // Let the platform layer get the current DNS information
2441     mDNS_Lock(m);
2442     mDNSPlatformSetDNSConfig(mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains, mDNSfalse);
2443     mDNS_Unlock(m);
2444 
2445     // Any automatic registration domains are also implicitly automatic browsing domains
2446     if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue);                             // Add the new list first
2447     if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse);  // Then clear the old list
2448 
2449     // Add any new domains not already in our AutoRegistrationDomains list
2450     for (p=RegDomains; p; p=p->next)
2451     {
2452         DNameListElem **pp = &AutoRegistrationDomains;
2453         while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
2454         if (!*pp)       // If not found in our existing list, this is a new default registration domain
2455         {
2456             RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
2457             udsserver_default_reg_domain_changed(p, mDNStrue);
2458         }
2459         else            // else found same domainname in both old and new lists, so no change, just delete old copy
2460         {
2461             DNameListElem *del = *pp;
2462             *pp = (*pp)->next;
2463             mDNSPlatformMemFree(del);
2464         }
2465     }
2466 
2467     // Delete any domains in our old AutoRegistrationDomains list that are now gone
2468     while (AutoRegistrationDomains)
2469     {
2470         DNameListElem *del = AutoRegistrationDomains;
2471         AutoRegistrationDomains = AutoRegistrationDomains->next;        // Cut record from list FIRST,
2472         DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
2473         udsserver_default_reg_domain_changed(del, mDNSfalse);           // before calling udsserver_default_reg_domain_changed()
2474         mDNSPlatformMemFree(del);
2475     }
2476 
2477     // Now we have our new updated automatic registration domain list
2478     AutoRegistrationDomains = RegDomains;
2479 
2480     // Add new browse domains to internal list
2481     if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
2482 
2483     // Remove old browse domains from internal list
2484     if (SCPrefBrowseDomains)
2485     {
2486         SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
2487         while (SCPrefBrowseDomains)
2488         {
2489             DNameListElem *fptr = SCPrefBrowseDomains;
2490             SCPrefBrowseDomains = SCPrefBrowseDomains->next;
2491             mDNSPlatformMemFree(fptr);
2492         }
2493     }
2494 
2495     // Replace the old browse domains array with the new array
2496     SCPrefBrowseDomains = BrowseDomains;
2497 }
2498 
2499 mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
2500 {
2501     (void)m; // unused;
2502     (void)q; // unused
2503 
2504     LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2505                  AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
2506 
2507     if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
2508     else RmvAutoBrowseDomain(0, &answer->rdata->u.name);
2509 }
2510 
2511 mDNSlocal mStatus handle_browse_request(request_state *request)
2512 {
2513     char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2514     domainname typedn, d, temp;
2515     mDNSs32 NumSubTypes;
2516     char *AnonData = mDNSNULL;
2517     mStatus err = mStatus_NoError;
2518     int AnonDataLen;
2519 
2520     DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2521     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2522     mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2523 
2524     // The browse is scoped to a specific interface index, but the
2525     // interface is not currently in our list.
2526     if (interfaceIndex && !InterfaceID)
2527     {
2528         // If it's one of the specially defined inteface index values, just return an error.
2529         if (PreDefinedInterfaceIndex(interfaceIndex))
2530         {
2531             LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex);
2532             return(mStatus_BadParamErr);
2533         }
2534 
2535         // Otherwise, use the specified interface index value and the browse will
2536         // be applied to that interface when it comes up.
2537         InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2538         LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex);
2539     }
2540 
2541     if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2542         get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
2543 
2544     if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2545 
2546     request->flags = flags;
2547     request->interfaceIndex = interfaceIndex;
2548     typedn.c[0] = 0;
2549     NumSubTypes = ChopSubTypes(regtype, &AnonData);    // Note: Modifies regtype string to remove trailing subtypes
2550     if (NumSubTypes < 0 || NumSubTypes > 1)
2551         return(mStatus_BadParamErr);
2552     AnonDataLen = 0;
2553     if (AnonData)
2554     {
2555         AnonDataLen = strlen(AnonData);
2556         if (AnonDataLen > MAX_ANONYMOUS_DATA)
2557         {
2558             LogMsg("handle_browse_request: AnonDataLen %d", AnonDataLen);
2559             return(mStatus_BadParamErr);
2560         }
2561         // Account for the null byte
2562         AnonDataLen += 1;
2563     }
2564     if (NumSubTypes == 1)
2565     {
2566         if (!AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1 + AnonDataLen))
2567             return(mStatus_BadParamErr);
2568     }
2569 
2570     if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
2571 
2572     if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
2573     // For over-long service types, we only allow domain "local"
2574     if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrLCopy(domain, "local.", sizeof(domain));
2575 
2576     // Set up browser info
2577     request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
2578     request->u.browser.interface_id = InterfaceID;
2579     AssignDomainName(&request->u.browser.regtype, &typedn);
2580     request->u.browser.default_domain = !domain[0];
2581     request->u.browser.browsers = NULL;
2582 
2583     LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START PID[%d](%s)",
2584                  request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain, request->process_id, request->pid_name);
2585 
2586     if (request->u.browser.default_domain)
2587     {
2588         // Start the domain enumeration queries to discover the WAB browse domains
2589         LogInfo("%3d: DNSServiceBrowse Start WAB PID[%d](%s)", request->sd, request->process_id, request->pid_name);
2590         uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2591     }
2592     request->u.browser.AnonData = mDNSNULL;
2593     if (AnonData)
2594     {
2595         int len = strlen(AnonData) + 1;
2596         request->u.browser.AnonData = mallocL("Anonymous", len);
2597         if (!request->u.browser.AnonData)
2598             return mStatus_NoMemoryErr;
2599         else
2600             mDNSPlatformMemCopy((void *)request->u.browser.AnonData, AnonData, len);
2601     }
2602     // We need to unconditionally set request->terminate, because even if we didn't successfully
2603     // start any browses right now, subsequent configuration changes may cause successful
2604     // browses to be added, and we'll need to cancel them before freeing this memory.
2605     request->terminate = browse_termination_callback;
2606 
2607     if (domain[0])
2608     {
2609         if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
2610         err = add_domain_to_browser(request, &d);
2611     }
2612     else
2613     {
2614         DNameListElem *sdom;
2615         for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
2616             if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
2617             {
2618                 err = add_domain_to_browser(request, &sdom->name);
2619                 if (err)
2620                 {
2621                     if (SameDomainName(&sdom->name, &localdomain)) break;
2622                     else err = mStatus_NoError;  // suppress errors for non-local "default" domains
2623                 }
2624             }
2625     }
2626 
2627     return(err);
2628 }
2629 
2630 // ***************************************************************************
2631 #if COMPILER_LIKES_PRAGMA_MARK
2632 #pragma mark -
2633 #pragma mark - DNSServiceResolve
2634 #endif
2635 
2636 mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2637 {
2638     size_t len = 0;
2639     char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME] = "0";
2640     char *data;
2641     reply_state *rep;
2642     request_state *req = question->QuestionContext;
2643     const DNSServiceErrorType error =
2644         (answer->RecordType == kDNSRecordTypePacketNegative) ? kDNSServiceErr_NoSuchRecord : kDNSServiceErr_NoError;
2645     (void)m; // Unused
2646 
2647     LogOperation("%3d: DNSServiceResolve(%##s) %s interface %d: %s",
2648         req->sd, question->qname.c, AddRecord ? "ADD" : "RMV",
2649         mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2650 
2651     if (!AddRecord)
2652     {
2653         if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
2654         if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
2655         return;
2656     }
2657 
2658     if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
2659     if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
2660 
2661     if (!req->u.resolve.txt || !req->u.resolve.srv) return;     // only deliver result to client if we have both answers
2662 
2663     ConvertDomainNameToCString(answer->name, fullname);
2664 
2665     if (answer->RecordType != kDNSRecordTypePacketNegative)
2666         ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
2667 
2668     // calculate reply length
2669     len += sizeof(DNSServiceFlags);
2670     len += sizeof(mDNSu32);  // interface index
2671     len += sizeof(DNSServiceErrorType);
2672     len += strlen(fullname) + 1;
2673     len += strlen(target) + 1;
2674     len += 2 * sizeof(mDNSu16);  // port, txtLen
2675     len += req->u.resolve.txt->rdlength;
2676 
2677     // allocate/init reply header
2678     rep = create_reply(resolve_reply_op, len, req);
2679     rep->rhdr->flags = dnssd_htonl(0);
2680     rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
2681     rep->rhdr->error = dnssd_htonl(error);
2682 
2683     data = (char *)&rep->rhdr[1];
2684 
2685     // write reply data to message
2686     put_string(fullname, &data);
2687     put_string(target, &data);
2688     *data++ =  req->u.resolve.srv->rdata->u.srv.port.b[0];
2689     *data++ =  req->u.resolve.srv->rdata->u.srv.port.b[1];
2690     put_uint16(req->u.resolve.txt->rdlength, &data);
2691     put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
2692 
2693     LogOperation("%3d: DNSServiceResolve(%s) RESULT   %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
2694     append_reply(req, rep);
2695 }
2696 
2697 mDNSlocal void resolve_termination_callback(request_state *request)
2698 {
2699     LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") STOP PID[%d](%s)",
2700                  request->sd, request->flags, request->interfaceIndex, request->u.resolve.qtxt.qname.c, request->process_id, request->pid_name);
2701     mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
2702     mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2703     LogMcastQ(&request->u.resolve.qsrv, request, q_stop);
2704     if (request->u.resolve.external_advertise)
2705         external_stop_resolving_service(request->u.resolve.qsrv.InterfaceID, &request->u.resolve.qsrv.qname, request->flags);
2706 }
2707 
2708 mDNSlocal mStatus handle_resolve_request(request_state *request)
2709 {
2710     char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2711     domainname fqdn;
2712     mStatus err;
2713 
2714     // extract the data from the message
2715     DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2716     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2717     mDNSInterfaceID InterfaceID;
2718 
2719     // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2720     // flag set so that the resolve will run over P2P interfaces that are not yet created.
2721     if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
2722     {
2723         LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2724         flags |= kDNSServiceFlagsIncludeP2P;
2725         interfaceIndex = kDNSServiceInterfaceIndexAny;
2726     }
2727 
2728     InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2729 
2730     // The operation is scoped to a specific interface index, but the
2731     // interface is not currently in our list.
2732     if (interfaceIndex && !InterfaceID)
2733     {
2734         // If it's one of the specially defined inteface index values, just return an error.
2735         if (PreDefinedInterfaceIndex(interfaceIndex))
2736         {
2737             LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex);
2738             return(mStatus_BadParamErr);
2739         }
2740 
2741         // Otherwise, use the specified interface index value and the operation will
2742         // be applied to that interface when it comes up.
2743         InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2744         LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex);
2745     }
2746 
2747     if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
2748         get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2749         get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
2750     { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2751 
2752     if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2753 
2754     if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
2755     { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
2756 
2757     mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
2758 
2759 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2760     // Determine if this request should be promoted to use BLE triggered discovery.
2761     if (shouldUseBLE(InterfaceID, 0, (domainname *)SkipLeadingLabels(&fqdn, 1), &fqdn))
2762     {
2763         flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2764         LogInfo("handle_resolve_request: request promoted to use kDNSServiceFlagsAutoTrigger");
2765     }
2766 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2767 
2768     request->flags = flags;
2769     request->interfaceIndex = interfaceIndex;
2770 
2771     // format questions
2772     request->u.resolve.qsrv.InterfaceID      = InterfaceID;
2773     request->u.resolve.qsrv.flags            = flags;
2774     request->u.resolve.qsrv.Target           = zeroAddr;
2775     AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
2776     request->u.resolve.qsrv.qtype            = kDNSType_SRV;
2777     request->u.resolve.qsrv.qclass           = kDNSClass_IN;
2778     request->u.resolve.qsrv.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2779     request->u.resolve.qsrv.ExpectUnique     = mDNStrue;
2780     request->u.resolve.qsrv.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
2781     request->u.resolve.qsrv.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2782     request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
2783     request->u.resolve.qsrv.SearchListIndex  = 0;
2784     request->u.resolve.qsrv.AppendSearchDomains = 0;
2785     request->u.resolve.qsrv.RetryWithSearchDomains = mDNSfalse;
2786     request->u.resolve.qsrv.TimeoutQuestion  = 0;
2787     request->u.resolve.qsrv.WakeOnResolve    = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
2788     request->u.resolve.qsrv.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2789     request->u.resolve.qsrv.ValidationRequired = 0;
2790     request->u.resolve.qsrv.ValidatingResponse = 0;
2791     request->u.resolve.qsrv.ProxyQuestion    = 0;
2792     request->u.resolve.qsrv.qnameOrig        = mDNSNULL;
2793     request->u.resolve.qsrv.AnonInfo         = mDNSNULL;
2794     request->u.resolve.qsrv.pid              = request->process_id;
2795     request->u.resolve.qsrv.euid             = request->uid;
2796     request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
2797     request->u.resolve.qsrv.QuestionContext  = request;
2798 
2799     request->u.resolve.qtxt.InterfaceID      = InterfaceID;
2800     request->u.resolve.qtxt.flags            = flags;
2801     request->u.resolve.qtxt.Target           = zeroAddr;
2802     AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn);
2803     request->u.resolve.qtxt.qtype            = kDNSType_TXT;
2804     request->u.resolve.qtxt.qclass           = kDNSClass_IN;
2805     request->u.resolve.qtxt.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2806     request->u.resolve.qtxt.ExpectUnique     = mDNStrue;
2807     request->u.resolve.qtxt.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
2808     request->u.resolve.qtxt.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2809     request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
2810     request->u.resolve.qtxt.SearchListIndex  = 0;
2811     request->u.resolve.qtxt.AppendSearchDomains = 0;
2812     request->u.resolve.qtxt.RetryWithSearchDomains = mDNSfalse;
2813     request->u.resolve.qtxt.TimeoutQuestion  = 0;
2814     request->u.resolve.qtxt.WakeOnResolve    = 0;
2815     request->u.resolve.qtxt.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2816     request->u.resolve.qtxt.ValidationRequired = 0;
2817     request->u.resolve.qtxt.ValidatingResponse = 0;
2818     request->u.resolve.qtxt.ProxyQuestion    = 0;
2819     request->u.resolve.qtxt.qnameOrig        = mDNSNULL;
2820     request->u.resolve.qtxt.AnonInfo         = mDNSNULL;
2821     request->u.resolve.qtxt.pid              = request->process_id;
2822     request->u.resolve.qtxt.euid             = request->uid;
2823     request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
2824     request->u.resolve.qtxt.QuestionContext  = request;
2825 
2826     request->u.resolve.ReportTime            = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
2827 
2828     request->u.resolve.external_advertise    = mDNSfalse;
2829 
2830 #if 0
2831     if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains)) return(mStatus_NoError);
2832 #endif
2833 
2834     // ask the questions
2835     LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") START PID[%d](%s)", request->sd, flags, interfaceIndex,
2836                  request->u.resolve.qsrv.qname.c, request->process_id, request->pid_name);
2837 
2838     err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);
2839 
2840     if (!err)
2841     {
2842         err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
2843         if (err)
2844         {
2845             mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2846         }
2847         else
2848         {
2849             request->terminate = resolve_termination_callback;
2850             LogMcastQ(&request->u.resolve.qsrv, request, q_start);
2851             if (callExternalHelpers(InterfaceID, &fqdn, flags))
2852             {
2853                 request->u.resolve.external_advertise    = mDNStrue;
2854                 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2855                 external_start_resolving_service(InterfaceID, &fqdn, flags);
2856             }
2857         }
2858     }
2859 
2860     return(err);
2861 }
2862 
2863 // ***************************************************************************
2864 #if COMPILER_LIKES_PRAGMA_MARK
2865 #pragma mark -
2866 #pragma mark - DNSServiceQueryRecord
2867 #endif
2868 
2869 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2870 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2871 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2872 // the mDNSCore operation if the client dies or closes its socket.
2873 
2874 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2875 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2876 // Returns 0 when there are no more search domains and the caller should reissue the query
2877 mDNSlocal int AppendNewSearchDomain(DNSQuestion *question)
2878 {
2879     domainname *sd;
2880     mStatus err;
2881 
2882     // Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2883     // the domains and should try the single label query directly on the wire.
2884     if (question->SearchListIndex == -1)
2885     {
2886         LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question->qname.c, DNSTypeName(question->qtype));
2887         return -1;
2888     }
2889 
2890     if (!question->AppendSearchDomains)
2891     {
2892         LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question->qname.c, DNSTypeName(question->qtype));
2893         return -1;
2894     }
2895 
2896     // Save the original name, before we modify them below.
2897     if (!question->qnameOrig)
2898     {
2899         question->qnameOrig =  mallocL("AppendNewSearchDomain", sizeof(domainname));
2900         if (!question->qnameOrig) { LogMsg("AppendNewSearchDomain: ERROR!!  malloc failure"); return -1; }
2901         question->qnameOrig->c[0] = 0;
2902         AssignDomainName(question->qnameOrig, &question->qname);
2903         LogInfo("AppendSearchDomain: qnameOrig %##s", question->qnameOrig->c);
2904     }
2905 
2906     sd = uDNS_GetNextSearchDomain(question->InterfaceID, &question->SearchListIndex, !question->AppendLocalSearchDomains);
2907     // We use -1 to indicate that we have searched all the domains and should try the single label
2908     // query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2909     if (question->SearchListIndex == -1)
2910     {
2911         LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2912         return -1;
2913     }
2914 
2915     // Not a common case. Perhaps, we should try the next search domain if it exceeds ?
2916     if (sd && (DomainNameLength(question->qnameOrig) + DomainNameLength(sd)) > MAX_DOMAIN_NAME)
2917     {
2918         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));
2919         return -1;
2920     }
2921 
2922     // if there are no more search domains and we have already tried this question
2923     // without appending search domains, then we are done.
2924     if (!sd && !ApplySearchDomainsFirst(question))
2925     {
2926         LogInfo("AppendNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question->qname.c, DNSTypeName(question->qtype));
2927         return -1;
2928     }
2929 
2930     // Stop the question before changing the name as negative cache entries could be pointing at this question.
2931     // Even if we don't change the question in the case of returning 0, the caller is going to restart the
2932     // question.
2933     err = mDNS_StopQuery(&mDNSStorage, question);
2934     if (err) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question->qname.c, DNSTypeName(question->qtype), (int)err); }
2935 
2936     AssignDomainName(&question->qname, question->qnameOrig);
2937     if (sd)
2938     {
2939         AppendDomainName(&question->qname, sd);
2940         LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question->qname.c, question->SearchListIndex);
2941         return 1;
2942     }
2943 
2944     // Try the question as single label
2945     LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question->qname.c, DNSTypeName(question->qtype));
2946     return 0;
2947 }
2948 
2949 #if APPLE_OSX_mDNSResponder
2950 
2951 mDNSlocal mDNSBool DomainInSearchList(const domainname *domain, mDNSBool excludeLocal)
2952 {
2953     const SearchListElem *s;
2954     int qcount, scount;
2955 
2956     qcount = CountLabels(domain);
2957     for (s=SearchList; s; s=s->next)
2958     {
2959         if (excludeLocal && SameDomainName(&s->domain, &localdomain))
2960             continue;
2961         scount = CountLabels(&s->domain);
2962         if (qcount >= scount)
2963         {
2964             // Note: When qcount == scount, we do a complete match of the domain
2965             // which is expected by the callers.
2966             const domainname *d = SkipLeadingLabels(domain, (qcount - scount));
2967             if (SameDomainName(&s->domain, d))
2968             {
2969                 return mDNStrue;
2970             }
2971         }
2972     }
2973     return mDNSfalse;
2974 }
2975 
2976 // The caller already checks that this is a dotlocal question.
2977 mDNSlocal mDNSBool ShouldDeliverNegativeResponse(DNSQuestion *question)
2978 {
2979     mDNSu16 qtype;
2980 
2981     // If the question matches the search domain exactly or the search domain is a
2982     // subdomain of the question, it is most likely a valid unicast domain and hence
2983     // don't suppress negative responses.
2984     //
2985     // If the user has configured ".local" as a search domain, we don't want
2986     // to deliver a negative response for names ending in ".local" as that would
2987     // prevent bonjour discovery. Passing mDNStrue for the last argument excludes
2988     // ".local" search domains.
2989     if (DomainInSearchList(&question->qname, mDNStrue))
2990     {
2991         LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) in SearchList", question->qname.c, DNSTypeName(question->qtype));
2992         return mDNStrue;
2993     }
2994 
2995     // Deliver negative response for A/AAAA if there was a positive response for AAAA/A respectively.
2996     if (question->qtype != kDNSType_A && question->qtype != kDNSType_AAAA)
2997     {
2998         LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) not answering local question with negative unicast response",
2999             question->qname.c, DNSTypeName(question->qtype));
3000         return mDNSfalse;
3001     }
3002     qtype = (question->qtype == kDNSType_A ? kDNSType_AAAA : kDNSType_A);
3003     if (!mDNS_CheckForCacheRecord(&mDNSStorage, question, qtype))
3004     {
3005         LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) not answering local question with negative unicast response"
3006             " (can't find positive record)", question->qname.c, DNSTypeName(question->qtype));
3007         return mDNSfalse;
3008     }
3009     LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) answering local with negative unicast response (found positive record)",
3010         question->qname.c, DNSTypeName(question->qtype));
3011     return mDNStrue;
3012 }
3013 
3014 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
3015 // top-level domain
3016 mDNSlocal mStatus SendAdditionalQuery(DNSQuestion *q, request_state *request, mStatus err)
3017 {
3018 #ifndef UNICAST_DISABLED
3019     extern domainname ActiveDirectoryPrimaryDomain;
3020     DNSQuestion **question2;
3021     #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
3022     #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
3023 
3024     question2 = mDNSNULL;
3025     if (request->hdr.op == query_request)
3026         question2 = &request->u.queryrecord.q2;
3027     else if (request->hdr.op == addrinfo_request)
3028     {
3029         if (q->qtype == kDNSType_A)
3030             question2 = &request->u.addrinfo.q42;
3031         else if (q->qtype == kDNSType_AAAA)
3032             question2 = &request->u.addrinfo.q62;
3033     }
3034     if (!question2)
3035     {
3036         LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3037         return mStatus_BadParamErr;
3038     }
3039 
3040     // Sanity check: If we already sent an additonal query, we don't need to send one more.
3041     //
3042     // 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
3043     // is called to see whether a unicast query should be sent or not.
3044     //
3045     // 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
3046     // was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
3047     // send the additional query.
3048     //
3049     // Thus, it should not be called more than once.
3050     if (*question2)
3051     {
3052         LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q->qname.c, DNSTypeName(q->qtype));
3053         return err;
3054     }
3055 
3056     if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
3057         if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q))
3058         {
3059             DNSQuestion *q2;
3060             int labels = CountLabels(&q->qname);
3061             q2 = mallocL("DNSQuestion", sizeof(DNSQuestion));
3062             if (!q2) FatalError("ERROR: SendAdditionalQuery malloc");
3063             *question2        = q2;
3064             *q2               = *q;
3065             q2->InterfaceID   = mDNSInterface_Unicast;
3066             q2->ExpectUnique  = mDNStrue;
3067             // Always set the QuestionContext to indicate that this question should be stopped
3068             // before freeing. Don't rely on "q".
3069             q2->QuestionContext = request;
3070             // If the query starts as a single label e.g., somehost, and we have search domains with .local,
3071             // queryrecord_result_callback calls this function when .local is appended to "somehost".
3072             // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
3073             // "somehost". We need to copy that information so that when we retry with a different search
3074             // domain e.g., mycompany.local, we get "somehost.mycompany.local".
3075             if (q->qnameOrig)
3076             {
3077                 (*question2)->qnameOrig =  mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
3078                 if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!!  malloc failure"); return mStatus_NoMemoryErr; }
3079                 (*question2)->qnameOrig->c[0] = 0;
3080                 AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
3081                 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
3082             }
3083             // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
3084             // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
3085             // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
3086             // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
3087             // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
3088             // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
3089             // for names in the "local" domain will be safely answered privately before they hit the root name servers.
3090             // Note that in the "my-small-company.local" example above there will typically be an SOA record for
3091             // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
3092             // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
3093             // of those, we don't want do the SOA check for the local
3094             if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname, mDNSfalse))
3095             {
3096                 AssignDomainName(&q2->qname, &localdomain);
3097                 q2->qtype          = kDNSType_SOA;
3098                 q2->LongLived      = mDNSfalse;
3099                 q2->ForceMCast     = mDNSfalse;
3100                 q2->ReturnIntermed = mDNStrue;
3101                 // Don't append search domains for the .local SOA query
3102                 q2->AppendSearchDomains = 0;
3103                 q2->AppendLocalSearchDomains = 0;
3104                 q2->RetryWithSearchDomains = mDNSfalse;
3105                 q2->SearchListIndex = 0;
3106                 q2->TimeoutQuestion = 0;
3107                 q2->AnonInfo        = mDNSNULL;
3108                 q2->pid             = request->process_id;
3109                 q2->euid            = request->uid;
3110             }
3111             LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
3112             err = mDNS_StartQuery(&mDNSStorage, q2);
3113             if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
3114         }
3115     return(err);
3116 #else // !UNICAST_DISABLED
3117     (void) q;
3118     (void) request;
3119     (void) err;
3120 
3121     return mStatus_NoError;
3122 #endif // !UNICAST_DISABLED
3123 }
3124 #endif // APPLE_OSX_mDNSResponder
3125 
3126 // This function tries to append a search domain if valid and possible. If so, returns true.
3127 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(DNSQuestion *question, request_state *req, QC_result AddRecord)
3128 {
3129     int result;
3130     // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
3131     // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
3132     // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
3133     // RetryWithSearchDomains which may or may not be set.
3134     //
3135     // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
3136     // is a valid question for appending search domains, retry by appending domains
3137 
3138     if ((AddRecord != QC_suppressed) && question->SearchListIndex != -1 && question->AppendSearchDomains)
3139     {
3140         question->RetryWithSearchDomains = 0;
3141         result = AppendNewSearchDomain(question);
3142         // As long as the result is either zero or 1, we retry the question. If we exahaust the search
3143         // domains (result is zero) we try the original query (as it was before appending the search
3144         // domains) as such on the wire as a last resort if we have not tried them before. For queries
3145         // with more than one label, we have already tried them before appending search domains and
3146         // hence don't retry again
3147         if (result != -1)
3148         {
3149             mStatus err;
3150             err = mDNS_StartQuery(&mDNSStorage, question);
3151             if (!err)
3152             {
3153                 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
3154                 // If the result was zero, it meant that there are no search domains and we just retried the question
3155                 // as a single label and we should not retry with search domains anymore.
3156                 if (!result) question->SearchListIndex = -1;
3157                 return mDNStrue;
3158             }
3159             else
3160             {
3161                 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3162                 // We have already stopped the query and could not restart. Reset the appropriate pointers
3163                 // so that we don't call stop again when the question terminates
3164                 question->QuestionContext = mDNSNULL;
3165             }
3166         }
3167     }
3168     else
3169     {
3170         LogDebug("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, AddRecord, question->SearchListIndex, question->AppendSearchDomains);
3171     }
3172     return mDNSfalse;
3173 }
3174 
3175 mDNSlocal void queryrecord_result_reply(mDNS *const m, request_state *req, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord,
3176     DNSServiceErrorType error)
3177 {
3178     char name[MAX_ESCAPED_DOMAIN_NAME];
3179     size_t len;
3180     DNSServiceFlags flags = 0;
3181     reply_state *rep;
3182     char *data;
3183 
3184     ConvertDomainNameToCString(answer->name, name);
3185 
3186     LogOperation("%3d: %s(%##s, %s) RESULT %s interface %d: (%s)%s", req->sd,
3187                  req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
3188                  question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV",
3189                  mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse),
3190                  MortalityDisplayString(answer->mortality), RRDisplayString(m, answer));
3191 
3192     len = sizeof(DNSServiceFlags);  // calculate reply data length
3193     len += sizeof(mDNSu32);     // interface index
3194     len += sizeof(DNSServiceErrorType);
3195     len += strlen(name) + 1;
3196     len += 3 * sizeof(mDNSu16); // type, class, rdlen
3197     len += answer->rdlength;
3198     len += sizeof(mDNSu32);     // TTL
3199 
3200     rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
3201 
3202     if (AddRecord)
3203         flags |= kDNSServiceFlagsAdd;
3204     if (answer->mortality == Mortality_Ghost)
3205         flags |= kDNSServiceFlagsExpiredAnswer;
3206     if (question->ValidationStatus != 0)
3207     {
3208         error =   kDNSServiceErr_NoError;
3209         if (question->ValidationRequired && question->ValidationState == DNSSECValDone)
3210         {
3211             switch (question->ValidationStatus) //Set the dnssec flags to be passed on to the Apps here
3212             {
3213             case DNSSEC_Secure:
3214                 flags |= kDNSServiceFlagsSecure;
3215                 break;
3216             case DNSSEC_Insecure:
3217                 flags |= kDNSServiceFlagsInsecure;
3218                 break;
3219             case DNSSEC_Indeterminate:
3220                 flags |= kDNSServiceFlagsIndeterminate;
3221                 break;
3222             case DNSSEC_Bogus:
3223                 flags |= kDNSServiceFlagsBogus;
3224                 break;
3225             default:
3226                 LogMsg("queryrecord_result_reply unknown status %d for %##s", question->ValidationStatus, question->qname.c);
3227             }
3228         }
3229     }
3230 
3231     rep->rhdr->flags = dnssd_htonl(flags);
3232     // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
3233     // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
3234     // to be stopped and started including  *this* one. Normally the InterfaceID is valid. But when we
3235     // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
3236     // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
3237     // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
3238     // should not have existed to answer this question if the corresponding interface is not valid.
3239     rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
3240     rep->rhdr->error = dnssd_htonl(error);
3241 
3242     data = (char *)&rep->rhdr[1];
3243 
3244     put_string(name,             &data);
3245     put_uint16(answer->rrtype,   &data);
3246     put_uint16(answer->rrclass,  &data);
3247     put_uint16(answer->rdlength, &data);
3248     // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
3249     // function just does a blind memory copy without regard to structures that may have holes in them.
3250     if (answer->rdlength)
3251         if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
3252             LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
3253     data += answer->rdlength;
3254     put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
3255 
3256     append_reply(req, rep);
3257     // Stop the question, if we just timed out
3258     if (error == kDNSServiceErr_Timeout)
3259     {
3260         mDNS_StopQuery(m, question);
3261         // Reset the pointers so that we don't call stop on termination
3262         question->QuestionContext = mDNSNULL;
3263     }
3264     else if ((AddRecord == QC_add) && req->hdr.op == addrinfo_request)
3265     {
3266         // Note: We count all answers including LocalOnly e.g., /etc/hosts. If we
3267         // exclude that, v4ans/v6ans will be zero and we would wrongly think that
3268         // we did not answer questions and setup the status to deliver triggers.
3269         if (question->qtype == kDNSType_A)
3270             req->u.addrinfo.v4ans = 1;
3271         if (question->qtype == kDNSType_AAAA)
3272             req->u.addrinfo.v6ans = 1;
3273     }
3274     else if ((AddRecord == QC_add) && req->hdr.op == query_request)
3275     {
3276         if (question->qtype == kDNSType_A || question->qtype == kDNSType_AAAA)
3277             req->u.queryrecord.ans = 1;
3278     }
3279 
3280 #if APPLE_OSX_mDNSResponder
3281 #if !NO_WCF
3282     CHECK_WCF_FUNCTION(WCFIsServerRunning)
3283     {
3284         struct xucred x;
3285         socklen_t xucredlen = sizeof(x);
3286 
3287         if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
3288         {
3289             if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
3290                 (x.cr_version == XUCRED_VERSION))
3291             {
3292                 struct sockaddr_storage addr;
3293                 addr.ss_len = 0;
3294                 if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
3295                 {
3296                     if (answer->rrtype == kDNSType_A)
3297                     {
3298                         struct sockaddr_in *const sin = (struct sockaddr_in *)&addr;
3299                         sin->sin_port = 0;
3300                         // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3301                         // sin->sin_addr.s_addr = answer->rdata->u.ipv4.NotAnInteger;
3302                         if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(mDNSv4Addr)), answer))
3303                             LogMsg("queryrecord_result_reply: WCF AF_INET putRData failed");
3304                         else
3305                         {
3306                             addr.ss_len = sizeof (struct sockaddr_in);
3307                             addr.ss_family = AF_INET;
3308                         }
3309                     }
3310                     else if (answer->rrtype == kDNSType_AAAA)
3311                     {
3312                         struct sockaddr_in6 *const sin6 = (struct sockaddr_in6 *)&addr;
3313                         sin6->sin6_port = 0;
3314                         // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3315                         // sin6->sin6_addr.__u6_addr.__u6_addr32[0] = answer->rdata->u.ipv6.l[0];
3316                         // sin6->sin6_addr.__u6_addr.__u6_addr32[1] = answer->rdata->u.ipv6.l[1];
3317                         // sin6->sin6_addr.__u6_addr.__u6_addr32[2] = answer->rdata->u.ipv6.l[2];
3318                         // sin6->sin6_addr.__u6_addr.__u6_addr32[3] = answer->rdata->u.ipv6.l[3];
3319                         if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(mDNSv6Addr)), answer))
3320                             LogMsg("queryrecord_result_reply: WCF AF_INET6 putRData failed");
3321                         else
3322                         {
3323                             addr.ss_len = sizeof (struct sockaddr_in6);
3324                             addr.ss_family = AF_INET6;
3325                         }
3326                     }
3327                     if (addr.ss_len)
3328                     {
3329                         debugf("queryrecord_result_reply: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
3330                         CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3331                         {
3332                             WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
3333                         }
3334                     }
3335                 }
3336                 else if (answer->rrtype == kDNSType_CNAME)
3337                 {
3338                     domainname cname;
3339                     char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
3340                     if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
3341                         LogMsg("queryrecord_result_reply: WCF CNAME putRData failed");
3342                     else
3343                     {
3344                         ConvertDomainNameToCString(&cname, cname_cstr);
3345                         CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3346                         {
3347                             WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
3348                         }
3349                     }
3350                 }
3351             }
3352             else my_perror("queryrecord_result_reply: ERROR: getsockopt LOCAL_PEERCRED");
3353         }
3354     }
3355 #endif
3356 #endif
3357 }
3358 
3359 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
3360 {
3361     request_state *req = question->QuestionContext;
3362     DNSServiceErrorType error = kDNSServiceErr_NoError;
3363     DNSQuestion *q = mDNSNULL;
3364 
3365 #if APPLE_OSX_mDNSResponder
3366     {
3367         // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
3368         // get any callbacks from the core after this.
3369         if (!req)
3370         {
3371             LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3372             return;
3373         }
3374         if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
3375             q = &req->u.queryrecord.q;
3376         else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
3377             q = &req->u.addrinfo.q4;
3378         else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
3379             q = &req->u.addrinfo.q6;
3380 
3381         if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
3382         {
3383             mStatus err;
3384             domainname *orig = question->qnameOrig;
3385 
3386             LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
3387             mDNS_StopQuery(m, question);
3388             question->QuestionContext = mDNSNULL;
3389 
3390             // We got a negative response for the SOA record indicating that .local does not exist.
3391             // But we might have other search domains (that does not end in .local) that can be
3392             // appended to this question. In that case, we want to retry the question. Otherwise,
3393             // we don't want to try this question as unicast.
3394             if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
3395             {
3396                 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
3397                 return;
3398             }
3399 
3400             // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
3401             //
3402             // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
3403             // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
3404             // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
3405             // SendAdditionalQuery as to how qnameOrig gets initialized.
3406             *question              = *q;
3407             question->InterfaceID  = mDNSInterface_Unicast;
3408             question->ExpectUnique = mDNStrue;
3409             question->qnameOrig    = orig;
3410 
3411             LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
3412 
3413             // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
3414             // Hence, we need to set it explicitly here.
3415             question->QuestionContext = req;
3416             err = mDNS_StartQuery(m, question);
3417             if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3418 
3419             // If we got a positive response to local SOA, then try the .local question as unicast
3420             if (answer->RecordType != kDNSRecordTypePacketNegative) return;
3421 
3422             // Fall through and get the next search domain. The question is pointing at .local
3423             // and we don't want to try that. Try the next search domain. Don't try with local
3424             // search domains for the unicast question anymore.
3425             //
3426             // Note: we started the question above which will be stopped immediately (never sent on the wire)
3427             // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
3428             // question has already started.
3429             question->AppendLocalSearchDomains = 0;
3430         }
3431 
3432         if (q && AddRecord && AddRecord != QC_dnssec && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
3433         {
3434             // If we get a negative response to the unicast query that we sent above, retry after appending search domains
3435             // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
3436             // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
3437             // To keep things simple, we handle unicast ".local" separately here.
3438             LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3439             if (RetryQuestionWithSearchDomains(question, req, AddRecord))
3440                 return;
3441             if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
3442             {
3443                 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
3444                 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
3445                 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
3446                 // in the list. We leave it disabled so that it does not hit the wire.
3447                 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3448                 question->ThisQInterval = 0;
3449             }
3450         }
3451         // 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
3452         // domains to append for "q2". In all cases, fall through and deliver the response
3453     }
3454 #endif // APPLE_OSX_mDNSResponder
3455 
3456     // If a query is being suppressed for some reason, we don't have to do any other
3457     // processing.
3458     //
3459     // Note: We don't check for "SuppressQuery" and instead use QC_suppressed because
3460     // the "core" needs to temporarily turn off SuppressQuery to answer this query.
3461     if (AddRecord == QC_suppressed)
3462     {
3463         LogDebug("queryrecord_result_callback: Suppressed question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3464         queryrecord_result_reply(m, req, question, answer, AddRecord, kDNSServiceErr_NoSuchRecord);
3465         return;
3466     }
3467 
3468     if (answer->RecordType == kDNSRecordTypePacketNegative)
3469     {
3470         // If this question needs to be timed out and we have reached the stop time, mark
3471         // the error as timeout. It is possible that we might get a negative response from an
3472         // external DNS server at the same time when this question reaches its stop time. We
3473         // can't tell the difference as there is no indication in the callback. This should
3474         // be okay as we will be timing out this query anyway.
3475         mDNS_Lock(m);
3476         if (question->TimeoutQuestion)
3477         {
3478             if ((m->timenow - question->StopTime) >= 0)
3479             {
3480                 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3481                 error = kDNSServiceErr_Timeout;
3482             }
3483         }
3484         mDNS_Unlock(m);
3485         // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
3486         // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
3487         // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
3488         // server is going to assert that pretty much every single multicast name doesn't exist.
3489         //
3490         // If we are timing out this query, we need to deliver the negative answer to the application
3491         if (error != kDNSServiceErr_Timeout)
3492         {
3493             if (!answer->InterfaceID && IsLocalDomain(answer->name))
3494             {
3495                 // Sanity check: "q" will be set only if "question" is the .local unicast query.
3496                 if (!q)
3497                 {
3498                     LogMsg("queryrecord_result_callback: ERROR!! answering multicast question %s with unicast cache record",
3499                         RRDisplayString(m, answer));
3500                     return;
3501                 }
3502 #if APPLE_OSX_mDNSResponder
3503                 if (!ShouldDeliverNegativeResponse(question))
3504                 {
3505                     return;
3506                 }
3507 #endif  // APPLE_OSX_mDNSResponder
3508                 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with negative unicast response", question->qname.c,
3509                     DNSTypeName(question->qtype));
3510             }
3511             error = kDNSServiceErr_NoSuchRecord;
3512         }
3513     }
3514     // If we get a negative answer, try appending search domains. Don't append search domains
3515     // - if we are timing out this question
3516     // - if the negative response was received as a result of a multicast query
3517     // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
3518     // - if this response is forced e.g., dnssec validation result
3519     if (error != kDNSServiceErr_Timeout)
3520     {
3521         if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord && AddRecord != QC_dnssec)
3522         {
3523             // If the original question did not end in .local, we did not send an SOA query
3524             // to figure out whether we should send an additional unicast query or not. If we just
3525             // appended .local, we need to see if we need to send an additional query. This should
3526             // normally happen just once because after we append .local, we ignore all negative
3527             // responses for .local above.
3528             LogDebug("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3529             if (RetryQuestionWithSearchDomains(question, req, AddRecord))
3530             {
3531                 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
3532                 // be anywhere in the search domain list.
3533 #if APPLE_OSX_mDNSResponder
3534                 mStatus err = mStatus_NoError;
3535                 err = SendAdditionalQuery(question, req, err);
3536                 if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
3537 #endif // APPLE_OSX_mDNSResponder
3538                 return;
3539             }
3540         }
3541     }
3542     queryrecord_result_reply(m, req, question, answer, AddRecord, error);
3543 }
3544 
3545 mDNSlocal void queryrecord_termination_callback(request_state *request)
3546 {
3547     LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) STOP PID[%d](%s)",
3548         request->sd, request->flags, request->interfaceIndex, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype), request->process_id, request->pid_name);
3549     if (request->u.queryrecord.q.QuestionContext)
3550     {
3551         mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q);  // no need to error check
3552         LogMcastQ(&request->u.queryrecord.q, request, q_stop);
3553         request->u.queryrecord.q.QuestionContext = mDNSNULL;
3554     }
3555     else
3556     {
3557         DNSQuestion *question = &request->u.queryrecord.q;
3558         LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3559     }
3560 
3561     if (request->u.queryrecord.q.qnameOrig)
3562     {
3563         freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
3564         request->u.queryrecord.q.qnameOrig = mDNSNULL;
3565     }
3566 
3567     if (callExternalHelpers(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->u.queryrecord.q.flags))
3568     {
3569         LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
3570         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);
3571     }
3572     if (request->u.queryrecord.q2)
3573     {
3574         if (request->u.queryrecord.q2->QuestionContext)
3575         {
3576             LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
3577             mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
3578             LogMcastQ(request->u.queryrecord.q2, request, q_stop);
3579         }
3580         else
3581         {
3582             DNSQuestion *question = request->u.queryrecord.q2;
3583             LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3584         }
3585         if (request->u.queryrecord.q2->qnameOrig)
3586         {
3587             LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
3588             freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
3589             request->u.queryrecord.q2->qnameOrig = mDNSNULL;
3590         }
3591         freeL("queryrecord Q2", request->u.queryrecord.q2);
3592         request->u.queryrecord.q2 = mDNSNULL;
3593     }
3594 #if APPLE_OSX_mDNSResponder
3595     {
3596         if (request->u.queryrecord.ans)
3597         {
3598             DNSQuestion *v4q, *v6q;
3599             // If we are receiving poisitive answers, provide the hint to the
3600             // upper layer.
3601             v4q = v6q = mDNSNULL;
3602             if (request->u.queryrecord.q.qtype == kDNSType_A)
3603                 v4q = &request->u.queryrecord.q;
3604             else if (request->u.queryrecord.q.qtype == kDNSType_AAAA)
3605                 v6q = &request->u.queryrecord.q;
3606             mDNSPlatformTriggerDNSRetry(v4q, v6q);
3607         }
3608     }
3609 #endif // APPLE_OSX_mDNSResponder
3610 }
3611 
3612 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
3613 {
3614     DNSQuestion *const q = &request->u.queryrecord.q;
3615     char name[256];
3616     size_t nameLen;
3617     mDNSu16 rrtype, rrclass;
3618     mStatus err;
3619 
3620     DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3621     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3622     mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3623 
3624     // The request is scoped to a specific interface index, but the
3625     // interface is not currently in our list.
3626     if (interfaceIndex && !InterfaceID)
3627     {
3628         if (interfaceIndex > 1)
3629             LogMsg("handle_queryrecord_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
3630                     interfaceIndex, request->process_id, request->pid_name);
3631         // If it's one of the specially defined inteface index values, just return an error.
3632         // Also, caller should return an error immediately if lo0 (index 1) is not configured
3633         // into the current active interfaces.  See background in Radar 21967160.
3634         if (PreDefinedInterfaceIndex(interfaceIndex) || interfaceIndex == 1)
3635         {
3636             LogInfo("handle_queryrecord_request: bad interfaceIndex %d", interfaceIndex);
3637             return(mStatus_BadParamErr);
3638         }
3639 
3640         // Otherwise, use the specified interface index value and the request will
3641         // be applied to that interface when it comes up.
3642         InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
3643         LogInfo("handle_queryrecord_request: query pending for interface index %d", interfaceIndex);
3644     }
3645 
3646     if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
3647     rrtype  = get_uint16(&request->msgptr, request->msgend);
3648     rrclass = get_uint16(&request->msgptr, request->msgend);
3649 
3650     if (!request->msgptr)
3651     { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3652 
3653     request->flags = flags;
3654     request->interfaceIndex = interfaceIndex;
3655     mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
3656 
3657     q->InterfaceID         = InterfaceID;
3658     q->flags               = flags;
3659     q->Target              = zeroAddr;
3660     if (!MakeDomainNameFromDNSNameString(&q->qname, name)) return(mStatus_BadParamErr);
3661 #if 0
3662     if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains)) return (mStatus_NoError);
3663 #endif
3664     q->qtype               = rrtype;
3665     q->qclass              = rrclass;
3666     q->LongLived           = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
3667     q->ExpectUnique        = mDNSfalse;
3668     q->ForceMCast          = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
3669     q->ReturnIntermed      = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3670     q->SuppressUnusable    = (flags & kDNSServiceFlagsSuppressUnusable   ) != 0;
3671     q->TimeoutQuestion     = (flags & kDNSServiceFlagsTimeout            ) != 0;
3672     q->allowExpired        = (EnableAllowExpired && (flags & kDNSServiceFlagsAllowExpiredAnswers) != 0) ? AllowExpired_AllowExpiredAnswers : AllowExpired_None;
3673     q->WakeOnResolve       = 0;
3674     q->UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
3675     if ((flags & kDNSServiceFlagsValidate) != 0)
3676         q->ValidationRequired = DNSSEC_VALIDATION_SECURE;
3677     else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
3678         q->ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
3679     q->ValidatingResponse = 0;
3680     q->ProxyQuestion      = 0;
3681     q->AnonInfo = mDNSNULL;
3682     q->QuestionCallback   = queryrecord_result_callback;
3683     q->QuestionContext    = request;
3684     q->SearchListIndex    = 0;
3685     q->StopTime           = 0;
3686 
3687     q->DNSSECAuthInfo = mDNSNULL;
3688     q->DAIFreeCallback = mDNSNULL;
3689 
3690     //Turn off dnssec validation for local domains and Question Types: RRSIG/ANY(ANY Type is not supported yet)
3691     if ((IsLocalDomain(&q->qname)) || (q->qtype == kDNSServiceType_RRSIG) || (q->qtype == kDNSServiceType_ANY))
3692         q->ValidationRequired = 0;
3693 
3694     // Don't append search domains for fully qualified domain names including queries
3695     // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3696     // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3697     // append search domains or not.  So, we record that information in AppendSearchDomains.
3698     //
3699     // We append search domains only for queries that are a single label. If overriden using command line
3700     // argument "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
3701     // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
3702 
3703     nameLen = strlen(name);
3704     if ((!(q->ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(q->ValidationRequired == DNSSEC_VALIDATION_INSECURE))
3705         && (rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && ((nameLen == 0) || (name[nameLen - 1] != '.')) &&
3706         (AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3707     {
3708         q->AppendSearchDomains = 1;
3709         q->AppendLocalSearchDomains = 1;
3710     }
3711     else
3712     {
3713         q->AppendSearchDomains = 0;
3714         q->AppendLocalSearchDomains = 0;
3715     }
3716 
3717     // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3718     // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3719     // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3720     // the cache
3721     q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3722     q->qnameOrig        = mDNSNULL;
3723     SetQuestionPolicy(q, request);
3724 
3725 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3726     // Determine if this request should be promoted to use BLE triggered discovery.
3727     if (shouldUseBLE(InterfaceID, rrtype, (domainname *)SkipLeadingLabels(&q->qname, 1), &q->qname))
3728     {
3729         q->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
3730         request->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
3731         LogInfo("handle_queryrecord_request: request promoted to use kDNSServiceFlagsAutoTrigger");
3732     }
3733 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3734 
3735     LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START PID[%d](%s)",
3736         request->sd, request->flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype), request->process_id, request->pid_name);
3737     err = mDNS_StartQuery(&mDNSStorage, q);
3738 
3739     if (err)
3740     {
3741         LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3742     }
3743     else
3744     {
3745         request->terminate = queryrecord_termination_callback;
3746         LogMcastQ(q, request, q_start);
3747         if (callExternalHelpers(q->InterfaceID, &q->qname, q->flags))
3748         {
3749             LogDebug("handle_queryrecord_request: calling external_start_browsing_for_service()");
3750             external_start_browsing_for_service(q->InterfaceID, &q->qname, q->qtype, q->flags);
3751         }
3752     }
3753 
3754 #if APPLE_OSX_mDNSResponder
3755     err = SendAdditionalQuery(q, request, err);
3756 #endif // APPLE_OSX_mDNSResponder
3757 
3758     return(err);
3759 }
3760 
3761 // ***************************************************************************
3762 #if COMPILER_LIKES_PRAGMA_MARK
3763 #pragma mark -
3764 #pragma mark - DNSServiceEnumerateDomains
3765 #endif
3766 
3767 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3768                                                 const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3769 {
3770     size_t len;
3771     reply_state *reply;
3772     char *data;
3773 
3774     len = sizeof(DNSServiceFlags);
3775     len += sizeof(mDNSu32);
3776     len += sizeof(DNSServiceErrorType);
3777     len += strlen(domain) + 1;
3778 
3779     reply = create_reply(enumeration_reply_op, len, request);
3780     reply->rhdr->flags = dnssd_htonl(flags);
3781     reply->rhdr->ifi   = dnssd_htonl(ifi);
3782     reply->rhdr->error = dnssd_htonl(err);
3783     data = (char *)&reply->rhdr[1];
3784     put_string(domain, &data);
3785     return reply;
3786 }
3787 
3788 mDNSlocal void enum_termination_callback(request_state *request)
3789 {
3790     // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3791     if (request->u.enumeration.flags & kDNSServiceFlagsRegistrationDomains)
3792     {
3793         LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3794         uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3795     }
3796     else
3797     {
3798         LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3799         uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
3800         mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_autoall);
3801     }
3802     mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3803     mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3804 }
3805 
3806 mDNSlocal void enum_result_callback(mDNS *const m,
3807                                     DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3808 {
3809     char domain[MAX_ESCAPED_DOMAIN_NAME];
3810     request_state *request = question->QuestionContext;
3811     DNSServiceFlags flags = 0;
3812     reply_state *reply;
3813     (void)m; // Unused
3814 
3815     if (answer->rrtype != kDNSType_PTR) return;
3816 
3817 #if 0
3818     if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3819 #endif
3820 
3821     // We only return add/remove events for the browse and registration lists
3822     // For the default browse and registration answers, we only give an "ADD" event
3823     if (question == &request->u.enumeration.q_default && !AddRecord) return;
3824 
3825     if (AddRecord)
3826     {
3827         flags |= kDNSServiceFlagsAdd;
3828         if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3829     }
3830 
3831     ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3832     // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3833     // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3834     // network, so we just pass kDNSServiceInterfaceIndexAny
3835     reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3836     if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3837 
3838     LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "ADD" : "RMV", domain);
3839 
3840     append_reply(request, reply);
3841 }
3842 
3843 mDNSlocal mStatus handle_enum_request(request_state *request)
3844 {
3845     mStatus err;
3846     DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3847     DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3848     mDNS_DomainType t_all     = reg ? mDNS_DomainTypeRegistration        : mDNS_DomainTypeBrowse;
3849     mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3850     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3851     mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3852     if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3853 
3854     if (!request->msgptr)
3855     { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3856 
3857     request->flags = flags;
3858     request->interfaceIndex = interfaceIndex;
3859 
3860     // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
3861     request->u.enumeration.flags = reg;
3862 
3863     // enumeration requires multiple questions, so we must link all the context pointers so that
3864     // necessary context can be reached from the callbacks
3865     request->u.enumeration.q_all.QuestionContext = request;
3866     request->u.enumeration.q_default.QuestionContext = request;
3867     if (!reg) request->u.enumeration.q_autoall.QuestionContext = request;
3868 
3869     // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3870     if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
3871 
3872     // make the calls
3873     LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
3874                  (flags & kDNSServiceFlagsBrowseDomains      ) ? "kDNSServiceFlagsBrowseDomains" :
3875                  (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3876     err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
3877     if (!err)
3878     {
3879         err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
3880         if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3881         else if (!reg)
3882         {
3883             err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_autoall, mDNS_DomainTypeBrowseAutomatic, NULL, InterfaceID, enum_result_callback, request);
3884             if (err)
3885             {
3886                 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3887                 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3888             }
3889         }
3890         if (!err) request->terminate = enum_termination_callback;
3891     }
3892     if (!err)
3893     {
3894         // Start the domain enumeration queries to discover the WAB Browse/Registration domains
3895         if (reg)
3896         {
3897             LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3898             uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3899         }
3900         else
3901         {
3902             LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3903             uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
3904         }
3905     }
3906 
3907     return(err);
3908 }
3909 
3910 // ***************************************************************************
3911 #if COMPILER_LIKES_PRAGMA_MARK
3912 #pragma mark -
3913 #pragma mark - DNSServiceReconfirmRecord & Misc
3914 #endif
3915 
3916 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
3917 {
3918     mStatus status = mStatus_BadParamErr;
3919     AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
3920     if (rr)
3921     {
3922         status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
3923         LogOperation(
3924             (status == mStatus_NoError) ?
3925             "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated PID[%d](%s)" :
3926             "%3d: DNSServiceReconfirmRecord(%s) interface %d failed PID[%d](%s) status %d",
3927             request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
3928             mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse),
3929             request->process_id, request->pid_name, status);
3930         freeL("AuthRecord/handle_reconfirm_request", rr);
3931     }
3932     return(status);
3933 }
3934 
3935 #if APPLE_OSX_mDNSResponder
3936 
3937 mDNSlocal mStatus handle_release_request(request_state *request)
3938 {
3939     mStatus err = 0;
3940     char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
3941     domainname instance;
3942 
3943     // extract the data from the message
3944     DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3945 
3946     if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
3947         get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3948         get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
3949     {
3950         LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
3951         return(mStatus_BadParamErr);
3952     }
3953 
3954     if (!request->msgptr)
3955     {
3956         LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request->sd);
3957         return(mStatus_BadParamErr);
3958     }
3959 
3960     if (build_domainname_from_strings(&instance, name, regtype, domain) < 0)
3961     {
3962         LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name, regtype, domain);
3963         return(mStatus_BadParamErr);
3964     }
3965 
3966     LogOperation("%3d: PeerConnectionRelease(%X %##s) START PID[%d](%s)",
3967                  request->sd, flags, instance.c, request->process_id, request->pid_name);
3968 
3969     external_connection_release(&instance);
3970     return(err);
3971 }
3972 
3973 #else   // APPLE_OSX_mDNSResponder
3974 
3975 mDNSlocal mStatus handle_release_request(request_state *request)
3976 {
3977     (void) request;
3978     return mStatus_UnsupportedErr;
3979 }
3980 
3981 #endif  // APPLE_OSX_mDNSResponder
3982 
3983 mDNSlocal mStatus handle_setdomain_request(request_state *request)
3984 {
3985     char domainstr[MAX_ESCAPED_DOMAIN_NAME];
3986     domainname domain;
3987     DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3988     (void)flags; // Unused
3989     if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3990         !MakeDomainNameFromDNSNameString(&domain, domainstr))
3991     { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3992 
3993     LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
3994     return(mStatus_NoError);
3995 }
3996 
3997 typedef packedstruct
3998 {
3999     mStatus err;
4000     mDNSu32 len;
4001     mDNSu32 vers;
4002 } DaemonVersionReply;
4003 
4004 mDNSlocal void handle_getproperty_request(request_state *request)
4005 {
4006     const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
4007     char prop[256];
4008     if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
4009     {
4010         LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
4011         if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
4012         {
4013             DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
4014             send_all(request->sd, (const char *)&x, sizeof(x));
4015             return;
4016         }
4017     }
4018 
4019     // If we didn't recogize the requested property name, return BadParamErr
4020     send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
4021 }
4022 
4023 #ifdef APPLE_OSX_mDNSResponder
4024 // The caller can specify either the pid or the uuid. If the pid is not specified,
4025 // update the effective uuid. Don't overwrite the pid which is used for debugging
4026 // purposes and initialized when the socket is opened.
4027 mDNSlocal void handle_connection_delegate_request(request_state *request)
4028 {
4029     mDNSs32 pid;
4030     socklen_t len;
4031 
4032     LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4033                  request->sd, request->process_id, request->pid_name);
4034     request->terminate = connection_termination;
4035 
4036     len = 0;
4037     pid = get_uint32(&request->msgptr, request->msgend);
4038 #ifdef LOCAL_PEEREPID
4039     if (pid)
4040     {
4041         len = sizeof(pid);
4042         if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &request->process_id, &len) != 0)
4043         {
4044             LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno, strerror(errno));
4045             return;
4046         }
4047         // to extract the process name from the pid value
4048         if (proc_pidinfo(request->process_id, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
4049             return;
4050         mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
4051         debugf("handle_connection_delegate_request: process id %d, name %s", request->process_id, request->pid_name);
4052     }
4053 #endif
4054 #ifdef LOCAL_PEEREUUID
4055     if (!pid)
4056     {
4057         len = UUID_SIZE;
4058         if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREUUID, request->uuid, &len) != 0)
4059         {
4060             LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno, strerror(errno));
4061             return;
4062         }
4063         request->validUUID = mDNStrue;
4064     }
4065 #endif
4066 }
4067 #else
4068 mDNSlocal void handle_connection_delegate_request(request_state *request)
4069 {
4070     (void) request;
4071 }
4072 #endif
4073 
4074 typedef packedstruct
4075 {
4076     mStatus err;
4077     mDNSs32 pid;
4078 } PIDInfo;
4079 
4080 mDNSlocal void handle_getpid_request(request_state *request)
4081 {
4082     const request_state *req;
4083     mDNSs32 pid = -1;
4084     mDNSu16 srcport = get_uint16(&request->msgptr, request->msgend);
4085     const DNSQuestion *q = NULL;
4086     PIDInfo pi;
4087 
4088     LogMsg("%3d: DNSServiceGetPID START", request->sd);
4089 
4090     for (req = all_requests; req; req=req->next)
4091     {
4092         if (req->hdr.op == query_request)
4093             q = &req->u.queryrecord.q;
4094         else if (req->hdr.op == addrinfo_request)
4095             q = &req->u.addrinfo.q4;
4096         else if (req->hdr.op == addrinfo_request)
4097             q = &req->u.addrinfo.q6;
4098 
4099         if (q && q->LocalSocket != NULL)
4100         {
4101             mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4102             if (port == srcport)
4103             {
4104                 pid = req->process_id;
4105                 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s] question %##s", htons(srcport), pid, req->pid_name, q->qname.c);
4106                 break;
4107             }
4108         }
4109     }
4110     // If we cannot find in the client requests, look to see if this was
4111     // started by mDNSResponder.
4112     if (pid == -1)
4113     {
4114         for (q = mDNSStorage.Questions; q; q = q->next)
4115         {
4116             if (q && q->LocalSocket != NULL)
4117             {
4118                 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4119                 if (port == srcport)
4120                 {
4121 #if APPLE_OSX_mDNSResponder
4122                     pid = getpid();
4123 #endif // APPLE_OSX_mDNSResponder
4124                     LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s], question %##s", htons(srcport), pid, "_mDNSResponder", q->qname.c);
4125                     break;
4126                 }
4127             }
4128         }
4129     }
4130 
4131     pi.err = 0;
4132     pi.pid = pid;
4133     send_all(request->sd, (const char *)&pi, sizeof(PIDInfo));
4134     LogMsg("%3d: DNSServiceGetPID STOP", request->sd);
4135 }
4136 
4137 // ***************************************************************************
4138 #if COMPILER_LIKES_PRAGMA_MARK
4139 #pragma mark -
4140 #pragma mark - DNSServiceNATPortMappingCreate
4141 #endif
4142 
4143 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
4144 
4145 mDNSlocal void port_mapping_termination_callback(request_state *request)
4146 {
4147     LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](%s)", request->sd,
4148                  DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4149                  mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4150                  request->process_id, request->pid_name);
4151     mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4152 }
4153 
4154 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
4155 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
4156 {
4157     request_state *request = (request_state *)n->clientContext;
4158     reply_state *rep;
4159     int replyLen;
4160     char *data;
4161 
4162     if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
4163 
4164     // calculate reply data length
4165     replyLen = sizeof(DNSServiceFlags);
4166     replyLen += 3 * sizeof(mDNSu32);  // if index + addr + ttl
4167     replyLen += sizeof(DNSServiceErrorType);
4168     replyLen += 2 * sizeof(mDNSu16);  // Internal Port + External Port
4169     replyLen += sizeof(mDNSu8);       // protocol
4170 
4171     rep = create_reply(port_mapping_reply_op, replyLen, request);
4172 
4173     rep->rhdr->flags = dnssd_htonl(0);
4174     rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
4175     rep->rhdr->error = dnssd_htonl(n->Result);
4176 
4177     data = (char *)&rep->rhdr[1];
4178 
4179     *data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
4180     *data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
4181     *data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
4182     *data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
4183     *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
4184     *data++ = request->u.pm.NATinfo.IntPort.b[0];
4185     *data++ = request->u.pm.NATinfo.IntPort.b[1];
4186     *data++ = request->u.pm.NATinfo.ExternalPort.b[0];
4187     *data++ = request->u.pm.NATinfo.ExternalPort.b[1];
4188     put_uint32(request->u.pm.NATinfo.Lifetime, &data);
4189 
4190     LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
4191                  DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4192                  mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4193                  &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
4194 
4195     append_reply(request, rep);
4196 }
4197 
4198 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
4199 {
4200     mDNSu32 ttl = 0;
4201     mStatus err = mStatus_NoError;
4202 
4203     DNSServiceFlags flags          = get_flags(&request->msgptr, request->msgend);
4204     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4205     mDNSInterfaceID InterfaceID    = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4206     mDNSu8 protocol       = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
4207     (void)flags; // Unused
4208     if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
4209     if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
4210     else
4211     {
4212         request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
4213         request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
4214         request->u.pm.ReqExt.b[0]          = *request->msgptr++;
4215         request->u.pm.ReqExt.b[1]          = *request->msgptr++;
4216         ttl = get_uint32(&request->msgptr, request->msgend);
4217     }
4218 
4219     if (!request->msgptr)
4220     { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4221 
4222     if (protocol == 0)  // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
4223     {
4224         if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
4225     }
4226     else
4227     {
4228         if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
4229         if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
4230     }
4231 
4232     request->flags                       = flags;
4233     request->interfaceIndex              = interfaceIndex;
4234     request->u.pm.NATinfo.Protocol       = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
4235     //       u.pm.NATinfo.IntPort        = already set above
4236     request->u.pm.NATinfo.RequestedPort  = request->u.pm.ReqExt;
4237     request->u.pm.NATinfo.NATLease       = ttl;
4238     request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
4239     request->u.pm.NATinfo.clientContext  = request;
4240 
4241     LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](%s)", request->sd,
4242                  protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4243                  request->process_id, request->pid_name);
4244     err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4245     if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
4246     else request->terminate = port_mapping_termination_callback;
4247 
4248     return(err);
4249 }
4250 
4251 // ***************************************************************************
4252 #if COMPILER_LIKES_PRAGMA_MARK
4253 #pragma mark -
4254 #pragma mark - DNSServiceGetAddrInfo
4255 #endif
4256 
4257 mDNSlocal void addrinfo_termination_callback(request_state *request)
4258 {
4259     LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP PID[%d](%s)", request->sd, request->u.addrinfo.q4.qname.c,
4260                   request->process_id, request->pid_name);
4261 
4262     if (request->u.addrinfo.q4.QuestionContext)
4263     {
4264         mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
4265         LogMcastQ(&request->u.addrinfo.q4, request, q_stop);
4266         request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4267 
4268         if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, request->flags))
4269         {
4270             LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for A record");
4271             external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, kDNSServiceType_A, request->flags);
4272         }
4273     }
4274     if (request->u.addrinfo.q4.qnameOrig)
4275     {
4276         freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
4277         request->u.addrinfo.q4.qnameOrig = mDNSNULL;
4278     }
4279     if (request->u.addrinfo.q42)
4280     {
4281         if (request->u.addrinfo.q42->QuestionContext)
4282         {
4283             LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
4284             mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
4285             LogMcastQ(request->u.addrinfo.q42, request, q_stop);
4286         }
4287         if (request->u.addrinfo.q42->qnameOrig)
4288         {
4289             LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
4290             freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
4291             request->u.addrinfo.q42->qnameOrig = mDNSNULL;
4292         }
4293         freeL("addrinfo Q42", request->u.addrinfo.q42);
4294         request->u.addrinfo.q42 = mDNSNULL;
4295     }
4296 
4297     if (request->u.addrinfo.q6.QuestionContext)
4298     {
4299         mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4300         LogMcastQ(&request->u.addrinfo.q6, request, q_stop);
4301         request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4302 
4303         if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, request->flags))
4304         {
4305             LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for AAAA record");
4306             external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, kDNSServiceType_AAAA, request->flags);
4307         }
4308     }
4309     if (request->u.addrinfo.q6.qnameOrig)
4310     {
4311         freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
4312         request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4313     }
4314     if (request->u.addrinfo.q62)
4315     {
4316         if (request->u.addrinfo.q62->QuestionContext)
4317         {
4318             LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
4319             mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
4320             LogMcastQ(request->u.addrinfo.q62, request, q_stop);
4321         }
4322         if (request->u.addrinfo.q62->qnameOrig)
4323         {
4324             LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
4325             freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
4326             request->u.addrinfo.q62->qnameOrig = mDNSNULL;
4327         }
4328         freeL("addrinfo Q62", request->u.addrinfo.q62);
4329         request->u.addrinfo.q62 = mDNSNULL;
4330     }
4331 #if APPLE_OSX_mDNSResponder
4332     {
4333         DNSQuestion *v4q, *v6q;
4334         v4q = v6q = mDNSNULL;
4335         if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
4336         {
4337             // If we are not delivering answers, we may be timing out prematurely.
4338             // Note down the current state so that we know to retry when we see a
4339             // valid response again.
4340             if (request->u.addrinfo.q4.TimeoutQuestion && !request->u.addrinfo.v4ans)
4341             {
4342                 mDNSPlatformUpdateDNSStatus(&request->u.addrinfo.q4);
4343             }
4344             // If we have a v4 answer and if we timed out prematurely before, provide
4345             // a trigger to the upper layer so that it can retry questions if needed.
4346             if (request->u.addrinfo.v4ans)
4347                 v4q = &request->u.addrinfo.q4;
4348         }
4349         if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4350         {
4351             if (request->u.addrinfo.q6.TimeoutQuestion && !request->u.addrinfo.v6ans)
4352             {
4353                 mDNSPlatformUpdateDNSStatus(&request->u.addrinfo.q6);
4354             }
4355             if (request->u.addrinfo.v6ans)
4356                 v6q = &request->u.addrinfo.q6;
4357         }
4358         mDNSPlatformTriggerDNSRetry(v4q, v6q);
4359     }
4360 #endif // APPLE_OSX_mDNSResponder
4361 }
4362 
4363 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
4364 {
4365     char hostname[256];
4366     size_t hostnameLen;
4367     domainname d;
4368     mStatus err = 0;
4369     mDNSs32 serviceIndex   = -1;  // default unscoped value for ServiceID is -1
4370     mDNSInterfaceID InterfaceID;
4371 
4372     DNSServiceFlags flags  = get_flags(&request->msgptr, request->msgend);
4373 
4374     mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4375 
4376     if (flags & kDNSServiceFlagsServiceIndex)
4377     {
4378         // NOTE: kDNSServiceFlagsServiceIndex flag can only be set for DNSServiceGetAddrInfo()
4379         LogInfo("DNSServiceGetAddrInfo: kDNSServiceFlagsServiceIndex is SET by the client");
4380         // if kDNSServiceFlagsServiceIndex is SET,
4381         // interpret the interfaceID as the serviceId and set the interfaceID to 0.
4382         serviceIndex   = interfaceIndex;
4383         interfaceIndex = 0;
4384     }
4385 
4386     mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
4387 
4388     InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4389 
4390     // The request is scoped to a specific interface index, but the
4391     // interface is not currently in our list.
4392     if (interfaceIndex && !InterfaceID)
4393     {
4394         if (interfaceIndex > 1)
4395             LogMsg("handle_addrinfo_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
4396                     interfaceIndex, request->process_id, request->pid_name);
4397         // If it's one of the specially defined inteface index values, just return an error.
4398         if (PreDefinedInterfaceIndex(interfaceIndex))
4399         {
4400             LogInfo("handle_addrinfo_request: bad interfaceIndex %d", interfaceIndex);
4401             return(mStatus_BadParamErr);
4402         }
4403 
4404         // Otherwise, use the specified interface index value and the request will
4405         // be applied to that interface when it comes up.
4406         InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
4407         LogInfo("handle_addrinfo_request: query pending for interface index %d", interfaceIndex);
4408     }
4409 
4410     request->flags                   = flags;
4411     request->interfaceIndex          = interfaceIndex;
4412     request->u.addrinfo.interface_id = InterfaceID;
4413     request->u.addrinfo.flags        = flags;
4414     request->u.addrinfo.protocol     = get_uint32(&request->msgptr, request->msgend);
4415 
4416     if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
4417 
4418     if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
4419 
4420     if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4421 
4422     if (!MakeDomainNameFromDNSNameString(&d, hostname))
4423     { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
4424 
4425 #if 0
4426     if (!AuthorizedDomain(request, &d, AutoBrowseDomains)) return (mStatus_NoError);
4427 #endif
4428 
4429     if (!request->u.addrinfo.protocol)
4430     {
4431         flags |= kDNSServiceFlagsSuppressUnusable;
4432         request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
4433     }
4434 
4435     request->u.addrinfo.q4.InterfaceID         = request->u.addrinfo.q6.InterfaceID         = request->u.addrinfo.interface_id;
4436     request->u.addrinfo.q4.ServiceID           = request->u.addrinfo.q6.ServiceID           = serviceIndex;
4437     request->u.addrinfo.q4.flags               = request->u.addrinfo.q6.flags               = flags;
4438     request->u.addrinfo.q4.Target              = request->u.addrinfo.q6.Target              = zeroAddr;
4439     request->u.addrinfo.q4.qname               = request->u.addrinfo.q6.qname               = d;
4440     request->u.addrinfo.q4.qclass              = request->u.addrinfo.q6.qclass              = kDNSServiceClass_IN;
4441     request->u.addrinfo.q4.LongLived           = request->u.addrinfo.q6.LongLived           = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
4442     request->u.addrinfo.q4.ExpectUnique        = request->u.addrinfo.q6.ExpectUnique        = mDNSfalse;
4443     request->u.addrinfo.q4.ForceMCast          = request->u.addrinfo.q6.ForceMCast          = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
4444     request->u.addrinfo.q4.ReturnIntermed      = request->u.addrinfo.q6.ReturnIntermed      = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
4445     request->u.addrinfo.q4.SuppressUnusable    = request->u.addrinfo.q6.SuppressUnusable    = (flags & kDNSServiceFlagsSuppressUnusable   ) != 0;
4446     request->u.addrinfo.q4.TimeoutQuestion     = request->u.addrinfo.q6.TimeoutQuestion     = (flags & kDNSServiceFlagsTimeout            ) != 0;
4447     request->u.addrinfo.q4.allowExpired        = request->u.addrinfo.q6.allowExpired        = (EnableAllowExpired && (flags & kDNSServiceFlagsAllowExpiredAnswers) != 0) ? AllowExpired_AllowExpiredAnswers : AllowExpired_None;
4448     request->u.addrinfo.q4.WakeOnResolve       = request->u.addrinfo.q6.WakeOnResolve    = 0;
4449     request->u.addrinfo.q4.UseBackgroundTrafficClass = request->u.addrinfo.q6.UseBackgroundTrafficClass  = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
4450     if ((flags & kDNSServiceFlagsValidate) != 0)
4451         request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE;
4452     else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
4453         request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
4454     request->u.addrinfo.q4.ValidatingResponse = request->u.addrinfo.q6.ValidatingResponse = 0;
4455     request->u.addrinfo.q4.ProxyQuestion      = request->u.addrinfo.q6.ProxyQuestion      = 0;
4456     request->u.addrinfo.q4.qnameOrig          = request->u.addrinfo.q6.qnameOrig          = mDNSNULL;
4457     request->u.addrinfo.q4.AnonInfo           = request->u.addrinfo.q6.AnonInfo           = mDNSNULL;
4458 
4459     SetQuestionPolicy(&request->u.addrinfo.q4, request);
4460     SetQuestionPolicy(&request->u.addrinfo.q6, request);
4461 
4462     request->u.addrinfo.q4.StopTime = request->u.addrinfo.q6.StopTime  = 0;
4463 
4464     request->u.addrinfo.q4.DNSSECAuthInfo = request->u.addrinfo.q6.DNSSECAuthInfo = mDNSNULL;
4465     request->u.addrinfo.q4.DAIFreeCallback = request->u.addrinfo.q6.DAIFreeCallback = mDNSNULL;
4466 
4467     //Turn off dnssec validation for local domains
4468     if (IsLocalDomain(&d))
4469         request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = 0;
4470 
4471     hostnameLen = strlen(hostname);
4472 
4473     LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START PID[%d](%s)",
4474         request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c, request->process_id, request->pid_name);
4475 
4476     if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4477     {
4478         request->u.addrinfo.q6.qtype            = kDNSServiceType_AAAA;
4479         request->u.addrinfo.q6.SearchListIndex  = 0;
4480         // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set
4481         if ((!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4482             && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4483         {
4484             request->u.addrinfo.q6.AppendSearchDomains = 1;
4485             request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
4486         }
4487         else
4488         {
4489             request->u.addrinfo.q6.AppendSearchDomains = 0;
4490             request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
4491         }
4492         request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
4493         request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
4494         request->u.addrinfo.q6.QuestionContext  = request;
4495         err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
4496         if (err != mStatus_NoError)
4497         {
4498             LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4499             request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4500         }
4501         #if APPLE_OSX_mDNSResponder
4502         err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
4503         #endif // APPLE_OSX_mDNSResponder
4504         if (!err)
4505         {
4506             request->terminate = addrinfo_termination_callback;
4507             LogMcastQ(&request->u.addrinfo.q6, request, q_start);
4508             if (callExternalHelpers(InterfaceID, &d, flags))
4509             {
4510                 LogDebug("handle_addrinfo_request: calling external_start_browsing_for_service() for AAAA record");
4511                 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags);
4512             }
4513         }
4514     }
4515 
4516     if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4))
4517     {
4518         request->u.addrinfo.q4.qtype            = kDNSServiceType_A;
4519         request->u.addrinfo.q4.SearchListIndex  = 0;
4520 
4521         // We append search domains only for queries that are a single label. If overriden using cmd line arg
4522         // "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
4523         // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
4524 
4525         if ((!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4526             && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4527         {
4528             request->u.addrinfo.q4.AppendSearchDomains = 1;
4529             request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
4530         }
4531         else
4532         {
4533             request->u.addrinfo.q4.AppendSearchDomains = 0;
4534             request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
4535         }
4536         request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
4537         request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
4538         request->u.addrinfo.q4.QuestionContext  = request;
4539         err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
4540         if (err != mStatus_NoError)
4541         {
4542             LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4543             request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4544             if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4545             {
4546                 // If we started a query for IPv6, we need to cancel it
4547                 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4548                 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4549 
4550                 if (callExternalHelpers(InterfaceID, &d, flags))
4551                 {
4552                     LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for AAAA record");
4553                     external_stop_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags);
4554                 }
4555             }
4556         }
4557         #if APPLE_OSX_mDNSResponder
4558         err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
4559         #endif // APPLE_OSX_mDNSResponder
4560         if (!err)
4561         {
4562             request->terminate = addrinfo_termination_callback;
4563             LogMcastQ(&request->u.addrinfo.q4, request, q_start);
4564             if (callExternalHelpers(InterfaceID, &d, flags))
4565             {
4566                 LogDebug("handle_addrinfo_request: calling external_start_browsing_for_service() for A record");
4567                 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_A, flags);
4568             }
4569         }
4570     }
4571 
4572     return(err);
4573 }
4574 
4575 // ***************************************************************************
4576 #if COMPILER_LIKES_PRAGMA_MARK
4577 #pragma mark -
4578 #pragma mark - Main Request Handler etc.
4579 #endif
4580 
4581 mDNSlocal request_state *NewRequest(void)
4582 {
4583     request_state **p = &all_requests;
4584     while (*p)
4585         p=&(*p)->next;
4586     *p = mallocL("request_state", sizeof(request_state));
4587     if (!*p)
4588         FatalError("ERROR: malloc");
4589     mDNSPlatformMemZero(*p, sizeof(request_state));
4590     return(*p);
4591 }
4592 
4593 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
4594 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
4595 mDNSlocal void read_msg(request_state *req)
4596 {
4597     if (req->ts == t_terminated || req->ts == t_error)
4598     { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
4599 
4600     if (req->ts == t_complete)  // this must be death or something is wrong
4601     {
4602         char buf[4];    // dummy for death notification
4603         int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
4604         if (!nread) { req->ts = t_terminated; return; }
4605         if (nread < 0) goto rerror;
4606         LogMsg("%3d: ERROR: read data from a completed request", req->sd);
4607         req->ts = t_error;
4608         return;
4609     }
4610 
4611     if (req->ts != t_morecoming)
4612     { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
4613 
4614     if (req->hdr_bytes < sizeof(ipc_msg_hdr))
4615     {
4616         mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
4617         int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
4618         if (nread == 0) { req->ts = t_terminated; return; }
4619         if (nread < 0) goto rerror;
4620         req->hdr_bytes += nread;
4621         if (req->hdr_bytes > sizeof(ipc_msg_hdr))
4622         { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
4623 
4624         // only read data if header is complete
4625         if (req->hdr_bytes == sizeof(ipc_msg_hdr))
4626         {
4627             ConvertHeaderBytes(&req->hdr);
4628             if (req->hdr.version != VERSION)
4629             { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
4630 
4631             // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
4632             // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
4633             // for other overhead, this means any message above 70kB is definitely bogus.
4634             if (req->hdr.datalen > 70000)
4635             { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
4636             req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
4637             if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
4638             req->msgptr = req->msgbuf;
4639             req->msgend = req->msgbuf + req->hdr.datalen;
4640             mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
4641         }
4642     }
4643 
4644     // If our header is complete, but we're still needing more body data, then try to read it now
4645     // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
4646     // Any time we need to get the error return socket we know we'll have at least one data byte
4647     // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
4648     if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
4649     {
4650         mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
4651         int nread;
4652 #if !defined(_WIN32)
4653         struct iovec vec = { req->msgbuf + req->data_bytes, nleft };    // Tell recvmsg where we want the bytes put
4654         struct msghdr msg;
4655         struct cmsghdr *cmsg;
4656         char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
4657         msg.msg_name       = 0;
4658         msg.msg_namelen    = 0;
4659         msg.msg_iov        = &vec;
4660         msg.msg_iovlen     = 1;
4661         msg.msg_control    = cbuf;
4662         msg.msg_controllen = sizeof(cbuf);
4663         msg.msg_flags      = 0;
4664         nread = recvmsg(req->sd, &msg, 0);
4665 #else
4666         nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
4667 #endif
4668         if (nread == 0) { req->ts = t_terminated; return; }
4669         if (nread < 0) goto rerror;
4670         req->data_bytes += nread;
4671         if (req->data_bytes > req->hdr.datalen)
4672         { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
4673 #if !defined(_WIN32)
4674         cmsg = CMSG_FIRSTHDR(&msg);
4675 #if DEBUG_64BIT_SCM_RIGHTS
4676         LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf), sizeof(cbuf), SOL_SOCKET, SCM_RIGHTS);
4677         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);
4678 #endif // DEBUG_64BIT_SCM_RIGHTS
4679         if (cmsg && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
4680         {
4681 #if APPLE_OSX_mDNSResponder
4682             // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
4683             // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
4684             // and it's convenient to repurpose the existing fd-passing code here for that task
4685             if (req->hdr.op == send_bpf)
4686             {
4687                 dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4688                 LogOperation("%3d: Got len %d, BPF %d", req->sd, cmsg->cmsg_len, x);
4689                 mDNSPlatformReceiveBPF_fd(x);
4690             }
4691             else
4692 #endif // APPLE_OSX_mDNSResponder
4693             req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4694 #if DEBUG_64BIT_SCM_RIGHTS
4695             LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
4696 #endif // DEBUG_64BIT_SCM_RIGHTS
4697             if (req->data_bytes < req->hdr.datalen)
4698             {
4699                 LogMsg("%3d: Client(PID [%d](%s)) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
4700                        req->sd, req->process_id, req->pid_name, req->errsd, req->data_bytes, req->hdr.datalen);
4701                 req->ts = t_error;
4702                 return;
4703             }
4704         }
4705 #endif
4706     }
4707 
4708     // If our header and data are both complete, see if we need to make our separate error return socket
4709     if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
4710     {
4711         if (req->terminate && req->hdr.op != cancel_request)
4712         {
4713             dnssd_sockaddr_t cliaddr;
4714 #if defined(USE_TCP_LOOPBACK)
4715             mDNSOpaque16 port;
4716             u_long opt = 1;
4717             port.b[0] = req->msgptr[0];
4718             port.b[1] = req->msgptr[1];
4719             req->msgptr += 2;
4720             cliaddr.sin_family      = AF_INET;
4721             cliaddr.sin_port        = port.NotAnInteger;
4722             cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4723 #else
4724             char ctrl_path[MAX_CTLPATH];
4725             get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH);  // path is first element in message buffer
4726             mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
4727             cliaddr.sun_family = AF_LOCAL;
4728             mDNSPlatformStrLCopy(cliaddr.sun_path, ctrl_path, sizeof(cliaddr.sun_path));
4729             // If the error return path UDS name is empty string, that tells us
4730             // that this is a new version of the library that's going to pass us
4731             // the error return path socket via sendmsg/recvmsg
4732             if (ctrl_path[0] == 0)
4733             {
4734                 if (req->errsd == req->sd)
4735                 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
4736                 goto got_errfd;
4737             }
4738 #endif
4739 
4740             req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
4741             if (!dnssd_SocketValid(req->errsd))
4742             {
4743                 my_throttled_perror("ERROR: socket");
4744                 req->ts = t_error;
4745                 return;
4746             }
4747 
4748             if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
4749             {
4750 #if !defined(USE_TCP_LOOPBACK)
4751                 struct stat sb;
4752                 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
4753                        req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4754                 if (stat(cliaddr.sun_path, &sb) < 0)
4755                     LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4756                 else
4757                     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);
4758 #endif
4759                 req->ts = t_error;
4760                 return;
4761             }
4762 
4763 #if !defined(USE_TCP_LOOPBACK)
4764 got_errfd:
4765 #endif
4766             LogDebug("%3d: Result code socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
4767 #if defined(_WIN32)
4768             if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
4769 #else
4770             if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
4771 #endif
4772             {
4773                 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
4774                        req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4775                 req->ts = t_error;
4776                 return;
4777             }
4778         }
4779 
4780         req->ts = t_complete;
4781     }
4782 
4783     return;
4784 
4785 rerror:
4786     if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
4787     LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4788     req->ts = t_error;
4789 }
4790 
4791 mDNSlocal mStatus handle_client_request(request_state *req)
4792 {
4793     mStatus err = mStatus_NoError;
4794     switch(req->hdr.op)
4795     {
4796             // These are all operations that have their own first-class request_state object
4797         case connection_request:
4798             LogOperation("%3d: DNSServiceCreateConnection START PID[%d](%s)",
4799                          req->sd, req->process_id, req->pid_name);
4800             req->terminate = connection_termination;
4801             break;
4802         case connection_delegate_request:
4803             LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4804                          req->sd, req->process_id, req->pid_name);
4805             req->terminate = connection_termination;
4806             handle_connection_delegate_request(req);
4807             break;
4808         case resolve_request:              err = handle_resolve_request     (req);  break;
4809         case query_request:                err = handle_queryrecord_request (req);  break;
4810         case browse_request:               err = handle_browse_request      (req);  break;
4811         case reg_service_request:          err = handle_regservice_request  (req);  break;
4812         case enumeration_request:          err = handle_enum_request        (req);  break;
4813         case reconfirm_record_request:     err = handle_reconfirm_request   (req);  break;
4814         case setdomain_request:            err = handle_setdomain_request   (req);  break;
4815         case getproperty_request:                handle_getproperty_request (req);  break;
4816         case getpid_request:                     handle_getpid_request      (req);  break;
4817         case port_mapping_request:         err = handle_port_mapping_request(req);  break;
4818         case addrinfo_request:             err = handle_addrinfo_request    (req);  break;
4819         case send_bpf:                     /* Do nothing for send_bpf */            break;
4820 
4821             // These are all operations that work with an existing request_state object
4822         case reg_record_request:           err = handle_regrecord_request   (req);  break;
4823         case add_record_request:           err = handle_add_request         (req);  break;
4824         case update_record_request:        err = handle_update_request      (req);  break;
4825         case remove_record_request:        err = handle_removerecord_request(req);  break;
4826         case cancel_request:                     handle_cancel_request      (req);  break;
4827         case release_request:              err = handle_release_request     (req);  break;
4828         default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
4829                         req->sd, req->hdr.op, req->process_id, req->pid_name);
4830             err = mStatus_BadParamErr;
4831             break;
4832     }
4833 
4834     return err;
4835 }
4836 
4837 #define RecordOrientedOp(X) \
4838     ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
4839 
4840 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
4841 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
4842 
4843 mDNSlocal void request_callback(int fd, short filter, void *info)
4844 {
4845     mStatus err = 0;
4846     request_state *req = info;
4847     mDNSs32 min_size = sizeof(DNSServiceFlags);
4848     (void)fd; // Unused
4849     (void)filter; // Unused
4850 
4851     for (;;)
4852     {
4853         read_msg(req);
4854         if (req->ts == t_morecoming)
4855             return;
4856         if (req->ts == t_terminated || req->ts == t_error)
4857         {
4858             AbortUnlinkAndFree(req);
4859             return;
4860         }
4861         if (req->ts != t_complete)
4862         {
4863             LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req->ts, req->process_id, req->pid_name);
4864             AbortUnlinkAndFree(req);
4865             return;
4866         }
4867 
4868         switch(req->hdr.op)            //          Interface       + other data
4869         {
4870             case connection_request:       min_size = 0;                                                                           break;
4871             case connection_delegate_request: min_size = 4; /* pid */                                                              break;
4872             case reg_service_request:      min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
4873             case add_record_request:       min_size +=                   4 /* type, rdlen */              + 4 /* ttl */;           break;
4874             case update_record_request:    min_size +=                   2 /* rdlen */                    + 4 /* ttl */;           break;
4875             case remove_record_request:                                                                                            break;
4876             case browse_request:           min_size += sizeof(mDNSu32) + 2 /* type, domain */;                                     break;
4877             case resolve_request:          min_size += sizeof(mDNSu32) + 3 /* type, type, domain */;                               break;
4878             case query_request:            min_size += sizeof(mDNSu32) + 1 /* name */                     + 4 /* type, class*/;    break;
4879             case enumeration_request:      min_size += sizeof(mDNSu32);                                                            break;
4880             case reg_record_request:       min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */;  break;
4881             case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */;                break;
4882             case setdomain_request:        min_size +=                   1 /* domain */;                                           break;
4883             case getproperty_request:      min_size = 2;                                                                           break;
4884             case getpid_request:           min_size = 2;                                                                           break;
4885             case port_mapping_request:     min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */    + 4 /* ttl */;  break;
4886             case addrinfo_request:         min_size += sizeof(mDNSu32) + 4 /* v4/v6 */   + 1 /* hostname */;                       break;
4887             case send_bpf:                 // Same as cancel_request below
4888             case cancel_request:           min_size = 0;                                                                           break;
4889             case release_request:          min_size += sizeof(mDNSu32) + 3 /* type, type, domain */;                               break;
4890             default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
4891                             req->hdr.op, req->process_id, req->pid_name);
4892                      min_size = -1;                                                                                                break;
4893         }
4894 
4895         if ((mDNSs32)req->data_bytes < min_size)
4896         {
4897             LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
4898                     req->data_bytes, req->hdr.op, min_size, req->process_id, req->pid_name);
4899             AbortUnlinkAndFree(req);
4900             return;
4901         }
4902         if (LightweightOp(req->hdr.op) && !req->terminate)
4903         {
4904             LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
4905                     req->hdr.op, req->process_id, req->pid_name);
4906             AbortUnlinkAndFree(req);
4907             return;
4908         }
4909 
4910         // If req->terminate is already set, this means this operation is sharing an existing connection
4911         if (req->terminate && !LightweightOp(req->hdr.op))
4912         {
4913             request_state *newreq = NewRequest();
4914             newreq->primary = req;
4915             newreq->sd      = req->sd;
4916             newreq->errsd   = req->errsd;
4917             newreq->uid     = req->uid;
4918             newreq->hdr     = req->hdr;
4919             newreq->msgbuf  = req->msgbuf;
4920             newreq->msgptr  = req->msgptr;
4921             newreq->msgend  = req->msgend;
4922             // if the parent request is a delegate connection, copy the
4923             // relevant bits
4924             if (req->validUUID)
4925             {
4926                 newreq->validUUID = mDNStrue;
4927                 mDNSPlatformMemCopy(newreq->uuid, req->uuid, UUID_SIZE);
4928             }
4929             else
4930             {
4931                 if (req->process_id)
4932                 {
4933                     newreq->process_id = req->process_id;
4934                     mDNSPlatformStrLCopy(newreq->pid_name, req->pid_name, (mDNSu32)sizeof(newreq->pid_name));
4935                 }
4936                 else
4937                 {
4938                     set_peer_pid(newreq);
4939                 }
4940             }
4941             req = newreq;
4942         }
4943 
4944         // Check if the request wants no asynchronous replies.
4945         if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
4946 
4947         // If we're shutting down, don't allow new client requests
4948         // We do allow "cancel" and "getproperty" during shutdown
4949         if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
4950             err = mStatus_ServiceNotRunning;
4951         else
4952             err = handle_client_request(req);
4953 
4954         // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
4955         if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
4956 
4957         // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
4958         // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
4959         if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf && req->hdr.op != getpid_request)
4960         {
4961             const mStatus err_netorder = dnssd_htonl(err);
4962             send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
4963             if (req->errsd != req->sd)
4964             {
4965                 LogDebug("%3d: Result code socket %d closed  %08X %08X (%d)",
4966                          req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
4967                 dnssd_close(req->errsd);
4968                 req->errsd = req->sd;
4969                 // Also need to reset the parent's errsd, if this is a subordinate operation
4970                 if (req->primary) req->primary->errsd = req->primary->sd;
4971             }
4972         }
4973 
4974         // Reset ready to accept the next req on this pipe
4975         if (req->primary) req = req->primary;
4976         req->ts         = t_morecoming;
4977         req->hdr_bytes  = 0;
4978         req->data_bytes = 0;
4979         req->msgbuf     = mDNSNULL;
4980         req->msgptr     = mDNSNULL;
4981         req->msgend     = 0;
4982     }
4983 }
4984 
4985 mDNSlocal void connect_callback(int fd, short filter, void *info)
4986 {
4987     dnssd_sockaddr_t cliaddr;
4988     dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
4989     dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
4990 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
4991     unsigned long optval = 1;
4992 #endif
4993 
4994     (void)filter; // Unused
4995     (void)info; // Unused
4996 
4997     if (!dnssd_SocketValid(sd))
4998     {
4999         if (dnssd_errno != dnssd_EWOULDBLOCK)
5000             my_throttled_perror("ERROR: accept");
5001         return;
5002     }
5003 
5004 #ifdef SO_NOSIGPIPE
5005     // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
5006     if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
5007         LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
5008 #endif
5009 
5010 #if defined(_WIN32)
5011     if (ioctlsocket(sd, FIONBIO, &optval) != 0)
5012 #else
5013     if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
5014 #endif
5015     {
5016         my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
5017         dnssd_close(sd);
5018         return;
5019     }
5020     else
5021     {
5022         request_state *request = NewRequest();
5023         request->ts    = t_morecoming;
5024         request->sd    = sd;
5025         request->errsd = sd;
5026         set_peer_pid(request);
5027 #if APPLE_OSX_mDNSResponder
5028         struct xucred x;
5029         socklen_t xucredlen = sizeof(x);
5030         if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION)
5031             request->uid = x.cr_uid; // save the effective userid of the client
5032         else
5033             my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
5034 
5035         debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
5036 #endif // APPLE_OSX_mDNSResponder
5037         LogDebug("%3d: connect_callback: Adding FD for uid %u", request->sd, request->uid);
5038         udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
5039     }
5040 }
5041 
5042 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
5043 {
5044 #if defined(SO_NP_EXTENSIONS)
5045     struct      so_np_extensions sonpx;
5046     socklen_t optlen = sizeof(struct so_np_extensions);
5047     sonpx.npx_flags = SONPX_SETOPTSHUT;
5048     sonpx.npx_mask  = SONPX_SETOPTSHUT;
5049     if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
5050         my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
5051 #endif
5052 #if defined(_WIN32)
5053     // SEH: do we even need to do this on windows?
5054     // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
5055     u_long opt = 1;
5056     if (ioctlsocket(skt, FIONBIO, &opt) != 0)
5057 #else
5058     if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
5059 #endif
5060     {
5061         my_perror("ERROR: could not set listen socket to non-blocking mode");
5062         return mDNSfalse;
5063     }
5064 
5065     if (listen(skt, LISTENQ) != 0)
5066     {
5067         my_perror("ERROR: could not listen on listen socket");
5068         return mDNSfalse;
5069     }
5070 
5071     if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
5072     {
5073         my_perror("ERROR: could not add listen socket to event loop");
5074         return mDNSfalse;
5075     }
5076     else
5077     {
5078         LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
5079         mDNSStorage.uds_listener_skt = skt;
5080     }
5081     return mDNStrue;
5082 }
5083 
5084 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
5085 {
5086     dnssd_sockaddr_t laddr;
5087     int ret;
5088     mDNSu32 i = 0;
5089 
5090     LogInfo("udsserver_init: %d %d", _DNS_SD_H, mDNSStorage.mDNS_plat);
5091 
5092     // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
5093     if (PID_FILE[0])
5094     {
5095         FILE *fp = fopen(PID_FILE, "w");
5096         if (fp != NULL)
5097         {
5098             fprintf(fp, "%d\n", (int)getpid());
5099             fclose(fp);
5100         }
5101     }
5102 
5103     if (skts)
5104     {
5105         for (i = 0; i < count; i++)
5106             if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
5107                 goto error;
5108     }
5109     else
5110     {
5111         listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
5112         if (!dnssd_SocketValid(listenfd))
5113         {
5114             my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
5115             goto error;
5116         }
5117 
5118         mDNSPlatformMemZero(&laddr, sizeof(laddr));
5119 
5120         #if defined(USE_TCP_LOOPBACK)
5121         {
5122             laddr.sin_family = AF_INET;
5123             laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
5124             laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
5125             ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5126             if (ret < 0)
5127             {
5128                 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5129                 goto error;
5130             }
5131         }
5132         #else
5133         {
5134             mode_t mask = umask(0);
5135             unlink(boundPath);  // OK if this fails
5136             laddr.sun_family = AF_LOCAL;
5137             #ifndef NOT_HAVE_SA_LEN
5138             // According to Stevens (section 3.2), there is no portable way to
5139             // determine whether sa_len is defined on a particular platform.
5140             laddr.sun_len = sizeof(struct sockaddr_un);
5141             #endif
5142             if (strlen(boundPath) >= sizeof(laddr.sun_path))
5143             {
5144                 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
5145                 goto error;
5146             }
5147             mDNSPlatformStrLCopy(laddr.sun_path, boundPath, sizeof(laddr.sun_path));
5148             ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5149             umask(mask);
5150             if (ret < 0)
5151             {
5152                 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5153                 goto error;
5154             }
5155         }
5156         #endif
5157 
5158         if (!uds_socket_setup(listenfd)) goto error;
5159     }
5160 
5161 #if !defined(PLATFORM_NO_RLIMIT)
5162     {
5163         // Set maximum number of open file descriptors
5164     #define MIN_OPENFILES 10240
5165         struct rlimit maxfds, newfds;
5166 
5167         // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
5168         // you have to get and set rlimits once before getrlimit will return sensible values
5169         if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5170         if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5171 
5172         if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5173         newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
5174         newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
5175         if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
5176             if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5177 
5178         if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5179         debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
5180         debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
5181     }
5182 #endif
5183 
5184     // We start a "LocalOnly" query looking for Automatic Browse Domain records.
5185     // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
5186     // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
5187     mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
5188                     mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
5189 
5190     // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
5191     RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
5192     RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
5193     AddAutoBrowseDomain(0, &localdomain);
5194 
5195     udsserver_handle_configchange(&mDNSStorage);
5196     return 0;
5197 
5198 error:
5199 
5200     my_perror("ERROR: udsserver_init");
5201     return -1;
5202 }
5203 
5204 mDNSexport int udsserver_exit(void)
5205 {
5206     // Cancel all outstanding client requests
5207     while (all_requests) AbortUnlinkAndFree(all_requests);
5208 
5209     // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
5210     // created in udsserver_init, and others we created as a result of reading local configuration data
5211     while (LocalDomainEnumRecords)
5212     {
5213         ARListElem *rem = LocalDomainEnumRecords;
5214         LocalDomainEnumRecords = LocalDomainEnumRecords->next;
5215         mDNS_Deregister(&mDNSStorage, &rem->ar);
5216     }
5217 
5218     // If the launching environment created no listening socket,
5219     // that means we created it ourselves, so we should clean it up on exit
5220     if (dnssd_SocketValid(listenfd))
5221     {
5222         dnssd_close(listenfd);
5223 #if !defined(USE_TCP_LOOPBACK)
5224         // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
5225         // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
5226         // It would be nice if we could find a solution to this problem
5227         if (unlink(boundPath))
5228             debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
5229 #endif
5230     }
5231 
5232     if (PID_FILE[0]) unlink(PID_FILE);
5233 
5234     return 0;
5235 }
5236 
5237 mDNSlocal void LogClientInfo(request_state *req)
5238 {
5239     char prefix[16];
5240     if (req->primary)
5241         mDNS_snprintf(prefix, sizeof(prefix), " -> ");
5242     else
5243         mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
5244 
5245     if (!req->terminate)
5246         LogMsgNoIdent("%s No operation yet on this socket", prefix);
5247     else if (req->terminate == connection_termination)
5248     {
5249         int num_records = 0, num_ops = 0;
5250         const registered_record_entry *p;
5251         request_state *r;
5252         for (p = req->u.reg_recs; p; p=p->next) num_records++;
5253         for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
5254         LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
5255                        prefix, num_records, num_records != 1 ? "s" : "", num_ops,     num_ops     != 1 ? "s" : "",
5256                        req->process_id, req->pid_name);
5257         for (p = req->u.reg_recs; p; p=p->next)
5258             LogMsgNoIdent(" ->  DNSServiceRegisterRecord   0x%08X %2d %3d %s PID[%d](%s)",
5259                            req->flags, req->interfaceIndex, p->key, ARDisplayString(&mDNSStorage, p->rr), req->process_id, req->pid_name);
5260         for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(r);
5261     }
5262     else if (req->terminate == regservice_termination_callback)
5263     {
5264         service_instance *ptr;
5265         char anonstr[256];
5266         for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5267             LogMsgNoIdent("%s DNSServiceRegister         0x%08X %2d %##s%s %u/%u PID[%d](%s)",
5268                            (ptr == req->u.servicereg.instances) ? prefix : "    ", req->flags, req->interfaceIndex, ptr->srs.RR_SRV.resrec.name->c,
5269                            AnonDataToString(ptr->srs.AnonData, 0, anonstr, sizeof(anonstr)), mDNSVal16(req->u.servicereg.port),
5270                            SRS_PORT(&ptr->srs), req->process_id, req->pid_name);
5271     }
5272     else if (req->terminate == browse_termination_callback)
5273     {
5274         browser_t *blist;
5275         char anonstr[256];
5276         for (blist = req->u.browser.browsers; blist; blist = blist->next)
5277             LogMsgNoIdent("%s DNSServiceBrowse           0x%08X %2d %##s%s PID[%d](%s)",
5278                            (blist == req->u.browser.browsers) ? prefix : "    ", req->flags, req->interfaceIndex, blist->q.qname.c,
5279                            AnonDataToString(req->u.browser.AnonData, 0, anonstr, sizeof(anonstr)), req->process_id, req->pid_name);
5280     }
5281     else if (req->terminate == resolve_termination_callback)
5282         LogMsgNoIdent("%s DNSServiceResolve          0x%08X %2d %##s PID[%d](%s)",
5283                        prefix, req->flags, req->interfaceIndex, req->u.resolve.qsrv.qname.c, req->process_id, req->pid_name);
5284     else if (req->terminate == queryrecord_termination_callback)
5285         LogMsgNoIdent("%s DNSServiceQueryRecord      0x%08X %2d %##s (%s) PID[%d](%s)",
5286                        prefix, req->flags, req->interfaceIndex, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype), req->process_id, req->pid_name);
5287     else if (req->terminate == enum_termination_callback)
5288         LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
5289                        prefix, req->flags, req->interfaceIndex, req->u.enumeration.q_all.qname.c, req->process_id, req->pid_name);
5290     else if (req->terminate == port_mapping_termination_callback)
5291         LogMsgNoIdent("%s DNSServiceNATPortMapping   0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
5292                       prefix,
5293                       req->flags,
5294                       req->interfaceIndex,
5295                       req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : "   ",
5296                       req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : "   ",
5297                       mDNSVal16(req->u.pm.NATinfo.IntPort),
5298                       mDNSVal16(req->u.pm.ReqExt),
5299                       &req->u.pm.NATinfo.ExternalAddress,
5300                       mDNSVal16(req->u.pm.NATinfo.ExternalPort),
5301                       req->u.pm.NATinfo.NATLease,
5302                       req->u.pm.NATinfo.Lifetime,
5303                       req->process_id, req->pid_name);
5304     else if (req->terminate == addrinfo_termination_callback)
5305         LogMsgNoIdent("%s DNSServiceGetAddrInfo      0x%08X %2d %s%s %##s PID[%d](%s)",
5306                       prefix, req->flags, req->interfaceIndex,
5307                       req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : "  ",
5308                       req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : "  ",
5309                       req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name);
5310     else
5311         LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
5312 }
5313 
5314 mDNSlocal void GetMcastClients(request_state *req)
5315 {
5316     if (req->terminate == connection_termination)
5317     {
5318         int num_records = 0, num_ops = 0;
5319         const registered_record_entry *p;
5320         request_state *r;
5321         for (p = req->u.reg_recs; p; p=p->next)
5322             num_records++;
5323         for (r = req->next; r; r=r->next)
5324             if (r->primary == req)
5325                 num_ops++;
5326         for (p = req->u.reg_recs; p; p=p->next)
5327         {
5328             if (!AuthRecord_uDNS(p->rr))
5329                 n_mrecords++;
5330         }
5331         for (r = req->next; r; r=r->next)
5332             if (r->primary == req)
5333                 GetMcastClients(r);
5334     }
5335     else if (req->terminate == regservice_termination_callback)
5336     {
5337         service_instance *ptr;
5338         for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5339         {
5340             if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5341                 n_mrecords++;
5342         }
5343     }
5344     else if (req->terminate == browse_termination_callback)
5345     {
5346         browser_t *blist;
5347         for (blist = req->u.browser.browsers; blist; blist = blist->next)
5348         {
5349             if (mDNSOpaque16IsZero(blist->q.TargetQID))
5350                 n_mquests++;
5351         }
5352     }
5353     else if (req->terminate == resolve_termination_callback)
5354     {
5355         if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5356             n_mquests++;
5357     }
5358     else if (req->terminate == queryrecord_termination_callback)
5359     {
5360         if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5361             n_mquests++;
5362     }
5363     else if (req->terminate == addrinfo_termination_callback)
5364     {
5365         if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5366             n_mquests++;
5367     }
5368     else
5369     {
5370         return;
5371     }
5372 }
5373 
5374 
5375 mDNSlocal void LogMcastClientInfo(request_state *req)
5376 {
5377     if (!req->terminate)
5378         LogMcastNoIdent("No operation yet on this socket");
5379     else if (req->terminate == connection_termination)
5380     {
5381         int num_records = 0, num_ops = 0;
5382         const registered_record_entry *p;
5383         request_state *r;
5384         for (p = req->u.reg_recs; p; p=p->next)
5385             num_records++;
5386         for (r = req->next; r; r=r->next)
5387             if (r->primary == req)
5388                 num_ops++;
5389         for (p = req->u.reg_recs; p; p=p->next)
5390         {
5391             if (!AuthRecord_uDNS(p->rr))
5392                 LogMcastNoIdent("R: ->  DNSServiceRegisterRecord:  %##s %s PID[%d](%s)", p->rr->resrec.name->c,
5393                                 DNSTypeName(p->rr->resrec.rrtype), req->process_id, req->pid_name, i_mcount++);
5394         }
5395         for (r = req->next; r; r=r->next)
5396             if (r->primary == req)
5397                 LogMcastClientInfo(r);
5398     }
5399     else if (req->terminate == regservice_termination_callback)
5400     {
5401         service_instance *ptr;
5402         for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5403         {
5404             if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5405                 LogMcastNoIdent("R: DNSServiceRegister:  %##s %u/%u PID[%d](%s)", ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port),
5406                                 SRS_PORT(&ptr->srs), req->process_id, req->pid_name, i_mcount++);
5407         }
5408     }
5409     else if (req->terminate == browse_termination_callback)
5410     {
5411         browser_t *blist;
5412         for (blist = req->u.browser.browsers; blist; blist = blist->next)
5413         {
5414             if (mDNSOpaque16IsZero(blist->q.TargetQID))
5415                 LogMcastNoIdent("Q: DNSServiceBrowse  %##s %s PID[%d](%s)", blist->q.qname.c, DNSTypeName(blist->q.qtype),
5416                                 req->process_id, req->pid_name, i_mcount++);
5417         }
5418     }
5419     else if (req->terminate == resolve_termination_callback)
5420     {
5421         if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5422             LogMcastNoIdent("Q: DNSServiceResolve  %##s %s PID[%d](%s)", req->u.resolve.qsrv.qname.c, DNSTypeName(req->u.resolve.qsrv.qtype),
5423                             req->process_id, req->pid_name, i_mcount++);
5424     }
5425     else if (req->terminate == queryrecord_termination_callback)
5426     {
5427         if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5428             LogMcastNoIdent("Q: DNSServiceQueryRecord  %##s %s PID[%d](%s)", req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype),
5429                           req->process_id, req->pid_name, i_mcount++);
5430     }
5431     else if (req->terminate == addrinfo_termination_callback)
5432     {
5433         if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5434             LogMcastNoIdent("Q: DNSServiceGetAddrInfo  %s%s %##s PID[%d](%s)",
5435                           req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : "  ",
5436                           req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : "  ",
5437                           req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name, i_mcount++);
5438     }
5439     else
5440     {
5441         return;
5442     }
5443 
5444 }
5445 
5446 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
5447 {
5448     switch (rtype)
5449     {
5450     case kDNSRecordTypeUnregistered:  return ("Unregistered ");
5451     case kDNSRecordTypeDeregistering: return ("Deregistering");
5452     case kDNSRecordTypeUnique:        return ("Unique       ");
5453     case kDNSRecordTypeAdvisory:      return ("Advisory     ");
5454     case kDNSRecordTypeShared:        return ("Shared       ");
5455     case kDNSRecordTypeVerified:      return ("Verified     ");
5456     case kDNSRecordTypeKnownUnique:   return ("KnownUnique  ");
5457     default: return("Unknown");
5458     }
5459 }
5460 
5461 mDNSlocal int LogEtcHosts(mDNS *const m)
5462 {
5463     mDNSBool showheader = mDNStrue;
5464     const AuthRecord *ar;
5465     mDNSu32 slot;
5466     AuthGroup *ag;
5467     int count = 0;
5468     int authslot = 0;
5469     mDNSBool truncated = 0;
5470 
5471     for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5472     {
5473         if (m->rrauth.rrauth_hash[slot]) authslot++;
5474         for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5475             for (ar = ag->members; ar; ar = ar->next)
5476             {
5477                 if (ar->RecordCallback != FreeEtcHosts) continue;
5478                 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("  State       Interface"); }
5479 
5480                 // Print a maximum of 50 records
5481                 if (count++ >= 50) { truncated = mDNStrue; continue; }
5482                 if (ar->ARType == AuthRecordLocalOnly)
5483                 {
5484                     if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
5485                         LogMsgNoIdent(" %s   LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5486                     else
5487                     {
5488                         mDNSu32 scopeid  = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
5489                         LogMsgNoIdent(" %s   %u  %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
5490                     }
5491                 }
5492             }
5493     }
5494 
5495     if (showheader) LogMsgNoIdent("<None>");
5496     else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
5497     return count;
5498 }
5499 
5500 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
5501 {
5502     mDNSBool showheader = mDNStrue;
5503     const AuthRecord *ar;
5504     mDNSu32 slot;
5505     AuthGroup *ag;
5506 
5507     for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5508     {
5509         for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5510             for (ar = ag->members; ar; ar = ar->next)
5511             {
5512                 if (ar->RecordCallback == FreeEtcHosts) continue;
5513                 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("  State       Interface"); }
5514 
5515                 // Print a maximum of 400 records
5516                 if (ar->ARType == AuthRecordLocalOnly)
5517                     LogMsgNoIdent(" %s   LO  %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5518                 else if (ar->ARType == AuthRecordP2P)
5519                 {
5520                     if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5521                         LogMsgNoIdent(" %s   BLE %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5522                     else
5523                         LogMsgNoIdent(" %s   PP  %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5524                 }
5525             }
5526     }
5527 
5528     if (showheader) LogMsgNoIdent("<None>");
5529 }
5530 
5531 mDNSlocal char *AnonInfoToString(AnonymousInfo *ai, char *anonstr, int anstrlen)
5532 {
5533     anonstr[0] = 0;
5534     if (ai && ai->AnonData)
5535     {
5536         return (AnonDataToString(ai->AnonData, ai->AnonDataLen, anonstr, anstrlen));
5537     }
5538     return anonstr;
5539 }
5540 
5541 mDNSlocal void LogOneAuthRecord(const AuthRecord *ar, mDNSs32 now, const char *const ifname)
5542 {
5543     char anstr[256];
5544     if (AuthRecord_uDNS(ar))
5545     {
5546         LogMsgNoIdent("%7d %7d %7d %-7s %4d %s %s",
5547                       ar->ThisAPInterval / mDNSPlatformOneSecond,
5548                       (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5549                       ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5550                       "-U-",
5551                       ar->state,
5552                       ar->AllowRemoteQuery ? "☠" : " ",
5553                       ARDisplayString(&mDNSStorage, ar));
5554     }
5555     else
5556     {
5557         LogMsgNoIdent("%7d %7d %7d %-7s 0x%02X %s %s%s",
5558                       ar->ThisAPInterval / mDNSPlatformOneSecond,
5559                       ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5560                       ar->TimeExpire    ? (ar->TimeExpire                      - now) / mDNSPlatformOneSecond : 0,
5561                       ifname ? ifname : "ALL",
5562                       ar->resrec.RecordType,
5563                       ar->AllowRemoteQuery ? "☠" : " ",
5564                       ARDisplayString(&mDNSStorage, ar), AnonInfoToString(ar->resrec.AnonInfo, anstr, sizeof(anstr)));
5565     }
5566 }
5567 
5568 mDNSlocal void LogAuthRecords(const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
5569 {
5570     mDNSBool showheader = mDNStrue;
5571     const AuthRecord *ar;
5572     OwnerOptData owner = zeroOwner;
5573     for (ar = ResourceRecords; ar; ar=ar->next)
5574     {
5575         const char *const ifname = InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID);
5576         if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
5577         {
5578             if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("    Int    Next  Expire if     State"); }
5579             if (proxy) (*proxy)++;
5580             if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
5581             {
5582                 owner = ar->WakeUp;
5583                 if (owner.password.l[0])
5584                     LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
5585                 else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
5586                     LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d",               &owner.HMAC, &owner.IMAC,                  owner.seq);
5587                 else
5588                     LogMsgNoIdent("Proxying for %.6a seq %d",                                &owner.HMAC,                               owner.seq);
5589             }
5590             if (AuthRecord_uDNS(ar))
5591             {
5592                 LogOneAuthRecord(ar, now, ifname);
5593             }
5594             else if (ar->ARType == AuthRecordLocalOnly)
5595             {
5596                 LogMsgNoIdent("                             LO %s", ARDisplayString(&mDNSStorage, ar));
5597             }
5598             else if (ar->ARType == AuthRecordP2P)
5599             {
5600                 if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5601                     LogMsgNoIdent("                             BLE %s", ARDisplayString(&mDNSStorage, ar));
5602                 else
5603                     LogMsgNoIdent("                             PP %s", ARDisplayString(&mDNSStorage, ar));
5604             }
5605             else
5606             {
5607                 LogOneAuthRecord(ar, now, ifname);
5608                 if (ar->resrec.AnonInfo)
5609                 {
5610                     ResourceRecord *nsec3 = ar->resrec.AnonInfo->nsec3RR;
5611                     // We just print the values from the AuthRecord to keep it nicely aligned though
5612                     // all we want here is the nsec3 information.
5613                     LogMsgNoIdent("%7d %7d %7d %7s %s",
5614                                   ar->ThisAPInterval / mDNSPlatformOneSecond,
5615                                   ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5616                                   ar->TimeExpire    ? (ar->TimeExpire                      - now) / mDNSPlatformOneSecond : 0,
5617                                   ifname ? ifname : "ALL",
5618                                   RRDisplayString(&mDNSStorage, nsec3));
5619                 }
5620             }
5621         }
5622     }
5623     if (showheader) LogMsgNoIdent("<None>");
5624 }
5625 
5626 mDNSlocal void PrintOneCacheRecord(const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5627 {
5628     LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5629                   slot,
5630                   cr->CRActiveQuestion ? "*" : " ",
5631                   remain,
5632                   ifname ? ifname : "-U-",
5633                   (cr->resrec.RecordType == kDNSRecordTypePacketNegative)  ? "-" :
5634                   (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5635                   DNSTypeName(cr->resrec.rrtype),
5636                   CRDisplayString(&mDNSStorage, cr));
5637     (*CacheUsed)++;
5638 }
5639 
5640 mDNSlocal void PrintCachedRecords(const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5641 {
5642     CacheRecord *nsec;
5643     CacheRecord *soa;
5644     nsec = cr->nsec;
5645 
5646     // The records that are cached under the main cache record like nsec, soa don't have
5647     // their own lifetime. If the main cache record expires, they also expire.
5648     while (nsec)
5649     {
5650         PrintOneCacheRecord(nsec, slot, remain, ifname, CacheUsed);
5651         nsec = nsec->next;
5652     }
5653     soa = cr->soa;
5654     if (soa)
5655     {
5656         PrintOneCacheRecord(soa, slot, remain, ifname, CacheUsed);
5657     }
5658     if (cr->resrec.AnonInfo)
5659     {
5660         ResourceRecord *nsec3 = cr->resrec.AnonInfo->nsec3RR;
5661         // Even though it is a resource record, we print the sameway
5662         // as a cache record so that it aligns properly.
5663         if (nsec3)
5664         {
5665             LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5666                           slot,
5667                           " ",
5668                           remain,
5669                           ifname ? ifname : "-U-",
5670                           (nsec3->RecordType == kDNSRecordTypePacketNegative)  ? "-" :
5671                           (nsec3->RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5672                           DNSTypeName(nsec3->rrtype),
5673                           RRDisplayString(&mDNSStorage, nsec3));
5674         }
5675     }
5676 }
5677 
5678 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen)
5679 {
5680     adstr[0] = 0;
5681     if (ad)
5682     {
5683         int len;
5684         char *orig = adstr;
5685 
5686         // If the caller is lazy to compute the length, we do it for them.
5687         if (!adlen)
5688             len = strlen((const char *)ad);
5689         else
5690             len = adlen;
5691 
5692         // Print the anondata within brackets. Hence, we need space for two
5693         // brackets and a NULL byte.
5694         if (len > (adstrlen - 3))
5695             len = adstrlen - 3;
5696 
5697         *adstr++ = '(';
5698         mDNSPlatformMemCopy(adstr, ad, len);
5699         adstr[len] = ')';
5700         adstr[len+1] = 0;
5701         return orig;
5702     }
5703     return adstr;
5704 }
5705 
5706 mDNSexport void LogMDNSStatistics(mDNS *const m)
5707 {
5708     LogMsgNoIdent("--- MDNS Statistics ---");
5709 
5710     LogMsgNoIdent("Name Conflicts                 %u", m->mDNSStats.NameConflicts);
5711     LogMsgNoIdent("KnownUnique Name Conflicts     %u", m->mDNSStats.KnownUniqueNameConflicts);
5712     LogMsgNoIdent("Duplicate Query Suppressions   %u", m->mDNSStats.DupQuerySuppressions);
5713     LogMsgNoIdent("KA Suppressions                %u", m->mDNSStats.KnownAnswerSuppressions);
5714     LogMsgNoIdent("KA Multiple Packets            %u", m->mDNSStats.KnownAnswerMultiplePkts);
5715     LogMsgNoIdent("Poof Cache Deletions           %u", m->mDNSStats.PoofCacheDeletions);
5716     LogMsgNoIdent("--------------------------------");
5717 
5718     LogMsgNoIdent("Multicast packets Sent         %u", m->MulticastPacketsSent);
5719     LogMsgNoIdent("Multicast packets Received     %u", m->MPktNum);
5720     LogMsgNoIdent("Remote Subnet packets          %u", m->RemoteSubnet);
5721     LogMsgNoIdent("QU questions  received         %u", m->mDNSStats.UnicastBitInQueries);
5722     LogMsgNoIdent("Normal multicast questions     %u", m->mDNSStats.NormalQueries);
5723     LogMsgNoIdent("Answers for questions          %u", m->mDNSStats.MatchingAnswersForQueries);
5724     LogMsgNoIdent("Unicast responses              %u", m->mDNSStats.UnicastResponses);
5725     LogMsgNoIdent("Multicast responses            %u", m->mDNSStats.MulticastResponses);
5726     LogMsgNoIdent("Unicast response Demotions     %u", m->mDNSStats.UnicastDemotedToMulticast);
5727     LogMsgNoIdent("--------------------------------");
5728 
5729     LogMsgNoIdent("Sleeps                         %u", m->mDNSStats.Sleeps);
5730     LogMsgNoIdent("Wakeups                        %u", m->mDNSStats.Wakes);
5731     LogMsgNoIdent("Interface UP events            %u", m->mDNSStats.InterfaceUp);
5732     LogMsgNoIdent("Interface UP Flap events       %u", m->mDNSStats.InterfaceUpFlap);
5733     LogMsgNoIdent("Interface Down events          %u", m->mDNSStats.InterfaceDown);
5734     LogMsgNoIdent("Interface DownFlap events      %u", m->mDNSStats.InterfaceDownFlap);
5735     LogMsgNoIdent("Cache refresh queries          %u", m->mDNSStats.CacheRefreshQueries);
5736     LogMsgNoIdent("Cache refreshed                %u", m->mDNSStats.CacheRefreshed);
5737     LogMsgNoIdent("Wakeup on Resolves             %u", m->mDNSStats.WakeOnResolves);
5738 }
5739 
5740 mDNSexport void udsserver_info()
5741 {
5742     mDNS *const m = &mDNSStorage;
5743     const mDNSs32 now = mDNS_TimeNow(m);
5744     mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
5745     int ProxyA = 0, ProxyD = 0;
5746     mDNSu32 groupCount = 0;
5747     mDNSu32 mcastRecordCount = 0;
5748     mDNSu32 ucastRecordCount = 0;
5749     const CacheGroup *cg;
5750     const CacheRecord *cr;
5751     const DNSQuestion *q;
5752     const DNameListElem *d;
5753     const SearchListElem *s;
5754 
5755     LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
5756 
5757     LogMsgNoIdent("------------ Cache -------------");
5758     LogMsgNoIdent("Slt Q     TTL if     U Type rdlen");
5759     for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5760     {
5761         for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
5762         {
5763             groupCount++;   // Count one cache entity for the CacheGroup object
5764             for (cr = cg->members; cr; cr=cr->next)
5765             {
5766                 const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
5767                 const char *ifname;
5768                 mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
5769                 mDNSu32 *const countPtr = InterfaceID ? &mcastRecordCount : &ucastRecordCount;
5770                 if (!InterfaceID && cr->resrec.rDNSServer && cr->resrec.rDNSServer->scoped)
5771                     InterfaceID = cr->resrec.rDNSServer->interface;
5772                 ifname = InterfaceNameForID(m, InterfaceID);
5773                 if (cr->CRActiveQuestion) CacheActive++;
5774                 PrintOneCacheRecord(cr, slot, remain, ifname, countPtr);
5775                 PrintCachedRecords(cr, slot, remain, ifname, countPtr);
5776             }
5777         }
5778     }
5779 
5780     CacheUsed = groupCount + mcastRecordCount + ucastRecordCount;
5781     if (m->rrcache_totalused != CacheUsed)
5782         LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
5783     if (m->rrcache_active != CacheActive)
5784         LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
5785     LogMsgNoIdent("Cache size %u entities; %u in use (%u group, %u multicast, %u unicast); %u referenced by active questions",
5786         m->rrcache_size, CacheUsed, groupCount, mcastRecordCount, ucastRecordCount, CacheActive);
5787 
5788     LogMsgNoIdent("--------- Auth Records ---------");
5789     LogAuthRecords(now, m->ResourceRecords, mDNSNULL);
5790 
5791     LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
5792     LogLocalOnlyAuthRecords(m);
5793 
5794     LogMsgNoIdent("--------- /etc/hosts ---------");
5795     LogEtcHosts(m);
5796 
5797     LogMsgNoIdent("------ Duplicate Records -------");
5798     LogAuthRecords(now, m->DuplicateRecords, mDNSNULL);
5799 
5800     LogMsgNoIdent("----- Auth Records Proxied -----");
5801     LogAuthRecords(now, m->ResourceRecords, &ProxyA);
5802 
5803     LogMsgNoIdent("-- Duplicate Records Proxied ---");
5804     LogAuthRecords(now, m->DuplicateRecords, &ProxyD);
5805 
5806     LogMsgNoIdent("---------- Questions -----------");
5807     if (!m->Questions) LogMsgNoIdent("<None>");
5808     else
5809     {
5810         char anonstr[256];
5811         CacheUsed = 0;
5812         CacheActive = 0;
5813         LogMsgNoIdent("   Int  Next if     T  NumAns VDNS    Qptr     DupOf    SU SQ Type Name");
5814         for (q = m->Questions; q; q=q->next)
5815         {
5816             mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
5817             mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
5818             char *ifname = InterfaceNameForID(m, q->InterfaceID);
5819             CacheUsed++;
5820             if (q->ThisQInterval) CacheActive++;
5821             LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s%s",
5822                           i, n,
5823                           ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
5824                           mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
5825                           PrivateQuery(q)    ? "P" : q->ValidationRequired ? "V" : q->ValidatingResponse ? "R" : " ",
5826                           q->CurrentAnswers, q->validDNSServers.l[3], q->validDNSServers.l[2], q->validDNSServers.l[1],
5827                           q->validDNSServers.l[0], q, q->DuplicateOf,
5828                           q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c,
5829                           AnonInfoToString(q->AnonInfo, anonstr, sizeof(anonstr)),
5830                           q->DuplicateOf ? " (dup)" : "");
5831         }
5832         LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
5833     }
5834 
5835     LogMsgNoIdent("----- LocalOnly, P2P Questions -----");
5836     if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
5837     else for (q = m->LocalOnlyQuestions; q; q=q->next)
5838             LogMsgNoIdent("                 %3s   %5d  %-6s%##s%s",
5839                           q->InterfaceID == mDNSInterface_LocalOnly ? "LO ": q->InterfaceID == mDNSInterface_BLE ? "BLE": "P2P",
5840                           q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
5841 
5842     LogMsgNoIdent("---- Active UDS Client Requests ----");
5843     if (!all_requests) LogMsgNoIdent("<None>");
5844     else
5845     {
5846         request_state *req, *r;
5847         for (req = all_requests; req; req=req->next)
5848         {
5849             if (req->primary)   // If this is a subbordinate operation, check that the parent is in the list
5850             {
5851                 for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
5852                 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
5853             }
5854             // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
5855             LogClientInfo(req);
5856 foundparent:;
5857         }
5858     }
5859 
5860     LogMsgNoIdent("-------- NAT Traversals --------");
5861     LogMsgNoIdent("ExtAddress %.4a Retry %d Interval %d",
5862                   &m->ExtAddress,
5863                   m->retryGetAddr ? (m->retryGetAddr - now) / mDNSPlatformOneSecond : 0,
5864                   m->retryIntervalGetAddr / mDNSPlatformOneSecond);
5865     if (m->NATTraversals)
5866     {
5867         const NATTraversalInfo *nat;
5868         for (nat = m->NATTraversals; nat; nat=nat->next)
5869         {
5870             LogMsgNoIdent("%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
5871                           nat,
5872                           nat->Protocol ? (nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP") : "ADD",
5873                           mDNSVal16(nat->IntPort),
5874                           (nat->lastSuccessfulProtocol == NATTProtocolNone    ? "None    " :
5875                            nat->lastSuccessfulProtocol == NATTProtocolNATPMP  ? "NAT-PMP " :
5876                            nat->lastSuccessfulProtocol == NATTProtocolUPNPIGD ? "UPnP/IGD" :
5877                            nat->lastSuccessfulProtocol == NATTProtocolPCP     ? "PCP     " :
5878                            /* else */                                           "Unknown " ),
5879                           nat->Result,
5880                           nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5881                           nat->retryInterval / mDNSPlatformOneSecond,
5882                           nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5883                           &nat->NewAddress, mDNSVal16(nat->RequestedPort),
5884                           &nat->ExternalAddress, mDNSVal16(nat->ExternalPort));
5885         }
5886     }
5887 
5888     LogMsgNoIdent("--------- AuthInfoList ---------");
5889     if (!m->AuthInfoList) LogMsgNoIdent("<None>");
5890     else
5891     {
5892         const DomainAuthInfo *a;
5893         for (a = m->AuthInfoList; a; a = a->next)
5894         {
5895             LogMsgNoIdent("%##s %##s %##s %d %d %.16a%s",
5896                           a->domain.c, a->keyname.c,
5897                           a->hostname.c, (a->port.b[0] << 8 | a->port.b[1]),
5898                           (a->deltime ? (a->deltime - now) : 0),
5899                           &a->AutoTunnelInnerAddress, a->AutoTunnel ? " AutoTunnel" : "");
5900         }
5901     }
5902 
5903     #if APPLE_OSX_mDNSResponder
5904     LogMsgNoIdent("--------- TunnelClients --------");
5905     if (!m->TunnelClients) LogMsgNoIdent("<None>");
5906     else
5907     {
5908         const ClientTunnel *c;
5909         for (c = m->TunnelClients; c; c = c->next)
5910             LogMsgNoIdent("%##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
5911                           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);
5912     }
5913     #endif // APPLE_OSX_mDNSResponder
5914 
5915     LogMsgNoIdent("---------- Misc State ----------");
5916 
5917     LogMsgNoIdent("PrimaryMAC:   %.6a", &m->PrimaryMAC);
5918 
5919     LogMsgNoIdent("m->SleepState %d (%s) seq %d",
5920                   m->SleepState,
5921                   m->SleepState == SleepState_Awake        ? "Awake"        :
5922                   m->SleepState == SleepState_Transferring ? "Transferring" :
5923                   m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?",
5924                   m->SleepSeqNum);
5925 
5926     if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
5927 #ifndef SPC_DISABLED
5928     else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
5929 #endif
5930     if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
5931     else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
5932 
5933     LogMsgNoIdent("------ Auto Browse Domains -----");
5934     if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
5935     else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5936 
5937     LogMsgNoIdent("--- Auto Registration Domains --");
5938     if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
5939     else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5940 
5941     LogMsgNoIdent("--- Search Domains --");
5942     if (!SearchList) LogMsgNoIdent("<None>");
5943     else
5944     {
5945         for (s=SearchList; s; s=s->next)
5946         {
5947             char *ifname = InterfaceNameForID(m, s->InterfaceID);
5948             LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
5949         }
5950     }
5951     LogInfo("--- Trust Anchors ---");
5952     if (!m->TrustAnchors)
5953     {
5954         LogInfo("<None>");
5955     }
5956     else
5957     {
5958         TrustAnchor *ta;
5959         mDNSu8 fromTimeBuf[64];
5960         mDNSu8 untilTimeBuf[64];
5961 
5962         for (ta=m->TrustAnchors; ta; ta=ta->next)
5963         {
5964             mDNSPlatformFormatTime((unsigned long)ta->validFrom, fromTimeBuf, sizeof(fromTimeBuf));
5965             mDNSPlatformFormatTime((unsigned long)ta->validUntil, untilTimeBuf, sizeof(untilTimeBuf));
5966             LogInfo("%##s %d %d %d %d %s %s", ta->zone.c, ta->rds.keyTag,
5967                 ta->rds.alg, ta->rds.digestType, ta->digestLen, fromTimeBuf, untilTimeBuf);
5968         }
5969     }
5970 
5971     LogInfo("--- DNSSEC Statistics ---");
5972 
5973     LogMsgNoIdent("Unicast Cache size              %u", m->rrcache_totalused_unicast);
5974     LogInfo("DNSSEC  Cache size              %u", m->DNSSECStats.TotalMemUsed);
5975     if (m->rrcache_totalused_unicast)
5976         LogInfo("DNSSEC  usage percentage        %u", ((unsigned long)(m->DNSSECStats.TotalMemUsed * 100))/m->rrcache_totalused_unicast);
5977     LogInfo("DNSSEC  Extra Packets (0 to 2)  %u", m->DNSSECStats.ExtraPackets0);
5978     LogInfo("DNSSEC  Extra Packets (3 to 6)  %u", m->DNSSECStats.ExtraPackets3);
5979     LogInfo("DNSSEC  Extra Packets (7 to 9)  %u", m->DNSSECStats.ExtraPackets7);
5980     LogInfo("DNSSEC  Extra Packets ( >= 10)  %u", m->DNSSECStats.ExtraPackets10);
5981 
5982     LogInfo("DNSSEC  Latency (0 to 4ms)      %u", m->DNSSECStats.Latency0);
5983     LogInfo("DNSSEC  Latency (4 to 9ms)      %u", m->DNSSECStats.Latency5);
5984     LogInfo("DNSSEC  Latency (10 to 19ms)    %u", m->DNSSECStats.Latency10);
5985     LogInfo("DNSSEC  Latency (20 to 49ms)    %u", m->DNSSECStats.Latency20);
5986     LogInfo("DNSSEC  Latency (50 to 99ms)    %u", m->DNSSECStats.Latency50);
5987     LogInfo("DNSSEC  Latency (   >=100ms)    %u", m->DNSSECStats.Latency100);
5988 
5989     LogInfo("DNSSEC  Secure Status           %u", m->DNSSECStats.SecureStatus);
5990     LogInfo("DNSSEC  Insecure Status         %u", m->DNSSECStats.InsecureStatus);
5991     LogInfo("DNSSEC  Indeterminate Status    %u", m->DNSSECStats.IndeterminateStatus);
5992     LogInfo("DNSSEC  Bogus Status            %u", m->DNSSECStats.BogusStatus);
5993     LogInfo("DNSSEC  NoResponse Status       %u", m->DNSSECStats.NoResponseStatus);
5994     LogInfo("DNSSEC  Probes sent             %u", m->DNSSECStats.NumProbesSent);
5995     LogInfo("DNSSEC  Msg Size (<=1024)       %u", m->DNSSECStats.MsgSize0);
5996     LogInfo("DNSSEC  Msg Size (<=2048)       %u", m->DNSSECStats.MsgSize1);
5997     LogInfo("DNSSEC  Msg Size (> 2048)       %u", m->DNSSECStats.MsgSize2);
5998 
5999     LogMDNSStatistics(m);
6000 
6001     LogMsgNoIdent("---- Task Scheduling Timers ----");
6002 
6003 #if BONJOUR_ON_DEMAND
6004     LogMsgNoIdent("BonjourEnabled %d", m->BonjourEnabled);
6005 #endif // BONJOUR_ON_DEMAND
6006 
6007 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
6008     LogMsgNoIdent("EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery);
6009     LogMsgNoIdent("DefaultToBLETriggered %d", DefaultToBLETriggered);
6010 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
6011 
6012     if (!m->NewQuestions)
6013         LogMsgNoIdent("NewQuestion <NONE>");
6014     else
6015         LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
6016                       m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
6017                       m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
6018 
6019     if (!m->NewLocalOnlyQuestions)
6020         LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
6021     else
6022         LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
6023                       m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
6024 
6025     if (!m->NewLocalRecords)
6026         LogMsgNoIdent("NewLocalRecords <NONE>");
6027     else
6028         LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
6029 
6030     LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
6031     LogMsgNoIdent("LocalRemoveEvents%s",   m->LocalRemoveEvents   ? "" : " <NONE>");
6032     LogMsgNoIdent("m->AutoTunnelRelayAddr %.16a", &m->AutoTunnelRelayAddr);
6033     LogMsgNoIdent("m->WABBrowseQueriesCount %d", m->WABBrowseQueriesCount);
6034     LogMsgNoIdent("m->WABLBrowseQueriesCount %d", m->WABLBrowseQueriesCount);
6035     LogMsgNoIdent("m->WABRegQueriesCount %d", m->WABRegQueriesCount);
6036     LogMsgNoIdent("m->AutoTargetServices %d", m->AutoTargetServices);
6037 
6038     LogMsgNoIdent("                         ABS (hex)  ABS (dec)  REL (hex)  REL (dec)");
6039     LogMsgNoIdent("m->timenow               %08X %11d", now, now);
6040     LogMsgNoIdent("m->timenow_adjust        %08X %11d", m->timenow_adjust, m->timenow_adjust);
6041     LogTimer("m->NextScheduledEvent   ", m->NextScheduledEvent);
6042 
6043 #ifndef UNICAST_DISABLED
6044     LogTimer("m->NextuDNSEvent        ", m->NextuDNSEvent);
6045     LogTimer("m->NextSRVUpdate        ", m->NextSRVUpdate);
6046     LogTimer("m->NextScheduledNATOp   ", m->NextScheduledNATOp);
6047     LogTimer("m->retryGetAddr         ", m->retryGetAddr);
6048 #endif
6049 
6050     LogTimer("m->NextCacheCheck       ", m->NextCacheCheck);
6051     LogTimer("m->NextScheduledSPS     ", m->NextScheduledSPS);
6052     LogTimer("m->NextScheduledKA      ", m->NextScheduledKA);
6053 
6054 #if BONJOUR_ON_DEMAND
6055     LogTimer("m->NextBonjourDisableTime ", m->NextBonjourDisableTime);
6056 #endif // BONJOUR_ON_DEMAND
6057 
6058     LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
6059     LogTimer("m->DelaySleep           ", m->DelaySleep);
6060 
6061     LogTimer("m->NextScheduledQuery   ", m->NextScheduledQuery);
6062     LogTimer("m->NextScheduledProbe   ", m->NextScheduledProbe);
6063     LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
6064 
6065     LogTimer("m->SuppressSending      ", m->SuppressSending);
6066     LogTimer("m->SuppressProbes       ", m->SuppressProbes);
6067     LogTimer("m->ProbeFailTime        ", m->ProbeFailTime);
6068     LogTimer("m->DelaySleep           ", m->DelaySleep);
6069     LogTimer("m->SleepLimit           ", m->SleepLimit);
6070     LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
6071 }
6072 
6073 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6074 mDNSexport void uds_validatelists(void)
6075 {
6076     const request_state *req, *p;
6077     for (req = all_requests; req; req=req->next)
6078     {
6079         if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
6080             LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
6081 
6082         if (req->primary == req)
6083             LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
6084 
6085         if (req->primary && req->replies)
6086             LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
6087                              req, req->sd, req->primary && req->replies);
6088 
6089         p = req->primary;
6090         if ((long)p & 3)
6091             LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
6092         else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
6093             LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
6094 
6095         reply_state *rep;
6096         for (rep = req->replies; rep; rep=rep->next)
6097             if (rep->next == (reply_state *)~0)
6098                 LogMemCorruption("UDS req->replies: %p is garbage", rep);
6099 
6100         if (req->terminate == connection_termination)
6101         {
6102             registered_record_entry *r;
6103             for (r = req->u.reg_recs; r; r=r->next)
6104                 if (r->next == (registered_record_entry *)~0)
6105                     LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
6106         }
6107         else if (req->terminate == regservice_termination_callback)
6108         {
6109             service_instance *s;
6110             for (s = req->u.servicereg.instances; s; s=s->next)
6111                 if (s->next == (service_instance *)~0)
6112                     LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
6113         }
6114         else if (req->terminate == browse_termination_callback)
6115         {
6116             browser_t *b;
6117             for (b = req->u.browser.browsers; b; b=b->next)
6118                 if (b->next == (browser_t *)~0)
6119                     LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
6120         }
6121     }
6122 
6123     DNameListElem *d;
6124     for (d = SCPrefBrowseDomains; d; d=d->next)
6125         if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6126             LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6127 
6128     ARListElem *b;
6129     for (b = LocalDomainEnumRecords; b; b=b->next)
6130         if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
6131             LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
6132 
6133     for (d = AutoBrowseDomains; d; d=d->next)
6134         if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6135             LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6136 
6137     for (d = AutoRegistrationDomains; d; d=d->next)
6138         if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6139             LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
6140 }
6141 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6142 
6143 mDNSlocal int send_msg(request_state *const req)
6144 {
6145     reply_state *const rep = req->replies;      // Send the first waiting reply
6146     ssize_t nwriten;
6147 
6148     ConvertHeaderBytes(rep->mhdr);
6149     nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
6150     ConvertHeaderBytes(rep->mhdr);
6151 
6152     if (nwriten < 0)
6153     {
6154         if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
6155         else
6156         {
6157 #if !defined(PLATFORM_NO_EPIPE)
6158             if (dnssd_errno == EPIPE)
6159                 return(req->ts = t_terminated);
6160             else
6161 #endif
6162             {
6163                 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
6164                        rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
6165                 return(t_error);
6166             }
6167         }
6168     }
6169     rep->nwriten += nwriten;
6170     return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
6171 }
6172 
6173 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
6174 {
6175     mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
6176     request_state **req = &all_requests;
6177 
6178     while (*req)
6179     {
6180         request_state *const r = *req;
6181 
6182         if (r->terminate == resolve_termination_callback)
6183             if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
6184             {
6185                 r->u.resolve.ReportTime = 0;
6186                 // if client received results and resolve still active
6187                 if (r->u.resolve.txt && r->u.resolve.srv)
6188                     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);
6189             }
6190 
6191         // Note: Only primary req's have reply lists, not subordinate req's.
6192         while (r->replies)      // Send queued replies
6193         {
6194             transfer_state result;
6195             if (r->replies->next)
6196                 r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
6197             result = send_msg(r);   // Returns t_morecoming if buffer full because client is not reading
6198             if (result == t_complete)
6199             {
6200                 reply_state *fptr = r->replies;
6201                 r->replies = r->replies->next;
6202                 freeL("reply_state/udsserver_idle", fptr);
6203                 r->time_blocked = 0; // reset failure counter after successful send
6204                 r->unresponsiveness_reports = 0;
6205                 continue;
6206             }
6207             else if (result == t_terminated)
6208             {
6209                 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);
6210                 abort_request(r);
6211             }
6212             else if (result == t_error)
6213             {
6214                 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r->sd, r->process_id, r->pid_name);
6215                 LogClientInfo(r);
6216                 abort_request(r);
6217             }
6218             break;
6219         }
6220 
6221         if (r->replies)     // If we failed to send everything, check our time_blocked timer
6222         {
6223             if (nextevent - now > mDNSPlatformOneSecond)
6224                 nextevent = now + mDNSPlatformOneSecond;
6225 
6226             if (mDNSStorage.SleepState != SleepState_Awake)
6227                 r->time_blocked = 0;
6228             else if (!r->time_blocked)
6229                 r->time_blocked = NonZeroTime(now);
6230             else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
6231             {
6232                 int num = 0;
6233                 struct reply_state *x = r->replies;
6234                 while (x)
6235                 {
6236                     num++;
6237                     x=x->next;
6238                 }
6239                 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
6240                        r->sd, r->process_id, r->pid_name, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
6241                 if (++r->unresponsiveness_reports >= 60)
6242                 {
6243                     LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r->sd, r->process_id, r->pid_name);
6244                     LogClientInfo(r);
6245                     abort_request(r);
6246                 }
6247             }
6248         }
6249 
6250         if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
6251         {
6252             // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
6253             *req = r->next;
6254             freeL("request_state/udsserver_idle", r);
6255         }
6256         else
6257             req = &r->next;
6258     }
6259     return nextevent;
6260 }
6261 
6262 struct CompileTimeAssertionChecks_uds_daemon
6263 {
6264     // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
6265     // other overly-large structures instead of having a pointer to them, can inadvertently
6266     // cause structure sizes (and therefore memory usage) to balloon unreasonably.
6267     char sizecheck_request_state          [(sizeof(request_state)           <= 3696) ? 1 : -1];
6268     char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <=   60) ? 1 : -1];
6269     char sizecheck_service_instance       [(sizeof(service_instance)        <= 6552) ? 1 : -1];
6270     char sizecheck_browser_t              [(sizeof(browser_t)               <= 1432) ? 1 : -1];
6271     char sizecheck_reply_hdr              [(sizeof(reply_hdr)               <=   12) ? 1 : -1];
6272     char sizecheck_reply_state            [(sizeof(reply_state)             <=   64) ? 1 : -1];
6273 };
6274 
6275 #ifdef UNIT_TEST
6276 #include "../unittests/uds_daemon_ut.c"
6277 #endif  //  UNIT_TEST
6278