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)");
545 rr
= (AuthRecord
*) callocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord
) - sizeof(RDataBody
) + storage_size
);
546 if (!rr
) FatalError("ERROR: calloc");
548 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
550 // The registration is scoped to a specific interface index, but the interface is not currently on our list.
551 if ((InterfaceID
== mDNSInterface_Any
) && (interfaceIndex
!= kDNSServiceInterfaceIndexAny
))
553 // On Apple platforms, an interface's mDNSInterfaceID is equal to its index. Using an interface index that isn't
554 // currently valid will cause the registration to take place as soon as it becomes valid. On other platforms,
555 // mDNSInterfaceID is actually a pointer to a platform-specific interface object, but we don't know what the pointer
556 // for the interface index will be ahead of time. For now, just return NULL to indicate an error condition since the
557 // interface index is invalid. Otherwise, the registration would be performed on all interfaces.
558 #if APPLE_OSX_mDNSResponder
559 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
564 if (InterfaceID
== mDNSInterface_LocalOnly
)
565 artype
= AuthRecordLocalOnly
;
566 else if (InterfaceID
== mDNSInterface_P2P
|| InterfaceID
== mDNSInterface_BLE
)
567 artype
= AuthRecordP2P
;
568 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
)
569 && (flags
& kDNSServiceFlagsIncludeAWDL
))
570 artype
= AuthRecordAnyIncludeAWDLandP2P
;
571 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
))
572 artype
= AuthRecordAnyIncludeP2P
;
573 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeAWDL
))
574 artype
= AuthRecordAnyIncludeAWDL
;
576 artype
= AuthRecordAny
;
578 if (flags
& kDNSServiceFlagsShared
)
579 recordType
= (mDNSu8
) kDNSRecordTypeShared
;
580 else if (flags
& kDNSServiceFlagsKnownUnique
)
581 recordType
= (mDNSu8
) kDNSRecordTypeKnownUnique
;
583 recordType
= (mDNSu8
) kDNSRecordTypeUnique
;
585 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, type
, 0, recordType
, artype
, mDNSNULL
, mDNSNULL
);
587 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, name
))
589 LogMsg("ERROR: bad name: %s", name
);
590 freeL("AuthRecord/read_rr_from_ipc_msg", rr
);
594 if (flags
& kDNSServiceFlagsAllowRemoteQuery
) rr
->AllowRemoteQuery
= mDNStrue
;
595 rr
->resrec
.rrclass
= class;
596 rr
->resrec
.rdlength
= rdlen
;
597 rr
->resrec
.rdata
->MaxRDLength
= rdlen
;
598 mDNSPlatformMemCopy(rr
->resrec
.rdata
->u
.data
, rdata
, rdlen
);
599 if (GetTTL
) rr
->resrec
.rroriginalttl
= ttl
;
600 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
601 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Sets rr->rdatahash for us
605 mDNSlocal
int build_domainname_from_strings(domainname
*srv
, char *name
, char *regtype
, char *domain
)
610 if (!MakeDomainLabelFromLiteralString(&n
, name
)) return -1;
611 if (!MakeDomainNameFromDNSNameString(&t
, regtype
)) return -1;
612 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return -1;
613 if (!ConstructServiceName(srv
, &n
, &t
, &d
)) return -1;
617 mDNSlocal
void send_all(dnssd_sock_t s
, const char *ptr
, int len
)
619 int n
= send(s
, ptr
, len
, 0);
620 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
621 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
622 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
624 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
625 s
, n
, len
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
629 mDNSlocal mDNSBool
AuthorizedDomain(const request_state
* const request
, const domainname
* const d
, const DNameListElem
* const doms
)
631 const DNameListElem
*delem
= mDNSNULL
;
632 int bestDelta
= -1; // the delta of the best match, lower is better
634 mDNSBool allow
= mDNSfalse
;
636 if (SystemUID(request
->uid
)) return mDNStrue
;
638 dLabels
= CountLabels(d
);
639 for (delem
= doms
; delem
; delem
= delem
->next
)
643 int delemLabels
= CountLabels(&delem
->name
);
644 int delta
= dLabels
- delemLabels
;
645 if ((bestDelta
== -1 || delta
<= bestDelta
) && SameDomainName(&delem
->name
, SkipLeadingLabels(d
, delta
)))
648 allow
= (allow
|| (delem
->uid
== request
->uid
));
653 return bestDelta
== -1 ? mDNStrue
: allow
;
657 // ***************************************************************************
658 #if COMPILER_LIKES_PRAGMA_MARK
660 #pragma mark - external helpers
663 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
664 mDNSlocal
void external_start_advertising_helper(service_instance
*const instance
)
666 AuthRecord
*st
= instance
->subtypes
;
667 ExtraResourceRecord
*e
;
670 if (mDNSIPPortIsZero(instance
->request
->u
.servicereg
.port
))
672 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
676 if (instance
->external_advertise
) LogMsg("external_start_advertising_helper: external_advertise already set!");
678 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
679 external_start_advertising_service(&st
[i
].resrec
, instance
->request
->flags
);
681 external_start_advertising_service(&instance
->srs
.RR_PTR
.resrec
, instance
->request
->flags
);
682 external_start_advertising_service(&instance
->srs
.RR_SRV
.resrec
, instance
->request
->flags
);
683 external_start_advertising_service(&instance
->srs
.RR_TXT
.resrec
, instance
->request
->flags
);
685 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
686 external_start_advertising_service(&e
->r
.resrec
, instance
->request
->flags
);
688 instance
->external_advertise
= mDNStrue
;
691 mDNSlocal
void external_stop_advertising_helper(service_instance
*const instance
)
693 AuthRecord
*st
= instance
->subtypes
;
694 ExtraResourceRecord
*e
;
697 if (!instance
->external_advertise
) return;
699 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
701 if (instance
->request
)
703 for (i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
705 external_stop_advertising_service(&st
[i
].resrec
, instance
->request
->flags
);
708 external_stop_advertising_service(&instance
->srs
.RR_PTR
.resrec
, instance
->request
->flags
);
709 external_stop_advertising_service(&instance
->srs
.RR_SRV
.resrec
, instance
->request
->flags
);
710 external_stop_advertising_service(&instance
->srs
.RR_TXT
.resrec
, instance
->request
->flags
);
712 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
714 external_stop_advertising_service(&e
->r
.resrec
, instance
->request
->flags
);
718 instance
->external_advertise
= mDNSfalse
;
720 #endif // MDNSRESPONDER_SUPPORTS(APPLE, D2D)
722 // ***************************************************************************
723 #if COMPILER_LIKES_PRAGMA_MARK
725 #pragma mark - DNSServiceRegister
728 mDNSexport
void FreeExtraRR(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
730 ExtraResourceRecord
*extra
= (ExtraResourceRecord
*)rr
->RecordContext
;
733 if (result
!= mStatus_MemFree
) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result
); return; }
735 LogInfo(" FreeExtraRR %s", RRDisplayString(m
, &rr
->resrec
));
737 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
)
738 freeL("Extra RData", rr
->resrec
.rdata
);
739 freeL("ExtraResourceRecord/FreeExtraRR", extra
);
742 mDNSlocal
void unlink_and_free_service_instance(service_instance
*srv
)
744 ExtraResourceRecord
*e
= srv
->srs
.Extras
, *tmp
;
746 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
747 external_stop_advertising_helper(srv
);
750 // clear pointers from parent struct
753 service_instance
**p
= &srv
->request
->u
.servicereg
.instances
;
756 if (*p
== srv
) { *p
= (*p
)->next
; break; }
763 e
->r
.RecordContext
= e
;
766 FreeExtraRR(&mDNSStorage
, &tmp
->r
, mStatus_MemFree
);
769 if (srv
->srs
.RR_TXT
.resrec
.rdata
!= &srv
->srs
.RR_TXT
.rdatastorage
)
770 freeL("TXT RData", srv
->srs
.RR_TXT
.resrec
.rdata
);
774 freeL("ServiceSubTypes", srv
->subtypes
);
775 srv
->subtypes
= NULL
;
777 freeL("service_instance", srv
);
780 // Count how many other service records we have locally with the same name, but different rdata.
781 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
782 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
783 mDNSexport
int CountPeerRegistrations(ServiceRecordSet
*const srs
)
786 ResourceRecord
*r
= &srs
->RR_SRV
.resrec
;
789 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
790 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& SameDomainName(rr
->resrec
.name
, r
->name
) && !IdenticalSameNameRecord(&rr
->resrec
, r
))
793 verbosedebugf("%d peer registrations for %##s", count
, r
->name
->c
);
797 mDNSexport
int CountExistingRegistrations(domainname
*srv
, mDNSIPPort port
)
801 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
802 if (rr
->resrec
.rrtype
== kDNSType_SRV
&&
803 mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, port
) &&
804 SameDomainName(rr
->resrec
.name
, srv
))
809 mDNSlocal
void SendServiceRemovalNotification(ServiceRecordSet
*const srs
)
812 service_instance
*instance
= srs
->ServiceContext
;
813 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, 0, mStatus_NoError
) != mStatus_NoError
)
814 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
815 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNSfalse
; }
818 // service registration callback performs three duties - frees memory for deregistered services,
819 // handles name conflicts, and delivers completed registration information to the client
820 mDNSlocal
void regservice_callback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
823 mDNSBool SuppressError
= mDNSfalse
;
824 service_instance
*instance
;
830 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regservice_callback: srs is NULL %d", result
);
834 instance
= srs
->ServiceContext
;
837 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regservice_callback: srs->ServiceContext is NULL %d", result
);
841 // don't send errors up to client for wide-area, empty-string registrations
842 if (instance
->request
&&
843 instance
->request
->u
.servicereg
.default_domain
&&
844 !instance
->default_local
)
845 SuppressError
= mDNStrue
;
847 if (mDNS_LoggingEnabled
)
849 const char *result_description
;
850 char description
[32]; // 32-byte is enough for holding "suppressed error -2147483648\0"
851 mDNSu32 request_id
= instance
->request
? instance
->request
->request_id
: 0;
853 case mStatus_NoError
:
854 result_description
= "REGISTERED";
856 case mStatus_MemFree
:
857 result_description
= "DEREGISTERED";
859 case mStatus_NameConflict
:
860 result_description
= "NAME CONFLICT";
863 mDNS_snprintf(description
, sizeof(description
), "%s %d", SuppressError
? "suppressed error" : "CALLBACK", result
);
864 result_description
= description
;
867 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%u] DNSServiceRegister(" PRI_DM_NAME
", %u) %s",
868 request_id
, DM_NAME_PARAM(srs
->RR_SRV
.resrec
.name
->c
), mDNSVal16(srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
), result_description
);
871 if (!instance
->request
&& result
!= mStatus_MemFree
)
873 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regservice_callback: instance->request is NULL %d", result
);
877 if (result
== mStatus_NoError
)
879 if (instance
->request
->u
.servicereg
.allowremotequery
)
881 ExtraResourceRecord
*e
;
882 srs
->RR_ADV
.AllowRemoteQuery
= mDNStrue
;
883 srs
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
884 srs
->RR_SRV
.AllowRemoteQuery
= mDNStrue
;
885 srs
->RR_TXT
.AllowRemoteQuery
= mDNStrue
;
886 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
) e
->r
.AllowRemoteQuery
= mDNStrue
;
889 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
890 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
));
891 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
893 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
894 if (callExternalHelpers(instance
->request
->u
.servicereg
.InterfaceID
, &instance
->domain
, instance
->request
->flags
))
896 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%u] regservice_callback: calling external_start_advertising_helper()", instance
->request
->request_id
);
897 external_start_advertising_helper(instance
);
900 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(srs
) == 0)
901 RecordUpdatedNiceLabel(0); // Successfully got new name, tell user immediately
903 else if (result
== mStatus_MemFree
)
905 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
906 curr_num_regservices
--;
908 if (instance
->request
&& instance
->renameonmemfree
)
910 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
911 external_stop_advertising_helper(instance
);
913 instance
->renameonmemfree
= 0;
914 err
= mDNS_RenameAndReregisterService(m
, srs
, &instance
->request
->u
.servicereg
.name
);
916 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "[R%u] ERROR: regservice_callback - RenameAndReregisterService returned %d", instance
->request
->request_id
, err
);
917 // error should never happen - safest to log and continue
920 unlink_and_free_service_instance(instance
);
922 else if (result
== mStatus_NameConflict
)
924 if (instance
->request
->u
.servicereg
.autorename
)
926 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
927 external_stop_advertising_helper(instance
);
929 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(srs
) == 0)
931 // On conflict for an autoname service, rename and reregister *all* autoname services
932 IncrementLabelSuffix(&m
->nicelabel
, mDNStrue
);
933 mDNS_ConfigChanged(m
); // Will call back into udsserver_handle_configchange()
935 else // On conflict for a non-autoname service, rename and reregister just that one service
937 if (instance
->clientnotified
) SendServiceRemovalNotification(srs
);
938 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
945 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
946 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
));
947 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
949 unlink_and_free_service_instance(instance
);
952 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
956 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
957 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
));
958 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
963 mDNSlocal
void regrecord_callback(mDNS
*const m
, AuthRecord
*rr
, mStatus result
)
966 if (!rr
->RecordContext
) // parent struct already freed by termination callback
968 if (result
== mStatus_NoError
)
969 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "Error: regrecord_callback: successful registration of orphaned record " PRI_S
, ARDisplayString(m
, rr
));
972 if (result
!= mStatus_MemFree
)
973 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
, "regrecord_callback: error %d received after parent termination", result
);
975 // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
976 // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
977 // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
978 // to free the latest rdata for which the update_callback was never called with.
979 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
) freeL("RData/regrecord_callback", rr
->resrec
.rdata
);
980 freeL("AuthRecord/regrecord_callback", rr
);
985 registered_record_entry
*re
= rr
->RecordContext
;
986 request_state
*request
= re
->request
;
988 if (mDNS_LoggingEnabled
)
990 const char *result_description
;
991 char description
[16]; // 16-byte is enough for holding -2147483648\0
993 case mStatus_NoError
:
994 result_description
= "REGISTERED";
996 case mStatus_MemFree
:
997 result_description
= "DEREGISTERED";
999 case mStatus_NameConflict
:
1000 result_description
= "NAME CONFLICT";
1003 mDNS_snprintf(description
, sizeof(description
), "%d", result
);
1004 result_description
= description
;
1008 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%u] DNSServiceRegisterRecord(%u " PRI_S
")" PUB_S
,
1009 request
->request_id
, re
->key
, RRDisplayString(m
, &rr
->resrec
), result_description
);
1012 if (result
!= mStatus_MemFree
)
1014 int len
= sizeof(DNSServiceFlags
) + sizeof(mDNSu32
) + sizeof(DNSServiceErrorType
);
1015 reply_state
*reply
= create_reply(reg_record_reply_op
, len
, request
);
1016 reply
->mhdr
->client_context
= re
->regrec_client_context
;
1017 reply
->rhdr
->flags
= dnssd_htonl(0);
1018 reply
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, rr
->resrec
.InterfaceID
, mDNSfalse
));
1019 reply
->rhdr
->error
= dnssd_htonl(result
);
1020 append_reply(request
, reply
);
1025 // If this is a callback to a keepalive record, do not free it.
1026 if (result
== mStatus_BadStateErr
)
1028 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1029 "[R%u] regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.", request
->request_id
);
1033 // unlink from list, free memory
1034 registered_record_entry
**ptr
= &request
->u
.reg_recs
;
1035 while (*ptr
&& (*ptr
) != re
) ptr
= &(*ptr
)->next
;
1038 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1039 "[R%u] regrecord_callback - record not in list!", request
->request_id
);
1042 *ptr
= (*ptr
)->next
;
1043 freeL("registered_record_entry AuthRecord regrecord_callback", re
->rr
);
1044 freeL("registered_record_entry regrecord_callback", re
);
1049 if (re
->external_advertise
)
1051 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1052 "[R%u] regrecord_callback: external_advertise already set!", request
->request_id
);
1055 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1056 if (callExternalHelpers(re
->origInterfaceID
, &rr
->namestorage
, request
->flags
))
1058 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1059 "[R%u] regrecord_callback: calling external_start_advertising_service", request
->request_id
);
1060 external_start_advertising_service(&rr
->resrec
, request
->flags
);
1061 re
->external_advertise
= mDNStrue
;
1068 // set_peer_pid() is called after mem is allocated for each new request in NewRequest()
1069 // This accounts for 2 places (connect_callback, request_callback)
1070 mDNSlocal
void set_peer_pid(request_state
*request
)
1072 request
->pid_name
[0] = '\0';
1073 request
->process_id
= -1;
1074 #ifdef LOCAL_PEEREPID
1075 pid_t p
= (pid_t
) -1;
1076 socklen_t len
= sizeof(p
);
1077 if (request
->sd
< 0)
1079 // to extract the effective pid value
1080 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREPID
, &p
, &len
) != 0)
1082 // to extract the process name from the pid value
1083 if (proc_pidinfo(p
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0)
1085 mDNSPlatformStrLCopy(request
->pid_name
, proc
.pbsi_comm
, sizeof(request
->pid_name
));
1086 request
->process_id
= p
;
1087 debugf("set_peer_pid: Client PEEREPID is %d %s", p
, request
->pid_name
);
1088 #else // !LOCAL_PEEREPID
1089 LogInfo("set_peer_pid: Not Supported on this version of OS");
1090 if (request
->sd
< 0)
1092 #endif // LOCAL_PEEREPID
1095 mDNSlocal
void connection_termination(request_state
*request
)
1097 // When terminating a shared connection, we need to scan the all_requests list
1098 // and terminate any subbordinate operations sharing this file descriptor
1099 request_state
**req
= &all_requests
;
1101 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1102 "[R%d] DNSServiceCreateConnection STOP PID[%d](" PUB_S
")",
1103 request
->request_id
, request
->process_id
, request
->pid_name
);
1107 if ((*req
)->primary
== request
)
1109 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1110 request_state
*tmp
= *req
;
1111 if (tmp
->primary
== tmp
) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp
, tmp
->sd
);
1112 if (tmp
->replies
) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp
, tmp
->sd
);
1115 freeL("request_state/connection_termination", tmp
);
1118 req
= &(*req
)->next
;
1121 while (request
->u
.reg_recs
)
1123 registered_record_entry
*ptr
= request
->u
.reg_recs
;
1124 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1125 "[R%d] DNSServiceRegisterRecord(0x%X, %d, " PRI_S
") STOP PID[%d](" PUB_S
")",
1126 request
->request_id
, request
->flags
, request
->interfaceIndex
, RRDisplayString(&mDNSStorage
, &ptr
->rr
->resrec
), request
->process_id
,
1128 request
->u
.reg_recs
= request
->u
.reg_recs
->next
;
1129 ptr
->rr
->RecordContext
= NULL
;
1130 if (ptr
->external_advertise
)
1132 ptr
->external_advertise
= mDNSfalse
;
1133 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1134 external_stop_advertising_service(&ptr
->rr
->resrec
, request
->flags
);
1137 LogMcastS(ptr
->rr
, request
, reg_stop
);
1138 mDNS_Deregister(&mDNSStorage
, ptr
->rr
); // Will free ptr->rr for us
1139 freeL("registered_record_entry/connection_termination", ptr
);
1143 mDNSlocal
void handle_cancel_request(request_state
*request
)
1145 request_state
**req
= &all_requests
;
1146 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
, "[R%d] Cancel %08X %08X",
1147 request
->request_id
, request
->hdr
.client_context
.u32
[1], request
->hdr
.client_context
.u32
[0]);
1150 if ((*req
)->primary
== request
&&
1151 (*req
)->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1152 (*req
)->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1])
1154 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1155 request_state
*tmp
= *req
;
1158 freeL("request_state/handle_cancel_request", tmp
);
1161 req
= &(*req
)->next
;
1165 mDNSlocal mStatus
handle_regrecord_request(request_state
*request
)
1167 mStatus err
= mStatus_BadParamErr
;
1170 if (request
->terminate
!= connection_termination
)
1171 { LogMsg("%3d: DNSServiceRegisterRecord(not a shared connection ref)", request
->sd
); return(err
); }
1173 rr
= read_rr_from_ipc_msg(request
, 1, 1);
1176 registered_record_entry
*re
;
1177 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1178 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1179 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
&& !IsLocalDomain(rr
->resrec
.name
) &&
1180 rr
->resrec
.rrclass
== kDNSClass_IN
&& (rr
->resrec
.rrtype
== kDNSType_A
|| rr
->resrec
.rrtype
== kDNSType_AAAA
||
1181 rr
->resrec
.rrtype
== kDNSType_CNAME
))
1183 freeL("AuthRecord/handle_regrecord_request", rr
);
1184 return (mStatus_BadParamErr
);
1186 // allocate registration entry, link into list
1187 re
= (registered_record_entry
*) callocL("registered_record_entry", sizeof(*re
));
1188 if (!re
) FatalError("ERROR: calloc");
1189 re
->key
= request
->hdr
.reg_index
;
1191 re
->regrec_client_context
= request
->hdr
.client_context
;
1192 re
->request
= request
;
1193 re
->external_advertise
= mDNSfalse
;
1194 rr
->RecordContext
= re
;
1195 rr
->RecordCallback
= regrecord_callback
;
1197 re
->origInterfaceID
= rr
->resrec
.InterfaceID
;
1198 if (rr
->resrec
.InterfaceID
== mDNSInterface_P2P
)
1199 rr
->resrec
.InterfaceID
= mDNSInterface_Any
;
1201 if (!AuthorizedDomain(request
, rr
->resrec
.name
, AutoRegistrationDomains
)) return (mStatus_NoError
);
1203 if (rr
->resrec
.rroriginalttl
== 0)
1204 rr
->resrec
.rroriginalttl
= DefaultTTLforRRType(rr
->resrec
.rrtype
);
1206 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1207 "[R%d] DNSServiceRegisterRecord(0x%X, %d, " PRI_S
") START PID[%d](" PUB_S
")",
1208 request
->request_id
, request
->flags
, request
->interfaceIndex
, RRDisplayString(&mDNSStorage
, &rr
->resrec
), request
->process_id
,
1211 err
= mDNS_Register(&mDNSStorage
, rr
);
1214 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1215 "[R%d] DNSServiceRegisterRecord(0x%X, %d," PRI_S
") ERROR (%d)",
1216 request
->request_id
, request
->flags
, request
->interfaceIndex
, RRDisplayString(&mDNSStorage
, &rr
->resrec
), err
);
1217 freeL("registered_record_entry", re
);
1218 freeL("registered_record_entry/AuthRecord", rr
);
1222 LogMcastS(rr
, request
, reg_start
);
1223 re
->next
= request
->u
.reg_recs
;
1224 request
->u
.reg_recs
= re
;
1230 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
);
1232 mDNSlocal
void regservice_termination_callback(request_state
*request
)
1236 LogMsg("regservice_termination_callback context is NULL");
1239 while (request
->u
.servicereg
.instances
)
1241 service_instance
*p
= request
->u
.servicereg
.instances
;
1242 request
->u
.servicereg
.instances
= request
->u
.servicereg
.instances
->next
;
1243 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1244 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceRegister(" PRI_DM_NAME
", %u) STOP PID[%d](" PUB_S
")",
1245 request
->request_id
, DM_NAME_PARAM(p
->srs
.RR_SRV
.resrec
.name
->c
),
1246 mDNSVal16(p
->srs
.RR_SRV
.resrec
.rdata
->u
.srv
.port
), request
->process_id
, request
->pid_name
);
1248 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1249 external_stop_advertising_helper(p
);
1252 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1253 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1254 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1255 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1256 // because by then we might have already freed p
1258 LogMcastS(&p
->srs
.RR_SRV
, request
, reg_stop
);
1259 if (mDNS_DeregisterService(&mDNSStorage
, &p
->srs
))
1261 unlink_and_free_service_instance(p
);
1262 // Don't touch service_instance *p after this -- it's likely to have been freed already
1265 if (request
->u
.servicereg
.txtdata
)
1267 freeL("service_info txtdata", request
->u
.servicereg
.txtdata
);
1268 request
->u
.servicereg
.txtdata
= NULL
;
1270 if (request
->u
.servicereg
.autoname
)
1272 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1273 request
->u
.servicereg
.autoname
= mDNSfalse
;
1274 UpdateDeviceInfoRecord(&mDNSStorage
);
1278 mDNSlocal request_state
*LocateSubordinateRequest(request_state
*request
)
1281 for (req
= all_requests
; req
; req
= req
->next
)
1282 if (req
->primary
== request
&&
1283 req
->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1284 req
->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1]) return(req
);
1288 mDNSlocal mStatus
add_record_to_service(request_state
*request
, service_instance
*instance
, mDNSu16 rrtype
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
)
1290 ServiceRecordSet
*srs
= &instance
->srs
;
1292 size_t size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1293 ExtraResourceRecord
*extra
= (ExtraResourceRecord
*) mallocL("ExtraResourceRecord", sizeof(*extra
) - sizeof(RDataBody
) + size
);
1294 if (!extra
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1296 mDNSPlatformMemZero(extra
, sizeof(*extra
)); // OK if oversized rdata not zero'd
1297 extra
->r
.resrec
.rrtype
= rrtype
;
1298 extra
->r
.rdatastorage
.MaxRDLength
= (mDNSu16
) size
;
1299 extra
->r
.resrec
.rdlength
= rdlen
;
1300 mDNSPlatformMemCopy(&extra
->r
.rdatastorage
.u
.data
, rdata
, rdlen
);
1301 // use InterfaceID value from DNSServiceRegister() call that created the original service
1302 extra
->r
.resrec
.InterfaceID
= request
->u
.servicereg
.InterfaceID
;
1304 result
= mDNS_AddRecordToService(&mDNSStorage
, srs
, extra
, &extra
->r
.rdatastorage
, ttl
, request
->flags
);
1307 freeL("ExtraResourceRecord/add_record_to_service", extra
);
1310 LogMcastS(&srs
->RR_PTR
, request
, reg_start
);
1312 extra
->ClientID
= request
->hdr
.reg_index
;
1313 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1314 if ( instance
->external_advertise
1315 && callExternalHelpers(request
->u
.servicereg
.InterfaceID
, &instance
->domain
, request
->flags
))
1317 LogInfo("add_record_to_service: calling external_start_advertising_service");
1318 external_start_advertising_service(&extra
->r
.resrec
, request
->flags
);
1324 mDNSlocal mStatus
handle_add_request(request_state
*request
)
1326 service_instance
*i
;
1327 mStatus result
= mStatus_UnknownErr
;
1328 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
);
1329 mDNSu16 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
1330 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1331 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1332 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1333 if (!ttl
) ttl
= DefaultTTLforRRType(rrtype
);
1334 (void)flags
; // Unused
1336 if (!request
->msgptr
)
1338 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1339 "[R%d] DNSServiceAddRecord(unreadable parameters)", request
->request_id
);
1340 return(mStatus_BadParamErr
);
1343 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1344 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1346 if (request
->terminate
!= regservice_termination_callback
)
1348 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1349 "[R%d] DNSServiceAddRecord(not a registered service ref)", request
->request_id
);
1350 return(mStatus_BadParamErr
);
1353 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1354 // in the application. See radar://9165807.
1355 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1357 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1358 "[R%d] DNSServiceAddRecord: adding record to a service registered with zero port", request
->request_id
);
1359 return(mStatus_BadParamErr
);
1361 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
1362 "[R%d] DNSServiceAddRecord(%X, " PRI_DM_NAME
", " PUB_S
", %d) PID[%d](" PUB_S
")",
1363 request
->request_id
, flags
,
1364 DM_NAME_PARAM((request
->u
.servicereg
.instances
) ? (request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
) : mDNSNULL
),
1365 DNSTypeName(rrtype
), rdlen
, request
->process_id
, request
->pid_name
);
1367 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1369 result
= add_record_to_service(request
, i
, rrtype
, rdlen
, rdata
, ttl
);
1370 if (result
&& i
->default_local
) break;
1371 else result
= mStatus_NoError
; // suppress non-local default errors
1377 mDNSlocal
void update_callback(mDNS
*const m
, AuthRecord
*const rr
, RData
*oldrd
, mDNSu16 oldrdlen
)
1379 mDNSBool external_advertise
= (rr
->UpdateContext
) ? *((mDNSBool
*)rr
->UpdateContext
) : mDNSfalse
;
1382 // There are three cases.
1384 // 1. We have updated the primary TXT record of the service
1385 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1386 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1388 // external_advertise is set if we have advertised at least once during the initial addition
1389 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1390 // checks during the first time and hence we don't do any checks here
1391 if (external_advertise
)
1393 ResourceRecord ext
= rr
->resrec
;
1394 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1395 DNSServiceFlags flags
= deriveD2DFlagsFromAuthRecType(rr
->ARType
);
1398 if (ext
.rdlength
== oldrdlen
&& mDNSPlatformMemSame(&ext
.rdata
->u
, &oldrd
->u
, oldrdlen
)) goto exit
;
1399 SetNewRData(&ext
, oldrd
, oldrdlen
);
1400 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1401 external_stop_advertising_service(&ext
, flags
);
1402 LogInfo("update_callback: calling external_start_advertising_service");
1403 external_start_advertising_service(&rr
->resrec
, flags
);
1407 if (oldrd
!= &rr
->rdatastorage
) freeL("RData/update_callback", oldrd
);
1410 mDNSlocal mStatus
update_record(AuthRecord
*rr
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
, const mDNSBool
*const external_advertise
)
1413 const size_t rdsize
= (rdlen
> sizeof(RDataBody
)) ? rdlen
: sizeof(RDataBody
);
1414 RData
*newrd
= (RData
*) mallocL("RData/update_record", sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
1415 if (!newrd
) FatalError("ERROR: malloc");
1416 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
1417 mDNSPlatformMemCopy(&newrd
->u
, rdata
, rdlen
);
1419 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1420 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1421 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1422 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rdlen
== 0) { rdlen
= 1; newrd
->u
.txt
.c
[0] = 0; }
1424 if (external_advertise
) rr
->UpdateContext
= (void *)external_advertise
;
1426 result
= mDNS_Update(&mDNSStorage
, rr
, ttl
, rdlen
, newrd
, update_callback
);
1427 if (result
) { LogMsg("update_record: Error %d for %s", (int)result
, ARDisplayString(&mDNSStorage
, rr
)); freeL("RData/update_record", newrd
); }
1431 mDNSlocal mStatus
handle_update_request(request_state
*request
)
1433 const ipc_msg_hdr
*const hdr
= &request
->hdr
;
1434 mStatus result
= mStatus_BadReferenceErr
;
1435 service_instance
*i
;
1436 AuthRecord
*rr
= NULL
;
1438 // get the message data
1439 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
); // flags unused
1440 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1441 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1442 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1443 (void)flags
; // Unused
1445 if (!request
->msgptr
)
1447 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1448 "[R%d] DNSServiceUpdateRecord(unreadable parameters)", request
->request_id
);
1449 return(mStatus_BadParamErr
);
1452 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1453 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1455 if (request
->terminate
== connection_termination
)
1457 // update an individually registered record
1458 registered_record_entry
*reptr
;
1459 for (reptr
= request
->u
.reg_recs
; reptr
; reptr
= reptr
->next
)
1461 if (reptr
->key
== hdr
->reg_index
)
1463 result
= update_record(reptr
->rr
, rdlen
, rdata
, ttl
, &reptr
->external_advertise
);
1464 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1465 "[R%d] DNSServiceUpdateRecord(" PRI_DM_NAME
", " PUB_S
") PID[%d](" PUB_S
")",
1466 request
->request_id
, DM_NAME_PARAM(reptr
->rr
->resrec
.name
->c
),
1467 reptr
->rr
? DNSTypeName(reptr
->rr
->resrec
.rrtype
) : "<NONE>",
1468 request
->process_id
, request
->pid_name
);
1472 result
= mStatus_BadReferenceErr
;
1476 if (request
->terminate
!= regservice_termination_callback
)
1478 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1479 "[R%d] DNSServiceUpdateRecord(not a registered service ref)", request
->request_id
);
1480 return(mStatus_BadParamErr
);
1483 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1484 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1486 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1487 "[R%d] DNSServiceUpdateRecord: updating the record of a service registered with zero port", request
->request_id
);
1488 return(mStatus_BadParamErr
);
1491 // update the saved off TXT data for the service
1492 if (hdr
->reg_index
== TXT_RECORD_INDEX
)
1494 if (request
->u
.servicereg
.txtdata
)
1495 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1498 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", rdlen
);
1499 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_update_request - malloc");
1500 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, rdata
, rdlen
);
1502 request
->u
.servicereg
.txtlen
= rdlen
;
1505 // update a record from a service record set
1506 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1508 if (hdr
->reg_index
== TXT_RECORD_INDEX
) rr
= &i
->srs
.RR_TXT
;
1511 ExtraResourceRecord
*e
;
1512 for (e
= i
->srs
.Extras
; e
; e
= e
->next
)
1513 if (e
->ClientID
== hdr
->reg_index
) { rr
= &e
->r
; break; }
1516 if (!rr
) { result
= mStatus_BadReferenceErr
; goto end
; }
1517 result
= update_record(rr
, rdlen
, rdata
, ttl
, &i
->external_advertise
);
1518 if (result
&& i
->default_local
) goto end
;
1519 else result
= mStatus_NoError
; // suppress non-local default errors
1523 if (request
->terminate
== regservice_termination_callback
)
1524 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)", request
->sd
,
1525 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1526 rr
? DNSTypeName(rr
->resrec
.rrtype
) : "<NONE>",
1527 request
->process_id
, request
->pid_name
);
1532 // remove a resource record registered via DNSServiceRegisterRecord()
1533 mDNSlocal mStatus
remove_record(request_state
*request
)
1535 mStatus err
= mStatus_UnknownErr
;
1536 registered_record_entry
*e
, **ptr
= &request
->u
.reg_recs
;
1538 while (*ptr
&& (*ptr
)->key
!= request
->hdr
.reg_index
) ptr
= &(*ptr
)->next
;
1539 if (!*ptr
) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request
->sd
, request
->hdr
.reg_index
); return mStatus_BadReferenceErr
; }
1541 *ptr
= e
->next
; // unlink
1543 LogOperation("%3d: DNSServiceRemoveRecord(%u %s) PID[%d](%s)",
1544 request
->sd
, e
->key
, RRDisplayString(&mDNSStorage
, &e
->rr
->resrec
), request
->process_id
, request
->pid_name
);
1545 e
->rr
->RecordContext
= NULL
;
1546 if (e
->external_advertise
)
1548 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1549 external_stop_advertising_service(&e
->rr
->resrec
, request
->flags
);
1551 e
->external_advertise
= mDNSfalse
;
1553 LogMcastS(e
->rr
, request
, reg_stop
);
1554 err
= mDNS_Deregister(&mDNSStorage
, e
->rr
); // Will free e->rr for us; we're responsible for freeing e
1557 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err
);
1558 freeL("registered_record_entry AuthRecord remove_record", e
->rr
);
1560 freeL("registered_record_entry remove_record", e
);
1564 mDNSlocal mStatus
remove_extra(const request_state
*const request
, service_instance
*const serv
, mDNSu16
*const rrtype
)
1566 mStatus err
= mStatus_BadReferenceErr
;
1567 ExtraResourceRecord
*ptr
;
1569 for (ptr
= serv
->srs
.Extras
; ptr
; ptr
= ptr
->next
)
1571 if (ptr
->ClientID
== request
->hdr
.reg_index
) // found match
1573 *rrtype
= ptr
->r
.resrec
.rrtype
;
1574 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
1575 if (serv
->external_advertise
) external_stop_advertising_service(&ptr
->r
.resrec
, request
->flags
);
1577 err
= mDNS_RemoveRecordFromService(&mDNSStorage
, &serv
->srs
, ptr
, FreeExtraRR
, ptr
);
1584 mDNSlocal mStatus
handle_removerecord_request(request_state
*request
)
1586 mStatus err
= mStatus_BadReferenceErr
;
1587 get_flags(&request
->msgptr
, request
->msgend
); // flags unused
1589 if (!request
->msgptr
)
1591 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1592 "[R%d] DNSServiceRemoveRecord(unreadable parameters)", request
->request_id
);
1593 return(mStatus_BadParamErr
);
1596 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1597 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1599 if (request
->terminate
== connection_termination
)
1600 err
= remove_record(request
); // remove individually registered record
1601 else if (request
->terminate
!= regservice_termination_callback
)
1603 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
1604 "[R%d] DNSServiceRemoveRecord(not a registered service ref)", request
->request_id
);
1605 return(mStatus_BadParamErr
);
1609 service_instance
*i
;
1611 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceRemoveRecord(" PRI_DM_NAME
", " PUB_S
") PID[%d](" PUB_S
")",
1612 request
->request_id
,
1613 DM_NAME_PARAM((request
->u
.servicereg
.instances
) ? (request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
) : mDNSNULL
),
1614 rrtype
? DNSTypeName(rrtype
) : "<NONE>", request
->process_id
, request
->pid_name
);
1615 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1617 err
= remove_extra(request
, i
, &rrtype
);
1618 if (err
&& i
->default_local
) break;
1619 else err
= mStatus_NoError
; // suppress non-local default errors
1626 // If there's a comma followed by another character,
1627 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1628 // Otherwise, it returns a pointer to the final nul at the end of the string
1629 mDNSlocal
char *FindFirstSubType(char *p
)
1633 if (p
[0] == '\\' && p
[1])
1637 else if (p
[0] == ',' && p
[1])
1650 // If there's a comma followed by another character,
1651 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1652 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1653 // Otherwise, it returns a pointer to the final nul at the end of the string
1654 mDNSlocal
char *FindNextSubType(char *p
)
1658 if (p
[0] == '\\' && p
[1]) // If escape character
1659 p
+= 2; // ignore following character
1660 else if (p
[0] == ',') // If we found a comma
1665 else if (p
[0] == '.')
1672 // Returns -1 if illegal subtype found
1673 mDNSlocal mDNSs32
ChopSubTypes(char *regtype
)
1675 mDNSs32 NumSubTypes
= 0;
1676 char *stp
= FindFirstSubType(regtype
);
1677 while (stp
&& *stp
) // If we found a comma...
1679 if (*stp
== ',') return(-1);
1681 stp
= FindNextSubType(stp
);
1683 if (!stp
) return(-1);
1684 return(NumSubTypes
);
1687 mDNSlocal AuthRecord
*AllocateSubTypes(mDNSs32 NumSubTypes
, char *p
)
1689 AuthRecord
*st
= mDNSNULL
;
1693 st
= (AuthRecord
*) callocL("ServiceSubTypes", NumSubTypes
* sizeof(AuthRecord
));
1694 if (!st
) return(mDNSNULL
);
1695 for (i
= 0; i
< NumSubTypes
; i
++)
1697 mDNS_SetupResourceRecord(&st
[i
], mDNSNULL
, mDNSInterface_Any
, kDNSQType_ANY
, kStandardTTL
, 0, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
1700 if (!MakeDomainNameFromDNSNameString(&st
[i
].namestorage
, p
))
1702 freeL("ServiceSubTypes", st
);
1710 mDNSlocal mStatus
register_service_instance(request_state
*request
, const domainname
*domain
)
1712 service_instance
**ptr
, *instance
;
1713 size_t extra_size
= (request
->u
.servicereg
.txtlen
> sizeof(RDataBody
)) ? (request
->u
.servicereg
.txtlen
- sizeof(RDataBody
)) : 0;
1714 const mDNSBool DomainIsLocal
= SameDomainName(domain
, &localdomain
);
1716 mDNSInterfaceID interfaceID
= request
->u
.servicereg
.InterfaceID
;
1718 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1719 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1720 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1721 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1722 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1723 if (request
->u
.servicereg
.default_domain
&& !DomainIsLocal
) interfaceID
= mDNSInterface_Any
;
1725 for (ptr
= &request
->u
.servicereg
.instances
; *ptr
; ptr
= &(*ptr
)->next
)
1727 if (SameDomainName(&(*ptr
)->domain
, domain
))
1729 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1730 domain
->c
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
);
1731 return mStatus_AlreadyRegistered
;
1735 instance
= (service_instance
*) callocL("service_instance", sizeof(*instance
) + extra_size
);
1736 if (!instance
) { my_perror("ERROR: calloc"); return mStatus_NoMemoryErr
; }
1738 instance
->next
= mDNSNULL
;
1739 instance
->request
= request
;
1740 instance
->renameonmemfree
= 0;
1741 instance
->clientnotified
= mDNSfalse
;
1742 instance
->default_local
= (request
->u
.servicereg
.default_domain
&& DomainIsLocal
);
1743 instance
->external_advertise
= mDNSfalse
;
1744 AssignDomainName(&instance
->domain
, domain
);
1746 instance
->subtypes
= AllocateSubTypes(request
->u
.servicereg
.num_subtypes
, request
->u
.servicereg
.type_as_string
);
1748 if (request
->u
.servicereg
.num_subtypes
&& !instance
->subtypes
)
1750 unlink_and_free_service_instance(instance
);
1752 FatalError("ERROR: malloc");
1755 result
= mDNS_RegisterService(&mDNSStorage
, &instance
->srs
,
1756 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
,
1757 request
->u
.servicereg
.host
.c
[0] ? &request
->u
.servicereg
.host
: NULL
,
1758 request
->u
.servicereg
.port
,
1759 mDNSNULL
, request
->u
.servicereg
.txtdata
, request
->u
.servicereg
.txtlen
,
1760 instance
->subtypes
, request
->u
.servicereg
.num_subtypes
,
1761 interfaceID
, regservice_callback
, instance
, request
->flags
);
1765 *ptr
= instance
; // Append this to the end of our request->u.servicereg.instances list
1766 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance
->request
->sd
,
1767 instance
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(request
->u
.servicereg
.port
));
1768 LogMcastS(&instance
->srs
.RR_SRV
, request
, reg_start
);
1772 LogMsg("register_service_instance %#s.%##s%##s error %d",
1773 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
->c
, result
);
1774 unlink_and_free_service_instance(instance
);
1780 mDNSlocal
void udsserver_default_reg_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
1782 request_state
*request
;
1784 LogMsg("%s registration domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
1785 for (request
= all_requests
; request
; request
= request
->next
)
1787 if (request
->terminate
!= regservice_termination_callback
) continue;
1788 if (!request
->u
.servicereg
.default_domain
) continue;
1789 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
1791 service_instance
**ptr
= &request
->u
.servicereg
.instances
;
1792 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
1795 // If we don't already have this domain in our list for this registration, add it now
1796 if (!*ptr
) register_service_instance(request
, &d
->name
);
1797 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d
->name
);
1801 // Normally we should not fail to find the specified instance
1802 // One case where this can happen is if a uDNS update fails for some reason,
1803 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1805 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1806 &d
->name
, request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type_as_string
);
1810 for (p
= AutoRegistrationDomains
; p
; p
=p
->next
)
1811 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
1812 if (SameDomainName(&d
->name
, &p
->name
)) break;
1813 if (p
) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d
->name
);
1817 service_instance
*si
= *ptr
;
1819 if (si
->clientnotified
) SendServiceRemovalNotification(&si
->srs
); // Do this *before* clearing si->request backpointer
1820 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1821 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1822 // process of completing asynchronously, the client cancels the entire operation, so
1823 // regservice_termination_callback then runs through the whole list deregistering each
1824 // instance, clearing the backpointers, and then disposing the parent request_state object.
1825 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1826 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1827 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1828 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1830 err
= mDNS_DeregisterService(&mDNSStorage
, &si
->srs
);
1831 if (err
) { LogMsg("udsserver_default_reg_domain_changed err %d", err
); unlink_and_free_service_instance(si
); }
1839 // Returns true if the interfaceIndex value matches one of the pre-defined
1840 // special values listed in the switch statement below.
1841 mDNSlocal mDNSBool
PreDefinedInterfaceIndex(mDNSu32 interfaceIndex
)
1843 switch(interfaceIndex
)
1845 case kDNSServiceInterfaceIndexAny
:
1846 case kDNSServiceInterfaceIndexLocalOnly
:
1847 case kDNSServiceInterfaceIndexUnicast
:
1848 case kDNSServiceInterfaceIndexP2P
:
1849 case kDNSServiceInterfaceIndexBLE
:
1856 mDNSlocal mStatus
handle_regservice_request(request_state
*request
)
1858 char name
[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1859 char domain
[MAX_ESCAPED_DOMAIN_NAME
], host
[MAX_ESCAPED_DOMAIN_NAME
];
1860 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
]; // Note that this service type may include a trailing list of subtypes
1863 const char *msgTXTData
;
1865 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
1866 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
1867 mDNSInterfaceID InterfaceID
;
1869 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
1870 // kDNSServiceFlagsIncludeP2P flag set.
1871 if (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)
1873 LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
1874 flags
|= kDNSServiceFlagsIncludeP2P
;
1875 interfaceIndex
= kDNSServiceInterfaceIndexAny
;
1878 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
1880 // The registration is scoped to a specific interface index, but the
1881 // interface is not currently in our list.
1882 if (interfaceIndex
&& !InterfaceID
)
1884 // If it's one of the specially defined inteface index values, just return an error.
1885 if (PreDefinedInterfaceIndex(interfaceIndex
))
1887 LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex
);
1888 return(mStatus_BadParamErr
);
1891 // Otherwise, use the specified interface index value and the registration will
1892 // be applied to that interface when it comes up.
1893 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
1894 LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex
);
1897 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
1898 get_string(&request
->msgptr
, request
->msgend
, type_as_string
, sizeof(type_as_string
)) < 0 ||
1899 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 0 ||
1900 get_string(&request
->msgptr
, request
->msgend
, host
, sizeof(host
)) < 0)
1901 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
1903 request
->flags
= flags
;
1904 request
->interfaceIndex
= interfaceIndex
;
1905 request
->u
.servicereg
.InterfaceID
= InterfaceID
;
1906 request
->u
.servicereg
.instances
= NULL
;
1907 request
->u
.servicereg
.txtlen
= 0;
1908 request
->u
.servicereg
.txtdata
= NULL
;
1909 mDNSPlatformStrLCopy(request
->u
.servicereg
.type_as_string
, type_as_string
, sizeof(request
->u
.servicereg
.type_as_string
));
1911 if (request
->msgptr
+ 2 > request
->msgend
) request
->msgptr
= NULL
;
1914 request
->u
.servicereg
.port
.b
[0] = *request
->msgptr
++;
1915 request
->u
.servicereg
.port
.b
[1] = *request
->msgptr
++;
1918 request
->u
.servicereg
.txtlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1919 msgTXTData
= get_rdata(&request
->msgptr
, request
->msgend
, request
->u
.servicereg
.txtlen
);
1921 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1923 if (request
->u
.servicereg
.txtlen
)
1925 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", request
->u
.servicereg
.txtlen
);
1926 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_regservice_request - malloc");
1927 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, msgTXTData
, request
->u
.servicereg
.txtlen
);
1930 // Check for sub-types after the service type
1931 request
->u
.servicereg
.num_subtypes
= ChopSubTypes(request
->u
.servicereg
.type_as_string
); // Note: Modifies regtype string to remove trailing subtypes
1932 if (request
->u
.servicereg
.num_subtypes
< 0)
1934 LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request
->u
.servicereg
.type_as_string
);
1938 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1939 if (!*request
->u
.servicereg
.type_as_string
|| !MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.type
, request
->u
.servicereg
.type_as_string
))
1940 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request
->u
.servicereg
.type_as_string
); goto bad_param
; }
1944 request
->u
.servicereg
.name
= mDNSStorage
.nicelabel
;
1945 request
->u
.servicereg
.autoname
= mDNStrue
;
1949 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1950 if ((flags
& kDNSServiceFlagsNoAutoRename
) == 0)
1952 int newlen
= TruncateUTF8ToLength((mDNSu8
*)name
, mDNSPlatformStrLen(name
), MAX_DOMAIN_LABEL
);
1955 if (!MakeDomainLabelFromLiteralString(&request
->u
.servicereg
.name
, name
))
1956 { LogMsg("ERROR: handle_regservice_request - name bad %s", name
); goto bad_param
; }
1957 request
->u
.servicereg
.autoname
= mDNSfalse
;
1962 request
->u
.servicereg
.default_domain
= mDNSfalse
;
1963 if (!MakeDomainNameFromDNSNameString(&d
, domain
))
1964 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain
); goto bad_param
; }
1968 request
->u
.servicereg
.default_domain
= mDNStrue
;
1969 MakeDomainNameFromDNSNameString(&d
, "local.");
1972 if (!ConstructServiceName(&srv
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, &d
))
1974 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1975 request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type
.c
, d
.c
); goto bad_param
;
1978 if (!MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.host
, host
))
1979 { LogMsg("ERROR: handle_regservice_request - host bad %s", host
); goto bad_param
; }
1980 request
->u
.servicereg
.autorename
= (flags
& kDNSServiceFlagsNoAutoRename
) == 0;
1981 request
->u
.servicereg
.allowremotequery
= (flags
& kDNSServiceFlagsAllowRemoteQuery
) != 0;
1983 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1984 // a port number of zero. When two instances of the protected client are allowed to run on one
1985 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1986 if (!mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1988 int count
= CountExistingRegistrations(&srv
, request
->u
.servicereg
.port
);
1990 LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request
->process_id
,
1991 request
->pid_name
, count
+1, srv
.c
, mDNSVal16(request
->u
.servicereg
.port
));
1994 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
1995 // Determine if this request should be promoted to use BLE triggered feature.
1996 if (shouldUseBLE(InterfaceID
, 0, &request
->u
.servicereg
.type
, &d
))
1998 request
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
1999 LogInfo("handle_regservice_request: registration promoted to use kDNSServiceFlagsAutoTrigger");
2001 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2003 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2004 "[R%d] DNSServiceRegister(%X, %d, \"" PRI_S
"\", \"" PRI_S
"\", \"" PRI_S
"\", \"" PRI_S
"\", %u) START PID[%d](" PUB_S
")",
2005 request
->request_id
, request
->flags
, interfaceIndex
, name
, request
->u
.servicereg
.type_as_string
, domain
, host
,
2006 mDNSVal16(request
->u
.servicereg
.port
), request
->process_id
, request
->pid_name
);
2008 // We need to unconditionally set request->terminate, because even if we didn't successfully
2009 // start any registrations right now, subsequent configuration changes may cause successful
2010 // registrations to be added, and we'll need to cancel them before freeing this memory.
2011 // We also need to set request->terminate first, before adding additional service instances,
2012 // because the udsserver_validatelists uses the request->terminate function pointer to determine
2013 // what kind of request this is, and therefore what kind of list validation is required.
2014 request
->terminate
= regservice_termination_callback
;
2016 err
= register_service_instance(request
, &d
);
2018 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
2019 ++curr_num_regservices
;
2020 if (curr_num_regservices
> max_num_regservices
)
2021 max_num_regservices
= curr_num_regservices
;
2025 err
= AuthorizedDomain(request
, &d
, AutoRegistrationDomains
) ? register_service_instance(request
, &d
) : mStatus_NoError
;
2029 if (request
->u
.servicereg
.autoname
) UpdateDeviceInfoRecord(&mDNSStorage
);
2034 // Note that we don't report errors for non-local, non-explicit domains
2035 for (ptr
= AutoRegistrationDomains
; ptr
; ptr
= ptr
->next
)
2036 if (!ptr
->uid
|| SystemUID(request
->uid
) || request
->uid
== ptr
->uid
)
2037 register_service_instance(request
, &ptr
->name
);
2044 freeL("handle_regservice_request (txtdata)", request
->u
.servicereg
.txtdata
);
2045 request
->u
.servicereg
.txtdata
= NULL
;
2046 return mStatus_BadParamErr
;
2049 // ***************************************************************************
2050 #if COMPILER_LIKES_PRAGMA_MARK
2052 #pragma mark - DNSServiceBrowse
2055 mDNSlocal
void FoundInstance(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2057 DNSServiceFlags flags
= AddRecord
? kDNSServiceFlagsAdd
: 0;
2058 request_state
*req
= question
->QuestionContext
;
2062 if (answer
->rrtype
!= kDNSType_PTR
)
2063 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req
->sd
, answer
->rrtype
); return; }
2065 if (mDNSOpaque16IsZero(question
->TargetQID
) && (question
->BrowseThreshold
> 0) && (question
->CurrentAnswers
>= question
->BrowseThreshold
))
2067 flags
|= kDNSServiceFlagsThresholdReached
;
2070 // if returning a negative answer, then use question's name in reply
2071 if (answer
->RecordType
== kDNSRecordTypePacketNegative
)
2073 GenerateBrowseReply(&question
->qname
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, kDNSServiceErr_NoSuchRecord
);
2077 if (GenerateNTDResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
) != mStatus_NoError
)
2079 if (SameDomainName(&req
->u
.browser
.regtype
, (const domainname
*)"\x09_services\x07_dns-sd\x04_udp"))
2081 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2082 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2083 GenerateBrowseReply(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
);
2087 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2088 req
->sd
, answer
->name
->c
, answer
->rdata
->u
.name
.c
);
2094 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2095 "[R%d->Q%d] DNSServiceBrowse(" PRI_DM_NAME
", " PUB_S
") RESULT " PUB_S
" interface %d: " PRI_S
,
2096 req
->request_id
, mDNSVal16(question
->TargetQID
), DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
),
2097 AddRecord
? "ADD" : "RMV", mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
),
2098 RRDisplayString(m
, answer
));
2100 append_reply(req
, rep
);
2103 mDNSlocal
void SetQuestionPolicy(DNSQuestion
*q
, request_state
*req
)
2106 // The policy is either based on pid or UUID. Pass a zero pid
2107 // to the "core" if the UUID is valid. If we always pass the pid,
2108 // then the "core" needs to determine whether the uuid is valid
2109 // by examining all the 16 bytes at the time of the policy
2110 // check and also when setting the delegate socket option. Also, it
2111 // requires that we zero out the uuid wherever the question is
2112 // initialized to make sure that it is not interpreted as valid.
2113 // To prevent these intrusive changes, just pass a zero pid to indicate
2114 // that pid is not valid when uuid is valid. In future if we need the
2115 // pid in the question, we will reevaluate this strategy.
2118 mDNSPlatformMemCopy(q
->uuid
, req
->uuid
, UUID_SIZE
);
2123 q
->pid
= req
->process_id
;
2126 //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
2129 mDNSlocal mStatus
add_domain_to_browser(request_state
*info
, const domainname
*d
)
2134 for (p
= info
->u
.browser
.browsers
; p
; p
= p
->next
)
2136 if (SameDomainName(&p
->domain
, d
))
2137 { debugf("add_domain_to_browser %##s already in list", d
->c
); return mStatus_AlreadyRegistered
; }
2140 b
= (browser_t
*) callocL("browser_t", sizeof(*b
));
2141 if (!b
) return mStatus_NoMemoryErr
;
2142 AssignDomainName(&b
->domain
, d
);
2143 SetQuestionPolicy(&b
->q
, info
);
2144 err
= mDNS_StartBrowse(&mDNSStorage
, &b
->q
, &info
->u
.browser
.regtype
, d
, info
->u
.browser
.interface_id
, info
->flags
,
2145 info
->u
.browser
.ForceMCast
, (info
->flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0, FoundInstance
, info
);
2148 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err
, info
->u
.browser
.regtype
.c
, d
->c
);
2149 freeL("browser_t/add_domain_to_browser", b
);
2153 b
->next
= info
->u
.browser
.browsers
;
2154 info
->u
.browser
.browsers
= b
;
2156 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2157 // Determine if this request should be promoted to use BLE triggered discovery.
2158 if (shouldUseBLE(info
->u
.browser
.interface_id
, 0, &info
->u
.browser
.regtype
, (domainname
*) d
))
2160 info
->flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2161 b
->q
.flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2162 LogInfo("add_domain_to_browser: request promoted to use kDNSServiceFlagsAutoTrigger");
2164 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2166 LogMcastQ(&b
->q
, info
, q_start
);
2167 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2168 if (callExternalHelpers(info
->u
.browser
.interface_id
, &b
->domain
, info
->flags
))
2171 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &b
->domain
);
2172 LogDebug("add_domain_to_browser: calling external_start_browsing_for_service()");
2173 external_start_browsing_for_service(info
->u
.browser
.interface_id
, &tmp
, kDNSType_PTR
, info
->flags
);
2180 mDNSlocal
void browse_termination_callback(request_state
*info
)
2182 if (info
->u
.browser
.default_domain
)
2184 // Stop the domain enumeration queries to discover the WAB legacy browse domains
2185 LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info
->sd
, info
->process_id
, info
->pid_name
);
2186 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_LBROWSE_QUERY
);
2188 while (info
->u
.browser
.browsers
)
2190 browser_t
*ptr
= info
->u
.browser
.browsers
;
2192 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2193 if (callExternalHelpers(ptr
->q
.InterfaceID
, &ptr
->domain
, ptr
->q
.flags
))
2196 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &ptr
->domain
);
2197 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2198 external_stop_browsing_for_service(ptr
->q
.InterfaceID
, &tmp
, kDNSType_PTR
, ptr
->q
.flags
);
2201 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2202 "[R%d] DNSServiceBrowse(%X, %d, \"" PRI_DM_NAME
"\") STOP PID[%d](" PUB_S
")",
2203 info
->request_id
, info
->flags
, info
->interfaceIndex
, DM_NAME_PARAM(ptr
->q
.qname
.c
),
2204 info
->process_id
, info
->pid_name
);
2206 info
->u
.browser
.browsers
= ptr
->next
;
2207 mDNS_StopBrowse(&mDNSStorage
, &ptr
->q
); // no need to error-check result
2208 LogMcastQ(&ptr
->q
, info
, q_stop
);
2209 freeL("browser_t/browse_termination_callback", ptr
);
2213 mDNSlocal
void udsserver_automatic_browse_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
2215 request_state
*request
;
2216 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
2218 for (request
= all_requests
; request
; request
= request
->next
)
2220 if (request
->terminate
!= browse_termination_callback
) continue; // Not a browse operation
2221 if (!request
->u
.browser
.default_domain
) continue; // Not an auto-browse operation
2222 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
2224 browser_t
**ptr
= &request
->u
.browser
.browsers
;
2225 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
2228 // If we don't already have this domain in our list for this browse operation, add it now
2229 if (!*ptr
) add_domain_to_browser(request
, &d
->name
);
2230 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d
->name
);
2234 if (!*ptr
) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d
->name
);
2238 for (p
= AutoBrowseDomains
; p
; p
=p
->next
)
2239 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
2240 if (SameDomainName(&d
->name
, &p
->name
)) break;
2241 if (p
) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d
->name
);
2244 browser_t
*rem
= *ptr
;
2245 *ptr
= (*ptr
)->next
;
2246 mDNS_StopQueryWithRemoves(&mDNSStorage
, &rem
->q
);
2247 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem
);
2255 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
2258 if (result
== mStatus_MemFree
)
2260 // On shutdown, mDNS_Close automatically deregisters all records
2261 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2262 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2263 // (This should actually no longer be necessary, now that we do the proper cleanup in
2264 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2265 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2266 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2267 while (*ptr
&& &(*ptr
)->ar
!= rr
) ptr
= &(*ptr
)->next
;
2268 if (*ptr
) { *ptr
= (*ptr
)->next
; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m
, rr
)); }
2269 mDNSPlatformMemFree(rr
->RecordContext
);
2273 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2274 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2275 // We may want to turn the common code into a subroutine.
2277 mDNSlocal
void RegisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2279 // allocate/register legacy and non-legacy _browse PTR record
2281 ARListElem
*ptr
= (ARListElem
*) mDNSPlatformMemAllocateClear(sizeof(*ptr
));
2283 debugf("Incrementing %s refcount for %##s",
2284 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2285 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2286 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2288 mDNS_SetupResourceRecord(&ptr
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, AuthRecordLocalOnly
, FreeARElemCallback
, ptr
);
2289 MakeDomainNameFromDNSNameString(&ptr
->ar
.namestorage
, mDNS_DomainTypeNames
[type
]);
2290 AppendDNSNameString (&ptr
->ar
.namestorage
, "local");
2291 AssignDomainName(&ptr
->ar
.resrec
.rdata
->u
.name
, d
);
2292 err
= mDNS_Register(m
, &ptr
->ar
);
2295 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err
);
2296 mDNSPlatformMemFree(ptr
);
2300 ptr
->next
= LocalDomainEnumRecords
;
2301 LocalDomainEnumRecords
= ptr
;
2305 mDNSlocal
void DeregisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2307 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2308 domainname lhs
; // left-hand side of PTR, for comparison
2310 debugf("Decrementing %s refcount for %##s",
2311 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2312 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2313 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2315 MakeDomainNameFromDNSNameString(&lhs
, mDNS_DomainTypeNames
[type
]);
2316 AppendDNSNameString (&lhs
, "local");
2320 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, d
) && SameDomainName((*ptr
)->ar
.resrec
.name
, &lhs
))
2322 ARListElem
*rem
= *ptr
;
2323 *ptr
= (*ptr
)->next
;
2324 mDNS_Deregister(m
, &rem
->ar
);
2327 else ptr
= &(*ptr
)->next
;
2331 mDNSlocal
void AddAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2333 DNameListElem
*new = (DNameListElem
*) mDNSPlatformMemAllocateClear(sizeof(*new));
2334 if (!new) { LogMsg("ERROR: malloc"); return; }
2335 AssignDomainName(&new->name
, name
);
2337 new->next
= AutoBrowseDomains
;
2338 AutoBrowseDomains
= new;
2339 udsserver_automatic_browse_domain_changed(new, mDNStrue
);
2342 mDNSlocal
void RmvAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2344 DNameListElem
**p
= &AutoBrowseDomains
;
2345 while (*p
&& (!SameDomainName(&(*p
)->name
, name
) || (*p
)->uid
!= uid
)) p
= &(*p
)->next
;
2346 if (!*p
) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name
->c
);
2349 DNameListElem
*ptr
= *p
;
2351 udsserver_automatic_browse_domain_changed(ptr
, mDNSfalse
);
2352 mDNSPlatformMemFree(ptr
);
2356 mDNSlocal
void SetPrefsBrowseDomains(mDNS
*m
, DNameListElem
*browseDomains
, mDNSBool add
)
2359 for (d
= browseDomains
; d
; d
= d
->next
)
2363 RegisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2364 AddAutoBrowseDomain(d
->uid
, &d
->name
);
2368 DeregisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2369 RmvAutoBrowseDomain(d
->uid
, &d
->name
);
2374 #if APPLE_OSX_mDNSResponder
2376 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
2378 int num_autoname
= 0;
2381 // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2382 for (req
= all_requests
; req
; req
= req
->next
)
2384 if (req
->terminate
== regservice_termination_callback
&& req
->u
.servicereg
.autoname
&& req
->interfaceIndex
!= kDNSServiceInterfaceIndexLocalOnly
)
2388 // If DeviceInfo record is currently registered, see if we need to deregister it
2389 if (m
->DeviceInfo
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
)
2390 if (num_autoname
== 0 || !SameDomainLabelCS(m
->DeviceInfo
.resrec
.name
->c
, m
->nicelabel
.c
))
2392 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m
->DeviceInfo
.resrec
.name
);
2393 mDNS_Deregister(m
, &m
->DeviceInfo
);
2396 // If DeviceInfo record is not currently registered, see if we need to register it
2397 if (m
->DeviceInfo
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2398 if (num_autoname
> 0)
2400 mDNS_SetupResourceRecord(&m
->DeviceInfo
, mDNSNULL
, mDNSNULL
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeAdvisory
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2401 ConstructServiceName(&m
->DeviceInfo
.namestorage
, &m
->nicelabel
, &DeviceInfoName
, &localdomain
);
2402 m
->DeviceInfo
.resrec
.rdlength
= initializeDeviceInfoTXT(m
, m
->DeviceInfo
.resrec
.rdata
->u
.data
);
2403 LogOperation("UpdateDeviceInfoRecord Register %##s", m
->DeviceInfo
.resrec
.name
);
2404 mDNS_Register(m
, &m
->DeviceInfo
);
2407 #else // APPLE_OSX_mDNSResponder
2408 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
2412 #endif // APPLE_OSX_mDNSResponder
2414 mDNSexport
void udsserver_handle_configchange(mDNS
*const m
)
2417 service_instance
*ptr
;
2418 DNameListElem
*RegDomains
= NULL
;
2419 DNameListElem
*BrowseDomains
= NULL
;
2422 UpdateDeviceInfoRecord(m
);
2424 // For autoname services, see if the default service name has changed, necessitating an automatic update
2425 for (req
= all_requests
; req
; req
= req
->next
)
2426 if (req
->terminate
== regservice_termination_callback
)
2427 if (req
->u
.servicereg
.autoname
&& !SameDomainLabelCS(req
->u
.servicereg
.name
.c
, m
->nicelabel
.c
))
2429 req
->u
.servicereg
.name
= m
->nicelabel
;
2430 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
2432 ptr
->renameonmemfree
= 1;
2433 if (ptr
->clientnotified
) SendServiceRemovalNotification(&ptr
->srs
);
2434 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr
->srs
.RR_PTR
.resrec
.name
->c
);
2435 if (mDNS_DeregisterService_drt(m
, &ptr
->srs
, mDNS_Dereg_rapid
))
2436 regservice_callback(m
, &ptr
->srs
, mStatus_MemFree
); // If service deregistered already, we can re-register immediately
2440 // Let the platform layer get the current DNS information
2442 mDNSPlatformSetDNSConfig(mDNSfalse
, mDNSfalse
, mDNSNULL
, &RegDomains
, &BrowseDomains
, mDNSfalse
);
2445 // Any automatic registration domains are also implicitly automatic browsing domains
2446 if (RegDomains
) SetPrefsBrowseDomains(m
, RegDomains
, mDNStrue
); // Add the new list first
2447 if (AutoRegistrationDomains
) SetPrefsBrowseDomains(m
, AutoRegistrationDomains
, mDNSfalse
); // Then clear the old list
2449 // Add any new domains not already in our AutoRegistrationDomains list
2450 for (p
=RegDomains
; p
; p
=p
->next
)
2452 DNameListElem
**pp
= &AutoRegistrationDomains
;
2453 while (*pp
&& ((*pp
)->uid
!= p
->uid
|| !SameDomainName(&(*pp
)->name
, &p
->name
))) pp
= &(*pp
)->next
;
2454 if (!*pp
) // If not found in our existing list, this is a new default registration domain
2456 RegisterLocalOnlyDomainEnumPTR(m
, &p
->name
, mDNS_DomainTypeRegistration
);
2457 udsserver_default_reg_domain_changed(p
, mDNStrue
);
2459 else // else found same domainname in both old and new lists, so no change, just delete old copy
2461 DNameListElem
*del
= *pp
;
2463 mDNSPlatformMemFree(del
);
2467 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2468 while (AutoRegistrationDomains
)
2470 DNameListElem
*del
= AutoRegistrationDomains
;
2471 AutoRegistrationDomains
= AutoRegistrationDomains
->next
; // Cut record from list FIRST,
2472 DeregisterLocalOnlyDomainEnumPTR(m
, &del
->name
, mDNS_DomainTypeRegistration
);
2473 udsserver_default_reg_domain_changed(del
, mDNSfalse
); // before calling udsserver_default_reg_domain_changed()
2474 mDNSPlatformMemFree(del
);
2477 // Now we have our new updated automatic registration domain list
2478 AutoRegistrationDomains
= RegDomains
;
2480 // Add new browse domains to internal list
2481 if (BrowseDomains
) SetPrefsBrowseDomains(m
, BrowseDomains
, mDNStrue
);
2483 // Remove old browse domains from internal list
2484 if (SCPrefBrowseDomains
)
2486 SetPrefsBrowseDomains(m
, SCPrefBrowseDomains
, mDNSfalse
);
2487 while (SCPrefBrowseDomains
)
2489 DNameListElem
*fptr
= SCPrefBrowseDomains
;
2490 SCPrefBrowseDomains
= SCPrefBrowseDomains
->next
;
2491 mDNSPlatformMemFree(fptr
);
2495 // Replace the old browse domains array with the new array
2496 SCPrefBrowseDomains
= BrowseDomains
;
2499 mDNSlocal
void AutomaticBrowseDomainChange(mDNS
*const m
, DNSQuestion
*q
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2504 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2505 AddRecord
? "Adding" : "Removing", answer
->rdata
->u
.name
.c
);
2507 if (AddRecord
) AddAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2508 else RmvAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2511 mDNSlocal mStatus
handle_browse_request(request_state
*request
)
2513 // Note that regtype may include a trailing subtype
2514 char regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2515 domainname typedn
, d
, temp
;
2516 mDNSs32 NumSubTypes
;
2517 mStatus err
= mStatus_NoError
;
2519 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2520 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2521 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2523 // The browse is scoped to a specific interface index, but the
2524 // interface is not currently in our list.
2525 if (interfaceIndex
&& !InterfaceID
)
2527 // If it's one of the specially defined inteface index values, just return an error.
2528 if (PreDefinedInterfaceIndex(interfaceIndex
))
2530 LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex
);
2531 return(mStatus_BadParamErr
);
2534 // Otherwise, use the specified interface index value and the browse will
2535 // be applied to that interface when it comes up.
2536 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
2537 LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex
);
2540 if (get_string(&request
->msgptr
, request
->msgend
, regtype
, sizeof(regtype
)) < 0 ||
2541 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 0) return(mStatus_BadParamErr
);
2543 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2545 request
->flags
= flags
;
2546 request
->interfaceIndex
= interfaceIndex
;
2548 NumSubTypes
= ChopSubTypes(regtype
); // Note: Modifies regtype string to remove trailing subtypes
2549 if (NumSubTypes
< 0 || NumSubTypes
> 1)
2550 return(mStatus_BadParamErr
);
2551 if (NumSubTypes
== 1)
2553 if (!AppendDNSNameString(&typedn
, regtype
+ strlen(regtype
) + 1))
2554 return(mStatus_BadParamErr
);
2557 if (!regtype
[0] || !AppendDNSNameString(&typedn
, regtype
)) return(mStatus_BadParamErr
);
2559 if (!MakeDomainNameFromDNSNameString(&temp
, regtype
)) return(mStatus_BadParamErr
);
2560 // For over-long service types, we only allow domain "local"
2561 if (temp
.c
[0] > 15 && domain
[0] == 0) mDNSPlatformStrLCopy(domain
, "local.", sizeof(domain
));
2563 // Set up browser info
2564 request
->u
.browser
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2565 request
->u
.browser
.interface_id
= InterfaceID
;
2566 AssignDomainName(&request
->u
.browser
.regtype
, &typedn
);
2567 request
->u
.browser
.default_domain
= !domain
[0];
2568 request
->u
.browser
.browsers
= NULL
;
2570 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceBrowse(%X, %d, \"" PRI_DM_NAME
"\", \"" PRI_S
"\") START PID[%d](" PUB_S
")",
2571 request
->request_id
, request
->flags
, interfaceIndex
, DM_NAME_PARAM(request
->u
.browser
.regtype
.c
), domain
,
2572 request
->process_id
, request
->pid_name
);
2574 if (request
->u
.browser
.default_domain
)
2576 // Start the domain enumeration queries to discover the WAB browse domains
2577 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2578 "[R%d] DNSServiceBrowse Start WAB PID[%d](" PUB_S
")",
2579 request
->request_id
, request
->process_id
, request
->pid_name
);
2580 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_LBROWSE_QUERY
);
2582 // We need to unconditionally set request->terminate, because even if we didn't successfully
2583 // start any browses right now, subsequent configuration changes may cause successful
2584 // browses to be added, and we'll need to cancel them before freeing this memory.
2585 request
->terminate
= browse_termination_callback
;
2589 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return(mStatus_BadParamErr
);
2590 err
= add_domain_to_browser(request
, &d
);
2594 DNameListElem
*sdom
;
2595 for (sdom
= AutoBrowseDomains
; sdom
; sdom
= sdom
->next
)
2596 if (!sdom
->uid
|| SystemUID(request
->uid
) || request
->uid
== sdom
->uid
)
2598 err
= add_domain_to_browser(request
, &sdom
->name
);
2601 if (SameDomainName(&sdom
->name
, &localdomain
)) break;
2602 else err
= mStatus_NoError
; // suppress errors for non-local "default" domains
2610 // ***************************************************************************
2611 #if COMPILER_LIKES_PRAGMA_MARK
2613 #pragma mark - DNSServiceResolve
2616 mDNSlocal
void resolve_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2619 char fullname
[MAX_ESCAPED_DOMAIN_NAME
], target
[MAX_ESCAPED_DOMAIN_NAME
] = "0";
2622 request_state
*req
= question
->QuestionContext
;
2623 const DNSServiceErrorType error
=
2624 (answer
->RecordType
== kDNSRecordTypePacketNegative
) ? kDNSServiceErr_NoSuchRecord
: kDNSServiceErr_NoError
;
2627 LogOperation("%3d: DNSServiceResolve(%##s) %s interface %d: %s",
2628 req
->sd
, question
->qname
.c
, AddRecord
? "ADD" : "RMV",
2629 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
), RRDisplayString(m
, answer
));
2633 if (req
->u
.resolve
.srv
== answer
) req
->u
.resolve
.srv
= mDNSNULL
;
2634 if (req
->u
.resolve
.txt
== answer
) req
->u
.resolve
.txt
= mDNSNULL
;
2638 if (answer
->rrtype
== kDNSType_SRV
) req
->u
.resolve
.srv
= answer
;
2639 if (answer
->rrtype
== kDNSType_TXT
) req
->u
.resolve
.txt
= answer
;
2641 if (!req
->u
.resolve
.txt
|| !req
->u
.resolve
.srv
) return; // only deliver result to client if we have both answers
2643 ConvertDomainNameToCString(answer
->name
, fullname
);
2645 if (answer
->RecordType
!= kDNSRecordTypePacketNegative
)
2646 ConvertDomainNameToCString(&req
->u
.resolve
.srv
->rdata
->u
.srv
.target
, target
);
2648 // calculate reply length
2649 len
+= sizeof(DNSServiceFlags
);
2650 len
+= sizeof(mDNSu32
); // interface index
2651 len
+= sizeof(DNSServiceErrorType
);
2652 len
+= strlen(fullname
) + 1;
2653 len
+= strlen(target
) + 1;
2654 len
+= 2 * sizeof(mDNSu16
); // port, txtLen
2655 len
+= req
->u
.resolve
.txt
->rdlength
;
2657 // allocate/init reply header
2658 rep
= create_reply(resolve_reply_op
, len
, req
);
2659 rep
->rhdr
->flags
= dnssd_htonl(0);
2660 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
));
2661 rep
->rhdr
->error
= dnssd_htonl(error
);
2663 data
= (char *)&rep
->rhdr
[1];
2665 // write reply data to message
2666 put_string(fullname
, &data
);
2667 put_string(target
, &data
);
2668 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[0];
2669 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[1];
2670 put_uint16(req
->u
.resolve
.txt
->rdlength
, &data
);
2671 put_rdata (req
->u
.resolve
.txt
->rdlength
, req
->u
.resolve
.txt
->rdata
->u
.data
, &data
);
2673 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d->Q%d] DNSServiceResolve(" PRI_S
") RESULT " PRI_S
":%d",
2674 req
->request_id
, mDNSVal16(question
->TargetQID
), fullname
, target
,
2675 mDNSVal16(req
->u
.resolve
.srv
->rdata
->u
.srv
.port
));
2676 append_reply(req
, rep
);
2679 mDNSlocal
void resolve_termination_callback(request_state
*request
)
2681 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2682 "[R%d] DNSServiceResolve(%X, %d, \"" PRI_DM_NAME
"\") STOP PID[%d](" PUB_S
")",
2683 request
->request_id
, request
->flags
, request
->interfaceIndex
, DM_NAME_PARAM(request
->u
.resolve
.qtxt
.qname
.c
),
2684 request
->process_id
, request
->pid_name
);
2685 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2686 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2687 LogMcastQ(&request
->u
.resolve
.qsrv
, request
, q_stop
);
2688 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2689 if (request
->u
.resolve
.external_advertise
)
2690 external_stop_resolving_service(request
->u
.resolve
.qsrv
.InterfaceID
, &request
->u
.resolve
.qsrv
.qname
, request
->flags
);
2694 mDNSlocal mStatus
handle_resolve_request(request_state
*request
)
2696 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2700 // extract the data from the message
2701 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2702 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2703 mDNSInterfaceID InterfaceID
;
2705 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2706 // flag set so that the resolve will run over P2P interfaces that are not yet created.
2707 if (interfaceIndex
== kDNSServiceInterfaceIndexP2P
)
2709 LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2710 flags
|= kDNSServiceFlagsIncludeP2P
;
2711 interfaceIndex
= kDNSServiceInterfaceIndexAny
;
2714 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2716 // The operation is scoped to a specific interface index, but the
2717 // interface is not currently in our list.
2718 if (interfaceIndex
&& !InterfaceID
)
2720 // If it's one of the specially defined inteface index values, just return an error.
2721 if (PreDefinedInterfaceIndex(interfaceIndex
))
2723 LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex
);
2724 return(mStatus_BadParamErr
);
2727 // Otherwise, use the specified interface index value and the operation will
2728 // be applied to that interface when it comes up.
2729 InterfaceID
= (mDNSInterfaceID
)(uintptr_t)interfaceIndex
;
2730 LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex
);
2733 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
2734 get_string(&request
->msgptr
, request
->msgend
, regtype
, sizeof(regtype
)) < 0 ||
2735 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 0)
2736 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
2738 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2740 if (build_domainname_from_strings(&fqdn
, name
, regtype
, domain
) < 0)
2741 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name
, regtype
, domain
); return(mStatus_BadParamErr
); }
2743 mDNSPlatformMemZero(&request
->u
.resolve
, sizeof(request
->u
.resolve
));
2745 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2746 // Determine if this request should be promoted to use BLE triggered discovery.
2747 if (shouldUseBLE(InterfaceID
, 0, (domainname
*)SkipLeadingLabels(&fqdn
, 1), &fqdn
))
2749 flags
|= (kDNSServiceFlagsAutoTrigger
| kDNSServiceFlagsIncludeAWDL
);
2750 LogInfo("handle_resolve_request: request promoted to use kDNSServiceFlagsAutoTrigger");
2752 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2754 request
->flags
= flags
;
2755 request
->interfaceIndex
= interfaceIndex
;
2758 request
->u
.resolve
.qsrv
.InterfaceID
= InterfaceID
;
2759 request
->u
.resolve
.qsrv
.flags
= flags
;
2760 AssignDomainName(&request
->u
.resolve
.qsrv
.qname
, &fqdn
);
2761 request
->u
.resolve
.qsrv
.qtype
= kDNSType_SRV
;
2762 request
->u
.resolve
.qsrv
.qclass
= kDNSClass_IN
;
2763 request
->u
.resolve
.qsrv
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2764 request
->u
.resolve
.qsrv
.ExpectUnique
= mDNStrue
;
2765 request
->u
.resolve
.qsrv
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2766 request
->u
.resolve
.qsrv
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2767 request
->u
.resolve
.qsrv
.SuppressUnusable
= mDNSfalse
;
2768 request
->u
.resolve
.qsrv
.AppendSearchDomains
= 0;
2769 request
->u
.resolve
.qsrv
.TimeoutQuestion
= 0;
2770 request
->u
.resolve
.qsrv
.WakeOnResolve
= (flags
& kDNSServiceFlagsWakeOnResolve
) != 0;
2771 request
->u
.resolve
.qsrv
.UseBackgroundTraffic
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
2772 request
->u
.resolve
.qsrv
.ValidationRequired
= 0;
2773 request
->u
.resolve
.qsrv
.ValidatingResponse
= 0;
2774 request
->u
.resolve
.qsrv
.ProxyQuestion
= 0;
2775 request
->u
.resolve
.qsrv
.pid
= request
->process_id
;
2776 request
->u
.resolve
.qsrv
.euid
= request
->uid
;
2777 request
->u
.resolve
.qsrv
.QuestionCallback
= resolve_result_callback
;
2778 request
->u
.resolve
.qsrv
.QuestionContext
= request
;
2780 request
->u
.resolve
.qtxt
.InterfaceID
= InterfaceID
;
2781 request
->u
.resolve
.qtxt
.flags
= flags
;
2782 AssignDomainName(&request
->u
.resolve
.qtxt
.qname
, &fqdn
);
2783 request
->u
.resolve
.qtxt
.qtype
= kDNSType_TXT
;
2784 request
->u
.resolve
.qtxt
.qclass
= kDNSClass_IN
;
2785 request
->u
.resolve
.qtxt
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2786 request
->u
.resolve
.qtxt
.ExpectUnique
= mDNStrue
;
2787 request
->u
.resolve
.qtxt
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2788 request
->u
.resolve
.qtxt
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2789 request
->u
.resolve
.qtxt
.SuppressUnusable
= mDNSfalse
;
2790 request
->u
.resolve
.qtxt
.AppendSearchDomains
= 0;
2791 request
->u
.resolve
.qtxt
.TimeoutQuestion
= 0;
2792 request
->u
.resolve
.qtxt
.WakeOnResolve
= 0;
2793 request
->u
.resolve
.qtxt
.UseBackgroundTraffic
= (flags
& kDNSServiceFlagsBackgroundTrafficClass
) != 0;
2794 request
->u
.resolve
.qtxt
.ValidationRequired
= 0;
2795 request
->u
.resolve
.qtxt
.ValidatingResponse
= 0;
2796 request
->u
.resolve
.qtxt
.ProxyQuestion
= 0;
2797 request
->u
.resolve
.qtxt
.pid
= request
->process_id
;
2798 request
->u
.resolve
.qtxt
.euid
= request
->uid
;
2799 request
->u
.resolve
.qtxt
.QuestionCallback
= resolve_result_callback
;
2800 request
->u
.resolve
.qtxt
.QuestionContext
= request
;
2802 request
->u
.resolve
.ReportTime
= NonZeroTime(mDNS_TimeNow(&mDNSStorage
) + 130 * mDNSPlatformOneSecond
);
2804 request
->u
.resolve
.external_advertise
= mDNSfalse
;
2807 if (!AuthorizedDomain(request
, &fqdn
, AutoBrowseDomains
)) return(mStatus_NoError
);
2810 // ask the questions
2811 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2812 "[R%d] DNSServiceResolve(%X, %d, \"" PRI_DM_NAME
"\") START PID[%d](" PUB_S
")",
2813 request
->request_id
, flags
, interfaceIndex
, DM_NAME_PARAM(request
->u
.resolve
.qsrv
.qname
.c
),
2814 request
->process_id
, request
->pid_name
);
2816 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2820 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2823 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2827 request
->terminate
= resolve_termination_callback
;
2828 LogMcastQ(&request
->u
.resolve
.qsrv
, request
, q_start
);
2829 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2830 if (callExternalHelpers(InterfaceID
, &fqdn
, flags
))
2832 request
->u
.resolve
.external_advertise
= mDNStrue
;
2833 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2834 external_start_resolving_service(InterfaceID
, &fqdn
, flags
);
2843 // ***************************************************************************
2844 #if COMPILER_LIKES_PRAGMA_MARK
2846 #pragma mark - DNSServiceQueryRecord
2849 mDNSlocal
void queryrecord_result_reply(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
, DNSServiceErrorType error
, void *context
)
2851 char name
[MAX_ESCAPED_DOMAIN_NAME
];
2853 DNSServiceFlags flags
= 0;
2856 request_state
*req
= (request_state
*)context
;
2858 ConvertDomainNameToCString(answer
->name
, name
);
2860 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2861 "[R%u->Q%u] DNSService" PUB_S
"(" PRI_DM_NAME
", " PUB_S
") RESULT " PUB_S
" interface %d: (" PUB_S
")" PRI_S
,
2862 req
->request_id
, mDNSVal16(question
->TargetQID
), req
->hdr
.op
== query_request
? "QueryRecord" : "GetAddrInfo",
2863 DM_NAME_PARAM(question
->qname
.c
), DNSTypeName(question
->qtype
), AddRecord
? "ADD" : "RMV",
2864 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
),
2865 MortalityDisplayString(answer
->mortality
), RRDisplayString(m
, answer
));
2867 len
= sizeof(DNSServiceFlags
); // calculate reply data length
2868 len
+= sizeof(mDNSu32
); // interface index
2869 len
+= sizeof(DNSServiceErrorType
);
2870 len
+= strlen(name
) + 1;
2871 len
+= 3 * sizeof(mDNSu16
); // type, class, rdlen
2872 len
+= answer
->rdlength
;
2873 len
+= sizeof(mDNSu32
); // TTL
2875 rep
= create_reply(req
->hdr
.op
== query_request
? query_reply_op
: addrinfo_reply_op
, len
, req
);
2878 flags
|= kDNSServiceFlagsAdd
;
2879 if (answer
->mortality
== Mortality_Ghost
)
2880 flags
|= kDNSServiceFlagsExpiredAnswer
;
2881 if (!question
->InitialCacheMiss
)
2882 flags
|= kDNSServiceFlagAnsweredFromCache
;
2883 if (question
->ValidationStatus
!= 0)
2885 error
= kDNSServiceErr_NoError
;
2886 if (question
->ValidationRequired
&& question
->ValidationState
== DNSSECValDone
)
2888 switch (question
->ValidationStatus
) //Set the dnssec flags to be passed on to the Apps here
2891 flags
|= kDNSServiceFlagsSecure
;
2893 case DNSSEC_Insecure
:
2894 flags
|= kDNSServiceFlagsInsecure
;
2896 case DNSSEC_Indeterminate
:
2897 flags
|= kDNSServiceFlagsIndeterminate
;
2900 flags
|= kDNSServiceFlagsBogus
;
2903 LogMsg("queryrecord_result_reply unknown status %d for %##s", question
->ValidationStatus
, question
->qname
.c
);
2908 rep
->rhdr
->flags
= dnssd_htonl(flags
);
2909 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
2910 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
2911 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
2912 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
2913 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
2914 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
2915 // should not have existed to answer this question if the corresponding interface is not valid.
2916 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNStrue
));
2917 rep
->rhdr
->error
= dnssd_htonl(error
);
2919 data
= (char *)&rep
->rhdr
[1];
2921 put_string(name
, &data
);
2922 put_uint16(answer
->rrtype
, &data
);
2923 put_uint16(answer
->rrclass
, &data
);
2924 put_uint16(answer
->rdlength
, &data
);
2925 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2926 // function just does a blind memory copy without regard to structures that may have holes in them.
2927 if (answer
->rdlength
)
2928 if (!putRData(mDNSNULL
, (mDNSu8
*)data
, (mDNSu8
*)rep
->rhdr
+ len
, answer
))
2929 LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8
*)rep
->rhdr
+ len
- (mDNSu8
*)data
);
2930 data
+= answer
->rdlength
;
2931 put_uint32(AddRecord
? answer
->rroriginalttl
: 0, &data
);
2933 append_reply(req
, rep
);
2936 mDNSlocal
void queryrecord_termination_callback(request_state
*request
)
2938 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2939 "[R%u] DNSServiceQueryRecord(%X, %d, " PRI_DM_NAME
", " PUB_S
") STOP PID[%d](" PUB_S
")",
2940 request
->request_id
, request
->flags
, request
->interfaceIndex
,
2941 DM_NAME_PARAM(QueryRecordClientRequestGetQName(&request
->u
.queryrecord
)->c
),
2942 DNSTypeName(QueryRecordClientRequestGetType(&request
->u
.queryrecord
)), request
->process_id
, request
->pid_name
);
2944 QueryRecordClientRequestStop(&request
->u
.queryrecord
);
2947 mDNSlocal mStatus
handle_queryrecord_request(request_state
*request
)
2950 DNSServiceFlags flags
;
2951 mDNSu32 interfaceIndex
;
2952 mDNSu16 qtype
, qclass
;
2953 char qname
[MAX_ESCAPED_DOMAIN_NAME
];
2955 flags
= get_flags(&request
->msgptr
, request
->msgend
);
2956 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2957 if (get_string(&request
->msgptr
, request
->msgend
, qname
, sizeof(qname
)) < 0)
2959 err
= mStatus_BadParamErr
;
2962 qtype
= get_uint16(&request
->msgptr
, request
->msgend
);
2963 qclass
= get_uint16(&request
->msgptr
, request
->msgend
);
2965 if (!request
->msgptr
)
2967 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
2968 "[R%d] DNSServiceQueryRecord(unreadable parameters)", request
->request_id
);
2969 err
= mStatus_BadParamErr
;
2973 request
->flags
= flags
;
2974 request
->interfaceIndex
= interfaceIndex
;
2976 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
2977 "[R%d] DNSServiceQueryRecord(%X, %d, " PRI_S
", " PUB_S
") START PID[%d](" PUB_S
")",
2978 request
->request_id
, request
->flags
, request
->interfaceIndex
, qname
, DNSTypeName(qtype
), request
->process_id
,
2981 mDNSPlatformMemZero(&request
->u
.queryrecord
, (mDNSu32
)sizeof(request
->u
.queryrecord
));
2983 err
= QueryRecordClientRequestStart(&request
->u
.queryrecord
, request
->request_id
, qname
, interfaceIndex
, flags
, qtype
,
2984 qclass
, request
->validUUID
? 0 : request
->process_id
, request
->validUUID
? request
->uuid
: mDNSNULL
, request
->uid
,
2985 queryrecord_result_reply
, request
);
2988 request
->terminate
= queryrecord_termination_callback
;
2994 // ***************************************************************************
2995 #if COMPILER_LIKES_PRAGMA_MARK
2997 #pragma mark - DNSServiceEnumerateDomains
3000 mDNSlocal reply_state
*format_enumeration_reply(request_state
*request
,
3001 const char *domain
, DNSServiceFlags flags
, mDNSu32 ifi
, DNSServiceErrorType err
)
3007 len
= sizeof(DNSServiceFlags
);
3008 len
+= sizeof(mDNSu32
);
3009 len
+= sizeof(DNSServiceErrorType
);
3010 len
+= strlen(domain
) + 1;
3012 reply
= create_reply(enumeration_reply_op
, len
, request
);
3013 reply
->rhdr
->flags
= dnssd_htonl(flags
);
3014 reply
->rhdr
->ifi
= dnssd_htonl(ifi
);
3015 reply
->rhdr
->error
= dnssd_htonl(err
);
3016 data
= (char *)&reply
->rhdr
[1];
3017 put_string(domain
, &data
);
3021 mDNSlocal
void enum_termination_callback(request_state
*request
)
3023 // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3024 if (request
->u
.enumeration
.flags
& kDNSServiceFlagsRegistrationDomains
)
3026 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3027 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_REG_QUERY
);
3031 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3032 uDNS_StopWABQueries(&mDNSStorage
, UDNS_WAB_BROWSE_QUERY
| UDNS_WAB_LBROWSE_QUERY
);
3033 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_autoall
);
3035 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3036 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3039 mDNSlocal
void enum_result_callback(mDNS
*const m
,
3040 DNSQuestion
*const question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
3042 char domain
[MAX_ESCAPED_DOMAIN_NAME
];
3043 request_state
*request
= question
->QuestionContext
;
3044 DNSServiceFlags flags
= 0;
3048 if (answer
->rrtype
!= kDNSType_PTR
) return;
3051 if (!AuthorizedDomain(request
, &answer
->rdata
->u
.name
, request
->u
.enumeration
.flags
? AutoRegistrationDomains
: AutoBrowseDomains
)) return;
3054 // We only return add/remove events for the browse and registration lists
3055 // For the default browse and registration answers, we only give an "ADD" event
3056 if (question
== &request
->u
.enumeration
.q_default
&& !AddRecord
) return;
3060 flags
|= kDNSServiceFlagsAdd
;
3061 if (question
== &request
->u
.enumeration
.q_default
) flags
|= kDNSServiceFlagsDefault
;
3064 ConvertDomainNameToCString(&answer
->rdata
->u
.name
, domain
);
3065 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3066 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3067 // network, so we just pass kDNSServiceInterfaceIndexAny
3068 reply
= format_enumeration_reply(request
, domain
, flags
, kDNSServiceInterfaceIndexAny
, kDNSServiceErr_NoError
);
3069 if (!reply
) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3071 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3072 "[R%d->Q%d] DNSServiceEnumerateDomains(%2.*s) RESULT " PUB_S
": " PRI_S
,
3073 request
->request_id
, mDNSVal16(question
->TargetQID
), question
->qname
.c
[0], &question
->qname
.c
[1],
3074 AddRecord
? "ADD" : "RMV", domain
);
3076 append_reply(request
, reply
);
3079 mDNSlocal mStatus
handle_enum_request(request_state
*request
)
3082 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3083 DNSServiceFlags reg
= flags
& kDNSServiceFlagsRegistrationDomains
;
3084 mDNS_DomainType t_all
= reg
? mDNS_DomainTypeRegistration
: mDNS_DomainTypeBrowse
;
3085 mDNS_DomainType t_default
= reg
? mDNS_DomainTypeRegistrationDefault
: mDNS_DomainTypeBrowseDefault
;
3086 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3087 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3088 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3090 if (!request
->msgptr
)
3091 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3093 request
->flags
= flags
;
3094 request
->interfaceIndex
= interfaceIndex
;
3096 // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
3097 request
->u
.enumeration
.flags
= reg
;
3099 // enumeration requires multiple questions, so we must link all the context pointers so that
3100 // necessary context can be reached from the callbacks
3101 request
->u
.enumeration
.q_all
.QuestionContext
= request
;
3102 request
->u
.enumeration
.q_default
.QuestionContext
= request
;
3103 if (!reg
) request
->u
.enumeration
.q_autoall
.QuestionContext
= request
;
3105 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3106 if (!InterfaceID
) InterfaceID
= mDNSInterface_LocalOnly
;
3109 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request
->sd
, flags
,
3110 (flags
& kDNSServiceFlagsBrowseDomains
) ? "kDNSServiceFlagsBrowseDomains" :
3111 (flags
& kDNSServiceFlagsRegistrationDomains
) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3112 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
, t_all
, NULL
, InterfaceID
, enum_result_callback
, request
);
3115 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
, t_default
, NULL
, InterfaceID
, enum_result_callback
, request
);
3116 if (err
) mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3119 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_autoall
, mDNS_DomainTypeBrowseAutomatic
, NULL
, InterfaceID
, enum_result_callback
, request
);
3122 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3123 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3126 if (!err
) request
->terminate
= enum_termination_callback
;
3130 // Start the domain enumeration queries to discover the WAB Browse/Registration domains
3133 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3134 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_REG_QUERY
);
3138 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request
->sd
, request
->process_id
, request
->pid_name
);
3139 uDNS_StartWABQueries(&mDNSStorage
, UDNS_WAB_BROWSE_QUERY
| UDNS_WAB_LBROWSE_QUERY
);
3146 // ***************************************************************************
3147 #if COMPILER_LIKES_PRAGMA_MARK
3149 #pragma mark - DNSServiceReconfirmRecord & Misc
3152 mDNSlocal mStatus
handle_reconfirm_request(request_state
*request
)
3154 mStatus status
= mStatus_BadParamErr
;
3155 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 0, 0);
3158 status
= mDNS_ReconfirmByValue(&mDNSStorage
, &rr
->resrec
);
3160 (status
== mStatus_NoError
) ?
3161 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated PID[%d](%s)" :
3162 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed PID[%d](%s) status %d",
3163 request
->sd
, RRDisplayString(&mDNSStorage
, &rr
->resrec
),
3164 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, rr
->resrec
.InterfaceID
, mDNSfalse
),
3165 request
->process_id
, request
->pid_name
, status
);
3166 freeL("AuthRecord/handle_reconfirm_request", rr
);
3171 #if APPLE_OSX_mDNSResponder
3173 mDNSlocal mStatus
handle_release_request(request_state
*request
)
3176 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
3177 domainname instance
;
3179 // extract the data from the message
3180 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3182 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
3183 get_string(&request
->msgptr
, request
->msgend
, regtype
, sizeof(regtype
)) < 0 ||
3184 get_string(&request
->msgptr
, request
->msgend
, domain
, sizeof(domain
)) < 0)
3186 LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
3187 return(mStatus_BadParamErr
);
3190 if (!request
->msgptr
)
3192 LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request
->sd
);
3193 return(mStatus_BadParamErr
);
3196 if (build_domainname_from_strings(&instance
, name
, regtype
, domain
) < 0)
3198 LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name
, regtype
, domain
);
3199 return(mStatus_BadParamErr
);
3202 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3203 "[R%d] PeerConnectionRelease(%X " PRI_DM_NAME
") START PID[%d](" PUB_S
")",
3204 request
->request_id
, flags
, DM_NAME_PARAM(instance
.c
), request
->process_id
, request
->pid_name
);
3206 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
3207 external_connection_release(&instance
);
3212 #else // APPLE_OSX_mDNSResponder
3214 mDNSlocal mStatus
handle_release_request(request_state
*request
)
3217 return mStatus_UnsupportedErr
;
3220 #endif // APPLE_OSX_mDNSResponder
3222 mDNSlocal mStatus
handle_setdomain_request(request_state
*request
)
3224 char domainstr
[MAX_ESCAPED_DOMAIN_NAME
];
3226 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3227 (void)flags
; // Unused
3228 if (get_string(&request
->msgptr
, request
->msgend
, domainstr
, sizeof(domainstr
)) < 0 ||
3229 !MakeDomainNameFromDNSNameString(&domain
, domainstr
))
3230 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3232 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request
->sd
, domain
.c
);
3233 return(mStatus_NoError
);
3236 typedef packedstruct
3241 } DaemonVersionReply
;
3243 mDNSlocal
void handle_getproperty_request(request_state
*request
)
3245 const mStatus BadParamErr
= dnssd_htonl((mDNSu32
)mStatus_BadParamErr
);
3247 if (get_string(&request
->msgptr
, request
->msgend
, prop
, sizeof(prop
)) >= 0)
3249 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3250 "[R%d] DNSServiceGetProperty(" PUB_S
")", request
->request_id
, prop
);
3251 if (!strcmp(prop
, kDNSServiceProperty_DaemonVersion
))
3253 DaemonVersionReply x
= { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H
) };
3254 send_all(request
->sd
, (const char *)&x
, sizeof(x
));
3259 // If we didn't recogize the requested property name, return BadParamErr
3260 send_all(request
->sd
, (const char *)&BadParamErr
, sizeof(BadParamErr
));
3263 #ifdef APPLE_OSX_mDNSResponder
3264 // The caller can specify either the pid or the uuid. If the pid is not specified,
3265 // update the effective uuid. Don't overwrite the pid which is used for debugging
3266 // purposes and initialized when the socket is opened.
3267 mDNSlocal
void handle_connection_delegate_request(request_state
*request
)
3272 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3273 "[R%d] DNSServiceCreateDelegateConnection START PID[%d](" PUB_S
")",
3274 request
->request_id
, request
->process_id
, request
->pid_name
);
3275 request
->terminate
= connection_termination
;
3278 pid
= get_uint32(&request
->msgptr
, request
->msgend
);
3279 #ifdef LOCAL_PEEREPID
3283 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREPID
, &request
->process_id
, &len
) != 0)
3285 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno
, strerror(errno
));
3288 // to extract the process name from the pid value
3289 if (proc_pidinfo(request
->process_id
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0)
3291 mDNSPlatformStrLCopy(request
->pid_name
, proc
.pbsi_comm
, sizeof(request
->pid_name
));
3292 debugf("handle_connection_delegate_request: process id %d, name %s", request
->process_id
, request
->pid_name
);
3295 #ifdef LOCAL_PEEREUUID
3299 if (getsockopt(request
->sd
, SOL_LOCAL
, LOCAL_PEEREUUID
, request
->uuid
, &len
) != 0)
3301 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno
, strerror(errno
));
3304 request
->validUUID
= mDNStrue
;
3309 mDNSlocal
void handle_connection_delegate_request(request_state
*request
)
3315 typedef packedstruct
3321 // ***************************************************************************
3322 #if COMPILER_LIKES_PRAGMA_MARK
3324 #pragma mark - DNSServiceNATPortMappingCreate
3327 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
3329 mDNSlocal
void port_mapping_termination_callback(request_state
*request
)
3331 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
, "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](" PUB_S
")",
3332 request
->request_id
, DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3333 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
3334 request
->process_id
, request
->pid_name
);
3336 mDNS_StopNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3339 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
3340 mDNSlocal
void port_mapping_create_request_callback(mDNS
*m
, NATTraversalInfo
*n
)
3342 request_state
*request
= (request_state
*)n
->clientContext
;
3347 if (!request
) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
3349 // calculate reply data length
3350 replyLen
= sizeof(DNSServiceFlags
);
3351 replyLen
+= 3 * sizeof(mDNSu32
); // if index + addr + ttl
3352 replyLen
+= sizeof(DNSServiceErrorType
);
3353 replyLen
+= 2 * sizeof(mDNSu16
); // Internal Port + External Port
3354 replyLen
+= sizeof(mDNSu8
); // protocol
3356 rep
= create_reply(port_mapping_reply_op
, replyLen
, request
);
3358 rep
->rhdr
->flags
= dnssd_htonl(0);
3359 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, n
->InterfaceID
, mDNSfalse
));
3360 rep
->rhdr
->error
= dnssd_htonl(n
->Result
);
3362 data
= (char *)&rep
->rhdr
[1];
3364 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[0];
3365 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[1];
3366 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[2];
3367 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[3];
3368 *data
++ = DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
);
3369 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[0];
3370 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[1];
3371 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[0];
3372 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[1];
3373 put_uint32(request
->u
.pm
.NATinfo
.Lifetime
, &data
);
3375 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3376 "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT " PRI_IPv4_ADDR
":%u TTL %u",
3377 request
->request_id
, DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3378 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
3379 &request
->u
.pm
.NATinfo
.ExternalAddress
, mDNSVal16(request
->u
.pm
.NATinfo
.ExternalPort
),
3380 request
->u
.pm
.NATinfo
.Lifetime
);
3382 append_reply(request
, rep
);
3385 mDNSlocal mStatus
handle_port_mapping_request(request_state
*request
)
3388 mStatus err
= mStatus_NoError
;
3390 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3391 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3392 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3393 mDNSu8 protocol
= (mDNSu8
)get_uint32(&request
->msgptr
, request
->msgend
);
3394 (void)flags
; // Unused
3395 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3396 if (request
->msgptr
+ 8 > request
->msgend
) request
->msgptr
= NULL
;
3399 request
->u
.pm
.NATinfo
.IntPort
.b
[0] = *request
->msgptr
++;
3400 request
->u
.pm
.NATinfo
.IntPort
.b
[1] = *request
->msgptr
++;
3401 request
->u
.pm
.ReqExt
.b
[0] = *request
->msgptr
++;
3402 request
->u
.pm
.ReqExt
.b
[1] = *request
->msgptr
++;
3403 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
3406 if (!request
->msgptr
)
3408 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3409 "[R%d] DNSServiceNATPortMappingCreate(unreadable parameters)", request
->request_id
);
3410 return(mStatus_BadParamErr
);
3413 if (protocol
== 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
3415 if (!mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
) || !mDNSIPPortIsZero(request
->u
.pm
.ReqExt
) || ttl
) return(mStatus_BadParamErr
);
3419 if (mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
)) return(mStatus_BadParamErr
);
3420 if (!(protocol
& (kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
))) return(mStatus_BadParamErr
);
3423 request
->flags
= flags
;
3424 request
->interfaceIndex
= interfaceIndex
;
3425 request
->u
.pm
.NATinfo
.Protocol
= !protocol
? NATOp_AddrRequest
: (protocol
== kDNSServiceProtocol_UDP
) ? NATOp_MapUDP
: NATOp_MapTCP
;
3426 // u.pm.NATinfo.IntPort = already set above
3427 request
->u
.pm
.NATinfo
.RequestedPort
= request
->u
.pm
.ReqExt
;
3428 request
->u
.pm
.NATinfo
.NATLease
= ttl
;
3429 request
->u
.pm
.NATinfo
.clientCallback
= port_mapping_create_request_callback
;
3430 request
->u
.pm
.NATinfo
.clientContext
= request
;
3432 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3433 "[R%d] DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](" PUB_S
")",
3434 request
->request_id
, protocol
, mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
),
3435 request
->u
.pm
.NATinfo
.NATLease
, request
->process_id
, request
->pid_name
);
3436 err
= mDNS_StartNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3437 if (err
) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err
);
3438 else request
->terminate
= port_mapping_termination_callback
;
3443 // ***************************************************************************
3444 #if COMPILER_LIKES_PRAGMA_MARK
3446 #pragma mark - DNSServiceGetAddrInfo
3449 mDNSlocal
void addrinfo_termination_callback(request_state
*request
)
3451 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3452 "[R%u] DNSServiceGetAddrInfo(" PRI_DM_NAME
") STOP PID[%d](" PUB_S
")",
3453 request
->request_id
, DM_NAME_PARAM(GetAddrInfoClientRequestGetQName(&request
->u
.addrinfo
)->c
),
3454 request
->process_id
, request
->pid_name
);
3456 GetAddrInfoClientRequestStop(&request
->u
.addrinfo
);
3459 mDNSlocal mStatus
handle_addrinfo_request(request_state
*request
)
3462 DNSServiceFlags flags
;
3463 mDNSu32 interfaceIndex
;
3465 char hostname
[MAX_ESCAPED_DOMAIN_NAME
];
3467 flags
= get_flags(&request
->msgptr
, request
->msgend
);
3468 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3469 protocols
= get_uint32(&request
->msgptr
, request
->msgend
);
3470 if (get_string(&request
->msgptr
, request
->msgend
, hostname
, sizeof(hostname
)) < 0)
3472 err
= mStatus_BadParamErr
;
3475 if (!request
->msgptr
)
3477 LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request
->sd
);
3478 err
= mStatus_BadParamErr
;
3482 request
->flags
= flags
;
3483 request
->interfaceIndex
= interfaceIndex
;
3485 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3486 "[R%u] DNSServiceGetAddrInfo(%X, %d, %u, " PRI_S
") START PID[%d](" PUB_S
")",
3487 request
->request_id
, request
->flags
, request
->interfaceIndex
, protocols
, hostname
, request
->process_id
,
3490 mDNSPlatformMemZero(&request
->u
.addrinfo
, (mDNSu32
)sizeof(request
->u
.addrinfo
));
3492 err
= GetAddrInfoClientRequestStart(&request
->u
.addrinfo
, request
->request_id
, hostname
, interfaceIndex
, flags
,
3493 protocols
, request
->validUUID
? 0 : request
->process_id
, request
->validUUID
? request
->uuid
: mDNSNULL
,
3494 request
->uid
, queryrecord_result_reply
, request
);
3497 request
->terminate
= addrinfo_termination_callback
;
3503 // ***************************************************************************
3504 #if COMPILER_LIKES_PRAGMA_MARK
3506 #pragma mark - Main Request Handler etc.
3509 mDNSlocal request_state
*NewRequest(void)
3511 request_state
*request
;
3512 request_state
**p
= &all_requests
;
3513 request
= (request_state
*) callocL("request_state", sizeof(*request
));
3514 if (!request
) FatalError("ERROR: calloc");
3515 while (*p
) p
= &(*p
)->next
;
3520 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
3521 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
3522 mDNSlocal
void read_msg(request_state
*req
)
3524 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
3526 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3527 "[R%u] ERROR: read_msg called with transfer state terminated or error", req
->request_id
);
3532 if (req
->ts
== t_complete
) // this must be death or something is wrong
3534 char buf
[4]; // dummy for death notification
3535 int nread
= udsSupportReadFD(req
->sd
, buf
, 4, 0, req
->platform_data
);
3536 if (!nread
) { req
->ts
= t_terminated
; return; }
3537 if (nread
< 0) goto rerror
;
3538 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3539 "[R%u] ERROR: read data from a completed request", req
->request_id
);
3544 if (req
->ts
!= t_morecoming
)
3546 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3547 "[R%u] ERROR: read_msg called with invalid transfer state (%d)", req
->request_id
, req
->ts
);
3552 if (req
->hdr_bytes
< sizeof(ipc_msg_hdr
))
3554 mDNSu32 nleft
= sizeof(ipc_msg_hdr
) - req
->hdr_bytes
;
3555 int nread
= udsSupportReadFD(req
->sd
, (char *)&req
->hdr
+ req
->hdr_bytes
, nleft
, 0, req
->platform_data
);
3556 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3557 if (nread
< 0) goto rerror
;
3558 req
->hdr_bytes
+= nread
;
3559 if (req
->hdr_bytes
> sizeof(ipc_msg_hdr
))
3561 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3562 "[R%u] ERROR: read_msg - read too many header bytes", req
->request_id
);
3567 // only read data if header is complete
3568 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
))
3570 ConvertHeaderBytes(&req
->hdr
);
3571 if (req
->hdr
.version
!= VERSION
)
3573 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3574 "[R%u] ERROR: client version 0x%08X daemon version 0x%08X", req
->request_id
, req
->hdr
.version
, VERSION
);
3579 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
3580 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
3581 // for other overhead, this means any message above 70kB is definitely bogus.
3582 if (req
->hdr
.datalen
> 70000)
3584 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3585 "[R%u] ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req
->request_id
, req
->hdr
.datalen
, req
->hdr
.datalen
);
3589 req
->msgbuf
= (char *) callocL("request_state msgbuf", req
->hdr
.datalen
+ MSG_PAD_BYTES
);
3590 if (!req
->msgbuf
) { my_perror("ERROR: calloc"); req
->ts
= t_error
; return; }
3591 req
->msgptr
= req
->msgbuf
;
3592 req
->msgend
= req
->msgbuf
+ req
->hdr
.datalen
;
3596 // If our header is complete, but we're still needing more body data, then try to read it now
3597 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
3598 // Any time we need to get the error return socket we know we'll have at least one data byte
3599 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
3600 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
< req
->hdr
.datalen
)
3602 mDNSu32 nleft
= req
->hdr
.datalen
- req
->data_bytes
;
3604 #if !defined(_WIN32)
3605 struct iovec vec
= { req
->msgbuf
+ req
->data_bytes
, nleft
}; // Tell recvmsg where we want the bytes put
3607 struct cmsghdr
*cmsg
;
3608 char cbuf
[CMSG_SPACE(4 * sizeof(dnssd_sock_t
))];
3610 msg
.msg_namelen
= 0;
3613 msg
.msg_control
= cbuf
;
3614 msg
.msg_controllen
= sizeof(cbuf
);
3616 nread
= recvmsg(req
->sd
, &msg
, 0);
3618 nread
= udsSupportReadFD(req
->sd
, (char *)req
->msgbuf
+ req
->data_bytes
, nleft
, 0, req
->platform_data
);
3620 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3621 if (nread
< 0) goto rerror
;
3622 req
->data_bytes
+= nread
;
3623 if (req
->data_bytes
> req
->hdr
.datalen
)
3625 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3626 "[R%u] ERROR: read_msg - read too many data bytes", req
->request_id
);
3630 #if !defined(_WIN32)
3631 cmsg
= CMSG_FIRSTHDR(&msg
);
3632 #if DEBUG_64BIT_SCM_RIGHTS
3633 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3634 "[R%u] Expecting %d %d %d %d", req
->request_id
, sizeof(cbuf
), sizeof(cbuf
), SOL_SOCKET
, SCM_RIGHTS
);
3635 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3636 "[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);
3637 #endif // DEBUG_64BIT_SCM_RIGHTS
3638 if (cmsg
&& cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
== SCM_RIGHTS
)
3640 #if APPLE_OSX_mDNSResponder
3641 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3642 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3643 // and it's convenient to repurpose the existing fd-passing code here for that task
3644 if (req
->hdr
.op
== send_bpf
)
3646 dnssd_sock_t x
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3647 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3648 "[R%u] Got len %d, BPF %d", req
->request_id
, cmsg
->cmsg_len
, x
);
3649 mDNSPlatformReceiveBPF_fd(x
);
3652 #endif // APPLE_OSX_mDNSResponder
3653 req
->errsd
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3654 #if DEBUG_64BIT_SCM_RIGHTS
3655 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEFAULT
,
3656 "[R%u] read req->errsd %d", req
->request_id
, req
->errsd
);
3657 #endif // DEBUG_64BIT_SCM_RIGHTS
3658 if (req
->data_bytes
< req
->hdr
.datalen
)
3660 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_DEBUG
,
3661 "[R%u] Client(PID [%d](" PUB_S
")) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3662 req
->request_id
, req
->process_id
, req
->pid_name
, req
->errsd
, req
->data_bytes
, req
->hdr
.datalen
);
3670 // If our header and data are both complete, see if we need to make our separate error return socket
3671 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
== req
->hdr
.datalen
)
3673 if (req
->terminate
&& req
->hdr
.op
!= cancel_request
)
3675 dnssd_sockaddr_t cliaddr
;
3676 #if defined(USE_TCP_LOOPBACK)
3679 port
.b
[0] = req
->msgptr
[0];
3680 port
.b
[1] = req
->msgptr
[1];
3682 cliaddr
.sin_family
= AF_INET
;
3683 cliaddr
.sin_port
= port
.NotAnInteger
;
3684 cliaddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3686 char ctrl_path
[MAX_CTLPATH
];
3687 get_string(&req
->msgptr
, req
->msgend
, ctrl_path
, MAX_CTLPATH
); // path is first element in message buffer
3688 mDNSPlatformMemZero(&cliaddr
, sizeof(cliaddr
));
3689 cliaddr
.sun_family
= AF_LOCAL
;
3690 mDNSPlatformStrLCopy(cliaddr
.sun_path
, ctrl_path
, sizeof(cliaddr
.sun_path
));
3691 // If the error return path UDS name is empty string, that tells us
3692 // that this is a new version of the library that's going to pass us
3693 // the error return path socket via sendmsg/recvmsg
3694 if (ctrl_path
[0] == 0)
3696 if (req
->errsd
== req
->sd
)
3698 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3699 "[R%u] read_msg: ERROR failed to get errsd via SCM_RIGHTS", req
->request_id
);
3707 req
->errsd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3708 if (!dnssd_SocketValid(req
->errsd
))
3710 my_throttled_perror("ERROR: socket");
3715 if (connect(req
->errsd
, (struct sockaddr
*)&cliaddr
, sizeof(cliaddr
)) < 0)
3717 #if !defined(USE_TCP_LOOPBACK)
3719 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3720 "[R%u] read_msg: Couldn't connect to error return path socket " PUB_S
" errno %d (" PUB_S
")",
3721 req
->request_id
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3722 if (stat(cliaddr
.sun_path
, &sb
) < 0)
3724 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3725 "[R%u] read_msg: stat failed " PUB_S
" errno %d (" PUB_S
")",
3726 req
->request_id
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3730 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3731 "[R%u] read_msg: file " PUB_S
" mode %o (octal) uid %d gid %d",
3732 req
->request_id
, cliaddr
.sun_path
, sb
.st_mode
, sb
.st_uid
, sb
.st_gid
);
3739 #if !defined(USE_TCP_LOOPBACK)
3744 if (ioctlsocket(req
->errsd
, FIONBIO
, &opt
) != 0)
3746 if (fcntl(req
->errsd
, F_SETFL
, fcntl(req
->errsd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3749 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3750 "[R%u] ERROR: could not set control socket to non-blocking mode errno %d (" PUB_S
")",
3751 req
->request_id
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3757 req
->ts
= t_complete
;
3763 if (dnssd_errno
== dnssd_EWOULDBLOCK
|| dnssd_errno
== dnssd_EINTR
) return;
3764 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_ERROR
,
3765 "[R%u] ERROR: read_msg errno %d (" PUB_S
")", req
->request_id
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3769 mDNSlocal mStatus
handle_client_request(request_state
*req
)
3771 mStatus err
= mStatus_NoError
;
3774 // These are all operations that have their own first-class request_state object
3775 case connection_request
:
3776 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3777 "[R%d] DNSServiceCreateConnection START PID[%d](" PUB_S
")",
3778 req
->request_id
, req
->process_id
, req
->pid_name
);
3779 req
->terminate
= connection_termination
;
3781 case connection_delegate_request
:
3782 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
3783 "[R%d] DNSServiceCreateDelegateConnection START PID[%d](" PRI_S
")",
3784 req
->request_id
, req
->process_id
, req
->pid_name
);
3785 req
->terminate
= connection_termination
;
3786 handle_connection_delegate_request(req
);
3788 case resolve_request
: err
= handle_resolve_request (req
); break;
3789 case query_request
: err
= handle_queryrecord_request (req
); break;
3790 case browse_request
: err
= handle_browse_request (req
); break;
3791 case reg_service_request
: err
= handle_regservice_request (req
); break;
3792 case enumeration_request
: err
= handle_enum_request (req
); break;
3793 case reconfirm_record_request
: err
= handle_reconfirm_request (req
); break;
3794 case setdomain_request
: err
= handle_setdomain_request (req
); break;
3795 case getproperty_request
: handle_getproperty_request (req
); break;
3796 case port_mapping_request
: err
= handle_port_mapping_request(req
); break;
3797 case addrinfo_request
: err
= handle_addrinfo_request (req
); break;
3798 case send_bpf
: /* Do nothing for send_bpf */ break;
3800 // These are all operations that work with an existing request_state object
3801 case reg_record_request
: err
= handle_regrecord_request (req
); break;
3802 case add_record_request
: err
= handle_add_request (req
); break;
3803 case update_record_request
: err
= handle_update_request (req
); break;
3804 case remove_record_request
: err
= handle_removerecord_request(req
); break;
3805 case cancel_request
: handle_cancel_request (req
); break;
3806 case release_request
: err
= handle_release_request (req
); break;
3807 default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
3808 req
->sd
, req
->hdr
.op
, req
->process_id
, req
->pid_name
);
3809 err
= mStatus_BadParamErr
;
3816 #define RecordOrientedOp(X) \
3817 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3819 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3820 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3822 mDNSlocal
void request_callback(int fd
, void *info
)
3825 request_state
*req
= info
;
3826 mDNSs32 min_size
= sizeof(DNSServiceFlags
);
3832 if (req
->ts
== t_morecoming
)
3834 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
3836 AbortUnlinkAndFree(req
);
3839 if (req
->ts
!= t_complete
)
3841 LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req
->ts
, req
->process_id
, req
->pid_name
);
3842 AbortUnlinkAndFree(req
);
3846 switch(req
->hdr
.op
) // Interface + other data
3848 case connection_request
: min_size
= 0; break;
3849 case connection_delegate_request
: min_size
= 4; /* pid */ break;
3850 case reg_service_request
: min_size
+= sizeof(mDNSu32
) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3851 case add_record_request
: min_size
+= 4 /* type, rdlen */ + 4 /* ttl */; break;
3852 case update_record_request
: min_size
+= 2 /* rdlen */ + 4 /* ttl */; break;
3853 case remove_record_request
: break;
3854 case browse_request
: min_size
+= sizeof(mDNSu32
) + 2 /* type, domain */; break;
3855 case resolve_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
3856 case query_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 4 /* type, class*/; break;
3857 case enumeration_request
: min_size
+= sizeof(mDNSu32
); break;
3858 case reg_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
3859 case reconfirm_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */; break;
3860 case setdomain_request
: min_size
+= 1 /* domain */; break;
3861 case getproperty_request
: min_size
= 2; break;
3862 case port_mapping_request
: min_size
+= sizeof(mDNSu32
) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
3863 case addrinfo_request
: min_size
+= sizeof(mDNSu32
) + 4 /* v4/v6 */ + 1 /* hostname */; break;
3864 case send_bpf
: // Same as cancel_request below
3865 case cancel_request
: min_size
= 0; break;
3866 case release_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
3867 default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
3868 req
->hdr
.op
, req
->process_id
, req
->pid_name
);
3869 min_size
= -1; break;
3872 if ((mDNSs32
)req
->data_bytes
< min_size
)
3874 LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
3875 req
->data_bytes
, req
->hdr
.op
, min_size
, req
->process_id
, req
->pid_name
);
3876 AbortUnlinkAndFree(req
);
3879 if (LightweightOp(req
->hdr
.op
) && !req
->terminate
)
3881 LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
3882 req
->hdr
.op
, req
->process_id
, req
->pid_name
);
3883 AbortUnlinkAndFree(req
);
3887 // If req->terminate is already set, this means this operation is sharing an existing connection
3888 if (req
->terminate
&& !LightweightOp(req
->hdr
.op
))
3890 request_state
*newreq
= NewRequest();
3891 newreq
->primary
= req
;
3892 newreq
->sd
= req
->sd
;
3893 newreq
->errsd
= req
->errsd
;
3894 newreq
->uid
= req
->uid
;
3895 newreq
->hdr
= req
->hdr
;
3896 newreq
->msgbuf
= req
->msgbuf
;
3897 newreq
->msgptr
= req
->msgptr
;
3898 newreq
->msgend
= req
->msgend
;
3899 newreq
->request_id
= mDNSStorage
.next_request_id
++;
3900 // if the parent request is a delegate connection, copy the
3904 newreq
->validUUID
= mDNStrue
;
3905 mDNSPlatformMemCopy(newreq
->uuid
, req
->uuid
, UUID_SIZE
);
3909 if (req
->process_id
)
3911 newreq
->process_id
= req
->process_id
;
3912 mDNSPlatformStrLCopy(newreq
->pid_name
, req
->pid_name
, (mDNSu32
)sizeof(newreq
->pid_name
));
3916 set_peer_pid(newreq
);
3922 // Check if the request wants no asynchronous replies.
3923 if (req
->hdr
.ipc_flags
& IPC_FLAGS_NOREPLY
) req
->no_reply
= 1;
3925 // If we're shutting down, don't allow new client requests
3926 // We do allow "cancel" and "getproperty" during shutdown
3927 if (mDNSStorage
.ShutdownTime
&& req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
)
3928 err
= mStatus_ServiceNotRunning
;
3930 err
= handle_client_request(req
);
3932 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3933 if (req
->msgbuf
) freeL("request_state msgbuf", req
->msgbuf
);
3935 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3936 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3937 if (req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
&& req
->hdr
.op
!= send_bpf
&& req
->hdr
.op
!= getpid_request
)
3939 const mStatus err_netorder
= dnssd_htonl(err
);
3940 send_all(req
->errsd
, (const char *)&err_netorder
, sizeof(err_netorder
));
3941 if (req
->errsd
!= req
->sd
)
3943 dnssd_close(req
->errsd
);
3944 req
->errsd
= req
->sd
;
3945 // Also need to reset the parent's errsd, if this is a subordinate operation
3946 if (req
->primary
) req
->primary
->errsd
= req
->primary
->sd
;
3950 // Reset ready to accept the next req on this pipe
3951 if (req
->primary
) req
= req
->primary
;
3952 req
->ts
= t_morecoming
;
3954 req
->data_bytes
= 0;
3955 req
->msgbuf
= mDNSNULL
;
3956 req
->msgptr
= mDNSNULL
;
3961 mDNSlocal
void connect_callback(int fd
, void *info
)
3963 dnssd_sockaddr_t cliaddr
;
3964 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(cliaddr
);
3965 dnssd_sock_t sd
= accept(fd
, (struct sockaddr
*) &cliaddr
, &len
);
3966 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3967 unsigned long optval
= 1;
3970 (void)info
; // Unused
3972 if (!dnssd_SocketValid(sd
))
3974 if (dnssd_errno
!= dnssd_EWOULDBLOCK
)
3975 my_throttled_perror("ERROR: accept");
3980 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3981 if (setsockopt(sd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
3982 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3986 if (ioctlsocket(sd
, FIONBIO
, &optval
) != 0)
3988 if (fcntl(sd
, F_SETFL
, fcntl(sd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3991 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3997 request_state
*request
= NewRequest();
3998 request
->ts
= t_morecoming
;
4000 request
->errsd
= sd
;
4001 request
->request_id
= mDNSStorage
.next_request_id
++;
4002 set_peer_pid(request
);
4003 #if APPLE_OSX_mDNSResponder
4005 socklen_t xucredlen
= sizeof(x
);
4006 if (getsockopt(sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 && x
.cr_version
== XUCRED_VERSION
)
4007 request
->uid
= x
.cr_uid
; // save the effective userid of the client
4009 my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
4011 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen
, x
.cr_version
, x
.cr_uid
, x
.cr_ngroups
);
4012 #endif // APPLE_OSX_mDNSResponder
4013 LogDebug("%3d: connect_callback: Adding FD for uid %u", request
->sd
, request
->uid
);
4014 udsSupportAddFDToEventLoop(sd
, request_callback
, request
, &request
->platform_data
);
4018 mDNSlocal mDNSBool
uds_socket_setup(dnssd_sock_t skt
)
4020 #if defined(SO_NP_EXTENSIONS)
4021 struct so_np_extensions sonpx
;
4022 socklen_t optlen
= sizeof(struct so_np_extensions
);
4023 sonpx
.npx_flags
= SONPX_SETOPTSHUT
;
4024 sonpx
.npx_mask
= SONPX_SETOPTSHUT
;
4025 if (setsockopt(skt
, SOL_SOCKET
, SO_NP_EXTENSIONS
, &sonpx
, optlen
) < 0)
4026 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
4029 // SEH: do we even need to do this on windows?
4030 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
4032 if (ioctlsocket(skt
, FIONBIO
, &opt
) != 0)
4034 if (fcntl(skt
, F_SETFL
, fcntl(skt
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
4037 my_perror("ERROR: could not set listen socket to non-blocking mode");
4041 if (listen(skt
, LISTENQ
) != 0)
4043 my_perror("ERROR: could not listen on listen socket");
4047 if (mStatus_NoError
!= udsSupportAddFDToEventLoop(skt
, connect_callback
, (void *) NULL
, (void **) NULL
))
4049 my_perror("ERROR: could not add listen socket to event loop");
4054 LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt
);
4055 mDNSStorage
.uds_listener_skt
= skt
;
4060 #if MDNS_MALLOC_DEBUGGING
4061 mDNSlocal
void udsserver_validatelists(void *context
);
4064 mDNSexport
int udsserver_init(dnssd_sock_t skts
[], mDNSu32 count
)
4066 dnssd_sockaddr_t laddr
;
4071 FILE *fp
= fopen(PID_FILE
, "w");
4074 fprintf(fp
, "%d\n", getpid());
4079 #if MDNS_MALLOC_DEBUGGING
4080 static mDNSListValidator validator
;
4081 mDNSPlatformAddListValidator(&validator
, udsserver_validatelists
, "udsserver_validatelists", NULL
);
4086 for (i
= 0; i
< count
; i
++)
4087 if (dnssd_SocketValid(skts
[i
]) && !uds_socket_setup(skts
[i
]))
4092 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
4093 if (!dnssd_SocketValid(listenfd
))
4095 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
4099 mDNSPlatformMemZero(&laddr
, sizeof(laddr
));
4101 #if defined(USE_TCP_LOOPBACK)
4103 laddr
.sin_family
= AF_INET
;
4104 laddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
4105 laddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
4106 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
4109 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4115 mode_t mask
= umask(0);
4116 unlink(boundPath
); // OK if this fails
4117 laddr
.sun_family
= AF_LOCAL
;
4118 #ifndef NOT_HAVE_SA_LEN
4119 // According to Stevens (section 3.2), there is no portable way to
4120 // determine whether sa_len is defined on a particular platform.
4121 laddr
.sun_len
= sizeof(struct sockaddr_un
);
4123 if (strlen(boundPath
) >= sizeof(laddr
.sun_path
))
4125 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr
.sun_path
));
4128 mDNSPlatformStrLCopy(laddr
.sun_path
, boundPath
, sizeof(laddr
.sun_path
));
4129 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
4133 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4139 if (!uds_socket_setup(listenfd
)) goto error
;
4142 #if !defined(PLATFORM_NO_RLIMIT)
4144 // Set maximum number of open file descriptors
4145 #define MIN_OPENFILES 10240
4146 struct rlimit maxfds
, newfds
;
4148 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
4149 // you have to get and set rlimits once before getrlimit will return sensible values
4150 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4151 if (setrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4153 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4154 newfds
.rlim_max
= (maxfds
.rlim_max
> MIN_OPENFILES
) ? maxfds
.rlim_max
: MIN_OPENFILES
;
4155 newfds
.rlim_cur
= (maxfds
.rlim_cur
> MIN_OPENFILES
) ? maxfds
.rlim_cur
: MIN_OPENFILES
;
4156 if (newfds
.rlim_max
!= maxfds
.rlim_max
|| newfds
.rlim_cur
!= maxfds
.rlim_cur
)
4157 if (setrlimit(RLIMIT_NOFILE
, &newfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4159 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4160 debugf("maxfds.rlim_max %d", (long)maxfds
.rlim_max
);
4161 debugf("maxfds.rlim_cur %d", (long)maxfds
.rlim_cur
);
4165 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
4166 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
4167 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
4168 mDNS_GetDomains(&mDNSStorage
, &mDNSStorage
.AutomaticBrowseDomainQ
, mDNS_DomainTypeBrowseAutomatic
,
4169 mDNSNULL
, mDNSInterface_LocalOnly
, AutomaticBrowseDomainChange
, mDNSNULL
);
4171 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
4172 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeRegistration
);
4173 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeBrowse
);
4174 AddAutoBrowseDomain(0, &localdomain
);
4176 udsserver_handle_configchange(&mDNSStorage
);
4181 my_perror("ERROR: udsserver_init");
4185 mDNSexport
int udsserver_exit(void)
4187 // Cancel all outstanding client requests
4188 while (all_requests
) AbortUnlinkAndFree(all_requests
);
4190 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
4191 // created in udsserver_init, and others we created as a result of reading local configuration data
4192 while (LocalDomainEnumRecords
)
4194 ARListElem
*rem
= LocalDomainEnumRecords
;
4195 LocalDomainEnumRecords
= LocalDomainEnumRecords
->next
;
4196 mDNS_Deregister(&mDNSStorage
, &rem
->ar
);
4199 // If the launching environment created no listening socket,
4200 // that means we created it ourselves, so we should clean it up on exit
4201 if (dnssd_SocketValid(listenfd
))
4203 dnssd_close(listenfd
);
4204 #if !defined(USE_TCP_LOOPBACK)
4205 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
4206 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
4207 // It would be nice if we could find a solution to this problem
4208 if (unlink(boundPath
))
4209 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH
);
4220 mDNSlocal
void LogClientInfoToFD(int fd
, request_state
*req
)
4225 mDNS_snprintf(reqIDStr
, sizeof(reqIDStr
), "[R%u]", req
->request_id
);
4227 mDNS_snprintf(prefix
, sizeof(prefix
), "%-6s %2s", reqIDStr
, req
->primary
? "->" : "");
4229 if (!req
->terminate
)
4230 LogToFD(fd
, "%s No operation yet on this socket", prefix
);
4231 else if (req
->terminate
== connection_termination
)
4233 int num_records
= 0, num_ops
= 0;
4234 const registered_record_entry
*p
;
4236 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
) num_records
++;
4237 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) num_ops
++;
4238 LogToFD(fd
, "%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
4239 prefix
, num_records
, num_records
!= 1 ? "s" : "", num_ops
, num_ops
!= 1 ? "s" : "",
4240 req
->process_id
, req
->pid_name
);
4241 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4242 LogToFD(fd
, " -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
4243 req
->flags
, req
->interfaceIndex
, p
->key
, ARDisplayString(&mDNSStorage
, p
->rr
), req
->process_id
, req
->pid_name
);
4244 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) LogClientInfoToFD(fd
, r
);
4246 else if (req
->terminate
== regservice_termination_callback
)
4248 service_instance
*ptr
;
4249 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4250 LogToFD(fd
, "%-9s DNSServiceRegister 0x%08X %2d %##s %u/%u PID[%d](%s)",
4251 (ptr
== req
->u
.servicereg
.instances
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, ptr
->srs
.RR_SRV
.resrec
.name
->c
,
4252 mDNSVal16(req
->u
.servicereg
.port
),
4253 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
);
4255 else if (req
->terminate
== browse_termination_callback
)
4258 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4259 LogToFD(fd
, "%-9s DNSServiceBrowse 0x%08X %2d %##s PID[%d](%s)",
4260 (blist
== req
->u
.browser
.browsers
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, blist
->q
.qname
.c
,
4261 req
->process_id
, req
->pid_name
);
4263 else if (req
->terminate
== resolve_termination_callback
)
4264 LogToFD(fd
, "%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
4265 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.resolve
.qsrv
.qname
.c
, req
->process_id
, req
->pid_name
);
4266 else if (req
->terminate
== queryrecord_termination_callback
)
4267 LogToFD(fd
, "%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
4268 prefix
, req
->flags
, req
->interfaceIndex
, QueryRecordClientRequestGetQName(&req
->u
.queryrecord
), DNSTypeName(QueryRecordClientRequestGetType(&req
->u
.queryrecord
)), req
->process_id
, req
->pid_name
);
4269 else if (req
->terminate
== enum_termination_callback
)
4270 LogToFD(fd
, "%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
4271 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.enumeration
.q_all
.qname
.c
, req
->process_id
, req
->pid_name
);
4272 else if (req
->terminate
== port_mapping_termination_callback
)
4273 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)",
4276 req
->interfaceIndex
,
4277 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
4278 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
4279 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
4280 mDNSVal16(req
->u
.pm
.ReqExt
),
4281 &req
->u
.pm
.NATinfo
.ExternalAddress
,
4282 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
4283 req
->u
.pm
.NATinfo
.NATLease
,
4284 req
->u
.pm
.NATinfo
.Lifetime
,
4285 req
->process_id
, req
->pid_name
);
4286 else if (req
->terminate
== addrinfo_termination_callback
)
4287 LogToFD(fd
, "%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
4288 prefix
, req
->flags
, req
->interfaceIndex
,
4289 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4290 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4291 GetAddrInfoClientRequestGetQName(&req
->u
.addrinfo
), req
->process_id
, req
->pid_name
);
4293 LogToFD(fd
, "%s Unrecognized operation %p", prefix
, req
->terminate
);
4296 mDNSlocal
void LogClientInfo(request_state
*req
)
4301 mDNS_snprintf(reqIDStr
, sizeof(reqIDStr
), "[R%u]", req
->request_id
);
4303 mDNS_snprintf(prefix
, sizeof(prefix
), "%-6s %2s", reqIDStr
, req
->primary
? "->" : "");
4305 if (!req
->terminate
)
4306 LogMsgNoIdent("%s No operation yet on this socket", prefix
);
4307 else if (req
->terminate
== connection_termination
)
4309 int num_records
= 0, num_ops
= 0;
4310 const registered_record_entry
*p
;
4312 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
) num_records
++;
4313 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) num_ops
++;
4314 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
4315 prefix
, num_records
, num_records
!= 1 ? "s" : "", num_ops
, num_ops
!= 1 ? "s" : "",
4316 req
->process_id
, req
->pid_name
);
4317 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4318 LogMsgNoIdent(" -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
4319 req
->flags
, req
->interfaceIndex
, p
->key
, ARDisplayString(&mDNSStorage
, p
->rr
), req
->process_id
, req
->pid_name
);
4320 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) LogClientInfo(r
);
4322 else if (req
->terminate
== regservice_termination_callback
)
4324 service_instance
*ptr
;
4325 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4326 LogMsgNoIdent("%-9s DNSServiceRegister 0x%08X %2d %##s %u/%u PID[%d](%s)",
4327 (ptr
== req
->u
.servicereg
.instances
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, ptr
->srs
.RR_SRV
.resrec
.name
->c
,
4328 mDNSVal16(req
->u
.servicereg
.port
),
4329 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
);
4331 else if (req
->terminate
== browse_termination_callback
)
4334 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4335 LogMsgNoIdent("%-9s DNSServiceBrowse 0x%08X %2d %##s PID[%d](%s)",
4336 (blist
== req
->u
.browser
.browsers
) ? prefix
: "", req
->flags
, req
->interfaceIndex
, blist
->q
.qname
.c
,
4337 req
->process_id
, req
->pid_name
);
4339 else if (req
->terminate
== resolve_termination_callback
)
4340 LogMsgNoIdent("%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
4341 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.resolve
.qsrv
.qname
.c
, req
->process_id
, req
->pid_name
);
4342 else if (req
->terminate
== queryrecord_termination_callback
)
4343 LogMsgNoIdent("%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
4344 prefix
, req
->flags
, req
->interfaceIndex
, QueryRecordClientRequestGetQName(&req
->u
.queryrecord
), DNSTypeName(QueryRecordClientRequestGetType(&req
->u
.queryrecord
)), req
->process_id
, req
->pid_name
);
4345 else if (req
->terminate
== enum_termination_callback
)
4346 LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
4347 prefix
, req
->flags
, req
->interfaceIndex
, req
->u
.enumeration
.q_all
.qname
.c
, req
->process_id
, req
->pid_name
);
4348 else if (req
->terminate
== port_mapping_termination_callback
)
4349 LogMsgNoIdent("%s DNSServiceNATPortMapping 0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
4352 req
->interfaceIndex
,
4353 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
4354 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
4355 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
4356 mDNSVal16(req
->u
.pm
.ReqExt
),
4357 &req
->u
.pm
.NATinfo
.ExternalAddress
,
4358 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
4359 req
->u
.pm
.NATinfo
.NATLease
,
4360 req
->u
.pm
.NATinfo
.Lifetime
,
4361 req
->process_id
, req
->pid_name
);
4362 else if (req
->terminate
== addrinfo_termination_callback
)
4363 LogMsgNoIdent("%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
4364 prefix
, req
->flags
, req
->interfaceIndex
,
4365 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4366 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4367 GetAddrInfoClientRequestGetQName(&req
->u
.addrinfo
), req
->process_id
, req
->pid_name
);
4369 LogMsgNoIdent("%s Unrecognized operation %p", prefix
, req
->terminate
);
4372 mDNSlocal
void GetMcastClients(request_state
*req
)
4374 if (req
->terminate
== connection_termination
)
4376 int num_records
= 0, num_ops
= 0;
4377 const registered_record_entry
*p
;
4379 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4381 for (r
= req
->next
; r
; r
=r
->next
)
4382 if (r
->primary
== req
)
4384 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4386 if (!AuthRecord_uDNS(p
->rr
))
4389 for (r
= req
->next
; r
; r
=r
->next
)
4390 if (r
->primary
== req
)
4393 else if (req
->terminate
== regservice_termination_callback
)
4395 service_instance
*ptr
;
4396 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4398 if (!AuthRecord_uDNS(&ptr
->srs
.RR_SRV
))
4402 else if (req
->terminate
== browse_termination_callback
)
4405 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4407 if (mDNSOpaque16IsZero(blist
->q
.TargetQID
))
4411 else if (req
->terminate
== resolve_termination_callback
)
4413 if ((mDNSOpaque16IsZero(req
->u
.resolve
.qsrv
.TargetQID
)) && (req
->u
.resolve
.qsrv
.ThisQInterval
> 0))
4416 else if (req
->terminate
== queryrecord_termination_callback
)
4418 if (QueryRecordClientRequestIsMulticast(&req
->u
.queryrecord
))
4421 else if (req
->terminate
== addrinfo_termination_callback
)
4423 if (GetAddrInfoClientRequestIsMulticast(&req
->u
.addrinfo
))
4433 mDNSlocal
void LogMcastClientInfo(request_state
*req
)
4435 if (!req
->terminate
)
4436 LogMcastNoIdent("No operation yet on this socket");
4437 else if (req
->terminate
== connection_termination
)
4439 int num_records
= 0, num_ops
= 0;
4440 const registered_record_entry
*p
;
4442 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4444 for (r
= req
->next
; r
; r
=r
->next
)
4445 if (r
->primary
== req
)
4447 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4449 if (!AuthRecord_uDNS(p
->rr
))
4450 LogMcastNoIdent("R: -> DNSServiceRegisterRecord: %##s %s PID[%d](%s)", p
->rr
->resrec
.name
->c
,
4451 DNSTypeName(p
->rr
->resrec
.rrtype
), req
->process_id
, req
->pid_name
, i_mcount
++);
4453 for (r
= req
->next
; r
; r
=r
->next
)
4454 if (r
->primary
== req
)
4455 LogMcastClientInfo(r
);
4457 else if (req
->terminate
== regservice_termination_callback
)
4459 service_instance
*ptr
;
4460 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4462 if (!AuthRecord_uDNS(&ptr
->srs
.RR_SRV
))
4463 LogMcastNoIdent("R: DNSServiceRegister: %##s %u/%u PID[%d](%s)", ptr
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(req
->u
.servicereg
.port
),
4464 SRS_PORT(&ptr
->srs
), req
->process_id
, req
->pid_name
, i_mcount
++);
4467 else if (req
->terminate
== browse_termination_callback
)
4470 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4472 if (mDNSOpaque16IsZero(blist
->q
.TargetQID
))
4473 LogMcastNoIdent("Q: DNSServiceBrowse %##s %s PID[%d](%s)", blist
->q
.qname
.c
, DNSTypeName(blist
->q
.qtype
),
4474 req
->process_id
, req
->pid_name
, i_mcount
++);
4477 else if (req
->terminate
== resolve_termination_callback
)
4479 if ((mDNSOpaque16IsZero(req
->u
.resolve
.qsrv
.TargetQID
)) && (req
->u
.resolve
.qsrv
.ThisQInterval
> 0))
4480 LogMcastNoIdent("Q: DNSServiceResolve %##s %s PID[%d](%s)", req
->u
.resolve
.qsrv
.qname
.c
, DNSTypeName(req
->u
.resolve
.qsrv
.qtype
),
4481 req
->process_id
, req
->pid_name
, i_mcount
++);
4483 else if (req
->terminate
== queryrecord_termination_callback
)
4485 if (QueryRecordClientRequestIsMulticast(&req
->u
.queryrecord
))
4487 LogMcastNoIdent("Q: DNSServiceQueryRecord %##s %s PID[%d](%s)",
4488 QueryRecordClientRequestGetQName(&req
->u
.queryrecord
),
4489 DNSTypeName(QueryRecordClientRequestGetType(&req
->u
.queryrecord
)),
4490 req
->process_id
, req
->pid_name
, i_mcount
++);
4493 else if (req
->terminate
== addrinfo_termination_callback
)
4495 if (GetAddrInfoClientRequestIsMulticast(&req
->u
.addrinfo
))
4497 LogMcastNoIdent("Q: DNSServiceGetAddrInfo %s%s %##s PID[%d](%s)",
4498 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4499 req
->u
.addrinfo
.protocols
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4500 GetAddrInfoClientRequestGetQName(&req
->u
.addrinfo
), req
->process_id
, req
->pid_name
, i_mcount
++);
4505 mDNSlocal
char *RecordTypeName(mDNSu8 rtype
)
4509 case kDNSRecordTypeUnregistered
: return ("Unregistered ");
4510 case kDNSRecordTypeDeregistering
: return ("Deregistering");
4511 case kDNSRecordTypeUnique
: return ("Unique ");
4512 case kDNSRecordTypeAdvisory
: return ("Advisory ");
4513 case kDNSRecordTypeShared
: return ("Shared ");
4514 case kDNSRecordTypeVerified
: return ("Verified ");
4515 case kDNSRecordTypeKnownUnique
: return ("KnownUnique ");
4516 default: return("Unknown");
4520 mDNSlocal
int LogEtcHostsToFD(int fd
, mDNS
*const m
)
4522 mDNSBool showheader
= mDNStrue
;
4523 const AuthRecord
*ar
;
4528 mDNSBool truncated
= 0;
4530 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4532 if (m
->rrauth
.rrauth_hash
[slot
]) authslot
++;
4533 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4534 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
4536 if (ar
->RecordCallback
!= FreeEtcHosts
) continue;
4537 if (showheader
) { showheader
= mDNSfalse
; LogToFD(fd
, " State Interface"); }
4539 // Print a maximum of 50 records
4540 if (count
++ >= 50) { truncated
= mDNStrue
; continue; }
4541 if (ar
->ARType
== AuthRecordLocalOnly
)
4543 if (ar
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
)
4544 LogToFD(fd
, " %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4547 mDNSu32 scopeid
= (mDNSu32
)(uintptr_t)ar
->resrec
.InterfaceID
;
4548 LogToFD(fd
, " %s %u %s", RecordTypeName(ar
->resrec
.RecordType
), scopeid
, ARDisplayString(m
, ar
));
4554 if (showheader
) LogToFD(fd
, "<None>");
4555 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
);
4559 mDNSlocal
void LogLocalOnlyAuthRecordsToFD(int fd
, mDNS
*const m
)
4561 mDNSBool showheader
= mDNStrue
;
4562 const AuthRecord
*ar
;
4566 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4568 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4569 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
4571 if (ar
->RecordCallback
== FreeEtcHosts
) continue;
4572 if (showheader
) { showheader
= mDNSfalse
; LogToFD(fd
, " State Interface"); }
4574 // Print a maximum of 400 records
4575 if (ar
->ARType
== AuthRecordLocalOnly
)
4576 LogToFD(fd
, " %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4577 else if (ar
->ARType
== AuthRecordP2P
)
4579 if (ar
->resrec
.InterfaceID
== mDNSInterface_BLE
)
4580 LogToFD(fd
, " %s BLE %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4582 LogToFD(fd
, " %s PP %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4587 if (showheader
) LogToFD(fd
, "<None>");
4590 mDNSlocal
void LogOneAuthRecordToFD(int fd
, const AuthRecord
*ar
, mDNSs32 now
, const char *ifname
)
4592 if (AuthRecord_uDNS(ar
))
4594 LogToFD(fd
, "%7d %7d %7d %-7s %4d %s %s",
4595 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4596 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
4597 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
4600 ar
->AllowRemoteQuery
? "☠" : " ",
4601 ARDisplayString(&mDNSStorage
, ar
));
4605 LogToFD(fd
, "%7d %7d %7d %-7s 0x%02X %s %s",
4606 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4607 ar
->AnnounceCount
? (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
: 0,
4608 ar
->TimeExpire
? (ar
->TimeExpire
- now
) / mDNSPlatformOneSecond
: 0,
4609 ifname
? ifname
: "ALL",
4610 ar
->resrec
.RecordType
,
4611 ar
->AllowRemoteQuery
? "☠" : " ",
4612 ARDisplayString(&mDNSStorage
, ar
));
4616 mDNSlocal
void LogAuthRecordsToFD(int fd
,
4617 const mDNSs32 now
, AuthRecord
*ResourceRecords
, int *proxy
)
4619 mDNSBool showheader
= mDNStrue
;
4620 const AuthRecord
*ar
;
4621 OwnerOptData owner
= zeroOwner
;
4622 for (ar
= ResourceRecords
; ar
; ar
=ar
->next
)
4624 const char *const ifname
= InterfaceNameForID(&mDNSStorage
, ar
->resrec
.InterfaceID
);
4625 if ((ar
->WakeUp
.HMAC
.l
[0] != 0) == (proxy
!= mDNSNULL
))
4627 if (showheader
) { showheader
= mDNSfalse
; LogToFD(fd
, " Int Next Expire if State"); }
4628 if (proxy
) (*proxy
)++;
4629 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)))
4632 if (owner
.password
.l
[0])
4633 LogToFD(fd
, "Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
4634 else if (!mDNSSameEthAddress(&owner
.HMAC
, &owner
.IMAC
))
4635 LogToFD(fd
, "Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, owner
.seq
);
4637 LogToFD(fd
, "Proxying for %.6a seq %d", &owner
.HMAC
, owner
.seq
);
4639 if (AuthRecord_uDNS(ar
))
4641 LogOneAuthRecordToFD(fd
, ar
, now
, ifname
);
4643 else if (ar
->ARType
== AuthRecordLocalOnly
)
4645 LogToFD(fd
, " LO %s", ARDisplayString(&mDNSStorage
, ar
));
4647 else if (ar
->ARType
== AuthRecordP2P
)
4649 if (ar
->resrec
.InterfaceID
== mDNSInterface_BLE
)
4650 LogToFD(fd
, " BLE %s", ARDisplayString(&mDNSStorage
, ar
));
4652 LogToFD(fd
, " PP %s", ARDisplayString(&mDNSStorage
, ar
));
4656 LogOneAuthRecordToFD(fd
, ar
, now
, ifname
);
4660 if (showheader
) LogToFD(fd
, "<None>");
4663 mDNSlocal
void PrintOneCacheRecordToFD(int fd
, const CacheRecord
*cr
, mDNSu32 slot
, const mDNSu32 remain
, const char *ifname
, mDNSu32
*CacheUsed
)
4665 LogToFD(fd
, "%3d %s%8d %-7s%s %-6s%s",
4667 cr
->CRActiveQuestion
? "*" : " ",
4669 ifname
? ifname
: "-U-",
4670 (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) ? "-" :
4671 (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ? " " : "+",
4672 DNSTypeName(cr
->resrec
.rrtype
),
4673 CRDisplayString(&mDNSStorage
, cr
));
4677 mDNSlocal
void PrintCachedRecordsToFD(int fd
, const CacheRecord
*cr
, mDNSu32 slot
, const mDNSu32 remain
, const char *ifname
, mDNSu32
*CacheUsed
)
4683 // The records that are cached under the main cache record like nsec, soa don't have
4684 // their own lifetime. If the main cache record expires, they also expire.
4687 PrintOneCacheRecordToFD(fd
, nsec
, slot
, remain
, ifname
, CacheUsed
);
4693 PrintOneCacheRecordToFD(fd
, soa
, slot
, remain
, ifname
, CacheUsed
);
4697 mDNSexport
void LogMDNSStatisticsToFD(int fd
, mDNS
*const m
)
4699 LogToFD(fd
, "--- MDNS Statistics ---");
4701 LogToFD(fd
, "Name Conflicts %u", m
->mDNSStats
.NameConflicts
);
4702 LogToFD(fd
, "KnownUnique Name Conflicts %u", m
->mDNSStats
.KnownUniqueNameConflicts
);
4703 LogToFD(fd
, "Duplicate Query Suppressions %u", m
->mDNSStats
.DupQuerySuppressions
);
4704 LogToFD(fd
, "KA Suppressions %u", m
->mDNSStats
.KnownAnswerSuppressions
);
4705 LogToFD(fd
, "KA Multiple Packets %u", m
->mDNSStats
.KnownAnswerMultiplePkts
);
4706 LogToFD(fd
, "Poof Cache Deletions %u", m
->mDNSStats
.PoofCacheDeletions
);
4707 LogToFD(fd
, "--------------------------------");
4709 LogToFD(fd
, "Multicast packets Sent %u", m
->MulticastPacketsSent
);
4710 LogToFD(fd
, "Multicast packets Received %u", m
->MPktNum
);
4711 LogToFD(fd
, "Remote Subnet packets %u", m
->RemoteSubnet
);
4712 LogToFD(fd
, "QU questions received %u", m
->mDNSStats
.UnicastBitInQueries
);
4713 LogToFD(fd
, "Normal multicast questions %u", m
->mDNSStats
.NormalQueries
);
4714 LogToFD(fd
, "Answers for questions %u", m
->mDNSStats
.MatchingAnswersForQueries
);
4715 LogToFD(fd
, "Unicast responses %u", m
->mDNSStats
.UnicastResponses
);
4716 LogToFD(fd
, "Multicast responses %u", m
->mDNSStats
.MulticastResponses
);
4717 LogToFD(fd
, "Unicast response Demotions %u", m
->mDNSStats
.UnicastDemotedToMulticast
);
4718 LogToFD(fd
, "--------------------------------");
4720 LogToFD(fd
, "Sleeps %u", m
->mDNSStats
.Sleeps
);
4721 LogToFD(fd
, "Wakeups %u", m
->mDNSStats
.Wakes
);
4722 LogToFD(fd
, "Interface UP events %u", m
->mDNSStats
.InterfaceUp
);
4723 LogToFD(fd
, "Interface UP Flap events %u", m
->mDNSStats
.InterfaceUpFlap
);
4724 LogToFD(fd
, "Interface Down events %u", m
->mDNSStats
.InterfaceDown
);
4725 LogToFD(fd
, "Interface DownFlap events %u", m
->mDNSStats
.InterfaceDownFlap
);
4726 LogToFD(fd
, "Cache refresh queries %u", m
->mDNSStats
.CacheRefreshQueries
);
4727 LogToFD(fd
, "Cache refreshed %u", m
->mDNSStats
.CacheRefreshed
);
4728 LogToFD(fd
, "Wakeup on Resolves %u", m
->mDNSStats
.WakeOnResolves
);
4731 mDNSexport
void udsserver_info_dump_to_fd(int fd
)
4733 mDNS
*const m
= &mDNSStorage
;
4734 const mDNSs32 now
= mDNS_TimeNow(m
);
4735 mDNSu32 CacheUsed
= 0, CacheActive
= 0, slot
;
4736 int ProxyA
= 0, ProxyD
= 0;
4737 mDNSu32 groupCount
= 0;
4738 mDNSu32 mcastRecordCount
= 0;
4739 mDNSu32 ucastRecordCount
= 0;
4740 const CacheGroup
*cg
;
4741 const CacheRecord
*cr
;
4742 const DNSQuestion
*q
;
4743 const DNameListElem
*d
;
4744 const SearchListElem
*s
;
4746 LogToFD(fd
, "------------ Cache -------------");
4747 LogToFD(fd
, "Slt Q TTL if U Type rdlen");
4748 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4750 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
4752 groupCount
++; // Count one cache entity for the CacheGroup object
4753 for (cr
= cg
->members
; cr
; cr
=cr
->next
)
4755 const mDNSs32 remain
= cr
->resrec
.rroriginalttl
- (now
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
4757 mDNSInterfaceID InterfaceID
= cr
->resrec
.InterfaceID
;
4758 mDNSu32
*const countPtr
= InterfaceID
? &mcastRecordCount
: &ucastRecordCount
;
4759 if (!InterfaceID
&& cr
->resrec
.rDNSServer
&& cr
->resrec
.rDNSServer
->scopeType
)
4760 InterfaceID
= cr
->resrec
.rDNSServer
->interface
;
4761 ifname
= InterfaceNameForID(m
, InterfaceID
);
4762 if (cr
->CRActiveQuestion
) CacheActive
++;
4763 PrintOneCacheRecordToFD(fd
, cr
, slot
, remain
, ifname
, countPtr
);
4764 PrintCachedRecordsToFD(fd
, cr
, slot
, remain
, ifname
, countPtr
);
4769 CacheUsed
= groupCount
+ mcastRecordCount
+ ucastRecordCount
;
4770 if (m
->rrcache_totalused
!= CacheUsed
)
4771 LogToFD(fd
, "Cache use mismatch: rrcache_totalused is %lu, true count %lu", m
->rrcache_totalused
, CacheUsed
);
4772 if (m
->rrcache_active
!= CacheActive
)
4773 LogToFD(fd
, "Cache use mismatch: rrcache_active is %lu, true count %lu", m
->rrcache_active
, CacheActive
);
4774 LogToFD(fd
, "Cache size %u entities; %u in use (%u group, %u multicast, %u unicast); %u referenced by active questions",
4775 m
->rrcache_size
, CacheUsed
, groupCount
, mcastRecordCount
, ucastRecordCount
, CacheActive
);
4777 LogToFD(fd
, "--------- Auth Records ---------");
4778 LogAuthRecordsToFD(fd
, now
, m
->ResourceRecords
, mDNSNULL
);
4780 LogToFD(fd
, "--------- LocalOnly, P2P Auth Records ---------");
4781 LogLocalOnlyAuthRecordsToFD(fd
, m
);
4783 LogToFD(fd
, "--------- /etc/hosts ---------");
4784 LogEtcHostsToFD(fd
, m
);
4786 LogToFD(fd
, "------ Duplicate Records -------");
4787 LogAuthRecordsToFD(fd
, now
, m
->DuplicateRecords
, mDNSNULL
);
4789 LogToFD(fd
, "----- Auth Records Proxied -----");
4790 LogAuthRecordsToFD(fd
, now
, m
->ResourceRecords
, &ProxyA
);
4792 LogToFD(fd
, "-- Duplicate Records Proxied ---");
4793 LogAuthRecordsToFD(fd
, now
, m
->DuplicateRecords
, &ProxyD
);
4795 LogToFD(fd
, "---------- Questions -----------");
4796 if (!m
->Questions
) LogToFD(fd
, "<None>");
4801 LogToFD(fd
, " Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
4802 for (q
= m
->Questions
; q
; q
=q
->next
)
4804 mDNSs32 i
= q
->ThisQInterval
/ mDNSPlatformOneSecond
;
4805 mDNSs32 n
= (NextQSendTime(q
) - now
) / mDNSPlatformOneSecond
;
4806 char *ifname
= InterfaceNameForID(m
, q
->InterfaceID
);
4808 if (q
->ThisQInterval
) CacheActive
++;
4809 LogToFD(fd
, "%6d%6d %-7s%s%s %5d 0x%08x%08x%08x%08x 0x%p 0x%p %1d %2d %-5s%##s%s",
4811 ifname
? ifname
: mDNSOpaque16IsZero(q
->TargetQID
) ? "" : "-U-",
4812 mDNSOpaque16IsZero(q
->TargetQID
) ? (q
->LongLived
? "l" : " ") : (q
->LongLived
? "L" : "O"),
4813 q
->ValidationRequired
? "V" : q
->ValidatingResponse
? "R" : " ",
4815 q
->validDNSServers
.l
[3], q
->validDNSServers
.l
[2], q
->validDNSServers
.l
[1], q
->validDNSServers
.l
[0],
4817 q
->SuppressUnusable
, q
->Suppressed
, DNSTypeName(q
->qtype
), q
->qname
.c
,
4818 q
->DuplicateOf
? " (dup)" : "");
4820 LogToFD(fd
, "%lu question%s; %lu active", CacheUsed
, CacheUsed
> 1 ? "s" : "", CacheActive
);
4823 LogToFD(fd
, "----- LocalOnly, P2P Questions -----");
4824 if (!m
->LocalOnlyQuestions
) LogToFD(fd
, "<None>");
4825 else for (q
= m
->LocalOnlyQuestions
; q
; q
=q
->next
)
4826 LogToFD(fd
, " %3s %5d %-6s%##s%s",
4827 q
->InterfaceID
== mDNSInterface_LocalOnly
? "LO ": q
->InterfaceID
== mDNSInterface_BLE
? "BLE": "P2P",
4828 q
->CurrentAnswers
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
4830 LogToFD(fd
, "---- Active UDS Client Requests ----");
4831 if (!all_requests
) LogToFD(fd
, "<None>");
4834 request_state
*req
, *r
;
4835 for (req
= all_requests
; req
; req
=req
->next
)
4837 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
4839 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
) if (r
== req
->primary
) goto foundparent
;
4840 LogToFD(fd
, "%3d: Orhpan operation %p; parent %p not found in request list", req
->sd
);
4842 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
4843 LogClientInfoToFD(fd
, req
);
4848 LogToFD(fd
, "-------- NAT Traversals --------");
4849 LogToFD(fd
, "ExtAddress %.4a Retry %d Interval %d",
4851 m
->retryGetAddr
? (m
->retryGetAddr
- now
) / mDNSPlatformOneSecond
: 0,
4852 m
->retryIntervalGetAddr
/ mDNSPlatformOneSecond
);
4853 if (m
->NATTraversals
)
4855 const NATTraversalInfo
*nat
;
4856 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
4858 LogToFD(fd
, "%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
4860 nat
->Protocol
? (nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP") : "ADD",
4861 mDNSVal16(nat
->IntPort
),
4862 (nat
->lastSuccessfulProtocol
== NATTProtocolNone
? "None " :
4863 nat
->lastSuccessfulProtocol
== NATTProtocolNATPMP
? "NAT-PMP " :
4864 nat
->lastSuccessfulProtocol
== NATTProtocolUPNPIGD
? "UPnP/IGD" :
4865 nat
->lastSuccessfulProtocol
== NATTProtocolPCP
? "PCP " :
4866 /* else */ "Unknown " ),
4868 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
4869 nat
->retryInterval
/ mDNSPlatformOneSecond
,
4870 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0,
4871 &nat
->NewAddress
, mDNSVal16(nat
->RequestedPort
),
4872 &nat
->ExternalAddress
, mDNSVal16(nat
->ExternalPort
));
4876 LogToFD(fd
, "--------- AuthInfoList ---------");
4877 if (!m
->AuthInfoList
) LogToFD(fd
, "<None>");
4880 const DomainAuthInfo
*a
;
4881 for (a
= m
->AuthInfoList
; a
; a
= a
->next
)
4883 LogToFD(fd
, "%##s %##s %##s %d %d",
4884 a
->domain
.c
, a
->keyname
.c
,
4885 a
->hostname
.c
, (a
->port
.b
[0] << 8 | a
->port
.b
[1]),
4886 (a
->deltime
? (a
->deltime
- now
) : 0));
4890 LogToFD(fd
, "---------- Misc State ----------");
4892 LogToFD(fd
, "PrimaryMAC: %.6a", &m
->PrimaryMAC
);
4894 LogToFD(fd
, "m->SleepState %d (%s) seq %d",
4896 m
->SleepState
== SleepState_Awake
? "Awake" :
4897 m
->SleepState
== SleepState_Transferring
? "Transferring" :
4898 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?",
4901 if (!m
->SPSSocket
) LogToFD(fd
, "Not offering Sleep Proxy Service");
4902 #ifndef SPC_DISABLED
4903 else LogToFD(fd
, "Offering Sleep Proxy Service: %#s", m
->SPSRecords
.RR_SRV
.resrec
.name
->c
);
4905 if (m
->ProxyRecords
== ProxyA
+ ProxyD
) LogToFD(fd
, "ProxyRecords: %d + %d = %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
);
4906 else LogToFD(fd
, "ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
, m
->ProxyRecords
);
4908 LogToFD(fd
, "------ Auto Browse Domains -----");
4909 if (!AutoBrowseDomains
) LogToFD(fd
, "<None>");
4910 else for (d
=AutoBrowseDomains
; d
; d
=d
->next
) LogToFD(fd
, "%##s", d
->name
.c
);
4912 LogToFD(fd
, "--- Auto Registration Domains --");
4913 if (!AutoRegistrationDomains
) LogToFD(fd
, "<None>");
4914 else for (d
=AutoRegistrationDomains
; d
; d
=d
->next
) LogToFD(fd
, "%##s", d
->name
.c
);
4916 LogToFD(fd
, "--- Search Domains --");
4917 if (!SearchList
) LogToFD(fd
, "<None>");
4920 for (s
=SearchList
; s
; s
=s
->next
)
4922 char *ifname
= InterfaceNameForID(m
, s
->InterfaceID
);
4923 LogToFD(fd
, "%##s %s", s
->domain
.c
, ifname
? ifname
: "");
4926 LogToFD(fd
, "--- Trust Anchors ---");
4927 if (!m
->TrustAnchors
)
4929 LogToFD(fd
, "<None>");
4934 mDNSu8 fromTimeBuf
[64];
4935 mDNSu8 untilTimeBuf
[64];
4937 for (ta
=m
->TrustAnchors
; ta
; ta
=ta
->next
)
4939 mDNSPlatformFormatTime((unsigned long)ta
->validFrom
, fromTimeBuf
, sizeof(fromTimeBuf
));
4940 mDNSPlatformFormatTime((unsigned long)ta
->validUntil
, untilTimeBuf
, sizeof(untilTimeBuf
));
4941 LogToFD(fd
, "%##s %d %d %d %d %s %s", ta
->zone
.c
, ta
->rds
.keyTag
,
4942 ta
->rds
.alg
, ta
->rds
.digestType
, ta
->digestLen
, fromTimeBuf
, untilTimeBuf
);
4946 LogToFD(fd
, "--- DNSSEC Statistics ---");
4948 LogToFD(fd
, "Unicast Cache size %u", m
->rrcache_totalused_unicast
);
4949 LogToFD(fd
, "DNSSEC Cache size %u", m
->DNSSECStats
.TotalMemUsed
);
4950 if (m
->rrcache_totalused_unicast
)
4951 LogToFD(fd
, "DNSSEC usage percentage %u", ((unsigned long)(m
->DNSSECStats
.TotalMemUsed
* 100))/m
->rrcache_totalused_unicast
);
4952 LogToFD(fd
, "DNSSEC Extra Packets (0 to 2) %u", m
->DNSSECStats
.ExtraPackets0
);
4953 LogToFD(fd
, "DNSSEC Extra Packets (3 to 6) %u", m
->DNSSECStats
.ExtraPackets3
);
4954 LogToFD(fd
, "DNSSEC Extra Packets (7 to 9) %u", m
->DNSSECStats
.ExtraPackets7
);
4955 LogToFD(fd
, "DNSSEC Extra Packets ( >= 10) %u", m
->DNSSECStats
.ExtraPackets10
);
4957 LogToFD(fd
, "DNSSEC Latency (0 to 4ms) %u", m
->DNSSECStats
.Latency0
);
4958 LogToFD(fd
, "DNSSEC Latency (4 to 9ms) %u", m
->DNSSECStats
.Latency5
);
4959 LogToFD(fd
, "DNSSEC Latency (10 to 19ms) %u", m
->DNSSECStats
.Latency10
);
4960 LogToFD(fd
, "DNSSEC Latency (20 to 49ms) %u", m
->DNSSECStats
.Latency20
);
4961 LogToFD(fd
, "DNSSEC Latency (50 to 99ms) %u", m
->DNSSECStats
.Latency50
);
4962 LogToFD(fd
, "DNSSEC Latency ( >=100ms) %u", m
->DNSSECStats
.Latency100
);
4964 LogToFD(fd
, "DNSSEC Secure Status %u", m
->DNSSECStats
.SecureStatus
);
4965 LogToFD(fd
, "DNSSEC Insecure Status %u", m
->DNSSECStats
.InsecureStatus
);
4966 LogToFD(fd
, "DNSSEC Indeterminate Status %u", m
->DNSSECStats
.IndeterminateStatus
);
4967 LogToFD(fd
, "DNSSEC Bogus Status %u", m
->DNSSECStats
.BogusStatus
);
4968 LogToFD(fd
, "DNSSEC NoResponse Status %u", m
->DNSSECStats
.NoResponseStatus
);
4969 LogToFD(fd
, "DNSSEC Probes sent %u", m
->DNSSECStats
.NumProbesSent
);
4970 LogToFD(fd
, "DNSSEC Msg Size (<=1024) %u", m
->DNSSECStats
.MsgSize0
);
4971 LogToFD(fd
, "DNSSEC Msg Size (<=2048) %u", m
->DNSSECStats
.MsgSize1
);
4972 LogToFD(fd
, "DNSSEC Msg Size (> 2048) %u", m
->DNSSECStats
.MsgSize2
);
4974 LogMDNSStatisticsToFD(fd
, m
);
4976 LogToFD(fd
, "---- Task Scheduling Timers ----");
4978 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
4979 LogToFD(fd
, "BonjourEnabled %d", m
->BonjourEnabled
);
4982 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
4983 LogToFD(fd
, "EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery
);
4984 LogToFD(fd
, "DefaultToBLETriggered %d", DefaultToBLETriggered
);
4985 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
4987 if (!m
->NewQuestions
)
4988 LogToFD(fd
, "NewQuestion <NONE>");
4990 LogToFD(fd
, "NewQuestion DelayAnswering %d %d %##s (%s)",
4991 m
->NewQuestions
->DelayAnswering
, m
->NewQuestions
->DelayAnswering
-now
,
4992 m
->NewQuestions
->qname
.c
, DNSTypeName(m
->NewQuestions
->qtype
));
4994 if (!m
->NewLocalOnlyQuestions
)
4995 LogToFD(fd
, "NewLocalOnlyQuestions <NONE>");
4997 LogToFD(fd
, "NewLocalOnlyQuestions %##s (%s)",
4998 m
->NewLocalOnlyQuestions
->qname
.c
, DNSTypeName(m
->NewLocalOnlyQuestions
->qtype
));
5000 if (!m
->NewLocalRecords
)
5001 LogToFD(fd
, "NewLocalRecords <NONE>");
5003 LogToFD(fd
, "NewLocalRecords %02X %s", m
->NewLocalRecords
->resrec
.RecordType
, ARDisplayString(m
, m
->NewLocalRecords
));
5005 LogToFD(fd
, "SPSProxyListChanged%s", m
->SPSProxyListChanged
? "" : " <NONE>");
5006 LogToFD(fd
, "LocalRemoveEvents%s", m
->LocalRemoveEvents
? "" : " <NONE>");
5007 LogToFD(fd
, "m->WABBrowseQueriesCount %d", m
->WABBrowseQueriesCount
);
5008 LogToFD(fd
, "m->WABLBrowseQueriesCount %d", m
->WABLBrowseQueriesCount
);
5009 LogToFD(fd
, "m->WABRegQueriesCount %d", m
->WABRegQueriesCount
);
5010 LogToFD(fd
, "m->AutoTargetServices %u", m
->AutoTargetServices
);
5011 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
5012 LogToFD(fd
, "m->AutoTargetAWDLIncludedCount %u", m
->AutoTargetAWDLIncludedCount
);
5013 LogToFD(fd
, "m->AutoTargetAWDLOnlyCount %u", m
->AutoTargetAWDLOnlyCount
);
5016 LogToFD(fd
, " ABS (hex) ABS (dec) REL (hex) REL (dec)");
5017 LogToFD(fd
, "m->timenow %08X %11d", now
, now
);
5018 LogToFD(fd
, "m->timenow_adjust %08X %11d", m
->timenow_adjust
, m
->timenow_adjust
);
5019 LogTimerToFD(fd
, "m->NextScheduledEvent ", m
->NextScheduledEvent
);
5021 #ifndef UNICAST_DISABLED
5022 LogTimerToFD(fd
, "m->NextuDNSEvent ", m
->NextuDNSEvent
);
5023 LogTimerToFD(fd
, "m->NextSRVUpdate ", m
->NextSRVUpdate
);
5024 LogTimerToFD(fd
, "m->NextScheduledNATOp ", m
->NextScheduledNATOp
);
5025 LogTimerToFD(fd
, "m->retryGetAddr ", m
->retryGetAddr
);
5028 LogTimerToFD(fd
, "m->NextCacheCheck ", m
->NextCacheCheck
);
5029 LogTimerToFD(fd
, "m->NextScheduledSPS ", m
->NextScheduledSPS
);
5030 LogTimerToFD(fd
, "m->NextScheduledKA ", m
->NextScheduledKA
);
5032 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5033 LogTimerToFD(fd
, "m->NextBonjourDisableTime ", m
->NextBonjourDisableTime
);
5036 LogTimerToFD(fd
, "m->NextScheduledSPRetry ", m
->NextScheduledSPRetry
);
5037 LogTimerToFD(fd
, "m->DelaySleep ", m
->DelaySleep
);
5039 LogTimerToFD(fd
, "m->NextScheduledQuery ", m
->NextScheduledQuery
);
5040 LogTimerToFD(fd
, "m->NextScheduledProbe ", m
->NextScheduledProbe
);
5041 LogTimerToFD(fd
, "m->NextScheduledResponse", m
->NextScheduledResponse
);
5043 LogTimerToFD(fd
, "m->SuppressSending ", m
->SuppressSending
);
5044 LogTimerToFD(fd
, "m->SuppressProbes ", m
->SuppressProbes
);
5045 LogTimerToFD(fd
, "m->ProbeFailTime ", m
->ProbeFailTime
);
5046 LogTimerToFD(fd
, "m->DelaySleep ", m
->DelaySleep
);
5047 LogTimerToFD(fd
, "m->SleepLimit ", m
->SleepLimit
);
5048 LogTimerToFD(fd
, "m->NextScheduledStopTime ", m
->NextScheduledStopTime
);
5051 #if MDNS_MALLOC_DEBUGGING
5052 mDNSlocal
void udsserver_validatelists(void *context
)
5054 const request_state
*req
, *p
;
5055 (void)context
; // unused
5056 for (req
= all_requests
; req
; req
=req
->next
)
5058 if (req
->next
== (request_state
*)~0 || (req
->sd
< 0 && req
->sd
!= -2))
5059 LogMemCorruption("UDS request list: %p is garbage (%d)", req
, req
->sd
);
5061 if (req
->primary
== req
)
5062 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req
, req
->sd
);
5064 if (req
->primary
&& req
->replies
)
5065 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
5066 req
, req
->sd
, req
->primary
&& req
->replies
);
5070 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req
, p
, req
->sd
);
5071 else if (p
&& (p
->next
== (request_state
*)~0 || (p
->sd
< 0 && p
->sd
!= -2)))
5072 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req
, p
, p
->sd
);
5075 for (rep
= req
->replies
; rep
; rep
=rep
->next
)
5076 if (rep
->next
== (reply_state
*)~0)
5077 LogMemCorruption("UDS req->replies: %p is garbage", rep
);
5079 if (req
->terminate
== connection_termination
)
5081 registered_record_entry
*r
;
5082 for (r
= req
->u
.reg_recs
; r
; r
=r
->next
)
5083 if (r
->next
== (registered_record_entry
*)~0)
5084 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r
);
5086 else if (req
->terminate
== regservice_termination_callback
)
5088 service_instance
*s
;
5089 for (s
= req
->u
.servicereg
.instances
; s
; s
=s
->next
)
5090 if (s
->next
== (service_instance
*)~0)
5091 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s
);
5093 else if (req
->terminate
== browse_termination_callback
)
5096 for (b
= req
->u
.browser
.browsers
; b
; b
=b
->next
)
5097 if (b
->next
== (browser_t
*)~0)
5098 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b
);
5103 for (d
= SCPrefBrowseDomains
; d
; d
=d
->next
)
5104 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
5105 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
5108 for (b
= LocalDomainEnumRecords
; b
; b
=b
->next
)
5109 if (b
->next
== (ARListElem
*)~0 || b
->ar
.resrec
.name
->c
[0] > 63)
5110 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b
, b
->ar
.resrec
.name
->c
[0]);
5112 for (d
= AutoBrowseDomains
; d
; d
=d
->next
)
5113 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
5114 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
5116 for (d
= AutoRegistrationDomains
; d
; d
=d
->next
)
5117 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
5118 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
5120 #endif // MDNS_MALLOC_DEBUGGING
5122 mDNSlocal
int send_msg(request_state
*const req
)
5124 reply_state
*const rep
= req
->replies
; // Send the first waiting reply
5127 ConvertHeaderBytes(rep
->mhdr
);
5128 nwriten
= send(req
->sd
, (char *)&rep
->mhdr
+ rep
->nwriten
, rep
->totallen
- rep
->nwriten
, 0);
5129 ConvertHeaderBytes(rep
->mhdr
);
5133 if (dnssd_errno
== dnssd_EINTR
|| dnssd_errno
== dnssd_EWOULDBLOCK
) nwriten
= 0;
5136 #if !defined(PLATFORM_NO_EPIPE)
5137 if (dnssd_errno
== EPIPE
)
5138 return(req
->ts
= t_terminated
);
5142 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
5143 rep
->totallen
- rep
->nwriten
, rep
->totallen
, req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
5148 rep
->nwriten
+= nwriten
;
5149 return (rep
->nwriten
== rep
->totallen
) ? t_complete
: t_morecoming
;
5152 mDNSexport mDNSs32
udsserver_idle(mDNSs32 nextevent
)
5154 mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
5155 request_state
**req
= &all_requests
;
5159 request_state
*const r
= *req
;
5161 if (r
->terminate
== resolve_termination_callback
)
5162 if (r
->u
.resolve
.ReportTime
&& now
- r
->u
.resolve
.ReportTime
>= 0)
5164 r
->u
.resolve
.ReportTime
= 0;
5165 // if client received results and resolve still active
5166 if (r
->u
.resolve
.txt
&& r
->u
.resolve
.srv
)
5167 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
);
5170 // Note: Only primary req's have reply lists, not subordinate req's.
5171 while (r
->replies
) // Send queued replies
5173 transfer_state result
;
5174 if (r
->replies
->next
)
5175 r
->replies
->rhdr
->flags
|= dnssd_htonl(kDNSServiceFlagsMoreComing
);
5176 result
= send_msg(r
); // Returns t_morecoming if buffer full because client is not reading
5177 if (result
== t_complete
)
5179 reply_state
*fptr
= r
->replies
;
5180 r
->replies
= r
->replies
->next
;
5181 freeL("reply_state/udsserver_idle", fptr
);
5182 r
->time_blocked
= 0; // reset failure counter after successful send
5183 r
->unresponsiveness_reports
= 0;
5186 else if (result
== t_terminated
)
5188 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
);
5191 else if (result
== t_error
)
5193 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r
->sd
, r
->process_id
, r
->pid_name
);
5200 if (r
->replies
) // If we failed to send everything, check our time_blocked timer
5202 if (nextevent
- now
> mDNSPlatformOneSecond
)
5203 nextevent
= now
+ mDNSPlatformOneSecond
;
5205 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_INFO
,
5206 "[R%u] Could not send all replies. Will try again in %d ticks.", r
->request_id
, nextevent
- now
);
5207 if (mDNSStorage
.SleepState
!= SleepState_Awake
)
5208 r
->time_blocked
= 0;
5209 else if (!r
->time_blocked
)
5210 r
->time_blocked
= NonZeroTime(now
);
5211 else if (now
- r
->time_blocked
>= 10 * mDNSPlatformOneSecond
* (r
->unresponsiveness_reports
+1))
5214 struct reply_state
*x
= r
->replies
;
5220 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
5221 r
->sd
, r
->process_id
, r
->pid_name
, (now
- r
->time_blocked
) / mDNSPlatformOneSecond
, num
, num
== 1 ? "y" : "ies");
5222 if (++r
->unresponsiveness_reports
>= 60)
5224 LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r
->sd
, r
->process_id
, r
->pid_name
);
5231 if (!dnssd_SocketValid(r
->sd
)) // If this request is finished, unlink it from the list and free the memory
5233 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
5235 freeL("request_state/udsserver_idle", r
);
5243 struct CompileTimeAssertionChecks_uds_daemon
5245 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
5246 // other overly-large structures instead of having a pointer to them, can inadvertently
5247 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
5248 char sizecheck_request_state
[(sizeof(request_state
) <= 3696) ? 1 : -1];
5249 char sizecheck_registered_record_entry
[(sizeof(registered_record_entry
) <= 60) ? 1 : -1];
5250 char sizecheck_service_instance
[(sizeof(service_instance
) <= 6552) ? 1 : -1];
5251 char sizecheck_browser_t
[(sizeof(browser_t
) <= 1432) ? 1 : -1];
5252 char sizecheck_reply_hdr
[(sizeof(reply_hdr
) <= 12) ? 1 : -1];
5253 char sizecheck_reply_state
[(sizeof(reply_state
) <= 64) ? 1 : -1];
5257 #include "../unittests/uds_daemon_ut.c"