1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2018 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 #define usleep(X) Sleep(((X)+999)/1000)
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
27 #include <sys/resource.h>
33 #include "mDNSEmbeddedAPI.h"
34 #include "DNSCommon.h"
36 #include "uds_daemon.h"
37 #include "dns_sd_internal.h"
39 // Normally we append search domains only for queries with a single label that are not
40 // fully qualified. This can be overridden to apply search domains for queries (that are
41 // not fully qualified) with any number of labels e.g., moon, moon.cs, moon.cs.be, etc.
42 mDNSBool AlwaysAppendSearchDomains
= mDNSfalse
;
44 // Control enabling ioptimistic DNS
45 mDNSBool EnableAllowExpired
= mDNStrue
;
47 // Apple-specific functionality, not required for other platforms
48 #if APPLE_OSX_mDNSResponder
49 #include <sys/ucred.h>
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
66 #if APPLE_OSX_mDNSResponder
67 #include <WebFilterDNS/WebFilterDNS.h>
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
));
76 // Do we really need to define a macro for "if"?
77 #define CHECK_WCF_FUNCTION(X) if (X)
82 #endif // APPLE_OSX_mDNSResponder
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)
88 #define MAX_ANONYMOUS_DATA 256
90 // ***************************************************************************
91 #if COMPILER_LIKES_PRAGMA_MARK
93 #pragma mark - Globals
97 mDNSexport mDNS mDNSStorage
;
98 mDNSexport
const char ProgramName
[] = "mDNSResponder";
100 #if defined(USE_TCP_LOOPBACK)
101 static char* boundPath
= NULL
;
103 static char* boundPath
= MDNS_UDS_SERVERPATH
;
106 #define MDNS_UDS_SERVERPATH_DEBUG "/var/tmp/mDNSResponder"
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
122 #if TARGET_OS_EMBEDDED
123 mDNSu32 curr_num_regservices
= 0;
124 mDNSu32 max_num_regservices
= 0;
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.
137 mDNSexport DNameListElem
*AutoRegistrationDomains
; // Domains where we automatically register for empty-string registrations
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
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
147 // If a platform specifies its own PID file name, we use that
149 #define PID_FILE "/var/run/mDNSResponder.pid"
152 mDNSlocal
char *AnonDataToString(const mDNSu8
*ad
, int adlen
, char *adstr
, int adstrlen
);
154 // ***************************************************************************
155 #if COMPILER_LIKES_PRAGMA_MARK
157 #pragma mark - General Utility Functions
160 mDNSlocal
void FatalError(char *errmsg
)
162 LogMsg("%s: %s", errmsg
, dnssd_strerror(dnssd_errno
));
166 mDNSlocal mDNSu32
dnssd_htonl(mDNSu32 l
)
169 char *data
= (char*) &ret
;
170 put_uint32(l
, &data
);
174 // hack to search-replace perror's to LogMsg's
175 mDNSlocal
void my_perror(char *errmsg
)
177 LogMsg("%s: %d (%s)", errmsg
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
180 // Throttled version of my_perror: Logs once every 250 msgs
181 mDNSlocal
void my_throttled_perror(char *err_msg
)
183 static int uds_throttle_count
= 0;
184 if ((uds_throttle_count
++ % 250) == 0)
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
)
192 if (mDNSOpaque16IsZero(q
->TargetQID
)) // Check for Mcast Query
194 mDNSBool mflag
= mDNSfalse
;
195 if (status
== q_start
)
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
);
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
)
219 if (!AuthRecord_uDNS(ar
)) // Check for Mcast Service
221 mDNSBool mflag
= mDNSfalse
;
222 if (status
== reg_start
)
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
);
242 // For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
243 mDNSexport
void LogMcastStateInfo(mDNSBool mflag
, mDNSBool start
, mDNSBool mstatelog
)
245 mDNS
*const m
= &mDNSStorage
;
250 LogMcastNoIdent("<None>");
254 request_state
*req
, *r
;
255 for (req
= all_requests
; req
; req
=req
->next
)
257 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
259 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
)
260 if (r
== req
->primary
)
263 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
264 GetMcastClients(req
);
267 LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords
, n_mquests
);
268 n_mrecords
= n_mquests
= 0; // Reset the values
273 static mDNSu32 i_mpktnum
;
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 ---");
283 LogMcastNoIdent("<None>");
287 request_state
*req
, *r
;
288 for (req
= all_requests
; req
; req
=req
->next
)
290 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
292 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
)
293 if (r
== req
->primary
)
295 LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req
->sd
);
297 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
298 LogMcastClientInfo(req
);
301 if(!mcount
) // To initially set mcount
306 i_mpktnum
= m
->MPktNum
;
307 LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount
, i_mpktnum
);
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 ---");
315 mDNSlocal
void abort_request(request_state
*req
)
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; }
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
);
325 if (!dnssd_SocketValid(req
->sd
))
326 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req
, req
->sd
); return; }
328 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
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
; }
336 while (req
->replies
) // free pending replies
338 reply_state
*ptr
= req
->replies
;
339 req
->replies
= req
->replies
->next
;
340 freeL("reply_state (abort)", ptr
);
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;
350 req
->sd
= req
->errsd
= dnssd_InvalidSocket
;
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;
357 mDNSexport
void SetDebugBoundPath(void)
359 #if !defined(USE_TCP_LOOPBACK)
360 boundPath
= MDNS_UDS_SERVERPATH_DEBUG
;
364 mDNSexport
int IsDebugSocketInUse(void)
366 #if !defined(USE_TCP_LOOPBACK)
367 return !strcmp(boundPath
, MDNS_UDS_SERVERPATH_DEBUG
);
374 mDNSlocal
void AbortUnlinkAndFree(request_state
*req
)
376 request_state
**p
= &all_requests
;
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
);
383 mDNSlocal reply_state
*create_reply(const reply_op_t op
, const size_t datalen
, request_state
*const request
)
387 if ((unsigned)datalen
< sizeof(reply_hdr
))
389 LogMsg("ERROR: create_reply - data length less than length of required fields");
393 reply
= mallocL("reply_state", sizeof(reply_state
) + datalen
- sizeof(reply_hdr
));
394 if (!reply
) FatalError("ERROR: malloc");
396 reply
->next
= mDNSNULL
;
397 reply
->totallen
= (mDNSu32
)datalen
+ sizeof(ipc_msg_hdr
);
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;
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
)
420 freeL("reply_state/append_reply", rep
);
424 r
= req
->primary
? req
->primary
: req
;
426 while (*ptr
) ptr
= &(*ptr
)->next
;
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
)
438 domainname type
, dom
;
440 if (!DeconstructServiceName(servicename
, &name
, &type
, &dom
))
441 return kDNSServiceErr_Invalid
;
444 char namestr
[MAX_DOMAIN_LABEL
+1];
445 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
446 char domstr
[MAX_ESCAPED_DOMAIN_NAME
];
450 ConvertDomainLabelToCString_unescaped(&name
, namestr
);
451 ConvertDomainNameToCString(&type
, typestr
);
452 ConvertDomainNameToCString(&dom
, domstr
);
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);
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
);
469 data
= (char *)&(*rep
)->rhdr
[1];
470 put_string(namestr
, &data
);
471 put_string(typestr
, &data
);
472 put_string(domstr
, &data
);
474 return mStatus_NoError
;
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
)
481 char namestr
[MAX_DOMAIN_LABEL
+1];
482 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
483 static const char domstr
[] = ".";
489 // 1. Put first label in namestr
490 ConvertDomainLabelToCString_unescaped((const domainlabel
*)servicename
, namestr
);
492 // 2. Put second label and "local" into typestr
493 mDNS_snprintf(typestr
, sizeof(typestr
), "%#s.local.", SecondLabel(servicename
));
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);
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
);
510 data
= (char *)&(*rep
)->rhdr
[1];
511 put_string(namestr
, &data
);
512 put_string(typestr
, &data
);
513 put_string(domstr
, &data
);
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
)
521 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
522 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
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
);
532 mDNSInterfaceID InterfaceID
;
535 request
->flags
= flags
;
536 request
->interfaceIndex
= interfaceIndex
;
538 if (str_err
) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL
; }
540 if (!request
->msgptr
) { LogMsg("Error reading Resource Record from client"); return NULL
; }
542 if (validate_flags
&&
543 !((flags
& kDNSServiceFlagsShared
) == kDNSServiceFlagsShared
) &&
544 !((flags
& kDNSServiceFlagsUnique
) == kDNSServiceFlagsUnique
))
546 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
550 rr
= mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord
) - sizeof(RDataBody
) + storage_size
);
551 if (!rr
) FatalError("ERROR: malloc");
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
;
566 artype
= AuthRecordAny
;
568 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, type
, 0,
569 (mDNSu8
) ((flags
& kDNSServiceFlagsShared
) ? kDNSRecordTypeShared
: kDNSRecordTypeUnique
), artype
, mDNSNULL
, mDNSNULL
);
571 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, name
))
573 LogMsg("ERROR: bad name: %s", name
);
574 freeL("AuthRecord/read_rr_from_ipc_msg", rr
);
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
589 mDNSlocal
int build_domainname_from_strings(domainname
*srv
, char *name
, char *regtype
, char *domain
)
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;
601 mDNSlocal
void send_all(dnssd_sock_t s
, const char *ptr
, int len
)
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.
608 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
609 s
, n
, len
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
613 mDNSlocal mDNSBool
AuthorizedDomain(const request_state
* const request
, const domainname
* const d
, const DNameListElem
* const doms
)
615 const DNameListElem
*delem
= mDNSNULL
;
616 int bestDelta
= -1; // the delta of the best match, lower is better
618 mDNSBool allow
= mDNSfalse
;
620 if (SystemUID(request
->uid
)) return mDNStrue
;
622 dLabels
= CountLabels(d
);
623 for (delem
= doms
; delem
; delem
= delem
->next
)
627 int delemLabels
= CountLabels(&delem
->name
);
628 int delta
= dLabels
- delemLabels
;
629 if ((bestDelta
== -1 || delta
<= bestDelta
) && SameDomainName(&delem
->name
, SkipLeadingLabels(d
, delta
)))
632 allow
= (allow
|| (delem
->uid
== request
->uid
));
637 return bestDelta
== -1 ? mDNStrue
: allow
;
641 // ***************************************************************************
642 #if COMPILER_LIKES_PRAGMA_MARK
644 #pragma mark - external helpers
647 mDNSexport mDNSBool
callExternalHelpers(mDNSInterfaceID InterfaceID
, const domainname
*const domain
, DNSServiceFlags flags
)
649 #if APPLE_OSX_mDNSResponder
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
))
667 #endif // APPLE_OSX_mDNSResponder
670 mDNSlocal
void external_start_advertising_helper(service_instance
*const instance
)
672 AuthRecord
*st
= instance
->subtypes
;
673 ExtraResourceRecord
*e
;
676 if (mDNSIPPortIsZero(instance
->request
->u
.servicereg
.port
))
678 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
682 if (instance
->external_advertise
) LogMsg("external_start_advertising_helper: external_advertise already set!");
684 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
685 external_start_advertising_service(&st
[i
].resrec
, instance
->request
->flags
);
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
);
690 external_start_advertising_service(&instance
->srs
.RR_TXT
.resrec
, instance
->request
->flags
);
692 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
693 external_start_advertising_service(&e
->r
.resrec
, instance
->request
->flags
);
695 instance
->external_advertise
= mDNStrue
;
698 mDNSlocal
void external_stop_advertising_helper(service_instance
*const instance
)
700 AuthRecord
*st
= instance
->subtypes
;
701 ExtraResourceRecord
*e
;
704 if (!instance
->external_advertise
) return;
706 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
708 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
709 external_stop_advertising_service(&st
[i
].resrec
, instance
->request
->flags
);
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
);
715 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
716 external_stop_advertising_service(&e
->r
.resrec
, instance
->request
->flags
);
718 instance
->external_advertise
= mDNSfalse
;
721 // ***************************************************************************
722 #if COMPILER_LIKES_PRAGMA_MARK
724 #pragma mark - DNSServiceRegister
727 mDNSexport
void FreeExtraRR(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
729 ExtraResourceRecord
*extra
= (ExtraResourceRecord
*)rr
->RecordContext
;
732 if (result
!= mStatus_MemFree
) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result
); return; }
734 LogInfo(" FreeExtraRR %s", RRDisplayString(m
, &rr
->resrec
));
736 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
)
737 freeL("Extra RData", rr
->resrec
.rdata
);
738 freeL("ExtraResourceRecord/FreeExtraRR", extra
);
741 mDNSlocal
void unlink_and_free_service_instance(service_instance
*srv
)
743 ExtraResourceRecord
*e
= srv
->srs
.Extras
, *tmp
;
745 external_stop_advertising_helper(srv
);
747 // clear pointers from parent struct
750 service_instance
**p
= &srv
->request
->u
.servicereg
.instances
;
753 if (*p
== srv
) { *p
= (*p
)->next
; break; }
760 e
->r
.RecordContext
= e
;
763 FreeExtraRR(&mDNSStorage
, &tmp
->r
, mStatus_MemFree
);
766 if (srv
->srs
.RR_TXT
.resrec
.rdata
!= &srv
->srs
.RR_TXT
.rdatastorage
)
767 freeL("TXT RData", srv
->srs
.RR_TXT
.resrec
.rdata
);
771 freeL("ServiceSubTypes", srv
->subtypes
);
772 srv
->subtypes
= NULL
;
774 if (srv
->srs
.AnonData
)
776 freeL("Anonymous", (void *)srv
->srs
.AnonData
);
777 srv
->srs
.AnonData
= NULL
;
779 freeL("service_instance", srv
);
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
)
788 ResourceRecord
*r
= &srs
->RR_SRV
.resrec
;
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
))
795 verbosedebugf("%d peer registrations for %##s", count
, r
->name
->c
);
799 mDNSexport
int CountExistingRegistrations(domainname
*srv
, mDNSIPPort port
)
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
))
811 mDNSlocal
void SendServiceRemovalNotification(ServiceRecordSet
*const srs
)
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
; }
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
)
825 mDNSBool SuppressError
= mDNSfalse
;
826 service_instance
*instance
;
830 if (!srs
) { LogMsg("regservice_callback: srs is NULL %d", result
); return; }
832 instance
= srs
->ServiceContext
;
833 if (!instance
) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result
); return; }
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
;
841 if (mDNS_LoggingEnabled
)
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
);
854 if (!instance
->request
&& result
!= mStatus_MemFree
) { LogMsg("regservice_callback: instance->request is NULL %d", result
); return; }
856 if (result
== mStatus_NoError
)
858 if (instance
->request
->u
.servicereg
.allowremotequery
)
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
;
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
; }
872 if (callExternalHelpers(instance
->request
->u
.servicereg
.InterfaceID
, &instance
->domain
, instance
->request
->flags
))
874 LogInfo("regservice_callback: calling external_start_advertising_helper()");
875 external_start_advertising_helper(instance
);
877 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(srs
) == 0)
878 RecordUpdatedNiceLabel(0); // Successfully got new name, tell user immediately
880 else if (result
== mStatus_MemFree
)
882 #if TARGET_OS_EMBEDDED
883 curr_num_regservices
--;
885 if (instance
->request
&& instance
->renameonmemfree
)
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
894 unlink_and_free_service_instance(instance
);
896 else if (result
== mStatus_NameConflict
)
898 if (instance
->request
->u
.servicereg
.autorename
)
900 external_stop_advertising_helper(instance
);
901 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(srs
) == 0)
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()
907 else // On conflict for a non-autoname service, rename and reregister just that one service
909 if (instance
->clientnotified
) SendServiceRemovalNotification(srs
);
910 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
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
; }
921 unlink_and_free_service_instance(instance
);
924 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
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
; }
935 mDNSlocal
void regrecord_callback(mDNS
*const m
, AuthRecord
*rr
, mStatus result
)
938 if (!rr
->RecordContext
) // parent struct already freed by termination callback
940 if (result
== mStatus_NoError
)
941 LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m
, rr
));
944 if (result
!= mStatus_MemFree
) LogMsg("regrecord_callback: error %d received after parent termination", result
);
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
);
956 registered_record_entry
*re
= rr
->RecordContext
;
957 request_state
*request
= re
->request
;
959 if (mDNS_LoggingEnabled
)
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
);
968 if (result
!= mStatus_MemFree
)
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
);
981 // If this is a callback to a keepalive record, do not free it.
982 if (result
== mStatus_BadStateErr
)
984 LogInfo("regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.");
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; }
993 freeL("registered_record_entry AuthRecord regrecord_callback", re
->rr
);
994 freeL("registered_record_entry regrecord_callback", re
);
999 if (re
->external_advertise
) LogMsg("regrecord_callback: external_advertise already set!");
1001 if (callExternalHelpers(re
->origInterfaceID
, &rr
->namestorage
, request
->flags
))
1003 LogInfo("regrecord_callback: calling external_start_advertising_service");
1004 external_start_advertising_service(&rr
->resrec
, request
->flags
);
1005 re
->external_advertise
= mDNStrue
;
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
)
1015 pid_t p
= (pid_t
) -1;
1016 socklen_t len
= sizeof(p
);
1017 request
->pid_name
[0] = '\0';
1018 request
->process_id
= -1;
1019 #ifdef LOCAL_PEEREPID
1020 if (request
->sd
< 0)
1022 // to extract the effective pid value
1023 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREPID
, &p
, &len
) != 0)
1025 // to extract the process name from the pid value
1026 if (proc_pidinfo(p
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0)
1028 mDNSPlatformStrLCopy(request
->pid_name
, proc
.pbsi_comm
, sizeof(request
->pid_name
));
1029 request
->process_id
= p
;
1030 debugf("set_peer_pid: Client PEEREPID is %d %s", p
, request
->pid_name
);
1031 #else // !LOCAL_PEEREPID
1033 LogInfo("set_peer_pid: Not Supported on this version of OS");
1034 if (request
->sd
< 0)
1036 #endif // LOCAL_PEEREPID
1039 mDNSlocal
void connection_termination(request_state
*request
)
1041 // When terminating a shared connection, we need to scan the all_requests list
1042 // and terminate any subbordinate operations sharing this file descriptor
1043 request_state
**req
= &all_requests
;
1045 LogOperation("%3d: DNSServiceCreateConnection STOP PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
1049 if ((*req
)->primary
== request
)
1051 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1052 request_state
*tmp
= *req
;
1053 if (tmp
->primary
== tmp
) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp
, tmp
->sd
);
1054 if (tmp
->replies
) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp
, tmp
->sd
);
1057 freeL("request_state/connection_termination", tmp
);
1060 req
= &(*req
)->next
;
1063 while (request
->u
.reg_recs
)
1065 registered_record_entry
*ptr
= request
->u
.reg_recs
;
1066 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP PID[%d](%s)", request
->sd
, ptr
->key
, RRDisplayString(&mDNSStorage
, &ptr
->rr
->resrec
), request
->process_id
, request
->pid_name
);
1067 request
->u
.reg_recs
= request
->u
.reg_recs
->next
;
1068 ptr
->rr
->RecordContext
= NULL
;
1069 if (ptr
->external_advertise
)
1071 ptr
->external_advertise
= mDNSfalse
;
1072 external_stop_advertising_service(&ptr
->rr
->resrec
, request
->flags
);
1074 LogMcastS(ptr
->rr
, request
, reg_stop
);
1075 mDNS_Deregister(&mDNSStorage
, ptr
->rr
); // Will free ptr->rr for us
1076 freeL("registered_record_entry/connection_termination", ptr
);
1080 mDNSlocal
void handle_cancel_request(request_state
*request
)
1082 request_state
**req
= &all_requests
;
1083 LogDebug("%3d: Cancel %08X %08X", request
->sd
, request
->hdr
.client_context
.u32
[1], request
->hdr
.client_context
.u32
[0]);
1086 if ((*req
)->primary
== request
&&
1087 (*req
)->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1088 (*req
)->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1])
1090 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1091 request_state
*tmp
= *req
;
1094 freeL("request_state/handle_cancel_request", tmp
);
1097 req
= &(*req
)->next
;
1101 mDNSlocal mStatus
handle_regrecord_request(request_state
*request
)
1103 mStatus err
= mStatus_BadParamErr
;
1106 if (request
->terminate
!= connection_termination
)
1107 { LogMsg("%3d: DNSServiceRegisterRecord(not a shared connection ref)", request
->sd
); return(err
); }
1109 rr
= read_rr_from_ipc_msg(request
, 1, 1);
1112 registered_record_entry
*re
;
1113 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1114 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1115 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
&& !IsLocalDomain(rr
->resrec
.name
) &&
1116 rr
->resrec
.rrclass
== kDNSClass_IN
&& (rr
->resrec
.rrtype
== kDNSType_A
|| rr
->resrec
.rrtype
== kDNSType_AAAA
||
1117 rr
->resrec
.rrtype
== kDNSType_CNAME
))
1119 freeL("AuthRecord/handle_regrecord_request", rr
);
1120 return (mStatus_BadParamErr
);
1122 // allocate registration entry, link into list
1123 re
= mallocL("registered_record_entry", sizeof(registered_record_entry
));
1125 FatalError("ERROR: malloc");
1126 re
->key
= request
->hdr
.reg_index
;
1128 re
->regrec_client_context
= request
->hdr
.client_context
;
1129 re
->request
= request
;
1130 re
->external_advertise
= mDNSfalse
;
1131 rr
->RecordContext
= re
;
1132 rr
->RecordCallback
= regrecord_callback
;
1134 re
->origInterfaceID
= rr
->resrec
.InterfaceID
;
1135 if (rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1136 rr
->resrec
.InterfaceID
= mDNSInterface_Any
;
1138 if (!AuthorizedDomain(request
, rr
->resrec
.name
, AutoRegistrationDomains
)) return (mStatus_NoError
);
1140 if (rr
->resrec
.rroriginalttl
== 0)
1141 rr
->resrec
.rroriginalttl
= DefaultTTLforRRType(rr
->resrec
.rrtype
);
1143 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START PID[%d](%s)", request
->sd
, re
->key
, RRDisplayString(&mDNSStorage
, &rr
->resrec
),
1144 request
->process_id
, request
->pid_name
);
1146 err
= mDNS_Register(&mDNSStorage
, rr
);
1149 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request
->sd
, re
->key
, RRDisplayString(&mDNSStorage
, &rr
->resrec
), err
);
1150 freeL("registered_record_entry", re
);
1151 freeL("registered_record_entry/AuthRecord", rr
);
1155 LogMcastS(rr
, request
, reg_start
);
1156 re
->next
= request
->u
.reg_recs
;
1157 request
->u
.reg_recs
= re
;
1163 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
);
1165 mDNSlocal
void regservice_termination_callback(request_state
*request
)
1169 LogMsg("regservice_termination_callback context is NULL");
1172 while (request
->u
.servicereg
.instances
)
1174 service_instance
*p
= request
->u
.servicereg
.instances
;
1175 request
->u
.servicereg
.instances
= request
->u
.servicereg
.instances
->next
;
1176 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1177 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP PID[%d](%s)", request
->sd
, p
->srs
.RR_SRV
.resrec
.name
->c
,
1178 mDNSVal16(p
->srs
.RR_SRV
.resrec
.rdata
->u
.srv
.port
), request
->process_id
, request
->pid_name
);
1180 external_stop_advertising_helper(p
);
1182 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1183 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1184 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1185 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1186 // because by then we might have already freed p
1188 LogMcastS(&p
->srs
.RR_SRV
, request
, reg_stop
);
1189 if (mDNS_DeregisterService(&mDNSStorage
, &p
->srs
))
1191 unlink_and_free_service_instance(p
);
1192 // Don't touch service_instance *p after this -- it's likely to have been freed already
1195 if (request
->u
.servicereg
.txtdata
)
1197 freeL("service_info txtdata", request
->u
.servicereg
.txtdata
);
1198 request
->u
.servicereg
.txtdata
= NULL
;
1200 if (request
->u
.servicereg
.autoname
)
1202 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1203 request
->u
.servicereg
.autoname
= mDNSfalse
;
1204 UpdateDeviceInfoRecord(&mDNSStorage
);
1208 mDNSlocal request_state
*LocateSubordinateRequest(request_state
*request
)
1211 for (req
= all_requests
; req
; req
= req
->next
)
1212 if (req
->primary
== request
&&
1213 req
->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1214 req
->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1]) return(req
);
1218 mDNSlocal mStatus
add_record_to_service(request_state
*request
, service_instance
*instance
, mDNSu16 rrtype
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
)
1220 ServiceRecordSet
*srs
= &instance
->srs
;
1222 size_t size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1223 ExtraResourceRecord
*extra
= mallocL("ExtraResourceRecord", sizeof(*extra
) - sizeof(RDataBody
) + size
);
1224 if (!extra
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1226 mDNSPlatformMemZero(extra
, sizeof(ExtraResourceRecord
)); // OK if oversized rdata not zero'd
1227 extra
->r
.resrec
.rrtype
= rrtype
;
1228 extra
->r
.rdatastorage
.MaxRDLength
= (mDNSu16
) size
;
1229 extra
->r
.resrec
.rdlength
= rdlen
;
1230 mDNSPlatformMemCopy(&extra
->r
.rdatastorage
.u
.data
, rdata
, rdlen
);
1231 // use InterfaceID value from DNSServiceRegister() call that created the original service
1232 extra
->r
.resrec
.InterfaceID
= request
->u
.servicereg
.InterfaceID
;
1234 result
= mDNS_AddRecordToService(&mDNSStorage
, srs
, extra
, &extra
->r
.rdatastorage
, ttl
, request
->flags
);
1237 freeL("ExtraResourceRecord/add_record_to_service", extra
);
1240 LogMcastS(&srs
->RR_PTR
, request
, reg_start
);
1242 extra
->ClientID
= request
->hdr
.reg_index
;
1243 if ( instance
->external_advertise
1244 && callExternalHelpers(request
->u
.servicereg
.InterfaceID
, &instance
->domain
, request
->flags
))
1246 LogInfo("add_record_to_service: calling external_start_advertising_service");
1247 external_start_advertising_service(&extra
->r
.resrec
, request
->flags
);
1252 mDNSlocal mStatus
handle_add_request(request_state
*request
)
1254 service_instance
*i
;
1255 mStatus result
= mStatus_UnknownErr
;
1256 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
);
1257 mDNSu16 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
1258 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1259 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1260 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1261 if (!ttl
) ttl
= DefaultTTLforRRType(rrtype
);
1262 (void)flags
; // Unused
1264 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1266 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1267 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1269 if (request
->terminate
!= regservice_termination_callback
)
1270 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1272 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1273 // in the application. See radar://9165807.
1274 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1275 { LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request
->sd
); return(mStatus_BadParamErr
); }
1277 LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d) PID[%d](%s)", request
->sd
, flags
,
1278 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
, DNSTypeName(rrtype
), rdlen
,
1279 request
->process_id
, request
->pid_name
);
1281 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1283 result
= add_record_to_service(request
, i
, rrtype
, rdlen
, rdata
, ttl
);
1284 if (result
&& i
->default_local
) break;
1285 else result
= mStatus_NoError
; // suppress non-local default errors
1291 mDNSlocal
void update_callback(mDNS
*const m
, AuthRecord
*const rr
, RData
*oldrd
, mDNSu16 oldrdlen
)
1293 mDNSBool external_advertise
= (rr
->UpdateContext
) ? *((mDNSBool
*)rr
->UpdateContext
) : mDNSfalse
;
1296 // There are three cases.
1298 // 1. We have updated the primary TXT record of the service
1299 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1300 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1302 // external_advertise is set if we have advertised at least once during the initial addition
1303 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1304 // checks during the first time and hence we don't do any checks here
1305 if (external_advertise
)
1307 ResourceRecord ext
= rr
->resrec
;
1308 DNSServiceFlags flags
= deriveD2DFlagsFromAuthRecType(rr
->ARType
);
1310 if (ext
.rdlength
== oldrdlen
&& mDNSPlatformMemSame(&ext
.rdata
->u
, &oldrd
->u
, oldrdlen
)) goto exit
;
1311 SetNewRData(&ext
, oldrd
, oldrdlen
);
1312 external_stop_advertising_service(&ext
, flags
);
1313 LogInfo("update_callback: calling external_start_advertising_service");
1314 external_start_advertising_service(&rr
->resrec
, flags
);
1317 if (oldrd
!= &rr
->rdatastorage
) freeL("RData/update_callback", oldrd
);
1320 mDNSlocal mStatus
update_record(AuthRecord
*rr
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
, const mDNSBool
*const external_advertise
)
1323 const size_t rdsize
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1324 RData
*newrd
= mallocL("RData/update_record", sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
1325 if (!newrd
) FatalError("ERROR: malloc");
1326 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
1327 mDNSPlatformMemCopy(&newrd
->u
, rdata
, rdlen
);
1329 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1330 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1331 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1332 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rdlen
== 0) { rdlen
= 1; newrd
->u
.txt
.c
[0] = 0; }
1334 if (external_advertise
) rr
->UpdateContext
= (void *)external_advertise
;
1336 result
= mDNS_Update(&mDNSStorage
, rr
, ttl
, rdlen
, newrd
, update_callback
);
1337 if (result
) { LogMsg("update_record: Error %d for %s", (int)result
, ARDisplayString(&mDNSStorage
, rr
)); freeL("RData/update_record", newrd
); }
1341 mDNSlocal mStatus
handle_update_request(request_state
*request
)
1343 const ipc_msg_hdr
*const hdr
= &request
->hdr
;
1344 mStatus result
= mStatus_BadReferenceErr
;
1345 service_instance
*i
;
1346 AuthRecord
*rr
= NULL
;
1348 // get the message data
1349 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
); // flags unused
1350 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1351 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1352 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1353 (void)flags
; // Unused
1355 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1357 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1358 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1360 if (request
->terminate
== connection_termination
)
1362 // update an individually registered record
1363 registered_record_entry
*reptr
;
1364 for (reptr
= request
->u
.reg_recs
; reptr
; reptr
= reptr
->next
)
1366 if (reptr
->key
== hdr
->reg_index
)
1368 result
= update_record(reptr
->rr
, rdlen
, rdata
, ttl
, &reptr
->external_advertise
);
1369 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)",
1370 request
->sd
, reptr
->rr
->resrec
.name
->c
, reptr
->rr
? DNSTypeName(reptr
->rr
->resrec
.rrtype
) : "<NONE>",
1371 request
->process_id
, request
->pid_name
);
1375 result
= mStatus_BadReferenceErr
;
1379 if (request
->terminate
!= regservice_termination_callback
)
1380 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1382 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1383 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1384 { LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request
->sd
); return(mStatus_BadParamErr
); }
1386 // update the saved off TXT data for the service
1387 if (hdr
->reg_index
== TXT_RECORD_INDEX
)
1389 if (request
->u
.servicereg
.txtdata
)
1390 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1393 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", rdlen
);
1394 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_update_request - malloc");
1395 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, rdata
, rdlen
);
1397 request
->u
.servicereg
.txtlen
= rdlen
;
1400 // update a record from a service record set
1401 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1403 if (hdr
->reg_index
== TXT_RECORD_INDEX
) rr
= &i
->srs
.RR_TXT
;
1406 ExtraResourceRecord
*e
;
1407 for (e
= i
->srs
.Extras
; e
; e
= e
->next
)
1408 if (e
->ClientID
== hdr
->reg_index
) { rr
= &e
->r
; break; }
1411 if (!rr
) { result
= mStatus_BadReferenceErr
; goto end
; }
1412 result
= update_record(rr
, rdlen
, rdata
, ttl
, &i
->external_advertise
);
1413 if (result
&& i
->default_local
) goto end
;
1414 else result
= mStatus_NoError
; // suppress non-local default errors
1418 if (request
->terminate
== regservice_termination_callback
)
1419 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)", request
->sd
,
1420 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1421 rr
? DNSTypeName(rr
->resrec
.rrtype
) : "<NONE>",
1422 request
->process_id
, request
->pid_name
);
1427 // remove a resource record registered via DNSServiceRegisterRecord()
1428 mDNSlocal mStatus
remove_record(request_state
*request
)
1430 mStatus err
= mStatus_UnknownErr
;
1431 registered_record_entry
*e
, **ptr
= &request
->u
.reg_recs
;
1433 while (*ptr
&& (*ptr
)->key
!= request
->hdr
.reg_index
) ptr
= &(*ptr
)->next
;
1434 if (!*ptr
) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request
->sd
, request
->hdr
.reg_index
); return mStatus_BadReferenceErr
; }
1436 *ptr
= e
->next
; // unlink
1438 LogOperation("%3d: DNSServiceRemoveRecord(%u %s) PID[%d](%s)",
1439 request
->sd
, e
->key
, RRDisplayString(&mDNSStorage
, &e
->rr
->resrec
), request
->process_id
, request
->pid_name
);
1440 e
->rr
->RecordContext
= NULL
;
1441 if (e
->external_advertise
)
1443 external_stop_advertising_service(&e
->rr
->resrec
, request
->flags
);
1444 e
->external_advertise
= mDNSfalse
;
1446 LogMcastS(e
->rr
, request
, reg_stop
);
1447 err
= mDNS_Deregister(&mDNSStorage
, e
->rr
); // Will free e->rr for us; we're responsible for freeing e
1450 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err
);
1451 freeL("registered_record_entry AuthRecord remove_record", e
->rr
);
1453 freeL("registered_record_entry remove_record", e
);
1457 mDNSlocal mStatus
remove_extra(const request_state
*const request
, service_instance
*const serv
, mDNSu16
*const rrtype
)
1459 mStatus err
= mStatus_BadReferenceErr
;
1460 ExtraResourceRecord
*ptr
;
1462 for (ptr
= serv
->srs
.Extras
; ptr
; ptr
= ptr
->next
)
1464 if (ptr
->ClientID
== request
->hdr
.reg_index
) // found match
1466 *rrtype
= ptr
->r
.resrec
.rrtype
;
1467 if (serv
->external_advertise
) external_stop_advertising_service(&ptr
->r
.resrec
, request
->flags
);
1468 err
= mDNS_RemoveRecordFromService(&mDNSStorage
, &serv
->srs
, ptr
, FreeExtraRR
, ptr
);
1475 mDNSlocal mStatus
handle_removerecord_request(request_state
*request
)
1477 mStatus err
= mStatus_BadReferenceErr
;
1478 get_flags(&request
->msgptr
, request
->msgend
); // flags unused
1480 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1482 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1483 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1485 if (request
->terminate
== connection_termination
)
1486 err
= remove_record(request
); // remove individually registered record
1487 else if (request
->terminate
!= regservice_termination_callback
)
1488 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1491 service_instance
*i
;
1493 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s) PID[%d](%s)", request
->sd
,
1494 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1495 rrtype
? DNSTypeName(rrtype
) : "<NONE>", request
->process_id
, request
->pid_name
);
1496 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1498 err
= remove_extra(request
, i
, &rrtype
);
1499 if (err
&& i
->default_local
) break;
1500 else err
= mStatus_NoError
; // suppress non-local default errors
1507 // If there's a comma followed by another character,
1508 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1509 // Otherwise, it returns a pointer to the final nul at the end of the string
1510 mDNSlocal
char *FindFirstSubType(char *p
, char **AnonData
)
1514 if (p
[0] == '\\' && p
[1])
1518 else if (p
[0] == ',' && p
[1])
1523 else if (p
[0] == ':' && p
[1])
1536 // If there's a comma followed by another character,
1537 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1538 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1539 // Otherwise, it returns a pointer to the final nul at the end of the string
1540 mDNSlocal
char *FindNextSubType(char *p
)
1544 if (p
[0] == '\\' && p
[1]) // If escape character
1545 p
+= 2; // ignore following character
1546 else if (p
[0] == ',') // If we found a comma
1551 else if (p
[0] == '.')
1558 // Returns -1 if illegal subtype found
1559 mDNSexport mDNSs32
ChopSubTypes(char *regtype
, char **AnonData
)
1561 mDNSs32 NumSubTypes
= 0;
1562 char *stp
= FindFirstSubType(regtype
, AnonData
);
1563 while (stp
&& *stp
) // If we found a comma...
1565 if (*stp
== ',') return(-1);
1567 stp
= FindNextSubType(stp
);
1569 if (!stp
) return(-1);
1570 return(NumSubTypes
);
1573 mDNSexport AuthRecord
*AllocateSubTypes(mDNSs32 NumSubTypes
, char *p
, char **AnonData
)
1575 AuthRecord
*st
= mDNSNULL
;
1577 // "p" is pointing at the regtype e.g., _http._tcp followed by ":<AnonData>" indicated
1578 // by AnonData being non-NULL which is in turn follwed by ",<SubTypes>" indicated by
1579 // NumSubTypes being non-zero. We need to skip the initial regtype to get to the actual
1580 // data that we want. When we come here, ChopSubTypes has null terminated like this e.g.,
1582 // _http._tcp<NULL><AnonData><NULL><SubType1><NULL><SubType2><NULL> etc.
1584 // 1. If we have Anonymous data and subtypes, skip the regtype (e.g., "_http._tcp")
1585 // to get the AnonData and then skip the AnonData to get to the SubType.
1587 // 2. If we have only SubTypes, skip the regtype to get to the SubType data.
1589 // 3. If we have only AnonData, skip the regtype to get to the AnonData.
1591 // 4. If we don't have AnonData or NumStypes, it is a noop.
1601 len
= strlen(p
) + 1;
1602 *AnonData
= mallocL("Anonymous", len
);
1607 mDNSPlatformMemCopy(*AnonData
, p
, len
);
1612 st
= mallocL("ServiceSubTypes", NumSubTypes
* sizeof(AuthRecord
));
1613 if (!st
) return(mDNSNULL
);
1614 for (i
= 0; i
< NumSubTypes
; i
++)
1616 mDNS_SetupResourceRecord(&st
[i
], mDNSNULL
, mDNSInterface_Any
, kDNSQType_ANY
, kStandardTTL
, 0, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
1617 // First time through we skip the regtype or AnonData. Subsequently, the
1618 // previous subtype.
1621 if (!MakeDomainNameFromDNSNameString(&st
[i
].namestorage
, p
))
1623 freeL("ServiceSubTypes", st
);
1624 if (AnonData
&& *AnonData
)
1625 freeL("AnonymousData", *AnonData
);
1630 // If NumSubTypes is zero and AnonData is non-NULL, we still return NULL but AnonData has been
1631 // initialized. The caller knows how to handle this.
1635 mDNSlocal mStatus
register_service_instance(request_state
*request
, const domainname
*domain
)
1637 service_instance
**ptr
, *instance
;
1638 size_t extra_size
= (request
->u
.servicereg
.txtlen
> sizeof(RDataBody
)) ? (request
->u
.servicereg
.txtlen
- sizeof(RDataBody
)) : 0;
1639 const mDNSBool DomainIsLocal
= SameDomainName(domain
, &localdomain
);
1641 mDNSInterfaceID interfaceID
= request
->u
.servicereg
.InterfaceID
;
1643 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1644 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1645 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1646 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1647 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1648 if (request
->u
.servicereg
.default_domain
&& !DomainIsLocal
) interfaceID
= mDNSInterface_Any
;
1650 for (ptr
= &request
->u
.servicereg
.instances
; *ptr
; ptr
= &(*ptr
)->next
)
1652 if (SameDomainName(&(*ptr
)->domain
, domain
))
1654 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1655 domain
->c
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
);
1656 return mStatus_AlreadyRegistered
;
1660 instance
= mallocL("service_instance", sizeof(*instance
) + extra_size
);
1661 if (!instance
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1663 instance
->next
= mDNSNULL
;
1664 instance
->request
= request
;
1665 instance
->renameonmemfree
= 0;
1666 instance
->clientnotified
= mDNSfalse
;
1667 instance
->default_local
= (request
->u
.servicereg
.default_domain
&& DomainIsLocal
);
1668 instance
->external_advertise
= mDNSfalse
;
1669 AssignDomainName(&instance
->domain
, domain
);
1671 instance
->srs
.AnonData
= mDNSNULL
;
1672 if (!request
->u
.servicereg
.AnonData
)
1674 instance
->subtypes
= AllocateSubTypes(request
->u
.servicereg
.num_subtypes
, request
->u
.servicereg
.type_as_string
, mDNSNULL
);
1678 char *AnonData
= mDNSNULL
;
1679 instance
->subtypes
= AllocateSubTypes(request
->u
.servicereg
.num_subtypes
, request
->u
.servicereg
.type_as_string
, &AnonData
);
1681 instance
->srs
.AnonData
= (const mDNSu8
*)AnonData
;
1684 if (request
->u
.servicereg
.num_subtypes
&& !instance
->subtypes
)
1686 unlink_and_free_service_instance(instance
);
1688 FatalError("ERROR: malloc");
1691 result
= mDNS_RegisterService(&mDNSStorage
, &instance
->srs
,
1692 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
,
1693 request
->u
.servicereg
.host
.c
[0] ? &request
->u
.servicereg
.host
: NULL
,
1694 request
->u
.servicereg
.port
,
1695 mDNSNULL
, request
->u
.servicereg
.txtdata
, request
->u
.servicereg
.txtlen
,
1696 instance
->subtypes
, request
->u
.servicereg
.num_subtypes
,
1697 interfaceID
, regservice_callback
, instance
, request
->flags
);
1701 *ptr
= instance
; // Append this to the end of our request->u.servicereg.instances list
1702 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance
->request
->sd
,
1703 instance
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(request
->u
.servicereg
.port
));
1704 LogMcastS(&instance
->srs
.RR_SRV
, request
, reg_start
);
1708 LogMsg("register_service_instance %#s.%##s%##s error %d",
1709 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
->c
, result
);
1710 unlink_and_free_service_instance(instance
);
1716 mDNSlocal
void udsserver_default_reg_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
1718 request_state
*request
;
1720 LogMsg("%s registration domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
1721 for (request
= all_requests
; request
; request
= request
->next
)
1723 if (request
->terminate
!= regservice_termination_callback
) continue;
1724 if (!request
->u
.servicereg
.default_domain
) continue;
1725 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
1727 service_instance
**ptr
= &request
->u
.servicereg
.instances
;
1728 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
1731 // If we don't already have this domain in our list for this registration, add it now
1732 if (!*ptr
) register_service_instance(request
, &d
->name
);
1733 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d
->name
);
1737 // Normally we should not fail to find the specified instance
1738 // One case where this can happen is if a uDNS update fails for some reason,
1739 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1741 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1742 &d
->name
, request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type_as_string
);
1746 for (p
= AutoRegistrationDomains
; p
; p
=p
->next
)
1747 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
1748 if (SameDomainName(&d
->name
, &p
->name
)) break;
1749 if (p
) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d
->name
);
1753 service_instance
*si
= *ptr
;
1755 if (si
->clientnotified
) SendServiceRemovalNotification(&si
->srs
); // Do this *before* clearing si->request backpointer
1756 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1757 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1758 // process of completing asynchronously, the client cancels the entire operation, so
1759 // regservice_termination_callback then runs through the whole list deregistering each
1760 // instance, clearing the backpointers, and then disposing the parent request_state object.
1761 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1762 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1763 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1764 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1766 err
= mDNS_DeregisterService(&mDNSStorage
, &si
->srs
);
1767 if (err
) { LogMsg("udsserver_default_reg_domain_changed err %d", err
); unlink_and_free_service_instance(si
); }
1775 // Don't allow normal and anonymous registration to coexist.
1776 mDNSlocal mDNSBool
CheckForMixedRegistrations(domainname
*regtype
, domainname
*domain
, mDNSBool AnonData
)
1778 request_state
*request
;
1780 // We only care about local domains where the anonymous extension is
1782 if (!SameDomainName(domain
, (const domainname
*) "\x5" "local"))
1787 for (request
= all_requests
; request
; request
= request
->next
)
1789 service_instance
*ptr
;
1791 if (request
->terminate
!= regservice_termination_callback
) continue;
1792 for (ptr
= request
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
1794 if (!SameDomainName(&ptr
->domain
, (const domainname
*)"\x5" "local") ||
1795 !SameDomainName(&request
->u
.servicereg
.type
, regtype
))
1800 // If we are about to register a anonymous registraion, we dont't want to
1801 // allow the regular ones and vice versa.
1804 if (!ptr
->srs
.AnonData
)
1806 LogMsg("CheckForMixedRegistrations: Normal registration already exists for %##s", regtype
->c
);
1812 // Allow multiple regular registrations
1813 if (ptr
->srs
.AnonData
)
1815 LogMsg("CheckForMixedRegistrations: Anonymous registration already exists for %##s", regtype
->c
);
1824 // Returns true if the interfaceIndex value matches one of the pre-defined
1825 // special values listed in the switch statement below.
1826 mDNSlocal mDNSBool
PreDefinedInterfaceIndex(mDNSu32 interfaceIndex
)
1828 switch(interfaceIndex
)
1830 case kDNSServiceInterfaceIndexAny
:
1831 case kDNSServiceInterfaceIndexLocalOnly
:
1832 case kDNSServiceInterfaceIndexUnicast
:
1833 case kDNSServiceInterfaceIndexP2P
:
1834 case kDNSServiceInterfaceIndexBLE
:
1841 mDNSlocal mStatus
handle_regservice_request(request_state
*request
)
1843 char name
[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1844 char domain
[MAX_ESCAPED_DOMAIN_NAME
], host
[MAX_ESCAPED_DOMAIN_NAME
];
1845 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
];
1848 char *AnonData
= mDNSNULL
;
1849 const char *msgTXTData
;
1851 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
1852 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
1853 mDNSInterfaceID InterfaceID
;
1855 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
1856 // kDNSServiceFlagsIncludeP2P flag set.
1857 if (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)
1859 LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
1860 flags
|= kDNSServiceFlagsIncludeP2P
;
1861 interfaceIndex
= kDNSServiceInterfaceIndexAny
;
1864 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
1866 // The registration is scoped to a specific interface index, but the
1867 // interface is not currently in our list.
1868 if (interfaceIndex
&& !InterfaceID
)
1870 // If it's one of the specially defined inteface index values, just return an error.
1871 if (PreDefinedInterfaceIndex(interfaceIndex
))
1873 LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex
);
1874 return(mStatus_BadParamErr
);
1877 // Otherwise, use the specified interface index value and the registration will
1878 // be applied to that interface when it comes up.
1879 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
1880 LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex
);
1883 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
1884 get_string(&request
->msgptr
, request
->msgend
, type_as_string
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
1885 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
1886 get_string(&request
->msgptr
, request
->msgend
, host
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
1887 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
1889 request
->flags
= flags
;
1890 request
->interfaceIndex
= interfaceIndex
;
1891 request
->u
.servicereg
.InterfaceID
= InterfaceID
;
1892 request
->u
.servicereg
.instances
= NULL
;
1893 request
->u
.servicereg
.txtlen
= 0;
1894 request
->u
.servicereg
.txtdata
= NULL
;
1895 mDNSPlatformStrLCopy(request
->u
.servicereg
.type_as_string
, type_as_string
, sizeof(request
->u
.servicereg
.type_as_string
));
1897 if (request
->msgptr
+ 2 > request
->msgend
) request
->msgptr
= NULL
;
1900 request
->u
.servicereg
.port
.b
[0] = *request
->msgptr
++;
1901 request
->u
.servicereg
.port
.b
[1] = *request
->msgptr
++;
1904 request
->u
.servicereg
.txtlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1905 msgTXTData
= get_rdata(&request
->msgptr
, request
->msgend
, request
->u
.servicereg
.txtlen
);
1907 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1909 if (request
->u
.servicereg
.txtlen
)
1911 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", request
->u
.servicereg
.txtlen
);
1912 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_regservice_request - malloc");
1913 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, msgTXTData
, request
->u
.servicereg
.txtlen
);
1916 // Check for sub-types after the service type
1917 request
->u
.servicereg
.num_subtypes
= ChopSubTypes(request
->u
.servicereg
.type_as_string
, &AnonData
); // Note: Modifies regtype string to remove trailing subtypes
1918 if (request
->u
.servicereg
.num_subtypes
< 0)
1920 LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request
->u
.servicereg
.type_as_string
);
1925 int AnonDataLen
= strlen(AnonData
);
1926 if (AnonDataLen
> MAX_ANONYMOUS_DATA
)
1928 LogMsg("ERROR: handle_regservice_request: AnonDataLen %d", AnonDataLen
);
1931 request
->u
.servicereg
.AnonData
= mDNStrue
;
1935 request
->u
.servicereg
.AnonData
= mDNSfalse
;
1938 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1939 if (!*request
->u
.servicereg
.type_as_string
|| !MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.type
, request
->u
.servicereg
.type_as_string
))
1940 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request
->u
.servicereg
.type_as_string
); goto bad_param
; }
1944 request
->u
.servicereg
.name
= mDNSStorage
.nicelabel
;
1945 request
->u
.servicereg
.autoname
= mDNStrue
;
1949 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1950 if ((flags
& kDNSServiceFlagsNoAutoRename
) == 0)
1952 int newlen
= TruncateUTF8ToLength((mDNSu8
*)name
, mDNSPlatformStrLen(name
), MAX_DOMAIN_LABEL
);
1955 if (!MakeDomainLabelFromLiteralString(&request
->u
.servicereg
.name
, name
))
1956 { LogMsg("ERROR: handle_regservice_request - name bad %s", name
); goto bad_param
; }
1957 request
->u
.servicereg
.autoname
= mDNSfalse
;
1962 request
->u
.servicereg
.default_domain
= mDNSfalse
;
1963 if (!MakeDomainNameFromDNSNameString(&d
, domain
))
1964 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain
); goto bad_param
; }
1968 request
->u
.servicereg
.default_domain
= mDNStrue
;
1969 MakeDomainNameFromDNSNameString(&d
, "local.");
1972 // We don't allow the anonymous and the regular ones to coexist
1973 if (!CheckForMixedRegistrations(&request
->u
.servicereg
.type
, &d
, request
->u
.servicereg
.AnonData
)) { goto bad_param
; }
1975 if (!ConstructServiceName(&srv
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, &d
))
1977 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1978 request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type
.c
, d
.c
); goto bad_param
;
1981 if (!MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.host
, host
))
1982 { LogMsg("ERROR: handle_regservice_request - host bad %s", host
); goto bad_param
; }
1983 request
->u
.servicereg
.autorename
= (flags
& kDNSServiceFlagsNoAutoRename
) == 0;
1984 request
->u
.servicereg
.allowremotequery
= (flags
& kDNSServiceFlagsAllowRemoteQuery
) != 0;
1986 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1987 // a port number of zero. When two instances of the protected client are allowed to run on one
1988 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1989 if (!mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1991 int count
= CountExistingRegistrations(&srv
, request
->u
.servicereg
.port
);
1993 LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request
->process_id
,
1994 request
->pid_name
, count
+1, srv
.c
, mDNSVal16(request
->u
.servicereg
.port
));
1997 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
1998 // Determine if this request should be promoted to use BLE triggered feature.
1999 if (shouldUseBLE(InterfaceID
, 0, &request
->u
.servicereg
.type
, &d
))
2001 request
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2002 LogInfo("handle_regservice_request: registration promoted to use kDNSServiceFlagsAutoTrigger");
2004 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2006 LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START PID[%d](%s)",
2007 request
->sd
, request
->flags
, interfaceIndex
, name
, request
->u
.servicereg
.type_as_string
, domain
, host
,
2008 mDNSVal16(request
->u
.servicereg
.port
), request
->process_id
, request
->pid_name
);
2010 // We need to unconditionally set request->terminate, because even if we didn't successfully
2011 // start any registrations right now, subsequent configuration changes may cause successful
2012 // registrations to be added, and we'll need to cancel them before freeing this memory.
2013 // We also need to set request->terminate first, before adding additional service instances,
2014 // because the uds_validatelists uses the request->terminate function pointer to determine
2015 // what kind of request this is, and therefore what kind of list validation is required.
2016 request
->terminate
= regservice_termination_callback
;
2018 err
= register_service_instance(request
, &d
);
2020 #if TARGET_OS_EMBEDDED
2021 ++curr_num_regservices
;
2022 if (curr_num_regservices
> max_num_regservices
)
2023 max_num_regservices
= curr_num_regservices
;
2027 err
= AuthorizedDomain(request
, &d
, AutoRegistrationDomains
) ? register_service_instance(request
, &d
) : mStatus_NoError
;
2031 if (request
->u
.servicereg
.autoname
) UpdateDeviceInfoRecord(&mDNSStorage
);
2036 // Note that we don't report errors for non-local, non-explicit domains
2037 for (ptr
= AutoRegistrationDomains
; ptr
; ptr
= ptr
->next
)
2038 if (!ptr
->uid
|| SystemUID(request
->uid
) || request
->uid
== ptr
->uid
)
2039 register_service_instance(request
, &ptr
->name
);
2046 freeL("handle_regservice_request (txtdata)", request
->u
.servicereg
.txtdata
);
2047 request
->u
.servicereg
.txtdata
= NULL
;
2048 return mStatus_BadParamErr
;
2051 // ***************************************************************************
2052 #if COMPILER_LIKES_PRAGMA_MARK
2054 #pragma mark - DNSServiceBrowse
2057 mDNSlocal
void FoundInstance(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2059 DNSServiceFlags flags
= AddRecord
? kDNSServiceFlagsAdd
: 0;
2060 request_state
*req
= question
->QuestionContext
;
2064 if (answer
->rrtype
!= kDNSType_PTR
)
2065 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req
->sd
, answer
->rrtype
); return; }
2067 if (mDNSOpaque16IsZero(question
->TargetQID
) && (question
->BrowseThreshold
> 0) && (question
->CurrentAnswers
>= question
->BrowseThreshold
))
2069 flags
|= kDNSServiceFlagsThresholdReached
;
2072 // if returning a negative answer, then use question's name in reply
2073 if (answer
->RecordType
== kDNSRecordTypePacketNegative
)
2075 GenerateBrowseReply(&question
->qname
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, kDNSServiceErr_NoSuchRecord
);
2079 if (GenerateNTDResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
) != mStatus_NoError
)
2081 if (SameDomainName(&req
->u
.browser
.regtype
, (const domainname
*)"\x09_services\x07_dns-sd\x04_udp"))
2083 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2084 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2085 GenerateBrowseReply(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
);
2089 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2090 req
->sd
, answer
->name
->c
, answer
->rdata
->u
.name
.c
);
2096 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s interface %d: %s",
2097 req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "ADD" : "RMV",
2098 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
), RRDisplayString(m
, answer
));
2100 append_reply(req
, rep
);
2103 mDNSlocal
void SetQuestionPolicy(DNSQuestion
*q
, request_state
*req
)
2106 // The policy is either based on pid or UUID. Pass a zero pid
2107 // to the "core" if the UUID is valid. If we always pass the pid,
2108 // then the "core" needs to determine whether the uuid is valid
2109 // by examining all the 16 bytes at the time of the policy
2110 // check and also when setting the delegate socket option. Also, it
2111 // requires that we zero out the uuid wherever the question is
2112 // initialized to make sure that it is not interpreted as valid.
2113 // To prevent these intrusive changes, just pass a zero pid to indicate
2114 // that pid is not valid when uuid is valid. In future if we need the
2115 // pid in the question, we will reevaluate this strategy.
2118 mDNSPlatformMemCopy(q
->uuid
, req
->uuid
, UUID_SIZE
);
2123 q
->pid
= req
->process_id
;
2126 //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
2129 mDNSlocal mStatus
add_domain_to_browser(request_state
*info
, const domainname
*d
)
2134 for (p
= info
->u
.browser
.browsers
; p
; p
= p
->next
)
2136 if (SameDomainName(&p
->domain
, d
))
2137 { debugf("add_domain_to_browser %##s already in list", d
->c
); return mStatus_AlreadyRegistered
; }
2140 b
= mallocL("browser_t", sizeof(*b
));
2141 if (!b
) return mStatus_NoMemoryErr
;
2142 mDNSPlatformMemZero(b
, sizeof(*b
));
2143 AssignDomainName(&b
->domain
, d
);
2144 SetQuestionPolicy(&b
->q
, info
);
2145 err
= mDNS_StartBrowse(&mDNSStorage
, &b
->q
, &info
->u
.browser
.regtype
, d
, info
->u
.browser
.AnonData
, info
->u
.browser
.interface_id
, info
->flags
,
2146 info
->u
.browser
.ForceMCast
, (info
->flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0, FoundInstance
, info
);
2149 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err
, info
->u
.browser
.regtype
.c
, d
->c
);
2150 freeL("browser_t/add_domain_to_browser", b
);
2154 b
->next
= info
->u
.browser
.browsers
;
2155 info
->u
.browser
.browsers
= b
;
2157 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2158 // Determine if this request should be promoted to use BLE triggered discovery.
2159 if (shouldUseBLE(info
->u
.browser
.interface_id
, 0, &info
->u
.browser
.regtype
, (domainname
*) d
))
2161 info
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2162 b
->q
.flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2163 LogInfo("add_domain_to_browser: request promoted to use kDNSServiceFlagsAutoTrigger");
2165 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2167 LogMcastQ(&b
->q
, info
, q_start
);
2168 if (callExternalHelpers(info
->u
.browser
.interface_id
, &b
->domain
, info
->flags
))
2171 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &b
->domain
);
2172 LogDebug("add_domain_to_browser: calling external_start_browsing_for_service()");
2173 external_start_browsing_for_service(info
->u
.browser
.interface_id
, &tmp
, kDNSType_PTR
, info
->flags
);
2179 mDNSlocal
void browse_termination_callback(request_state
*info
)
2181 if (info
->u
.browser
.default_domain
)
2183 // Stop the domain enumeration queries to discover the WAB legacy browse domains
2184 LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info
->sd
, info
->process_id
, info
->pid_name
);
2185 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_LBROWSE_QUERY
);
2187 if (info
->u
.browser
.AnonData
)
2188 freeL("Anonymous", (void *)info
->u
.browser
.AnonData
);
2189 while (info
->u
.browser
.browsers
)
2191 browser_t
*ptr
= info
->u
.browser
.browsers
;
2193 if (callExternalHelpers(ptr
->q
.InterfaceID
, &ptr
->domain
, ptr
->q
.flags
))
2196 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &ptr
->domain
);
2197 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2198 external_stop_browsing_for_service(ptr
->q
.InterfaceID
, &tmp
, kDNSType_PTR
, ptr
->q
.flags
);
2201 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\") STOP PID[%d](%s)",
2202 info
->sd
, info
->flags
, info
->interfaceIndex
, ptr
->q
.qname
.c
, info
->process_id
, info
->pid_name
);
2204 info
->u
.browser
.browsers
= ptr
->next
;
2205 mDNS_StopBrowse(&mDNSStorage
, &ptr
->q
); // no need to error-check result
2206 LogMcastQ(&ptr
->q
, info
, q_stop
);
2207 freeL("browser_t/browse_termination_callback", ptr
);
2211 mDNSlocal
void udsserver_automatic_browse_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
2213 request_state
*request
;
2214 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
2216 for (request
= all_requests
; request
; request
= request
->next
)
2218 if (request
->terminate
!= browse_termination_callback
) continue; // Not a browse operation
2219 if (!request
->u
.browser
.default_domain
) continue; // Not an auto-browse operation
2220 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
2222 browser_t
**ptr
= &request
->u
.browser
.browsers
;
2223 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
2226 // If we don't already have this domain in our list for this browse operation, add it now
2227 if (!*ptr
) add_domain_to_browser(request
, &d
->name
);
2228 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d
->name
);
2232 if (!*ptr
) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d
->name
);
2236 for (p
= AutoBrowseDomains
; p
; p
=p
->next
)
2237 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
2238 if (SameDomainName(&d
->name
, &p
->name
)) break;
2239 if (p
) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d
->name
);
2242 browser_t
*rem
= *ptr
;
2243 *ptr
= (*ptr
)->next
;
2244 mDNS_StopQueryWithRemoves(&mDNSStorage
, &rem
->q
);
2245 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem
);
2253 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
2256 if (result
== mStatus_MemFree
)
2258 // On shutdown, mDNS_Close automatically deregisters all records
2259 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2260 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2261 // (This should actually no longer be necessary, now that we do the proper cleanup in
2262 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2263 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2264 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2265 while (*ptr
&& &(*ptr
)->ar
!= rr
) ptr
= &(*ptr
)->next
;
2266 if (*ptr
) { *ptr
= (*ptr
)->next
; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m
, rr
)); }
2267 mDNSPlatformMemFree(rr
->RecordContext
);
2271 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2272 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2273 // We may want to turn the common code into a subroutine.
2275 mDNSlocal
void RegisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2277 // allocate/register legacy and non-legacy _browse PTR record
2279 ARListElem
*ptr
= mDNSPlatformMemAllocate(sizeof(*ptr
));
2281 debugf("Incrementing %s refcount for %##s",
2282 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2283 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2284 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2286 mDNS_SetupResourceRecord(&ptr
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, AuthRecordLocalOnly
, FreeARElemCallback
, ptr
);
2287 MakeDomainNameFromDNSNameString(&ptr
->ar
.namestorage
, mDNS_DomainTypeNames
[type
]);
2288 AppendDNSNameString (&ptr
->ar
.namestorage
, "local");
2289 AssignDomainName(&ptr
->ar
.resrec
.rdata
->u
.name
, d
);
2290 err
= mDNS_Register(m
, &ptr
->ar
);
2293 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err
);
2294 mDNSPlatformMemFree(ptr
);
2298 ptr
->next
= LocalDomainEnumRecords
;
2299 LocalDomainEnumRecords
= ptr
;
2303 mDNSlocal
void DeregisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2305 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2306 domainname lhs
; // left-hand side of PTR, for comparison
2308 debugf("Decrementing %s refcount for %##s",
2309 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2310 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2311 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2313 MakeDomainNameFromDNSNameString(&lhs
, mDNS_DomainTypeNames
[type
]);
2314 AppendDNSNameString (&lhs
, "local");
2318 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, d
) && SameDomainName((*ptr
)->ar
.resrec
.name
, &lhs
))
2320 ARListElem
*rem
= *ptr
;
2321 *ptr
= (*ptr
)->next
;
2322 mDNS_Deregister(m
, &rem
->ar
);
2325 else ptr
= &(*ptr
)->next
;
2329 mDNSlocal
void AddAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2331 DNameListElem
*new = mDNSPlatformMemAllocate(sizeof(DNameListElem
));
2332 if (!new) { LogMsg("ERROR: malloc"); return; }
2333 AssignDomainName(&new->name
, name
);
2335 new->next
= AutoBrowseDomains
;
2336 AutoBrowseDomains
= new;
2337 udsserver_automatic_browse_domain_changed(new, mDNStrue
);
2340 mDNSlocal
void RmvAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2342 DNameListElem
**p
= &AutoBrowseDomains
;
2343 while (*p
&& (!SameDomainName(&(*p
)->name
, name
) || (*p
)->uid
!= uid
)) p
= &(*p
)->next
;
2344 if (!*p
) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name
->c
);
2347 DNameListElem
*ptr
= *p
;
2349 udsserver_automatic_browse_domain_changed(ptr
, mDNSfalse
);
2350 mDNSPlatformMemFree(ptr
);
2354 mDNSlocal
void SetPrefsBrowseDomains(mDNS
*m
, DNameListElem
*browseDomains
, mDNSBool add
)
2357 for (d
= browseDomains
; d
; d
= d
->next
)
2361 RegisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2362 AddAutoBrowseDomain(d
->uid
, &d
->name
);
2366 DeregisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2367 RmvAutoBrowseDomain(d
->uid
, &d
->name
);
2372 #if APPLE_OSX_mDNSResponder
2374 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
2376 int num_autoname
= 0;
2379 // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2380 for (req
= all_requests
; req
; req
= req
->next
)
2382 if (req
->terminate
== regservice_termination_callback
&& req
->u
.servicereg
.autoname
&& req
->interfaceIndex
!= kDNSServiceInterfaceIndexLocalOnly
)
2386 // If DeviceInfo record is currently registered, see if we need to deregister it
2387 if (m
->DeviceInfo
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
)
2388 if (num_autoname
== 0 || !SameDomainLabelCS(m
->DeviceInfo
.resrec
.name
->c
, m
->nicelabel
.c
))
2390 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m
->DeviceInfo
.resrec
.name
);
2391 mDNS_Deregister(m
, &m
->DeviceInfo
);
2394 // If DeviceInfo record is not currently registered, see if we need to register it
2395 if (m
->DeviceInfo
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2396 if (num_autoname
> 0)
2398 mDNS_SetupResourceRecord(&m
->DeviceInfo
, mDNSNULL
, mDNSNULL
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeAdvisory
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2399 ConstructServiceName(&m
->DeviceInfo
.namestorage
, &m
->nicelabel
, &DeviceInfoName
, &localdomain
);
2400 m
->DeviceInfo
.resrec
.rdlength
= initializeDeviceInfoTXT(m
, m
->DeviceInfo
.resrec
.rdata
->u
.data
);
2401 LogOperation("UpdateDeviceInfoRecord Register %##s", m
->DeviceInfo
.resrec
.name
);
2402 mDNS_Register(m
, &m
->DeviceInfo
);
2405 #else // APPLE_OSX_mDNSResponder
2406 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
2410 #endif // APPLE_OSX_mDNSResponder
2412 mDNSexport
void udsserver_handle_configchange(mDNS
*const m
)
2415 service_instance
*ptr
;
2416 DNameListElem
*RegDomains
= NULL
;
2417 DNameListElem
*BrowseDomains
= NULL
;
2420 UpdateDeviceInfoRecord(m
);
2422 // For autoname services, see if the default service name has changed, necessitating an automatic update
2423 for (req
= all_requests
; req
; req
= req
->next
)
2424 if (req
->terminate
== regservice_termination_callback
)
2425 if (req
->u
.servicereg
.autoname
&& !SameDomainLabelCS(req
->u
.servicereg
.name
.c
, m
->nicelabel
.c
))
2427 req
->u
.servicereg
.name
= m
->nicelabel
;
2428 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
2430 ptr
->renameonmemfree
= 1;
2431 if (ptr
->clientnotified
) SendServiceRemovalNotification(&ptr
->srs
);
2432 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr
->srs
.RR_PTR
.resrec
.name
->c
);
2433 if (mDNS_DeregisterService_drt(m
, &ptr
->srs
, mDNS_Dereg_rapid
))
2434 regservice_callback(m
, &ptr
->srs
, mStatus_MemFree
); // If service deregistered already, we can re-register immediately
2438 // Let the platform layer get the current DNS information
2440 mDNSPlatformSetDNSConfig(mDNSfalse
, mDNSfalse
, mDNSNULL
, &RegDomains
, &BrowseDomains
, mDNSfalse
);
2443 // Any automatic registration domains are also implicitly automatic browsing domains
2444 if (RegDomains
) SetPrefsBrowseDomains(m
, RegDomains
, mDNStrue
); // Add the new list first
2445 if (AutoRegistrationDomains
) SetPrefsBrowseDomains(m
, AutoRegistrationDomains
, mDNSfalse
); // Then clear the old list
2447 // Add any new domains not already in our AutoRegistrationDomains list
2448 for (p
=RegDomains
; p
; p
=p
->next
)
2450 DNameListElem
**pp
= &AutoRegistrationDomains
;
2451 while (*pp
&& ((*pp
)->uid
!= p
->uid
|| !SameDomainName(&(*pp
)->name
, &p
->name
))) pp
= &(*pp
)->next
;
2452 if (!*pp
) // If not found in our existing list, this is a new default registration domain
2454 RegisterLocalOnlyDomainEnumPTR(m
, &p
->name
, mDNS_DomainTypeRegistration
);
2455 udsserver_default_reg_domain_changed(p
, mDNStrue
);
2457 else // else found same domainname in both old and new lists, so no change, just delete old copy
2459 DNameListElem
*del
= *pp
;
2461 mDNSPlatformMemFree(del
);
2465 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2466 while (AutoRegistrationDomains
)
2468 DNameListElem
*del
= AutoRegistrationDomains
;
2469 AutoRegistrationDomains
= AutoRegistrationDomains
->next
; // Cut record from list FIRST,
2470 DeregisterLocalOnlyDomainEnumPTR(m
, &del
->name
, mDNS_DomainTypeRegistration
);
2471 udsserver_default_reg_domain_changed(del
, mDNSfalse
); // before calling udsserver_default_reg_domain_changed()
2472 mDNSPlatformMemFree(del
);
2475 // Now we have our new updated automatic registration domain list
2476 AutoRegistrationDomains
= RegDomains
;
2478 // Add new browse domains to internal list
2479 if (BrowseDomains
) SetPrefsBrowseDomains(m
, BrowseDomains
, mDNStrue
);
2481 // Remove old browse domains from internal list
2482 if (SCPrefBrowseDomains
)
2484 SetPrefsBrowseDomains(m
, SCPrefBrowseDomains
, mDNSfalse
);
2485 while (SCPrefBrowseDomains
)
2487 DNameListElem
*fptr
= SCPrefBrowseDomains
;
2488 SCPrefBrowseDomains
= SCPrefBrowseDomains
->next
;
2489 mDNSPlatformMemFree(fptr
);
2493 // Replace the old browse domains array with the new array
2494 SCPrefBrowseDomains
= BrowseDomains
;
2497 mDNSlocal
void AutomaticBrowseDomainChange(mDNS
*const m
, DNSQuestion
*q
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2502 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2503 AddRecord
? "Adding" : "Removing", answer
->rdata
->u
.name
.c
);
2505 if (AddRecord
) AddAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2506 else RmvAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2509 mDNSlocal mStatus
handle_browse_request(request_state
*request
)
2511 char regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2512 domainname typedn
, d
, temp
;
2513 mDNSs32 NumSubTypes
;
2514 char *AnonData
= mDNSNULL
;
2515 mStatus err
= mStatus_NoError
;
2518 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2519 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2520 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2522 // The browse is scoped to a specific interface index, but the
2523 // interface is not currently in our list.
2524 if (interfaceIndex
&& !InterfaceID
)
2526 // If it's one of the specially defined inteface index values, just return an error.
2527 if (PreDefinedInterfaceIndex(interfaceIndex
))
2529 LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex
);
2530 return(mStatus_BadParamErr
);
2533 // Otherwise, use the specified interface index value and the browse will
2534 // be applied to that interface when it comes up.
2535 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
2536 LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex
);
2539 if (get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2540 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0) return(mStatus_BadParamErr
);
2542 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2544 request
->flags
= flags
;
2545 request
->interfaceIndex
= interfaceIndex
;
2547 NumSubTypes
= ChopSubTypes(regtype
, &AnonData
); // Note: Modifies regtype string to remove trailing subtypes
2548 if (NumSubTypes
< 0 || NumSubTypes
> 1)
2549 return(mStatus_BadParamErr
);
2553 AnonDataLen
= strlen(AnonData
);
2554 if (AnonDataLen
> MAX_ANONYMOUS_DATA
)
2556 LogMsg("handle_browse_request: AnonDataLen %d", AnonDataLen
);
2557 return(mStatus_BadParamErr
);
2559 // Account for the null byte
2562 if (NumSubTypes
== 1)
2564 if (!AppendDNSNameString(&typedn
, regtype
+ strlen(regtype
) + 1 + AnonDataLen
))
2565 return(mStatus_BadParamErr
);
2568 if (!regtype
[0] || !AppendDNSNameString(&typedn
, regtype
)) return(mStatus_BadParamErr
);
2570 if (!MakeDomainNameFromDNSNameString(&temp
, regtype
)) return(mStatus_BadParamErr
);
2571 // For over-long service types, we only allow domain "local"
2572 if (temp
.c
[0] > 15 && domain
[0] == 0) mDNSPlatformStrLCopy(domain
, "local.", sizeof(domain
));
2574 // Set up browser info
2575 request
->u
.browser
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2576 request
->u
.browser
.interface_id
= InterfaceID
;
2577 AssignDomainName(&request
->u
.browser
.regtype
, &typedn
);
2578 request
->u
.browser
.default_domain
= !domain
[0];
2579 request
->u
.browser
.browsers
= NULL
;
2581 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START PID[%d](%s)",
2582 request
->sd
, request
->flags
, interfaceIndex
, request
->u
.browser
.regtype
.c
, domain
, request
->process_id
, request
->pid_name
);
2584 if (request
->u
.browser
.default_domain
)
2586 // Start the domain enumeration queries to discover the WAB browse domains
2587 LogInfo("%3d: DNSServiceBrowse Start WAB PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
2588 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_LBROWSE_QUERY
);
2590 request
->u
.browser
.AnonData
= mDNSNULL
;
2593 int len
= strlen(AnonData
) + 1;
2594 request
->u
.browser
.AnonData
= mallocL("Anonymous", len
);
2595 if (!request
->u
.browser
.AnonData
)
2596 return mStatus_NoMemoryErr
;
2598 mDNSPlatformMemCopy((void *)request
->u
.browser
.AnonData
, AnonData
, len
);
2600 // We need to unconditionally set request->terminate, because even if we didn't successfully
2601 // start any browses right now, subsequent configuration changes may cause successful
2602 // browses to be added, and we'll need to cancel them before freeing this memory.
2603 request
->terminate
= browse_termination_callback
;
2607 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return(mStatus_BadParamErr
);
2608 err
= add_domain_to_browser(request
, &d
);
2612 DNameListElem
*sdom
;
2613 for (sdom
= AutoBrowseDomains
; sdom
; sdom
= sdom
->next
)
2614 if (!sdom
->uid
|| SystemUID(request
->uid
) || request
->uid
== sdom
->uid
)
2616 err
= add_domain_to_browser(request
, &sdom
->name
);
2619 if (SameDomainName(&sdom
->name
, &localdomain
)) break;
2620 else err
= mStatus_NoError
; // suppress errors for non-local "default" domains
2628 // ***************************************************************************
2629 #if COMPILER_LIKES_PRAGMA_MARK
2631 #pragma mark - DNSServiceResolve
2634 mDNSlocal
void resolve_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2637 char fullname
[MAX_ESCAPED_DOMAIN_NAME
], target
[MAX_ESCAPED_DOMAIN_NAME
] = "0";
2640 request_state
*req
= question
->QuestionContext
;
2641 const DNSServiceErrorType error
=
2642 (answer
->RecordType
== kDNSRecordTypePacketNegative
) ? kDNSServiceErr_NoSuchRecord
: kDNSServiceErr_NoError
;
2645 LogOperation("%3d: DNSServiceResolve(%##s) %s interface %d: %s",
2646 req
->sd
, question
->qname
.c
, AddRecord
? "ADD" : "RMV",
2647 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
), RRDisplayString(m
, answer
));
2651 if (req
->u
.resolve
.srv
== answer
) req
->u
.resolve
.srv
= mDNSNULL
;
2652 if (req
->u
.resolve
.txt
== answer
) req
->u
.resolve
.txt
= mDNSNULL
;
2656 if (answer
->rrtype
== kDNSType_SRV
) req
->u
.resolve
.srv
= answer
;
2657 if (answer
->rrtype
== kDNSType_TXT
) req
->u
.resolve
.txt
= answer
;
2659 if (!req
->u
.resolve
.txt
|| !req
->u
.resolve
.srv
) return; // only deliver result to client if we have both answers
2661 ConvertDomainNameToCString(answer
->name
, fullname
);
2663 if (answer
->RecordType
!= kDNSRecordTypePacketNegative
)
2664 ConvertDomainNameToCString(&req
->u
.resolve
.srv
->rdata
->u
.srv
.target
, target
);
2666 // calculate reply length
2667 len
+= sizeof(DNSServiceFlags
);
2668 len
+= sizeof(mDNSu32
); // interface index
2669 len
+= sizeof(DNSServiceErrorType
);
2670 len
+= strlen(fullname
) + 1;
2671 len
+= strlen(target
) + 1;
2672 len
+= 2 * sizeof(mDNSu16
); // port, txtLen
2673 len
+= req
->u
.resolve
.txt
->rdlength
;
2675 // allocate/init reply header
2676 rep
= create_reply(resolve_reply_op
, len
, req
);
2677 rep
->rhdr
->flags
= dnssd_htonl(0);
2678 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
));
2679 rep
->rhdr
->error
= dnssd_htonl(error
);
2681 data
= (char *)&rep
->rhdr
[1];
2683 // write reply data to message
2684 put_string(fullname
, &data
);
2685 put_string(target
, &data
);
2686 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[0];
2687 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[1];
2688 put_uint16(req
->u
.resolve
.txt
->rdlength
, &data
);
2689 put_rdata (req
->u
.resolve
.txt
->rdlength
, req
->u
.resolve
.txt
->rdata
->u
.data
, &data
);
2691 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req
->sd
, fullname
, target
, mDNSVal16(req
->u
.resolve
.srv
->rdata
->u
.srv
.port
));
2692 append_reply(req
, rep
);
2695 mDNSlocal
void resolve_termination_callback(request_state
*request
)
2697 LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") STOP PID[%d](%s)",
2698 request
->sd
, request
->flags
, request
->interfaceIndex
, request
->u
.resolve
.qtxt
.qname
.c
, request
->process_id
, request
->pid_name
);
2699 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2700 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2701 LogMcastQ(&request
->u
.resolve
.qsrv
, request
, q_stop
);
2702 if (request
->u
.resolve
.external_advertise
)
2703 external_stop_resolving_service(request
->u
.resolve
.qsrv
.InterfaceID
, &request
->u
.resolve
.qsrv
.qname
, request
->flags
);
2706 mDNSlocal mStatus
handle_resolve_request(request_state
*request
)
2708 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2712 // extract the data from the message
2713 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2714 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2715 mDNSInterfaceID InterfaceID
;
2717 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2718 // flag set so that the resolve will run over P2P interfaces that are not yet created.
2719 if (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)
2721 LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2722 flags
|= kDNSServiceFlagsIncludeP2P
;
2723 interfaceIndex
= kDNSServiceInterfaceIndexAny
;
2726 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2728 // The operation is scoped to a specific interface index, but the
2729 // interface is not currently in our list.
2730 if (interfaceIndex
&& !InterfaceID
)
2732 // If it's one of the specially defined inteface index values, just return an error.
2733 if (PreDefinedInterfaceIndex(interfaceIndex
))
2735 LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex
);
2736 return(mStatus_BadParamErr
);
2739 // Otherwise, use the specified interface index value and the operation will
2740 // be applied to that interface when it comes up.
2741 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
2742 LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex
);
2745 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0 ||
2746 get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2747 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
2748 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
2750 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2752 if (build_domainname_from_strings(&fqdn
, name
, regtype
, domain
) < 0)
2753 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name
, regtype
, domain
); return(mStatus_BadParamErr
); }
2755 mDNSPlatformMemZero(&request
->u
.resolve
, sizeof(request
->u
.resolve
));
2757 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2758 // Determine if this request should be promoted to use BLE triggered discovery.
2759 if (shouldUseBLE(InterfaceID
, 0, (domainname
*)SkipLeadingLabels(&fqdn
, 1), &fqdn
))
2761 flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2762 LogInfo("handle_resolve_request: request promoted to use kDNSServiceFlagsAutoTrigger");
2764 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2766 request
->flags
= flags
;
2767 request
->interfaceIndex
= interfaceIndex
;
2770 request
->u
.resolve
.qsrv
.InterfaceID
= InterfaceID
;
2771 request
->u
.resolve
.qsrv
.flags
= flags
;
2772 request
->u
.resolve
.qsrv
.Target
= zeroAddr
;
2773 AssignDomainName(&request
->u
.resolve
.qsrv
.qname
, &fqdn
);
2774 request
->u
.resolve
.qsrv
.qtype
= kDNSType_SRV
;
2775 request
->u
.resolve
.qsrv
.qclass
= kDNSClass_IN
;
2776 request
->u
.resolve
.qsrv
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2777 request
->u
.resolve
.qsrv
.ExpectUnique
= mDNStrue
;
2778 request
->u
.resolve
.qsrv
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2779 request
->u
.resolve
.qsrv
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2780 request
->u
.resolve
.qsrv
.SuppressUnusable
= mDNSfalse
;
2781 request
->u
.resolve
.qsrv
.SearchListIndex
= 0;
2782 request
->u
.resolve
.qsrv
.AppendSearchDomains
= 0;
2783 request
->u
.resolve
.qsrv
.RetryWithSearchDomains
= mDNSfalse
;
2784 request
->u
.resolve
.qsrv
.TimeoutQuestion
= 0;
2785 request
->u
.resolve
.qsrv
.WakeOnResolve
= (flags
& kDNSServiceFlagsWakeOnResolve
) != 0;
2786 request
->u
.resolve
.qsrv
.UseBackgroundTrafficClass
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
2787 request
->u
.resolve
.qsrv
.ValidationRequired
= 0;
2788 request
->u
.resolve
.qsrv
.ValidatingResponse
= 0;
2789 request
->u
.resolve
.qsrv
.ProxyQuestion
= 0;
2790 request
->u
.resolve
.qsrv
.qnameOrig
= mDNSNULL
;
2791 request
->u
.resolve
.qsrv
.AnonInfo
= mDNSNULL
;
2792 request
->u
.resolve
.qsrv
.pid
= request
->process_id
;
2793 request
->u
.resolve
.qsrv
.euid
= request
->uid
;
2794 request
->u
.resolve
.qsrv
.QuestionCallback
= resolve_result_callback
;
2795 request
->u
.resolve
.qsrv
.QuestionContext
= request
;
2797 request
->u
.resolve
.qtxt
.InterfaceID
= InterfaceID
;
2798 request
->u
.resolve
.qtxt
.flags
= flags
;
2799 request
->u
.resolve
.qtxt
.Target
= zeroAddr
;
2800 AssignDomainName(&request
->u
.resolve
.qtxt
.qname
, &fqdn
);
2801 request
->u
.resolve
.qtxt
.qtype
= kDNSType_TXT
;
2802 request
->u
.resolve
.qtxt
.qclass
= kDNSClass_IN
;
2803 request
->u
.resolve
.qtxt
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2804 request
->u
.resolve
.qtxt
.ExpectUnique
= mDNStrue
;
2805 request
->u
.resolve
.qtxt
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2806 request
->u
.resolve
.qtxt
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2807 request
->u
.resolve
.qtxt
.SuppressUnusable
= mDNSfalse
;
2808 request
->u
.resolve
.qtxt
.SearchListIndex
= 0;
2809 request
->u
.resolve
.qtxt
.AppendSearchDomains
= 0;
2810 request
->u
.resolve
.qtxt
.RetryWithSearchDomains
= mDNSfalse
;
2811 request
->u
.resolve
.qtxt
.TimeoutQuestion
= 0;
2812 request
->u
.resolve
.qtxt
.WakeOnResolve
= 0;
2813 request
->u
.resolve
.qtxt
.UseBackgroundTrafficClass
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
2814 request
->u
.resolve
.qtxt
.ValidationRequired
= 0;
2815 request
->u
.resolve
.qtxt
.ValidatingResponse
= 0;
2816 request
->u
.resolve
.qtxt
.ProxyQuestion
= 0;
2817 request
->u
.resolve
.qtxt
.qnameOrig
= mDNSNULL
;
2818 request
->u
.resolve
.qtxt
.AnonInfo
= mDNSNULL
;
2819 request
->u
.resolve
.qtxt
.pid
= request
->process_id
;
2820 request
->u
.resolve
.qtxt
.euid
= request
->uid
;
2821 request
->u
.resolve
.qtxt
.QuestionCallback
= resolve_result_callback
;
2822 request
->u
.resolve
.qtxt
.QuestionContext
= request
;
2824 request
->u
.resolve
.ReportTime
= NonZeroTime(mDNS_TimeNow(&mDNSStorage
) + 130 * mDNSPlatformOneSecond
);
2826 request
->u
.resolve
.external_advertise
= mDNSfalse
;
2829 if (!AuthorizedDomain(request
, &fqdn
, AutoBrowseDomains
)) return(mStatus_NoError
);
2832 // ask the questions
2833 LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") START PID[%d](%s)", request
->sd
, flags
, interfaceIndex
,
2834 request
->u
.resolve
.qsrv
.qname
.c
, request
->process_id
, request
->pid_name
);
2836 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2840 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2843 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2847 request
->terminate
= resolve_termination_callback
;
2848 LogMcastQ(&request
->u
.resolve
.qsrv
, request
, q_start
);
2849 if (callExternalHelpers(InterfaceID
, &fqdn
, flags
))
2851 request
->u
.resolve
.external_advertise
= mDNStrue
;
2852 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2853 external_start_resolving_service(InterfaceID
, &fqdn
, flags
);
2861 // ***************************************************************************
2862 #if COMPILER_LIKES_PRAGMA_MARK
2864 #pragma mark - DNSServiceQueryRecord
2867 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2868 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2869 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2870 // the mDNSCore operation if the client dies or closes its socket.
2872 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2873 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2874 // Returns 0 when there are no more search domains and the caller should reissue the query
2875 mDNSlocal
int AppendNewSearchDomain(DNSQuestion
*question
)
2880 // Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2881 // the domains and should try the single label query directly on the wire.
2882 if (question
->SearchListIndex
== -1)
2884 LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question
->qname
.c
, DNSTypeName(question
->qtype
));
2888 if (!question
->AppendSearchDomains
)
2890 LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question
->qname
.c
, DNSTypeName(question
->qtype
));
2894 // Save the original name, before we modify them below.
2895 if (!question
->qnameOrig
)
2897 question
->qnameOrig
= mallocL("AppendNewSearchDomain", sizeof(domainname
));
2898 if (!question
->qnameOrig
) { LogMsg("AppendNewSearchDomain: ERROR!! malloc failure"); return -1; }
2899 question
->qnameOrig
->c
[0] = 0;
2900 AssignDomainName(question
->qnameOrig
, &question
->qname
);
2901 LogInfo("AppendSearchDomain: qnameOrig %##s", question
->qnameOrig
->c
);
2904 sd
= uDNS_GetNextSearchDomain(question
->InterfaceID
, &question
->SearchListIndex
, !question
->AppendLocalSearchDomains
);
2905 // We use -1 to indicate that we have searched all the domains and should try the single label
2906 // query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2907 if (question
->SearchListIndex
== -1)
2909 LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2913 // Not a common case. Perhaps, we should try the next search domain if it exceeds ?
2914 if (sd
&& (DomainNameLength(question
->qnameOrig
) + DomainNameLength(sd
)) > MAX_DOMAIN_NAME
)
2916 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
));
2920 // if there are no more search domains and we have already tried this question
2921 // without appending search domains, then we are done.
2922 if (!sd
&& !ApplySearchDomainsFirst(question
))
2924 LogInfo("AppendNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question
->qname
.c
, DNSTypeName(question
->qtype
));
2928 // Stop the question before changing the name as negative cache entries could be pointing at this question.
2929 // Even if we don't change the question in the case of returning 0, the caller is going to restart the
2931 err
= mDNS_StopQuery(&mDNSStorage
, question
);
2932 if (err
) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
); }
2934 AssignDomainName(&question
->qname
, question
->qnameOrig
);
2937 AppendDomainName(&question
->qname
, sd
);
2938 LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question
->qname
.c
, question
->SearchListIndex
);
2942 // Try the question as single label
2943 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question
->qname
.c
, DNSTypeName(question
->qtype
));
2947 #if APPLE_OSX_mDNSResponder
2949 mDNSlocal mDNSBool
DomainInSearchList(const domainname
*domain
, mDNSBool excludeLocal
)
2951 const SearchListElem
*s
;
2954 qcount
= CountLabels(domain
);
2955 for (s
=SearchList
; s
; s
=s
->next
)
2957 if (excludeLocal
&& SameDomainName(&s
->domain
, &localdomain
))
2959 scount
= CountLabels(&s
->domain
);
2960 if (qcount
>= scount
)
2962 // Note: When qcount == scount, we do a complete match of the domain
2963 // which is expected by the callers.
2964 const domainname
*d
= SkipLeadingLabels(domain
, (qcount
- scount
));
2965 if (SameDomainName(&s
->domain
, d
))
2974 // The caller already checks that this is a dotlocal question.
2975 mDNSlocal mDNSBool
ShouldDeliverNegativeResponse(DNSQuestion
*question
)
2979 // If the question matches the search domain exactly or the search domain is a
2980 // subdomain of the question, it is most likely a valid unicast domain and hence
2981 // don't suppress negative responses.
2983 // If the user has configured ".local" as a search domain, we don't want
2984 // to deliver a negative response for names ending in ".local" as that would
2985 // prevent bonjour discovery. Passing mDNStrue for the last argument excludes
2986 // ".local" search domains.
2987 if (DomainInSearchList(&question
->qname
, mDNStrue
))
2989 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) in SearchList", question
->qname
.c
, DNSTypeName(question
->qtype
));
2993 // Deliver negative response for A/AAAA if there was a positive response for AAAA/A respectively.
2994 if (question
->qtype
!= kDNSType_A
&& question
->qtype
!= kDNSType_AAAA
)
2996 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) not answering local question with negative unicast response",
2997 question
->qname
.c
, DNSTypeName(question
->qtype
));
3000 qtype
= (question
->qtype
== kDNSType_A
? kDNSType_AAAA
: kDNSType_A
);
3001 if (!mDNS_CheckForCacheRecord(&mDNSStorage
, question
, qtype
))
3003 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) not answering local question with negative unicast response"
3004 " (can't find positive record)", question
->qname
.c
, DNSTypeName(question
->qtype
));
3007 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) answering local with negative unicast response (found positive record)",
3008 question
->qname
.c
, DNSTypeName(question
->qtype
));
3012 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
3014 mDNSlocal mStatus
SendAdditionalQuery(DNSQuestion
*q
, request_state
*request
, mStatus err
)
3016 #ifndef UNICAST_DISABLED
3017 extern domainname ActiveDirectoryPrimaryDomain
;
3018 DNSQuestion
**question2
;
3019 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
3020 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
3022 question2
= mDNSNULL
;
3023 if (request
->hdr
.op
== query_request
)
3024 question2
= &request
->u
.queryrecord
.q2
;
3025 else if (request
->hdr
.op
== addrinfo_request
)
3027 if (q
->qtype
== kDNSType_A
)
3028 question2
= &request
->u
.addrinfo
.q42
;
3029 else if (q
->qtype
== kDNSType_AAAA
)
3030 question2
= &request
->u
.addrinfo
.q62
;
3034 LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
3035 return mStatus_BadParamErr
;
3038 // Sanity check: If we already sent an additonal query, we don't need to send one more.
3040 // 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
3041 // is called to see whether a unicast query should be sent or not.
3043 // 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
3044 // was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
3045 // send the additional query.
3047 // Thus, it should not be called more than once.
3050 LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q
->qname
.c
, DNSTypeName(q
->qtype
));
3054 if (!q
->ForceMCast
&& SameDomainLabel(LastLabel(&q
->qname
), (const mDNSu8
*)&localdomain
))
3055 if (q
->qtype
== kDNSType_A
|| q
->qtype
== kDNSType_AAAA
|| VALID_MSAD_SRV(q
))
3058 int labels
= CountLabels(&q
->qname
);
3059 q2
= mallocL("DNSQuestion", sizeof(DNSQuestion
));
3060 if (!q2
) FatalError("ERROR: SendAdditionalQuery malloc");
3063 q2
->InterfaceID
= mDNSInterface_Unicast
;
3064 q2
->ExpectUnique
= mDNStrue
;
3065 // Always set the QuestionContext to indicate that this question should be stopped
3066 // before freeing. Don't rely on "q".
3067 q2
->QuestionContext
= request
;
3068 // If the query starts as a single label e.g., somehost, and we have search domains with .local,
3069 // queryrecord_result_callback calls this function when .local is appended to "somehost".
3070 // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
3071 // "somehost". We need to copy that information so that when we retry with a different search
3072 // domain e.g., mycompany.local, we get "somehost.mycompany.local".
3075 (*question2
)->qnameOrig
= mallocL("SendAdditionalQuery", DomainNameLength(q
->qnameOrig
));
3076 if (!(*question2
)->qnameOrig
) { LogMsg("SendAdditionalQuery: ERROR!! malloc failure"); return mStatus_NoMemoryErr
; }
3077 (*question2
)->qnameOrig
->c
[0] = 0;
3078 AssignDomainName((*question2
)->qnameOrig
, q
->qnameOrig
);
3079 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2
)->qnameOrig
->c
);
3081 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
3082 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
3083 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
3084 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
3085 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
3086 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
3087 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
3088 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
3089 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
3090 // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
3091 // of those, we don't want do the SOA check for the local
3092 if (labels
== 2 && !SameDomainName(&q
->qname
, &ActiveDirectoryPrimaryDomain
) && !DomainInSearchList(&q
->qname
, mDNSfalse
))
3094 AssignDomainName(&q2
->qname
, &localdomain
);
3095 q2
->qtype
= kDNSType_SOA
;
3096 q2
->LongLived
= mDNSfalse
;
3097 q2
->ForceMCast
= mDNSfalse
;
3098 q2
->ReturnIntermed
= mDNStrue
;
3099 // Don't append search domains for the .local SOA query
3100 q2
->AppendSearchDomains
= 0;
3101 q2
->AppendLocalSearchDomains
= 0;
3102 q2
->RetryWithSearchDomains
= mDNSfalse
;
3103 q2
->SearchListIndex
= 0;
3104 q2
->TimeoutQuestion
= 0;
3105 q2
->AnonInfo
= mDNSNULL
;
3106 q2
->pid
= request
->process_id
;
3107 q2
->euid
= request
->uid
;
3109 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
));
3110 err
= mDNS_StartQuery(&mDNSStorage
, q2
);
3111 if (err
) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
), (int)err
);
3114 #else // !UNICAST_DISABLED
3119 return mStatus_NoError
;
3120 #endif // !UNICAST_DISABLED
3122 #endif // APPLE_OSX_mDNSResponder
3124 // This function tries to append a search domain if valid and possible. If so, returns true.
3125 mDNSlocal mDNSBool
RetryQuestionWithSearchDomains(DNSQuestion
*question
, request_state
*req
, QC_result AddRecord
)
3128 // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
3129 // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
3130 // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
3131 // RetryWithSearchDomains which may or may not be set.
3133 // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
3134 // is a valid question for appending search domains, retry by appending domains
3136 if ((AddRecord
!= QC_suppressed
) && question
->SearchListIndex
!= -1 && question
->AppendSearchDomains
)
3138 question
->RetryWithSearchDomains
= 0;
3139 result
= AppendNewSearchDomain(question
);
3140 // As long as the result is either zero or 1, we retry the question. If we exahaust the search
3141 // domains (result is zero) we try the original query (as it was before appending the search
3142 // domains) as such on the wire as a last resort if we have not tried them before. For queries
3143 // with more than one label, we have already tried them before appending search domains and
3144 // hence don't retry again
3148 err
= mDNS_StartQuery(&mDNSStorage
, question
);
3151 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
));
3152 // If the result was zero, it meant that there are no search domains and we just retried the question
3153 // as a single label and we should not retry with search domains anymore.
3154 if (!result
) question
->SearchListIndex
= -1;
3159 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
);
3160 // We have already stopped the query and could not restart. Reset the appropriate pointers
3161 // so that we don't call stop again when the question terminates
3162 question
->QuestionContext
= mDNSNULL
;
3168 LogDebug("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req
->sd
, AddRecord
, question
->SearchListIndex
, question
->AppendSearchDomains
);
3173 mDNSlocal
void queryrecord_result_reply(mDNS
*const m
, request_state
*req
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
,
3174 DNSServiceErrorType error
)
3176 char name
[MAX_ESCAPED_DOMAIN_NAME
];
3178 DNSServiceFlags flags
= 0;
3182 ConvertDomainNameToCString(answer
->name
, name
);
3184 LogOperation("%3d: %s(%##s, %s) RESULT %s interface %d: (%s)%s", req
->sd
,
3185 req
->hdr
.op
== query_request
? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
3186 question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "ADD" : "RMV",
3187 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
),
3188 MortalityDisplayString(answer
->mortality
), RRDisplayString(m
, answer
));
3190 len
= sizeof(DNSServiceFlags
); // calculate reply data length
3191 len
+= sizeof(mDNSu32
); // interface index
3192 len
+= sizeof(DNSServiceErrorType
);
3193 len
+= strlen(name
) + 1;
3194 len
+= 3 * sizeof(mDNSu16
); // type, class, rdlen
3195 len
+= answer
->rdlength
;
3196 len
+= sizeof(mDNSu32
); // TTL
3198 rep
= create_reply(req
->hdr
.op
== query_request
? query_reply_op
: addrinfo_reply_op
, len
, req
);
3201 flags
|= kDNSServiceFlagsAdd
;
3202 if (answer
->mortality
== Mortality_Ghost
)
3203 flags
|= kDNSServiceFlagsExpiredAnswer
;
3204 if (question
->ValidationStatus
!= 0)
3206 error
= kDNSServiceErr_NoError
;
3207 if (question
->ValidationRequired
&& question
->ValidationState
== DNSSECValDone
)
3209 switch (question
->ValidationStatus
) //Set the dnssec flags to be passed on to the Apps here
3212 flags
|= kDNSServiceFlagsSecure
;
3214 case DNSSEC_Insecure
:
3215 flags
|= kDNSServiceFlagsInsecure
;
3217 case DNSSEC_Indeterminate
:
3218 flags
|= kDNSServiceFlagsIndeterminate
;
3221 flags
|= kDNSServiceFlagsBogus
;
3224 LogMsg("queryrecord_result_reply unknown status %d for %##s", question
->ValidationStatus
, question
->qname
.c
);
3229 rep
->rhdr
->flags
= dnssd_htonl(flags
);
3230 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
3231 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
3232 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
3233 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
3234 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
3235 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
3236 // should not have existed to answer this question if the corresponding interface is not valid.
3237 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNStrue
));
3238 rep
->rhdr
->error
= dnssd_htonl(error
);
3240 data
= (char *)&rep
->rhdr
[1];
3242 put_string(name
, &data
);
3243 put_uint16(answer
->rrtype
, &data
);
3244 put_uint16(answer
->rrclass
, &data
);
3245 put_uint16(answer
->rdlength
, &data
);
3246 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
3247 // function just does a blind memory copy without regard to structures that may have holes in them.
3248 if (answer
->rdlength
)
3249 if (!putRData(mDNSNULL
, (mDNSu8
*)data
, (mDNSu8
*)rep
->rhdr
+ len
, answer
))
3250 LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8
*)rep
->rhdr
+ len
- (mDNSu8
*)data
);
3251 data
+= answer
->rdlength
;
3252 put_uint32(AddRecord
? answer
->rroriginalttl
: 0, &data
);
3254 append_reply(req
, rep
);
3255 // Stop the question, if we just timed out
3256 if (error
== kDNSServiceErr_Timeout
)
3258 mDNS_StopQuery(m
, question
);
3259 // Reset the pointers so that we don't call stop on termination
3260 question
->QuestionContext
= mDNSNULL
;
3262 else if ((AddRecord
== QC_add
) && req
->hdr
.op
== addrinfo_request
)
3264 // Note: We count all answers including LocalOnly e.g., /etc/hosts. If we
3265 // exclude that, v4ans/v6ans will be zero and we would wrongly think that
3266 // we did not answer questions and setup the status to deliver triggers.
3267 if (question
->qtype
== kDNSType_A
)
3268 req
->u
.addrinfo
.v4ans
= 1;
3269 if (question
->qtype
== kDNSType_AAAA
)
3270 req
->u
.addrinfo
.v6ans
= 1;
3272 else if ((AddRecord
== QC_add
) && req
->hdr
.op
== query_request
)
3274 if (question
->qtype
== kDNSType_A
|| question
->qtype
== kDNSType_AAAA
)
3275 req
->u
.queryrecord
.ans
= 1;
3278 #if APPLE_OSX_mDNSResponder
3280 CHECK_WCF_FUNCTION(WCFIsServerRunning
)
3283 socklen_t xucredlen
= sizeof(x
);
3285 if (WCFIsServerRunning((WCFConnection
*)m
->WCF
) && answer
->rdlength
!= 0)
3287 if (getsockopt(req
->sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 &&
3288 (x
.cr_version
== XUCRED_VERSION
))
3290 struct sockaddr_storage addr
;
3292 if (answer
->rrtype
== kDNSType_A
|| answer
->rrtype
== kDNSType_AAAA
)
3294 if (answer
->rrtype
== kDNSType_A
)
3296 struct sockaddr_in
*const sin
= (struct sockaddr_in
*)&addr
;
3298 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3299 // sin->sin_addr.s_addr = answer->rdata->u.ipv4.NotAnInteger;
3300 if (!putRData(mDNSNULL
, (mDNSu8
*)&sin
->sin_addr
, (mDNSu8
*)(&sin
->sin_addr
+ sizeof(mDNSv4Addr
)), answer
))
3301 LogMsg("queryrecord_result_reply: WCF AF_INET putRData failed");
3304 addr
.ss_len
= sizeof (struct sockaddr_in
);
3305 addr
.ss_family
= AF_INET
;
3308 else if (answer
->rrtype
== kDNSType_AAAA
)
3310 struct sockaddr_in6
*const sin6
= (struct sockaddr_in6
*)&addr
;
3311 sin6
->sin6_port
= 0;
3312 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3313 // sin6->sin6_addr.__u6_addr.__u6_addr32[0] = answer->rdata->u.ipv6.l[0];
3314 // sin6->sin6_addr.__u6_addr.__u6_addr32[1] = answer->rdata->u.ipv6.l[1];
3315 // sin6->sin6_addr.__u6_addr.__u6_addr32[2] = answer->rdata->u.ipv6.l[2];
3316 // sin6->sin6_addr.__u6_addr.__u6_addr32[3] = answer->rdata->u.ipv6.l[3];
3317 if (!putRData(mDNSNULL
, (mDNSu8
*)&sin6
->sin6_addr
, (mDNSu8
*)(&sin6
->sin6_addr
+ sizeof(mDNSv6Addr
)), answer
))
3318 LogMsg("queryrecord_result_reply: WCF AF_INET6 putRData failed");
3321 addr
.ss_len
= sizeof (struct sockaddr_in6
);
3322 addr
.ss_family
= AF_INET6
;
3327 debugf("queryrecord_result_reply: Name %s, uid %u, addr length %d", name
, x
.cr_uid
, addr
.ss_len
);
3328 CHECK_WCF_FUNCTION((WCFConnection
*)WCFNameResolvesToAddr
)
3330 WCFNameResolvesToAddr(m
->WCF
, name
, (struct sockaddr
*)&addr
, x
.cr_uid
);
3334 else if (answer
->rrtype
== kDNSType_CNAME
)
3337 char cname_cstr
[MAX_ESCAPED_DOMAIN_NAME
];
3338 if (!putRData(mDNSNULL
, cname
.c
, (mDNSu8
*)(cname
.c
+ MAX_DOMAIN_NAME
), answer
))
3339 LogMsg("queryrecord_result_reply: WCF CNAME putRData failed");
3342 ConvertDomainNameToCString(&cname
, cname_cstr
);
3343 CHECK_WCF_FUNCTION((WCFConnection
*)WCFNameResolvesToAddr
)
3345 WCFNameResolvesToName(m
->WCF
, name
, cname_cstr
, x
.cr_uid
);
3350 else my_perror("queryrecord_result_reply: ERROR: getsockopt LOCAL_PEERCRED");
3357 mDNSlocal
void queryrecord_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
3359 request_state
*req
= question
->QuestionContext
;
3360 DNSServiceErrorType error
= kDNSServiceErr_NoError
;
3361 DNSQuestion
*q
= mDNSNULL
;
3363 #if APPLE_OSX_mDNSResponder
3365 // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
3366 // get any callbacks from the core after this.
3369 LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
3372 if (req
->hdr
.op
== query_request
&& question
== req
->u
.queryrecord
.q2
)
3373 q
= &req
->u
.queryrecord
.q
;
3374 else if (req
->hdr
.op
== addrinfo_request
&& question
== req
->u
.addrinfo
.q42
)
3375 q
= &req
->u
.addrinfo
.q4
;
3376 else if (req
->hdr
.op
== addrinfo_request
&& question
== req
->u
.addrinfo
.q62
)
3377 q
= &req
->u
.addrinfo
.q6
;
3379 if (q
&& question
->qtype
!= q
->qtype
&& !SameDomainName(&question
->qname
, &q
->qname
))
3382 domainname
*orig
= question
->qnameOrig
;
3384 LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question
->qname
.c
);
3385 mDNS_StopQuery(m
, question
);
3386 question
->QuestionContext
= mDNSNULL
;
3388 // We got a negative response for the SOA record indicating that .local does not exist.
3389 // But we might have other search domains (that does not end in .local) that can be
3390 // appended to this question. In that case, we want to retry the question. Otherwise,
3391 // we don't want to try this question as unicast.
3392 if (answer
->RecordType
== kDNSRecordTypePacketNegative
&& !q
->AppendSearchDomains
)
3394 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q
->qname
.c
);
3398 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
3400 // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
3401 // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
3402 // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
3403 // SendAdditionalQuery as to how qnameOrig gets initialized.
3405 question
->InterfaceID
= mDNSInterface_Unicast
;
3406 question
->ExpectUnique
= mDNStrue
;
3407 question
->qnameOrig
= orig
;
3409 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), question
->QuestionContext
);
3411 // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
3412 // Hence, we need to set it explicitly here.
3413 question
->QuestionContext
= req
;
3414 err
= mDNS_StartQuery(m
, question
);
3415 if (err
) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
);
3417 // If we got a positive response to local SOA, then try the .local question as unicast
3418 if (answer
->RecordType
!= kDNSRecordTypePacketNegative
) return;
3420 // Fall through and get the next search domain. The question is pointing at .local
3421 // and we don't want to try that. Try the next search domain. Don't try with local
3422 // search domains for the unicast question anymore.
3424 // Note: we started the question above which will be stopped immediately (never sent on the wire)
3425 // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
3426 // question has already started.
3427 question
->AppendLocalSearchDomains
= 0;
3430 if (q
&& AddRecord
&& AddRecord
!= QC_dnssec
&& (question
->InterfaceID
== mDNSInterface_Unicast
) && !answer
->rdlength
)
3432 // If we get a negative response to the unicast query that we sent above, retry after appending search domains
3433 // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
3434 // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
3435 // To keep things simple, we handle unicast ".local" separately here.
3436 LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question
->qname
.c
, DNSTypeName(question
->qtype
));
3437 if (RetryQuestionWithSearchDomains(question
, req
, AddRecord
))
3439 if (question
->AppendSearchDomains
&& !question
->AppendLocalSearchDomains
&& IsLocalDomain(&question
->qname
))
3441 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
3442 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
3443 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
3444 // in the list. We leave it disabled so that it does not hit the wire.
3445 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
3446 question
->ThisQInterval
= 0;
3449 // 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
3450 // domains to append for "q2". In all cases, fall through and deliver the response
3452 #endif // APPLE_OSX_mDNSResponder
3454 // If a query is being suppressed for some reason, we don't have to do any other
3457 // Note: We don't check for "SuppressQuery" and instead use QC_suppressed because
3458 // the "core" needs to temporarily turn off SuppressQuery to answer this query.
3459 if (AddRecord
== QC_suppressed
)
3461 LogDebug("queryrecord_result_callback: Suppressed question %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
3462 queryrecord_result_reply(m
, req
, question
, answer
, AddRecord
, kDNSServiceErr_NoSuchRecord
);
3466 if (answer
->RecordType
== kDNSRecordTypePacketNegative
)
3468 // If this question needs to be timed out and we have reached the stop time, mark
3469 // the error as timeout. It is possible that we might get a negative response from an
3470 // external DNS server at the same time when this question reaches its stop time. We
3471 // can't tell the difference as there is no indication in the callback. This should
3472 // be okay as we will be timing out this query anyway.
3474 if (question
->TimeoutQuestion
)
3476 if ((m
->timenow
- question
->StopTime
) >= 0)
3478 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
);
3479 error
= kDNSServiceErr_Timeout
;
3483 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
3484 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
3485 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
3486 // server is going to assert that pretty much every single multicast name doesn't exist.
3488 // If we are timing out this query, we need to deliver the negative answer to the application
3489 if (error
!= kDNSServiceErr_Timeout
)
3491 if (!answer
->InterfaceID
&& IsLocalDomain(answer
->name
))
3493 // Sanity check: "q" will be set only if "question" is the .local unicast query.
3496 LogMsg("queryrecord_result_callback: ERROR!! answering multicast question %s with unicast cache record",
3497 RRDisplayString(m
, answer
));
3500 #if APPLE_OSX_mDNSResponder
3501 if (!ShouldDeliverNegativeResponse(question
))
3505 #endif // APPLE_OSX_mDNSResponder
3506 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with negative unicast response", question
->qname
.c
,
3507 DNSTypeName(question
->qtype
));
3509 error
= kDNSServiceErr_NoSuchRecord
;
3512 // If we get a negative answer, try appending search domains. Don't append search domains
3513 // - if we are timing out this question
3514 // - if the negative response was received as a result of a multicast query
3515 // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
3516 // - if this response is forced e.g., dnssec validation result
3517 if (error
!= kDNSServiceErr_Timeout
)
3519 if (!q
&& !answer
->InterfaceID
&& !answer
->rdlength
&& AddRecord
&& AddRecord
!= QC_dnssec
)
3521 // If the original question did not end in .local, we did not send an SOA query
3522 // to figure out whether we should send an additional unicast query or not. If we just
3523 // appended .local, we need to see if we need to send an additional query. This should
3524 // normally happen just once because after we append .local, we ignore all negative
3525 // responses for .local above.
3526 LogDebug("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question
->qname
.c
, DNSTypeName(question
->qtype
));
3527 if (RetryQuestionWithSearchDomains(question
, req
, AddRecord
))
3529 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
3530 // be anywhere in the search domain list.
3531 #if APPLE_OSX_mDNSResponder
3532 mStatus err
= mStatus_NoError
;
3533 err
= SendAdditionalQuery(question
, req
, err
);
3534 if (err
) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
3535 #endif // APPLE_OSX_mDNSResponder
3540 queryrecord_result_reply(m
, req
, question
, answer
, AddRecord
, error
);
3543 mDNSlocal
void queryrecord_termination_callback(request_state
*request
)
3545 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) STOP PID[%d](%s)",
3546 request
->sd
, request
->flags
, request
->interfaceIndex
, request
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(request
->u
.queryrecord
.q
.qtype
), request
->process_id
, request
->pid_name
);
3547 if (request
->u
.queryrecord
.q
.QuestionContext
)
3549 mDNS_StopQuery(&mDNSStorage
, &request
->u
.queryrecord
.q
); // no need to error check
3550 LogMcastQ(&request
->u
.queryrecord
.q
, request
, q_stop
);
3551 request
->u
.queryrecord
.q
.QuestionContext
= mDNSNULL
;
3555 DNSQuestion
*question
= &request
->u
.queryrecord
.q
;
3556 LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
);
3559 if (request
->u
.queryrecord
.q
.qnameOrig
)
3561 freeL("QueryTermination", request
->u
.queryrecord
.q
.qnameOrig
);
3562 request
->u
.queryrecord
.q
.qnameOrig
= mDNSNULL
;
3565 if (callExternalHelpers(request
->u
.queryrecord
.q
.InterfaceID
, &request
->u
.queryrecord
.q
.qname
, request
->u
.queryrecord
.q
.flags
))
3567 LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
3568 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
);
3570 if (request
->u
.queryrecord
.q2
)
3572 if (request
->u
.queryrecord
.q2
->QuestionContext
)
3574 LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request
->u
.queryrecord
.q2
->qname
.c
);
3575 mDNS_StopQuery(&mDNSStorage
, request
->u
.queryrecord
.q2
);
3576 LogMcastQ(request
->u
.queryrecord
.q2
, request
, q_stop
);
3580 DNSQuestion
*question
= request
->u
.queryrecord
.q2
;
3581 LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
);
3583 if (request
->u
.queryrecord
.q2
->qnameOrig
)
3585 LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request
->u
.queryrecord
.q2
->qnameOrig
->c
);
3586 freeL("QueryTermination q2", request
->u
.queryrecord
.q2
->qnameOrig
);
3587 request
->u
.queryrecord
.q2
->qnameOrig
= mDNSNULL
;
3589 freeL("queryrecord Q2", request
->u
.queryrecord
.q2
);
3590 request
->u
.queryrecord
.q2
= mDNSNULL
;
3592 #if APPLE_OSX_mDNSResponder
3594 if (request
->u
.queryrecord
.ans
)
3596 DNSQuestion
*v4q
, *v6q
;
3597 // If we are receiving poisitive answers, provide the hint to the
3599 v4q
= v6q
= mDNSNULL
;
3600 if (request
->u
.queryrecord
.q
.qtype
== kDNSType_A
)
3601 v4q
= &request
->u
.queryrecord
.q
;
3602 else if (request
->u
.queryrecord
.q
.qtype
== kDNSType_AAAA
)
3603 v6q
= &request
->u
.queryrecord
.q
;
3604 mDNSPlatformTriggerDNSRetry(v4q
, v6q
);
3607 #endif // APPLE_OSX_mDNSResponder
3610 mDNSlocal mStatus
handle_queryrecord_request(request_state
*request
)
3612 DNSQuestion
*const q
= &request
->u
.queryrecord
.q
;
3615 mDNSu16 rrtype
, rrclass
;
3618 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3619 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3620 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3622 // The request is scoped to a specific interface index, but the
3623 // interface is not currently in our list.
3624 if (interfaceIndex
&& !InterfaceID
)
3626 if (interfaceIndex
> 1)
3627 LogMsg("handle_queryrecord_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
3628 interfaceIndex
, request
->process_id
, request
->pid_name
);
3629 // If it's one of the specially defined inteface index values, just return an error.
3630 // Also, caller should return an error immediately if lo0 (index 1) is not configured
3631 // into the current active interfaces. See background in Radar 21967160.
3632 if (PreDefinedInterfaceIndex(interfaceIndex
) || interfaceIndex
== 1)
3634 LogInfo("handle_queryrecord_request: bad interfaceIndex %d", interfaceIndex
);
3635 return(mStatus_BadParamErr
);
3638 // Otherwise, use the specified interface index value and the request will
3639 // be applied to that interface when it comes up.
3640 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
3641 LogInfo("handle_queryrecord_request: query pending for interface index %d", interfaceIndex
);
3644 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0) return(mStatus_BadParamErr
);
3645 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
3646 rrclass
= get_uint16(&request
->msgptr
, request
->msgend
);
3648 if (!request
->msgptr
)
3649 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3651 request
->flags
= flags
;
3652 request
->interfaceIndex
= interfaceIndex
;
3653 mDNSPlatformMemZero(&request
->u
.queryrecord
, sizeof(request
->u
.queryrecord
));
3655 q
->InterfaceID
= InterfaceID
;
3657 q
->Target
= zeroAddr
;
3658 if (!MakeDomainNameFromDNSNameString(&q
->qname
, name
)) return(mStatus_BadParamErr
);
3660 if (!AuthorizedDomain(request
, &q
->qname
, AutoBrowseDomains
)) return (mStatus_NoError
);
3663 q
->qclass
= rrclass
;
3664 q
->LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
3665 q
->ExpectUnique
= mDNSfalse
;
3666 q
->ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
3667 q
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
3668 q
->SuppressUnusable
= (flags
& kDNSServiceFlagsSuppressUnusable
) != 0;
3669 q
->TimeoutQuestion
= (flags
& kDNSServiceFlagsTimeout
) != 0;
3670 q
->allowExpired
= (EnableAllowExpired
&& (flags
& kDNSServiceFlagsAllowExpiredAnswers
) != 0) ? AllowExpired_AllowExpiredAnswers
: AllowExpired_None
;
3671 q
->WakeOnResolve
= 0;
3672 q
->UseBackgroundTrafficClass
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
3673 if ((flags
& kDNSServiceFlagsValidate
) != 0)
3674 q
->ValidationRequired
= DNSSEC_VALIDATION_SECURE
;
3675 else if ((flags
& kDNSServiceFlagsValidateOptional
) != 0)
3676 q
->ValidationRequired
= DNSSEC_VALIDATION_SECURE_OPTIONAL
;
3677 q
->ValidatingResponse
= 0;
3678 q
->ProxyQuestion
= 0;
3679 q
->AnonInfo
= mDNSNULL
;
3680 q
->QuestionCallback
= queryrecord_result_callback
;
3681 q
->QuestionContext
= request
;
3682 q
->SearchListIndex
= 0;
3685 q
->DNSSECAuthInfo
= mDNSNULL
;
3686 q
->DAIFreeCallback
= mDNSNULL
;
3688 //Turn off dnssec validation for local domains and Question Types: RRSIG/ANY(ANY Type is not supported yet)
3689 if ((IsLocalDomain(&q
->qname
)) || (q
->qtype
== kDNSServiceType_RRSIG
) || (q
->qtype
== kDNSServiceType_ANY
))
3690 q
->ValidationRequired
= 0;
3692 // Don't append search domains for fully qualified domain names including queries
3693 // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3694 // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3695 // append search domains or not. So, we record that information in AppendSearchDomains.
3697 // We append search domains only for queries that are a single label. If overriden using command line
3698 // argument "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
3699 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
3701 nameLen
= strlen(name
);
3702 if ((!(q
->ValidationRequired
== DNSSEC_VALIDATION_SECURE
)) && (!(q
->ValidationRequired
== DNSSEC_VALIDATION_INSECURE
))
3703 && (rrtype
== kDNSType_A
|| rrtype
== kDNSType_AAAA
) && ((nameLen
== 0) || (name
[nameLen
- 1] != '.')) &&
3704 (AlwaysAppendSearchDomains
|| CountLabels(&q
->qname
) == 1))
3706 q
->AppendSearchDomains
= 1;
3707 q
->AppendLocalSearchDomains
= 1;
3711 q
->AppendSearchDomains
= 0;
3712 q
->AppendLocalSearchDomains
= 0;
3715 // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3716 // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3717 // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3719 q
->RetryWithSearchDomains
= ApplySearchDomainsFirst(q
) ? 1 : 0;
3720 q
->qnameOrig
= mDNSNULL
;
3721 SetQuestionPolicy(q
, request
);
3723 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3724 // Determine if this request should be promoted to use BLE triggered discovery.
3725 if (shouldUseBLE(InterfaceID
, rrtype
, (domainname
*)SkipLeadingLabels(&q
->qname
, 1), &q
->qname
))
3727 q
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
3728 request
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
3729 LogInfo("handle_queryrecord_request: request promoted to use kDNSServiceFlagsAutoTrigger");
3731 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3733 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START PID[%d](%s)",
3734 request
->sd
, request
->flags
, interfaceIndex
, q
->qname
.c
, DNSTypeName(q
->qtype
), request
->process_id
, request
->pid_name
);
3735 err
= mDNS_StartQuery(&mDNSStorage
, q
);
3739 LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q
->qname
.c
, DNSTypeName(q
->qtype
), (int)err
);
3743 request
->terminate
= queryrecord_termination_callback
;
3744 LogMcastQ(q
, request
, q_start
);
3745 if (callExternalHelpers(q
->InterfaceID
, &q
->qname
, q
->flags
))
3747 LogDebug("handle_queryrecord_request: calling external_start_browsing_for_service()");
3748 external_start_browsing_for_service(q
->InterfaceID
, &q
->qname
, q
->qtype
, q
->flags
);
3752 #if APPLE_OSX_mDNSResponder
3753 err
= SendAdditionalQuery(q
, request
, err
);
3754 #endif // APPLE_OSX_mDNSResponder
3759 // ***************************************************************************
3760 #if COMPILER_LIKES_PRAGMA_MARK
3762 #pragma mark - DNSServiceEnumerateDomains
3765 mDNSlocal reply_state
*format_enumeration_reply(request_state
*request
,
3766 const char *domain
, DNSServiceFlags flags
, mDNSu32 ifi
, DNSServiceErrorType err
)
3772 len
= sizeof(DNSServiceFlags
);
3773 len
+= sizeof(mDNSu32
);
3774 len
+= sizeof(DNSServiceErrorType
);
3775 len
+= strlen(domain
) + 1;
3777 reply
= create_reply(enumeration_reply_op
, len
, request
);
3778 reply
->rhdr
->flags
= dnssd_htonl(flags
);
3779 reply
->rhdr
->ifi
= dnssd_htonl(ifi
);
3780 reply
->rhdr
->error
= dnssd_htonl(err
);
3781 data
= (char *)&reply
->rhdr
[1];
3782 put_string(domain
, &data
);
3786 mDNSlocal
void enum_termination_callback(request_state
*request
)
3788 // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3789 if (request
->u
.enumeration
.flags
& kDNSServiceFlagsRegistrationDomains
)
3791 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3792 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_REG_QUERY
);
3796 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3797 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_BROWSE_QUERY
| UDNS_WAB_LBROWSE_QUERY
);
3798 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_autoall
);
3800 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3801 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3804 mDNSlocal
void enum_result_callback(mDNS
*const m
,
3805 DNSQuestion
*const question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
3807 char domain
[MAX_ESCAPED_DOMAIN_NAME
];
3808 request_state
*request
= question
->QuestionContext
;
3809 DNSServiceFlags flags
= 0;
3813 if (answer
->rrtype
!= kDNSType_PTR
) return;
3816 if (!AuthorizedDomain(request
, &answer
->rdata
->u
.name
, request
->u
.enumeration
.flags
? AutoRegistrationDomains
: AutoBrowseDomains
)) return;
3819 // We only return add/remove events for the browse and registration lists
3820 // For the default browse and registration answers, we only give an "ADD" event
3821 if (question
== &request
->u
.enumeration
.q_default
&& !AddRecord
) return;
3825 flags
|= kDNSServiceFlagsAdd
;
3826 if (question
== &request
->u
.enumeration
.q_default
) flags
|= kDNSServiceFlagsDefault
;
3829 ConvertDomainNameToCString(&answer
->rdata
->u
.name
, domain
);
3830 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3831 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3832 // network, so we just pass kDNSServiceInterfaceIndexAny
3833 reply
= format_enumeration_reply(request
, domain
, flags
, kDNSServiceInterfaceIndexAny
, kDNSServiceErr_NoError
);
3834 if (!reply
) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3836 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request
->sd
, question
->qname
.c
, AddRecord
? "ADD" : "RMV", domain
);
3838 append_reply(request
, reply
);
3841 mDNSlocal mStatus
handle_enum_request(request_state
*request
)
3844 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3845 DNSServiceFlags reg
= flags
& kDNSServiceFlagsRegistrationDomains
;
3846 mDNS_DomainType t_all
= reg
? mDNS_DomainTypeRegistration
: mDNS_DomainTypeBrowse
;
3847 mDNS_DomainType t_default
= reg
? mDNS_DomainTypeRegistrationDefault
: mDNS_DomainTypeBrowseDefault
;
3848 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3849 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3850 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3852 if (!request
->msgptr
)
3853 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3855 request
->flags
= flags
;
3856 request
->interfaceIndex
= interfaceIndex
;
3858 // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
3859 request
->u
.enumeration
.flags
= reg
;
3861 // enumeration requires multiple questions, so we must link all the context pointers so that
3862 // necessary context can be reached from the callbacks
3863 request
->u
.enumeration
.q_all
.QuestionContext
= request
;
3864 request
->u
.enumeration
.q_default
.QuestionContext
= request
;
3865 if (!reg
) request
->u
.enumeration
.q_autoall
.QuestionContext
= request
;
3867 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3868 if (!InterfaceID
) InterfaceID
= mDNSInterface_LocalOnly
;
3871 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request
->sd
, flags
,
3872 (flags
& kDNSServiceFlagsBrowseDomains
) ? "kDNSServiceFlagsBrowseDomains" :
3873 (flags
& kDNSServiceFlagsRegistrationDomains
) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3874 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
, t_all
, NULL
, InterfaceID
, enum_result_callback
, request
);
3877 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
, t_default
, NULL
, InterfaceID
, enum_result_callback
, request
);
3878 if (err
) mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3881 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_autoall
, mDNS_DomainTypeBrowseAutomatic
, NULL
, InterfaceID
, enum_result_callback
, request
);
3884 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3885 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3888 if (!err
) request
->terminate
= enum_termination_callback
;
3892 // Start the domain enumeration queries to discover the WAB Browse/Registration domains
3895 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3896 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_REG_QUERY
);
3900 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3901 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_BROWSE_QUERY
| UDNS_WAB_LBROWSE_QUERY
);
3908 // ***************************************************************************
3909 #if COMPILER_LIKES_PRAGMA_MARK
3911 #pragma mark - DNSServiceReconfirmRecord & Misc
3914 mDNSlocal mStatus
handle_reconfirm_request(request_state
*request
)
3916 mStatus status
= mStatus_BadParamErr
;
3917 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 0, 0);
3920 status
= mDNS_ReconfirmByValue(&mDNSStorage
, &rr
->resrec
);
3922 (status
== mStatus_NoError
) ?
3923 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated PID[%d](%s)" :
3924 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed PID[%d](%s) status %d",
3925 request
->sd
, RRDisplayString(&mDNSStorage
, &rr
->resrec
),
3926 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, rr
->resrec
.InterfaceID
, mDNSfalse
),
3927 request
->process_id
, request
->pid_name
, status
);
3928 freeL("AuthRecord/handle_reconfirm_request", rr
);
3933 #if APPLE_OSX_mDNSResponder
3935 mDNSlocal mStatus
handle_release_request(request_state
*request
)
3938 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
3939 domainname instance
;
3941 // extract the data from the message
3942 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3944 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0 ||
3945 get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
3946 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
3948 LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
3949 return(mStatus_BadParamErr
);
3952 if (!request
->msgptr
)
3954 LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request
->sd
);
3955 return(mStatus_BadParamErr
);
3958 if (build_domainname_from_strings(&instance
, name
, regtype
, domain
) < 0)
3960 LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name
, regtype
, domain
);
3961 return(mStatus_BadParamErr
);
3964 LogOperation("%3d: PeerConnectionRelease(%X %##s) START PID[%d](%s)",
3965 request
->sd
, flags
, instance
.c
, request
->process_id
, request
->pid_name
);
3967 external_connection_release(&instance
);
3971 #else // APPLE_OSX_mDNSResponder
3973 mDNSlocal mStatus
handle_release_request(request_state
*request
)
3976 return mStatus_UnsupportedErr
;
3979 #endif // APPLE_OSX_mDNSResponder
3981 mDNSlocal mStatus
handle_setdomain_request(request_state
*request
)
3983 char domainstr
[MAX_ESCAPED_DOMAIN_NAME
];
3985 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3986 (void)flags
; // Unused
3987 if (get_string(&request
->msgptr
, request
->msgend
, domainstr
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
3988 !MakeDomainNameFromDNSNameString(&domain
, domainstr
))
3989 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3991 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request
->sd
, domain
.c
);
3992 return(mStatus_NoError
);
3995 typedef packedstruct
4000 } DaemonVersionReply
;
4002 mDNSlocal
void handle_getproperty_request(request_state
*request
)
4004 const mStatus BadParamErr
= dnssd_htonl((mDNSu32
)mStatus_BadParamErr
);
4006 if (get_string(&request
->msgptr
, request
->msgend
, prop
, sizeof(prop
)) >= 0)
4008 LogOperation("%3d: DNSServiceGetProperty(%s)", request
->sd
, prop
);
4009 if (!strcmp(prop
, kDNSServiceProperty_DaemonVersion
))
4011 DaemonVersionReply x
= { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H
) };
4012 send_all(request
->sd
, (const char *)&x
, sizeof(x
));
4017 // If we didn't recogize the requested property name, return BadParamErr
4018 send_all(request
->sd
, (const char *)&BadParamErr
, sizeof(BadParamErr
));
4021 #ifdef APPLE_OSX_mDNSResponder
4022 // The caller can specify either the pid or the uuid. If the pid is not specified,
4023 // update the effective uuid. Don't overwrite the pid which is used for debugging
4024 // purposes and initialized when the socket is opened.
4025 mDNSlocal
void handle_connection_delegate_request(request_state
*request
)
4030 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4031 request
->sd
, request
->process_id
, request
->pid_name
);
4032 request
->terminate
= connection_termination
;
4035 pid
= get_uint32(&request
->msgptr
, request
->msgend
);
4036 #ifdef LOCAL_PEEREPID
4040 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREPID
, &request
->process_id
, &len
) != 0)
4042 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno
, strerror(errno
));
4045 // to extract the process name from the pid value
4046 if (proc_pidinfo(request
->process_id
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0)
4048 mDNSPlatformStrLCopy(request
->pid_name
, proc
.pbsi_comm
, sizeof(request
->pid_name
));
4049 debugf("handle_connection_delegate_request: process id %d, name %s", request
->process_id
, request
->pid_name
);
4052 #ifdef LOCAL_PEEREUUID
4056 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREUUID
, request
->uuid
, &len
) != 0)
4058 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno
, strerror(errno
));
4061 request
->validUUID
= mDNStrue
;
4066 mDNSlocal
void handle_connection_delegate_request(request_state
*request
)
4072 typedef packedstruct
4078 mDNSlocal
void handle_getpid_request(request_state
*request
)
4080 const request_state
*req
;
4082 mDNSu16 srcport
= get_uint16(&request
->msgptr
, request
->msgend
);
4083 const DNSQuestion
*q
= NULL
;
4086 LogMsg("%3d: DNSServiceGetPID START", request
->sd
);
4088 for (req
= all_requests
; req
; req
=req
->next
)
4090 if (req
->hdr
.op
== query_request
)
4091 q
= &req
->u
.queryrecord
.q
;
4092 else if (req
->hdr
.op
== addrinfo_request
)
4093 q
= &req
->u
.addrinfo
.q4
;
4094 else if (req
->hdr
.op
== addrinfo_request
)
4095 q
= &req
->u
.addrinfo
.q6
;
4097 if (q
&& q
->LocalSocket
!= NULL
)
4099 mDNSu16 port
= mDNSPlatformGetUDPPort(q
->LocalSocket
);
4100 if (port
== srcport
)
4102 pid
= req
->process_id
;
4103 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s] question %##s", htons(srcport
), pid
, req
->pid_name
, q
->qname
.c
);
4108 // If we cannot find in the client requests, look to see if this was
4109 // started by mDNSResponder.
4112 for (q
= mDNSStorage
.Questions
; q
; q
= q
->next
)
4114 if (q
&& q
->LocalSocket
!= NULL
)
4116 mDNSu16 port
= mDNSPlatformGetUDPPort(q
->LocalSocket
);
4117 if (port
== srcport
)
4119 #if APPLE_OSX_mDNSResponder
4121 #endif // APPLE_OSX_mDNSResponder
4122 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s], question %##s", htons(srcport
), pid
, "_mDNSResponder", q
->qname
.c
);
4131 send_all(request
->sd
, (const char *)&pi
, sizeof(PIDInfo
));
4132 LogMsg("%3d: DNSServiceGetPID STOP", request
->sd
);
4135 // ***************************************************************************
4136 #if COMPILER_LIKES_PRAGMA_MARK
4138 #pragma mark - DNSServiceNATPortMappingCreate
4141 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
4143 mDNSlocal
void port_mapping_termination_callback(request_state
*request
)
4145 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](%s)", request
->sd
,
4146 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
4147 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
4148 request
->process_id
, request
->pid_name
);
4149 mDNS_StopNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
4152 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
4153 mDNSlocal
void port_mapping_create_request_callback(mDNS
*m
, NATTraversalInfo
*n
)
4155 request_state
*request
= (request_state
*)n
->clientContext
;
4160 if (!request
) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
4162 // calculate reply data length
4163 replyLen
= sizeof(DNSServiceFlags
);
4164 replyLen
+= 3 * sizeof(mDNSu32
); // if index + addr + ttl
4165 replyLen
+= sizeof(DNSServiceErrorType
);
4166 replyLen
+= 2 * sizeof(mDNSu16
); // Internal Port + External Port
4167 replyLen
+= sizeof(mDNSu8
); // protocol
4169 rep
= create_reply(port_mapping_reply_op
, replyLen
, request
);
4171 rep
->rhdr
->flags
= dnssd_htonl(0);
4172 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, n
->InterfaceID
, mDNSfalse
));
4173 rep
->rhdr
->error
= dnssd_htonl(n
->Result
);
4175 data
= (char *)&rep
->rhdr
[1];
4177 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[0];
4178 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[1];
4179 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[2];
4180 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[3];
4181 *data
++ = DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
);
4182 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[0];
4183 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[1];
4184 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[0];
4185 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[1];
4186 put_uint32(request
->u
.pm
.NATinfo
.Lifetime
, &data
);
4188 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request
->sd
,
4189 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
4190 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
4191 &request
->u
.pm
.NATinfo
.ExternalAddress
, mDNSVal16(request
->u
.pm
.NATinfo
.ExternalPort
), request
->u
.pm
.NATinfo
.Lifetime
);
4193 append_reply(request
, rep
);
4196 mDNSlocal mStatus
handle_port_mapping_request(request_state
*request
)
4199 mStatus err
= mStatus_NoError
;
4201 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
4202 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
4203 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
4204 mDNSu8 protocol
= (mDNSu8
)get_uint32(&request
->msgptr
, request
->msgend
);
4205 (void)flags
; // Unused
4206 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
4207 if (request
->msgptr
+ 8 > request
->msgend
) request
->msgptr
= NULL
;
4210 request
->u
.pm
.NATinfo
.IntPort
.b
[0] = *request
->msgptr
++;
4211 request
->u
.pm
.NATinfo
.IntPort
.b
[1] = *request
->msgptr
++;
4212 request
->u
.pm
.ReqExt
.b
[0] = *request
->msgptr
++;
4213 request
->u
.pm
.ReqExt
.b
[1] = *request
->msgptr
++;
4214 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
4217 if (!request
->msgptr
)
4218 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
4220 if (protocol
== 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
4222 if (!mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
) || !mDNSIPPortIsZero(request
->u
.pm
.ReqExt
) || ttl
) return(mStatus_BadParamErr
);
4226 if (mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
)) return(mStatus_BadParamErr
);
4227 if (!(protocol
& (kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
))) return(mStatus_BadParamErr
);
4230 request
->flags
= flags
;
4231 request
->interfaceIndex
= interfaceIndex
;
4232 request
->u
.pm
.NATinfo
.Protocol
= !protocol
? NATOp_AddrRequest
: (protocol
== kDNSServiceProtocol_UDP
) ? NATOp_MapUDP
: NATOp_MapTCP
;
4233 // u.pm.NATinfo.IntPort = already set above
4234 request
->u
.pm
.NATinfo
.RequestedPort
= request
->u
.pm
.ReqExt
;
4235 request
->u
.pm
.NATinfo
.NATLease
= ttl
;
4236 request
->u
.pm
.NATinfo
.clientCallback
= port_mapping_create_request_callback
;
4237 request
->u
.pm
.NATinfo
.clientContext
= request
;
4239 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](%s)", request
->sd
,
4240 protocol
, mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
4241 request
->process_id
, request
->pid_name
);
4242 err
= mDNS_StartNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
4243 if (err
) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err
);
4244 else request
->terminate
= port_mapping_termination_callback
;
4249 // ***************************************************************************
4250 #if COMPILER_LIKES_PRAGMA_MARK
4252 #pragma mark - DNSServiceGetAddrInfo
4255 mDNSlocal
void addrinfo_termination_callback(request_state
*request
)
4257 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP PID[%d](%s)", request
->sd
, request
->u
.addrinfo
.q4
.qname
.c
,
4258 request
->process_id
, request
->pid_name
);
4260 if (request
->u
.addrinfo
.q4
.QuestionContext
)
4262 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
4263 LogMcastQ(&request
->u
.addrinfo
.q4
, request
, q_stop
);
4264 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
4266 if (callExternalHelpers(request
->u
.addrinfo
.interface_id
, &request
->u
.addrinfo
.q4
.qname
, request
->flags
))
4268 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for A record");
4269 external_stop_browsing_for_service(request
->u
.addrinfo
.interface_id
, &request
->u
.addrinfo
.q4
.qname
, kDNSServiceType_A
, request
->flags
);
4272 if (request
->u
.addrinfo
.q4
.qnameOrig
)
4274 freeL("QueryTermination", request
->u
.addrinfo
.q4
.qnameOrig
);
4275 request
->u
.addrinfo
.q4
.qnameOrig
= mDNSNULL
;
4277 if (request
->u
.addrinfo
.q42
)
4279 if (request
->u
.addrinfo
.q42
->QuestionContext
)
4281 LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request
->u
.addrinfo
.q42
->qname
.c
);
4282 mDNS_StopQuery(&mDNSStorage
, request
->u
.addrinfo
.q42
);
4283 LogMcastQ(request
->u
.addrinfo
.q42
, request
, q_stop
);
4285 if (request
->u
.addrinfo
.q42
->qnameOrig
)
4287 LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request
->u
.addrinfo
.q42
->qnameOrig
->c
);
4288 freeL("QueryTermination q42", request
->u
.addrinfo
.q42
->qnameOrig
);
4289 request
->u
.addrinfo
.q42
->qnameOrig
= mDNSNULL
;
4291 freeL("addrinfo Q42", request
->u
.addrinfo
.q42
);
4292 request
->u
.addrinfo
.q42
= mDNSNULL
;
4295 if (request
->u
.addrinfo
.q6
.QuestionContext
)
4297 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
4298 LogMcastQ(&request
->u
.addrinfo
.q6
, request
, q_stop
);
4299 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
4301 if (callExternalHelpers(request
->u
.addrinfo
.interface_id
, &request
->u
.addrinfo
.q6
.qname
, request
->flags
))
4303 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for AAAA record");
4304 external_stop_browsing_for_service(request
->u
.addrinfo
.interface_id
, &request
->u
.addrinfo
.q6
.qname
, kDNSServiceType_AAAA
, request
->flags
);
4307 if (request
->u
.addrinfo
.q6
.qnameOrig
)
4309 freeL("QueryTermination", request
->u
.addrinfo
.q6
.qnameOrig
);
4310 request
->u
.addrinfo
.q6
.qnameOrig
= mDNSNULL
;
4312 if (request
->u
.addrinfo
.q62
)
4314 if (request
->u
.addrinfo
.q62
->QuestionContext
)
4316 LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request
->u
.addrinfo
.q62
->qname
.c
);
4317 mDNS_StopQuery(&mDNSStorage
, request
->u
.addrinfo
.q62
);
4318 LogMcastQ(request
->u
.addrinfo
.q62
, request
, q_stop
);
4320 if (request
->u
.addrinfo
.q62
->qnameOrig
)
4322 LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request
->u
.addrinfo
.q62
->qnameOrig
->c
);
4323 freeL("QueryTermination q62", request
->u
.addrinfo
.q62
->qnameOrig
);
4324 request
->u
.addrinfo
.q62
->qnameOrig
= mDNSNULL
;
4326 freeL("addrinfo Q62", request
->u
.addrinfo
.q62
);
4327 request
->u
.addrinfo
.q62
= mDNSNULL
;
4329 #if APPLE_OSX_mDNSResponder
4331 DNSQuestion
*v4q
, *v6q
;
4332 v4q
= v6q
= mDNSNULL
;
4333 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
)
4335 // If we are not delivering answers, we may be timing out prematurely.
4336 // Note down the current state so that we know to retry when we see a
4337 // valid response again.
4338 if (request
->u
.addrinfo
.q4
.TimeoutQuestion
&& !request
->u
.addrinfo
.v4ans
)
4340 mDNSPlatformUpdateDNSStatus(&request
->u
.addrinfo
.q4
);
4342 // If we have a v4 answer and if we timed out prematurely before, provide
4343 // a trigger to the upper layer so that it can retry questions if needed.
4344 if (request
->u
.addrinfo
.v4ans
)
4345 v4q
= &request
->u
.addrinfo
.q4
;
4347 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
)
4349 if (request
->u
.addrinfo
.q6
.TimeoutQuestion
&& !request
->u
.addrinfo
.v6ans
)
4351 mDNSPlatformUpdateDNSStatus(&request
->u
.addrinfo
.q6
);
4353 if (request
->u
.addrinfo
.v6ans
)
4354 v6q
= &request
->u
.addrinfo
.q6
;
4356 mDNSPlatformTriggerDNSRetry(v4q
, v6q
);
4358 #endif // APPLE_OSX_mDNSResponder
4361 mDNSlocal mStatus
handle_addrinfo_request(request_state
*request
)
4367 mDNSs32 serviceIndex
= -1; // default unscoped value for ServiceID is -1
4368 mDNSInterfaceID InterfaceID
;
4370 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
4372 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
4374 if (flags
& kDNSServiceFlagsServiceIndex
)
4376 // NOTE: kDNSServiceFlagsServiceIndex flag can only be set for DNSServiceGetAddrInfo()
4377 LogInfo("DNSServiceGetAddrInfo: kDNSServiceFlagsServiceIndex is SET by the client");
4378 // if kDNSServiceFlagsServiceIndex is SET,
4379 // interpret the interfaceID as the serviceId and set the interfaceID to 0.
4380 serviceIndex
= interfaceIndex
;
4384 mDNSPlatformMemZero(&request
->u
.addrinfo
, sizeof(request
->u
.addrinfo
));
4386 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
4388 // The request is scoped to a specific interface index, but the
4389 // interface is not currently in our list.
4390 if (interfaceIndex
&& !InterfaceID
)
4392 if (interfaceIndex
> 1)
4393 LogMsg("handle_addrinfo_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
4394 interfaceIndex
, request
->process_id
, request
->pid_name
);
4395 // If it's one of the specially defined inteface index values, just return an error.
4396 if (PreDefinedInterfaceIndex(interfaceIndex
))
4398 LogInfo("handle_addrinfo_request: bad interfaceIndex %d", interfaceIndex
);
4399 return(mStatus_BadParamErr
);
4402 // Otherwise, use the specified interface index value and the request will
4403 // be applied to that interface when it comes up.
4404 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
4405 LogInfo("handle_addrinfo_request: query pending for interface index %d", interfaceIndex
);
4408 request
->flags
= flags
;
4409 request
->interfaceIndex
= interfaceIndex
;
4410 request
->u
.addrinfo
.interface_id
= InterfaceID
;
4411 request
->u
.addrinfo
.flags
= flags
;
4412 request
->u
.addrinfo
.protocol
= get_uint32(&request
->msgptr
, request
->msgend
);
4414 if (request
->u
.addrinfo
.protocol
> (kDNSServiceProtocol_IPv4
|kDNSServiceProtocol_IPv6
)) return(mStatus_BadParamErr
);
4416 if (get_string(&request
->msgptr
, request
->msgend
, hostname
, 256) < 0) return(mStatus_BadParamErr
);
4418 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
4420 if (!MakeDomainNameFromDNSNameString(&d
, hostname
))
4421 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname
); return(mStatus_BadParamErr
); }
4424 if (!AuthorizedDomain(request
, &d
, AutoBrowseDomains
)) return (mStatus_NoError
);
4427 if (!request
->u
.addrinfo
.protocol
)
4429 flags
|= kDNSServiceFlagsSuppressUnusable
;
4430 request
->u
.addrinfo
.protocol
= (kDNSServiceProtocol_IPv4
| kDNSServiceProtocol_IPv6
);
4433 request
->u
.addrinfo
.q4
.InterfaceID
= request
->u
.addrinfo
.q6
.InterfaceID
= request
->u
.addrinfo
.interface_id
;
4434 request
->u
.addrinfo
.q4
.ServiceID
= request
->u
.addrinfo
.q6
.ServiceID
= serviceIndex
;
4435 request
->u
.addrinfo
.q4
.flags
= request
->u
.addrinfo
.q6
.flags
= flags
;
4436 request
->u
.addrinfo
.q4
.Target
= request
->u
.addrinfo
.q6
.Target
= zeroAddr
;
4437 request
->u
.addrinfo
.q4
.qname
= request
->u
.addrinfo
.q6
.qname
= d
;
4438 request
->u
.addrinfo
.q4
.qclass
= request
->u
.addrinfo
.q6
.qclass
= kDNSServiceClass_IN
;
4439 request
->u
.addrinfo
.q4
.LongLived
= request
->u
.addrinfo
.q6
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
4440 request
->u
.addrinfo
.q4
.ExpectUnique
= request
->u
.addrinfo
.q6
.ExpectUnique
= mDNSfalse
;
4441 request
->u
.addrinfo
.q4
.ForceMCast
= request
->u
.addrinfo
.q6
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
4442 request
->u
.addrinfo
.q4
.ReturnIntermed
= request
->u
.addrinfo
.q6
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
4443 request
->u
.addrinfo
.q4
.SuppressUnusable
= request
->u
.addrinfo
.q6
.SuppressUnusable
= (flags
& kDNSServiceFlagsSuppressUnusable
) != 0;
4444 request
->u
.addrinfo
.q4
.TimeoutQuestion
= request
->u
.addrinfo
.q6
.TimeoutQuestion
= (flags
& kDNSServiceFlagsTimeout
) != 0;
4445 request
->u
.addrinfo
.q4
.allowExpired
= request
->u
.addrinfo
.q6
.allowExpired
= (EnableAllowExpired
&& (flags
& kDNSServiceFlagsAllowExpiredAnswers
) != 0) ? AllowExpired_AllowExpiredAnswers
: AllowExpired_None
;
4446 request
->u
.addrinfo
.q4
.WakeOnResolve
= request
->u
.addrinfo
.q6
.WakeOnResolve
= 0;
4447 request
->u
.addrinfo
.q4
.UseBackgroundTrafficClass
= request
->u
.addrinfo
.q6
.UseBackgroundTrafficClass
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
4448 if ((flags
& kDNSServiceFlagsValidate
) != 0)
4449 request
->u
.addrinfo
.q4
.ValidationRequired
= request
->u
.addrinfo
.q6
.ValidationRequired
= DNSSEC_VALIDATION_SECURE
;
4450 else if ((flags
& kDNSServiceFlagsValidateOptional
) != 0)
4451 request
->u
.addrinfo
.q4
.ValidationRequired
= request
->u
.addrinfo
.q6
.ValidationRequired
= DNSSEC_VALIDATION_SECURE_OPTIONAL
;
4452 request
->u
.addrinfo
.q4
.ValidatingResponse
= request
->u
.addrinfo
.q6
.ValidatingResponse
= 0;
4453 request
->u
.addrinfo
.q4
.ProxyQuestion
= request
->u
.addrinfo
.q6
.ProxyQuestion
= 0;
4454 request
->u
.addrinfo
.q4
.qnameOrig
= request
->u
.addrinfo
.q6
.qnameOrig
= mDNSNULL
;
4455 request
->u
.addrinfo
.q4
.AnonInfo
= request
->u
.addrinfo
.q6
.AnonInfo
= mDNSNULL
;
4457 SetQuestionPolicy(&request
->u
.addrinfo
.q4
, request
);
4458 SetQuestionPolicy(&request
->u
.addrinfo
.q6
, request
);
4460 request
->u
.addrinfo
.q4
.StopTime
= request
->u
.addrinfo
.q6
.StopTime
= 0;
4462 request
->u
.addrinfo
.q4
.DNSSECAuthInfo
= request
->u
.addrinfo
.q6
.DNSSECAuthInfo
= mDNSNULL
;
4463 request
->u
.addrinfo
.q4
.DAIFreeCallback
= request
->u
.addrinfo
.q6
.DAIFreeCallback
= mDNSNULL
;
4465 //Turn off dnssec validation for local domains
4466 if (IsLocalDomain(&d
))
4467 request
->u
.addrinfo
.q4
.ValidationRequired
= request
->u
.addrinfo
.q6
.ValidationRequired
= 0;
4469 hostnameLen
= strlen(hostname
);
4471 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START PID[%d](%s)",
4472 request
->sd
, flags
, interfaceIndex
, request
->u
.addrinfo
.protocol
, d
.c
, request
->process_id
, request
->pid_name
);
4474 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
)
4476 request
->u
.addrinfo
.q6
.qtype
= kDNSServiceType_AAAA
;
4477 request
->u
.addrinfo
.q6
.SearchListIndex
= 0;
4478 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set
4479 if ((!(request
->u
.addrinfo
.q6
.ValidationRequired
== DNSSEC_VALIDATION_SECURE
)) && (!(request
->u
.addrinfo
.q6
.ValidationRequired
== DNSSEC_VALIDATION_INSECURE
))
4480 && ((hostnameLen
== 0) || (hostname
[hostnameLen
- 1] != '.')) && (AlwaysAppendSearchDomains
|| CountLabels(&d
) == 1))
4482 request
->u
.addrinfo
.q6
.AppendSearchDomains
= 1;
4483 request
->u
.addrinfo
.q6
.AppendLocalSearchDomains
= 1;
4487 request
->u
.addrinfo
.q6
.AppendSearchDomains
= 0;
4488 request
->u
.addrinfo
.q6
.AppendLocalSearchDomains
= 0;
4490 request
->u
.addrinfo
.q6
.RetryWithSearchDomains
= (ApplySearchDomainsFirst(&request
->u
.addrinfo
.q6
) ? 1 : 0);
4491 request
->u
.addrinfo
.q6
.QuestionCallback
= queryrecord_result_callback
;
4492 request
->u
.addrinfo
.q6
.QuestionContext
= request
;
4493 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
4494 if (err
!= mStatus_NoError
)
4496 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
4497 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
4499 #if APPLE_OSX_mDNSResponder
4500 err
= SendAdditionalQuery(&request
->u
.addrinfo
.q6
, request
, err
);
4501 #endif // APPLE_OSX_mDNSResponder
4504 request
->terminate
= addrinfo_termination_callback
;
4505 LogMcastQ(&request
->u
.addrinfo
.q6
, request
, q_start
);
4506 if (callExternalHelpers(InterfaceID
, &d
, flags
))
4508 LogDebug("handle_addrinfo_request: calling external_start_browsing_for_service() for AAAA record");
4509 external_start_browsing_for_service(InterfaceID
, &d
, kDNSServiceType_AAAA
, flags
);
4514 if (!err
&& (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
))
4516 request
->u
.addrinfo
.q4
.qtype
= kDNSServiceType_A
;
4517 request
->u
.addrinfo
.q4
.SearchListIndex
= 0;
4519 // We append search domains only for queries that are a single label. If overriden using cmd line arg
4520 // "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
4521 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
4523 if ((!(request
->u
.addrinfo
.q4
.ValidationRequired
== DNSSEC_VALIDATION_SECURE
)) && (!(request
->u
.addrinfo
.q4
.ValidationRequired
== DNSSEC_VALIDATION_INSECURE
))
4524 && ((hostnameLen
== 0) || (hostname
[hostnameLen
- 1] != '.')) && (AlwaysAppendSearchDomains
|| CountLabels(&d
) == 1))
4526 request
->u
.addrinfo
.q4
.AppendSearchDomains
= 1;
4527 request
->u
.addrinfo
.q4
.AppendLocalSearchDomains
= 1;
4531 request
->u
.addrinfo
.q4
.AppendSearchDomains
= 0;
4532 request
->u
.addrinfo
.q4
.AppendLocalSearchDomains
= 0;
4534 request
->u
.addrinfo
.q4
.RetryWithSearchDomains
= (ApplySearchDomainsFirst(&request
->u
.addrinfo
.q4
) ? 1 : 0);
4535 request
->u
.addrinfo
.q4
.QuestionCallback
= queryrecord_result_callback
;
4536 request
->u
.addrinfo
.q4
.QuestionContext
= request
;
4537 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
4538 if (err
!= mStatus_NoError
)
4540 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
4541 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
4542 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
)
4544 // If we started a query for IPv6, we need to cancel it
4545 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
4546 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
4548 if (callExternalHelpers(InterfaceID
, &d
, flags
))
4550 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for AAAA record");
4551 external_stop_browsing_for_service(InterfaceID
, &d
, kDNSServiceType_AAAA
, flags
);
4555 #if APPLE_OSX_mDNSResponder
4556 err
= SendAdditionalQuery(&request
->u
.addrinfo
.q4
, request
, err
);
4557 #endif // APPLE_OSX_mDNSResponder
4560 request
->terminate
= addrinfo_termination_callback
;
4561 LogMcastQ(&request
->u
.addrinfo
.q4
, request
, q_start
);
4562 if (callExternalHelpers(InterfaceID
, &d
, flags
))
4564 LogDebug("handle_addrinfo_request: calling external_start_browsing_for_service() for A record");
4565 external_start_browsing_for_service(InterfaceID
, &d
, kDNSServiceType_A
, flags
);
4573 // ***************************************************************************
4574 #if COMPILER_LIKES_PRAGMA_MARK
4576 #pragma mark - Main Request Handler etc.
4579 mDNSlocal request_state
*NewRequest(void)
4581 request_state
**p
= &all_requests
;
4584 *p
= mallocL("request_state", sizeof(request_state
));
4586 FatalError("ERROR: malloc");
4587 mDNSPlatformMemZero(*p
, sizeof(request_state
));
4591 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
4592 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
4593 mDNSlocal
void read_msg(request_state
*req
)
4595 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
4596 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req
->sd
); req
->ts
= t_error
; return; }
4598 if (req
->ts
== t_complete
) // this must be death or something is wrong
4600 char buf
[4]; // dummy for death notification
4601 int nread
= udsSupportReadFD(req
->sd
, buf
, 4, 0, req
->platform_data
);
4602 if (!nread
) { req
->ts
= t_terminated
; return; }
4603 if (nread
< 0) goto rerror
;
4604 LogMsg("%3d: ERROR: read data from a completed request", req
->sd
);
4609 if (req
->ts
!= t_morecoming
)
4610 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req
->sd
, req
->ts
); req
->ts
= t_error
; return; }
4612 if (req
->hdr_bytes
< sizeof(ipc_msg_hdr
))
4614 mDNSu32 nleft
= sizeof(ipc_msg_hdr
) - req
->hdr_bytes
;
4615 int nread
= udsSupportReadFD(req
->sd
, (char *)&req
->hdr
+ req
->hdr_bytes
, nleft
, 0, req
->platform_data
);
4616 if (nread
== 0) { req
->ts
= t_terminated
; return; }
4617 if (nread
< 0) goto rerror
;
4618 req
->hdr_bytes
+= nread
;
4619 if (req
->hdr_bytes
> sizeof(ipc_msg_hdr
))
4620 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req
->sd
); req
->ts
= t_error
; return; }
4622 // only read data if header is complete
4623 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
))
4625 ConvertHeaderBytes(&req
->hdr
);
4626 if (req
->hdr
.version
!= VERSION
)
4627 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req
->sd
, req
->hdr
.version
, VERSION
); req
->ts
= t_error
; return; }
4629 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
4630 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
4631 // for other overhead, this means any message above 70kB is definitely bogus.
4632 if (req
->hdr
.datalen
> 70000)
4633 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req
->sd
, req
->hdr
.datalen
, req
->hdr
.datalen
); req
->ts
= t_error
; return; }
4634 req
->msgbuf
= mallocL("request_state msgbuf", req
->hdr
.datalen
+ MSG_PAD_BYTES
);
4635 if (!req
->msgbuf
) { my_perror("ERROR: malloc"); req
->ts
= t_error
; return; }
4636 req
->msgptr
= req
->msgbuf
;
4637 req
->msgend
= req
->msgbuf
+ req
->hdr
.datalen
;
4638 mDNSPlatformMemZero(req
->msgbuf
, req
->hdr
.datalen
+ MSG_PAD_BYTES
);
4642 // If our header is complete, but we're still needing more body data, then try to read it now
4643 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
4644 // Any time we need to get the error return socket we know we'll have at least one data byte
4645 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
4646 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
< req
->hdr
.datalen
)
4648 mDNSu32 nleft
= req
->hdr
.datalen
- req
->data_bytes
;
4650 #if !defined(_WIN32)
4651 struct iovec vec
= { req
->msgbuf
+ req
->data_bytes
, nleft
}; // Tell recvmsg where we want the bytes put
4653 struct cmsghdr
*cmsg
;
4654 char cbuf
[CMSG_SPACE(4 * sizeof(dnssd_sock_t
))];
4656 msg
.msg_namelen
= 0;
4659 msg
.msg_control
= cbuf
;
4660 msg
.msg_controllen
= sizeof(cbuf
);
4662 nread
= recvmsg(req
->sd
, &msg
, 0);
4664 nread
= udsSupportReadFD(req
->sd
, (char *)req
->msgbuf
+ req
->data_bytes
, nleft
, 0, req
->platform_data
);
4666 if (nread
== 0) { req
->ts
= t_terminated
; return; }
4667 if (nread
< 0) goto rerror
;
4668 req
->data_bytes
+= nread
;
4669 if (req
->data_bytes
> req
->hdr
.datalen
)
4670 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req
->sd
); req
->ts
= t_error
; return; }
4671 #if !defined(_WIN32)
4672 cmsg
= CMSG_FIRSTHDR(&msg
);
4673 #if DEBUG_64BIT_SCM_RIGHTS
4674 LogMsg("%3d: Expecting %d %d %d %d", req
->sd
, sizeof(cbuf
), sizeof(cbuf
), SOL_SOCKET
, SCM_RIGHTS
);
4675 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);
4676 #endif // DEBUG_64BIT_SCM_RIGHTS
4677 if (cmsg
&& cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
4679 #if APPLE_OSX_mDNSResponder
4680 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
4681 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
4682 // and it's convenient to repurpose the existing fd-passing code here for that task
4683 if (req
->hdr
.op
== send_bpf
)
4685 dnssd_sock_t x
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
4686 LogOperation("%3d: Got len %d, BPF %d", req
->sd
, cmsg
->cmsg_len
, x
);
4687 mDNSPlatformReceiveBPF_fd(x
);
4690 #endif // APPLE_OSX_mDNSResponder
4691 req
->errsd
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
4692 #if DEBUG_64BIT_SCM_RIGHTS
4693 LogMsg("%3d: read req->errsd %d", req
->sd
, req
->errsd
);
4694 #endif // DEBUG_64BIT_SCM_RIGHTS
4695 if (req
->data_bytes
< req
->hdr
.datalen
)
4697 LogMsg("%3d: Client(PID [%d](%s)) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
4698 req
->sd
, req
->process_id
, req
->pid_name
, req
->errsd
, req
->data_bytes
, req
->hdr
.datalen
);
4706 // If our header and data are both complete, see if we need to make our separate error return socket
4707 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
== req
->hdr
.datalen
)
4709 if (req
->terminate
&& req
->hdr
.op
!= cancel_request
)
4711 dnssd_sockaddr_t cliaddr
;
4712 #if defined(USE_TCP_LOOPBACK)
4715 port
.b
[0] = req
->msgptr
[0];
4716 port
.b
[1] = req
->msgptr
[1];
4718 cliaddr
.sin_family
= AF_INET
;
4719 cliaddr
.sin_port
= port
.NotAnInteger
;
4720 cliaddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
4722 char ctrl_path
[MAX_CTLPATH
];
4723 get_string(&req
->msgptr
, req
->msgend
, ctrl_path
, MAX_CTLPATH
); // path is first element in message buffer
4724 mDNSPlatformMemZero(&cliaddr
, sizeof(cliaddr
));
4725 cliaddr
.sun_family
= AF_LOCAL
;
4726 mDNSPlatformStrLCopy(cliaddr
.sun_path
, ctrl_path
, sizeof(cliaddr
.sun_path
));
4727 // If the error return path UDS name is empty string, that tells us
4728 // that this is a new version of the library that's going to pass us
4729 // the error return path socket via sendmsg/recvmsg
4730 if (ctrl_path
[0] == 0)
4732 if (req
->errsd
== req
->sd
)
4733 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req
->sd
); req
->ts
= t_error
; return; }
4738 req
->errsd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
4739 if (!dnssd_SocketValid(req
->errsd
))
4741 my_throttled_perror("ERROR: socket");
4746 if (connect(req
->errsd
, (struct sockaddr
*)&cliaddr
, sizeof(cliaddr
)) < 0)
4748 #if !defined(USE_TCP_LOOPBACK)
4750 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
4751 req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
4752 if (stat(cliaddr
.sun_path
, &sb
) < 0)
4753 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
4755 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
);
4761 #if !defined(USE_TCP_LOOPBACK)
4764 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]);
4766 if (ioctlsocket(req
->errsd
, FIONBIO
, &opt
) != 0)
4768 if (fcntl(req
->errsd
, F_SETFL
, fcntl(req
->errsd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
4771 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
4772 req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
4778 req
->ts
= t_complete
;
4784 if (dnssd_errno
== dnssd_EWOULDBLOCK
|| dnssd_errno
== dnssd_EINTR
) return;
4785 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
4789 mDNSlocal mStatus
handle_client_request(request_state
*req
)
4791 mStatus err
= mStatus_NoError
;
4794 // These are all operations that have their own first-class request_state object
4795 case connection_request
:
4796 LogOperation("%3d: DNSServiceCreateConnection START PID[%d](%s)",
4797 req
->sd
, req
->process_id
, req
->pid_name
);
4798 req
->terminate
= connection_termination
;
4800 case connection_delegate_request
:
4801 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4802 req
->sd
, req
->process_id
, req
->pid_name
);
4803 req
->terminate
= connection_termination
;
4804 handle_connection_delegate_request(req
);
4806 case resolve_request
: err
= handle_resolve_request (req
); break;
4807 case query_request
: err
= handle_queryrecord_request (req
); break;
4808 case browse_request
: err
= handle_browse_request (req
); break;
4809 case reg_service_request
: err
= handle_regservice_request (req
); break;
4810 case enumeration_request
: err
= handle_enum_request (req
); break;
4811 case reconfirm_record_request
: err
= handle_reconfirm_request (req
); break;
4812 case setdomain_request
: err
= handle_setdomain_request (req
); break;
4813 case getproperty_request
: handle_getproperty_request (req
); break;
4814 case getpid_request
: handle_getpid_request (req
); break;
4815 case port_mapping_request
: err
= handle_port_mapping_request(req
); break;
4816 case addrinfo_request
: err
= handle_addrinfo_request (req
); break;
4817 case send_bpf
: /* Do nothing for send_bpf */ break;
4819 // These are all operations that work with an existing request_state object
4820 case reg_record_request
: err
= handle_regrecord_request (req
); break;
4821 case add_record_request
: err
= handle_add_request (req
); break;
4822 case update_record_request
: err
= handle_update_request (req
); break;
4823 case remove_record_request
: err
= handle_removerecord_request(req
); break;
4824 case cancel_request
: handle_cancel_request (req
); break;
4825 case release_request
: err
= handle_release_request (req
); break;
4826 default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
4827 req
->sd
, req
->hdr
.op
, req
->process_id
, req
->pid_name
);
4828 err
= mStatus_BadParamErr
;
4835 #define RecordOrientedOp(X) \
4836 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
4838 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
4839 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
4841 mDNSlocal
void request_callback(int fd
, short filter
, void *info
)
4844 request_state
*req
= info
;
4845 mDNSs32 min_size
= sizeof(DNSServiceFlags
);
4847 (void)filter
; // Unused
4852 if (req
->ts
== t_morecoming
)
4854 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
4856 AbortUnlinkAndFree(req
);
4859 if (req
->ts
!= t_complete
)
4861 LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req
->ts
, req
->process_id
, req
->pid_name
);
4862 AbortUnlinkAndFree(req
);
4866 switch(req
->hdr
.op
) // Interface + other data
4868 case connection_request
: min_size
= 0; break;
4869 case connection_delegate_request
: min_size
= 4; /* pid */ break;
4870 case reg_service_request
: min_size
+= sizeof(mDNSu32
) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
4871 case add_record_request
: min_size
+= 4 /* type, rdlen */ + 4 /* ttl */; break;
4872 case update_record_request
: min_size
+= 2 /* rdlen */ + 4 /* ttl */; break;
4873 case remove_record_request
: break;
4874 case browse_request
: min_size
+= sizeof(mDNSu32
) + 2 /* type, domain */; break;
4875 case resolve_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
4876 case query_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 4 /* type, class*/; break;
4877 case enumeration_request
: min_size
+= sizeof(mDNSu32
); break;
4878 case reg_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
4879 case reconfirm_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */; break;
4880 case setdomain_request
: min_size
+= 1 /* domain */; break;
4881 case getproperty_request
: min_size
= 2; break;
4882 case getpid_request
: min_size
= 2; break;
4883 case port_mapping_request
: min_size
+= sizeof(mDNSu32
) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
4884 case addrinfo_request
: min_size
+= sizeof(mDNSu32
) + 4 /* v4/v6 */ + 1 /* hostname */; break;
4885 case send_bpf
: // Same as cancel_request below
4886 case cancel_request
: min_size
= 0; break;
4887 case release_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
4888 default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
4889 req
->hdr
.op
, req
->process_id
, req
->pid_name
);
4890 min_size
= -1; break;
4893 if ((mDNSs32
)req
->data_bytes
< min_size
)
4895 LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
4896 req
->data_bytes
, req
->hdr
.op
, min_size
, req
->process_id
, req
->pid_name
);
4897 AbortUnlinkAndFree(req
);
4900 if (LightweightOp(req
->hdr
.op
) && !req
->terminate
)
4902 LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
4903 req
->hdr
.op
, req
->process_id
, req
->pid_name
);
4904 AbortUnlinkAndFree(req
);
4908 // If req->terminate is already set, this means this operation is sharing an existing connection
4909 if (req
->terminate
&& !LightweightOp(req
->hdr
.op
))
4911 request_state
*newreq
= NewRequest();
4912 newreq
->primary
= req
;
4913 newreq
->sd
= req
->sd
;
4914 newreq
->errsd
= req
->errsd
;
4915 newreq
->uid
= req
->uid
;
4916 newreq
->hdr
= req
->hdr
;
4917 newreq
->msgbuf
= req
->msgbuf
;
4918 newreq
->msgptr
= req
->msgptr
;
4919 newreq
->msgend
= req
->msgend
;
4920 // if the parent request is a delegate connection, copy the
4924 newreq
->validUUID
= mDNStrue
;
4925 mDNSPlatformMemCopy(newreq
->uuid
, req
->uuid
, UUID_SIZE
);
4929 if (req
->process_id
)
4931 newreq
->process_id
= req
->process_id
;
4932 mDNSPlatformStrLCopy(newreq
->pid_name
, req
->pid_name
, (mDNSu32
)sizeof(newreq
->pid_name
));
4936 set_peer_pid(newreq
);
4942 // Check if the request wants no asynchronous replies.
4943 if (req
->hdr
.ipc_flags
& IPC_FLAGS_NOREPLY
) req
->no_reply
= 1;
4945 // If we're shutting down, don't allow new client requests
4946 // We do allow "cancel" and "getproperty" during shutdown
4947 if (mDNSStorage
.ShutdownTime
&& req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
)
4948 err
= mStatus_ServiceNotRunning
;
4950 err
= handle_client_request(req
);
4952 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
4953 if (req
->msgbuf
) freeL("request_state msgbuf", req
->msgbuf
);
4955 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
4956 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
4957 if (req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
&& req
->hdr
.op
!= send_bpf
&& req
->hdr
.op
!= getpid_request
)
4959 const mStatus err_netorder
= dnssd_htonl(err
);
4960 send_all(req
->errsd
, (const char *)&err_netorder
, sizeof(err_netorder
));
4961 if (req
->errsd
!= req
->sd
)
4963 LogDebug("%3d: Result code socket %d closed %08X %08X (%d)",
4964 req
->sd
, req
->errsd
, req
->hdr
.client_context
.u32
[1], req
->hdr
.client_context
.u32
[0], err
);
4965 dnssd_close(req
->errsd
);
4966 req
->errsd
= req
->sd
;
4967 // Also need to reset the parent's errsd, if this is a subordinate operation
4968 if (req
->primary
) req
->primary
->errsd
= req
->primary
->sd
;
4972 // Reset ready to accept the next req on this pipe
4973 if (req
->primary
) req
= req
->primary
;
4974 req
->ts
= t_morecoming
;
4976 req
->data_bytes
= 0;
4977 req
->msgbuf
= mDNSNULL
;
4978 req
->msgptr
= mDNSNULL
;
4983 mDNSlocal
void connect_callback(int fd
, short filter
, void *info
)
4985 dnssd_sockaddr_t cliaddr
;
4986 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(cliaddr
);
4987 dnssd_sock_t sd
= accept(fd
, (struct sockaddr
*) &cliaddr
, &len
);
4988 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
4989 unsigned long optval
= 1;
4992 (void)filter
; // Unused
4993 (void)info
; // Unused
4995 if (!dnssd_SocketValid(sd
))
4997 if (dnssd_errno
!= dnssd_EWOULDBLOCK
)
4998 my_throttled_perror("ERROR: accept");
5003 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
5004 if (setsockopt(sd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
5005 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
5009 if (ioctlsocket(sd
, FIONBIO
, &optval
) != 0)
5011 if (fcntl(sd
, F_SETFL
, fcntl(sd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
5014 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
5020 request_state
*request
= NewRequest();
5021 request
->ts
= t_morecoming
;
5023 request
->errsd
= sd
;
5024 set_peer_pid(request
);
5025 #if APPLE_OSX_mDNSResponder
5027 socklen_t xucredlen
= sizeof(x
);
5028 if (getsockopt(sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 && x
.cr_version
== XUCRED_VERSION
)
5029 request
->uid
= x
.cr_uid
; // save the effective userid of the client
5031 my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
5033 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen
, x
.cr_version
, x
.cr_uid
, x
.cr_ngroups
);
5034 #endif // APPLE_OSX_mDNSResponder
5035 LogDebug("%3d: connect_callback: Adding FD for uid %u", request
->sd
, request
->uid
);
5036 udsSupportAddFDToEventLoop(sd
, request_callback
, request
, &request
->platform_data
);
5040 mDNSlocal mDNSBool
uds_socket_setup(dnssd_sock_t skt
)
5042 #if defined(SO_NP_EXTENSIONS)
5043 struct so_np_extensions sonpx
;
5044 socklen_t optlen
= sizeof(struct so_np_extensions
);
5045 sonpx
.npx_flags
= SONPX_SETOPTSHUT
;
5046 sonpx
.npx_mask
= SONPX_SETOPTSHUT
;
5047 if (setsockopt(skt
, SOL_SOCKET
, SO_NP_EXTENSIONS
, &sonpx
, optlen
) < 0)
5048 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
5051 // SEH: do we even need to do this on windows?
5052 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
5054 if (ioctlsocket(skt
, FIONBIO
, &opt
) != 0)
5056 if (fcntl(skt
, F_SETFL
, fcntl(skt
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
5059 my_perror("ERROR: could not set listen socket to non-blocking mode");
5063 if (listen(skt
, LISTENQ
) != 0)
5065 my_perror("ERROR: could not listen on listen socket");
5069 if (mStatus_NoError
!= udsSupportAddFDToEventLoop(skt
, connect_callback
, (void *) NULL
, (void **) NULL
))
5071 my_perror("ERROR: could not add listen socket to event loop");
5076 LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt
);
5077 mDNSStorage
.uds_listener_skt
= skt
;
5082 mDNSexport
int udsserver_init(dnssd_sock_t skts
[], mDNSu32 count
)
5084 dnssd_sockaddr_t laddr
;
5088 LogInfo("udsserver_init: %d %d", _DNS_SD_H
, mDNSStorage
.mDNS_plat
);
5090 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
5093 FILE *fp
= fopen(PID_FILE
, "w");
5096 fprintf(fp
, "%d\n", getpid());
5103 for (i
= 0; i
< count
; i
++)
5104 if (dnssd_SocketValid(skts
[i
]) && !uds_socket_setup(skts
[i
]))
5109 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
5110 if (!dnssd_SocketValid(listenfd
))
5112 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
5116 mDNSPlatformMemZero(&laddr
, sizeof(laddr
));
5118 #if defined(USE_TCP_LOOPBACK)
5120 laddr
.sin_family
= AF_INET
;
5121 laddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
5122 laddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
5123 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
5126 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5132 mode_t mask
= umask(0);
5133 unlink(boundPath
); // OK if this fails
5134 laddr
.sun_family
= AF_LOCAL
;
5135 #ifndef NOT_HAVE_SA_LEN
5136 // According to Stevens (section 3.2), there is no portable way to
5137 // determine whether sa_len is defined on a particular platform.
5138 laddr
.sun_len
= sizeof(struct sockaddr_un
);
5140 if (strlen(boundPath
) >= sizeof(laddr
.sun_path
))
5142 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr
.sun_path
));
5145 mDNSPlatformStrLCopy(laddr
.sun_path
, boundPath
, sizeof(laddr
.sun_path
));
5146 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
5150 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5156 if (!uds_socket_setup(listenfd
)) goto error
;
5159 #if !defined(PLATFORM_NO_RLIMIT)
5161 // Set maximum number of open file descriptors
5162 #define MIN_OPENFILES 10240
5163 struct rlimit maxfds
, newfds
;
5165 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
5166 // you have to get and set rlimits once before getrlimit will return sensible values
5167 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5168 if (setrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5170 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5171 newfds
.rlim_max
= (maxfds
.rlim_max
> MIN_OPENFILES
) ? maxfds
.rlim_max
: MIN_OPENFILES
;
5172 newfds
.rlim_cur
= (maxfds
.rlim_cur
> MIN_OPENFILES
) ? maxfds
.rlim_cur
: MIN_OPENFILES
;
5173 if (newfds
.rlim_max
!= maxfds
.rlim_max
|| newfds
.rlim_cur
!= maxfds
.rlim_cur
)
5174 if (setrlimit(RLIMIT_NOFILE
, &newfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5176 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5177 debugf("maxfds.rlim_max %d", (long)maxfds
.rlim_max
);
5178 debugf("maxfds.rlim_cur %d", (long)maxfds
.rlim_cur
);
5182 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
5183 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
5184 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
5185 mDNS_GetDomains(&mDNSStorage
, &mDNSStorage
.AutomaticBrowseDomainQ
, mDNS_DomainTypeBrowseAutomatic
,
5186 mDNSNULL
, mDNSInterface_LocalOnly
, AutomaticBrowseDomainChange
, mDNSNULL
);
5188 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
5189 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeRegistration
);
5190 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeBrowse
);
5191 AddAutoBrowseDomain(0, &localdomain
);
5193 udsserver_handle_configchange(&mDNSStorage
);
5198 my_perror("ERROR: udsserver_init");
5202 mDNSexport
int udsserver_exit(void)
5204 // Cancel all outstanding client requests
5205 while (all_requests
) AbortUnlinkAndFree(all_requests
);
5207 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
5208 // created in udsserver_init, and others we created as a result of reading local configuration data
5209 while (LocalDomainEnumRecords
)
5211 ARListElem
*rem
= LocalDomainEnumRecords
;
5212 LocalDomainEnumRecords
= LocalDomainEnumRecords
->next
;
5213 mDNS_Deregister(&mDNSStorage
, &rem
->ar
);
5216 // If the launching environment created no listening socket,
5217 // that means we created it ourselves, so we should clean it up on exit
5218 if (dnssd_SocketValid(listenfd
))
5220 dnssd_close(listenfd
);
5221 #if !defined(USE_TCP_LOOPBACK)
5222 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
5223 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
5224 // It would be nice if we could find a solution to this problem
5225 if (unlink(boundPath
))
5226 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH
);
5230 if (PID_FILE
[0]) unlink(PID_FILE
);
5235 mDNSlocal
void LogClientInfo(request_state
*req
)
5239 mDNS_snprintf(prefix
, sizeof(prefix
), " -> ");
5241 mDNS_snprintf(prefix
, sizeof(prefix
), "%3d:", req
->sd
);
5243 if (!req
->terminate
)
5244 LogMsgNoIdent("%s No operation yet on this socket", prefix
);
5245 else if (req
->terminate
== connection_termination
)
5247 int num_records
= 0, num_ops
= 0;
5248 const registered_record_entry
*p
;
5250 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
) num_records
++;
5251 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) num_ops
++;
5252 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
5253 prefix
, num_records
, num_records
!= 1 ? "s" : "", num_ops
, num_ops
!= 1 ? "s" : "",
5254 req
->process_id
, req
->pid_name
);
5255 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
5256 LogMsgNoIdent(" -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
5257 req
->flags
, req
->interfaceIndex
, p
->key
, ARDisplayString(&mDNSStorage
, p
->rr
), req
->process_id
, req
->pid_name
);
5258 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) LogClientInfo(r
);
5260 else if (req
->terminate
== regservice_termination_callback
)
5262 service_instance
*ptr
;
5264 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
5265 LogMsgNoIdent("%s DNSServiceRegister 0x%08X %2d %##s%s %u/%u PID[%d](%s)",
5266 (ptr
== req
->u
.servicereg
.instances
) ? prefix
: " ", req
->flags
, req
->interfaceIndex
, ptr
->srs
.RR_SRV
.resrec
.name
->c
,
5267 AnonDataToString(ptr
->srs
.AnonData
, 0, anonstr
, sizeof(anonstr
)), mDNSVal16(req
->u
.servicereg
.port
),
5268 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
);
5270 else if (req
->terminate
== browse_termination_callback
)
5274 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
5275 LogMsgNoIdent("%s DNSServiceBrowse 0x%08X %2d %##s%s PID[%d](%s)",
5276 (blist
== req
->u
.browser
.browsers
) ? prefix
: " ", req
->flags
, req
->interfaceIndex
, blist
->q
.qname
.c
,
5277 AnonDataToString(req
->u
.browser
.AnonData
, 0, anonstr
, sizeof(anonstr
)), req
->process_id
, req
->pid_name
);
5279 else if (req
->terminate
== resolve_termination_callback
)
5280 LogMsgNoIdent("%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
5281 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.resolve
.qsrv
.qname
.c
, req
->process_id
, req
->pid_name
);
5282 else if (req
->terminate
== queryrecord_termination_callback
)
5283 LogMsgNoIdent("%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
5284 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(req
->u
.queryrecord
.q
.qtype
), req
->process_id
, req
->pid_name
);
5285 else if (req
->terminate
== enum_termination_callback
)
5286 LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
5287 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.enumeration
.q_all
.qname
.c
, req
->process_id
, req
->pid_name
);
5288 else if (req
->terminate
== port_mapping_termination_callback
)
5289 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 req
->interfaceIndex
,
5293 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
5294 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
5295 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
5296 mDNSVal16(req
->u
.pm
.ReqExt
),
5297 &req
->u
.pm
.NATinfo
.ExternalAddress
,
5298 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
5299 req
->u
.pm
.NATinfo
.NATLease
,
5300 req
->u
.pm
.NATinfo
.Lifetime
,
5301 req
->process_id
, req
->pid_name
);
5302 else if (req
->terminate
== addrinfo_termination_callback
)
5303 LogMsgNoIdent("%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
5304 prefix
, req
->flags
, req
->interfaceIndex
,
5305 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
? "v4" : " ",
5306 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
? "v6" : " ",
5307 req
->u
.addrinfo
.q4
.qname
.c
, req
->process_id
, req
->pid_name
);
5309 LogMsgNoIdent("%s Unrecognized operation %p", prefix
, req
->terminate
);
5312 mDNSlocal
void GetMcastClients(request_state
*req
)
5314 if (req
->terminate
== connection_termination
)
5316 int num_records
= 0, num_ops
= 0;
5317 const registered_record_entry
*p
;
5319 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
5321 for (r
= req
->next
; r
; r
=r
->next
)
5322 if (r
->primary
== req
)
5324 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
5326 if (!AuthRecord_uDNS(p
->rr
))
5329 for (r
= req
->next
; r
; r
=r
->next
)
5330 if (r
->primary
== req
)
5333 else if (req
->terminate
== regservice_termination_callback
)
5335 service_instance
*ptr
;
5336 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
5338 if (!AuthRecord_uDNS(&ptr
->srs
.RR_SRV
))
5342 else if (req
->terminate
== browse_termination_callback
)
5345 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
5347 if (mDNSOpaque16IsZero(blist
->q
.TargetQID
))
5351 else if (req
->terminate
== resolve_termination_callback
)
5353 if ((mDNSOpaque16IsZero(req
->u
.resolve
.qsrv
.TargetQID
)) && (req
->u
.resolve
.qsrv
.ThisQInterval
> 0))
5356 else if (req
->terminate
== queryrecord_termination_callback
)
5358 if ((mDNSOpaque16IsZero(req
->u
.queryrecord
.q
.TargetQID
)) && (req
->u
.queryrecord
.q
.ThisQInterval
> 0))
5361 else if (req
->terminate
== addrinfo_termination_callback
)
5363 if ((mDNSOpaque16IsZero(req
->u
.addrinfo
.q4
.TargetQID
)) && (req
->u
.addrinfo
.q4
.ThisQInterval
> 0))
5373 mDNSlocal
void LogMcastClientInfo(request_state
*req
)
5375 if (!req
->terminate
)
5376 LogMcastNoIdent("No operation yet on this socket");
5377 else if (req
->terminate
== connection_termination
)
5379 int num_records
= 0, num_ops
= 0;
5380 const registered_record_entry
*p
;
5382 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
5384 for (r
= req
->next
; r
; r
=r
->next
)
5385 if (r
->primary
== req
)
5387 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
5389 if (!AuthRecord_uDNS(p
->rr
))
5390 LogMcastNoIdent("R: -> DNSServiceRegisterRecord: %##s %s PID[%d](%s)", p
->rr
->resrec
.name
->c
,
5391 DNSTypeName(p
->rr
->resrec
.rrtype
), req
->process_id
, req
->pid_name
, i_mcount
++);
5393 for (r
= req
->next
; r
; r
=r
->next
)
5394 if (r
->primary
== req
)
5395 LogMcastClientInfo(r
);
5397 else if (req
->terminate
== regservice_termination_callback
)
5399 service_instance
*ptr
;
5400 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
5402 if (!AuthRecord_uDNS(&ptr
->srs
.RR_SRV
))
5403 LogMcastNoIdent("R: DNSServiceRegister: %##s %u/%u PID[%d](%s)", ptr
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(req
->u
.servicereg
.port
),
5404 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
, i_mcount
++);
5407 else if (req
->terminate
== browse_termination_callback
)
5410 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
5412 if (mDNSOpaque16IsZero(blist
->q
.TargetQID
))
5413 LogMcastNoIdent("Q: DNSServiceBrowse %##s %s PID[%d](%s)", blist
->q
.qname
.c
, DNSTypeName(blist
->q
.qtype
),
5414 req
->process_id
, req
->pid_name
, i_mcount
++);
5417 else if (req
->terminate
== resolve_termination_callback
)
5419 if ((mDNSOpaque16IsZero(req
->u
.resolve
.qsrv
.TargetQID
)) && (req
->u
.resolve
.qsrv
.ThisQInterval
> 0))
5420 LogMcastNoIdent("Q: DNSServiceResolve %##s %s PID[%d](%s)", req
->u
.resolve
.qsrv
.qname
.c
, DNSTypeName(req
->u
.resolve
.qsrv
.qtype
),
5421 req
->process_id
, req
->pid_name
, i_mcount
++);
5423 else if (req
->terminate
== queryrecord_termination_callback
)
5425 if ((mDNSOpaque16IsZero(req
->u
.queryrecord
.q
.TargetQID
)) && (req
->u
.queryrecord
.q
.ThisQInterval
> 0))
5426 LogMcastNoIdent("Q: DNSServiceQueryRecord %##s %s PID[%d](%s)", req
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(req
->u
.queryrecord
.q
.qtype
),
5427 req
->process_id
, req
->pid_name
, i_mcount
++);
5429 else if (req
->terminate
== addrinfo_termination_callback
)
5431 if ((mDNSOpaque16IsZero(req
->u
.addrinfo
.q4
.TargetQID
)) && (req
->u
.addrinfo
.q4
.ThisQInterval
> 0))
5432 LogMcastNoIdent("Q: DNSServiceGetAddrInfo %s%s %##s PID[%d](%s)",
5433 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
? "v4" : " ",
5434 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
? "v6" : " ",
5435 req
->u
.addrinfo
.q4
.qname
.c
, req
->process_id
, req
->pid_name
, i_mcount
++);
5444 mDNSlocal
char *RecordTypeName(mDNSu8 rtype
)
5448 case kDNSRecordTypeUnregistered
: return ("Unregistered ");
5449 case kDNSRecordTypeDeregistering
: return ("Deregistering");
5450 case kDNSRecordTypeUnique
: return ("Unique ");
5451 case kDNSRecordTypeAdvisory
: return ("Advisory ");
5452 case kDNSRecordTypeShared
: return ("Shared ");
5453 case kDNSRecordTypeVerified
: return ("Verified ");
5454 case kDNSRecordTypeKnownUnique
: return ("KnownUnique ");
5455 default: return("Unknown");
5459 mDNSlocal
int LogEtcHosts(mDNS
*const m
)
5461 mDNSBool showheader
= mDNStrue
;
5462 const AuthRecord
*ar
;
5467 mDNSBool truncated
= 0;
5469 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5471 if (m
->rrauth
.rrauth_hash
[slot
]) authslot
++;
5472 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5473 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
5475 if (ar
->RecordCallback
!= FreeEtcHosts
) continue;
5476 if (showheader
) { showheader
= mDNSfalse
; LogMsgNoIdent(" State Interface"); }
5478 // Print a maximum of 50 records
5479 if (count
++ >= 50) { truncated
= mDNStrue
; continue; }
5480 if (ar
->ARType
== AuthRecordLocalOnly
)
5482 if (ar
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
)
5483 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
5486 mDNSu32 scopeid
= (mDNSu32
)(uintptr_t)ar
->resrec
.InterfaceID
;
5487 LogMsgNoIdent(" %s %u %s", RecordTypeName(ar
->resrec
.RecordType
), scopeid
, ARDisplayString(m
, ar
));
5493 if (showheader
) LogMsgNoIdent("<None>");
5494 else if (truncated
) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count
, m
->rrauth
.rrauth_totalused
, authslot
);
5498 mDNSlocal
void LogLocalOnlyAuthRecords(mDNS
*const m
)
5500 mDNSBool showheader
= mDNStrue
;
5501 const AuthRecord
*ar
;
5505 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
5507 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
5508 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
5510 if (ar
->RecordCallback
== FreeEtcHosts
) continue;
5511 if (showheader
) { showheader
= mDNSfalse
; LogMsgNoIdent(" State Interface"); }
5513 // Print a maximum of 400 records
5514 if (ar
->ARType
== AuthRecordLocalOnly
)
5515 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
5516 else if (ar
->ARType
== AuthRecordP2P
)
5518 if (ar
->resrec
.InterfaceID
== mDNSInterface_BLE
)
5519 LogMsgNoIdent(" %s BLE %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
5521 LogMsgNoIdent(" %s PP %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
5526 if (showheader
) LogMsgNoIdent("<None>");
5529 mDNSlocal
char *AnonInfoToString(AnonymousInfo
*ai
, char *anonstr
, int anstrlen
)
5532 if (ai
&& ai
->AnonData
)
5534 return (AnonDataToString(ai
->AnonData
, ai
->AnonDataLen
, anonstr
, anstrlen
));
5539 mDNSlocal
void LogOneAuthRecord(const AuthRecord
*ar
, mDNSs32 now
, const char *const ifname
)
5542 if (AuthRecord_uDNS(ar
))
5544 LogMsgNoIdent("%7d %7d %7d %-7s %4d %s %s",
5545 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
5546 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
5547 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
5550 ar
->AllowRemoteQuery
? "☠" : " ",
5551 ARDisplayString(&mDNSStorage
, ar
));
5555 LogMsgNoIdent("%7d %7d %7d %-7s 0x%02X %s %s%s",
5556 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
5557 ar
->AnnounceCount
? (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
: 0,
5558 ar
->TimeExpire
? (ar
->TimeExpire
- now
) / mDNSPlatformOneSecond
: 0,
5559 ifname
? ifname
: "ALL",
5560 ar
->resrec
.RecordType
,
5561 ar
->AllowRemoteQuery
? "☠" : " ",
5562 ARDisplayString(&mDNSStorage
, ar
), AnonInfoToString(ar
->resrec
.AnonInfo
, anstr
, sizeof(anstr
)));
5566 mDNSlocal
void LogAuthRecords(const mDNSs32 now
, AuthRecord
*ResourceRecords
, int *proxy
)
5568 mDNSBool showheader
= mDNStrue
;
5569 const AuthRecord
*ar
;
5570 OwnerOptData owner
= zeroOwner
;
5571 for (ar
= ResourceRecords
; ar
; ar
=ar
->next
)
5573 const char *const ifname
= InterfaceNameForID(&mDNSStorage
, ar
->resrec
.InterfaceID
);
5574 if ((ar
->WakeUp
.HMAC
.l
[0] != 0) == (proxy
!= mDNSNULL
))
5576 if (showheader
) { showheader
= mDNSfalse
; LogMsgNoIdent(" Int Next Expire if State"); }
5577 if (proxy
) (*proxy
)++;
5578 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)))
5581 if (owner
.password
.l
[0])
5582 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
5583 else if (!mDNSSameEthAddress(&owner
.HMAC
, &owner
.IMAC
))
5584 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, owner
.seq
);
5586 LogMsgNoIdent("Proxying for %.6a seq %d", &owner
.HMAC
, owner
.seq
);
5588 if (AuthRecord_uDNS(ar
))
5590 LogOneAuthRecord(ar
, now
, ifname
);
5592 else if (ar
->ARType
== AuthRecordLocalOnly
)
5594 LogMsgNoIdent(" LO %s", ARDisplayString(&mDNSStorage
, ar
));
5596 else if (ar
->ARType
== AuthRecordP2P
)
5598 if (ar
->resrec
.InterfaceID
== mDNSInterface_BLE
)
5599 LogMsgNoIdent(" BLE %s", ARDisplayString(&mDNSStorage
, ar
));
5601 LogMsgNoIdent(" PP %s", ARDisplayString(&mDNSStorage
, ar
));
5605 LogOneAuthRecord(ar
, now
, ifname
);
5606 if (ar
->resrec
.AnonInfo
)
5608 ResourceRecord
*nsec3
= ar
->resrec
.AnonInfo
->nsec3RR
;
5609 // We just print the values from the AuthRecord to keep it nicely aligned though
5610 // all we want here is the nsec3 information.
5611 LogMsgNoIdent("%7d %7d %7d %7s %s",
5612 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
5613 ar
->AnnounceCount
? (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
: 0,
5614 ar
->TimeExpire
? (ar
->TimeExpire
- now
) / mDNSPlatformOneSecond
: 0,
5615 ifname
? ifname
: "ALL",
5616 RRDisplayString(&mDNSStorage
, nsec3
));
5621 if (showheader
) LogMsgNoIdent("<None>");
5624 mDNSlocal
void PrintOneCacheRecord(const CacheRecord
*cr
, mDNSu32 slot
, const mDNSu32 remain
, const char *ifname
, mDNSu32
*CacheUsed
)
5626 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5628 cr
->CRActiveQuestion
? "*" : " ",
5630 ifname
? ifname
: "-U-",
5631 (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) ? "-" :
5632 (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ? " " : "+",
5633 DNSTypeName(cr
->resrec
.rrtype
),
5634 CRDisplayString(&mDNSStorage
, cr
));
5638 mDNSlocal
void PrintCachedRecords(const CacheRecord
*cr
, mDNSu32 slot
, const mDNSu32 remain
, const char *ifname
, mDNSu32
*CacheUsed
)
5644 // The records that are cached under the main cache record like nsec, soa don't have
5645 // their own lifetime. If the main cache record expires, they also expire.
5648 PrintOneCacheRecord(nsec
, slot
, remain
, ifname
, CacheUsed
);
5654 PrintOneCacheRecord(soa
, slot
, remain
, ifname
, CacheUsed
);
5656 if (cr
->resrec
.AnonInfo
)
5658 ResourceRecord
*nsec3
= cr
->resrec
.AnonInfo
->nsec3RR
;
5659 // Even though it is a resource record, we print the sameway
5660 // as a cache record so that it aligns properly.
5663 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5667 ifname
? ifname
: "-U-",
5668 (nsec3
->RecordType
== kDNSRecordTypePacketNegative
) ? "-" :
5669 (nsec3
->RecordType
& kDNSRecordTypePacketUniqueMask
) ? " " : "+",
5670 DNSTypeName(nsec3
->rrtype
),
5671 RRDisplayString(&mDNSStorage
, nsec3
));
5676 mDNSlocal
char *AnonDataToString(const mDNSu8
*ad
, int adlen
, char *adstr
, int adstrlen
)
5684 // If the caller is lazy to compute the length, we do it for them.
5686 len
= strlen((const char *)ad
);
5690 // Print the anondata within brackets. Hence, we need space for two
5691 // brackets and a NULL byte.
5692 if (len
> (adstrlen
- 3))
5696 mDNSPlatformMemCopy(adstr
, ad
, len
);
5704 mDNSexport
void LogMDNSStatistics(mDNS
*const m
)
5706 LogMsgNoIdent("--- MDNS Statistics ---");
5708 LogMsgNoIdent("Name Conflicts %u", m
->mDNSStats
.NameConflicts
);
5709 LogMsgNoIdent("KnownUnique Name Conflicts %u", m
->mDNSStats
.KnownUniqueNameConflicts
);
5710 LogMsgNoIdent("Duplicate Query Suppressions %u", m
->mDNSStats
.DupQuerySuppressions
);
5711 LogMsgNoIdent("KA Suppressions %u", m
->mDNSStats
.KnownAnswerSuppressions
);
5712 LogMsgNoIdent("KA Multiple Packets %u", m
->mDNSStats
.KnownAnswerMultiplePkts
);
5713 LogMsgNoIdent("Poof Cache Deletions %u", m
->mDNSStats
.PoofCacheDeletions
);
5714 LogMsgNoIdent("--------------------------------");
5716 LogMsgNoIdent("Multicast packets Sent %u", m
->MulticastPacketsSent
);
5717 LogMsgNoIdent("Multicast packets Received %u", m
->MPktNum
);
5718 LogMsgNoIdent("Remote Subnet packets %u", m
->RemoteSubnet
);
5719 LogMsgNoIdent("QU questions received %u", m
->mDNSStats
.UnicastBitInQueries
);
5720 LogMsgNoIdent("Normal multicast questions %u", m
->mDNSStats
.NormalQueries
);
5721 LogMsgNoIdent("Answers for questions %u", m
->mDNSStats
.MatchingAnswersForQueries
);
5722 LogMsgNoIdent("Unicast responses %u", m
->mDNSStats
.UnicastResponses
);
5723 LogMsgNoIdent("Multicast responses %u", m
->mDNSStats
.MulticastResponses
);
5724 LogMsgNoIdent("Unicast response Demotions %u", m
->mDNSStats
.UnicastDemotedToMulticast
);
5725 LogMsgNoIdent("--------------------------------");
5727 LogMsgNoIdent("Sleeps %u", m
->mDNSStats
.Sleeps
);
5728 LogMsgNoIdent("Wakeups %u", m
->mDNSStats
.Wakes
);
5729 LogMsgNoIdent("Interface UP events %u", m
->mDNSStats
.InterfaceUp
);
5730 LogMsgNoIdent("Interface UP Flap events %u", m
->mDNSStats
.InterfaceUpFlap
);
5731 LogMsgNoIdent("Interface Down events %u", m
->mDNSStats
.InterfaceDown
);
5732 LogMsgNoIdent("Interface DownFlap events %u", m
->mDNSStats
.InterfaceDownFlap
);
5733 LogMsgNoIdent("Cache refresh queries %u", m
->mDNSStats
.CacheRefreshQueries
);
5734 LogMsgNoIdent("Cache refreshed %u", m
->mDNSStats
.CacheRefreshed
);
5735 LogMsgNoIdent("Wakeup on Resolves %u", m
->mDNSStats
.WakeOnResolves
);
5738 mDNSexport
void udsserver_info()
5740 mDNS
*const m
= &mDNSStorage
;
5741 const mDNSs32 now
= mDNS_TimeNow(m
);
5742 mDNSu32 CacheUsed
= 0, CacheActive
= 0, slot
;
5743 int ProxyA
= 0, ProxyD
= 0;
5744 mDNSu32 groupCount
= 0;
5745 mDNSu32 mcastRecordCount
= 0;
5746 mDNSu32 ucastRecordCount
= 0;
5747 const CacheGroup
*cg
;
5748 const CacheRecord
*cr
;
5749 const DNSQuestion
*q
;
5750 const DNameListElem
*d
;
5751 const SearchListElem
*s
;
5753 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
5755 LogMsgNoIdent("------------ Cache -------------");
5756 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
5757 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
5759 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
5761 groupCount
++; // Count one cache entity for the CacheGroup object
5762 for (cr
= cg
->members
; cr
; cr
=cr
->next
)
5764 const mDNSs32 remain
= cr
->resrec
.rroriginalttl
- (now
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
5766 mDNSInterfaceID InterfaceID
= cr
->resrec
.InterfaceID
;
5767 mDNSu32
*const countPtr
= InterfaceID
? &mcastRecordCount
: &ucastRecordCount
;
5768 if (!InterfaceID
&& cr
->resrec
.rDNSServer
&& cr
->resrec
.rDNSServer
->scoped
)
5769 InterfaceID
= cr
->resrec
.rDNSServer
->interface
;
5770 ifname
= InterfaceNameForID(m
, InterfaceID
);
5771 if (cr
->CRActiveQuestion
) CacheActive
++;
5772 PrintOneCacheRecord(cr
, slot
, remain
, ifname
, countPtr
);
5773 PrintCachedRecords(cr
, slot
, remain
, ifname
, countPtr
);
5778 CacheUsed
= groupCount
+ mcastRecordCount
+ ucastRecordCount
;
5779 if (m
->rrcache_totalused
!= CacheUsed
)
5780 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m
->rrcache_totalused
, CacheUsed
);
5781 if (m
->rrcache_active
!= CacheActive
)
5782 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m
->rrcache_active
, CacheActive
);
5783 LogMsgNoIdent("Cache size %u entities; %u in use (%u group, %u multicast, %u unicast); %u referenced by active questions",
5784 m
->rrcache_size
, CacheUsed
, groupCount
, mcastRecordCount
, ucastRecordCount
, CacheActive
);
5786 LogMsgNoIdent("--------- Auth Records ---------");
5787 LogAuthRecords(now
, m
->ResourceRecords
, mDNSNULL
);
5789 LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
5790 LogLocalOnlyAuthRecords(m
);
5792 LogMsgNoIdent("--------- /etc/hosts ---------");
5795 LogMsgNoIdent("------ Duplicate Records -------");
5796 LogAuthRecords(now
, m
->DuplicateRecords
, mDNSNULL
);
5798 LogMsgNoIdent("----- Auth Records Proxied -----");
5799 LogAuthRecords(now
, m
->ResourceRecords
, &ProxyA
);
5801 LogMsgNoIdent("-- Duplicate Records Proxied ---");
5802 LogAuthRecords(now
, m
->DuplicateRecords
, &ProxyD
);
5804 LogMsgNoIdent("---------- Questions -----------");
5805 if (!m
->Questions
) LogMsgNoIdent("<None>");
5811 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
5812 for (q
= m
->Questions
; q
; q
=q
->next
)
5814 mDNSs32 i
= q
->ThisQInterval
/ mDNSPlatformOneSecond
;
5815 mDNSs32 n
= (NextQSendTime(q
) - now
) / mDNSPlatformOneSecond
;
5816 char *ifname
= InterfaceNameForID(m
, q
->InterfaceID
);
5818 if (q
->ThisQInterval
) CacheActive
++;
5819 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s%s",
5821 ifname
? ifname
: mDNSOpaque16IsZero(q
->TargetQID
) ? "" : "-U-",
5822 mDNSOpaque16IsZero(q
->TargetQID
) ? (q
->LongLived
? "l" : " ") : (q
->LongLived
? "L" : "O"),
5823 PrivateQuery(q
) ? "P" : q
->ValidationRequired
? "V" : q
->ValidatingResponse
? "R" : " ",
5824 q
->CurrentAnswers
, q
->validDNSServers
.l
[3], q
->validDNSServers
.l
[2], q
->validDNSServers
.l
[1],
5825 q
->validDNSServers
.l
[0], q
, q
->DuplicateOf
,
5826 q
->SuppressUnusable
, q
->SuppressQuery
, DNSTypeName(q
->qtype
), q
->qname
.c
,
5827 AnonInfoToString(q
->AnonInfo
, anonstr
, sizeof(anonstr
)),
5828 q
->DuplicateOf
? " (dup)" : "");
5830 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed
, CacheUsed
> 1 ? "s" : "", CacheActive
);
5833 LogMsgNoIdent("----- LocalOnly, P2P Questions -----");
5834 if (!m
->LocalOnlyQuestions
) LogMsgNoIdent("<None>");
5835 else for (q
= m
->LocalOnlyQuestions
; q
; q
=q
->next
)
5836 LogMsgNoIdent(" %3s %5d %-6s%##s%s",
5837 q
->InterfaceID
== mDNSInterface_LocalOnly
? "LO ": q
->InterfaceID
== mDNSInterface_BLE
? "BLE": "P2P",
5838 q
->CurrentAnswers
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
5840 LogMsgNoIdent("---- Active UDS Client Requests ----");
5841 if (!all_requests
) LogMsgNoIdent("<None>");
5844 request_state
*req
, *r
;
5845 for (req
= all_requests
; req
; req
=req
->next
)
5847 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
5849 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
) if (r
== req
->primary
) goto foundparent
;
5850 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req
->sd
);
5852 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
5858 LogMsgNoIdent("-------- NAT Traversals --------");
5859 LogMsgNoIdent("ExtAddress %.4a Retry %d Interval %d",
5861 m
->retryGetAddr
? (m
->retryGetAddr
- now
) / mDNSPlatformOneSecond
: 0,
5862 m
->retryIntervalGetAddr
/ mDNSPlatformOneSecond
);
5863 if (m
->NATTraversals
)
5865 const NATTraversalInfo
*nat
;
5866 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
5868 LogMsgNoIdent("%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
5870 nat
->Protocol
? (nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP") : "ADD",
5871 mDNSVal16(nat
->IntPort
),
5872 (nat
->lastSuccessfulProtocol
== NATTProtocolNone
? "None " :
5873 nat
->lastSuccessfulProtocol
== NATTProtocolNATPMP
? "NAT-PMP " :
5874 nat
->lastSuccessfulProtocol
== NATTProtocolUPNPIGD
? "UPnP/IGD" :
5875 nat
->lastSuccessfulProtocol
== NATTProtocolPCP
? "PCP " :
5876 /* else */ "Unknown " ),
5878 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
5879 nat
->retryInterval
/ mDNSPlatformOneSecond
,
5880 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
5881 &nat
->NewAddress
, mDNSVal16(nat
->RequestedPort
),
5882 &nat
->ExternalAddress
, mDNSVal16(nat
->ExternalPort
));
5886 LogMsgNoIdent("--------- AuthInfoList ---------");
5887 if (!m
->AuthInfoList
) LogMsgNoIdent("<None>");
5890 const DomainAuthInfo
*a
;
5891 for (a
= m
->AuthInfoList
; a
; a
= a
->next
)
5893 LogMsgNoIdent("%##s %##s %##s %d %d %.16a%s",
5894 a
->domain
.c
, a
->keyname
.c
,
5895 a
->hostname
.c
, (a
->port
.b
[0] << 8 | a
->port
.b
[1]),
5896 (a
->deltime
? (a
->deltime
- now
) : 0),
5897 &a
->AutoTunnelInnerAddress
, a
->AutoTunnel
? " AutoTunnel" : "");
5901 #if APPLE_OSX_mDNSResponder
5902 LogMsgNoIdent("--------- TunnelClients --------");
5903 if (!m
->TunnelClients
) LogMsgNoIdent("<None>");
5906 const ClientTunnel
*c
;
5907 for (c
= m
->TunnelClients
; c
; c
= c
->next
)
5908 LogMsgNoIdent("%##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
5909 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
);
5911 #endif // APPLE_OSX_mDNSResponder
5913 LogMsgNoIdent("---------- Misc State ----------");
5915 LogMsgNoIdent("PrimaryMAC: %.6a", &m
->PrimaryMAC
);
5917 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
5919 m
->SleepState
== SleepState_Awake
? "Awake" :
5920 m
->SleepState
== SleepState_Transferring
? "Transferring" :
5921 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?",
5924 if (!m
->SPSSocket
) LogMsgNoIdent("Not offering Sleep Proxy Service");
5925 #ifndef SPC_DISABLED
5926 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m
->SPSRecords
.RR_SRV
.resrec
.name
->c
);
5928 if (m
->ProxyRecords
== ProxyA
+ ProxyD
) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
);
5929 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
, m
->ProxyRecords
);
5931 LogMsgNoIdent("------ Auto Browse Domains -----");
5932 if (!AutoBrowseDomains
) LogMsgNoIdent("<None>");
5933 else for (d
=AutoBrowseDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
5935 LogMsgNoIdent("--- Auto Registration Domains --");
5936 if (!AutoRegistrationDomains
) LogMsgNoIdent("<None>");
5937 else for (d
=AutoRegistrationDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
5939 LogMsgNoIdent("--- Search Domains --");
5940 if (!SearchList
) LogMsgNoIdent("<None>");
5943 for (s
=SearchList
; s
; s
=s
->next
)
5945 char *ifname
= InterfaceNameForID(m
, s
->InterfaceID
);
5946 LogMsgNoIdent("%##s %s", s
->domain
.c
, ifname
? ifname
: "");
5949 LogInfo("--- Trust Anchors ---");
5950 if (!m
->TrustAnchors
)
5957 mDNSu8 fromTimeBuf
[64];
5958 mDNSu8 untilTimeBuf
[64];
5960 for (ta
=m
->TrustAnchors
; ta
; ta
=ta
->next
)
5962 mDNSPlatformFormatTime((unsigned long)ta
->validFrom
, fromTimeBuf
, sizeof(fromTimeBuf
));
5963 mDNSPlatformFormatTime((unsigned long)ta
->validUntil
, untilTimeBuf
, sizeof(untilTimeBuf
));
5964 LogInfo("%##s %d %d %d %d %s %s", ta
->zone
.c
, ta
->rds
.keyTag
,
5965 ta
->rds
.alg
, ta
->rds
.digestType
, ta
->digestLen
, fromTimeBuf
, untilTimeBuf
);
5969 LogInfo("--- DNSSEC Statistics ---");
5971 LogMsgNoIdent("Unicast Cache size %u", m
->rrcache_totalused_unicast
);
5972 LogInfo("DNSSEC Cache size %u", m
->DNSSECStats
.TotalMemUsed
);
5973 if (m
->rrcache_totalused_unicast
)
5974 LogInfo("DNSSEC usage percentage %u", ((unsigned long)(m
->DNSSECStats
.TotalMemUsed
* 100))/m
->rrcache_totalused_unicast
);
5975 LogInfo("DNSSEC Extra Packets (0 to 2) %u", m
->DNSSECStats
.ExtraPackets0
);
5976 LogInfo("DNSSEC Extra Packets (3 to 6) %u", m
->DNSSECStats
.ExtraPackets3
);
5977 LogInfo("DNSSEC Extra Packets (7 to 9) %u", m
->DNSSECStats
.ExtraPackets7
);
5978 LogInfo("DNSSEC Extra Packets ( >= 10) %u", m
->DNSSECStats
.ExtraPackets10
);
5980 LogInfo("DNSSEC Latency (0 to 4ms) %u", m
->DNSSECStats
.Latency0
);
5981 LogInfo("DNSSEC Latency (4 to 9ms) %u", m
->DNSSECStats
.Latency5
);
5982 LogInfo("DNSSEC Latency (10 to 19ms) %u", m
->DNSSECStats
.Latency10
);
5983 LogInfo("DNSSEC Latency (20 to 49ms) %u", m
->DNSSECStats
.Latency20
);
5984 LogInfo("DNSSEC Latency (50 to 99ms) %u", m
->DNSSECStats
.Latency50
);
5985 LogInfo("DNSSEC Latency ( >=100ms) %u", m
->DNSSECStats
.Latency100
);
5987 LogInfo("DNSSEC Secure Status %u", m
->DNSSECStats
.SecureStatus
);
5988 LogInfo("DNSSEC Insecure Status %u", m
->DNSSECStats
.InsecureStatus
);
5989 LogInfo("DNSSEC Indeterminate Status %u", m
->DNSSECStats
.IndeterminateStatus
);
5990 LogInfo("DNSSEC Bogus Status %u", m
->DNSSECStats
.BogusStatus
);
5991 LogInfo("DNSSEC NoResponse Status %u", m
->DNSSECStats
.NoResponseStatus
);
5992 LogInfo("DNSSEC Probes sent %u", m
->DNSSECStats
.NumProbesSent
);
5993 LogInfo("DNSSEC Msg Size (<=1024) %u", m
->DNSSECStats
.MsgSize0
);
5994 LogInfo("DNSSEC Msg Size (<=2048) %u", m
->DNSSECStats
.MsgSize1
);
5995 LogInfo("DNSSEC Msg Size (> 2048) %u", m
->DNSSECStats
.MsgSize2
);
5997 LogMDNSStatistics(m
);
5999 LogMsgNoIdent("---- Task Scheduling Timers ----");
6001 #if BONJOUR_ON_DEMAND
6002 LogMsgNoIdent("BonjourEnabled %d", m
->BonjourEnabled
);
6003 #endif // BONJOUR_ON_DEMAND
6005 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
6006 LogMsgNoIdent("EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery
);
6007 LogMsgNoIdent("DefaultToBLETriggered %d", DefaultToBLETriggered
);
6008 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
6010 if (!m
->NewQuestions
)
6011 LogMsgNoIdent("NewQuestion <NONE>");
6013 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
6014 m
->NewQuestions
->DelayAnswering
, m
->NewQuestions
->DelayAnswering
-now
,
6015 m
->NewQuestions
->qname
.c
, DNSTypeName(m
->NewQuestions
->qtype
));
6017 if (!m
->NewLocalOnlyQuestions
)
6018 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
6020 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
6021 m
->NewLocalOnlyQuestions
->qname
.c
, DNSTypeName(m
->NewLocalOnlyQuestions
->qtype
));
6023 if (!m
->NewLocalRecords
)
6024 LogMsgNoIdent("NewLocalRecords <NONE>");
6026 LogMsgNoIdent("NewLocalRecords %02X %s", m
->NewLocalRecords
->resrec
.RecordType
, ARDisplayString(m
, m
->NewLocalRecords
));
6028 LogMsgNoIdent("SPSProxyListChanged%s", m
->SPSProxyListChanged
? "" : " <NONE>");
6029 LogMsgNoIdent("LocalRemoveEvents%s", m
->LocalRemoveEvents
? "" : " <NONE>");
6030 LogMsgNoIdent("m->AutoTunnelRelayAddr %.16a", &m
->AutoTunnelRelayAddr
);
6031 LogMsgNoIdent("m->WABBrowseQueriesCount %d", m
->WABBrowseQueriesCount
);
6032 LogMsgNoIdent("m->WABLBrowseQueriesCount %d", m
->WABLBrowseQueriesCount
);
6033 LogMsgNoIdent("m->WABRegQueriesCount %d", m
->WABRegQueriesCount
);
6034 LogMsgNoIdent("m->AutoTargetServices %d", m
->AutoTargetServices
);
6036 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
6037 LogMsgNoIdent("m->timenow %08X %11d", now
, now
);
6038 LogMsgNoIdent("m->timenow_adjust %08X %11d", m
->timenow_adjust
, m
->timenow_adjust
);
6039 LogTimer("m->NextScheduledEvent ", m
->NextScheduledEvent
);
6041 #ifndef UNICAST_DISABLED
6042 LogTimer("m->NextuDNSEvent ", m
->NextuDNSEvent
);
6043 LogTimer("m->NextSRVUpdate ", m
->NextSRVUpdate
);
6044 LogTimer("m->NextScheduledNATOp ", m
->NextScheduledNATOp
);
6045 LogTimer("m->retryGetAddr ", m
->retryGetAddr
);
6048 LogTimer("m->NextCacheCheck ", m
->NextCacheCheck
);
6049 LogTimer("m->NextScheduledSPS ", m
->NextScheduledSPS
);
6050 LogTimer("m->NextScheduledKA ", m
->NextScheduledKA
);
6052 #if BONJOUR_ON_DEMAND
6053 LogTimer("m->NextBonjourDisableTime ", m
->NextBonjourDisableTime
);
6054 #endif // BONJOUR_ON_DEMAND
6056 LogTimer("m->NextScheduledSPRetry ", m
->NextScheduledSPRetry
);
6057 LogTimer("m->DelaySleep ", m
->DelaySleep
);
6059 LogTimer("m->NextScheduledQuery ", m
->NextScheduledQuery
);
6060 LogTimer("m->NextScheduledProbe ", m
->NextScheduledProbe
);
6061 LogTimer("m->NextScheduledResponse", m
->NextScheduledResponse
);
6063 LogTimer("m->SuppressSending ", m
->SuppressSending
);
6064 LogTimer("m->SuppressProbes ", m
->SuppressProbes
);
6065 LogTimer("m->ProbeFailTime ", m
->ProbeFailTime
);
6066 LogTimer("m->DelaySleep ", m
->DelaySleep
);
6067 LogTimer("m->SleepLimit ", m
->SleepLimit
);
6068 LogTimer("m->NextScheduledStopTime ", m
->NextScheduledStopTime
);
6071 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6072 mDNSexport
void uds_validatelists(void)
6074 const request_state
*req
, *p
;
6075 for (req
= all_requests
; req
; req
=req
->next
)
6077 if (req
->next
== (request_state
*)~0 || (req
->sd
< 0 && req
->sd
!= -2))
6078 LogMemCorruption("UDS request list: %p is garbage (%d)", req
, req
->sd
);
6080 if (req
->primary
== req
)
6081 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req
, req
->sd
);
6083 if (req
->primary
&& req
->replies
)
6084 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
6085 req
, req
->sd
, req
->primary
&& req
->replies
);
6089 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req
, p
, req
->sd
);
6090 else if (p
&& (p
->next
== (request_state
*)~0 || (p
->sd
< 0 && p
->sd
!= -2)))
6091 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req
, p
, p
->sd
);
6094 for (rep
= req
->replies
; rep
; rep
=rep
->next
)
6095 if (rep
->next
== (reply_state
*)~0)
6096 LogMemCorruption("UDS req->replies: %p is garbage", rep
);
6098 if (req
->terminate
== connection_termination
)
6100 registered_record_entry
*r
;
6101 for (r
= req
->u
.reg_recs
; r
; r
=r
->next
)
6102 if (r
->next
== (registered_record_entry
*)~0)
6103 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r
);
6105 else if (req
->terminate
== regservice_termination_callback
)
6107 service_instance
*s
;
6108 for (s
= req
->u
.servicereg
.instances
; s
; s
=s
->next
)
6109 if (s
->next
== (service_instance
*)~0)
6110 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s
);
6112 else if (req
->terminate
== browse_termination_callback
)
6115 for (b
= req
->u
.browser
.browsers
; b
; b
=b
->next
)
6116 if (b
->next
== (browser_t
*)~0)
6117 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b
);
6122 for (d
= SCPrefBrowseDomains
; d
; d
=d
->next
)
6123 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
6124 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
6127 for (b
= LocalDomainEnumRecords
; b
; b
=b
->next
)
6128 if (b
->next
== (ARListElem
*)~0 || b
->ar
.resrec
.name
->c
[0] > 63)
6129 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b
, b
->ar
.resrec
.name
->c
[0]);
6131 for (d
= AutoBrowseDomains
; d
; d
=d
->next
)
6132 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
6133 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
6135 for (d
= AutoRegistrationDomains
; d
; d
=d
->next
)
6136 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
6137 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
6139 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6141 mDNSlocal
int send_msg(request_state
*const req
)
6143 reply_state
*const rep
= req
->replies
; // Send the first waiting reply
6146 ConvertHeaderBytes(rep
->mhdr
);
6147 nwriten
= send(req
->sd
, (char *)&rep
->mhdr
+ rep
->nwriten
, rep
->totallen
- rep
->nwriten
, 0);
6148 ConvertHeaderBytes(rep
->mhdr
);
6152 if (dnssd_errno
== dnssd_EINTR
|| dnssd_errno
== dnssd_EWOULDBLOCK
) nwriten
= 0;
6155 #if !defined(PLATFORM_NO_EPIPE)
6156 if (dnssd_errno
== EPIPE
)
6157 return(req
->ts
= t_terminated
);
6161 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
6162 rep
->totallen
- rep
->nwriten
, rep
->totallen
, req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
6167 rep
->nwriten
+= nwriten
;
6168 return (rep
->nwriten
== rep
->totallen
) ? t_complete
: t_morecoming
;
6171 mDNSexport mDNSs32
udsserver_idle(mDNSs32 nextevent
)
6173 mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
6174 request_state
**req
= &all_requests
;
6178 request_state
*const r
= *req
;
6180 if (r
->terminate
== resolve_termination_callback
)
6181 if (r
->u
.resolve
.ReportTime
&& now
- r
->u
.resolve
.ReportTime
>= 0)
6183 r
->u
.resolve
.ReportTime
= 0;
6184 // if client received results and resolve still active
6185 if (r
->u
.resolve
.txt
&& r
->u
.resolve
.srv
)
6186 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 // Note: Only primary req's have reply lists, not subordinate req's.
6190 while (r
->replies
) // Send queued replies
6192 transfer_state result
;
6193 if (r
->replies
->next
)
6194 r
->replies
->rhdr
->flags
|= dnssd_htonl(kDNSServiceFlagsMoreComing
);
6195 result
= send_msg(r
); // Returns t_morecoming if buffer full because client is not reading
6196 if (result
== t_complete
)
6198 reply_state
*fptr
= r
->replies
;
6199 r
->replies
= r
->replies
->next
;
6200 freeL("reply_state/udsserver_idle", fptr
);
6201 r
->time_blocked
= 0; // reset failure counter after successful send
6202 r
->unresponsiveness_reports
= 0;
6205 else if (result
== t_terminated
)
6207 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 else if (result
== t_error
)
6212 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r
->sd
, r
->process_id
, r
->pid_name
);
6219 if (r
->replies
) // If we failed to send everything, check our time_blocked timer
6221 if (nextevent
- now
> mDNSPlatformOneSecond
)
6222 nextevent
= now
+ mDNSPlatformOneSecond
;
6224 if (mDNSStorage
.SleepState
!= SleepState_Awake
)
6225 r
->time_blocked
= 0;
6226 else if (!r
->time_blocked
)
6227 r
->time_blocked
= NonZeroTime(now
);
6228 else if (now
- r
->time_blocked
>= 10 * mDNSPlatformOneSecond
* (r
->unresponsiveness_reports
+1))
6231 struct reply_state
*x
= r
->replies
;
6237 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
6238 r
->sd
, r
->process_id
, r
->pid_name
, (now
- r
->time_blocked
) / mDNSPlatformOneSecond
, num
, num
== 1 ? "y" : "ies");
6239 if (++r
->unresponsiveness_reports
>= 60)
6241 LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r
->sd
, r
->process_id
, r
->pid_name
);
6248 if (!dnssd_SocketValid(r
->sd
)) // If this request is finished, unlink it from the list and free the memory
6250 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
6252 freeL("request_state/udsserver_idle", r
);
6260 struct CompileTimeAssertionChecks_uds_daemon
6262 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
6263 // other overly-large structures instead of having a pointer to them, can inadvertently
6264 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
6265 char sizecheck_request_state
[(sizeof(request_state
) <= 3696) ? 1 : -1];
6266 char sizecheck_registered_record_entry
[(sizeof(registered_record_entry
) <= 60) ? 1 : -1];
6267 char sizecheck_service_instance
[(sizeof(service_instance
) <= 6552) ? 1 : -1];
6268 char sizecheck_browser_t
[(sizeof(browser_t
) <= 1432) ? 1 : -1];
6269 char sizecheck_reply_hdr
[(sizeof(reply_hdr
) <= 12) ? 1 : -1];
6270 char sizecheck_reply_state
[(sizeof(reply_state
) <= 64) ? 1 : -1];
6274 #include "../unittests/uds_daemon_ut.c"