2 * Copyright (c) 2003-2019 Apple Inc. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #define usleep(X) Sleep(((X)+999)/1000)
23 #include <sys/ioctl.h>
24 #include <sys/types.h>
26 #include <sys/resource.h>
32 #include "mDNSEmbeddedAPI.h"
33 #include "DNSCommon.h"
35 #include "uds_daemon.h"
36 #include "dns_sd_internal.h"
38 // Apple-specific functionality, not required for other platforms
39 #if APPLE_OSX_mDNSResponder
41 #include <sys/ucred.h>
43 #define NO_PID_FILE // We need to signal that this platform has no PID file, and not just that we are taking the default
48 #include <sys/un.h> // for LOCAL_PEEREPID
49 #include <sys/socket.h> // for getsockopt
50 #include <sys/proc_info.h> // for struct proc_bsdshortinfo
51 #include <libproc.h> // for proc_pidinfo()
52 #endif //LOCAL_PEEREPID
54 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
58 #if APPLE_OSX_mDNSResponder
62 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
63 // User IDs for real user accounts start at 501 and count up from there
64 #define SystemUID(X) ((X) <= 500)
66 // ***************************************************************************
67 #if COMPILER_LIKES_PRAGMA_MARK
69 #pragma mark - Globals
73 mDNSexport mDNS mDNSStorage
;
74 mDNSexport
const char ProgramName
[] = "mDNSResponder";
76 #if defined(USE_TCP_LOOPBACK)
77 static char* boundPath
= NULL
;
79 static char* boundPath
= MDNS_UDS_SERVERPATH
;
82 #define MDNS_UDS_SERVERPATH_DEBUG "/var/tmp/mDNSResponder"
84 static dnssd_sock_t listenfd
= dnssd_InvalidSocket
;
85 static request_state
*all_requests
= NULL
;
87 struct proc_bsdshortinfo proc
;
88 #endif //LOCAL_PEEREPID
89 mDNSlocal
void set_peer_pid(request_state
*request
);
90 mDNSlocal
void LogMcastClientInfo(request_state
*req
);
91 mDNSlocal
void GetMcastClients(request_state
*req
);
92 static mDNSu32 mcount
; // tracks the current active mcast operations for McastLogging
93 static mDNSu32 i_mcount
; // sets mcount when McastLogging is enabled(PROF signal is sent)
94 static mDNSu32 n_mrecords
; // tracks the current active mcast records for McastLogging
95 static mDNSu32 n_mquests
; // tracks the current active mcast questions for McastLogging
98 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
99 mDNSu32 curr_num_regservices
= 0;
100 mDNSu32 max_num_regservices
= 0;
104 // Note asymmetry here between registration and browsing.
105 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
106 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
107 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
108 // 1. SCPrefBrowseDomains (local configuration data)
109 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
110 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
111 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
113 mDNSexport DNameListElem
*AutoRegistrationDomains
; // Domains where we automatically register for empty-string registrations
115 static DNameListElem
*SCPrefBrowseDomains
; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
116 static ARListElem
*LocalDomainEnumRecords
; // List of locally-generated PTR records to augment those we learn from the network
117 mDNSexport DNameListElem
*AutoBrowseDomains
; // List created from those local-only PTR records plus records we get from the network
119 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
120 // n get_string() calls w/o buffer overrun
121 // initialization, setup/teardown functions
123 // If a platform specifies its own PID file name, we use that
125 #define PID_FILE "/var/run/mDNSResponder.pid"
128 // ***************************************************************************
129 #if COMPILER_LIKES_PRAGMA_MARK
131 #pragma mark - General Utility Functions
134 mDNSlocal
void FatalError(char *errmsg
)
136 LogMsg("%s: %s", errmsg
, dnssd_strerror(dnssd_errno
));
140 mDNSlocal mDNSu32
dnssd_htonl(mDNSu32 l
)
143 char *data
= (char*) &ret
;
144 put_uint32(l
, &data
);
148 // hack to search-replace perror's to LogMsg's
149 mDNSlocal
void my_perror(char *errmsg
)
151 LogMsg("%s: %d (%s)", errmsg
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
154 // Throttled version of my_perror: Logs once every 250 msgs
155 mDNSlocal
void my_throttled_perror(char *err_msg
)
157 static int uds_throttle_count
= 0;
158 if ((uds_throttle_count
++ % 250) == 0)
162 // LogMcastQuestion/LogMcastQ should be called after the DNSQuestion struct is initialized(especially for q->TargetQID)
163 // Hence all calls are made after mDNS_StartQuery()/mDNS_StopQuery()/mDNS_StopBrowse() is called.
164 mDNSlocal
void LogMcastQuestion(const DNSQuestion
*const q
, request_state
*req
, q_state status
)
166 if (mDNSOpaque16IsZero(q
->TargetQID
)) // Check for Mcast Query
168 mDNSBool mflag
= mDNSfalse
;
169 if (status
== q_start
)
178 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status
? "+Question" : "-Question", q
->qname
.c
, DNSTypeName(q
->qtype
),
179 q
->InterfaceID
== mDNSInterface_LocalOnly
? "lo" :
180 q
->InterfaceID
== mDNSInterface_P2P
? "p2p" :
181 q
->InterfaceID
== mDNSInterface_BLE
? "BLE" :
182 q
->InterfaceID
== mDNSInterface_Any
? "any" : InterfaceNameForID(&mDNSStorage
, q
->InterfaceID
),
183 req
->process_id
, req
->pid_name
);
184 LogMcastStateInfo(mflag
, mDNSfalse
, mDNSfalse
);
189 // LogMcastService/LogMcastS should be called after the AuthRecord struct is initialized
190 // Hence all calls are made after mDNS_Register()/ just before mDNS_Deregister()
191 mDNSlocal
void LogMcastService(const AuthRecord
*const ar
, request_state
*req
, reg_state status
)
193 if (!AuthRecord_uDNS(ar
)) // Check for Mcast Service
195 mDNSBool mflag
= mDNSfalse
;
196 if (status
== reg_start
)
205 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status
? "+Service" : "-Service", ar
->resrec
.name
->c
, DNSTypeName(ar
->resrec
.rrtype
),
206 ar
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
? "lo" :
207 ar
->resrec
.InterfaceID
== mDNSInterface_P2P
? "p2p" :
208 ar
->resrec
.InterfaceID
== mDNSInterface_BLE
? "BLE" :
209 ar
->resrec
.InterfaceID
== mDNSInterface_Any
? "all" : InterfaceNameForID(&mDNSStorage
, ar
->resrec
.InterfaceID
),
210 req
->process_id
, req
->pid_name
);
211 LogMcastStateInfo(mflag
, mDNSfalse
, mDNSfalse
);
216 // For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
217 mDNSexport
void LogMcastStateInfo(mDNSBool mflag
, mDNSBool start
, mDNSBool mstatelog
)
219 mDNS
*const m
= &mDNSStorage
;
224 LogMcastNoIdent("<None>");
228 request_state
*req
, *r
;
229 for (req
= all_requests
; req
; req
=req
->next
)
231 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
233 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
)
234 if (r
== req
->primary
)
237 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
238 GetMcastClients(req
);
241 LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords
, n_mquests
);
242 n_mrecords
= n_mquests
= 0; // Reset the values
247 static mDNSu32 i_mpktnum
;
251 // mcount is initialized to 0 when the PROF signal is sent since mcount could have
252 // wrong value if MulticastLogging is disabled and then re-enabled
253 LogMcastNoIdent("--- START MCAST STATE LOG ---");
257 LogMcastNoIdent("<None>");
261 request_state
*req
, *r
;
262 for (req
= all_requests
; req
; req
=req
->next
)
264 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
266 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
)
267 if (r
== req
->primary
)
269 LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req
->sd
);
271 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
272 LogMcastClientInfo(req
);
275 if(!mcount
) // To initially set mcount
280 i_mpktnum
= m
->MPktNum
;
281 LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount
, i_mpktnum
);
284 LogMcastNoIdent("--- MCOUNT[%d]: CMPKTNUM[%d] - IMPKTNUM[%d] = [%d]PKTS ---", mcount
, m
->MPktNum
, i_mpktnum
, (m
->MPktNum
- i_mpktnum
));
285 LogMcastNoIdent("--- END MCAST STATE LOG ---");
289 mDNSlocal
void abort_request(request_state
*req
)
291 if (req
->terminate
== (req_termination_fn
) ~0)
293 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
294 "[R%d] abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req
->request_id
, req
, req
->terminate
);
298 // First stop whatever mDNSCore operation we were doing
299 // If this is actually a shared connection operation, then its req->terminate function will scan
300 // the all_requests list and terminate any subbordinate operations sharing this file descriptor
301 if (req
->terminate
) req
->terminate(req
);
303 if (!dnssd_SocketValid(req
->sd
))
305 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
306 "[R%d] abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req
->request_id
, req
, req
->sd
);
310 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
313 if (req
->errsd
!= req
->sd
)
315 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
316 "[R%d] Removing FD %d and closing errsd %d", req
->request_id
, req
->sd
, req
->errsd
);
320 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
321 "[R%d] Removing FD %d", req
->request_id
, req
->sd
);
323 udsSupportRemoveFDFromEventLoop(req
->sd
, req
->platform_data
); // Note: This also closes file descriptor req->sd for us
324 if (req
->errsd
!= req
->sd
) { dnssd_close(req
->errsd
); req
->errsd
= req
->sd
; }
326 while (req
->replies
) // free pending replies
328 reply_state
*ptr
= req
->replies
;
329 req
->replies
= req
->replies
->next
;
330 freeL("reply_state (abort)", ptr
);
334 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
335 #if MDNS_MALLOC_DEBUGGING
336 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MDNS_MALLOC_DEBUGGING uses
337 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
339 #error This will not work on Windows, look at IsValidSocket in mDNSShared/CommonServices.h to see why
341 req
->sd
= req
->errsd
= -2;
343 req
->sd
= req
->errsd
= dnssd_InvalidSocket
;
345 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
346 req
->terminate
= (req_termination_fn
) ~0;
350 mDNSexport
void SetDebugBoundPath(void)
352 #if !defined(USE_TCP_LOOPBACK)
353 boundPath
= MDNS_UDS_SERVERPATH_DEBUG
;
357 mDNSexport
int IsDebugSocketInUse(void)
359 #if !defined(USE_TCP_LOOPBACK)
360 return !strcmp(boundPath
, MDNS_UDS_SERVERPATH_DEBUG
);
367 mDNSlocal
void AbortUnlinkAndFree(request_state
*req
)
369 request_state
**p
= &all_requests
;
371 while (*p
&& *p
!= req
) p
=&(*p
)->next
;
372 if (*p
) { *p
= req
->next
; freeL("request_state/AbortUnlinkAndFree", req
); }
373 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req
);
376 mDNSlocal reply_state
*create_reply(const reply_op_t op
, const size_t datalen
, request_state
*const request
)
380 if ((unsigned)datalen
< sizeof(reply_hdr
))
382 LogMsg("ERROR: create_reply - data length less than length of required fields");
386 reply
= (reply_state
*) callocL("reply_state", sizeof(reply_state
) + datalen
- sizeof(reply_hdr
));
387 if (!reply
) FatalError("ERROR: calloc");
389 reply
->next
= mDNSNULL
;
390 reply
->totallen
= (mDNSu32
)datalen
+ sizeof(ipc_msg_hdr
);
393 reply
->mhdr
->version
= VERSION
;
394 reply
->mhdr
->datalen
= (mDNSu32
)datalen
;
395 reply
->mhdr
->ipc_flags
= 0;
396 reply
->mhdr
->op
= op
;
397 reply
->mhdr
->client_context
= request
->hdr
.client_context
;
398 reply
->mhdr
->reg_index
= 0;
403 // Append a reply to the list in a request object
404 // If our request is sharing a connection, then we append our reply_state onto the primary's list
405 // If the request does not want asynchronous replies, then the reply is freed instead of being appended to any list.
406 mDNSlocal
void append_reply(request_state
*req
, reply_state
*rep
)
413 freeL("reply_state/append_reply", rep
);
417 r
= req
->primary
? req
->primary
: req
;
419 while (*ptr
) ptr
= &(*ptr
)->next
;
424 // Generates a response message giving name, type, domain, plus interface index,
425 // suitable for a browse result or service registration result.
426 // On successful completion rep is set to point to a malloc'd reply_state struct
427 mDNSlocal mStatus
GenerateNTDResponse(const domainname
*const servicename
, const mDNSInterfaceID id
,
428 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
431 domainname type
, dom
;
433 if (!DeconstructServiceName(servicename
, &name
, &type
, &dom
))
434 return kDNSServiceErr_Invalid
;
437 char namestr
[MAX_DOMAIN_LABEL
+1];
438 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
439 char domstr
[MAX_ESCAPED_DOMAIN_NAME
];
443 ConvertDomainLabelToCString_unescaped(&name
, namestr
);
444 ConvertDomainNameToCString(&type
, typestr
);
445 ConvertDomainNameToCString(&dom
, domstr
);
447 // Calculate reply data length
448 len
= sizeof(DNSServiceFlags
);
449 len
+= sizeof(mDNSu32
); // if index
450 len
+= sizeof(DNSServiceErrorType
);
451 len
+= (int) (strlen(namestr
) + 1);
452 len
+= (int) (strlen(typestr
) + 1);
453 len
+= (int) (strlen(domstr
) + 1);
455 // Build reply header
456 *rep
= create_reply(op
, len
, request
);
457 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
458 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
, mDNSfalse
));
459 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
462 data
= (char *)&(*rep
)->rhdr
[1];
463 put_string(namestr
, &data
);
464 put_string(typestr
, &data
);
465 put_string(domstr
, &data
);
467 return mStatus_NoError
;
471 mDNSlocal
void GenerateBrowseReply(const domainname
*const servicename
, const mDNSInterfaceID id
,
472 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
474 char namestr
[MAX_DOMAIN_LABEL
+1];
475 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
476 static const char domstr
[] = ".";
482 // 1. Put first label in namestr
483 ConvertDomainLabelToCString_unescaped((const domainlabel
*)servicename
, namestr
);
485 // 2. Put second label and "local" into typestr
486 mDNS_snprintf(typestr
, sizeof(typestr
), "%#s.local.", SecondLabel(servicename
));
488 // Calculate reply data length
489 len
= sizeof(DNSServiceFlags
);
490 len
+= sizeof(mDNSu32
); // if index
491 len
+= sizeof(DNSServiceErrorType
);
492 len
+= (int) (strlen(namestr
) + 1);
493 len
+= (int) (strlen(typestr
) + 1);
494 len
+= (int) (strlen(domstr
) + 1);
496 // Build reply header
497 *rep
= create_reply(op
, len
, request
);
498 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
499 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
, mDNSfalse
));
500 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
503 data
= (char *)&(*rep
)->rhdr
[1];
504 put_string(namestr
, &data
);
505 put_string(typestr
, &data
);
506 put_string(domstr
, &data
);
509 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
510 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
511 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
512 mDNSlocal AuthRecord
*read_rr_from_ipc_msg(request_state
*request
, int GetTTL
, int validate_flags
)
514 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
515 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
516 char name
[MAX_ESCAPED_DOMAIN_NAME
];
517 int str_err
= get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
));
518 mDNSu16 type
= get_uint16(&request
->msgptr
, request
->msgend
);
519 mDNSu16
class = get_uint16(&request
->msgptr
, request
->msgend
);
520 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
521 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
522 mDNSu32 ttl
= GetTTL
? get_uint32(&request
->msgptr
, request
->msgend
) : 0;
523 size_t storage_size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
525 mDNSInterfaceID InterfaceID
;
529 request
->flags
= flags
;
530 request
->interfaceIndex
= interfaceIndex
;
532 if (str_err
) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL
; }
534 if (!request
->msgptr
) { LogMsg("Error reading Resource Record from client"); return NULL
; }
536 if (validate_flags
&&
537 !((flags
& kDNSServiceFlagsShared
) == kDNSServiceFlagsShared
) &&
538 !((flags
& kDNSServiceFlagsUnique
) == kDNSServiceFlagsUnique
) &&
539 !((flags
& kDNSServiceFlagsKnownUnique
) == kDNSServiceFlagsKnownUnique
))
541 LogMsg("ERROR: Bad resource record flags (must be one of either kDNSServiceFlagsShared, kDNSServiceFlagsUnique or kDNSServiceFlagsKnownUnique)");
544 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
546 // The registration is scoped to a specific interface index, but the interface is not currently on our list.
547 if ((InterfaceID
== mDNSInterface_Any
) && (interfaceIndex
!= kDNSServiceInterfaceIndexAny
))
549 // On Apple platforms, an interface's mDNSInterfaceID is equal to its index. Using an interface index that isn't
550 // currently valid will cause the registration to take place as soon as it becomes valid. On other platforms,
551 // mDNSInterfaceID is actually a pointer to a platform-specific interface object, but we don't know what the pointer
552 // for the interface index will be ahead of time. For now, just return NULL to indicate an error condition since the
553 // interface index is invalid. Otherwise, the registration would be performed on all interfaces.
554 #if APPLE_OSX_mDNSResponder
555 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
560 rr
= (AuthRecord
*) callocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord
) - sizeof(RDataBody
) + storage_size
);
561 if (!rr
) FatalError("ERROR: calloc");
563 if (InterfaceID
== mDNSInterface_LocalOnly
)
564 artype
= AuthRecordLocalOnly
;
565 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
566 artype
= AuthRecordP2P
;
567 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
)
568 && (flags
& kDNSServiceFlagsIncludeAWDL
))
569 artype
= AuthRecordAnyIncludeAWDLandP2P
;
570 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
))
571 artype
= AuthRecordAnyIncludeP2P
;
572 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeAWDL
))
573 artype
= AuthRecordAnyIncludeAWDL
;
575 artype
= AuthRecordAny
;
577 if (flags
& kDNSServiceFlagsShared
)
578 recordType
= (mDNSu8
) kDNSRecordTypeShared
;
579 else if (flags
& kDNSServiceFlagsKnownUnique
)
580 recordType
= (mDNSu8
) kDNSRecordTypeKnownUnique
;
582 recordType
= (mDNSu8
) kDNSRecordTypeUnique
;
584 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, type
, 0, recordType
, artype
, mDNSNULL
, mDNSNULL
);
586 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, name
))
588 LogMsg("ERROR: bad name: %s", name
);
589 freeL("AuthRecord/read_rr_from_ipc_msg", rr
);
593 if (flags
& kDNSServiceFlagsAllowRemoteQuery
) rr
->AllowRemoteQuery
= mDNStrue
;
594 rr
->resrec
.rrclass
= class;
595 rr
->resrec
.rdlength
= rdlen
;
596 rr
->resrec
.rdata
->MaxRDLength
= rdlen
;
597 mDNSPlatformMemCopy(rr
->resrec
.rdata
->u
.data
, rdata
, rdlen
);
598 if (GetTTL
) rr
->resrec
.rroriginalttl
= ttl
;
599 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
600 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Sets rr->rdatahash for us
604 mDNSlocal
int build_domainname_from_strings(domainname
*srv
, char *name
, char *regtype
, char *domain
)
609 if (!MakeDomainLabelFromLiteralString(&n
, name
)) return -1;
610 if (!MakeDomainNameFromDNSNameString(&t
, regtype
)) return -1;
611 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return -1;
612 if (!ConstructServiceName(srv
, &n
, &t
, &d
)) return -1;
616 mDNSlocal
void send_all(dnssd_sock_t s
, const char *ptr
, int len
)
618 int n
= send(s
, ptr
, len
, 0);
619 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
620 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
621 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
623 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
624 s
, n
, len
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
628 mDNSlocal mDNSBool
AuthorizedDomain(const request_state
* const request
, const domainname
* const d
, const DNameListElem
* const doms
)
630 const DNameListElem
*delem
= mDNSNULL
;
631 int bestDelta
= -1; // the delta of the best match, lower is better
633 mDNSBool allow
= mDNSfalse
;
635 if (SystemUID(request
->uid
)) return mDNStrue
;
637 dLabels
= CountLabels(d
);
638 for (delem
= doms
; delem
; delem
= delem
->next
)
642 int delemLabels
= CountLabels(&delem
->name
);
643 int delta
= dLabels
- delemLabels
;
644 if ((bestDelta
== -1 || delta
<= bestDelta
) && SameDomainName(&delem
->name
, SkipLeadingLabels(d
, delta
)))
647 allow
= (allow
|| (delem
->uid
== request
->uid
));
652 return bestDelta
== -1 ? mDNStrue
: allow
;
656 // ***************************************************************************
657 #if COMPILER_LIKES_PRAGMA_MARK
659 #pragma mark - external helpers
662 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
663 mDNSlocal
void external_start_advertising_helper(service_instance
*const instance
)
665 AuthRecord
*st
= instance
->subtypes
;
666 ExtraResourceRecord
*e
;
669 if (mDNSIPPortIsZero(instance
->request
->u
.servicereg
.port
))
671 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
675 if (instance
->external_advertise
) LogMsg("external_start_advertising_helper: external_advertise already set!");
677 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
678 external_start_advertising_service(&st
[i
].resrec
, instance
->request
->flags
);
680 external_start_advertising_service(&instance
->srs
.RR_PTR
.resrec
, instance
->request
->flags
);
681 external_start_advertising_service(&instance
->srs
.RR_SRV
.resrec
, instance
->request
->flags
);
682 external_start_advertising_service(&instance
->srs
.RR_TXT
.resrec
, instance
->request
->flags
);
684 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
685 external_start_advertising_service(&e
->r
.resrec
, instance
->request
->flags
);
687 instance
->external_advertise
= mDNStrue
;
690 mDNSlocal
void external_stop_advertising_helper(service_instance
*const instance
)
692 AuthRecord
*st
= instance
->subtypes
;
693 ExtraResourceRecord
*e
;
696 if (!instance
->external_advertise
) return;
698 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
700 if (instance
->request
)
702 for (i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
704 external_stop_advertising_service(&st
[i
].resrec
, instance
->request
->flags
);
707 external_stop_advertising_service(&instance
->srs
.RR_PTR
.resrec
, instance
->request
->flags
);
708 external_stop_advertising_service(&instance
->srs
.RR_SRV
.resrec
, instance
->request
->flags
);
709 external_stop_advertising_service(&instance
->srs
.RR_TXT
.resrec
, instance
->request
->flags
);
711 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
713 external_stop_advertising_service(&e
->r
.resrec
, instance
->request
->flags
);
717 instance
->external_advertise
= mDNSfalse
;
719 #endif // MDNSRESPONDER_SUPPORTS(APPLE, D2D)
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 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
746 external_stop_advertising_helper(srv
);
749 // clear pointers from parent struct
752 service_instance
**p
= &srv
->request
->u
.servicereg
.instances
;
755 if (*p
== srv
) { *p
= (*p
)->next
; break; }
762 e
->r
.RecordContext
= e
;
765 FreeExtraRR(&mDNSStorage
, &tmp
->r
, mStatus_MemFree
);
768 if (srv
->srs
.RR_TXT
.resrec
.rdata
!= &srv
->srs
.RR_TXT
.rdatastorage
)
769 freeL("TXT RData", srv
->srs
.RR_TXT
.resrec
.rdata
);
773 freeL("ServiceSubTypes", srv
->subtypes
);
774 srv
->subtypes
= NULL
;
776 freeL("service_instance", srv
);
779 // Count how many other service records we have locally with the same name, but different rdata.
780 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
781 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
782 mDNSexport
int CountPeerRegistrations(ServiceRecordSet
*const srs
)
785 ResourceRecord
*r
= &srs
->RR_SRV
.resrec
;
788 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
789 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& SameDomainName(rr
->resrec
.name
, r
->name
) && !IdenticalSameNameRecord(&rr
->resrec
, r
))
792 verbosedebugf("%d peer registrations for %##s", count
, r
->name
->c
);
796 mDNSexport
int CountExistingRegistrations(domainname
*srv
, mDNSIPPort port
)
800 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
801 if (rr
->resrec
.rrtype
== kDNSType_SRV
&&
802 mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, port
) &&
803 SameDomainName(rr
->resrec
.name
, srv
))
808 mDNSlocal
void SendServiceRemovalNotification(ServiceRecordSet
*const srs
)
811 service_instance
*instance
= srs
->ServiceContext
;
812 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, 0, mStatus_NoError
) != mStatus_NoError
)
813 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
814 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNSfalse
; }
817 // service registration callback performs three duties - frees memory for deregistered services,
818 // handles name conflicts, and delivers completed registration information to the client
819 mDNSlocal
void regservice_callback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
822 mDNSBool SuppressError
= mDNSfalse
;
823 service_instance
*instance
;
829 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regservice_callback: srs is NULL %d", result
);
833 instance
= srs
->ServiceContext
;
836 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regservice_callback: srs->ServiceContext is NULL %d", result
);
840 // don't send errors up to client for wide-area, empty-string registrations
841 if (instance
->request
&&
842 instance
->request
->u
.servicereg
.default_domain
&&
843 !instance
->default_local
)
844 SuppressError
= mDNStrue
;
846 if (mDNS_LoggingEnabled
)
848 const char *result_description
;
849 char description
[32]; // 32-byte is enough for holding "suppressed error -2147483648\0"
850 mDNSu32 request_id
= instance
->request
? instance
->request
->request_id
: 0;
852 case mStatus_NoError
:
853 result_description
= "REGISTERED";
855 case mStatus_MemFree
:
856 result_description
= "DEREGISTERED";
858 case mStatus_NameConflict
:
859 result_description
= "NAME CONFLICT";
862 mDNS_snprintf(description
, sizeof(description
), "%s %d", SuppressError
? "suppressed error" : "CALLBACK", result
);
863 result_description
= description
;
866 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%u] DNSServiceRegister(" PRI_DM_NAME
", %u) %s",
867 request_id
, DM_NAME_PARAM(srs
->RR_SRV
.resrec
.name
->c
), mDNSVal16(srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
), result_description
);
870 if (!instance
->request
&& result
!= mStatus_MemFree
)
872 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regservice_callback: instance->request is NULL %d", result
);
876 if (result
== mStatus_NoError
)
878 if (instance
->request
->u
.servicereg
.allowremotequery
)
880 ExtraResourceRecord
*e
;
881 srs
->RR_ADV
.AllowRemoteQuery
= mDNStrue
;
882 srs
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
883 srs
->RR_SRV
.AllowRemoteQuery
= mDNStrue
;
884 srs
->RR_TXT
.AllowRemoteQuery
= mDNStrue
;
885 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
) e
->r
.AllowRemoteQuery
= mDNStrue
;
888 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
889 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "[R%u] regservice_callback: " PRI_DM_NAME
" is not valid DNS-SD SRV name", instance
->request
->request_id
, DM_NAME_PARAM(srs
->RR_SRV
.resrec
.name
->c
));
890 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
892 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
893 if (callExternalHelpers(instance
->request
->u
.servicereg
.InterfaceID
, &instance
->domain
, instance
->request
->flags
))
895 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%u] regservice_callback: calling external_start_advertising_helper()", instance
->request
->request_id
);
896 external_start_advertising_helper(instance
);
899 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(srs
) == 0)
900 RecordUpdatedNiceLabel(0); // Successfully got new name, tell user immediately
902 else if (result
== mStatus_MemFree
)
904 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
905 curr_num_regservices
--;
907 if (instance
->request
&& instance
->renameonmemfree
)
909 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
910 external_stop_advertising_helper(instance
);
912 instance
->renameonmemfree
= 0;
913 err
= mDNS_RenameAndReregisterService(m
, srs
, &instance
->request
->u
.servicereg
.name
);
915 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "[R%u] ERROR: regservice_callback - RenameAndReregisterService returned %d", instance
->request
->request_id
, err
);
916 // error should never happen - safest to log and continue
919 unlink_and_free_service_instance(instance
);
921 else if (result
== mStatus_NameConflict
)
923 if (instance
->request
->u
.servicereg
.autorename
)
925 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
926 external_stop_advertising_helper(instance
);
928 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(srs
) == 0)
930 // On conflict for an autoname service, rename and reregister *all* autoname services
931 IncrementLabelSuffix(&m
->nicelabel
, mDNStrue
);
932 mDNS_ConfigChanged(m
); // Will call back into udsserver_handle_configchange()
934 else // On conflict for a non-autoname service, rename and reregister just that one service
936 if (instance
->clientnotified
) SendServiceRemovalNotification(srs
);
937 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
944 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
945 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "[R%u] regservice_callback: " PRI_DM_NAME
" is not valid DNS-SD SRV name", instance
->request
->request_id
, DM_NAME_PARAM(srs
->RR_SRV
.resrec
.name
->c
));
946 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
948 unlink_and_free_service_instance(instance
);
951 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
955 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
956 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "[R%u] regservice_callback: " PRI_DM_NAME
" is not valid DNS-SD SRV name", instance
->request
->request_id
, DM_NAME_PARAM(srs
->RR_SRV
.resrec
.name
->c
));
957 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
962 mDNSlocal
void regrecord_callback(mDNS
*const m
, AuthRecord
*rr
, mStatus result
)
965 if (!rr
->RecordContext
) // parent struct already freed by termination callback
967 if (result
== mStatus_NoError
)
968 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "Error: regrecord_callback: successful registration of orphaned record " PRI_S
, ARDisplayString(m
, rr
));
971 if (result
!= mStatus_MemFree
)
972 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regrecord_callback: error %d received after parent termination", result
);
974 // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
975 // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
976 // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
977 // to free the latest rdata for which the update_callback was never called with.
978 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
) freeL("RData/regrecord_callback", rr
->resrec
.rdata
);
979 freeL("AuthRecord/regrecord_callback", rr
);
984 registered_record_entry
*re
= rr
->RecordContext
;
985 request_state
*request
= re
->request
;
987 if (mDNS_LoggingEnabled
)
989 const char *result_description
;
990 char description
[16]; // 16-byte is enough for holding -2147483648\0
992 case mStatus_NoError
:
993 result_description
= "REGISTERED";
995 case mStatus_MemFree
:
996 result_description
= "DEREGISTERED";
998 case mStatus_NameConflict
:
999 result_description
= "NAME CONFLICT";
1002 mDNS_snprintf(description
, sizeof(description
), "%d", result
);
1003 result_description
= description
;
1007 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%u] DNSServiceRegisterRecord(%u " PRI_S
")" PUB_S
,
1008 request
->request_id
, re
->key
, RRDisplayString(m
, &rr
->resrec
), result_description
);
1011 if (result
!= mStatus_MemFree
)
1013 int len
= sizeof(DNSServiceFlags
) + sizeof(mDNSu32
) + sizeof(DNSServiceErrorType
);
1014 reply_state
*reply
= create_reply(reg_record_reply_op
, len
, request
);
1015 reply
->mhdr
->client_context
= re
->regrec_client_context
;
1016 reply
->rhdr
->flags
= dnssd_htonl(0);
1017 reply
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, rr
->resrec
.InterfaceID
, mDNSfalse
));
1018 reply
->rhdr
->error
= dnssd_htonl(result
);
1019 append_reply(request
, reply
);
1024 // If this is a callback to a keepalive record, do not free it.
1025 if (result
== mStatus_BadStateErr
)
1027 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1028 "[R%u] regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.", request
->request_id
);
1032 // unlink from list, free memory
1033 registered_record_entry
**ptr
= &request
->u
.reg_recs
;
1034 while (*ptr
&& (*ptr
) != re
) ptr
= &(*ptr
)->next
;
1037 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1038 "[R%u] regrecord_callback - record not in list!", request
->request_id
);
1041 *ptr
= (*ptr
)->next
;
1042 freeL("registered_record_entry AuthRecord regrecord_callback", re
->rr
);
1043 freeL("registered_record_entry regrecord_callback", re
);
1048 if (re
->external_advertise
)
1050 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1051 "[R%u] regrecord_callback: external_advertise already set!", request
->request_id
);
1054 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1055 if (callExternalHelpers(re
->origInterfaceID
, &rr
->namestorage
, request
->flags
))
1057 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1058 "[R%u] regrecord_callback: calling external_start_advertising_service", request
->request_id
);
1059 external_start_advertising_service(&rr
->resrec
, request
->flags
);
1060 re
->external_advertise
= mDNStrue
;
1067 // set_peer_pid() is called after mem is allocated for each new request in NewRequest()
1068 // This accounts for 2 places (connect_callback, request_callback)
1069 mDNSlocal
void set_peer_pid(request_state
*request
)
1071 request
->pid_name
[0] = '\0';
1072 request
->process_id
= -1;
1073 #ifdef LOCAL_PEEREPID
1074 pid_t p
= (pid_t
) -1;
1075 socklen_t len
= sizeof(p
);
1076 if (request
->sd
< 0)
1078 // to extract the effective pid value
1079 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREPID
, &p
, &len
) != 0)
1081 // to extract the process name from the pid value
1082 if (proc_pidinfo(p
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0)
1084 mDNSPlatformStrLCopy(request
->pid_name
, proc
.pbsi_comm
, sizeof(request
->pid_name
));
1085 request
->process_id
= p
;
1086 debugf("set_peer_pid: Client PEEREPID is %d %s", p
, request
->pid_name
);
1087 #else // !LOCAL_PEEREPID
1088 LogInfo("set_peer_pid: Not Supported on this version of OS");
1089 if (request
->sd
< 0)
1091 #endif // LOCAL_PEEREPID
1094 mDNSlocal
void connection_termination(request_state
*request
)
1096 // When terminating a shared connection, we need to scan the all_requests list
1097 // and terminate any subbordinate operations sharing this file descriptor
1098 request_state
**req
= &all_requests
;
1100 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1101 "[R%d] DNSServiceCreateConnection STOP PID[%d](" PUB_S
")",
1102 request
->request_id
, request
->process_id
, request
->pid_name
);
1106 if ((*req
)->primary
== request
)
1108 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1109 request_state
*tmp
= *req
;
1110 if (tmp
->primary
== tmp
) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp
, tmp
->sd
);
1111 if (tmp
->replies
) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp
, tmp
->sd
);
1114 freeL("request_state/connection_termination", tmp
);
1117 req
= &(*req
)->next
;
1120 while (request
->u
.reg_recs
)
1122 registered_record_entry
*ptr
= request
->u
.reg_recs
;
1123 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1124 "[R%d] DNSServiceRegisterRecord(0x%X, %d, " PRI_S
") STOP PID[%d](" PUB_S
")",
1125 request
->request_id
, request
->flags
, request
->interfaceIndex
, RRDisplayString(&mDNSStorage
, &ptr
->rr
->resrec
), request
->process_id
,
1127 request
->u
.reg_recs
= request
->u
.reg_recs
->next
;
1128 ptr
->rr
->RecordContext
= NULL
;
1129 if (ptr
->external_advertise
)
1131 ptr
->external_advertise
= mDNSfalse
;
1132 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1133 external_stop_advertising_service(&ptr
->rr
->resrec
, request
->flags
);
1136 LogMcastS(ptr
->rr
, request
, reg_stop
);
1137 mDNS_Deregister(&mDNSStorage
, ptr
->rr
); // Will free ptr->rr for us
1138 freeL("registered_record_entry/connection_termination", ptr
);
1142 mDNSlocal
void handle_cancel_request(request_state
*request
)
1144 request_state
**req
= &all_requests
;
1145 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "[R%d] Cancel %08X %08X",
1146 request
->request_id
, request
->hdr
.client_context
.u32
[1], request
->hdr
.client_context
.u32
[0]);
1149 if ((*req
)->primary
== request
&&
1150 (*req
)->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1151 (*req
)->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1])
1153 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1154 request_state
*tmp
= *req
;
1157 freeL("request_state/handle_cancel_request", tmp
);
1160 req
= &(*req
)->next
;
1164 mDNSlocal mStatus
handle_regrecord_request(request_state
*request
)
1166 mStatus err
= mStatus_BadParamErr
;
1169 if (request
->terminate
!= connection_termination
)
1170 { LogMsg("%3d: DNSServiceRegisterRecord(not a shared connection ref)", request
->sd
); return(err
); }
1172 rr
= read_rr_from_ipc_msg(request
, 1, 1);
1175 registered_record_entry
*re
;
1176 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1177 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1178 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
&& !IsLocalDomain(rr
->resrec
.name
) &&
1179 rr
->resrec
.rrclass
== kDNSClass_IN
&& (rr
->resrec
.rrtype
== kDNSType_A
|| rr
->resrec
.rrtype
== kDNSType_AAAA
||
1180 rr
->resrec
.rrtype
== kDNSType_CNAME
))
1182 freeL("AuthRecord/handle_regrecord_request", rr
);
1183 return (mStatus_BadParamErr
);
1185 // allocate registration entry, link into list
1186 re
= (registered_record_entry
*) callocL("registered_record_entry", sizeof(*re
));
1187 if (!re
) FatalError("ERROR: calloc");
1188 re
->key
= request
->hdr
.reg_index
;
1190 re
->regrec_client_context
= request
->hdr
.client_context
;
1191 re
->request
= request
;
1192 re
->external_advertise
= mDNSfalse
;
1193 rr
->RecordContext
= re
;
1194 rr
->RecordCallback
= regrecord_callback
;
1196 re
->origInterfaceID
= rr
->resrec
.InterfaceID
;
1197 if (rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1198 rr
->resrec
.InterfaceID
= mDNSInterface_Any
;
1200 if (!AuthorizedDomain(request
, rr
->resrec
.name
, AutoRegistrationDomains
)) return (mStatus_NoError
);
1202 if (rr
->resrec
.rroriginalttl
== 0)
1203 rr
->resrec
.rroriginalttl
= DefaultTTLforRRType(rr
->resrec
.rrtype
);
1205 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1206 "[R%d] DNSServiceRegisterRecord(0x%X, %d, " PRI_S
") START PID[%d](" PUB_S
")",
1207 request
->request_id
, request
->flags
, request
->interfaceIndex
, RRDisplayString(&mDNSStorage
, &rr
->resrec
), request
->process_id
,
1210 err
= mDNS_Register(&mDNSStorage
, rr
);
1213 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1214 "[R%d] DNSServiceRegisterRecord(0x%X, %d," PRI_S
") ERROR (%d)",
1215 request
->request_id
, request
->flags
, request
->interfaceIndex
, RRDisplayString(&mDNSStorage
, &rr
->resrec
), err
);
1216 freeL("registered_record_entry", re
);
1217 freeL("registered_record_entry/AuthRecord", rr
);
1221 LogMcastS(rr
, request
, reg_start
);
1222 re
->next
= request
->u
.reg_recs
;
1223 request
->u
.reg_recs
= re
;
1229 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
);
1231 mDNSlocal
void regservice_termination_callback(request_state
*request
)
1235 LogMsg("regservice_termination_callback context is NULL");
1238 while (request
->u
.servicereg
.instances
)
1240 service_instance
*p
= request
->u
.servicereg
.instances
;
1241 request
->u
.servicereg
.instances
= request
->u
.servicereg
.instances
->next
;
1242 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1243 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceRegister(" PRI_DM_NAME
", %u) STOP PID[%d](" PUB_S
")",
1244 request
->request_id
, DM_NAME_PARAM(p
->srs
.RR_SRV
.resrec
.name
->c
),
1245 mDNSVal16(p
->srs
.RR_SRV
.resrec
.rdata
->u
.srv
.port
), request
->process_id
, request
->pid_name
);
1247 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1248 external_stop_advertising_helper(p
);
1251 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1252 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1253 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1254 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1255 // because by then we might have already freed p
1257 LogMcastS(&p
->srs
.RR_SRV
, request
, reg_stop
);
1258 if (mDNS_DeregisterService(&mDNSStorage
, &p
->srs
))
1260 unlink_and_free_service_instance(p
);
1261 // Don't touch service_instance *p after this -- it's likely to have been freed already
1264 if (request
->u
.servicereg
.txtdata
)
1266 freeL("service_info txtdata", request
->u
.servicereg
.txtdata
);
1267 request
->u
.servicereg
.txtdata
= NULL
;
1269 if (request
->u
.servicereg
.autoname
)
1271 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1272 request
->u
.servicereg
.autoname
= mDNSfalse
;
1273 UpdateDeviceInfoRecord(&mDNSStorage
);
1277 mDNSlocal request_state
*LocateSubordinateRequest(request_state
*request
)
1280 for (req
= all_requests
; req
; req
= req
->next
)
1281 if (req
->primary
== request
&&
1282 req
->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1283 req
->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1]) return(req
);
1287 mDNSlocal mStatus
add_record_to_service(request_state
*request
, service_instance
*instance
, mDNSu16 rrtype
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
)
1289 ServiceRecordSet
*srs
= &instance
->srs
;
1291 size_t size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1292 ExtraResourceRecord
*extra
= (ExtraResourceRecord
*) mallocL("ExtraResourceRecord", sizeof(*extra
) - sizeof(RDataBody
) + size
);
1293 if (!extra
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1295 mDNSPlatformMemZero(extra
, sizeof(*extra
)); // OK if oversized rdata not zero'd
1296 extra
->r
.resrec
.rrtype
= rrtype
;
1297 extra
->r
.rdatastorage
.MaxRDLength
= (mDNSu16
) size
;
1298 extra
->r
.resrec
.rdlength
= rdlen
;
1299 mDNSPlatformMemCopy(&extra
->r
.rdatastorage
.u
.data
, rdata
, rdlen
);
1300 // use InterfaceID value from DNSServiceRegister() call that created the original service
1301 extra
->r
.resrec
.InterfaceID
= request
->u
.servicereg
.InterfaceID
;
1303 result
= mDNS_AddRecordToService(&mDNSStorage
, srs
, extra
, &extra
->r
.rdatastorage
, ttl
, request
->flags
);
1306 freeL("ExtraResourceRecord/add_record_to_service", extra
);
1309 LogMcastS(&srs
->RR_PTR
, request
, reg_start
);
1311 extra
->ClientID
= request
->hdr
.reg_index
;
1312 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1313 if ( instance
->external_advertise
1314 && callExternalHelpers(request
->u
.servicereg
.InterfaceID
, &instance
->domain
, request
->flags
))
1316 LogInfo("add_record_to_service: calling external_start_advertising_service");
1317 external_start_advertising_service(&extra
->r
.resrec
, request
->flags
);
1323 mDNSlocal mStatus
handle_add_request(request_state
*request
)
1325 service_instance
*i
;
1326 mStatus result
= mStatus_UnknownErr
;
1327 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
);
1328 mDNSu16 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
1329 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1330 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1331 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1332 if (!ttl
) ttl
= DefaultTTLforRRType(rrtype
);
1333 (void)flags
; // Unused
1335 if (!request
->msgptr
)
1337 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1338 "[R%d] DNSServiceAddRecord(unreadable parameters)", request
->request_id
);
1339 return(mStatus_BadParamErr
);
1342 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1343 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1345 if (request
->terminate
!= regservice_termination_callback
)
1347 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1348 "[R%d] DNSServiceAddRecord(not a registered service ref)", request
->request_id
);
1349 return(mStatus_BadParamErr
);
1352 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1353 // in the application. See radar://9165807.
1354 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1356 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1357 "[R%d] DNSServiceAddRecord: adding record to a service registered with zero port", request
->request_id
);
1358 return(mStatus_BadParamErr
);
1360 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1361 "[R%d] DNSServiceAddRecord(%X, " PRI_DM_NAME
", " PUB_S
", %d) PID[%d](" PUB_S
")",
1362 request
->request_id
, flags
,
1363 DM_NAME_PARAM((request
->u
.servicereg
.instances
) ? (request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
) : mDNSNULL
),
1364 DNSTypeName(rrtype
), rdlen
, request
->process_id
, request
->pid_name
);
1366 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1368 result
= add_record_to_service(request
, i
, rrtype
, rdlen
, rdata
, ttl
);
1369 if (result
&& i
->default_local
) break;
1370 else result
= mStatus_NoError
; // suppress non-local default errors
1376 mDNSlocal
void update_callback(mDNS
*const m
, AuthRecord
*const rr
, RData
*oldrd
, mDNSu16 oldrdlen
)
1378 mDNSBool external_advertise
= (rr
->UpdateContext
) ? *((mDNSBool
*)rr
->UpdateContext
) : mDNSfalse
;
1381 // There are three cases.
1383 // 1. We have updated the primary TXT record of the service
1384 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1385 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1387 // external_advertise is set if we have advertised at least once during the initial addition
1388 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1389 // checks during the first time and hence we don't do any checks here
1390 if (external_advertise
)
1392 ResourceRecord ext
= rr
->resrec
;
1393 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1394 DNSServiceFlags flags
= deriveD2DFlagsFromAuthRecType(rr
->ARType
);
1397 if (ext
.rdlength
== oldrdlen
&& mDNSPlatformMemSame(&ext
.rdata
->u
, &oldrd
->u
, oldrdlen
)) goto exit
;
1398 SetNewRData(&ext
, oldrd
, oldrdlen
);
1399 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1400 external_stop_advertising_service(&ext
, flags
);
1401 LogInfo("update_callback: calling external_start_advertising_service");
1402 external_start_advertising_service(&rr
->resrec
, flags
);
1406 if (oldrd
!= &rr
->rdatastorage
) freeL("RData/update_callback", oldrd
);
1409 mDNSlocal mStatus
update_record(AuthRecord
*rr
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
, const mDNSBool
*const external_advertise
)
1412 const size_t rdsize
= (rdlen
> sizeof(RDataBody
)) ? rdlen
: sizeof(RDataBody
);
1413 RData
*newrd
= (RData
*) mallocL("RData/update_record", sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
1414 if (!newrd
) FatalError("ERROR: malloc");
1415 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
1416 mDNSPlatformMemCopy(&newrd
->u
, rdata
, rdlen
);
1418 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1419 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1420 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1421 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rdlen
== 0) { rdlen
= 1; newrd
->u
.txt
.c
[0] = 0; }
1423 if (external_advertise
) rr
->UpdateContext
= (void *)external_advertise
;
1425 result
= mDNS_Update(&mDNSStorage
, rr
, ttl
, rdlen
, newrd
, update_callback
);
1426 if (result
) { LogMsg("update_record: Error %d for %s", (int)result
, ARDisplayString(&mDNSStorage
, rr
)); freeL("RData/update_record", newrd
); }
1430 mDNSlocal mStatus
handle_update_request(request_state
*request
)
1432 const ipc_msg_hdr
*const hdr
= &request
->hdr
;
1433 mStatus result
= mStatus_BadReferenceErr
;
1434 service_instance
*i
;
1435 AuthRecord
*rr
= NULL
;
1437 // get the message data
1438 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
); // flags unused
1439 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1440 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1441 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1442 (void)flags
; // Unused
1444 if (!request
->msgptr
)
1446 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1447 "[R%d] DNSServiceUpdateRecord(unreadable parameters)", request
->request_id
);
1448 return(mStatus_BadParamErr
);
1451 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1452 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1454 if (request
->terminate
== connection_termination
)
1456 // update an individually registered record
1457 registered_record_entry
*reptr
;
1458 for (reptr
= request
->u
.reg_recs
; reptr
; reptr
= reptr
->next
)
1460 if (reptr
->key
== hdr
->reg_index
)
1462 result
= update_record(reptr
->rr
, rdlen
, rdata
, ttl
, &reptr
->external_advertise
);
1463 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1464 "[R%d] DNSServiceUpdateRecord(" PRI_DM_NAME
", " PUB_S
") PID[%d](" PUB_S
")",
1465 request
->request_id
, DM_NAME_PARAM(reptr
->rr
->resrec
.name
->c
),
1466 reptr
->rr
? DNSTypeName(reptr
->rr
->resrec
.rrtype
) : "<NONE>",
1467 request
->process_id
, request
->pid_name
);
1471 result
= mStatus_BadReferenceErr
;
1475 if (request
->terminate
!= regservice_termination_callback
)
1477 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1478 "[R%d] DNSServiceUpdateRecord(not a registered service ref)", request
->request_id
);
1479 return(mStatus_BadParamErr
);
1482 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1483 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1485 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1486 "[R%d] DNSServiceUpdateRecord: updating the record of a service registered with zero port", request
->request_id
);
1487 return(mStatus_BadParamErr
);
1490 // update the saved off TXT data for the service
1491 if (hdr
->reg_index
== TXT_RECORD_INDEX
)
1493 if (request
->u
.servicereg
.txtdata
)
1494 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1497 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", rdlen
);
1498 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_update_request - malloc");
1499 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, rdata
, rdlen
);
1501 request
->u
.servicereg
.txtlen
= rdlen
;
1504 // update a record from a service record set
1505 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1507 if (hdr
->reg_index
== TXT_RECORD_INDEX
) rr
= &i
->srs
.RR_TXT
;
1510 ExtraResourceRecord
*e
;
1511 for (e
= i
->srs
.Extras
; e
; e
= e
->next
)
1512 if (e
->ClientID
== hdr
->reg_index
) { rr
= &e
->r
; break; }
1515 if (!rr
) { result
= mStatus_BadReferenceErr
; goto end
; }
1516 result
= update_record(rr
, rdlen
, rdata
, ttl
, &i
->external_advertise
);
1517 if (result
&& i
->default_local
) goto end
;
1518 else result
= mStatus_NoError
; // suppress non-local default errors
1522 if (request
->terminate
== regservice_termination_callback
)
1523 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)", request
->sd
,
1524 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1525 rr
? DNSTypeName(rr
->resrec
.rrtype
) : "<NONE>",
1526 request
->process_id
, request
->pid_name
);
1531 // remove a resource record registered via DNSServiceRegisterRecord()
1532 mDNSlocal mStatus
remove_record(request_state
*request
)
1534 mStatus err
= mStatus_UnknownErr
;
1535 registered_record_entry
*e
, **ptr
= &request
->u
.reg_recs
;
1537 while (*ptr
&& (*ptr
)->key
!= request
->hdr
.reg_index
) ptr
= &(*ptr
)->next
;
1538 if (!*ptr
) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request
->sd
, request
->hdr
.reg_index
); return mStatus_BadReferenceErr
; }
1540 *ptr
= e
->next
; // unlink
1542 LogOperation("%3d: DNSServiceRemoveRecord(%u %s) PID[%d](%s)",
1543 request
->sd
, e
->key
, RRDisplayString(&mDNSStorage
, &e
->rr
->resrec
), request
->process_id
, request
->pid_name
);
1544 e
->rr
->RecordContext
= NULL
;
1545 if (e
->external_advertise
)
1547 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1548 external_stop_advertising_service(&e
->rr
->resrec
, request
->flags
);
1550 e
->external_advertise
= mDNSfalse
;
1552 LogMcastS(e
->rr
, request
, reg_stop
);
1553 err
= mDNS_Deregister(&mDNSStorage
, e
->rr
); // Will free e->rr for us; we're responsible for freeing e
1556 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err
);
1557 freeL("registered_record_entry AuthRecord remove_record", e
->rr
);
1559 freeL("registered_record_entry remove_record", e
);
1563 mDNSlocal mStatus
remove_extra(const request_state
*const request
, service_instance
*const serv
, mDNSu16
*const rrtype
)
1565 mStatus err
= mStatus_BadReferenceErr
;
1566 ExtraResourceRecord
*ptr
;
1568 for (ptr
= serv
->srs
.Extras
; ptr
; ptr
= ptr
->next
)
1570 if (ptr
->ClientID
== request
->hdr
.reg_index
) // found match
1572 *rrtype
= ptr
->r
.resrec
.rrtype
;
1573 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1574 if (serv
->external_advertise
) external_stop_advertising_service(&ptr
->r
.resrec
, request
->flags
);
1576 err
= mDNS_RemoveRecordFromService(&mDNSStorage
, &serv
->srs
, ptr
, FreeExtraRR
, ptr
);
1583 mDNSlocal mStatus
handle_removerecord_request(request_state
*request
)
1585 mStatus err
= mStatus_BadReferenceErr
;
1586 get_flags(&request
->msgptr
, request
->msgend
); // flags unused
1588 if (!request
->msgptr
)
1590 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1591 "[R%d] DNSServiceRemoveRecord(unreadable parameters)", request
->request_id
);
1592 return(mStatus_BadParamErr
);
1595 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1596 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1598 if (request
->terminate
== connection_termination
)
1599 err
= remove_record(request
); // remove individually registered record
1600 else if (request
->terminate
!= regservice_termination_callback
)
1602 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1603 "[R%d] DNSServiceRemoveRecord(not a registered service ref)", request
->request_id
);
1604 return(mStatus_BadParamErr
);
1608 service_instance
*i
;
1610 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceRemoveRecord(" PRI_DM_NAME
", " PUB_S
") PID[%d](" PUB_S
")",
1611 request
->request_id
,
1612 DM_NAME_PARAM((request
->u
.servicereg
.instances
) ? (request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
) : mDNSNULL
),
1613 rrtype
? DNSTypeName(rrtype
) : "<NONE>", request
->process_id
, request
->pid_name
);
1614 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1616 err
= remove_extra(request
, i
, &rrtype
);
1617 if (err
&& i
->default_local
) break;
1618 else err
= mStatus_NoError
; // suppress non-local default errors
1625 // If there's a comma followed by another character,
1626 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1627 // Otherwise, it returns a pointer to the final nul at the end of the string
1628 mDNSlocal
char *FindFirstSubType(char *p
)
1632 if (p
[0] == '\\' && p
[1])
1636 else if (p
[0] == ',' && p
[1])
1649 // If there's a comma followed by another character,
1650 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1651 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1652 // Otherwise, it returns a pointer to the final nul at the end of the string
1653 mDNSlocal
char *FindNextSubType(char *p
)
1657 if (p
[0] == '\\' && p
[1]) // If escape character
1658 p
+= 2; // ignore following character
1659 else if (p
[0] == ',') // If we found a comma
1664 else if (p
[0] == '.')
1671 // Returns -1 if illegal subtype found
1672 mDNSlocal mDNSs32
ChopSubTypes(char *regtype
)
1674 mDNSs32 NumSubTypes
= 0;
1675 char *stp
= FindFirstSubType(regtype
);
1676 while (stp
&& *stp
) // If we found a comma...
1678 if (*stp
== ',') return(-1);
1680 stp
= FindNextSubType(stp
);
1682 if (!stp
) return(-1);
1683 return(NumSubTypes
);
1686 mDNSlocal AuthRecord
*AllocateSubTypes(mDNSs32 NumSubTypes
, char *p
)
1688 AuthRecord
*st
= mDNSNULL
;
1692 st
= (AuthRecord
*) callocL("ServiceSubTypes", NumSubTypes
* sizeof(AuthRecord
));
1693 if (!st
) return(mDNSNULL
);
1694 for (i
= 0; i
< NumSubTypes
; i
++)
1696 mDNS_SetupResourceRecord(&st
[i
], mDNSNULL
, mDNSInterface_Any
, kDNSQType_ANY
, kStandardTTL
, 0, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
1699 if (!MakeDomainNameFromDNSNameString(&st
[i
].namestorage
, p
))
1701 freeL("ServiceSubTypes", st
);
1709 mDNSlocal mStatus
register_service_instance(request_state
*request
, const domainname
*domain
)
1711 service_instance
**ptr
, *instance
;
1712 size_t extra_size
= (request
->u
.servicereg
.txtlen
> sizeof(RDataBody
)) ? (request
->u
.servicereg
.txtlen
- sizeof(RDataBody
)) : 0;
1713 const mDNSBool DomainIsLocal
= SameDomainName(domain
, &localdomain
);
1715 mDNSInterfaceID interfaceID
= request
->u
.servicereg
.InterfaceID
;
1717 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1718 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1719 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1720 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1721 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1722 if (request
->u
.servicereg
.default_domain
&& !DomainIsLocal
) interfaceID
= mDNSInterface_Any
;
1724 for (ptr
= &request
->u
.servicereg
.instances
; *ptr
; ptr
= &(*ptr
)->next
)
1726 if (SameDomainName(&(*ptr
)->domain
, domain
))
1728 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1729 domain
->c
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
);
1730 return mStatus_AlreadyRegistered
;
1734 instance
= (service_instance
*) callocL("service_instance", sizeof(*instance
) + extra_size
);
1735 if (!instance
) { my_perror("ERROR: calloc"); return mStatus_NoMemoryErr
; }
1737 instance
->next
= mDNSNULL
;
1738 instance
->request
= request
;
1739 instance
->renameonmemfree
= 0;
1740 instance
->clientnotified
= mDNSfalse
;
1741 instance
->default_local
= (request
->u
.servicereg
.default_domain
&& DomainIsLocal
);
1742 instance
->external_advertise
= mDNSfalse
;
1743 AssignDomainName(&instance
->domain
, domain
);
1745 instance
->subtypes
= AllocateSubTypes(request
->u
.servicereg
.num_subtypes
, request
->u
.servicereg
.type_as_string
);
1747 if (request
->u
.servicereg
.num_subtypes
&& !instance
->subtypes
)
1749 unlink_and_free_service_instance(instance
);
1751 FatalError("ERROR: malloc");
1754 result
= mDNS_RegisterService(&mDNSStorage
, &instance
->srs
,
1755 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
,
1756 request
->u
.servicereg
.host
.c
[0] ? &request
->u
.servicereg
.host
: NULL
,
1757 request
->u
.servicereg
.port
,
1758 mDNSNULL
, request
->u
.servicereg
.txtdata
, request
->u
.servicereg
.txtlen
,
1759 instance
->subtypes
, request
->u
.servicereg
.num_subtypes
,
1760 interfaceID
, regservice_callback
, instance
, request
->flags
);
1764 *ptr
= instance
; // Append this to the end of our request->u.servicereg.instances list
1765 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance
->request
->sd
,
1766 instance
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(request
->u
.servicereg
.port
));
1767 LogMcastS(&instance
->srs
.RR_SRV
, request
, reg_start
);
1771 LogMsg("register_service_instance %#s.%##s%##s error %d",
1772 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
->c
, result
);
1773 unlink_and_free_service_instance(instance
);
1779 mDNSlocal
void udsserver_default_reg_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
1781 request_state
*request
;
1783 LogMsg("%s registration domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
1784 for (request
= all_requests
; request
; request
= request
->next
)
1786 if (request
->terminate
!= regservice_termination_callback
) continue;
1787 if (!request
->u
.servicereg
.default_domain
) continue;
1788 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
1790 service_instance
**ptr
= &request
->u
.servicereg
.instances
;
1791 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
1794 // If we don't already have this domain in our list for this registration, add it now
1795 if (!*ptr
) register_service_instance(request
, &d
->name
);
1796 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d
->name
);
1800 // Normally we should not fail to find the specified instance
1801 // One case where this can happen is if a uDNS update fails for some reason,
1802 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1804 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1805 &d
->name
, request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type_as_string
);
1809 for (p
= AutoRegistrationDomains
; p
; p
=p
->next
)
1810 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
1811 if (SameDomainName(&d
->name
, &p
->name
)) break;
1812 if (p
) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d
->name
);
1816 service_instance
*si
= *ptr
;
1818 if (si
->clientnotified
) SendServiceRemovalNotification(&si
->srs
); // Do this *before* clearing si->request backpointer
1819 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1820 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1821 // process of completing asynchronously, the client cancels the entire operation, so
1822 // regservice_termination_callback then runs through the whole list deregistering each
1823 // instance, clearing the backpointers, and then disposing the parent request_state object.
1824 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1825 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1826 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1827 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1829 err
= mDNS_DeregisterService(&mDNSStorage
, &si
->srs
);
1830 if (err
) { LogMsg("udsserver_default_reg_domain_changed err %d", err
); unlink_and_free_service_instance(si
); }
1838 // Returns true if the interfaceIndex value matches one of the pre-defined
1839 // special values listed in the switch statement below.
1840 mDNSlocal mDNSBool
PreDefinedInterfaceIndex(mDNSu32 interfaceIndex
)
1842 switch(interfaceIndex
)
1844 case kDNSServiceInterfaceIndexAny
:
1845 case kDNSServiceInterfaceIndexLocalOnly
:
1846 case kDNSServiceInterfaceIndexUnicast
:
1847 case kDNSServiceInterfaceIndexP2P
:
1848 case kDNSServiceInterfaceIndexBLE
:
1855 mDNSlocal mStatus
handle_regservice_request(request_state
*request
)
1857 char name
[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1858 char domain
[MAX_ESCAPED_DOMAIN_NAME
], host
[MAX_ESCAPED_DOMAIN_NAME
];
1859 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
]; // Note that this service type may include a trailing list of subtypes
1862 const char *msgTXTData
;
1864 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
1865 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
1866 mDNSInterfaceID InterfaceID
;
1868 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
1869 // kDNSServiceFlagsIncludeP2P flag set.
1870 if (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)
1872 LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
1873 flags
|= kDNSServiceFlagsIncludeP2P
;
1874 interfaceIndex
= kDNSServiceInterfaceIndexAny
;
1877 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
1879 // The registration is scoped to a specific interface index, but the
1880 // interface is not currently in our list.
1881 if (interfaceIndex
&& !InterfaceID
)
1883 // If it's one of the specially defined inteface index values, just return an error.
1884 if (PreDefinedInterfaceIndex(interfaceIndex
))
1886 LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex
);
1887 return(mStatus_BadParamErr
);
1890 // Otherwise, use the specified interface index value and the registration will
1891 // be applied to that interface when it comes up.
1892 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
1893 LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex
);
1896 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
1897 get_string(&request
->msgptr
, request
->msgend
, type_as_string
, sizeof(type_as_string
)) < 0 ||
1898 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 0 ||
1899 get_string(&request
->msgptr
, request
->msgend
, host
, sizeof(host
)) < 0)
1900 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
1902 request
->flags
= flags
;
1903 request
->interfaceIndex
= interfaceIndex
;
1904 request
->u
.servicereg
.InterfaceID
= InterfaceID
;
1905 request
->u
.servicereg
.instances
= NULL
;
1906 request
->u
.servicereg
.txtlen
= 0;
1907 request
->u
.servicereg
.txtdata
= NULL
;
1908 mDNSPlatformStrLCopy(request
->u
.servicereg
.type_as_string
, type_as_string
, sizeof(request
->u
.servicereg
.type_as_string
));
1910 if (request
->msgptr
+ 2 > request
->msgend
) request
->msgptr
= NULL
;
1913 request
->u
.servicereg
.port
.b
[0] = *request
->msgptr
++;
1914 request
->u
.servicereg
.port
.b
[1] = *request
->msgptr
++;
1917 request
->u
.servicereg
.txtlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1918 msgTXTData
= get_rdata(&request
->msgptr
, request
->msgend
, request
->u
.servicereg
.txtlen
);
1920 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1922 if (request
->u
.servicereg
.txtlen
)
1924 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", request
->u
.servicereg
.txtlen
);
1925 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_regservice_request - malloc");
1926 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, msgTXTData
, request
->u
.servicereg
.txtlen
);
1929 // Check for sub-types after the service type
1930 request
->u
.servicereg
.num_subtypes
= ChopSubTypes(request
->u
.servicereg
.type_as_string
); // Note: Modifies regtype string to remove trailing subtypes
1931 if (request
->u
.servicereg
.num_subtypes
< 0)
1933 LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request
->u
.servicereg
.type_as_string
);
1937 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1938 if (!*request
->u
.servicereg
.type_as_string
|| !MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.type
, request
->u
.servicereg
.type_as_string
))
1939 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request
->u
.servicereg
.type_as_string
); goto bad_param
; }
1943 request
->u
.servicereg
.name
= mDNSStorage
.nicelabel
;
1944 request
->u
.servicereg
.autoname
= mDNStrue
;
1948 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1949 if ((flags
& kDNSServiceFlagsNoAutoRename
) == 0)
1951 int newlen
= TruncateUTF8ToLength((mDNSu8
*)name
, mDNSPlatformStrLen(name
), MAX_DOMAIN_LABEL
);
1954 if (!MakeDomainLabelFromLiteralString(&request
->u
.servicereg
.name
, name
))
1955 { LogMsg("ERROR: handle_regservice_request - name bad %s", name
); goto bad_param
; }
1956 request
->u
.servicereg
.autoname
= mDNSfalse
;
1961 request
->u
.servicereg
.default_domain
= mDNSfalse
;
1962 if (!MakeDomainNameFromDNSNameString(&d
, domain
))
1963 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain
); goto bad_param
; }
1967 request
->u
.servicereg
.default_domain
= mDNStrue
;
1968 MakeDomainNameFromDNSNameString(&d
, "local.");
1971 if (!ConstructServiceName(&srv
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, &d
))
1973 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1974 request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type
.c
, d
.c
); goto bad_param
;
1977 if (!MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.host
, host
))
1978 { LogMsg("ERROR: handle_regservice_request - host bad %s", host
); goto bad_param
; }
1979 request
->u
.servicereg
.autorename
= (flags
& kDNSServiceFlagsNoAutoRename
) == 0;
1980 request
->u
.servicereg
.allowremotequery
= (flags
& kDNSServiceFlagsAllowRemoteQuery
) != 0;
1982 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1983 // a port number of zero. When two instances of the protected client are allowed to run on one
1984 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1985 if (!mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1987 int count
= CountExistingRegistrations(&srv
, request
->u
.servicereg
.port
);
1989 LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request
->process_id
,
1990 request
->pid_name
, count
+1, srv
.c
, mDNSVal16(request
->u
.servicereg
.port
));
1993 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
1994 // Determine if this request should be promoted to use BLE triggered feature.
1995 if (shouldUseBLE(InterfaceID
, 0, &request
->u
.servicereg
.type
, &d
))
1997 request
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
1998 LogInfo("handle_regservice_request: registration promoted to use kDNSServiceFlagsAutoTrigger");
2000 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2002 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2003 "[R%d] DNSServiceRegister(%X, %d, \"" PRI_S
"\", \"" PRI_S
"\", \"" PRI_S
"\", \"" PRI_S
"\", %u) START PID[%d](" PUB_S
")",
2004 request
->request_id
, request
->flags
, interfaceIndex
, name
, request
->u
.servicereg
.type_as_string
, domain
, host
,
2005 mDNSVal16(request
->u
.servicereg
.port
), request
->process_id
, request
->pid_name
);
2007 // We need to unconditionally set request->terminate, because even if we didn't successfully
2008 // start any registrations right now, subsequent configuration changes may cause successful
2009 // registrations to be added, and we'll need to cancel them before freeing this memory.
2010 // We also need to set request->terminate first, before adding additional service instances,
2011 // because the udsserver_validatelists uses the request->terminate function pointer to determine
2012 // what kind of request this is, and therefore what kind of list validation is required.
2013 request
->terminate
= regservice_termination_callback
;
2015 err
= register_service_instance(request
, &d
);
2017 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
2018 ++curr_num_regservices
;
2019 if (curr_num_regservices
> max_num_regservices
)
2020 max_num_regservices
= curr_num_regservices
;
2024 err
= AuthorizedDomain(request
, &d
, AutoRegistrationDomains
) ? register_service_instance(request
, &d
) : mStatus_NoError
;
2028 if (request
->u
.servicereg
.autoname
) UpdateDeviceInfoRecord(&mDNSStorage
);
2033 // Note that we don't report errors for non-local, non-explicit domains
2034 for (ptr
= AutoRegistrationDomains
; ptr
; ptr
= ptr
->next
)
2035 if (!ptr
->uid
|| SystemUID(request
->uid
) || request
->uid
== ptr
->uid
)
2036 register_service_instance(request
, &ptr
->name
);
2043 freeL("handle_regservice_request (txtdata)", request
->u
.servicereg
.txtdata
);
2044 request
->u
.servicereg
.txtdata
= NULL
;
2045 return mStatus_BadParamErr
;
2048 // ***************************************************************************
2049 #if COMPILER_LIKES_PRAGMA_MARK
2051 #pragma mark - DNSServiceBrowse
2054 mDNSlocal
void FoundInstance(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2056 DNSServiceFlags flags
= AddRecord
? kDNSServiceFlagsAdd
: 0;
2057 request_state
*req
= question
->QuestionContext
;
2061 if (answer
->rrtype
!= kDNSType_PTR
)
2062 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req
->sd
, answer
->rrtype
); return; }
2064 if (mDNSOpaque16IsZero(question
->TargetQID
) && (question
->BrowseThreshold
> 0) && (question
->CurrentAnswers
>= question
->BrowseThreshold
))
2066 flags
|= kDNSServiceFlagsThresholdReached
;
2069 // if returning a negative answer, then use question's name in reply
2070 if (answer
->RecordType
== kDNSRecordTypePacketNegative
)
2072 GenerateBrowseReply(&question
->qname
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, kDNSServiceErr_NoSuchRecord
);
2076 if (GenerateNTDResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
) != mStatus_NoError
)
2078 if (SameDomainName(&req
->u
.browser
.regtype
, (const domainname
*)"\x09_services\x07_dns-sd\x04_udp"))
2080 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2081 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2082 GenerateBrowseReply(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
);
2086 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2087 req
->sd
, answer
->name
->c
, answer
->rdata
->u
.name
.c
);
2093 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2094 "[R%d->Q%d] DNSServiceBrowse(" PRI_DM_NAME
", " PUB_S
") RESULT " PUB_S
" interface %d: " PRI_S
,
2095 req
->request_id
, mDNSVal16(question
->TargetQID
), DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
),
2096 AddRecord
? "ADD" : "RMV", mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
),
2097 RRDisplayString(m
, answer
));
2099 append_reply(req
, rep
);
2102 mDNSlocal
void SetQuestionPolicy(DNSQuestion
*q
, request_state
*req
)
2105 // The policy is either based on pid or UUID. Pass a zero pid
2106 // to the "core" if the UUID is valid. If we always pass the pid,
2107 // then the "core" needs to determine whether the uuid is valid
2108 // by examining all the 16 bytes at the time of the policy
2109 // check and also when setting the delegate socket option. Also, it
2110 // requires that we zero out the uuid wherever the question is
2111 // initialized to make sure that it is not interpreted as valid.
2112 // To prevent these intrusive changes, just pass a zero pid to indicate
2113 // that pid is not valid when uuid is valid. In future if we need the
2114 // pid in the question, we will reevaluate this strategy.
2117 mDNSPlatformMemCopy(q
->uuid
, req
->uuid
, UUID_SIZE
);
2122 q
->pid
= req
->process_id
;
2125 //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
2128 mDNSlocal mStatus
add_domain_to_browser(request_state
*info
, const domainname
*d
)
2133 for (p
= info
->u
.browser
.browsers
; p
; p
= p
->next
)
2135 if (SameDomainName(&p
->domain
, d
))
2136 { debugf("add_domain_to_browser %##s already in list", d
->c
); return mStatus_AlreadyRegistered
; }
2139 b
= (browser_t
*) callocL("browser_t", sizeof(*b
));
2140 if (!b
) return mStatus_NoMemoryErr
;
2141 AssignDomainName(&b
->domain
, d
);
2142 SetQuestionPolicy(&b
->q
, info
);
2143 err
= mDNS_StartBrowse(&mDNSStorage
, &b
->q
, &info
->u
.browser
.regtype
, d
, info
->u
.browser
.interface_id
, info
->flags
,
2144 info
->u
.browser
.ForceMCast
, (info
->flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0, FoundInstance
, info
);
2147 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err
, info
->u
.browser
.regtype
.c
, d
->c
);
2148 freeL("browser_t/add_domain_to_browser", b
);
2152 b
->next
= info
->u
.browser
.browsers
;
2153 info
->u
.browser
.browsers
= b
;
2155 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2156 // Determine if this request should be promoted to use BLE triggered discovery.
2157 if (shouldUseBLE(info
->u
.browser
.interface_id
, 0, &info
->u
.browser
.regtype
, (domainname
*) d
))
2159 info
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2160 b
->q
.flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2161 LogInfo("add_domain_to_browser: request promoted to use kDNSServiceFlagsAutoTrigger");
2163 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2165 LogMcastQ(&b
->q
, info
, q_start
);
2166 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2167 if (callExternalHelpers(info
->u
.browser
.interface_id
, &b
->domain
, info
->flags
))
2170 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &b
->domain
);
2171 LogDebug("add_domain_to_browser: calling external_start_browsing_for_service()");
2172 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 while (info
->u
.browser
.browsers
)
2189 browser_t
*ptr
= info
->u
.browser
.browsers
;
2191 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2192 if (callExternalHelpers(ptr
->q
.InterfaceID
, &ptr
->domain
, ptr
->q
.flags
))
2195 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &ptr
->domain
);
2196 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2197 external_stop_browsing_for_service(ptr
->q
.InterfaceID
, &tmp
, kDNSType_PTR
, ptr
->q
.flags
);
2200 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2201 "[R%d] DNSServiceBrowse(%X, %d, \"" PRI_DM_NAME
"\") STOP PID[%d](" PUB_S
")",
2202 info
->request_id
, info
->flags
, info
->interfaceIndex
, DM_NAME_PARAM(ptr
->q
.qname
.c
),
2203 info
->process_id
, info
->pid_name
);
2205 info
->u
.browser
.browsers
= ptr
->next
;
2206 mDNS_StopBrowse(&mDNSStorage
, &ptr
->q
); // no need to error-check result
2207 LogMcastQ(&ptr
->q
, info
, q_stop
);
2208 freeL("browser_t/browse_termination_callback", ptr
);
2212 mDNSlocal
void udsserver_automatic_browse_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
2214 request_state
*request
;
2215 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
2217 for (request
= all_requests
; request
; request
= request
->next
)
2219 if (request
->terminate
!= browse_termination_callback
) continue; // Not a browse operation
2220 if (!request
->u
.browser
.default_domain
) continue; // Not an auto-browse operation
2221 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
2223 browser_t
**ptr
= &request
->u
.browser
.browsers
;
2224 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
2227 // If we don't already have this domain in our list for this browse operation, add it now
2228 if (!*ptr
) add_domain_to_browser(request
, &d
->name
);
2229 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d
->name
);
2233 if (!*ptr
) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d
->name
);
2237 for (p
= AutoBrowseDomains
; p
; p
=p
->next
)
2238 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
2239 if (SameDomainName(&d
->name
, &p
->name
)) break;
2240 if (p
) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d
->name
);
2243 browser_t
*rem
= *ptr
;
2244 *ptr
= (*ptr
)->next
;
2245 mDNS_StopQueryWithRemoves(&mDNSStorage
, &rem
->q
);
2246 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem
);
2254 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
2257 if (result
== mStatus_MemFree
)
2259 // On shutdown, mDNS_Close automatically deregisters all records
2260 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2261 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2262 // (This should actually no longer be necessary, now that we do the proper cleanup in
2263 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2264 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2265 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2266 while (*ptr
&& &(*ptr
)->ar
!= rr
) ptr
= &(*ptr
)->next
;
2267 if (*ptr
) { *ptr
= (*ptr
)->next
; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m
, rr
)); }
2268 mDNSPlatformMemFree(rr
->RecordContext
);
2272 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2273 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2274 // We may want to turn the common code into a subroutine.
2276 mDNSlocal
void RegisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2278 // allocate/register legacy and non-legacy _browse PTR record
2280 ARListElem
*ptr
= (ARListElem
*) mDNSPlatformMemAllocateClear(sizeof(*ptr
));
2282 debugf("Incrementing %s refcount for %##s",
2283 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2284 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2285 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2287 mDNS_SetupResourceRecord(&ptr
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, AuthRecordLocalOnly
, FreeARElemCallback
, ptr
);
2288 MakeDomainNameFromDNSNameString(&ptr
->ar
.namestorage
, mDNS_DomainTypeNames
[type
]);
2289 AppendDNSNameString (&ptr
->ar
.namestorage
, "local");
2290 AssignDomainName(&ptr
->ar
.resrec
.rdata
->u
.name
, d
);
2291 err
= mDNS_Register(m
, &ptr
->ar
);
2294 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err
);
2295 mDNSPlatformMemFree(ptr
);
2299 ptr
->next
= LocalDomainEnumRecords
;
2300 LocalDomainEnumRecords
= ptr
;
2304 mDNSlocal
void DeregisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2306 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2307 domainname lhs
; // left-hand side of PTR, for comparison
2309 debugf("Decrementing %s refcount for %##s",
2310 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2311 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2312 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2314 MakeDomainNameFromDNSNameString(&lhs
, mDNS_DomainTypeNames
[type
]);
2315 AppendDNSNameString (&lhs
, "local");
2319 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, d
) && SameDomainName((*ptr
)->ar
.resrec
.name
, &lhs
))
2321 ARListElem
*rem
= *ptr
;
2322 *ptr
= (*ptr
)->next
;
2323 mDNS_Deregister(m
, &rem
->ar
);
2326 else ptr
= &(*ptr
)->next
;
2330 mDNSlocal
void AddAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2332 DNameListElem
*new = (DNameListElem
*) mDNSPlatformMemAllocateClear(sizeof(*new));
2333 if (!new) { LogMsg("ERROR: malloc"); return; }
2334 AssignDomainName(&new->name
, name
);
2336 new->next
= AutoBrowseDomains
;
2337 AutoBrowseDomains
= new;
2338 udsserver_automatic_browse_domain_changed(new, mDNStrue
);
2341 mDNSlocal
void RmvAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2343 DNameListElem
**p
= &AutoBrowseDomains
;
2344 while (*p
&& (!SameDomainName(&(*p
)->name
, name
) || (*p
)->uid
!= uid
)) p
= &(*p
)->next
;
2345 if (!*p
) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name
->c
);
2348 DNameListElem
*ptr
= *p
;
2350 udsserver_automatic_browse_domain_changed(ptr
, mDNSfalse
);
2351 mDNSPlatformMemFree(ptr
);
2355 mDNSlocal
void SetPrefsBrowseDomains(mDNS
*m
, DNameListElem
*browseDomains
, mDNSBool add
)
2358 for (d
= browseDomains
; d
; d
= d
->next
)
2362 RegisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2363 AddAutoBrowseDomain(d
->uid
, &d
->name
);
2367 DeregisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2368 RmvAutoBrowseDomain(d
->uid
, &d
->name
);
2373 #if APPLE_OSX_mDNSResponder
2375 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
2377 int num_autoname
= 0;
2380 // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2381 for (req
= all_requests
; req
; req
= req
->next
)
2383 if (req
->terminate
== regservice_termination_callback
&& req
->u
.servicereg
.autoname
&& req
->interfaceIndex
!= kDNSServiceInterfaceIndexLocalOnly
)
2387 // If DeviceInfo record is currently registered, see if we need to deregister it
2388 if (m
->DeviceInfo
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
)
2389 if (num_autoname
== 0 || !SameDomainLabelCS(m
->DeviceInfo
.resrec
.name
->c
, m
->nicelabel
.c
))
2391 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m
->DeviceInfo
.resrec
.name
);
2392 mDNS_Deregister(m
, &m
->DeviceInfo
);
2395 // If DeviceInfo record is not currently registered, see if we need to register it
2396 if (m
->DeviceInfo
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2397 if (num_autoname
> 0)
2399 mDNS_SetupResourceRecord(&m
->DeviceInfo
, mDNSNULL
, mDNSNULL
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeAdvisory
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2400 ConstructServiceName(&m
->DeviceInfo
.namestorage
, &m
->nicelabel
, &DeviceInfoName
, &localdomain
);
2401 m
->DeviceInfo
.resrec
.rdlength
= initializeDeviceInfoTXT(m
, m
->DeviceInfo
.resrec
.rdata
->u
.data
);
2402 LogOperation("UpdateDeviceInfoRecord Register %##s", m
->DeviceInfo
.resrec
.name
);
2403 mDNS_Register(m
, &m
->DeviceInfo
);
2406 #else // APPLE_OSX_mDNSResponder
2407 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
2411 #endif // APPLE_OSX_mDNSResponder
2413 mDNSexport
void udsserver_handle_configchange(mDNS
*const m
)
2416 service_instance
*ptr
;
2417 DNameListElem
*RegDomains
= NULL
;
2418 DNameListElem
*BrowseDomains
= NULL
;
2421 UpdateDeviceInfoRecord(m
);
2423 // For autoname services, see if the default service name has changed, necessitating an automatic update
2424 for (req
= all_requests
; req
; req
= req
->next
)
2425 if (req
->terminate
== regservice_termination_callback
)
2426 if (req
->u
.servicereg
.autoname
&& !SameDomainLabelCS(req
->u
.servicereg
.name
.c
, m
->nicelabel
.c
))
2428 req
->u
.servicereg
.name
= m
->nicelabel
;
2429 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
2431 ptr
->renameonmemfree
= 1;
2432 if (ptr
->clientnotified
) SendServiceRemovalNotification(&ptr
->srs
);
2433 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr
->srs
.RR_PTR
.resrec
.name
->c
);
2434 if (mDNS_DeregisterService_drt(m
, &ptr
->srs
, mDNS_Dereg_rapid
))
2435 regservice_callback(m
, &ptr
->srs
, mStatus_MemFree
); // If service deregistered already, we can re-register immediately
2439 // Let the platform layer get the current DNS information
2441 mDNSPlatformSetDNSConfig(mDNSfalse
, mDNSfalse
, mDNSNULL
, &RegDomains
, &BrowseDomains
, mDNSfalse
);
2444 // Any automatic registration domains are also implicitly automatic browsing domains
2445 if (RegDomains
) SetPrefsBrowseDomains(m
, RegDomains
, mDNStrue
); // Add the new list first
2446 if (AutoRegistrationDomains
) SetPrefsBrowseDomains(m
, AutoRegistrationDomains
, mDNSfalse
); // Then clear the old list
2448 // Add any new domains not already in our AutoRegistrationDomains list
2449 for (p
=RegDomains
; p
; p
=p
->next
)
2451 DNameListElem
**pp
= &AutoRegistrationDomains
;
2452 while (*pp
&& ((*pp
)->uid
!= p
->uid
|| !SameDomainName(&(*pp
)->name
, &p
->name
))) pp
= &(*pp
)->next
;
2453 if (!*pp
) // If not found in our existing list, this is a new default registration domain
2455 RegisterLocalOnlyDomainEnumPTR(m
, &p
->name
, mDNS_DomainTypeRegistration
);
2456 udsserver_default_reg_domain_changed(p
, mDNStrue
);
2458 else // else found same domainname in both old and new lists, so no change, just delete old copy
2460 DNameListElem
*del
= *pp
;
2462 mDNSPlatformMemFree(del
);
2466 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2467 while (AutoRegistrationDomains
)
2469 DNameListElem
*del
= AutoRegistrationDomains
;
2470 AutoRegistrationDomains
= AutoRegistrationDomains
->next
; // Cut record from list FIRST,
2471 DeregisterLocalOnlyDomainEnumPTR(m
, &del
->name
, mDNS_DomainTypeRegistration
);
2472 udsserver_default_reg_domain_changed(del
, mDNSfalse
); // before calling udsserver_default_reg_domain_changed()
2473 mDNSPlatformMemFree(del
);
2476 // Now we have our new updated automatic registration domain list
2477 AutoRegistrationDomains
= RegDomains
;
2479 // Add new browse domains to internal list
2480 if (BrowseDomains
) SetPrefsBrowseDomains(m
, BrowseDomains
, mDNStrue
);
2482 // Remove old browse domains from internal list
2483 if (SCPrefBrowseDomains
)
2485 SetPrefsBrowseDomains(m
, SCPrefBrowseDomains
, mDNSfalse
);
2486 while (SCPrefBrowseDomains
)
2488 DNameListElem
*fptr
= SCPrefBrowseDomains
;
2489 SCPrefBrowseDomains
= SCPrefBrowseDomains
->next
;
2490 mDNSPlatformMemFree(fptr
);
2494 // Replace the old browse domains array with the new array
2495 SCPrefBrowseDomains
= BrowseDomains
;
2498 mDNSlocal
void AutomaticBrowseDomainChange(mDNS
*const m
, DNSQuestion
*q
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2503 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2504 AddRecord
? "Adding" : "Removing", answer
->rdata
->u
.name
.c
);
2506 if (AddRecord
) AddAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2507 else RmvAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2510 mDNSlocal mStatus
handle_browse_request(request_state
*request
)
2512 // Note that regtype may include a trailing subtype
2513 char regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2514 domainname typedn
, d
, temp
;
2515 mDNSs32 NumSubTypes
;
2516 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
, sizeof(regtype
)) < 0 ||
2540 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 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
); // Note: Modifies regtype string to remove trailing subtypes
2548 if (NumSubTypes
< 0 || NumSubTypes
> 1)
2549 return(mStatus_BadParamErr
);
2550 if (NumSubTypes
== 1)
2552 if (!AppendDNSNameString(&typedn
, regtype
+ strlen(regtype
) + 1))
2553 return(mStatus_BadParamErr
);
2556 if (!regtype
[0] || !AppendDNSNameString(&typedn
, regtype
)) return(mStatus_BadParamErr
);
2558 if (!MakeDomainNameFromDNSNameString(&temp
, regtype
)) return(mStatus_BadParamErr
);
2559 // For over-long service types, we only allow domain "local"
2560 if (temp
.c
[0] > 15 && domain
[0] == 0) mDNSPlatformStrLCopy(domain
, "local.", sizeof(domain
));
2562 // Set up browser info
2563 request
->u
.browser
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2564 request
->u
.browser
.interface_id
= InterfaceID
;
2565 AssignDomainName(&request
->u
.browser
.regtype
, &typedn
);
2566 request
->u
.browser
.default_domain
= !domain
[0];
2567 request
->u
.browser
.browsers
= NULL
;
2569 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceBrowse(%X, %d, \"" PRI_DM_NAME
"\", \"" PRI_S
"\") START PID[%d](" PUB_S
")",
2570 request
->request_id
, request
->flags
, interfaceIndex
, DM_NAME_PARAM(request
->u
.browser
.regtype
.c
), domain
,
2571 request
->process_id
, request
->pid_name
);
2573 if (request
->u
.browser
.default_domain
)
2575 // Start the domain enumeration queries to discover the WAB browse domains
2576 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2577 "[R%d] DNSServiceBrowse Start WAB PID[%d](" PUB_S
")",
2578 request
->request_id
, request
->process_id
, request
->pid_name
);
2579 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_LBROWSE_QUERY
);
2581 // We need to unconditionally set request->terminate, because even if we didn't successfully
2582 // start any browses right now, subsequent configuration changes may cause successful
2583 // browses to be added, and we'll need to cancel them before freeing this memory.
2584 request
->terminate
= browse_termination_callback
;
2588 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return(mStatus_BadParamErr
);
2589 err
= add_domain_to_browser(request
, &d
);
2593 DNameListElem
*sdom
;
2594 for (sdom
= AutoBrowseDomains
; sdom
; sdom
= sdom
->next
)
2595 if (!sdom
->uid
|| SystemUID(request
->uid
) || request
->uid
== sdom
->uid
)
2597 err
= add_domain_to_browser(request
, &sdom
->name
);
2600 if (SameDomainName(&sdom
->name
, &localdomain
)) break;
2601 else err
= mStatus_NoError
; // suppress errors for non-local "default" domains
2609 // ***************************************************************************
2610 #if COMPILER_LIKES_PRAGMA_MARK
2612 #pragma mark - DNSServiceResolve
2615 mDNSlocal
void resolve_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2618 char fullname
[MAX_ESCAPED_DOMAIN_NAME
], target
[MAX_ESCAPED_DOMAIN_NAME
] = "0";
2621 request_state
*req
= question
->QuestionContext
;
2622 const DNSServiceErrorType error
=
2623 (answer
->RecordType
== kDNSRecordTypePacketNegative
) ? kDNSServiceErr_NoSuchRecord
: kDNSServiceErr_NoError
;
2626 LogOperation("%3d: DNSServiceResolve(%##s) %s interface %d: %s",
2627 req
->sd
, question
->qname
.c
, AddRecord
? "ADD" : "RMV",
2628 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
), RRDisplayString(m
, answer
));
2632 if (req
->u
.resolve
.srv
== answer
) req
->u
.resolve
.srv
= mDNSNULL
;
2633 if (req
->u
.resolve
.txt
== answer
) req
->u
.resolve
.txt
= mDNSNULL
;
2637 if (answer
->rrtype
== kDNSType_SRV
) req
->u
.resolve
.srv
= answer
;
2638 if (answer
->rrtype
== kDNSType_TXT
) req
->u
.resolve
.txt
= answer
;
2640 if (!req
->u
.resolve
.txt
|| !req
->u
.resolve
.srv
) return; // only deliver result to client if we have both answers
2642 ConvertDomainNameToCString(answer
->name
, fullname
);
2644 if (answer
->RecordType
!= kDNSRecordTypePacketNegative
)
2645 ConvertDomainNameToCString(&req
->u
.resolve
.srv
->rdata
->u
.srv
.target
, target
);
2647 // calculate reply length
2648 len
+= sizeof(DNSServiceFlags
);
2649 len
+= sizeof(mDNSu32
); // interface index
2650 len
+= sizeof(DNSServiceErrorType
);
2651 len
+= strlen(fullname
) + 1;
2652 len
+= strlen(target
) + 1;
2653 len
+= 2 * sizeof(mDNSu16
); // port, txtLen
2654 len
+= req
->u
.resolve
.txt
->rdlength
;
2656 // allocate/init reply header
2657 rep
= create_reply(resolve_reply_op
, len
, req
);
2658 rep
->rhdr
->flags
= dnssd_htonl(0);
2659 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
));
2660 rep
->rhdr
->error
= dnssd_htonl(error
);
2662 data
= (char *)&rep
->rhdr
[1];
2664 // write reply data to message
2665 put_string(fullname
, &data
);
2666 put_string(target
, &data
);
2667 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[0];
2668 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[1];
2669 put_uint16(req
->u
.resolve
.txt
->rdlength
, &data
);
2670 put_rdata (req
->u
.resolve
.txt
->rdlength
, req
->u
.resolve
.txt
->rdata
->u
.data
, &data
);
2672 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d->Q%d] DNSServiceResolve(" PRI_S
") RESULT " PRI_S
":%d",
2673 req
->request_id
, mDNSVal16(question
->TargetQID
), fullname
, target
,
2674 mDNSVal16(req
->u
.resolve
.srv
->rdata
->u
.srv
.port
));
2675 append_reply(req
, rep
);
2678 mDNSlocal
void resolve_termination_callback(request_state
*request
)
2680 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2681 "[R%d] DNSServiceResolve(%X, %d, \"" PRI_DM_NAME
"\") STOP PID[%d](" PUB_S
")",
2682 request
->request_id
, request
->flags
, request
->interfaceIndex
, DM_NAME_PARAM(request
->u
.resolve
.qtxt
.qname
.c
),
2683 request
->process_id
, request
->pid_name
);
2684 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2685 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2686 LogMcastQ(&request
->u
.resolve
.qsrv
, request
, q_stop
);
2687 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2688 if (request
->u
.resolve
.external_advertise
)
2689 external_stop_resolving_service(request
->u
.resolve
.qsrv
.InterfaceID
, &request
->u
.resolve
.qsrv
.qname
, request
->flags
);
2693 mDNSlocal mStatus
handle_resolve_request(request_state
*request
)
2695 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2699 // extract the data from the message
2700 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2701 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2702 mDNSInterfaceID InterfaceID
;
2704 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2705 // flag set so that the resolve will run over P2P interfaces that are not yet created.
2706 if (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)
2708 LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2709 flags
|= kDNSServiceFlagsIncludeP2P
;
2710 interfaceIndex
= kDNSServiceInterfaceIndexAny
;
2713 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2715 // The operation is scoped to a specific interface index, but the
2716 // interface is not currently in our list.
2717 if (interfaceIndex
&& !InterfaceID
)
2719 // If it's one of the specially defined inteface index values, just return an error.
2720 if (PreDefinedInterfaceIndex(interfaceIndex
))
2722 LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex
);
2723 return(mStatus_BadParamErr
);
2726 // Otherwise, use the specified interface index value and the operation will
2727 // be applied to that interface when it comes up.
2728 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
2729 LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex
);
2732 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
2733 get_string(&request
->msgptr
, request
->msgend
, regtype
, sizeof(regtype
)) < 0 ||
2734 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 0)
2735 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
2737 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2739 if (build_domainname_from_strings(&fqdn
, name
, regtype
, domain
) < 0)
2740 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name
, regtype
, domain
); return(mStatus_BadParamErr
); }
2742 mDNSPlatformMemZero(&request
->u
.resolve
, sizeof(request
->u
.resolve
));
2744 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2745 // Determine if this request should be promoted to use BLE triggered discovery.
2746 if (shouldUseBLE(InterfaceID
, 0, (domainname
*)SkipLeadingLabels(&fqdn
, 1), &fqdn
))
2748 flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2749 LogInfo("handle_resolve_request: request promoted to use kDNSServiceFlagsAutoTrigger");
2751 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2753 request
->flags
= flags
;
2754 request
->interfaceIndex
= interfaceIndex
;
2757 request
->u
.resolve
.qsrv
.InterfaceID
= InterfaceID
;
2758 request
->u
.resolve
.qsrv
.flags
= flags
;
2759 AssignDomainName(&request
->u
.resolve
.qsrv
.qname
, &fqdn
);
2760 request
->u
.resolve
.qsrv
.qtype
= kDNSType_SRV
;
2761 request
->u
.resolve
.qsrv
.qclass
= kDNSClass_IN
;
2762 request
->u
.resolve
.qsrv
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2763 request
->u
.resolve
.qsrv
.ExpectUnique
= mDNStrue
;
2764 request
->u
.resolve
.qsrv
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2765 request
->u
.resolve
.qsrv
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2766 request
->u
.resolve
.qsrv
.SuppressUnusable
= mDNSfalse
;
2767 request
->u
.resolve
.qsrv
.AppendSearchDomains
= 0;
2768 request
->u
.resolve
.qsrv
.TimeoutQuestion
= 0;
2769 request
->u
.resolve
.qsrv
.WakeOnResolve
= (flags
& kDNSServiceFlagsWakeOnResolve
) != 0;
2770 request
->u
.resolve
.qsrv
.UseBackgroundTraffic
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
2771 request
->u
.resolve
.qsrv
.ValidationRequired
= 0;
2772 request
->u
.resolve
.qsrv
.ValidatingResponse
= 0;
2773 request
->u
.resolve
.qsrv
.ProxyQuestion
= 0;
2774 request
->u
.resolve
.qsrv
.pid
= request
->process_id
;
2775 request
->u
.resolve
.qsrv
.euid
= request
->uid
;
2776 request
->u
.resolve
.qsrv
.QuestionCallback
= resolve_result_callback
;
2777 request
->u
.resolve
.qsrv
.QuestionContext
= request
;
2779 request
->u
.resolve
.qtxt
.InterfaceID
= InterfaceID
;
2780 request
->u
.resolve
.qtxt
.flags
= flags
;
2781 AssignDomainName(&request
->u
.resolve
.qtxt
.qname
, &fqdn
);
2782 request
->u
.resolve
.qtxt
.qtype
= kDNSType_TXT
;
2783 request
->u
.resolve
.qtxt
.qclass
= kDNSClass_IN
;
2784 request
->u
.resolve
.qtxt
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2785 request
->u
.resolve
.qtxt
.ExpectUnique
= mDNStrue
;
2786 request
->u
.resolve
.qtxt
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2787 request
->u
.resolve
.qtxt
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2788 request
->u
.resolve
.qtxt
.SuppressUnusable
= mDNSfalse
;
2789 request
->u
.resolve
.qtxt
.AppendSearchDomains
= 0;
2790 request
->u
.resolve
.qtxt
.TimeoutQuestion
= 0;
2791 request
->u
.resolve
.qtxt
.WakeOnResolve
= 0;
2792 request
->u
.resolve
.qtxt
.UseBackgroundTraffic
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
2793 request
->u
.resolve
.qtxt
.ValidationRequired
= 0;
2794 request
->u
.resolve
.qtxt
.ValidatingResponse
= 0;
2795 request
->u
.resolve
.qtxt
.ProxyQuestion
= 0;
2796 request
->u
.resolve
.qtxt
.pid
= request
->process_id
;
2797 request
->u
.resolve
.qtxt
.euid
= request
->uid
;
2798 request
->u
.resolve
.qtxt
.QuestionCallback
= resolve_result_callback
;
2799 request
->u
.resolve
.qtxt
.QuestionContext
= request
;
2801 request
->u
.resolve
.ReportTime
= NonZeroTime(mDNS_TimeNow(&mDNSStorage
) + 130 * mDNSPlatformOneSecond
);
2803 request
->u
.resolve
.external_advertise
= mDNSfalse
;
2806 if (!AuthorizedDomain(request
, &fqdn
, AutoBrowseDomains
)) return(mStatus_NoError
);
2809 // ask the questions
2810 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2811 "[R%d] DNSServiceResolve(%X, %d, \"" PRI_DM_NAME
"\") START PID[%d](" PUB_S
")",
2812 request
->request_id
, flags
, interfaceIndex
, DM_NAME_PARAM(request
->u
.resolve
.qsrv
.qname
.c
),
2813 request
->process_id
, request
->pid_name
);
2815 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2819 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2822 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2826 request
->terminate
= resolve_termination_callback
;
2827 LogMcastQ(&request
->u
.resolve
.qsrv
, request
, q_start
);
2828 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2829 if (callExternalHelpers(InterfaceID
, &fqdn
, flags
))
2831 request
->u
.resolve
.external_advertise
= mDNStrue
;
2832 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2833 external_start_resolving_service(InterfaceID
, &fqdn
, flags
);
2842 // ***************************************************************************
2843 #if COMPILER_LIKES_PRAGMA_MARK
2845 #pragma mark - DNSServiceQueryRecord
2848 mDNSlocal
void queryrecord_result_reply(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
, DNSServiceErrorType error
, void *context
)
2850 char name
[MAX_ESCAPED_DOMAIN_NAME
];
2852 DNSServiceFlags flags
= 0;
2855 request_state
*req
= (request_state
*)context
;
2857 ConvertDomainNameToCString(answer
->name
, name
);
2859 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2860 "[R%u->Q%u] DNSService" PUB_S
"(" PRI_DM_NAME
", " PUB_S
") RESULT " PUB_S
" interface %d: (" PUB_S
")" PRI_S
,
2861 req
->request_id
, mDNSVal16(question
->TargetQID
), req
->hdr
.op
== query_request
? "QueryRecord" : "GetAddrInfo",
2862 DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
), AddRecord
? "ADD" : "RMV",
2863 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
),
2864 MortalityDisplayString(answer
->mortality
), RRDisplayString(m
, answer
));
2866 len
= sizeof(DNSServiceFlags
); // calculate reply data length
2867 len
+= sizeof(mDNSu32
); // interface index
2868 len
+= sizeof(DNSServiceErrorType
);
2869 len
+= strlen(name
) + 1;
2870 len
+= 3 * sizeof(mDNSu16
); // type, class, rdlen
2871 len
+= answer
->rdlength
;
2872 len
+= sizeof(mDNSu32
); // TTL
2874 rep
= create_reply(req
->hdr
.op
== query_request
? query_reply_op
: addrinfo_reply_op
, len
, req
);
2877 flags
|= kDNSServiceFlagsAdd
;
2878 if (answer
->mortality
== Mortality_Ghost
)
2879 flags
|= kDNSServiceFlagsExpiredAnswer
;
2880 if (!question
->InitialCacheMiss
)
2881 flags
|= kDNSServiceFlagAnsweredFromCache
;
2882 if (question
->ValidationStatus
!= 0)
2884 error
= kDNSServiceErr_NoError
;
2885 if (question
->ValidationRequired
&& question
->ValidationState
== DNSSECValDone
)
2887 switch (question
->ValidationStatus
) //Set the dnssec flags to be passed on to the Apps here
2890 flags
|= kDNSServiceFlagsSecure
;
2892 case DNSSEC_Insecure
:
2893 flags
|= kDNSServiceFlagsInsecure
;
2895 case DNSSEC_Indeterminate
:
2896 flags
|= kDNSServiceFlagsIndeterminate
;
2899 flags
|= kDNSServiceFlagsBogus
;
2902 LogMsg("queryrecord_result_reply unknown status %d for %##s", question
->ValidationStatus
, question
->qname
.c
);
2907 rep
->rhdr
->flags
= dnssd_htonl(flags
);
2908 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
2909 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
2910 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
2911 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
2912 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
2913 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
2914 // should not have existed to answer this question if the corresponding interface is not valid.
2915 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNStrue
));
2916 rep
->rhdr
->error
= dnssd_htonl(error
);
2918 data
= (char *)&rep
->rhdr
[1];
2920 put_string(name
, &data
);
2921 put_uint16(answer
->rrtype
, &data
);
2922 put_uint16(answer
->rrclass
, &data
);
2923 put_uint16(answer
->rdlength
, &data
);
2924 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2925 // function just does a blind memory copy without regard to structures that may have holes in them.
2926 if (answer
->rdlength
)
2927 if (!putRData(mDNSNULL
, (mDNSu8
*)data
, (mDNSu8
*)rep
->rhdr
+ len
, answer
))
2928 LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8
*)rep
->rhdr
+ len
- (mDNSu8
*)data
);
2929 data
+= answer
->rdlength
;
2930 put_uint32(AddRecord
? answer
->rroriginalttl
: 0, &data
);
2932 append_reply(req
, rep
);
2935 mDNSlocal
void queryrecord_termination_callback(request_state
*request
)
2937 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2938 "[R%u] DNSServiceQueryRecord(%X, %d, " PRI_DM_NAME
", " PUB_S
") STOP PID[%d](" PUB_S
")",
2939 request
->request_id
, request
->flags
, request
->interfaceIndex
,
2940 DM_NAME_PARAM(QueryRecordClientRequestGetQName(&request
->u
.queryrecord
)->c
),
2941 DNSTypeName(QueryRecordClientRequestGetType(&request
->u
.queryrecord
)), request
->process_id
, request
->pid_name
);
2943 QueryRecordClientRequestStop(&request
->u
.queryrecord
);
2946 mDNSlocal mStatus
handle_queryrecord_request(request_state
*request
)
2949 DNSServiceFlags flags
;
2950 mDNSu32 interfaceIndex
;
2951 mDNSu16 qtype
, qclass
;
2952 char qname
[MAX_ESCAPED_DOMAIN_NAME
];
2954 flags
= get_flags(&request
->msgptr
, request
->msgend
);
2955 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2956 if (get_string(&request
->msgptr
, request
->msgend
, qname
, sizeof(qname
)) < 0)
2958 err
= mStatus_BadParamErr
;
2961 qtype
= get_uint16(&request
->msgptr
, request
->msgend
);
2962 qclass
= get_uint16(&request
->msgptr
, request
->msgend
);
2964 if (!request
->msgptr
)
2966 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
2967 "[R%d] DNSServiceQueryRecord(unreadable parameters)", request
->request_id
);
2968 err
= mStatus_BadParamErr
;
2972 request
->flags
= flags
;
2973 request
->interfaceIndex
= interfaceIndex
;
2975 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2976 "[R%d] DNSServiceQueryRecord(%X, %d, " PRI_S
", " PUB_S
") START PID[%d](" PUB_S
")",
2977 request
->request_id
, request
->flags
, request
->interfaceIndex
, qname
, DNSTypeName(qtype
), request
->process_id
,
2980 mDNSPlatformMemZero(&request
->u
.queryrecord
, (mDNSu32
)sizeof(request
->u
.queryrecord
));
2982 err
= QueryRecordClientRequestStart(&request
->u
.queryrecord
, request
->request_id
, qname
, interfaceIndex
, flags
, qtype
,
2983 qclass
, request
->validUUID
? 0 : request
->process_id
, request
->validUUID
? request
->uuid
: mDNSNULL
, request
->uid
,
2984 queryrecord_result_reply
, request
);
2987 request
->terminate
= queryrecord_termination_callback
;
2993 // ***************************************************************************
2994 #if COMPILER_LIKES_PRAGMA_MARK
2996 #pragma mark - DNSServiceEnumerateDomains
2999 mDNSlocal reply_state
*format_enumeration_reply(request_state
*request
,
3000 const char *domain
, DNSServiceFlags flags
, mDNSu32 ifi
, DNSServiceErrorType err
)
3006 len
= sizeof(DNSServiceFlags
);
3007 len
+= sizeof(mDNSu32
);
3008 len
+= sizeof(DNSServiceErrorType
);
3009 len
+= strlen(domain
) + 1;
3011 reply
= create_reply(enumeration_reply_op
, len
, request
);
3012 reply
->rhdr
->flags
= dnssd_htonl(flags
);
3013 reply
->rhdr
->ifi
= dnssd_htonl(ifi
);
3014 reply
->rhdr
->error
= dnssd_htonl(err
);
3015 data
= (char *)&reply
->rhdr
[1];
3016 put_string(domain
, &data
);
3020 mDNSlocal
void enum_termination_callback(request_state
*request
)
3022 // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3023 if (request
->u
.enumeration
.flags
& kDNSServiceFlagsRegistrationDomains
)
3025 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3026 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_REG_QUERY
);
3030 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3031 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_BROWSE_QUERY
| UDNS_WAB_LBROWSE_QUERY
);
3032 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_autoall
);
3034 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3035 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3038 mDNSlocal
void enum_result_callback(mDNS
*const m
,
3039 DNSQuestion
*const question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
3041 char domain
[MAX_ESCAPED_DOMAIN_NAME
];
3042 request_state
*request
= question
->QuestionContext
;
3043 DNSServiceFlags flags
= 0;
3047 if (answer
->rrtype
!= kDNSType_PTR
) return;
3050 if (!AuthorizedDomain(request
, &answer
->rdata
->u
.name
, request
->u
.enumeration
.flags
? AutoRegistrationDomains
: AutoBrowseDomains
)) return;
3053 // We only return add/remove events for the browse and registration lists
3054 // For the default browse and registration answers, we only give an "ADD" event
3055 if (question
== &request
->u
.enumeration
.q_default
&& !AddRecord
) return;
3059 flags
|= kDNSServiceFlagsAdd
;
3060 if (question
== &request
->u
.enumeration
.q_default
) flags
|= kDNSServiceFlagsDefault
;
3063 ConvertDomainNameToCString(&answer
->rdata
->u
.name
, domain
);
3064 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3065 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3066 // network, so we just pass kDNSServiceInterfaceIndexAny
3067 reply
= format_enumeration_reply(request
, domain
, flags
, kDNSServiceInterfaceIndexAny
, kDNSServiceErr_NoError
);
3068 if (!reply
) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3070 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3071 "[R%d->Q%d] DNSServiceEnumerateDomains(%2.*s) RESULT " PUB_S
": " PRI_S
,
3072 request
->request_id
, mDNSVal16(question
->TargetQID
), question
->qname
.c
[0], &question
->qname
.c
[1],
3073 AddRecord
? "ADD" : "RMV", domain
);
3075 append_reply(request
, reply
);
3078 mDNSlocal mStatus
handle_enum_request(request_state
*request
)
3081 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3082 DNSServiceFlags reg
= flags
& kDNSServiceFlagsRegistrationDomains
;
3083 mDNS_DomainType t_all
= reg
? mDNS_DomainTypeRegistration
: mDNS_DomainTypeBrowse
;
3084 mDNS_DomainType t_default
= reg
? mDNS_DomainTypeRegistrationDefault
: mDNS_DomainTypeBrowseDefault
;
3085 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3086 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3087 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3089 if (!request
->msgptr
)
3090 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3092 request
->flags
= flags
;
3093 request
->interfaceIndex
= interfaceIndex
;
3095 // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
3096 request
->u
.enumeration
.flags
= reg
;
3098 // enumeration requires multiple questions, so we must link all the context pointers so that
3099 // necessary context can be reached from the callbacks
3100 request
->u
.enumeration
.q_all
.QuestionContext
= request
;
3101 request
->u
.enumeration
.q_default
.QuestionContext
= request
;
3102 if (!reg
) request
->u
.enumeration
.q_autoall
.QuestionContext
= request
;
3104 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3105 if (!InterfaceID
) InterfaceID
= mDNSInterface_LocalOnly
;
3108 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request
->sd
, flags
,
3109 (flags
& kDNSServiceFlagsBrowseDomains
) ? "kDNSServiceFlagsBrowseDomains" :
3110 (flags
& kDNSServiceFlagsRegistrationDomains
) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3111 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
, t_all
, NULL
, InterfaceID
, enum_result_callback
, request
);
3114 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
, t_default
, NULL
, InterfaceID
, enum_result_callback
, request
);
3115 if (err
) mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3118 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_autoall
, mDNS_DomainTypeBrowseAutomatic
, NULL
, InterfaceID
, enum_result_callback
, request
);
3121 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3122 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3125 if (!err
) request
->terminate
= enum_termination_callback
;
3129 // Start the domain enumeration queries to discover the WAB Browse/Registration domains
3132 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3133 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_REG_QUERY
);
3137 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3138 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_BROWSE_QUERY
| UDNS_WAB_LBROWSE_QUERY
);
3145 // ***************************************************************************
3146 #if COMPILER_LIKES_PRAGMA_MARK
3148 #pragma mark - DNSServiceReconfirmRecord & Misc
3151 mDNSlocal mStatus
handle_reconfirm_request(request_state
*request
)
3153 mStatus status
= mStatus_BadParamErr
;
3154 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 0, 0);
3157 status
= mDNS_ReconfirmByValue(&mDNSStorage
, &rr
->resrec
);
3159 (status
== mStatus_NoError
) ?
3160 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated PID[%d](%s)" :
3161 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed PID[%d](%s) status %d",
3162 request
->sd
, RRDisplayString(&mDNSStorage
, &rr
->resrec
),
3163 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, rr
->resrec
.InterfaceID
, mDNSfalse
),
3164 request
->process_id
, request
->pid_name
, status
);
3165 freeL("AuthRecord/handle_reconfirm_request", rr
);
3170 #if APPLE_OSX_mDNSResponder
3172 mDNSlocal mStatus
handle_release_request(request_state
*request
)
3175 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
3176 domainname instance
;
3178 // extract the data from the message
3179 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3181 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
3182 get_string(&request
->msgptr
, request
->msgend
, regtype
, sizeof(regtype
)) < 0 ||
3183 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 0)
3185 LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
3186 return(mStatus_BadParamErr
);
3189 if (!request
->msgptr
)
3191 LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request
->sd
);
3192 return(mStatus_BadParamErr
);
3195 if (build_domainname_from_strings(&instance
, name
, regtype
, domain
) < 0)
3197 LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name
, regtype
, domain
);
3198 return(mStatus_BadParamErr
);
3201 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3202 "[R%d] PeerConnectionRelease(%X " PRI_DM_NAME
") START PID[%d](" PUB_S
")",
3203 request
->request_id
, flags
, DM_NAME_PARAM(instance
.c
), request
->process_id
, request
->pid_name
);
3205 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
3206 external_connection_release(&instance
);
3211 #else // APPLE_OSX_mDNSResponder
3213 mDNSlocal mStatus
handle_release_request(request_state
*request
)
3216 return mStatus_UnsupportedErr
;
3219 #endif // APPLE_OSX_mDNSResponder
3221 mDNSlocal mStatus
handle_setdomain_request(request_state
*request
)
3223 char domainstr
[MAX_ESCAPED_DOMAIN_NAME
];
3225 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3226 (void)flags
; // Unused
3227 if (get_string(&request
->msgptr
, request
->msgend
, domainstr
, sizeof(domainstr
)) < 0 ||
3228 !MakeDomainNameFromDNSNameString(&domain
, domainstr
))
3229 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3231 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request
->sd
, domain
.c
);
3232 return(mStatus_NoError
);
3235 typedef packedstruct
3240 } DaemonVersionReply
;
3242 mDNSlocal
void handle_getproperty_request(request_state
*request
)
3244 const mStatus BadParamErr
= dnssd_htonl((mDNSu32
)mStatus_BadParamErr
);
3246 if (get_string(&request
->msgptr
, request
->msgend
, prop
, sizeof(prop
)) >= 0)
3248 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3249 "[R%d] DNSServiceGetProperty(" PUB_S
")", request
->request_id
, prop
);
3250 if (!strcmp(prop
, kDNSServiceProperty_DaemonVersion
))
3252 DaemonVersionReply x
= { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H
) };
3253 send_all(request
->sd
, (const char *)&x
, sizeof(x
));
3258 // If we didn't recogize the requested property name, return BadParamErr
3259 send_all(request
->sd
, (const char *)&BadParamErr
, sizeof(BadParamErr
));
3262 #ifdef APPLE_OSX_mDNSResponder
3263 // The caller can specify either the pid or the uuid. If the pid is not specified,
3264 // update the effective uuid. Don't overwrite the pid which is used for debugging
3265 // purposes and initialized when the socket is opened.
3266 mDNSlocal
void handle_connection_delegate_request(request_state
*request
)
3271 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3272 "[R%d] DNSServiceCreateDelegateConnection START PID[%d](" PUB_S
")",
3273 request
->request_id
, request
->process_id
, request
->pid_name
);
3274 request
->terminate
= connection_termination
;
3277 pid
= get_uint32(&request
->msgptr
, request
->msgend
);
3278 #ifdef LOCAL_PEEREPID
3282 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREPID
, &request
->process_id
, &len
) != 0)
3284 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno
, strerror(errno
));
3287 // to extract the process name from the pid value
3288 if (proc_pidinfo(request
->process_id
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0)
3290 mDNSPlatformStrLCopy(request
->pid_name
, proc
.pbsi_comm
, sizeof(request
->pid_name
));
3291 debugf("handle_connection_delegate_request: process id %d, name %s", request
->process_id
, request
->pid_name
);
3294 #ifdef LOCAL_PEEREUUID
3298 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREUUID
, request
->uuid
, &len
) != 0)
3300 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno
, strerror(errno
));
3303 request
->validUUID
= mDNStrue
;
3308 mDNSlocal
void handle_connection_delegate_request(request_state
*request
)
3314 typedef packedstruct
3320 // ***************************************************************************
3321 #if COMPILER_LIKES_PRAGMA_MARK
3323 #pragma mark - DNSServiceNATPortMappingCreate
3326 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
3328 mDNSlocal
void port_mapping_termination_callback(request_state
*request
)
3330 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](" PUB_S
")",
3331 request
->request_id
, DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3332 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
3333 request
->process_id
, request
->pid_name
);
3335 mDNS_StopNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3338 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
3339 mDNSlocal
void port_mapping_create_request_callback(mDNS
*m
, NATTraversalInfo
*n
)
3341 request_state
*request
= (request_state
*)n
->clientContext
;
3346 if (!request
) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
3348 // calculate reply data length
3349 replyLen
= sizeof(DNSServiceFlags
);
3350 replyLen
+= 3 * sizeof(mDNSu32
); // if index + addr + ttl
3351 replyLen
+= sizeof(DNSServiceErrorType
);
3352 replyLen
+= 2 * sizeof(mDNSu16
); // Internal Port + External Port
3353 replyLen
+= sizeof(mDNSu8
); // protocol
3355 rep
= create_reply(port_mapping_reply_op
, replyLen
, request
);
3357 rep
->rhdr
->flags
= dnssd_htonl(0);
3358 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, n
->InterfaceID
, mDNSfalse
));
3359 rep
->rhdr
->error
= dnssd_htonl(n
->Result
);
3361 data
= (char *)&rep
->rhdr
[1];
3363 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[0];
3364 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[1];
3365 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[2];
3366 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[3];
3367 *data
++ = DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
);
3368 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[0];
3369 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[1];
3370 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[0];
3371 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[1];
3372 put_uint32(request
->u
.pm
.NATinfo
.Lifetime
, &data
);
3374 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3375 "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT " PRI_IPv4_ADDR
":%u TTL %u",
3376 request
->request_id
, DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3377 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
3378 &request
->u
.pm
.NATinfo
.ExternalAddress
, mDNSVal16(request
->u
.pm
.NATinfo
.ExternalPort
),
3379 request
->u
.pm
.NATinfo
.Lifetime
);
3381 append_reply(request
, rep
);
3384 mDNSlocal mStatus
handle_port_mapping_request(request_state
*request
)
3387 mStatus err
= mStatus_NoError
;
3389 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3390 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3391 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3392 mDNSu8 protocol
= (mDNSu8
)get_uint32(&request
->msgptr
, request
->msgend
);
3393 (void)flags
; // Unused
3394 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3395 if (request
->msgptr
+ 8 > request
->msgend
) request
->msgptr
= NULL
;
3398 request
->u
.pm
.NATinfo
.IntPort
.b
[0] = *request
->msgptr
++;
3399 request
->u
.pm
.NATinfo
.IntPort
.b
[1] = *request
->msgptr
++;
3400 request
->u
.pm
.ReqExt
.b
[0] = *request
->msgptr
++;
3401 request
->u
.pm
.ReqExt
.b
[1] = *request
->msgptr
++;
3402 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
3405 if (!request
->msgptr
)
3407 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3408 "[R%d] DNSServiceNATPortMappingCreate(unreadable parameters)", request
->request_id
);
3409 return(mStatus_BadParamErr
);
3412 if (protocol
== 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
3414 if (!mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
) || !mDNSIPPortIsZero(request
->u
.pm
.ReqExt
) || ttl
) return(mStatus_BadParamErr
);
3418 if (mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
)) return(mStatus_BadParamErr
);
3419 if (!(protocol
& (kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
))) return(mStatus_BadParamErr
);
3422 request
->flags
= flags
;
3423 request
->interfaceIndex
= interfaceIndex
;
3424 request
->u
.pm
.NATinfo
.Protocol
= !protocol
? NATOp_AddrRequest
: (protocol
== kDNSServiceProtocol_UDP
) ? NATOp_MapUDP
: NATOp_MapTCP
;
3425 // u.pm.NATinfo.IntPort = already set above
3426 request
->u
.pm
.NATinfo
.RequestedPort
= request
->u
.pm
.ReqExt
;
3427 request
->u
.pm
.NATinfo
.NATLease
= ttl
;
3428 request
->u
.pm
.NATinfo
.clientCallback
= port_mapping_create_request_callback
;
3429 request
->u
.pm
.NATinfo
.clientContext
= request
;
3431 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3432 "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](" PUB_S
")",
3433 request
->request_id
, protocol
, mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
),
3434 request
->u
.pm
.NATinfo
.NATLease
, request
->process_id
, request
->pid_name
);
3435 err
= mDNS_StartNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3436 if (err
) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err
);
3437 else request
->terminate
= port_mapping_termination_callback
;
3442 // ***************************************************************************
3443 #if COMPILER_LIKES_PRAGMA_MARK
3445 #pragma mark - DNSServiceGetAddrInfo
3448 mDNSlocal
void addrinfo_termination_callback(request_state
*request
)
3450 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3451 "[R%u] DNSServiceGetAddrInfo(" PRI_DM_NAME
") STOP PID[%d](" PUB_S
")",
3452 request
->request_id
, DM_NAME_PARAM(GetAddrInfoClientRequestGetQName(&request
->u
.addrinfo
)->c
),
3453 request
->process_id
, request
->pid_name
);
3455 GetAddrInfoClientRequestStop(&request
->u
.addrinfo
);
3458 mDNSlocal mStatus
handle_addrinfo_request(request_state
*request
)
3461 DNSServiceFlags flags
;
3462 mDNSu32 interfaceIndex
;
3464 char hostname
[MAX_ESCAPED_DOMAIN_NAME
];
3466 flags
= get_flags(&request
->msgptr
, request
->msgend
);
3467 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3468 protocols
= get_uint32(&request
->msgptr
, request
->msgend
);
3469 if (get_string(&request
->msgptr
, request
->msgend
, hostname
, sizeof(hostname
)) < 0)
3471 err
= mStatus_BadParamErr
;
3474 if (!request
->msgptr
)
3476 LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request
->sd
);
3477 err
= mStatus_BadParamErr
;
3481 request
->flags
= flags
;
3482 request
->interfaceIndex
= interfaceIndex
;
3484 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3485 "[R%u] DNSServiceGetAddrInfo(%X, %d, %u, " PRI_S
") START PID[%d](" PUB_S
")",
3486 request
->request_id
, request
->flags
, request
->interfaceIndex
, protocols
, hostname
, request
->process_id
,
3489 mDNSPlatformMemZero(&request
->u
.addrinfo
, (mDNSu32
)sizeof(request
->u
.addrinfo
));
3491 err
= GetAddrInfoClientRequestStart(&request
->u
.addrinfo
, request
->request_id
, hostname
, interfaceIndex
, flags
,
3492 protocols
, request
->validUUID
? 0 : request
->process_id
, request
->validUUID
? request
->uuid
: mDNSNULL
,
3493 request
->uid
, queryrecord_result_reply
, request
);
3496 request
->terminate
= addrinfo_termination_callback
;
3502 // ***************************************************************************
3503 #if COMPILER_LIKES_PRAGMA_MARK
3505 #pragma mark - Main Request Handler etc.
3508 mDNSlocal request_state
*NewRequest(void)
3510 request_state
*request
;
3511 request_state
**p
= &all_requests
;
3512 request
= (request_state
*) callocL("request_state", sizeof(*request
));
3513 if (!request
) FatalError("ERROR: calloc");
3514 while (*p
) p
= &(*p
)->next
;
3519 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
3520 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
3521 mDNSlocal
void read_msg(request_state
*req
)
3523 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
3525 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3526 "[R%u] ERROR: read_msg called with transfer state terminated or error", req
->request_id
);
3531 if (req
->ts
== t_complete
) // this must be death or something is wrong
3533 char buf
[4]; // dummy for death notification
3534 int nread
= udsSupportReadFD(req
->sd
, buf
, 4, 0, req
->platform_data
);
3535 if (!nread
) { req
->ts
= t_terminated
; return; }
3536 if (nread
< 0) goto rerror
;
3537 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3538 "[R%u] ERROR: read data from a completed request", req
->request_id
);
3543 if (req
->ts
!= t_morecoming
)
3545 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3546 "[R%u] ERROR: read_msg called with invalid transfer state (%d)", req
->request_id
, req
->ts
);
3551 if (req
->hdr_bytes
< sizeof(ipc_msg_hdr
))
3553 mDNSu32 nleft
= sizeof(ipc_msg_hdr
) - req
->hdr_bytes
;
3554 int nread
= udsSupportReadFD(req
->sd
, (char *)&req
->hdr
+ req
->hdr_bytes
, nleft
, 0, req
->platform_data
);
3555 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3556 if (nread
< 0) goto rerror
;
3557 req
->hdr_bytes
+= nread
;
3558 if (req
->hdr_bytes
> sizeof(ipc_msg_hdr
))
3560 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3561 "[R%u] ERROR: read_msg - read too many header bytes", req
->request_id
);
3566 // only read data if header is complete
3567 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
))
3569 ConvertHeaderBytes(&req
->hdr
);
3570 if (req
->hdr
.version
!= VERSION
)
3572 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3573 "[R%u] ERROR: client version 0x%08X daemon version 0x%08X", req
->request_id
, req
->hdr
.version
, VERSION
);
3578 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
3579 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
3580 // for other overhead, this means any message above 70kB is definitely bogus.
3581 if (req
->hdr
.datalen
> 70000)
3583 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3584 "[R%u] ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req
->request_id
, req
->hdr
.datalen
, req
->hdr
.datalen
);
3588 req
->msgbuf
= (char *) callocL("request_state msgbuf", req
->hdr
.datalen
+ MSG_PAD_BYTES
);
3589 if (!req
->msgbuf
) { my_perror("ERROR: calloc"); req
->ts
= t_error
; return; }
3590 req
->msgptr
= req
->msgbuf
;
3591 req
->msgend
= req
->msgbuf
+ req
->hdr
.datalen
;
3595 // If our header is complete, but we're still needing more body data, then try to read it now
3596 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
3597 // Any time we need to get the error return socket we know we'll have at least one data byte
3598 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
3599 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
< req
->hdr
.datalen
)
3601 mDNSu32 nleft
= req
->hdr
.datalen
- req
->data_bytes
;
3603 #if !defined(_WIN32)
3604 struct iovec vec
= { req
->msgbuf
+ req
->data_bytes
, nleft
}; // Tell recvmsg where we want the bytes put
3606 struct cmsghdr
*cmsg
;
3607 char cbuf
[CMSG_SPACE(4 * sizeof(dnssd_sock_t
))];
3609 msg
.msg_namelen
= 0;
3612 msg
.msg_control
= cbuf
;
3613 msg
.msg_controllen
= sizeof(cbuf
);
3615 nread
= recvmsg(req
->sd
, &msg
, 0);
3617 nread
= udsSupportReadFD(req
->sd
, (char *)req
->msgbuf
+ req
->data_bytes
, nleft
, 0, req
->platform_data
);
3619 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3620 if (nread
< 0) goto rerror
;
3621 req
->data_bytes
+= nread
;
3622 if (req
->data_bytes
> req
->hdr
.datalen
)
3624 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3625 "[R%u] ERROR: read_msg - read too many data bytes", req
->request_id
);
3629 #if !defined(_WIN32)
3630 cmsg
= CMSG_FIRSTHDR(&msg
);
3631 #if DEBUG_64BIT_SCM_RIGHTS
3632 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3633 "[R%u] Expecting %d %d %d %d", req
->request_id
, sizeof(cbuf
), sizeof(cbuf
), SOL_SOCKET
, SCM_RIGHTS
);
3634 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3635 "[R%u] Got %d %d %d %d", req
->request_id
, msg
.msg_controllen
, cmsg
? cmsg
->cmsg_len
: -1, cmsg
? cmsg
->cmsg_level
: -1, cmsg
? cmsg
->cmsg_type
: -1);
3636 #endif // DEBUG_64BIT_SCM_RIGHTS
3637 if (cmsg
&& cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
3639 #if APPLE_OSX_mDNSResponder
3640 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3641 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3642 // and it's convenient to repurpose the existing fd-passing code here for that task
3643 if (req
->hdr
.op
== send_bpf
)
3645 dnssd_sock_t x
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3646 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3647 "[R%u] Got len %d, BPF %d", req
->request_id
, cmsg
->cmsg_len
, x
);
3648 mDNSPlatformReceiveBPF_fd(x
);
3651 #endif // APPLE_OSX_mDNSResponder
3652 req
->errsd
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3653 #if DEBUG_64BIT_SCM_RIGHTS
3654 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3655 "[R%u] read req->errsd %d", req
->request_id
, req
->errsd
);
3656 #endif // DEBUG_64BIT_SCM_RIGHTS
3657 if (req
->data_bytes
< req
->hdr
.datalen
)
3659 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
3660 "[R%u] Client(PID [%d](" PUB_S
")) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3661 req
->request_id
, req
->process_id
, req
->pid_name
, req
->errsd
, req
->data_bytes
, req
->hdr
.datalen
);
3669 // If our header and data are both complete, see if we need to make our separate error return socket
3670 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
== req
->hdr
.datalen
)
3672 if (req
->terminate
&& req
->hdr
.op
!= cancel_request
)
3674 dnssd_sockaddr_t cliaddr
;
3675 #if defined(USE_TCP_LOOPBACK)
3678 port
.b
[0] = req
->msgptr
[0];
3679 port
.b
[1] = req
->msgptr
[1];
3681 cliaddr
.sin_family
= AF_INET
;
3682 cliaddr
.sin_port
= port
.NotAnInteger
;
3683 cliaddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3685 char ctrl_path
[MAX_CTLPATH
];
3686 get_string(&req
->msgptr
, req
->msgend
, ctrl_path
, MAX_CTLPATH
); // path is first element in message buffer
3687 mDNSPlatformMemZero(&cliaddr
, sizeof(cliaddr
));
3688 cliaddr
.sun_family
= AF_LOCAL
;
3689 mDNSPlatformStrLCopy(cliaddr
.sun_path
, ctrl_path
, sizeof(cliaddr
.sun_path
));
3690 // If the error return path UDS name is empty string, that tells us
3691 // that this is a new version of the library that's going to pass us
3692 // the error return path socket via sendmsg/recvmsg
3693 if (ctrl_path
[0] == 0)
3695 if (req
->errsd
== req
->sd
)
3697 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3698 "[R%u] read_msg: ERROR failed to get errsd via SCM_RIGHTS", req
->request_id
);
3706 req
->errsd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3707 if (!dnssd_SocketValid(req
->errsd
))
3709 my_throttled_perror("ERROR: socket");
3714 if (connect(req
->errsd
, (struct sockaddr
*)&cliaddr
, sizeof(cliaddr
)) < 0)
3716 #if !defined(USE_TCP_LOOPBACK)
3718 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3719 "[R%u] read_msg: Couldn't connect to error return path socket " PUB_S
" errno %d (" PUB_S
")",
3720 req
->request_id
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3721 if (stat(cliaddr
.sun_path
, &sb
) < 0)
3723 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3724 "[R%u] read_msg: stat failed " PUB_S
" errno %d (" PUB_S
")",
3725 req
->request_id
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3729 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3730 "[R%u] read_msg: file " PUB_S
" mode %o (octal) uid %d gid %d",
3731 req
->request_id
, cliaddr
.sun_path
, sb
.st_mode
, sb
.st_uid
, sb
.st_gid
);
3738 #if !defined(USE_TCP_LOOPBACK)
3743 if (ioctlsocket(req
->errsd
, FIONBIO
, &opt
) != 0)
3745 if (fcntl(req
->errsd
, F_SETFL
, fcntl(req
->errsd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3748 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3749 "[R%u] ERROR: could not set control socket to non-blocking mode errno %d (" PUB_S
")",
3750 req
->request_id
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3756 req
->ts
= t_complete
;
3762 if (dnssd_errno
== dnssd_EWOULDBLOCK
|| dnssd_errno
== dnssd_EINTR
) return;
3763 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3764 "[R%u] ERROR: read_msg errno %d (" PUB_S
")", req
->request_id
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3768 mDNSlocal mStatus
handle_client_request(request_state
*req
)
3770 mStatus err
= mStatus_NoError
;
3773 // These are all operations that have their own first-class request_state object
3774 case connection_request
:
3775 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3776 "[R%d] DNSServiceCreateConnection START PID[%d](" PUB_S
")",
3777 req
->request_id
, req
->process_id
, req
->pid_name
);
3778 req
->terminate
= connection_termination
;
3780 case connection_delegate_request
:
3781 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3782 "[R%d] DNSServiceCreateDelegateConnection START PID[%d](" PRI_S
")",
3783 req
->request_id
, req
->process_id
, req
->pid_name
);
3784 req
->terminate
= connection_termination
;
3785 handle_connection_delegate_request(req
);
3787 case resolve_request
: err
= handle_resolve_request (req
); break;
3788 case query_request
: err
= handle_queryrecord_request (req
); break;
3789 case browse_request
: err
= handle_browse_request (req
); break;
3790 case reg_service_request
: err
= handle_regservice_request (req
); break;
3791 case enumeration_request
: err
= handle_enum_request (req
); break;
3792 case reconfirm_record_request
: err
= handle_reconfirm_request (req
); break;
3793 case setdomain_request
: err
= handle_setdomain_request (req
); break;
3794 case getproperty_request
: handle_getproperty_request (req
); break;
3795 case port_mapping_request
: err
= handle_port_mapping_request(req
); break;
3796 case addrinfo_request
: err
= handle_addrinfo_request (req
); break;
3797 case send_bpf
: /* Do nothing for send_bpf */ break;
3799 // These are all operations that work with an existing request_state object
3800 case reg_record_request
: err
= handle_regrecord_request (req
); break;
3801 case add_record_request
: err
= handle_add_request (req
); break;
3802 case update_record_request
: err
= handle_update_request (req
); break;
3803 case remove_record_request
: err
= handle_removerecord_request(req
); break;
3804 case cancel_request
: handle_cancel_request (req
); break;
3805 case release_request
: err
= handle_release_request (req
); break;
3806 default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
3807 req
->sd
, req
->hdr
.op
, req
->process_id
, req
->pid_name
);
3808 err
= mStatus_BadParamErr
;
3815 #define RecordOrientedOp(X) \
3816 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3818 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3819 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3821 mDNSlocal
void request_callback(int fd
, void *info
)
3824 request_state
*req
= info
;
3825 mDNSs32 min_size
= sizeof(DNSServiceFlags
);
3831 if (req
->ts
== t_morecoming
)
3833 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
3835 AbortUnlinkAndFree(req
);
3838 if (req
->ts
!= t_complete
)
3840 LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req
->ts
, req
->process_id
, req
->pid_name
);
3841 AbortUnlinkAndFree(req
);
3845 switch(req
->hdr
.op
) // Interface + other data
3847 case connection_request
: min_size
= 0; break;
3848 case connection_delegate_request
: min_size
= 4; /* pid */ break;
3849 case reg_service_request
: min_size
+= sizeof(mDNSu32
) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3850 case add_record_request
: min_size
+= 4 /* type, rdlen */ + 4 /* ttl */; break;
3851 case update_record_request
: min_size
+= 2 /* rdlen */ + 4 /* ttl */; break;
3852 case remove_record_request
: break;
3853 case browse_request
: min_size
+= sizeof(mDNSu32
) + 2 /* type, domain */; break;
3854 case resolve_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
3855 case query_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 4 /* type, class*/; break;
3856 case enumeration_request
: min_size
+= sizeof(mDNSu32
); break;
3857 case reg_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
3858 case reconfirm_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */; break;
3859 case setdomain_request
: min_size
+= 1 /* domain */; break;
3860 case getproperty_request
: min_size
= 2; break;
3861 case port_mapping_request
: min_size
+= sizeof(mDNSu32
) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
3862 case addrinfo_request
: min_size
+= sizeof(mDNSu32
) + 4 /* v4/v6 */ + 1 /* hostname */; break;
3863 case send_bpf
: // Same as cancel_request below
3864 case cancel_request
: min_size
= 0; break;
3865 case release_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
3866 default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
3867 req
->hdr
.op
, req
->process_id
, req
->pid_name
);
3868 min_size
= -1; break;
3871 if ((mDNSs32
)req
->data_bytes
< min_size
)
3873 LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
3874 req
->data_bytes
, req
->hdr
.op
, min_size
, req
->process_id
, req
->pid_name
);
3875 AbortUnlinkAndFree(req
);
3878 if (LightweightOp(req
->hdr
.op
) && !req
->terminate
)
3880 LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
3881 req
->hdr
.op
, req
->process_id
, req
->pid_name
);
3882 AbortUnlinkAndFree(req
);
3886 // If req->terminate is already set, this means this operation is sharing an existing connection
3887 if (req
->terminate
&& !LightweightOp(req
->hdr
.op
))
3889 request_state
*newreq
= NewRequest();
3890 newreq
->primary
= req
;
3891 newreq
->sd
= req
->sd
;
3892 newreq
->errsd
= req
->errsd
;
3893 newreq
->uid
= req
->uid
;
3894 newreq
->hdr
= req
->hdr
;
3895 newreq
->msgbuf
= req
->msgbuf
;
3896 newreq
->msgptr
= req
->msgptr
;
3897 newreq
->msgend
= req
->msgend
;
3898 newreq
->request_id
= mDNSStorage
.next_request_id
++;
3899 // if the parent request is a delegate connection, copy the
3903 newreq
->validUUID
= mDNStrue
;
3904 mDNSPlatformMemCopy(newreq
->uuid
, req
->uuid
, UUID_SIZE
);
3908 if (req
->process_id
)
3910 newreq
->process_id
= req
->process_id
;
3911 mDNSPlatformStrLCopy(newreq
->pid_name
, req
->pid_name
, (mDNSu32
)sizeof(newreq
->pid_name
));
3915 set_peer_pid(newreq
);
3921 // Check if the request wants no asynchronous replies.
3922 if (req
->hdr
.ipc_flags
& IPC_FLAGS_NOREPLY
) req
->no_reply
= 1;
3924 // If we're shutting down, don't allow new client requests
3925 // We do allow "cancel" and "getproperty" during shutdown
3926 if (mDNSStorage
.ShutdownTime
&& req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
)
3927 err
= mStatus_ServiceNotRunning
;
3929 err
= handle_client_request(req
);
3931 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3932 if (req
->msgbuf
) freeL("request_state msgbuf", req
->msgbuf
);
3934 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3935 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3936 if (req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
&& req
->hdr
.op
!= send_bpf
&& req
->hdr
.op
!= getpid_request
)
3938 const mStatus err_netorder
= dnssd_htonl(err
);
3939 send_all(req
->errsd
, (const char *)&err_netorder
, sizeof(err_netorder
));
3940 if (req
->errsd
!= req
->sd
)
3942 dnssd_close(req
->errsd
);
3943 req
->errsd
= req
->sd
;
3944 // Also need to reset the parent's errsd, if this is a subordinate operation
3945 if (req
->primary
) req
->primary
->errsd
= req
->primary
->sd
;
3949 // Reset ready to accept the next req on this pipe
3950 if (req
->primary
) req
= req
->primary
;
3951 req
->ts
= t_morecoming
;
3953 req
->data_bytes
= 0;
3954 req
->msgbuf
= mDNSNULL
;
3955 req
->msgptr
= mDNSNULL
;
3960 mDNSlocal
void connect_callback(int fd
, void *info
)
3962 dnssd_sockaddr_t cliaddr
;
3963 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(cliaddr
);
3964 dnssd_sock_t sd
= accept(fd
, (struct sockaddr
*) &cliaddr
, &len
);
3965 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3966 unsigned long optval
= 1;
3969 (void)info
; // Unused
3971 if (!dnssd_SocketValid(sd
))
3973 if (dnssd_errno
!= dnssd_EWOULDBLOCK
)
3974 my_throttled_perror("ERROR: accept");
3979 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3980 if (setsockopt(sd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
3981 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3985 if (ioctlsocket(sd
, FIONBIO
, &optval
) != 0)
3987 if (fcntl(sd
, F_SETFL
, fcntl(sd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3990 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3996 request_state
*request
= NewRequest();
3997 request
->ts
= t_morecoming
;
3999 request
->errsd
= sd
;
4000 request
->request_id
= mDNSStorage
.next_request_id
++;
4001 set_peer_pid(request
);
4002 #if APPLE_OSX_mDNSResponder
4004 socklen_t xucredlen
= sizeof(x
);
4005 if (getsockopt(sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 && x
.cr_version
== XUCRED_VERSION
)
4006 request
->uid
= x
.cr_uid
; // save the effective userid of the client
4008 my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
4010 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen
, x
.cr_version
, x
.cr_uid
, x
.cr_ngroups
);
4011 #endif // APPLE_OSX_mDNSResponder
4012 LogDebug("%3d: connect_callback: Adding FD for uid %u", request
->sd
, request
->uid
);
4013 udsSupportAddFDToEventLoop(sd
, request_callback
, request
, &request
->platform_data
);
4017 mDNSlocal mDNSBool
uds_socket_setup(dnssd_sock_t skt
)
4019 #if defined(SO_NP_EXTENSIONS)
4020 struct so_np_extensions sonpx
;
4021 socklen_t optlen
= sizeof(struct so_np_extensions
);
4022 sonpx
.npx_flags
= SONPX_SETOPTSHUT
;
4023 sonpx
.npx_mask
= SONPX_SETOPTSHUT
;
4024 if (setsockopt(skt
, SOL_SOCKET
, SO_NP_EXTENSIONS
, &sonpx
, optlen
) < 0)
4025 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
4028 // SEH: do we even need to do this on windows?
4029 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
4031 if (ioctlsocket(skt
, FIONBIO
, &opt
) != 0)
4033 if (fcntl(skt
, F_SETFL
, fcntl(skt
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
4036 my_perror("ERROR: could not set listen socket to non-blocking mode");
4040 if (listen(skt
, LISTENQ
) != 0)
4042 my_perror("ERROR: could not listen on listen socket");
4046 if (mStatus_NoError
!= udsSupportAddFDToEventLoop(skt
, connect_callback
, (void *) NULL
, (void **) NULL
))
4048 my_perror("ERROR: could not add listen socket to event loop");
4053 LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt
);
4054 mDNSStorage
.uds_listener_skt
= skt
;
4059 #if MDNS_MALLOC_DEBUGGING
4060 mDNSlocal
void udsserver_validatelists(void *context
);
4063 mDNSexport
int udsserver_init(dnssd_sock_t skts
[], mDNSu32 count
)
4065 dnssd_sockaddr_t laddr
;
4070 FILE *fp
= fopen(PID_FILE
, "w");
4073 fprintf(fp
, "%d\n", getpid());
4078 #if MDNS_MALLOC_DEBUGGING
4079 static mDNSListValidator validator
;
4080 mDNSPlatformAddListValidator(&validator
, udsserver_validatelists
, "udsserver_validatelists", NULL
);
4085 for (i
= 0; i
< count
; i
++)
4086 if (dnssd_SocketValid(skts
[i
]) && !uds_socket_setup(skts
[i
]))
4091 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
4092 if (!dnssd_SocketValid(listenfd
))
4094 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
4098 mDNSPlatformMemZero(&laddr
, sizeof(laddr
));
4100 #if defined(USE_TCP_LOOPBACK)
4102 laddr
.sin_family
= AF_INET
;
4103 laddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
4104 laddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
4105 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
4108 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4114 mode_t mask
= umask(0);
4115 unlink(boundPath
); // OK if this fails
4116 laddr
.sun_family
= AF_LOCAL
;
4117 #ifndef NOT_HAVE_SA_LEN
4118 // According to Stevens (section 3.2), there is no portable way to
4119 // determine whether sa_len is defined on a particular platform.
4120 laddr
.sun_len
= sizeof(struct sockaddr_un
);
4122 if (strlen(boundPath
) >= sizeof(laddr
.sun_path
))
4124 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr
.sun_path
));
4127 mDNSPlatformStrLCopy(laddr
.sun_path
, boundPath
, sizeof(laddr
.sun_path
));
4128 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
4132 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4138 if (!uds_socket_setup(listenfd
)) goto error
;
4141 #if !defined(PLATFORM_NO_RLIMIT)
4143 // Set maximum number of open file descriptors
4144 #define MIN_OPENFILES 10240
4145 struct rlimit maxfds
, newfds
;
4147 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
4148 // you have to get and set rlimits once before getrlimit will return sensible values
4149 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4150 if (setrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4152 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4153 newfds
.rlim_max
= (maxfds
.rlim_max
> MIN_OPENFILES
) ? maxfds
.rlim_max
: MIN_OPENFILES
;
4154 newfds
.rlim_cur
= (maxfds
.rlim_cur
> MIN_OPENFILES
) ? maxfds
.rlim_cur
: MIN_OPENFILES
;
4155 if (newfds
.rlim_max
!= maxfds
.rlim_max
|| newfds
.rlim_cur
!= maxfds
.rlim_cur
)
4156 if (setrlimit(RLIMIT_NOFILE
, &newfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4158 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4159 debugf("maxfds.rlim_max %d", (long)maxfds
.rlim_max
);
4160 debugf("maxfds.rlim_cur %d", (long)maxfds
.rlim_cur
);
4164 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
4165 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
4166 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
4167 mDNS_GetDomains(&mDNSStorage
, &mDNSStorage
.AutomaticBrowseDomainQ
, mDNS_DomainTypeBrowseAutomatic
,
4168 mDNSNULL
, mDNSInterface_LocalOnly
, AutomaticBrowseDomainChange
, mDNSNULL
);
4170 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
4171 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeRegistration
);
4172 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeBrowse
);
4173 AddAutoBrowseDomain(0, &localdomain
);
4175 udsserver_handle_configchange(&mDNSStorage
);
4180 my_perror("ERROR: udsserver_init");
4184 mDNSexport
int udsserver_exit(void)
4186 // Cancel all outstanding client requests
4187 while (all_requests
) AbortUnlinkAndFree(all_requests
);
4189 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
4190 // created in udsserver_init, and others we created as a result of reading local configuration data
4191 while (LocalDomainEnumRecords
)
4193 ARListElem
*rem
= LocalDomainEnumRecords
;
4194 LocalDomainEnumRecords
= LocalDomainEnumRecords
->next
;
4195 mDNS_Deregister(&mDNSStorage
, &rem
->ar
);
4198 // If the launching environment created no listening socket,
4199 // that means we created it ourselves, so we should clean it up on exit
4200 if (dnssd_SocketValid(listenfd
))
4202 dnssd_close(listenfd
);
4203 #if !defined(USE_TCP_LOOPBACK)
4204 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
4205 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
4206 // It would be nice if we could find a solution to this problem
4207 if (unlink(boundPath
))
4208 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH
);
4219 mDNSlocal
void LogClientInfoToFD(int fd
, request_state
*req
)
4224 mDNS_snprintf(reqIDStr
, sizeof(reqIDStr
), "[R%u]", req
->request_id
);
4226 mDNS_snprintf(prefix
, sizeof(prefix
), "%-6s %2s", reqIDStr
, req
->primary
? "->" : "");
4228 if (!req
->terminate
)
4229 LogToFD(fd
, "%s No operation yet on this socket", prefix
);
4230 else if (req
->terminate
== connection_termination
)
4232 int num_records
= 0, num_ops
= 0;
4233 const registered_record_entry
*p
;
4235 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
) num_records
++;
4236 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) num_ops
++;
4237 LogToFD(fd
, "%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
4238 prefix
, num_records
, num_records
!= 1 ? "s" : "", num_ops
, num_ops
!= 1 ? "s" : "",
4239 req
->process_id
, req
->pid_name
);
4240 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4241 LogToFD(fd
, " -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
4242 req
->flags
, req
->interfaceIndex
, p
->key
, ARDisplayString(&mDNSStorage
, p
->rr
), req
->process_id
, req
->pid_name
);
4243 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) LogClientInfoToFD(fd
, r
);
4245 else if (req
->terminate
== regservice_termination_callback
)
4247 service_instance
*ptr
;
4248 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4249 LogToFD(fd
, "%-9s DNSServiceRegister 0x%08X %2d %##s %u/%u PID[%d](%s)",
4250 (ptr
== req
->u
.servicereg
.instances
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, ptr
->srs
.RR_SRV
.resrec
.name
->c
,
4251 mDNSVal16(req
->u
.servicereg
.port
),
4252 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
);
4254 else if (req
->terminate
== browse_termination_callback
)
4257 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4258 LogToFD(fd
, "%-9s DNSServiceBrowse 0x%08X %2d %##s PID[%d](%s)",
4259 (blist
== req
->u
.browser
.browsers
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, blist
->q
.qname
.c
,
4260 req
->process_id
, req
->pid_name
);
4262 else if (req
->terminate
== resolve_termination_callback
)
4263 LogToFD(fd
, "%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
4264 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.resolve
.qsrv
.qname
.c
, req
->process_id
, req
->pid_name
);
4265 else if (req
->terminate
== queryrecord_termination_callback
)
4266 LogToFD(fd
, "%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
4267 prefix
, req
->flags
, req
->interfaceIndex
, QueryRecordClientRequestGetQName(&req
->u
.queryrecord
), DNSTypeName(QueryRecordClientRequestGetType(&req
->u
.queryrecord
)), req
->process_id
, req
->pid_name
);
4268 else if (req
->terminate
== enum_termination_callback
)
4269 LogToFD(fd
, "%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
4270 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.enumeration
.q_all
.qname
.c
, req
->process_id
, req
->pid_name
);
4271 else if (req
->terminate
== port_mapping_termination_callback
)
4272 LogToFD(fd
, "%s DNSServiceNATPortMapping 0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
4275 req
->interfaceIndex
,
4276 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
4277 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
4278 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
4279 mDNSVal16(req
->u
.pm
.ReqExt
),
4280 &req
->u
.pm
.NATinfo
.ExternalAddress
,
4281 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
4282 req
->u
.pm
.NATinfo
.NATLease
,
4283 req
->u
.pm
.NATinfo
.Lifetime
,
4284 req
->process_id
, req
->pid_name
);
4285 else if (req
->terminate
== addrinfo_termination_callback
)
4286 LogToFD(fd
, "%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
4287 prefix
, req
->flags
, req
->interfaceIndex
,
4288 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4289 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4290 GetAddrInfoClientRequestGetQName(&req
->u
.addrinfo
), req
->process_id
, req
->pid_name
);
4292 LogToFD(fd
, "%s Unrecognized operation %p", prefix
, req
->terminate
);
4295 mDNSlocal
void LogClientInfo(request_state
*req
)
4300 mDNS_snprintf(reqIDStr
, sizeof(reqIDStr
), "[R%u]", req
->request_id
);
4302 mDNS_snprintf(prefix
, sizeof(prefix
), "%-6s %2s", reqIDStr
, req
->primary
? "->" : "");
4304 if (!req
->terminate
)
4305 LogMsgNoIdent("%s No operation yet on this socket", prefix
);
4306 else if (req
->terminate
== connection_termination
)
4308 int num_records
= 0, num_ops
= 0;
4309 const registered_record_entry
*p
;
4311 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
) num_records
++;
4312 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) num_ops
++;
4313 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
4314 prefix
, num_records
, num_records
!= 1 ? "s" : "", num_ops
, num_ops
!= 1 ? "s" : "",
4315 req
->process_id
, req
->pid_name
);
4316 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4317 LogMsgNoIdent(" -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
4318 req
->flags
, req
->interfaceIndex
, p
->key
, ARDisplayString(&mDNSStorage
, p
->rr
), req
->process_id
, req
->pid_name
);
4319 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) LogClientInfo(r
);
4321 else if (req
->terminate
== regservice_termination_callback
)
4323 service_instance
*ptr
;
4324 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4325 LogMsgNoIdent("%-9s DNSServiceRegister 0x%08X %2d %##s %u/%u PID[%d](%s)",
4326 (ptr
== req
->u
.servicereg
.instances
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, ptr
->srs
.RR_SRV
.resrec
.name
->c
,
4327 mDNSVal16(req
->u
.servicereg
.port
),
4328 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
);
4330 else if (req
->terminate
== browse_termination_callback
)
4333 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4334 LogMsgNoIdent("%-9s DNSServiceBrowse 0x%08X %2d %##s PID[%d](%s)",
4335 (blist
== req
->u
.browser
.browsers
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, blist
->q
.qname
.c
,
4336 req
->process_id
, req
->pid_name
);
4338 else if (req
->terminate
== resolve_termination_callback
)
4339 LogMsgNoIdent("%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
4340 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.resolve
.qsrv
.qname
.c
, req
->process_id
, req
->pid_name
);
4341 else if (req
->terminate
== queryrecord_termination_callback
)
4342 LogMsgNoIdent("%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
4343 prefix
, req
->flags
, req
->interfaceIndex
, QueryRecordClientRequestGetQName(&req
->u
.queryrecord
), DNSTypeName(QueryRecordClientRequestGetType(&req
->u
.queryrecord
)), req
->process_id
, req
->pid_name
);
4344 else if (req
->terminate
== enum_termination_callback
)
4345 LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
4346 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.enumeration
.q_all
.qname
.c
, req
->process_id
, req
->pid_name
);
4347 else if (req
->terminate
== port_mapping_termination_callback
)
4348 LogMsgNoIdent("%s DNSServiceNATPortMapping 0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
4351 req
->interfaceIndex
,
4352 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
4353 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
4354 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
4355 mDNSVal16(req
->u
.pm
.ReqExt
),
4356 &req
->u
.pm
.NATinfo
.ExternalAddress
,
4357 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
4358 req
->u
.pm
.NATinfo
.NATLease
,
4359 req
->u
.pm
.NATinfo
.Lifetime
,
4360 req
->process_id
, req
->pid_name
);
4361 else if (req
->terminate
== addrinfo_termination_callback
)
4362 LogMsgNoIdent("%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
4363 prefix
, req
->flags
, req
->interfaceIndex
,
4364 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4365 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4366 GetAddrInfoClientRequestGetQName(&req
->u
.addrinfo
), req
->process_id
, req
->pid_name
);
4368 LogMsgNoIdent("%s Unrecognized operation %p", prefix
, req
->terminate
);
4371 mDNSlocal
void GetMcastClients(request_state
*req
)
4373 if (req
->terminate
== connection_termination
)
4375 int num_records
= 0, num_ops
= 0;
4376 const registered_record_entry
*p
;
4378 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4380 for (r
= req
->next
; r
; r
=r
->next
)
4381 if (r
->primary
== req
)
4383 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4385 if (!AuthRecord_uDNS(p
->rr
))
4388 for (r
= req
->next
; r
; r
=r
->next
)
4389 if (r
->primary
== req
)
4392 else if (req
->terminate
== regservice_termination_callback
)
4394 service_instance
*ptr
;
4395 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4397 if (!AuthRecord_uDNS(&ptr
->srs
.RR_SRV
))
4401 else if (req
->terminate
== browse_termination_callback
)
4404 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4406 if (mDNSOpaque16IsZero(blist
->q
.TargetQID
))
4410 else if (req
->terminate
== resolve_termination_callback
)
4412 if ((mDNSOpaque16IsZero(req
->u
.resolve
.qsrv
.TargetQID
)) && (req
->u
.resolve
.qsrv
.ThisQInterval
> 0))
4415 else if (req
->terminate
== queryrecord_termination_callback
)
4417 if (QueryRecordClientRequestIsMulticast(&req
->u
.queryrecord
))
4420 else if (req
->terminate
== addrinfo_termination_callback
)
4422 if (GetAddrInfoClientRequestIsMulticast(&req
->u
.addrinfo
))
4432 mDNSlocal
void LogMcastClientInfo(request_state
*req
)
4434 if (!req
->terminate
)
4435 LogMcastNoIdent("No operation yet on this socket");
4436 else if (req
->terminate
== connection_termination
)
4438 int num_records
= 0, num_ops
= 0;
4439 const registered_record_entry
*p
;
4441 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4443 for (r
= req
->next
; r
; r
=r
->next
)
4444 if (r
->primary
== req
)
4446 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4448 if (!AuthRecord_uDNS(p
->rr
))
4449 LogMcastNoIdent("R: -> DNSServiceRegisterRecord: %##s %s PID[%d](%s)", p
->rr
->resrec
.name
->c
,
4450 DNSTypeName(p
->rr
->resrec
.rrtype
), req
->process_id
, req
->pid_name
, i_mcount
++);
4452 for (r
= req
->next
; r
; r
=r
->next
)
4453 if (r
->primary
== req
)
4454 LogMcastClientInfo(r
);
4456 else if (req
->terminate
== regservice_termination_callback
)
4458 service_instance
*ptr
;
4459 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4461 if (!AuthRecord_uDNS(&ptr
->srs
.RR_SRV
))
4462 LogMcastNoIdent("R: DNSServiceRegister: %##s %u/%u PID[%d](%s)", ptr
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(req
->u
.servicereg
.port
),
4463 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
, i_mcount
++);
4466 else if (req
->terminate
== browse_termination_callback
)
4469 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4471 if (mDNSOpaque16IsZero(blist
->q
.TargetQID
))
4472 LogMcastNoIdent("Q: DNSServiceBrowse %##s %s PID[%d](%s)", blist
->q
.qname
.c
, DNSTypeName(blist
->q
.qtype
),
4473 req
->process_id
, req
->pid_name
, i_mcount
++);
4476 else if (req
->terminate
== resolve_termination_callback
)
4478 if ((mDNSOpaque16IsZero(req
->u
.resolve
.qsrv
.TargetQID
)) && (req
->u
.resolve
.qsrv
.ThisQInterval
> 0))
4479 LogMcastNoIdent("Q: DNSServiceResolve %##s %s PID[%d](%s)", req
->u
.resolve
.qsrv
.qname
.c
, DNSTypeName(req
->u
.resolve
.qsrv
.qtype
),
4480 req
->process_id
, req
->pid_name
, i_mcount
++);
4482 else if (req
->terminate
== queryrecord_termination_callback
)
4484 if (QueryRecordClientRequestIsMulticast(&req
->u
.queryrecord
))
4486 LogMcastNoIdent("Q: DNSServiceQueryRecord %##s %s PID[%d](%s)",
4487 QueryRecordClientRequestGetQName(&req
->u
.queryrecord
),
4488 DNSTypeName(QueryRecordClientRequestGetType(&req
->u
.queryrecord
)),
4489 req
->process_id
, req
->pid_name
, i_mcount
++);
4492 else if (req
->terminate
== addrinfo_termination_callback
)
4494 if (GetAddrInfoClientRequestIsMulticast(&req
->u
.addrinfo
))
4496 LogMcastNoIdent("Q: DNSServiceGetAddrInfo %s%s %##s PID[%d](%s)",
4497 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4498 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4499 GetAddrInfoClientRequestGetQName(&req
->u
.addrinfo
), req
->process_id
, req
->pid_name
, i_mcount
++);
4504 mDNSlocal
char *RecordTypeName(mDNSu8 rtype
)
4508 case kDNSRecordTypeUnregistered
: return ("Unregistered ");
4509 case kDNSRecordTypeDeregistering
: return ("Deregistering");
4510 case kDNSRecordTypeUnique
: return ("Unique ");
4511 case kDNSRecordTypeAdvisory
: return ("Advisory ");
4512 case kDNSRecordTypeShared
: return ("Shared ");
4513 case kDNSRecordTypeVerified
: return ("Verified ");
4514 case kDNSRecordTypeKnownUnique
: return ("KnownUnique ");
4515 default: return("Unknown");
4519 mDNSlocal
int LogEtcHostsToFD(int fd
, mDNS
*const m
)
4521 mDNSBool showheader
= mDNStrue
;
4522 const AuthRecord
*ar
;
4527 mDNSBool truncated
= 0;
4529 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4531 if (m
->rrauth
.rrauth_hash
[slot
]) authslot
++;
4532 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4533 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
4535 if (ar
->RecordCallback
!= FreeEtcHosts
) continue;
4536 if (showheader
) { showheader
= mDNSfalse
; LogToFD(fd
, " State Interface"); }
4538 // Print a maximum of 50 records
4539 if (count
++ >= 50) { truncated
= mDNStrue
; continue; }
4540 if (ar
->ARType
== AuthRecordLocalOnly
)
4542 if (ar
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
)
4543 LogToFD(fd
, " %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4546 mDNSu32 scopeid
= (mDNSu32
)(uintptr_t)ar
->resrec
.InterfaceID
;
4547 LogToFD(fd
, " %s %u %s", RecordTypeName(ar
->resrec
.RecordType
), scopeid
, ARDisplayString(m
, ar
));
4553 if (showheader
) LogToFD(fd
, "<None>");
4554 else if (truncated
) LogToFD(fd
, "<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count
, m
->rrauth
.rrauth_totalused
, authslot
);
4558 mDNSlocal
void LogLocalOnlyAuthRecordsToFD(int fd
, mDNS
*const m
)
4560 mDNSBool showheader
= mDNStrue
;
4561 const AuthRecord
*ar
;
4565 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4567 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4568 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
4570 if (ar
->RecordCallback
== FreeEtcHosts
) continue;
4571 if (showheader
) { showheader
= mDNSfalse
; LogToFD(fd
, " State Interface"); }
4573 // Print a maximum of 400 records
4574 if (ar
->ARType
== AuthRecordLocalOnly
)
4575 LogToFD(fd
, " %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4576 else if (ar
->ARType
== AuthRecordP2P
)
4578 if (ar
->resrec
.InterfaceID
== mDNSInterface_BLE
)
4579 LogToFD(fd
, " %s BLE %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4581 LogToFD(fd
, " %s PP %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4586 if (showheader
) LogToFD(fd
, "<None>");
4589 mDNSlocal
void LogOneAuthRecordToFD(int fd
, const AuthRecord
*ar
, mDNSs32 now
, const char *ifname
)
4591 if (AuthRecord_uDNS(ar
))
4593 LogToFD(fd
, "%7d %7d %7d %-7s %4d %s %s",
4594 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4595 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
4596 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
4599 ar
->AllowRemoteQuery
? "☠" : " ",
4600 ARDisplayString(&mDNSStorage
, ar
));
4604 LogToFD(fd
, "%7d %7d %7d %-7s 0x%02X %s %s",
4605 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4606 ar
->AnnounceCount
? (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
: 0,
4607 ar
->TimeExpire
? (ar
->TimeExpire
- now
) / mDNSPlatformOneSecond
: 0,
4608 ifname
? ifname
: "ALL",
4609 ar
->resrec
.RecordType
,
4610 ar
->AllowRemoteQuery
? "☠" : " ",
4611 ARDisplayString(&mDNSStorage
, ar
));
4615 mDNSlocal
void LogAuthRecordsToFD(int fd
,
4616 const mDNSs32 now
, AuthRecord
*ResourceRecords
, int *proxy
)
4618 mDNSBool showheader
= mDNStrue
;
4619 const AuthRecord
*ar
;
4620 OwnerOptData owner
= zeroOwner
;
4621 for (ar
= ResourceRecords
; ar
; ar
=ar
->next
)
4623 const char *const ifname
= InterfaceNameForID(&mDNSStorage
, ar
->resrec
.InterfaceID
);
4624 if ((ar
->WakeUp
.HMAC
.l
[0] != 0) == (proxy
!= mDNSNULL
))
4626 if (showheader
) { showheader
= mDNSfalse
; LogToFD(fd
, " Int Next Expire if State"); }
4627 if (proxy
) (*proxy
)++;
4628 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)))
4631 if (owner
.password
.l
[0])
4632 LogToFD(fd
, "Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
4633 else if (!mDNSSameEthAddress(&owner
.HMAC
, &owner
.IMAC
))
4634 LogToFD(fd
, "Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, owner
.seq
);
4636 LogToFD(fd
, "Proxying for %.6a seq %d", &owner
.HMAC
, owner
.seq
);
4638 if (AuthRecord_uDNS(ar
))
4640 LogOneAuthRecordToFD(fd
, ar
, now
, ifname
);
4642 else if (ar
->ARType
== AuthRecordLocalOnly
)
4644 LogToFD(fd
, " LO %s", ARDisplayString(&mDNSStorage
, ar
));
4646 else if (ar
->ARType
== AuthRecordP2P
)
4648 if (ar
->resrec
.InterfaceID
== mDNSInterface_BLE
)
4649 LogToFD(fd
, " BLE %s", ARDisplayString(&mDNSStorage
, ar
));
4651 LogToFD(fd
, " PP %s", ARDisplayString(&mDNSStorage
, ar
));
4655 LogOneAuthRecordToFD(fd
, ar
, now
, ifname
);
4659 if (showheader
) LogToFD(fd
, "<None>");
4662 mDNSlocal
void PrintOneCacheRecordToFD(int fd
, const CacheRecord
*cr
, mDNSu32 slot
, const mDNSu32 remain
, const char *ifname
, mDNSu32
*CacheUsed
)
4664 LogToFD(fd
, "%3d %s%8d %-7s%s %-6s%s",
4666 cr
->CRActiveQuestion
? "*" : " ",
4668 ifname
? ifname
: "-U-",
4669 (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) ? "-" :
4670 (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ? " " : "+",
4671 DNSTypeName(cr
->resrec
.rrtype
),
4672 CRDisplayString(&mDNSStorage
, cr
));
4676 mDNSlocal
void PrintCachedRecordsToFD(int fd
, const CacheRecord
*cr
, mDNSu32 slot
, const mDNSu32 remain
, const char *ifname
, mDNSu32
*CacheUsed
)
4682 // The records that are cached under the main cache record like nsec, soa don't have
4683 // their own lifetime. If the main cache record expires, they also expire.
4686 PrintOneCacheRecordToFD(fd
, nsec
, slot
, remain
, ifname
, CacheUsed
);
4692 PrintOneCacheRecordToFD(fd
, soa
, slot
, remain
, ifname
, CacheUsed
);
4696 mDNSexport
void LogMDNSStatisticsToFD(int fd
, mDNS
*const m
)
4698 LogToFD(fd
, "--- MDNS Statistics ---");
4700 LogToFD(fd
, "Name Conflicts %u", m
->mDNSStats
.NameConflicts
);
4701 LogToFD(fd
, "KnownUnique Name Conflicts %u", m
->mDNSStats
.KnownUniqueNameConflicts
);
4702 LogToFD(fd
, "Duplicate Query Suppressions %u", m
->mDNSStats
.DupQuerySuppressions
);
4703 LogToFD(fd
, "KA Suppressions %u", m
->mDNSStats
.KnownAnswerSuppressions
);
4704 LogToFD(fd
, "KA Multiple Packets %u", m
->mDNSStats
.KnownAnswerMultiplePkts
);
4705 LogToFD(fd
, "Poof Cache Deletions %u", m
->mDNSStats
.PoofCacheDeletions
);
4706 LogToFD(fd
, "--------------------------------");
4708 LogToFD(fd
, "Multicast packets Sent %u", m
->MulticastPacketsSent
);
4709 LogToFD(fd
, "Multicast packets Received %u", m
->MPktNum
);
4710 LogToFD(fd
, "Remote Subnet packets %u", m
->RemoteSubnet
);
4711 LogToFD(fd
, "QU questions received %u", m
->mDNSStats
.UnicastBitInQueries
);
4712 LogToFD(fd
, "Normal multicast questions %u", m
->mDNSStats
.NormalQueries
);
4713 LogToFD(fd
, "Answers for questions %u", m
->mDNSStats
.MatchingAnswersForQueries
);
4714 LogToFD(fd
, "Unicast responses %u", m
->mDNSStats
.UnicastResponses
);
4715 LogToFD(fd
, "Multicast responses %u", m
->mDNSStats
.MulticastResponses
);
4716 LogToFD(fd
, "Unicast response Demotions %u", m
->mDNSStats
.UnicastDemotedToMulticast
);
4717 LogToFD(fd
, "--------------------------------");
4719 LogToFD(fd
, "Sleeps %u", m
->mDNSStats
.Sleeps
);
4720 LogToFD(fd
, "Wakeups %u", m
->mDNSStats
.Wakes
);
4721 LogToFD(fd
, "Interface UP events %u", m
->mDNSStats
.InterfaceUp
);
4722 LogToFD(fd
, "Interface UP Flap events %u", m
->mDNSStats
.InterfaceUpFlap
);
4723 LogToFD(fd
, "Interface Down events %u", m
->mDNSStats
.InterfaceDown
);
4724 LogToFD(fd
, "Interface DownFlap events %u", m
->mDNSStats
.InterfaceDownFlap
);
4725 LogToFD(fd
, "Cache refresh queries %u", m
->mDNSStats
.CacheRefreshQueries
);
4726 LogToFD(fd
, "Cache refreshed %u", m
->mDNSStats
.CacheRefreshed
);
4727 LogToFD(fd
, "Wakeup on Resolves %u", m
->mDNSStats
.WakeOnResolves
);
4730 mDNSexport
void udsserver_info_dump_to_fd(int fd
)
4732 mDNS
*const m
= &mDNSStorage
;
4733 const mDNSs32 now
= mDNS_TimeNow(m
);
4734 mDNSu32 CacheUsed
= 0, CacheActive
= 0, slot
;
4735 int ProxyA
= 0, ProxyD
= 0;
4736 mDNSu32 groupCount
= 0;
4737 mDNSu32 mcastRecordCount
= 0;
4738 mDNSu32 ucastRecordCount
= 0;
4739 const CacheGroup
*cg
;
4740 const CacheRecord
*cr
;
4741 const DNSQuestion
*q
;
4742 const DNameListElem
*d
;
4743 const SearchListElem
*s
;
4745 LogToFD(fd
, "------------ Cache -------------");
4746 LogToFD(fd
, "Slt Q TTL if U Type rdlen");
4747 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4749 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
4751 groupCount
++; // Count one cache entity for the CacheGroup object
4752 for (cr
= cg
->members
; cr
; cr
=cr
->next
)
4754 const mDNSs32 remain
= cr
->resrec
.rroriginalttl
- (now
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
4756 mDNSInterfaceID InterfaceID
= cr
->resrec
.InterfaceID
;
4757 mDNSu32
*const countPtr
= InterfaceID
? &mcastRecordCount
: &ucastRecordCount
;
4758 if (!InterfaceID
&& cr
->resrec
.rDNSServer
&& cr
->resrec
.rDNSServer
->scopeType
)
4759 InterfaceID
= cr
->resrec
.rDNSServer
->interface
;
4760 ifname
= InterfaceNameForID(m
, InterfaceID
);
4761 if (cr
->CRActiveQuestion
) CacheActive
++;
4762 PrintOneCacheRecordToFD(fd
, cr
, slot
, remain
, ifname
, countPtr
);
4763 PrintCachedRecordsToFD(fd
, cr
, slot
, remain
, ifname
, countPtr
);
4768 CacheUsed
= groupCount
+ mcastRecordCount
+ ucastRecordCount
;
4769 if (m
->rrcache_totalused
!= CacheUsed
)
4770 LogToFD(fd
, "Cache use mismatch: rrcache_totalused is %lu, true count %lu", m
->rrcache_totalused
, CacheUsed
);
4771 if (m
->rrcache_active
!= CacheActive
)
4772 LogToFD(fd
, "Cache use mismatch: rrcache_active is %lu, true count %lu", m
->rrcache_active
, CacheActive
);
4773 LogToFD(fd
, "Cache size %u entities; %u in use (%u group, %u multicast, %u unicast); %u referenced by active questions",
4774 m
->rrcache_size
, CacheUsed
, groupCount
, mcastRecordCount
, ucastRecordCount
, CacheActive
);
4776 LogToFD(fd
, "--------- Auth Records ---------");
4777 LogAuthRecordsToFD(fd
, now
, m
->ResourceRecords
, mDNSNULL
);
4779 LogToFD(fd
, "--------- LocalOnly, P2P Auth Records ---------");
4780 LogLocalOnlyAuthRecordsToFD(fd
, m
);
4782 LogToFD(fd
, "--------- /etc/hosts ---------");
4783 LogEtcHostsToFD(fd
, m
);
4785 LogToFD(fd
, "------ Duplicate Records -------");
4786 LogAuthRecordsToFD(fd
, now
, m
->DuplicateRecords
, mDNSNULL
);
4788 LogToFD(fd
, "----- Auth Records Proxied -----");
4789 LogAuthRecordsToFD(fd
, now
, m
->ResourceRecords
, &ProxyA
);
4791 LogToFD(fd
, "-- Duplicate Records Proxied ---");
4792 LogAuthRecordsToFD(fd
, now
, m
->DuplicateRecords
, &ProxyD
);
4794 LogToFD(fd
, "---------- Questions -----------");
4795 if (!m
->Questions
) LogToFD(fd
, "<None>");
4800 LogToFD(fd
, " Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
4801 for (q
= m
->Questions
; q
; q
=q
->next
)
4803 mDNSs32 i
= q
->ThisQInterval
/ mDNSPlatformOneSecond
;
4804 mDNSs32 n
= (NextQSendTime(q
) - now
) / mDNSPlatformOneSecond
;
4805 char *ifname
= InterfaceNameForID(m
, q
->InterfaceID
);
4807 if (q
->ThisQInterval
) CacheActive
++;
4808 LogToFD(fd
, "%6d%6d %-7s%s%s %5d 0x%08x%08x%08x%08x 0x%p 0x%p %1d %2d %-5s%##s%s",
4810 ifname
? ifname
: mDNSOpaque16IsZero(q
->TargetQID
) ? "" : "-U-",
4811 mDNSOpaque16IsZero(q
->TargetQID
) ? (q
->LongLived
? "l" : " ") : (q
->LongLived
? "L" : "O"),
4812 q
->ValidationRequired
? "V" : q
->ValidatingResponse
? "R" : " ",
4814 q
->validDNSServers
.l
[3], q
->validDNSServers
.l
[2], q
->validDNSServers
.l
[1], q
->validDNSServers
.l
[0],
4816 q
->SuppressUnusable
, q
->Suppressed
, DNSTypeName(q
->qtype
), q
->qname
.c
,
4817 q
->DuplicateOf
? " (dup)" : "");
4819 LogToFD(fd
, "%lu question%s; %lu active", CacheUsed
, CacheUsed
> 1 ? "s" : "", CacheActive
);
4822 LogToFD(fd
, "----- LocalOnly, P2P Questions -----");
4823 if (!m
->LocalOnlyQuestions
) LogToFD(fd
, "<None>");
4824 else for (q
= m
->LocalOnlyQuestions
; q
; q
=q
->next
)
4825 LogToFD(fd
, " %3s %5d %-6s%##s%s",
4826 q
->InterfaceID
== mDNSInterface_LocalOnly
? "LO ": q
->InterfaceID
== mDNSInterface_BLE
? "BLE": "P2P",
4827 q
->CurrentAnswers
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
4829 LogToFD(fd
, "---- Active UDS Client Requests ----");
4830 if (!all_requests
) LogToFD(fd
, "<None>");
4833 request_state
*req
, *r
;
4834 for (req
= all_requests
; req
; req
=req
->next
)
4836 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
4838 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
) if (r
== req
->primary
) goto foundparent
;
4839 LogToFD(fd
, "%3d: Orhpan operation %p; parent %p not found in request list", req
->sd
);
4841 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
4842 LogClientInfoToFD(fd
, req
);
4847 LogToFD(fd
, "-------- NAT Traversals --------");
4848 LogToFD(fd
, "ExtAddress %.4a Retry %d Interval %d",
4850 m
->retryGetAddr
? (m
->retryGetAddr
- now
) / mDNSPlatformOneSecond
: 0,
4851 m
->retryIntervalGetAddr
/ mDNSPlatformOneSecond
);
4852 if (m
->NATTraversals
)
4854 const NATTraversalInfo
*nat
;
4855 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
4857 LogToFD(fd
, "%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
4859 nat
->Protocol
? (nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP") : "ADD",
4860 mDNSVal16(nat
->IntPort
),
4861 (nat
->lastSuccessfulProtocol
== NATTProtocolNone
? "None " :
4862 nat
->lastSuccessfulProtocol
== NATTProtocolNATPMP
? "NAT-PMP " :
4863 nat
->lastSuccessfulProtocol
== NATTProtocolUPNPIGD
? "UPnP/IGD" :
4864 nat
->lastSuccessfulProtocol
== NATTProtocolPCP
? "PCP " :
4865 /* else */ "Unknown " ),
4867 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
4868 nat
->retryInterval
/ mDNSPlatformOneSecond
,
4869 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
4870 &nat
->NewAddress
, mDNSVal16(nat
->RequestedPort
),
4871 &nat
->ExternalAddress
, mDNSVal16(nat
->ExternalPort
));
4875 LogToFD(fd
, "--------- AuthInfoList ---------");
4876 if (!m
->AuthInfoList
) LogToFD(fd
, "<None>");
4879 const DomainAuthInfo
*a
;
4880 for (a
= m
->AuthInfoList
; a
; a
= a
->next
)
4882 LogToFD(fd
, "%##s %##s %##s %d %d",
4883 a
->domain
.c
, a
->keyname
.c
,
4884 a
->hostname
.c
, (a
->port
.b
[0] << 8 | a
->port
.b
[1]),
4885 (a
->deltime
? (a
->deltime
- now
) : 0));
4889 LogToFD(fd
, "---------- Misc State ----------");
4891 LogToFD(fd
, "PrimaryMAC: %.6a", &m
->PrimaryMAC
);
4893 LogToFD(fd
, "m->SleepState %d (%s) seq %d",
4895 m
->SleepState
== SleepState_Awake
? "Awake" :
4896 m
->SleepState
== SleepState_Transferring
? "Transferring" :
4897 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?",
4900 if (!m
->SPSSocket
) LogToFD(fd
, "Not offering Sleep Proxy Service");
4901 #ifndef SPC_DISABLED
4902 else LogToFD(fd
, "Offering Sleep Proxy Service: %#s", m
->SPSRecords
.RR_SRV
.resrec
.name
->c
);
4904 if (m
->ProxyRecords
== ProxyA
+ ProxyD
) LogToFD(fd
, "ProxyRecords: %d + %d = %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
);
4905 else LogToFD(fd
, "ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
, m
->ProxyRecords
);
4907 LogToFD(fd
, "------ Auto Browse Domains -----");
4908 if (!AutoBrowseDomains
) LogToFD(fd
, "<None>");
4909 else for (d
=AutoBrowseDomains
; d
; d
=d
->next
) LogToFD(fd
, "%##s", d
->name
.c
);
4911 LogToFD(fd
, "--- Auto Registration Domains --");
4912 if (!AutoRegistrationDomains
) LogToFD(fd
, "<None>");
4913 else for (d
=AutoRegistrationDomains
; d
; d
=d
->next
) LogToFD(fd
, "%##s", d
->name
.c
);
4915 LogToFD(fd
, "--- Search Domains --");
4916 if (!SearchList
) LogToFD(fd
, "<None>");
4919 for (s
=SearchList
; s
; s
=s
->next
)
4921 char *ifname
= InterfaceNameForID(m
, s
->InterfaceID
);
4922 LogToFD(fd
, "%##s %s", s
->domain
.c
, ifname
? ifname
: "");
4925 LogToFD(fd
, "--- Trust Anchors ---");
4926 if (!m
->TrustAnchors
)
4928 LogToFD(fd
, "<None>");
4933 mDNSu8 fromTimeBuf
[64];
4934 mDNSu8 untilTimeBuf
[64];
4936 for (ta
=m
->TrustAnchors
; ta
; ta
=ta
->next
)
4938 mDNSPlatformFormatTime((unsigned long)ta
->validFrom
, fromTimeBuf
, sizeof(fromTimeBuf
));
4939 mDNSPlatformFormatTime((unsigned long)ta
->validUntil
, untilTimeBuf
, sizeof(untilTimeBuf
));
4940 LogToFD(fd
, "%##s %d %d %d %d %s %s", ta
->zone
.c
, ta
->rds
.keyTag
,
4941 ta
->rds
.alg
, ta
->rds
.digestType
, ta
->digestLen
, fromTimeBuf
, untilTimeBuf
);
4945 LogToFD(fd
, "--- DNSSEC Statistics ---");
4947 LogToFD(fd
, "Unicast Cache size %u", m
->rrcache_totalused_unicast
);
4948 LogToFD(fd
, "DNSSEC Cache size %u", m
->DNSSECStats
.TotalMemUsed
);
4949 if (m
->rrcache_totalused_unicast
)
4950 LogToFD(fd
, "DNSSEC usage percentage %u", ((unsigned long)(m
->DNSSECStats
.TotalMemUsed
* 100))/m
->rrcache_totalused_unicast
);
4951 LogToFD(fd
, "DNSSEC Extra Packets (0 to 2) %u", m
->DNSSECStats
.ExtraPackets0
);
4952 LogToFD(fd
, "DNSSEC Extra Packets (3 to 6) %u", m
->DNSSECStats
.ExtraPackets3
);
4953 LogToFD(fd
, "DNSSEC Extra Packets (7 to 9) %u", m
->DNSSECStats
.ExtraPackets7
);
4954 LogToFD(fd
, "DNSSEC Extra Packets ( >= 10) %u", m
->DNSSECStats
.ExtraPackets10
);
4956 LogToFD(fd
, "DNSSEC Latency (0 to 4ms) %u", m
->DNSSECStats
.Latency0
);
4957 LogToFD(fd
, "DNSSEC Latency (4 to 9ms) %u", m
->DNSSECStats
.Latency5
);
4958 LogToFD(fd
, "DNSSEC Latency (10 to 19ms) %u", m
->DNSSECStats
.Latency10
);
4959 LogToFD(fd
, "DNSSEC Latency (20 to 49ms) %u", m
->DNSSECStats
.Latency20
);
4960 LogToFD(fd
, "DNSSEC Latency (50 to 99ms) %u", m
->DNSSECStats
.Latency50
);
4961 LogToFD(fd
, "DNSSEC Latency ( >=100ms) %u", m
->DNSSECStats
.Latency100
);
4963 LogToFD(fd
, "DNSSEC Secure Status %u", m
->DNSSECStats
.SecureStatus
);
4964 LogToFD(fd
, "DNSSEC Insecure Status %u", m
->DNSSECStats
.InsecureStatus
);
4965 LogToFD(fd
, "DNSSEC Indeterminate Status %u", m
->DNSSECStats
.IndeterminateStatus
);
4966 LogToFD(fd
, "DNSSEC Bogus Status %u", m
->DNSSECStats
.BogusStatus
);
4967 LogToFD(fd
, "DNSSEC NoResponse Status %u", m
->DNSSECStats
.NoResponseStatus
);
4968 LogToFD(fd
, "DNSSEC Probes sent %u", m
->DNSSECStats
.NumProbesSent
);
4969 LogToFD(fd
, "DNSSEC Msg Size (<=1024) %u", m
->DNSSECStats
.MsgSize0
);
4970 LogToFD(fd
, "DNSSEC Msg Size (<=2048) %u", m
->DNSSECStats
.MsgSize1
);
4971 LogToFD(fd
, "DNSSEC Msg Size (> 2048) %u", m
->DNSSECStats
.MsgSize2
);
4973 LogMDNSStatisticsToFD(fd
, m
);
4975 LogToFD(fd
, "---- Task Scheduling Timers ----");
4977 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
4978 LogToFD(fd
, "BonjourEnabled %d", m
->BonjourEnabled
);
4981 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
4982 LogToFD(fd
, "EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery
);
4983 LogToFD(fd
, "DefaultToBLETriggered %d", DefaultToBLETriggered
);
4984 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
4986 if (!m
->NewQuestions
)
4987 LogToFD(fd
, "NewQuestion <NONE>");
4989 LogToFD(fd
, "NewQuestion DelayAnswering %d %d %##s (%s)",
4990 m
->NewQuestions
->DelayAnswering
, m
->NewQuestions
->DelayAnswering
-now
,
4991 m
->NewQuestions
->qname
.c
, DNSTypeName(m
->NewQuestions
->qtype
));
4993 if (!m
->NewLocalOnlyQuestions
)
4994 LogToFD(fd
, "NewLocalOnlyQuestions <NONE>");
4996 LogToFD(fd
, "NewLocalOnlyQuestions %##s (%s)",
4997 m
->NewLocalOnlyQuestions
->qname
.c
, DNSTypeName(m
->NewLocalOnlyQuestions
->qtype
));
4999 if (!m
->NewLocalRecords
)
5000 LogToFD(fd
, "NewLocalRecords <NONE>");
5002 LogToFD(fd
, "NewLocalRecords %02X %s", m
->NewLocalRecords
->resrec
.RecordType
, ARDisplayString(m
, m
->NewLocalRecords
));
5004 LogToFD(fd
, "SPSProxyListChanged%s", m
->SPSProxyListChanged
? "" : " <NONE>");
5005 LogToFD(fd
, "LocalRemoveEvents%s", m
->LocalRemoveEvents
? "" : " <NONE>");
5006 LogToFD(fd
, "m->WABBrowseQueriesCount %d", m
->WABBrowseQueriesCount
);
5007 LogToFD(fd
, "m->WABLBrowseQueriesCount %d", m
->WABLBrowseQueriesCount
);
5008 LogToFD(fd
, "m->WABRegQueriesCount %d", m
->WABRegQueriesCount
);
5009 LogToFD(fd
, "m->AutoTargetServices %u", m
->AutoTargetServices
);
5010 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
5011 LogToFD(fd
, "m->AutoTargetAWDLIncludedCount %u", m
->AutoTargetAWDLIncludedCount
);
5012 LogToFD(fd
, "m->AutoTargetAWDLOnlyCount %u", m
->AutoTargetAWDLOnlyCount
);
5015 LogToFD(fd
, " ABS (hex) ABS (dec) REL (hex) REL (dec)");
5016 LogToFD(fd
, "m->timenow %08X %11d", now
, now
);
5017 LogToFD(fd
, "m->timenow_adjust %08X %11d", m
->timenow_adjust
, m
->timenow_adjust
);
5018 LogTimerToFD(fd
, "m->NextScheduledEvent ", m
->NextScheduledEvent
);
5020 #ifndef UNICAST_DISABLED
5021 LogTimerToFD(fd
, "m->NextuDNSEvent ", m
->NextuDNSEvent
);
5022 LogTimerToFD(fd
, "m->NextSRVUpdate ", m
->NextSRVUpdate
);
5023 LogTimerToFD(fd
, "m->NextScheduledNATOp ", m
->NextScheduledNATOp
);
5024 LogTimerToFD(fd
, "m->retryGetAddr ", m
->retryGetAddr
);
5027 LogTimerToFD(fd
, "m->NextCacheCheck ", m
->NextCacheCheck
);
5028 LogTimerToFD(fd
, "m->NextScheduledSPS ", m
->NextScheduledSPS
);
5029 LogTimerToFD(fd
, "m->NextScheduledKA ", m
->NextScheduledKA
);
5031 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5032 LogTimerToFD(fd
, "m->NextBonjourDisableTime ", m
->NextBonjourDisableTime
);
5035 LogTimerToFD(fd
, "m->NextScheduledSPRetry ", m
->NextScheduledSPRetry
);
5036 LogTimerToFD(fd
, "m->DelaySleep ", m
->DelaySleep
);
5038 LogTimerToFD(fd
, "m->NextScheduledQuery ", m
->NextScheduledQuery
);
5039 LogTimerToFD(fd
, "m->NextScheduledProbe ", m
->NextScheduledProbe
);
5040 LogTimerToFD(fd
, "m->NextScheduledResponse", m
->NextScheduledResponse
);
5042 LogTimerToFD(fd
, "m->SuppressSending ", m
->SuppressSending
);
5043 LogTimerToFD(fd
, "m->SuppressProbes ", m
->SuppressProbes
);
5044 LogTimerToFD(fd
, "m->ProbeFailTime ", m
->ProbeFailTime
);
5045 LogTimerToFD(fd
, "m->DelaySleep ", m
->DelaySleep
);
5046 LogTimerToFD(fd
, "m->SleepLimit ", m
->SleepLimit
);
5047 LogTimerToFD(fd
, "m->NextScheduledStopTime ", m
->NextScheduledStopTime
);
5050 #if MDNS_MALLOC_DEBUGGING
5051 mDNSlocal
void udsserver_validatelists(void *context
)
5053 const request_state
*req
, *p
;
5054 (void)context
; // unused
5055 for (req
= all_requests
; req
; req
=req
->next
)
5057 if (req
->next
== (request_state
*)~0 || (req
->sd
< 0 && req
->sd
!= -2))
5058 LogMemCorruption("UDS request list: %p is garbage (%d)", req
, req
->sd
);
5060 if (req
->primary
== req
)
5061 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req
, req
->sd
);
5063 if (req
->primary
&& req
->replies
)
5064 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
5065 req
, req
->sd
, req
->primary
&& req
->replies
);
5069 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req
, p
, req
->sd
);
5070 else if (p
&& (p
->next
== (request_state
*)~0 || (p
->sd
< 0 && p
->sd
!= -2)))
5071 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req
, p
, p
->sd
);
5074 for (rep
= req
->replies
; rep
; rep
=rep
->next
)
5075 if (rep
->next
== (reply_state
*)~0)
5076 LogMemCorruption("UDS req->replies: %p is garbage", rep
);
5078 if (req
->terminate
== connection_termination
)
5080 registered_record_entry
*r
;
5081 for (r
= req
->u
.reg_recs
; r
; r
=r
->next
)
5082 if (r
->next
== (registered_record_entry
*)~0)
5083 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r
);
5085 else if (req
->terminate
== regservice_termination_callback
)
5087 service_instance
*s
;
5088 for (s
= req
->u
.servicereg
.instances
; s
; s
=s
->next
)
5089 if (s
->next
== (service_instance
*)~0)
5090 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s
);
5092 else if (req
->terminate
== browse_termination_callback
)
5095 for (b
= req
->u
.browser
.browsers
; b
; b
=b
->next
)
5096 if (b
->next
== (browser_t
*)~0)
5097 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b
);
5102 for (d
= SCPrefBrowseDomains
; d
; d
=d
->next
)
5103 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
5104 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
5107 for (b
= LocalDomainEnumRecords
; b
; b
=b
->next
)
5108 if (b
->next
== (ARListElem
*)~0 || b
->ar
.resrec
.name
->c
[0] > 63)
5109 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b
, b
->ar
.resrec
.name
->c
[0]);
5111 for (d
= AutoBrowseDomains
; d
; d
=d
->next
)
5112 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
5113 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
5115 for (d
= AutoRegistrationDomains
; d
; d
=d
->next
)
5116 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
5117 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
5119 #endif // MDNS_MALLOC_DEBUGGING
5121 mDNSlocal
int send_msg(request_state
*const req
)
5123 reply_state
*const rep
= req
->replies
; // Send the first waiting reply
5126 ConvertHeaderBytes(rep
->mhdr
);
5127 nwriten
= send(req
->sd
, (char *)&rep
->mhdr
+ rep
->nwriten
, rep
->totallen
- rep
->nwriten
, 0);
5128 ConvertHeaderBytes(rep
->mhdr
);
5132 if (dnssd_errno
== dnssd_EINTR
|| dnssd_errno
== dnssd_EWOULDBLOCK
) nwriten
= 0;
5135 #if !defined(PLATFORM_NO_EPIPE)
5136 if (dnssd_errno
== EPIPE
)
5137 return(req
->ts
= t_terminated
);
5141 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
5142 rep
->totallen
- rep
->nwriten
, rep
->totallen
, req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
5147 rep
->nwriten
+= nwriten
;
5148 return (rep
->nwriten
== rep
->totallen
) ? t_complete
: t_morecoming
;
5151 mDNSexport mDNSs32
udsserver_idle(mDNSs32 nextevent
)
5153 mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
5154 request_state
**req
= &all_requests
;
5158 request_state
*const r
= *req
;
5160 if (r
->terminate
== resolve_termination_callback
)
5161 if (r
->u
.resolve
.ReportTime
&& now
- r
->u
.resolve
.ReportTime
>= 0)
5163 r
->u
.resolve
.ReportTime
= 0;
5164 // if client received results and resolve still active
5165 if (r
->u
.resolve
.txt
&& r
->u
.resolve
.srv
)
5166 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
);
5169 // Note: Only primary req's have reply lists, not subordinate req's.
5170 while (r
->replies
) // Send queued replies
5172 transfer_state result
;
5173 if (r
->replies
->next
)
5174 r
->replies
->rhdr
->flags
|= dnssd_htonl(kDNSServiceFlagsMoreComing
);
5175 result
= send_msg(r
); // Returns t_morecoming if buffer full because client is not reading
5176 if (result
== t_complete
)
5178 reply_state
*fptr
= r
->replies
;
5179 r
->replies
= r
->replies
->next
;
5180 freeL("reply_state/udsserver_idle", fptr
);
5181 r
->time_blocked
= 0; // reset failure counter after successful send
5182 r
->unresponsiveness_reports
= 0;
5185 else if (result
== t_terminated
)
5187 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
);
5190 else if (result
== t_error
)
5192 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r
->sd
, r
->process_id
, r
->pid_name
);
5199 if (r
->replies
) // If we failed to send everything, check our time_blocked timer
5201 if (nextevent
- now
> mDNSPlatformOneSecond
)
5202 nextevent
= now
+ mDNSPlatformOneSecond
;
5204 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
5205 "[R%u] Could not send all replies. Will try again in %d ticks.", r
->request_id
, nextevent
- now
);
5206 if (mDNSStorage
.SleepState
!= SleepState_Awake
)
5207 r
->time_blocked
= 0;
5208 else if (!r
->time_blocked
)
5209 r
->time_blocked
= NonZeroTime(now
);
5210 else if (now
- r
->time_blocked
>= 10 * mDNSPlatformOneSecond
* (r
->unresponsiveness_reports
+1))
5213 struct reply_state
*x
= r
->replies
;
5219 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
5220 r
->sd
, r
->process_id
, r
->pid_name
, (now
- r
->time_blocked
) / mDNSPlatformOneSecond
, num
, num
== 1 ? "y" : "ies");
5221 if (++r
->unresponsiveness_reports
>= 60)
5223 LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r
->sd
, r
->process_id
, r
->pid_name
);
5230 if (!dnssd_SocketValid(r
->sd
)) // If this request is finished, unlink it from the list and free the memory
5232 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
5234 freeL("request_state/udsserver_idle", r
);
5242 struct CompileTimeAssertionChecks_uds_daemon
5244 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
5245 // other overly-large structures instead of having a pointer to them, can inadvertently
5246 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
5247 char sizecheck_request_state
[(sizeof(request_state
) <= 3696) ? 1 : -1];
5248 char sizecheck_registered_record_entry
[(sizeof(registered_record_entry
) <= 60) ? 1 : -1];
5249 char sizecheck_service_instance
[(sizeof(service_instance
) <= 6552) ? 1 : -1];
5250 char sizecheck_browser_t
[(sizeof(browser_t
) <= 1432) ? 1 : -1];
5251 char sizecheck_reply_hdr
[(sizeof(reply_hdr
) <= 12) ? 1 : -1];
5252 char sizecheck_reply_state
[(sizeof(reply_state
) <= 64) ? 1 : -1];
5256 #include "../unittests/uds_daemon_ut.c"