1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2006 Apple Computer, Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 #define usleep(X) Sleep(((X)+999)/1000)
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
27 #include <sys/resource.h>
33 #include "mDNSEmbeddedAPI.h"
34 #include "DNSCommon.h"
36 #include "uds_daemon.h"
38 // Apple-specific functionality, not required for other platforms
39 #if APPLE_OSX_mDNSResponder
40 #include <sys/ucred.h>
46 #if APPLE_OSX_mDNSResponder
47 #include <WebFilterDNS/WebFilterDNS.h>
51 int WCFIsServerRunning(WCFConnection
*conn
) __attribute__((weak_import
));
52 int WCFNameResolvesToAddr(WCFConnection
*conn
, char* domainName
, struct sockaddr
* address
, uid_t userid
) __attribute__((weak_import
));
53 int WCFNameResolvesToName(WCFConnection
*conn
, char* fromName
, char* toName
, uid_t userid
) __attribute__((weak_import
));
55 // Do we really need to define a macro for "if"?
56 #define CHECK_WCF_FUNCTION(X) if (X)
61 #endif // APPLE_OSX_mDNSResponder
63 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
64 // User IDs for real user accounts start at 501 and count up from there
65 #define SystemUID(X) ((X) <= 500)
67 // ***************************************************************************
68 #if COMPILER_LIKES_PRAGMA_MARK
70 #pragma mark - Types and Data Structures
82 typedef struct request_state request_state
;
84 typedef void (*req_termination_fn
)(request_state
*request
);
86 typedef struct registered_record_entry
88 struct registered_record_entry
*next
;
90 client_context_t regrec_client_context
;
91 request_state
*request
;
92 mDNSBool external_advertise
;
93 mDNSInterfaceID origInterfaceID
;
94 AuthRecord
*rr
; // Pointer to variable-sized AuthRecord (Why a pointer? Why not just embed it here?)
95 } registered_record_entry
;
97 // A single registered service: ServiceRecordSet + bookkeeping
98 // Note that we duplicate some fields from parent service_info object
99 // to facilitate cleanup, when instances and parent may be deallocated at different times.
100 typedef struct service_instance
102 struct service_instance
*next
;
103 request_state
*request
;
104 AuthRecord
*subtypes
;
105 mDNSBool renameonmemfree
; // Set on config change when we deregister original name
106 mDNSBool clientnotified
; // Has client been notified of successful registration yet?
107 mDNSBool default_local
; // is this the "local." from an empty-string registration?
108 mDNSBool external_advertise
; // is this is being advertised externally?
110 ServiceRecordSet srs
; // note -- variable-sized object -- must be last field in struct
113 // for multi-domain default browsing
114 typedef struct browser_t
116 struct browser_t
*next
;
124 request_state
*primary
; // If this operation is on a shared socket, pointer to primary
125 // request_state for the original DNSServiceCreateConnection() operation
129 void * platform_data
;
131 // Note: On a shared connection these fields in the primary structure, including hdr, are re-used
132 // for each new request. This is because, until we've read the ipc_msg_hdr to find out what the
133 // operation is, we don't know if we're going to need to allocate a new request_state or not.
135 mDNSu32 hdr_bytes
; // bytes of header already read
137 mDNSu32 data_bytes
; // bytes of message data already read
138 char *msgbuf
; // pointer to data storage to pass to free()
139 const char *msgptr
; // pointer to data to be read from (may be modified)
140 char *msgend
; // pointer to byte after last byte of message
142 // reply, termination, error, and client context info
143 int no_reply
; // don't send asynchronous replies to client
144 mDNSs32 time_blocked
; // record time of a blocked client
145 int unresponsiveness_reports
;
146 struct reply_state
*replies
; // corresponding (active) reply list
147 req_termination_fn terminate
;
151 registered_record_entry
*reg_recs
; // list of registrations for a connection-oriented request
154 mDNSInterfaceID interface_id
;
155 mDNSBool default_domain
;
162 mDNSInterfaceID InterfaceID
;
167 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
];
169 mDNSBool default_domain
;
171 mDNSBool autoname
; // Set if this name is tied to the Computer Name
172 mDNSBool autorename
; // Set if this client wants us to automatically rename on conflict
173 mDNSBool allowremotequery
; // Respond to unicast queries from outside the local link?
175 service_instance
*instances
;
179 mDNSInterfaceID interface_id
;
187 mDNSIPPort ReqExt
; // External port we originally requested, for logging purposes
188 NATTraversalInfo NATinfo
;
193 DNSServiceFlags flags
;
196 DNSQuestion q_default
;
207 const ResourceRecord
*txt
;
208 const ResourceRecord
*srv
;
210 mDNSBool external_advertise
;
215 // struct physically sits between ipc message header and call-specific fields in the message buffer
218 DNSServiceFlags flags
; // Note: This field is in NETWORK byte order
219 mDNSu32 ifi
; // Note: This field is in NETWORK byte order
220 DNSServiceErrorType error
; // Note: This field is in NETWORK byte order
223 typedef struct reply_state
225 struct reply_state
*next
; // If there are multiple unsent replies
232 // ***************************************************************************
233 #if COMPILER_LIKES_PRAGMA_MARK
235 #pragma mark - Globals
239 mDNSexport mDNS mDNSStorage
;
240 mDNSexport
const char ProgramName
[] = "mDNSResponder";
242 static dnssd_sock_t listenfd
= dnssd_InvalidSocket
;
243 static request_state
*all_requests
= NULL
;
245 // Note asymmetry here between registration and browsing.
246 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
247 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
248 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
249 // 1. SCPrefBrowseDomains (local configuration data)
250 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
251 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
252 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
254 mDNSexport DNameListElem
*AutoRegistrationDomains
; // Domains where we automatically register for empty-string registrations
256 static DNameListElem
*SCPrefBrowseDomains
; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
257 static ARListElem
*LocalDomainEnumRecords
; // List of locally-generated PTR records to augment those we learn from the network
258 mDNSexport DNameListElem
*AutoBrowseDomains
; // List created from those local-only PTR records plus records we get from the network
260 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
261 // n get_string() calls w/o buffer overrun
262 // initialization, setup/teardown functions
264 // If a platform specifies its own PID file name, we use that
266 #define PID_FILE "/var/run/mDNSResponder.pid"
269 // ***************************************************************************
270 #if COMPILER_LIKES_PRAGMA_MARK
272 #pragma mark - General Utility Functions
275 mDNSlocal
void FatalError(char *errmsg
)
277 LogMsg("%s: %s", errmsg
, dnssd_strerror(dnssd_errno
));
278 *(long*)0 = 0; // On OS X abort() doesn't generate a crash log, but writing to zero does
279 abort(); // On platforms where writing to zero doesn't generate an exception, abort instead
282 mDNSlocal mDNSu32
dnssd_htonl(mDNSu32 l
)
285 char *data
= (char*) &ret
;
286 put_uint32(l
, &data
);
290 // hack to search-replace perror's to LogMsg's
291 mDNSlocal
void my_perror(char *errmsg
)
293 LogMsg("%s: %d (%s)", errmsg
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
296 mDNSlocal
void abort_request(request_state
*req
)
298 if (req
->terminate
== (req_termination_fn
)~0)
299 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req
, req
->terminate
); return; }
301 // First stop whatever mDNSCore operation we were doing
302 // If this is actually a shared connection operation, then its req->terminate function will scan
303 // the all_requests list and terminate any subbordinate operations sharing this file descriptor
304 if (req
->terminate
) req
->terminate(req
);
306 if (!dnssd_SocketValid(req
->sd
))
307 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req
, req
->sd
); return; }
309 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
312 if (req
->errsd
!= req
->sd
) LogOperation("%3d: Removing FD and closing errsd %d", req
->sd
, req
->errsd
);
313 else LogOperation("%3d: Removing FD", req
->sd
);
314 udsSupportRemoveFDFromEventLoop(req
->sd
, req
->platform_data
); // Note: This also closes file descriptor req->sd for us
315 if (req
->errsd
!= req
->sd
) { dnssd_close(req
->errsd
); req
->errsd
= req
->sd
; }
317 while (req
->replies
) // free pending replies
319 reply_state
*ptr
= req
->replies
;
320 req
->replies
= req
->replies
->next
;
321 freeL("reply_state (abort)", ptr
);
325 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
326 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
327 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
328 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
329 req
->sd
= req
->errsd
= -2;
331 req
->sd
= req
->errsd
= dnssd_InvalidSocket
;
333 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
334 req
->terminate
= (req_termination_fn
)~0;
337 mDNSlocal
void AbortUnlinkAndFree(request_state
*req
)
339 request_state
**p
= &all_requests
;
341 while (*p
&& *p
!= req
) p
=&(*p
)->next
;
342 if (*p
) { *p
= req
->next
; freeL("request_state/AbortUnlinkAndFree", req
); }
343 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req
);
346 mDNSlocal reply_state
*create_reply(const reply_op_t op
, const size_t datalen
, request_state
*const request
)
350 if ((unsigned)datalen
< sizeof(reply_hdr
))
352 LogMsg("ERROR: create_reply - data length less than length of required fields");
356 reply
= mallocL("reply_state", sizeof(reply_state
) + datalen
- sizeof(reply_hdr
));
357 if (!reply
) FatalError("ERROR: malloc");
359 reply
->next
= mDNSNULL
;
360 reply
->totallen
= (mDNSu32
)datalen
+ sizeof(ipc_msg_hdr
);
363 reply
->mhdr
->version
= VERSION
;
364 reply
->mhdr
->datalen
= (mDNSu32
)datalen
;
365 reply
->mhdr
->ipc_flags
= 0;
366 reply
->mhdr
->op
= op
;
367 reply
->mhdr
->client_context
= request
->hdr
.client_context
;
368 reply
->mhdr
->reg_index
= 0;
373 // Append a reply to the list in a request object
374 // If our request is sharing a connection, then we append our reply_state onto the primary's list
375 mDNSlocal
void append_reply(request_state
*req
, reply_state
*rep
)
377 request_state
*r
= req
->primary
? req
->primary
: req
;
378 reply_state
**ptr
= &r
->replies
;
379 while (*ptr
) ptr
= &(*ptr
)->next
;
384 // Generates a response message giving name, type, domain, plus interface index,
385 // suitable for a browse result or service registration result.
386 // On successful completion rep is set to point to a malloc'd reply_state struct
387 mDNSlocal mStatus
GenerateNTDResponse(const domainname
*const servicename
, const mDNSInterfaceID id
,
388 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
391 domainname type
, dom
;
393 if (!DeconstructServiceName(servicename
, &name
, &type
, &dom
))
394 return kDNSServiceErr_Invalid
;
397 char namestr
[MAX_DOMAIN_LABEL
+1];
398 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
399 char domstr
[MAX_ESCAPED_DOMAIN_NAME
];
403 ConvertDomainLabelToCString_unescaped(&name
, namestr
);
404 ConvertDomainNameToCString(&type
, typestr
);
405 ConvertDomainNameToCString(&dom
, domstr
);
407 // Calculate reply data length
408 len
= sizeof(DNSServiceFlags
);
409 len
+= sizeof(mDNSu32
); // if index
410 len
+= sizeof(DNSServiceErrorType
);
411 len
+= (int) (strlen(namestr
) + 1);
412 len
+= (int) (strlen(typestr
) + 1);
413 len
+= (int) (strlen(domstr
) + 1);
415 // Build reply header
416 *rep
= create_reply(op
, len
, request
);
417 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
418 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
));
419 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
422 data
= (char *)&(*rep
)->rhdr
[1];
423 put_string(namestr
, &data
);
424 put_string(typestr
, &data
);
425 put_string(domstr
, &data
);
427 return mStatus_NoError
;
431 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
432 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
433 mDNSlocal
void GenerateBonjourBrowserResponse(const domainname
*const servicename
, const mDNSInterfaceID id
,
434 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
436 char namestr
[MAX_DOMAIN_LABEL
+1];
437 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
438 static const char domstr
[] = ".";
444 // 1. Put first label in namestr
445 ConvertDomainLabelToCString_unescaped((const domainlabel
*)servicename
, namestr
);
447 // 2. Put second label and "local" into typestr
448 mDNS_snprintf(typestr
, sizeof(typestr
), "%#s.local.", SecondLabel(servicename
));
450 // Calculate reply data length
451 len
= sizeof(DNSServiceFlags
);
452 len
+= sizeof(mDNSu32
); // if index
453 len
+= sizeof(DNSServiceErrorType
);
454 len
+= (int) (strlen(namestr
) + 1);
455 len
+= (int) (strlen(typestr
) + 1);
456 len
+= (int) (strlen(domstr
) + 1);
458 // Build reply header
459 *rep
= create_reply(op
, len
, request
);
460 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
461 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
));
462 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
465 data
= (char *)&(*rep
)->rhdr
[1];
466 put_string(namestr
, &data
);
467 put_string(typestr
, &data
);
468 put_string(domstr
, &data
);
471 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
472 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
473 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
474 mDNSlocal AuthRecord
*read_rr_from_ipc_msg(request_state
*request
, int GetTTL
, int validate_flags
)
476 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
477 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
479 int str_err
= get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
));
480 mDNSu16 type
= get_uint16(&request
->msgptr
, request
->msgend
);
481 mDNSu16
class = get_uint16(&request
->msgptr
, request
->msgend
);
482 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
483 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
484 mDNSu32 ttl
= GetTTL
? get_uint32(&request
->msgptr
, request
->msgend
) : 0;
485 int storage_size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
488 if (str_err
) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL
; }
490 if (!request
->msgptr
) { LogMsg("Error reading Resource Record from client"); return NULL
; }
492 if (validate_flags
&&
493 !((flags
& kDNSServiceFlagsShared
) == kDNSServiceFlagsShared
) &&
494 !((flags
& kDNSServiceFlagsUnique
) == kDNSServiceFlagsUnique
))
496 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
500 rr
= mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord
) - sizeof(RDataBody
) + storage_size
);
501 if (!rr
) FatalError("ERROR: malloc");
502 mDNS_SetupResourceRecord(rr
, mDNSNULL
, mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
),
503 type
, 0, (mDNSu8
) ((flags
& kDNSServiceFlagsShared
) ? kDNSRecordTypeShared
: kDNSRecordTypeUnique
), mDNSNULL
, mDNSNULL
);
505 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, name
))
507 LogMsg("ERROR: bad name: %s", name
);
508 freeL("AuthRecord/read_rr_from_ipc_msg", rr
);
512 if (flags
& kDNSServiceFlagsAllowRemoteQuery
) rr
->AllowRemoteQuery
= mDNStrue
;
513 rr
->resrec
.rrclass
= class;
514 rr
->resrec
.rdlength
= rdlen
;
515 rr
->resrec
.rdata
->MaxRDLength
= rdlen
;
516 mDNSPlatformMemCopy(rr
->resrec
.rdata
->u
.data
, rdata
, rdlen
);
517 if (GetTTL
) rr
->resrec
.rroriginalttl
= ttl
;
518 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
519 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Sets rr->rdatahash for us
523 mDNSlocal
int build_domainname_from_strings(domainname
*srv
, char *name
, char *regtype
, char *domain
)
528 if (!MakeDomainLabelFromLiteralString(&n
, name
)) return -1;
529 if (!MakeDomainNameFromDNSNameString(&t
, regtype
)) return -1;
530 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return -1;
531 if (!ConstructServiceName(srv
, &n
, &t
, &d
)) return -1;
535 mDNSlocal
void send_all(dnssd_sock_t s
, const char *ptr
, int len
)
537 int n
= send(s
, ptr
, len
, 0);
538 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
539 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
540 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
542 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
543 s
, n
, len
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
547 mDNSlocal mDNSBool
AuthorizedDomain(const request_state
* const request
, const domainname
* const d
, const DNameListElem
* const doms
)
549 const DNameListElem
*delem
= mDNSNULL
;
550 int bestDelta
= -1; // the delta of the best match, lower is better
552 mDNSBool allow
= mDNSfalse
;
554 if (SystemUID(request
->uid
)) return mDNStrue
;
556 dLabels
= CountLabels(d
);
557 for (delem
= doms
; delem
; delem
= delem
->next
)
561 int delemLabels
= CountLabels(&delem
->name
);
562 int delta
= dLabels
- delemLabels
;
563 if ((bestDelta
== -1 || delta
<= bestDelta
) && SameDomainName(&delem
->name
, SkipLeadingLabels(d
, delta
)))
566 allow
= (allow
|| (delem
->uid
== request
->uid
));
571 return bestDelta
== -1 ? mDNStrue
: allow
;
575 // ***************************************************************************
576 #if COMPILER_LIKES_PRAGMA_MARK
578 #pragma mark - external helpers
581 mDNSlocal
void external_start_advertising_helper(service_instance
*const instance
)
583 AuthRecord
*st
= instance
->subtypes
;
584 ExtraResourceRecord
*e
;
587 if (mDNSIPPortIsZero(instance
->request
->u
.servicereg
.port
))
589 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
593 if (instance
->external_advertise
) LogMsg("external_start_advertising_helper: external_advertise already set!");
595 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
596 external_start_advertising_service(&st
[i
].resrec
);
598 external_start_advertising_service(&instance
->srs
.RR_PTR
.resrec
);
599 external_start_advertising_service(&instance
->srs
.RR_TXT
.resrec
);
601 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
602 external_start_advertising_service(&e
->r
.resrec
);
604 instance
->external_advertise
= mDNStrue
;
607 mDNSlocal
void external_stop_advertising_helper(service_instance
*const instance
)
609 AuthRecord
*st
= instance
->subtypes
;
610 ExtraResourceRecord
*e
;
613 if (!instance
->external_advertise
) return;
615 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
616 external_start_advertising_service(&st
[i
].resrec
);
618 external_stop_advertising_service(&instance
->srs
.RR_PTR
.resrec
);
619 external_stop_advertising_service(&instance
->srs
.RR_TXT
.resrec
);
621 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
622 external_stop_advertising_service(&e
->r
.resrec
);
624 instance
->external_advertise
= mDNSfalse
;
627 // ***************************************************************************
628 #if COMPILER_LIKES_PRAGMA_MARK
630 #pragma mark - DNSServiceRegister
633 mDNSexport
void FreeExtraRR(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
635 ExtraResourceRecord
*extra
= (ExtraResourceRecord
*)rr
->RecordContext
;
638 if (result
!= mStatus_MemFree
) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result
); return; }
640 LogInfo(" FreeExtraRR %s", RRDisplayString(m
, &rr
->resrec
));
642 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
)
643 freeL("Extra RData", rr
->resrec
.rdata
);
644 freeL("ExtraResourceRecord/FreeExtraRR", extra
);
647 mDNSlocal
void unlink_and_free_service_instance(service_instance
*srv
)
649 ExtraResourceRecord
*e
= srv
->srs
.Extras
, *tmp
;
651 external_stop_advertising_helper(srv
);
653 // clear pointers from parent struct
656 service_instance
**p
= &srv
->request
->u
.servicereg
.instances
;
659 if (*p
== srv
) { *p
= (*p
)->next
; break; }
666 e
->r
.RecordContext
= e
;
669 FreeExtraRR(&mDNSStorage
, &tmp
->r
, mStatus_MemFree
);
672 if (srv
->srs
.RR_TXT
.resrec
.rdata
!= &srv
->srs
.RR_TXT
.rdatastorage
)
673 freeL("TXT RData", srv
->srs
.RR_TXT
.resrec
.rdata
);
675 if (srv
->subtypes
) { freeL("ServiceSubTypes", srv
->subtypes
); srv
->subtypes
= NULL
; }
676 freeL("service_instance", srv
);
679 // Count how many other service records we have locally with the same name, but different rdata.
680 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
681 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
682 mDNSexport
int CountPeerRegistrations(mDNS
*const m
, ServiceRecordSet
*const srs
)
685 ResourceRecord
*r
= &srs
->RR_SRV
.resrec
;
688 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
689 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& SameDomainName(rr
->resrec
.name
, r
->name
) && !IdenticalSameNameRecord(&rr
->resrec
, r
))
692 verbosedebugf("%d peer registrations for %##s", count
, r
->name
->c
);
696 mDNSexport
int CountExistingRegistrations(domainname
*srv
, mDNSIPPort port
)
700 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
701 if (rr
->resrec
.rrtype
== kDNSType_SRV
&&
702 mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, port
) &&
703 SameDomainName(rr
->resrec
.name
, srv
))
708 mDNSlocal
void SendServiceRemovalNotification(ServiceRecordSet
*const srs
)
711 service_instance
*instance
= srs
->ServiceContext
;
712 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, 0, mStatus_NoError
) != mStatus_NoError
)
713 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
714 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNSfalse
; }
717 // service registration callback performs three duties - frees memory for deregistered services,
718 // handles name conflicts, and delivers completed registration information to the client
719 mDNSlocal
void regservice_callback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
722 mDNSBool SuppressError
= mDNSfalse
;
723 service_instance
*instance
;
727 if (!srs
) { LogMsg("regservice_callback: srs is NULL %d", result
); return; }
729 instance
= srs
->ServiceContext
;
730 if (!instance
) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result
); return; }
732 // don't send errors up to client for wide-area, empty-string registrations
733 if (instance
->request
&&
734 instance
->request
->u
.servicereg
.default_domain
&&
735 !instance
->default_local
)
736 SuppressError
= mDNStrue
;
738 if (mDNS_LoggingEnabled
)
740 const char *const fmt
=
741 (result
== mStatus_NoError
) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
742 (result
== mStatus_MemFree
) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
743 (result
== mStatus_NameConflict
) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
744 "%s DNSServiceRegister(%##s, %u) %s %d";
745 char prefix
[16] = "---:";
746 if (instance
->request
) mDNS_snprintf(prefix
, sizeof(prefix
), "%3d:", instance
->request
->sd
);
747 LogOperation(fmt
, prefix
, srs
->RR_SRV
.resrec
.name
->c
, mDNSVal16(srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
),
748 SuppressError
? "suppressed error" : "CALLBACK", result
);
751 if (!instance
->request
&& result
!= mStatus_MemFree
) { LogMsg("regservice_callback: instance->request is NULL %d", result
); return; }
753 if (result
== mStatus_NoError
)
755 if (instance
->request
->u
.servicereg
.allowremotequery
)
757 ExtraResourceRecord
*e
;
758 srs
->RR_ADV
.AllowRemoteQuery
= mDNStrue
;
759 srs
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
760 srs
->RR_SRV
.AllowRemoteQuery
= mDNStrue
;
761 srs
->RR_TXT
.AllowRemoteQuery
= mDNStrue
;
762 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
) e
->r
.AllowRemoteQuery
= mDNStrue
;
765 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
766 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
767 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
769 if (instance
->request
->u
.servicereg
.InterfaceID
== mDNSInterface_P2P
|| (!instance
->request
->u
.servicereg
.InterfaceID
&& SameDomainName(&instance
->domain
, &localdomain
)))
770 external_start_advertising_helper(instance
);
771 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(m
, srs
) == 0)
772 RecordUpdatedNiceLabel(m
, 0); // Successfully got new name, tell user immediately
774 else if (result
== mStatus_MemFree
)
776 if (instance
->request
&& instance
->renameonmemfree
)
778 external_stop_advertising_helper(instance
);
779 instance
->renameonmemfree
= 0;
780 err
= mDNS_RenameAndReregisterService(m
, srs
, &instance
->request
->u
.servicereg
.name
);
781 if (err
) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err
);
782 // error should never happen - safest to log and continue
785 unlink_and_free_service_instance(instance
);
787 else if (result
== mStatus_NameConflict
)
789 if (instance
->request
->u
.servicereg
.autorename
)
791 external_stop_advertising_helper(instance
);
792 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(m
, srs
) == 0)
794 // On conflict for an autoname service, rename and reregister *all* autoname services
795 IncrementLabelSuffix(&m
->nicelabel
, mDNStrue
);
796 mDNS_ConfigChanged(m
); // Will call back into udsserver_handle_configchange()
798 else // On conflict for a non-autoname service, rename and reregister just that one service
800 if (instance
->clientnotified
) SendServiceRemovalNotification(srs
);
801 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
808 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
809 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
810 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
812 unlink_and_free_service_instance(instance
);
815 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
819 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
820 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
821 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
826 mDNSlocal
void regrecord_callback(mDNS
*const m
, AuthRecord
*rr
, mStatus result
)
829 if (!rr
->RecordContext
) // parent struct already freed by termination callback
831 if (result
== mStatus_NoError
)
832 LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m
, rr
));
835 if (result
!= mStatus_MemFree
) LogMsg("regrecord_callback: error %d received after parent termination", result
);
836 freeL("AuthRecord/regrecord_callback", rr
);
841 registered_record_entry
*re
= rr
->RecordContext
;
842 request_state
*request
= re
->request
;
844 if (mDNS_LoggingEnabled
)
846 char *fmt
= (result
== mStatus_NoError
) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
847 (result
== mStatus_MemFree
) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
848 (result
== mStatus_NameConflict
) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
849 "%3d: DNSServiceRegisterRecord(%u %s) %d";
850 LogOperation(fmt
, request
->sd
, re
->key
, RRDisplayString(m
, &rr
->resrec
), result
);
853 if (result
!= mStatus_MemFree
)
855 int len
= sizeof(DNSServiceFlags
) + sizeof(mDNSu32
) + sizeof(DNSServiceErrorType
);
856 reply_state
*reply
= create_reply(reg_record_reply_op
, len
, request
);
857 reply
->mhdr
->client_context
= re
->regrec_client_context
;
858 reply
->rhdr
->flags
= dnssd_htonl(0);
859 reply
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, rr
->resrec
.InterfaceID
));
860 reply
->rhdr
->error
= dnssd_htonl(result
);
861 append_reply(request
, reply
);
866 // unlink from list, free memory
867 registered_record_entry
**ptr
= &request
->u
.reg_recs
;
868 while (*ptr
&& (*ptr
) != re
) ptr
= &(*ptr
)->next
;
869 if (!*ptr
) { LogMsg("regrecord_callback - record not in list!"); return; }
871 freeL("registered_record_entry AuthRecord regrecord_callback", re
->rr
);
872 freeL("registered_record_entry regrecord_callback", re
);
876 if (re
->external_advertise
) LogMsg("regrecord_callback: external_advertise already set!");
877 if (re
->origInterfaceID
== mDNSInterface_P2P
|| (!re
->origInterfaceID
&& IsLocalDomain(&rr
->namestorage
)))
879 external_start_advertising_service(&rr
->resrec
);
880 re
->external_advertise
= mDNStrue
;
886 mDNSlocal
void connection_termination(request_state
*request
)
888 // When terminating a shared connection, we need to scan the all_requests list
889 // and terminate any subbordinate operations sharing this file descriptor
890 request_state
**req
= &all_requests
;
892 LogOperation("%3d: DNSServiceCreateConnection STOP", request
->sd
);
896 if ((*req
)->primary
== request
)
898 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
899 request_state
*tmp
= *req
;
900 if (tmp
->primary
== tmp
) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp
, tmp
->sd
);
901 if (tmp
->replies
) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp
, tmp
->sd
);
904 freeL("request_state/connection_termination", tmp
);
910 while (request
->u
.reg_recs
)
912 registered_record_entry
*ptr
= request
->u
.reg_recs
;
913 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP", request
->sd
, ptr
->key
, RRDisplayString(&mDNSStorage
, &ptr
->rr
->resrec
));
914 request
->u
.reg_recs
= request
->u
.reg_recs
->next
;
915 ptr
->rr
->RecordContext
= NULL
;
916 if (ptr
->external_advertise
)
918 ptr
->external_advertise
= mDNSfalse
;
919 external_stop_advertising_service(&ptr
->rr
->resrec
);
921 mDNS_Deregister(&mDNSStorage
, ptr
->rr
); // Will free ptr->rr for us
922 freeL("registered_record_entry/connection_termination", ptr
);
926 mDNSlocal
void handle_cancel_request(request_state
*request
)
928 request_state
**req
= &all_requests
;
929 LogOperation("%3d: Cancel %08X %08X", request
->sd
, request
->hdr
.client_context
.u32
[1], request
->hdr
.client_context
.u32
[0]);
932 if ((*req
)->primary
== request
&&
933 (*req
)->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
934 (*req
)->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1])
936 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
937 request_state
*tmp
= *req
;
940 freeL("request_state/handle_cancel_request", tmp
);
947 mDNSlocal mStatus
handle_regrecord_request(request_state
*request
)
949 mStatus err
= mStatus_BadParamErr
;
950 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 1, 1);
953 // allocate registration entry, link into list
954 registered_record_entry
*re
= mallocL("registered_record_entry", sizeof(registered_record_entry
));
955 if (!re
) FatalError("ERROR: malloc");
956 re
->key
= request
->hdr
.reg_index
;
958 re
->regrec_client_context
= request
->hdr
.client_context
;
959 re
->request
= request
;
960 re
->external_advertise
= mDNSfalse
;
961 rr
->RecordContext
= re
;
962 rr
->RecordCallback
= regrecord_callback
;
964 re
->next
= request
->u
.reg_recs
;
965 request
->u
.reg_recs
= re
;
967 re
->origInterfaceID
= rr
->resrec
.InterfaceID
;
968 if (rr
->resrec
.InterfaceID
== mDNSInterface_P2P
) rr
->resrec
.InterfaceID
= mDNSInterface_Any
;
970 if (!AuthorizedDomain(request
, rr
->resrec
.name
, AutoRegistrationDomains
)) return (mStatus_NoError
);
972 if (rr
->resrec
.rroriginalttl
== 0)
973 rr
->resrec
.rroriginalttl
= DefaultTTLforRRType(rr
->resrec
.rrtype
);
975 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START", request
->sd
, re
->key
, RRDisplayString(&mDNSStorage
, &rr
->resrec
));
976 err
= mDNS_Register(&mDNSStorage
, rr
);
981 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
);
983 mDNSlocal
void regservice_termination_callback(request_state
*request
)
985 if (!request
) { LogMsg("regservice_termination_callback context is NULL"); return; }
986 while (request
->u
.servicereg
.instances
)
988 service_instance
*p
= request
->u
.servicereg
.instances
;
989 request
->u
.servicereg
.instances
= request
->u
.servicereg
.instances
->next
;
990 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
991 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP",
992 request
->sd
, p
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(p
->srs
.RR_SRV
.resrec
.rdata
->u
.srv
.port
));
994 external_stop_advertising_helper(p
);
996 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
997 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
998 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
999 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1000 // because by then we might have already freed p
1002 if (mDNS_DeregisterService(&mDNSStorage
, &p
->srs
)) unlink_and_free_service_instance(p
);
1003 // Don't touch service_instance *p after this -- it's likely to have been freed already
1005 if (request
->u
.servicereg
.txtdata
)
1006 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1007 if (request
->u
.servicereg
.autoname
)
1009 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1010 request
->u
.servicereg
.autoname
= mDNSfalse
;
1011 UpdateDeviceInfoRecord(&mDNSStorage
);
1015 mDNSlocal request_state
*LocateSubordinateRequest(request_state
*request
)
1018 for (req
= all_requests
; req
; req
= req
->next
)
1019 if (req
->primary
== request
&&
1020 req
->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1021 req
->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1]) return(req
);
1025 mDNSlocal mStatus
add_record_to_service(request_state
*request
, service_instance
*instance
, mDNSu16 rrtype
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
)
1027 ServiceRecordSet
*srs
= &instance
->srs
;
1029 int size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1030 ExtraResourceRecord
*extra
= mallocL("ExtraResourceRecord", sizeof(*extra
) - sizeof(RDataBody
) + size
);
1031 if (!extra
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1033 mDNSPlatformMemZero(extra
, sizeof(ExtraResourceRecord
)); // OK if oversized rdata not zero'd
1034 extra
->r
.resrec
.rrtype
= rrtype
;
1035 extra
->r
.rdatastorage
.MaxRDLength
= (mDNSu16
) size
;
1036 extra
->r
.resrec
.rdlength
= rdlen
;
1037 mDNSPlatformMemCopy(&extra
->r
.rdatastorage
.u
.data
, rdata
, rdlen
);
1039 result
= mDNS_AddRecordToService(&mDNSStorage
, srs
, extra
, &extra
->r
.rdatastorage
, ttl
);
1040 if (result
) { freeL("ExtraResourceRecord/add_record_to_service", extra
); return result
; }
1042 extra
->ClientID
= request
->hdr
.reg_index
;
1043 if (instance
->external_advertise
&& (instance
->request
->u
.servicereg
.InterfaceID
== mDNSInterface_P2P
|| (!instance
->request
->u
.servicereg
.InterfaceID
&& SameDomainName(&instance
->domain
, &localdomain
))))
1044 external_start_advertising_service(&extra
->r
.resrec
);
1048 mDNSlocal mStatus
handle_add_request(request_state
*request
)
1050 service_instance
*i
;
1051 mStatus result
= mStatus_UnknownErr
;
1052 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
);
1053 mDNSu16 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
1054 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1055 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1056 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1057 if (!ttl
) ttl
= DefaultTTLforRRType(rrtype
);
1058 (void)flags
; // Unused
1060 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1062 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1063 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1065 if (request
->terminate
!= regservice_termination_callback
)
1066 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1068 LogOperation("%3d: DNSServiceAddRecord(%##s, %s, %d)", request
->sd
,
1069 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
, DNSTypeName(rrtype
), rdlen
);
1071 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1073 result
= add_record_to_service(request
, i
, rrtype
, rdlen
, rdata
, ttl
);
1074 if (result
&& i
->default_local
) break;
1075 else result
= mStatus_NoError
; // suppress non-local default errors
1081 mDNSlocal
void update_callback(mDNS
*const m
, AuthRecord
*const rr
, RData
*oldrd
, mDNSu16 oldrdlen
)
1083 mDNSBool external_advertise
= (rr
->UpdateContext
) ? *((mDNSBool
*)rr
->UpdateContext
) : mDNSfalse
;
1086 // There are three cases.
1088 // 1. We have updated the primary TXT record of the service
1089 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1090 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1092 // external_advertise is set if we have advertised at least once during the initial addition
1093 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1094 // checks during the first time and hence we don't do any checks here
1095 if (external_advertise
)
1097 ResourceRecord ext
= rr
->resrec
;
1098 if (ext
.rdlength
== oldrdlen
&& mDNSPlatformMemSame(&ext
.rdata
->u
, &oldrd
->u
, oldrdlen
)) goto exit
;
1099 SetNewRData(&ext
, oldrd
, oldrdlen
);
1100 external_stop_advertising_service(&ext
);
1101 external_start_advertising_service(&rr
->resrec
);
1104 if (oldrd
!= &rr
->rdatastorage
) freeL("RData/update_callback", oldrd
);
1107 mDNSlocal mStatus
update_record(AuthRecord
*rr
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
, const mDNSBool
*const external_advertise
)
1110 const int rdsize
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1111 RData
*newrd
= mallocL("RData/update_record", sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
1112 if (!newrd
) FatalError("ERROR: malloc");
1113 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
1114 mDNSPlatformMemCopy(&newrd
->u
, rdata
, rdlen
);
1116 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1117 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1118 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1119 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rdlen
== 0) { rdlen
= 1; newrd
->u
.txt
.c
[0] = 0; }
1121 if (external_advertise
) rr
->UpdateContext
= (void *)external_advertise
;
1123 result
= mDNS_Update(&mDNSStorage
, rr
, ttl
, rdlen
, newrd
, update_callback
);
1124 if (result
) { LogMsg("update_record: Error %d for %s", (int)result
, ARDisplayString(&mDNSStorage
, rr
)); freeL("RData/update_record", newrd
); }
1128 mDNSlocal mStatus
handle_update_request(request_state
*request
)
1130 const ipc_msg_hdr
*const hdr
= &request
->hdr
;
1131 mStatus result
= mStatus_BadReferenceErr
;
1132 service_instance
*i
;
1133 AuthRecord
*rr
= NULL
;
1135 // get the message data
1136 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
); // flags unused
1137 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1138 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1139 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1140 (void)flags
; // Unused
1142 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1144 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1145 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1147 if (request
->terminate
== connection_termination
)
1149 // update an individually registered record
1150 registered_record_entry
*reptr
;
1151 for (reptr
= request
->u
.reg_recs
; reptr
; reptr
= reptr
->next
)
1153 if (reptr
->key
== hdr
->reg_index
)
1155 result
= update_record(reptr
->rr
, rdlen
, rdata
, ttl
, &reptr
->external_advertise
);
1156 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)",
1157 request
->sd
, reptr
->rr
->resrec
.name
->c
, reptr
->rr
? DNSTypeName(reptr
->rr
->resrec
.rrtype
) : "<NONE>");
1161 result
= mStatus_BadReferenceErr
;
1165 if (request
->terminate
!= regservice_termination_callback
)
1166 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1168 // update the saved off TXT data for the service
1169 if (hdr
->reg_index
== TXT_RECORD_INDEX
)
1171 if (request
->u
.servicereg
.txtdata
)
1172 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1175 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", rdlen
);
1176 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_update_request - malloc");
1177 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, rdata
, rdlen
);
1179 request
->u
.servicereg
.txtlen
= rdlen
;
1182 // update a record from a service record set
1183 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1185 if (hdr
->reg_index
== TXT_RECORD_INDEX
) rr
= &i
->srs
.RR_TXT
;
1188 ExtraResourceRecord
*e
;
1189 for (e
= i
->srs
.Extras
; e
; e
= e
->next
)
1190 if (e
->ClientID
== hdr
->reg_index
) { rr
= &e
->r
; break; }
1193 if (!rr
) { result
= mStatus_BadReferenceErr
; goto end
; }
1194 result
= update_record(rr
, rdlen
, rdata
, ttl
, &i
->external_advertise
);
1195 if (result
&& i
->default_local
) goto end
;
1196 else result
= mStatus_NoError
; // suppress non-local default errors
1200 if (request
->terminate
== regservice_termination_callback
)
1201 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request
->sd
,
1202 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1203 rr
? DNSTypeName(rr
->resrec
.rrtype
) : "<NONE>");
1208 // remove a resource record registered via DNSServiceRegisterRecord()
1209 mDNSlocal mStatus
remove_record(request_state
*request
)
1211 mStatus err
= mStatus_UnknownErr
;
1212 registered_record_entry
*e
, **ptr
= &request
->u
.reg_recs
;
1214 while (*ptr
&& (*ptr
)->key
!= request
->hdr
.reg_index
) ptr
= &(*ptr
)->next
;
1215 if (!*ptr
) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request
->sd
, request
->hdr
.reg_index
); return mStatus_BadReferenceErr
; }
1217 *ptr
= e
->next
; // unlink
1219 LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request
->sd
, e
->key
, RRDisplayString(&mDNSStorage
, &e
->rr
->resrec
));
1220 e
->rr
->RecordContext
= NULL
;
1221 if (e
->external_advertise
)
1223 external_stop_advertising_service(&e
->rr
->resrec
);
1224 e
->external_advertise
= mDNSfalse
;
1226 err
= mDNS_Deregister(&mDNSStorage
, e
->rr
); // Will free e->rr for us; we're responsible for freeing e
1229 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err
);
1230 freeL("registered_record_entry AuthRecord remove_record", e
->rr
);
1233 freeL("registered_record_entry remove_record", e
);
1237 mDNSlocal mStatus
remove_extra(const request_state
*const request
, service_instance
*const serv
, mDNSu16
*const rrtype
)
1239 mStatus err
= mStatus_BadReferenceErr
;
1240 ExtraResourceRecord
*ptr
;
1242 for (ptr
= serv
->srs
.Extras
; ptr
; ptr
= ptr
->next
)
1244 if (ptr
->ClientID
== request
->hdr
.reg_index
) // found match
1246 *rrtype
= ptr
->r
.resrec
.rrtype
;
1247 if (serv
->external_advertise
) external_stop_advertising_service(&ptr
->r
.resrec
);
1248 err
= mDNS_RemoveRecordFromService(&mDNSStorage
, &serv
->srs
, ptr
, FreeExtraRR
, ptr
);
1255 mDNSlocal mStatus
handle_removerecord_request(request_state
*request
)
1257 mStatus err
= mStatus_BadReferenceErr
;
1258 get_flags(&request
->msgptr
, request
->msgend
); // flags unused
1260 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1262 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1263 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1265 if (request
->terminate
== connection_termination
)
1266 err
= remove_record(request
); // remove individually registered record
1267 else if (request
->terminate
!= regservice_termination_callback
)
1268 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1271 service_instance
*i
;
1273 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request
->sd
,
1274 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1275 rrtype
? DNSTypeName(rrtype
) : "<NONE>");
1276 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1278 err
= remove_extra(request
, i
, &rrtype
);
1279 if (err
&& i
->default_local
) break;
1280 else err
= mStatus_NoError
; // suppress non-local default errors
1287 // If there's a comma followed by another character,
1288 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1289 // Otherwise, it returns a pointer to the final nul at the end of the string
1290 mDNSlocal
char *FindFirstSubType(char *p
)
1294 if (p
[0] == '\\' && p
[1]) p
+= 2;
1295 else if (p
[0] == ',' && p
[1]) { *p
++ = 0; return(p
); }
1301 // If there's a comma followed by another character,
1302 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1303 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1304 // Otherwise, it returns a pointer to the final nul at the end of the string
1305 mDNSlocal
char *FindNextSubType(char *p
)
1309 if (p
[0] == '\\' && p
[1]) // If escape character
1310 p
+= 2; // ignore following character
1311 else if (p
[0] == ',') // If we found a comma
1316 else if (p
[0] == '.')
1323 // Returns -1 if illegal subtype found
1324 mDNSexport mDNSs32
ChopSubTypes(char *regtype
)
1326 mDNSs32 NumSubTypes
= 0;
1327 char *stp
= FindFirstSubType(regtype
);
1328 while (stp
&& *stp
) // If we found a comma...
1330 if (*stp
== ',') return(-1);
1332 stp
= FindNextSubType(stp
);
1334 if (!stp
) return(-1);
1335 return(NumSubTypes
);
1338 mDNSexport AuthRecord
*AllocateSubTypes(mDNSs32 NumSubTypes
, char *p
)
1340 AuthRecord
*st
= mDNSNULL
;
1344 st
= mallocL("ServiceSubTypes", NumSubTypes
* sizeof(AuthRecord
));
1345 if (!st
) return(mDNSNULL
);
1346 for (i
= 0; i
< NumSubTypes
; i
++)
1348 mDNS_SetupResourceRecord(&st
[i
], mDNSNULL
, mDNSInterface_Any
, kDNSQType_ANY
, kStandardTTL
, 0, mDNSNULL
, mDNSNULL
);
1351 if (!MakeDomainNameFromDNSNameString(&st
[i
].namestorage
, p
))
1352 { freeL("ServiceSubTypes", st
); return(mDNSNULL
); }
1358 mDNSlocal mStatus
register_service_instance(request_state
*request
, const domainname
*domain
)
1360 service_instance
**ptr
, *instance
;
1361 const int extra_size
= (request
->u
.servicereg
.txtlen
> sizeof(RDataBody
)) ? (request
->u
.servicereg
.txtlen
- sizeof(RDataBody
)) : 0;
1362 const mDNSBool DomainIsLocal
= SameDomainName(domain
, &localdomain
);
1364 mDNSInterfaceID interfaceID
= request
->u
.servicereg
.InterfaceID
;
1366 if (interfaceID
== mDNSInterface_P2P
) interfaceID
= mDNSInterface_Any
;
1368 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1369 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1370 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1371 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1372 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1373 if (request
->u
.servicereg
.default_domain
&& !DomainIsLocal
) interfaceID
= mDNSInterface_Any
;
1375 for (ptr
= &request
->u
.servicereg
.instances
; *ptr
; ptr
= &(*ptr
)->next
)
1377 if (SameDomainName(&(*ptr
)->domain
, domain
))
1379 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1380 domain
->c
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
);
1381 return mStatus_AlreadyRegistered
;
1385 if (mDNSStorage
.KnownBugs
& mDNS_KnownBug_LimitedIPv6
)
1387 // Special-case hack: On Mac OS X 10.6.x and earlier we don't advertise SMB service in AutoTunnel domains,
1388 // because AutoTunnel services have to support IPv6, and in Mac OS X 10.6.x the SMB server does not.
1389 // <rdar://problem/5482322> BTMM: Don't advertise SMB with BTMM because it doesn't support IPv6
1390 if (SameDomainName(&request
->u
.servicereg
.type
, (const domainname
*) "\x4" "_smb" "\x4" "_tcp"))
1392 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName(&mDNSStorage
, domain
);
1393 if (AuthInfo
&& AuthInfo
->AutoTunnel
) return(kDNSServiceErr_Unsupported
);
1397 instance
= mallocL("service_instance", sizeof(*instance
) + extra_size
);
1398 if (!instance
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1400 instance
->next
= mDNSNULL
;
1401 instance
->request
= request
;
1402 instance
->subtypes
= AllocateSubTypes(request
->u
.servicereg
.num_subtypes
, request
->u
.servicereg
.type_as_string
);
1403 instance
->renameonmemfree
= 0;
1404 instance
->clientnotified
= mDNSfalse
;
1405 instance
->default_local
= (request
->u
.servicereg
.default_domain
&& DomainIsLocal
);
1406 instance
->external_advertise
= mDNSfalse
;
1407 AssignDomainName(&instance
->domain
, domain
);
1409 if (request
->u
.servicereg
.num_subtypes
&& !instance
->subtypes
)
1410 { unlink_and_free_service_instance(instance
); instance
= NULL
; FatalError("ERROR: malloc"); }
1412 result
= mDNS_RegisterService(&mDNSStorage
, &instance
->srs
,
1413 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
,
1414 request
->u
.servicereg
.host
.c
[0] ? &request
->u
.servicereg
.host
: NULL
,
1415 request
->u
.servicereg
.port
,
1416 request
->u
.servicereg
.txtdata
, request
->u
.servicereg
.txtlen
,
1417 instance
->subtypes
, request
->u
.servicereg
.num_subtypes
,
1418 interfaceID
, regservice_callback
, instance
);
1422 *ptr
= instance
; // Append this to the end of our request->u.servicereg.instances list
1423 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED",
1424 instance
->request
->sd
, instance
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(request
->u
.servicereg
.port
));
1428 LogMsg("register_service_instance %#s.%##s%##s error %d",
1429 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
->c
, result
);
1430 unlink_and_free_service_instance(instance
);
1436 mDNSlocal
void udsserver_default_reg_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
1438 request_state
*request
;
1440 #if APPLE_OSX_mDNSResponder
1441 machserver_automatic_registration_domain_changed(&d
->name
, add
);
1442 #endif // APPLE_OSX_mDNSResponder
1444 LogMsg("%s registration domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
1445 for (request
= all_requests
; request
; request
= request
->next
)
1447 if (request
->terminate
!= regservice_termination_callback
) continue;
1448 if (!request
->u
.servicereg
.default_domain
) continue;
1449 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
1451 service_instance
**ptr
= &request
->u
.servicereg
.instances
;
1452 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
1455 // If we don't already have this domain in our list for this registration, add it now
1456 if (!*ptr
) register_service_instance(request
, &d
->name
);
1457 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d
->name
);
1461 // Normally we should not fail to find the specified instance
1462 // One case where this can happen is if a uDNS update fails for some reason,
1463 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1465 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1466 &d
->name
, request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type_as_string
);
1470 for (p
= AutoRegistrationDomains
; p
; p
=p
->next
)
1471 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
1472 if (SameDomainName(&d
->name
, &p
->name
)) break;
1473 if (p
) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d
->name
);
1477 service_instance
*si
= *ptr
;
1479 if (si
->clientnotified
) SendServiceRemovalNotification(&si
->srs
); // Do this *before* clearing si->request backpointer
1480 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1481 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1482 // process of completing asynchronously, the client cancels the entire operation, so
1483 // regservice_termination_callback then runs through the whole list deregistering each
1484 // instance, clearing the backpointers, and then disposing the parent request_state object.
1485 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1486 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1487 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1488 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1490 err
= mDNS_DeregisterService(&mDNSStorage
, &si
->srs
);
1491 if (err
) { LogMsg("udsserver_default_reg_domain_changed err %d", err
); unlink_and_free_service_instance(si
); }
1499 mDNSlocal mStatus
handle_regservice_request(request_state
*request
)
1501 char name
[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1502 char domain
[MAX_ESCAPED_DOMAIN_NAME
], host
[MAX_ESCAPED_DOMAIN_NAME
];
1503 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
];
1507 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
1508 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
1509 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
1510 if (interfaceIndex
&& !InterfaceID
)
1511 { LogMsg("ERROR: handle_regservice_request - Couldn't find interfaceIndex %d", interfaceIndex
); return(mStatus_BadParamErr
); }
1513 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
1514 get_string(&request
->msgptr
, request
->msgend
, type_as_string
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
1515 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
1516 get_string(&request
->msgptr
, request
->msgend
, host
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
1517 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
1519 request
->u
.servicereg
.InterfaceID
= InterfaceID
;
1520 request
->u
.servicereg
.instances
= NULL
;
1521 request
->u
.servicereg
.txtlen
= 0;
1522 request
->u
.servicereg
.txtdata
= NULL
;
1523 mDNSPlatformStrCopy(request
->u
.servicereg
.type_as_string
, type_as_string
);
1525 if (request
->msgptr
+ 2 > request
->msgend
) request
->msgptr
= NULL
;
1528 request
->u
.servicereg
.port
.b
[0] = *request
->msgptr
++;
1529 request
->u
.servicereg
.port
.b
[1] = *request
->msgptr
++;
1532 request
->u
.servicereg
.txtlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1533 if (request
->u
.servicereg
.txtlen
)
1535 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", request
->u
.servicereg
.txtlen
);
1536 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_regservice_request - malloc");
1537 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, get_rdata(&request
->msgptr
, request
->msgend
, request
->u
.servicereg
.txtlen
), request
->u
.servicereg
.txtlen
);
1540 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1542 // Check for sub-types after the service type
1543 request
->u
.servicereg
.num_subtypes
= ChopSubTypes(request
->u
.servicereg
.type_as_string
); // Note: Modifies regtype string to remove trailing subtypes
1544 if (request
->u
.servicereg
.num_subtypes
< 0)
1545 { LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request
->u
.servicereg
.type_as_string
); return(mStatus_BadParamErr
); }
1547 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1548 if (!*request
->u
.servicereg
.type_as_string
|| !MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.type
, request
->u
.servicereg
.type_as_string
))
1549 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request
->u
.servicereg
.type_as_string
); return(mStatus_BadParamErr
); }
1553 request
->u
.servicereg
.name
= mDNSStorage
.nicelabel
;
1554 request
->u
.servicereg
.autoname
= mDNStrue
;
1558 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1559 if ((flags
& kDNSServiceFlagsNoAutoRename
) == 0)
1561 int newlen
= TruncateUTF8ToLength((mDNSu8
*)name
, mDNSPlatformStrLen(name
), MAX_DOMAIN_LABEL
);
1564 if (!MakeDomainLabelFromLiteralString(&request
->u
.servicereg
.name
, name
))
1565 { LogMsg("ERROR: handle_regservice_request - name bad %s", name
); return(mStatus_BadParamErr
); }
1566 request
->u
.servicereg
.autoname
= mDNSfalse
;
1571 request
->u
.servicereg
.default_domain
= mDNSfalse
;
1572 if (!MakeDomainNameFromDNSNameString(&d
, domain
))
1573 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain
); return(mStatus_BadParamErr
); }
1577 request
->u
.servicereg
.default_domain
= mDNStrue
;
1578 MakeDomainNameFromDNSNameString(&d
, "local.");
1581 if (!ConstructServiceName(&srv
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, &d
))
1583 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1584 request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type
.c
, d
.c
); return(mStatus_BadParamErr
);
1587 if (!MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.host
, host
))
1588 { LogMsg("ERROR: handle_regservice_request - host bad %s", host
); return(mStatus_BadParamErr
); }
1589 request
->u
.servicereg
.autorename
= (flags
& kDNSServiceFlagsNoAutoRename
) == 0;
1590 request
->u
.servicereg
.allowremotequery
= (flags
& kDNSServiceFlagsAllowRemoteQuery
) != 0;
1592 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1593 // a port number of zero. When two instances of the protected client are allowed to run on one
1594 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1595 if (!mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1597 int count
= CountExistingRegistrations(&srv
, request
->u
.servicereg
.port
);
1599 LogMsg("Client application registered %d identical instances of service %##s port %u.",
1600 count
+1, srv
.c
, mDNSVal16(request
->u
.servicereg
.port
));
1603 LogOperation("%3d: DNSServiceRegister(\"%s\", \"%s\", \"%s\", \"%s\", %u) START",
1604 request
->sd
, name
, request
->u
.servicereg
.type_as_string
, domain
, host
, mDNSVal16(request
->u
.servicereg
.port
));
1606 // We need to unconditionally set request->terminate, because even if we didn't successfully
1607 // start any registrations right now, subsequent configuration changes may cause successful
1608 // registrations to be added, and we'll need to cancel them before freeing this memory.
1609 // We also need to set request->terminate first, before adding additional service instances,
1610 // because the uds_validatelists uses the request->terminate function pointer to determine
1611 // what kind of request this is, and therefore what kind of list validation is required.
1612 request
->terminate
= regservice_termination_callback
;
1614 err
= register_service_instance(request
, &d
);
1617 err
= AuthorizedDomain(request
, &d
, AutoRegistrationDomains
) ? register_service_instance(request
, &d
) : mStatus_NoError
;
1621 if (request
->u
.servicereg
.autoname
) UpdateDeviceInfoRecord(&mDNSStorage
);
1626 // Note that we don't report errors for non-local, non-explicit domains
1627 for (ptr
= AutoRegistrationDomains
; ptr
; ptr
= ptr
->next
)
1628 if (!ptr
->uid
|| SystemUID(request
->uid
) || request
->uid
== ptr
->uid
)
1629 register_service_instance(request
, &ptr
->name
);
1636 // ***************************************************************************
1637 #if COMPILER_LIKES_PRAGMA_MARK
1639 #pragma mark - DNSServiceBrowse
1642 mDNSlocal
void FoundInstance(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
1644 const DNSServiceFlags flags
= AddRecord
? kDNSServiceFlagsAdd
: 0;
1645 request_state
*req
= question
->QuestionContext
;
1649 if (answer
->rrtype
!= kDNSType_PTR
)
1650 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req
->sd
, answer
->rrtype
); return; }
1652 if (GenerateNTDResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
) != mStatus_NoError
)
1654 if (SameDomainName(&req
->u
.browser
.regtype
, (const domainname
*)"\x09_services\x07_dns-sd\x04_udp"))
1656 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
1657 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
1658 GenerateBonjourBrowserResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
);
1659 goto bonjourbrowserhack
;
1662 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
1663 req
->sd
, answer
->name
->c
, answer
->rdata
->u
.name
.c
);
1669 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
1670 req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "Add" : "Rmv",
1671 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
), RRDisplayString(m
, answer
));
1673 append_reply(req
, rep
);
1676 mDNSlocal mStatus
add_domain_to_browser(request_state
*info
, const domainname
*d
)
1681 for (p
= info
->u
.browser
.browsers
; p
; p
= p
->next
)
1683 if (SameDomainName(&p
->domain
, d
))
1684 { debugf("add_domain_to_browser %##s already in list", d
->c
); return mStatus_AlreadyRegistered
; }
1687 b
= mallocL("browser_t", sizeof(*b
));
1688 if (!b
) return mStatus_NoMemoryErr
;
1689 AssignDomainName(&b
->domain
, d
);
1690 err
= mDNS_StartBrowse(&mDNSStorage
, &b
->q
,
1691 &info
->u
.browser
.regtype
, d
, info
->u
.browser
.interface_id
, info
->u
.browser
.ForceMCast
, FoundInstance
, info
);
1694 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err
, info
->u
.browser
.regtype
.c
, d
->c
);
1695 freeL("browser_t/add_domain_to_browser", b
);
1699 b
->next
= info
->u
.browser
.browsers
;
1700 info
->u
.browser
.browsers
= b
;
1701 LogOperation("%3d: DNSServiceBrowse(%##s) START", info
->sd
, b
->q
.qname
.c
);
1702 if (info
->u
.browser
.interface_id
== mDNSInterface_P2P
|| (!info
->u
.browser
.interface_id
&& SameDomainName(&b
->domain
, &localdomain
)))
1705 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &b
->domain
);
1706 external_start_browsing_for_service(&mDNSStorage
, &tmp
, kDNSType_PTR
);
1712 mDNSlocal
void browse_termination_callback(request_state
*info
)
1714 while (info
->u
.browser
.browsers
)
1716 browser_t
*ptr
= info
->u
.browser
.browsers
;
1718 if (info
->u
.browser
.interface_id
== mDNSInterface_P2P
|| (!info
->u
.browser
.interface_id
&& SameDomainName(&ptr
->domain
, &localdomain
)))
1721 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &ptr
->domain
);
1722 external_stop_browsing_for_service(&mDNSStorage
, &tmp
, kDNSType_PTR
);
1725 info
->u
.browser
.browsers
= ptr
->next
;
1726 LogOperation("%3d: DNSServiceBrowse(%##s) STOP", info
->sd
, ptr
->q
.qname
.c
);
1727 mDNS_StopBrowse(&mDNSStorage
, &ptr
->q
); // no need to error-check result
1728 freeL("browser_t/browse_termination_callback", ptr
);
1732 mDNSlocal
void udsserver_automatic_browse_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
1734 request_state
*request
;
1735 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
1737 #if APPLE_OSX_mDNSResponder
1738 machserver_automatic_browse_domain_changed(&d
->name
, add
);
1739 #endif // APPLE_OSX_mDNSResponder
1741 for (request
= all_requests
; request
; request
= request
->next
)
1743 if (request
->terminate
!= browse_termination_callback
) continue; // Not a browse operation
1744 if (!request
->u
.browser
.default_domain
) continue; // Not an auto-browse operation
1745 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
1747 browser_t
**ptr
= &request
->u
.browser
.browsers
;
1748 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
1751 // If we don't already have this domain in our list for this browse operation, add it now
1752 if (!*ptr
) add_domain_to_browser(request
, &d
->name
);
1753 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d
->name
);
1757 if (!*ptr
) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d
->name
);
1761 for (p
= AutoBrowseDomains
; p
; p
=p
->next
)
1762 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
1763 if (SameDomainName(&d
->name
, &p
->name
)) break;
1764 if (p
) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d
->name
);
1767 browser_t
*rem
= *ptr
;
1768 *ptr
= (*ptr
)->next
;
1769 mDNS_StopQueryWithRemoves(&mDNSStorage
, &rem
->q
);
1770 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem
);
1778 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
1781 if (result
== mStatus_MemFree
)
1783 // On shutdown, mDNS_Close automatically deregisters all records
1784 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
1785 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
1786 // (This should actually no longer be necessary, now that we do the proper cleanup in
1787 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
1788 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
1789 ARListElem
**ptr
= &LocalDomainEnumRecords
;
1790 while (*ptr
&& &(*ptr
)->ar
!= rr
) ptr
= &(*ptr
)->next
;
1791 if (*ptr
) { *ptr
= (*ptr
)->next
; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m
, rr
)); }
1792 mDNSPlatformMemFree(rr
->RecordContext
);
1796 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
1797 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
1798 // We may want to turn the common code into a subroutine.
1800 mDNSlocal
void RegisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
1802 // allocate/register legacy and non-legacy _browse PTR record
1804 ARListElem
*ptr
= mDNSPlatformMemAllocate(sizeof(*ptr
));
1806 debugf("Incrementing %s refcount for %##s",
1807 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
1808 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
1809 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
1811 mDNS_SetupResourceRecord(&ptr
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, FreeARElemCallback
, ptr
);
1812 MakeDomainNameFromDNSNameString(&ptr
->ar
.namestorage
, mDNS_DomainTypeNames
[type
]);
1813 AppendDNSNameString (&ptr
->ar
.namestorage
, "local");
1814 AssignDomainName(&ptr
->ar
.resrec
.rdata
->u
.name
, d
);
1815 err
= mDNS_Register(m
, &ptr
->ar
);
1818 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err
);
1819 mDNSPlatformMemFree(ptr
);
1823 ptr
->next
= LocalDomainEnumRecords
;
1824 LocalDomainEnumRecords
= ptr
;
1828 mDNSlocal
void DeregisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
1830 ARListElem
**ptr
= &LocalDomainEnumRecords
;
1831 domainname lhs
; // left-hand side of PTR, for comparison
1833 debugf("Decrementing %s refcount for %##s",
1834 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
1835 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
1836 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
1838 MakeDomainNameFromDNSNameString(&lhs
, mDNS_DomainTypeNames
[type
]);
1839 AppendDNSNameString (&lhs
, "local");
1843 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, d
) && SameDomainName((*ptr
)->ar
.resrec
.name
, &lhs
))
1845 ARListElem
*rem
= *ptr
;
1846 *ptr
= (*ptr
)->next
;
1847 mDNS_Deregister(m
, &rem
->ar
);
1850 else ptr
= &(*ptr
)->next
;
1854 mDNSlocal
void AddAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
1856 DNameListElem
*new = mDNSPlatformMemAllocate(sizeof(DNameListElem
));
1857 if (!new) { LogMsg("ERROR: malloc"); return; }
1858 AssignDomainName(&new->name
, name
);
1860 new->next
= AutoBrowseDomains
;
1861 AutoBrowseDomains
= new;
1862 udsserver_automatic_browse_domain_changed(new, mDNStrue
);
1865 mDNSlocal
void RmvAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
1867 DNameListElem
**p
= &AutoBrowseDomains
;
1868 while (*p
&& (!SameDomainName(&(*p
)->name
, name
) || (*p
)->uid
!= uid
)) p
= &(*p
)->next
;
1869 if (!*p
) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name
->c
);
1872 DNameListElem
*ptr
= *p
;
1874 udsserver_automatic_browse_domain_changed(ptr
, mDNSfalse
);
1875 mDNSPlatformMemFree(ptr
);
1879 mDNSlocal
void SetPrefsBrowseDomains(mDNS
*m
, DNameListElem
*browseDomains
, mDNSBool add
)
1882 for (d
= browseDomains
; d
; d
= d
->next
)
1886 RegisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
1887 AddAutoBrowseDomain(d
->uid
, &d
->name
);
1891 DeregisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
1892 RmvAutoBrowseDomain(d
->uid
, &d
->name
);
1897 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
1899 int num_autoname
= 0;
1901 for (req
= all_requests
; req
; req
= req
->next
)
1902 if (req
->terminate
== regservice_termination_callback
&& req
->u
.servicereg
.autoname
)
1905 // If DeviceInfo record is currently registered, see if we need to deregister it
1906 if (m
->DeviceInfo
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
)
1907 if (num_autoname
== 0 || !SameDomainLabelCS(m
->DeviceInfo
.resrec
.name
->c
, m
->nicelabel
.c
))
1909 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m
->DeviceInfo
.resrec
.name
);
1910 mDNS_Deregister(m
, &m
->DeviceInfo
);
1913 // If DeviceInfo record is not currently registered, see if we need to register it
1914 if (m
->DeviceInfo
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
1915 if (num_autoname
> 0)
1917 mDNSu8 len
= m
->HIHardware
.c
[0] < 255 - 6 ? m
->HIHardware
.c
[0] : 255 - 6;
1918 mDNS_SetupResourceRecord(&m
->DeviceInfo
, mDNSNULL
, mDNSNULL
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeAdvisory
, mDNSNULL
, mDNSNULL
);
1919 ConstructServiceName(&m
->DeviceInfo
.namestorage
, &m
->nicelabel
, &DeviceInfoName
, &localdomain
);
1920 mDNSPlatformMemCopy(m
->DeviceInfo
.resrec
.rdata
->u
.data
+ 1, "model=", 6);
1921 mDNSPlatformMemCopy(m
->DeviceInfo
.resrec
.rdata
->u
.data
+ 7, m
->HIHardware
.c
+ 1, len
);
1922 m
->DeviceInfo
.resrec
.rdata
->u
.data
[0] = 6 + len
; // "model=" plus the device string
1923 m
->DeviceInfo
.resrec
.rdlength
= 7 + len
; // One extra for the length byte at the start of the string
1924 LogOperation("UpdateDeviceInfoRecord Register %##s", m
->DeviceInfo
.resrec
.name
);
1925 mDNS_Register(m
, &m
->DeviceInfo
);
1929 mDNSexport
void udsserver_handle_configchange(mDNS
*const m
)
1932 service_instance
*ptr
;
1933 DNameListElem
*RegDomains
= NULL
;
1934 DNameListElem
*BrowseDomains
= NULL
;
1937 UpdateDeviceInfoRecord(m
);
1939 // For autoname services, see if the default service name has changed, necessitating an automatic update
1940 for (req
= all_requests
; req
; req
= req
->next
)
1941 if (req
->terminate
== regservice_termination_callback
)
1942 if (req
->u
.servicereg
.autoname
&& !SameDomainLabelCS(req
->u
.servicereg
.name
.c
, m
->nicelabel
.c
))
1944 req
->u
.servicereg
.name
= m
->nicelabel
;
1945 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
1947 ptr
->renameonmemfree
= 1;
1948 if (ptr
->clientnotified
) SendServiceRemovalNotification(&ptr
->srs
);
1949 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr
->srs
.RR_PTR
.resrec
.name
->c
);
1950 if (mDNS_DeregisterService_drt(m
, &ptr
->srs
, mDNS_Dereg_rapid
))
1951 regservice_callback(m
, &ptr
->srs
, mStatus_MemFree
); // If service deregistered already, we can re-register immediately
1955 // Let the platform layer get the current DNS information
1957 mDNSPlatformSetDNSConfig(m
, mDNSfalse
, mDNSfalse
, mDNSNULL
, &RegDomains
, &BrowseDomains
);
1960 // Any automatic registration domains are also implicitly automatic browsing domains
1961 if (RegDomains
) SetPrefsBrowseDomains(m
, RegDomains
, mDNStrue
); // Add the new list first
1962 if (AutoRegistrationDomains
) SetPrefsBrowseDomains(m
, AutoRegistrationDomains
, mDNSfalse
); // Then clear the old list
1964 // Add any new domains not already in our AutoRegistrationDomains list
1965 for (p
=RegDomains
; p
; p
=p
->next
)
1967 DNameListElem
**pp
= &AutoRegistrationDomains
;
1968 while (*pp
&& ((*pp
)->uid
!= p
->uid
|| !SameDomainName(&(*pp
)->name
, &p
->name
))) pp
= &(*pp
)->next
;
1969 if (!*pp
) // If not found in our existing list, this is a new default registration domain
1971 RegisterLocalOnlyDomainEnumPTR(m
, &p
->name
, mDNS_DomainTypeRegistration
);
1972 udsserver_default_reg_domain_changed(p
, mDNStrue
);
1974 else // else found same domainname in both old and new lists, so no change, just delete old copy
1976 DNameListElem
*del
= *pp
;
1978 mDNSPlatformMemFree(del
);
1982 // Delete any domains in our old AutoRegistrationDomains list that are now gone
1983 while (AutoRegistrationDomains
)
1985 DNameListElem
*del
= AutoRegistrationDomains
;
1986 AutoRegistrationDomains
= AutoRegistrationDomains
->next
; // Cut record from list FIRST,
1987 DeregisterLocalOnlyDomainEnumPTR(m
, &del
->name
, mDNS_DomainTypeRegistration
);
1988 udsserver_default_reg_domain_changed(del
, mDNSfalse
); // before calling udsserver_default_reg_domain_changed()
1989 mDNSPlatformMemFree(del
);
1992 // Now we have our new updated automatic registration domain list
1993 AutoRegistrationDomains
= RegDomains
;
1995 // Add new browse domains to internal list
1996 if (BrowseDomains
) SetPrefsBrowseDomains(m
, BrowseDomains
, mDNStrue
);
1998 // Remove old browse domains from internal list
1999 if (SCPrefBrowseDomains
)
2001 SetPrefsBrowseDomains(m
, SCPrefBrowseDomains
, mDNSfalse
);
2002 while (SCPrefBrowseDomains
)
2004 DNameListElem
*fptr
= SCPrefBrowseDomains
;
2005 SCPrefBrowseDomains
= SCPrefBrowseDomains
->next
;
2006 mDNSPlatformMemFree(fptr
);
2010 // Replace the old browse domains array with the new array
2011 SCPrefBrowseDomains
= BrowseDomains
;
2014 mDNSlocal
void AutomaticBrowseDomainChange(mDNS
*const m
, DNSQuestion
*q
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2019 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2020 AddRecord
? "Adding" : "Removing", answer
->rdata
->u
.name
.c
);
2022 if (AddRecord
) AddAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2023 else RmvAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2026 mDNSlocal mStatus
handle_browse_request(request_state
*request
)
2028 char regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2029 domainname typedn
, d
, temp
;
2030 mDNSs32 NumSubTypes
;
2031 mStatus err
= mStatus_NoError
;
2033 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2034 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2035 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2036 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
2038 if (get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2039 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0) return(mStatus_BadParamErr
);
2041 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2043 if (domain
[0] == '\0') uDNS_RegisterSearchDomains(&mDNSStorage
);
2046 NumSubTypes
= ChopSubTypes(regtype
); // Note: Modifies regtype string to remove trailing subtypes
2047 if (NumSubTypes
< 0 || NumSubTypes
> 1) return(mStatus_BadParamErr
);
2048 if (NumSubTypes
== 1 && !AppendDNSNameString(&typedn
, regtype
+ strlen(regtype
) + 1)) return(mStatus_BadParamErr
);
2050 if (!regtype
[0] || !AppendDNSNameString(&typedn
, regtype
)) return(mStatus_BadParamErr
);
2052 if (!MakeDomainNameFromDNSNameString(&temp
, regtype
)) return(mStatus_BadParamErr
);
2053 // For over-long service types, we only allow domain "local"
2054 if (temp
.c
[0] > 15 && domain
[0] == 0) mDNSPlatformStrCopy(domain
, "local.");
2056 // Set up browser info
2057 request
->u
.browser
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2058 request
->u
.browser
.interface_id
= InterfaceID
;
2059 AssignDomainName(&request
->u
.browser
.regtype
, &typedn
);
2060 request
->u
.browser
.default_domain
= !domain
[0];
2061 request
->u
.browser
.browsers
= NULL
;
2063 LogOperation("%3d: DNSServiceBrowse(\"%##s\", \"%s\") START", request
->sd
, request
->u
.browser
.regtype
.c
, domain
);
2065 // We need to unconditionally set request->terminate, because even if we didn't successfully
2066 // start any browses right now, subsequent configuration changes may cause successful
2067 // browses to be added, and we'll need to cancel them before freeing this memory.
2068 request
->terminate
= browse_termination_callback
;
2072 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return(mStatus_BadParamErr
);
2073 err
= add_domain_to_browser(request
, &d
);
2075 err
= AuthorizedDomain(request
, &d
, AutoBrowseDomains
) ? add_domain_to_browser(request
, &d
) : mStatus_NoError
;
2080 DNameListElem
*sdom
;
2081 for (sdom
= AutoBrowseDomains
; sdom
; sdom
= sdom
->next
)
2082 if (!sdom
->uid
|| SystemUID(request
->uid
) || request
->uid
== sdom
->uid
)
2084 err
= add_domain_to_browser(request
, &sdom
->name
);
2087 if (SameDomainName(&sdom
->name
, &localdomain
)) break;
2088 else err
= mStatus_NoError
; // suppress errors for non-local "default" domains
2096 // ***************************************************************************
2097 #if COMPILER_LIKES_PRAGMA_MARK
2099 #pragma mark - DNSServiceResolve
2102 mDNSlocal
void resolve_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2105 char fullname
[MAX_ESCAPED_DOMAIN_NAME
], target
[MAX_ESCAPED_DOMAIN_NAME
];
2108 request_state
*req
= question
->QuestionContext
;
2111 LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req
->sd
, question
->qname
.c
, AddRecord
? "ADD" : "RMV", RRDisplayString(m
, answer
));
2115 if (req
->u
.resolve
.srv
== answer
) req
->u
.resolve
.srv
= mDNSNULL
;
2116 if (req
->u
.resolve
.txt
== answer
) req
->u
.resolve
.txt
= mDNSNULL
;
2120 if (answer
->rrtype
== kDNSType_SRV
) req
->u
.resolve
.srv
= answer
;
2121 if (answer
->rrtype
== kDNSType_TXT
) req
->u
.resolve
.txt
= answer
;
2123 if (!req
->u
.resolve
.txt
|| !req
->u
.resolve
.srv
) return; // only deliver result to client if we have both answers
2125 ConvertDomainNameToCString(answer
->name
, fullname
);
2126 ConvertDomainNameToCString(&req
->u
.resolve
.srv
->rdata
->u
.srv
.target
, target
);
2128 // calculate reply length
2129 len
+= sizeof(DNSServiceFlags
);
2130 len
+= sizeof(mDNSu32
); // interface index
2131 len
+= sizeof(DNSServiceErrorType
);
2132 len
+= strlen(fullname
) + 1;
2133 len
+= strlen(target
) + 1;
2134 len
+= 2 * sizeof(mDNSu16
); // port, txtLen
2135 len
+= req
->u
.resolve
.txt
->rdlength
;
2137 // allocate/init reply header
2138 rep
= create_reply(resolve_reply_op
, len
, req
);
2139 rep
->rhdr
->flags
= dnssd_htonl(0);
2140 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
));
2141 rep
->rhdr
->error
= dnssd_htonl(kDNSServiceErr_NoError
);
2143 data
= (char *)&rep
->rhdr
[1];
2145 // write reply data to message
2146 put_string(fullname
, &data
);
2147 put_string(target
, &data
);
2148 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[0];
2149 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[1];
2150 put_uint16(req
->u
.resolve
.txt
->rdlength
, &data
);
2151 put_rdata (req
->u
.resolve
.txt
->rdlength
, req
->u
.resolve
.txt
->rdata
->u
.data
, &data
);
2153 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req
->sd
, fullname
, target
, mDNSVal16(req
->u
.resolve
.srv
->rdata
->u
.srv
.port
));
2154 append_reply(req
, rep
);
2157 mDNSlocal
void resolve_termination_callback(request_state
*request
)
2159 LogOperation("%3d: DNSServiceResolve(%##s) STOP", request
->sd
, request
->u
.resolve
.qtxt
.qname
.c
);
2160 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2161 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2162 if (request
->u
.resolve
.external_advertise
) external_stop_resolving_service(&request
->u
.resolve
.qsrv
.qname
);
2165 mDNSlocal mStatus
handle_resolve_request(request_state
*request
)
2167 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2171 // extract the data from the message
2172 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2173 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2174 mDNSInterfaceID InterfaceID
;
2175 mDNSBool wasP2P
= (interfaceIndex
== kDNSServiceInterfaceIndexP2P
);
2178 if (wasP2P
) interfaceIndex
= kDNSServiceInterfaceIndexAny
;
2180 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2181 if (interfaceIndex
&& !InterfaceID
)
2182 { LogMsg("ERROR: handle_resolve_request bad interfaceIndex %d", interfaceIndex
); return(mStatus_BadParamErr
); }
2184 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0 ||
2185 get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2186 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
2187 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
2189 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2191 if (build_domainname_from_strings(&fqdn
, name
, regtype
, domain
) < 0)
2192 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name
, regtype
, domain
); return(mStatus_BadParamErr
); }
2194 mDNSPlatformMemZero(&request
->u
.resolve
, sizeof(request
->u
.resolve
));
2197 request
->u
.resolve
.qsrv
.InterfaceID
= InterfaceID
;
2198 request
->u
.resolve
.qsrv
.Target
= zeroAddr
;
2199 AssignDomainName(&request
->u
.resolve
.qsrv
.qname
, &fqdn
);
2200 request
->u
.resolve
.qsrv
.qtype
= kDNSType_SRV
;
2201 request
->u
.resolve
.qsrv
.qclass
= kDNSClass_IN
;
2202 request
->u
.resolve
.qsrv
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2203 request
->u
.resolve
.qsrv
.ExpectUnique
= mDNStrue
;
2204 request
->u
.resolve
.qsrv
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2205 request
->u
.resolve
.qsrv
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2206 request
->u
.resolve
.qsrv
.QuestionCallback
= resolve_result_callback
;
2207 request
->u
.resolve
.qsrv
.QuestionContext
= request
;
2209 request
->u
.resolve
.qtxt
.InterfaceID
= InterfaceID
;
2210 request
->u
.resolve
.qtxt
.Target
= zeroAddr
;
2211 AssignDomainName(&request
->u
.resolve
.qtxt
.qname
, &fqdn
);
2212 request
->u
.resolve
.qtxt
.qtype
= kDNSType_TXT
;
2213 request
->u
.resolve
.qtxt
.qclass
= kDNSClass_IN
;
2214 request
->u
.resolve
.qtxt
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2215 request
->u
.resolve
.qtxt
.ExpectUnique
= mDNStrue
;
2216 request
->u
.resolve
.qtxt
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2217 request
->u
.resolve
.qtxt
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2218 request
->u
.resolve
.qtxt
.SuppressUnusable
= mDNSfalse
;
2219 request
->u
.resolve
.qtxt
.QuestionCallback
= resolve_result_callback
;
2220 request
->u
.resolve
.qtxt
.QuestionContext
= request
;
2222 request
->u
.resolve
.ReportTime
= NonZeroTime(mDNS_TimeNow(&mDNSStorage
) + 130 * mDNSPlatformOneSecond
);
2224 request
->u
.resolve
.external_advertise
= mDNSfalse
;
2227 if (!AuthorizedDomain(request
, &fqdn
, AutoBrowseDomains
)) return(mStatus_NoError
);
2230 // ask the questions
2231 LogOperation("%3d: DNSServiceResolve(%##s) START", request
->sd
, request
->u
.resolve
.qsrv
.qname
.c
);
2232 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2235 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2236 if (err
) mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2239 request
->terminate
= resolve_termination_callback
;
2240 // If the user explicitly passed in P2P, we don't restrict the domain in which we resolve.
2241 if (wasP2P
|| (!InterfaceID
&& IsLocalDomain(&fqdn
)))
2242 { request
->u
.resolve
.external_advertise
= mDNStrue
; external_start_resolving_service(&fqdn
);}
2249 // ***************************************************************************
2250 #if COMPILER_LIKES_PRAGMA_MARK
2252 #pragma mark - DNSServiceQueryRecord
2255 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2256 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2257 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2258 // the mDNSCore operation if the client dies or closes its socket.
2260 mDNSlocal
void queryrecord_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2262 char name
[MAX_ESCAPED_DOMAIN_NAME
];
2263 request_state
*req
= question
->QuestionContext
;
2267 DNSServiceErrorType error
= kDNSServiceErr_NoError
;
2270 #if APPLE_OSX_mDNSResponder
2271 if (question
== &req
->u
.queryrecord
.q2
&& question
->qtype
!= req
->u
.queryrecord
.q
.qtype
&& !SameDomainName(&question
->qname
, &req
->u
.queryrecord
.q
.qname
))
2273 mDNS_StopQuery(&mDNSStorage
, question
);
2274 question
->QuestionCallback
= mDNSNULL
;
2275 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
2276 if (answer
->RecordType
!= kDNSRecordTypePacketNegative
)
2278 *question
= req
->u
.queryrecord
.q
;
2279 question
->InterfaceID
= mDNSInterface_Unicast
;
2280 question
->ExpectUnique
= mDNStrue
;
2281 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
));
2282 mStatus err
= mDNS_StartQuery(&mDNSStorage
, question
);
2283 if (err
) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
);
2287 #endif // APPLE_OSX_mDNSResponder
2289 if (answer
->RecordType
== kDNSRecordTypePacketNegative
)
2291 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
2292 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
2293 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
2294 // server is going to assert that pretty much every single multicast name doesn't exist.
2295 if (!answer
->InterfaceID
&& IsLocalDomain(answer
->name
)) return;
2296 error
= kDNSServiceErr_NoSuchRecord
;
2297 AddRecord
= mDNStrue
;
2300 ConvertDomainNameToCString(answer
->name
, name
);
2302 LogOperation("%3d: %s(%##s, %s) %s %s", req
->sd
,
2303 req
->hdr
.op
== query_request
? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
2304 question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "ADD" : "RMV", RRDisplayString(m
, answer
));
2306 len
= sizeof(DNSServiceFlags
); // calculate reply data length
2307 len
+= sizeof(mDNSu32
); // interface index
2308 len
+= sizeof(DNSServiceErrorType
);
2309 len
+= strlen(name
) + 1;
2310 len
+= 3 * sizeof(mDNSu16
); // type, class, rdlen
2311 len
+= answer
->rdlength
;
2312 len
+= sizeof(mDNSu32
); // TTL
2314 rep
= create_reply(req
->hdr
.op
== query_request
? query_reply_op
: addrinfo_reply_op
, len
, req
);
2316 rep
->rhdr
->flags
= dnssd_htonl(AddRecord
? kDNSServiceFlagsAdd
: 0);
2317 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
));
2318 rep
->rhdr
->error
= dnssd_htonl(error
);
2320 data
= (char *)&rep
->rhdr
[1];
2322 put_string(name
, &data
);
2323 put_uint16(answer
->rrtype
, &data
);
2324 put_uint16(answer
->rrclass
, &data
);
2325 put_uint16(answer
->rdlength
, &data
);
2326 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2327 // function just does a blind memory copy without regard to structures that may have holes in them.
2328 if (answer
->rdlength
)
2329 if (!putRData(mDNSNULL
, (mDNSu8
*)data
, (mDNSu8
*)rep
->rhdr
+ len
, answer
))
2330 LogMsg("queryrecord_result_callback putRData failed %d", (mDNSu8
*)rep
->rhdr
+ len
- (mDNSu8
*)data
);
2331 data
+= answer
->rdlength
;
2332 put_uint32(AddRecord
? answer
->rroriginalttl
: 0, &data
);
2334 append_reply(req
, rep
);
2335 #if APPLE_OSX_mDNSResponder
2337 CHECK_WCF_FUNCTION(WCFIsServerRunning
)
2340 socklen_t xucredlen
= sizeof(x
);
2342 if (WCFIsServerRunning((WCFConnection
*)m
->WCF
) && answer
->rdlength
!= 0)
2344 if (getsockopt(req
->sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 &&
2345 (x
.cr_version
== XUCRED_VERSION
))
2347 struct sockaddr_storage addr
;
2348 const RDataBody2
*const rdb
= (RDataBody2
*)answer
->rdata
->u
.data
;
2350 if (answer
->rrtype
== kDNSType_A
|| answer
->rrtype
== kDNSType_AAAA
)
2352 if (answer
->rrtype
== kDNSType_A
)
2354 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&addr
;
2356 if (!putRData(mDNSNULL
, (mDNSu8
*)&sin
->sin_addr
, (mDNSu8
*)(&sin
->sin_addr
+ sizeof(rdb
->ipv4
)), answer
))
2357 LogMsg("queryrecord_result_callback: WCF AF_INET putRData failed");
2360 addr
.ss_len
= sizeof (struct sockaddr_in
);
2361 addr
.ss_family
= AF_INET
;
2364 else if (answer
->rrtype
== kDNSType_AAAA
)
2366 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&addr
;
2367 sin6
->sin6_port
= 0;
2368 if (!putRData(mDNSNULL
, (mDNSu8
*)&sin6
->sin6_addr
, (mDNSu8
*)(&sin6
->sin6_addr
+ sizeof(rdb
->ipv6
)), answer
))
2369 LogMsg("queryrecord_result_callback: WCF AF_INET6 putRData failed");
2372 addr
.ss_len
= sizeof (struct sockaddr_in6
);
2373 addr
.ss_family
= AF_INET6
;
2378 debugf("queryrecord_result_callback: Name %s, uid %u, addr length %d", name
, x
.cr_uid
, addr
.ss_len
);
2379 CHECK_WCF_FUNCTION((WCFConnection
*)WCFNameResolvesToAddr
)
2381 WCFNameResolvesToAddr(m
->WCF
, name
, (struct sockaddr
*)&addr
, x
.cr_uid
);
2385 else if (answer
->rrtype
== kDNSType_CNAME
)
2388 char cname_cstr
[MAX_ESCAPED_DOMAIN_NAME
];
2389 if (!putRData(mDNSNULL
, cname
.c
, (mDNSu8
*)(cname
.c
+ MAX_DOMAIN_NAME
), answer
))
2390 LogMsg("queryrecord_result_callback: WCF CNAME putRData failed");
2393 ConvertDomainNameToCString(&cname
, cname_cstr
);
2394 CHECK_WCF_FUNCTION((WCFConnection
*)WCFNameResolvesToAddr
)
2396 WCFNameResolvesToName(m
->WCF
, name
, cname_cstr
, x
.cr_uid
);
2401 else my_perror("queryrecord_result_callback: ERROR: getsockopt LOCAL_PEERCRED");
2408 mDNSlocal
void queryrecord_termination_callback(request_state
*request
)
2410 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP",
2411 request
->sd
, request
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(request
->u
.queryrecord
.q
.qtype
));
2412 mDNS_StopQuery(&mDNSStorage
, &request
->u
.queryrecord
.q
); // no need to error check
2413 if (request
->u
.queryrecord
.q
.InterfaceID
== mDNSInterface_P2P
|| (!request
->u
.queryrecord
.q
.InterfaceID
&& SameDomainName((const domainname
*)LastLabel(&request
->u
.queryrecord
.q
.qname
), &localdomain
)))
2414 external_stop_browsing_for_service(&mDNSStorage
, &request
->u
.queryrecord
.q
.qname
, request
->u
.queryrecord
.q
.qtype
);
2415 if (request
->u
.queryrecord
.q2
.QuestionCallback
) mDNS_StopQuery(&mDNSStorage
, &request
->u
.queryrecord
.q2
);
2418 mDNSlocal mStatus
handle_queryrecord_request(request_state
*request
)
2420 DNSQuestion
*const q
= &request
->u
.queryrecord
.q
;
2422 mDNSu16 rrtype
, rrclass
;
2425 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2426 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2427 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2428 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
2430 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0) return(mStatus_BadParamErr
);
2431 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
2432 rrclass
= get_uint16(&request
->msgptr
, request
->msgend
);
2434 if (!request
->msgptr
)
2435 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2437 mDNSPlatformMemZero(&request
->u
.queryrecord
, sizeof(request
->u
.queryrecord
));
2439 q
->InterfaceID
= InterfaceID
;
2440 q
->Target
= zeroAddr
;
2441 if (!MakeDomainNameFromDNSNameString(&q
->qname
, name
)) return(mStatus_BadParamErr
);
2443 if (!AuthorizedDomain(request
, &q
->qname
, AutoBrowseDomains
)) return (mStatus_NoError
);
2446 q
->qclass
= rrclass
;
2447 q
->LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2448 q
->ExpectUnique
= mDNSfalse
;
2449 q
->ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2450 q
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2451 q
->SuppressUnusable
= (flags
& kDNSServiceFlagsSuppressUnusable
) != 0;
2452 q
->QuestionCallback
= queryrecord_result_callback
;
2453 q
->QuestionContext
= request
;
2455 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START", request
->sd
, flags
, interfaceIndex
, q
->qname
.c
, DNSTypeName(q
->qtype
));
2456 err
= mDNS_StartQuery(&mDNSStorage
, q
);
2457 if (err
) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q
->qname
.c
, DNSTypeName(q
->qtype
), (int)err
);
2460 request
->terminate
= queryrecord_termination_callback
;
2461 if (q
->InterfaceID
== mDNSInterface_P2P
|| (!q
->InterfaceID
&& SameDomainName((const domainname
*)LastLabel(&q
->qname
), &localdomain
)))
2462 external_start_browsing_for_service(&mDNSStorage
, &q
->qname
, q
->qtype
);
2465 #if APPLE_OSX_mDNSResponder
2466 // Workaround for networks using Microsoft Active Directory using "local" as a private internal top-level domain
2467 extern domainname ActiveDirectoryPrimaryDomain
;
2468 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
2469 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
2471 if (!q
->ForceMCast
&& SameDomainLabel(LastLabel(&q
->qname
), (const mDNSu8
*)&localdomain
))
2472 if (q
->qtype
== kDNSType_A
|| q
->qtype
== kDNSType_AAAA
|| VALID_MSAD_SRV(q
))
2474 int labels
= CountLabels(&q
->qname
);
2475 DNSQuestion
*const q2
= &request
->u
.queryrecord
.q2
;
2477 q2
->InterfaceID
= mDNSInterface_Unicast
;
2478 q2
->ExpectUnique
= mDNStrue
;
2480 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
2481 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
2482 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
2483 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
2484 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
2485 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
2486 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
2487 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
2488 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
2489 if (labels
== 2 && !SameDomainName(&q
->qname
, &ActiveDirectoryPrimaryDomain
))
2491 AssignDomainName(&q2
->qname
, &localdomain
);
2492 q2
->qtype
= kDNSType_SOA
;
2493 q2
->LongLived
= mDNSfalse
;
2494 q2
->ForceMCast
= mDNSfalse
;
2495 q2
->ReturnIntermed
= mDNStrue
;
2497 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
));
2498 err
= mDNS_StartQuery(&mDNSStorage
, q2
);
2499 if (err
) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
), (int)err
);
2501 #endif // APPLE_OSX_mDNSResponder
2506 // ***************************************************************************
2507 #if COMPILER_LIKES_PRAGMA_MARK
2509 #pragma mark - DNSServiceEnumerateDomains
2512 mDNSlocal reply_state
*format_enumeration_reply(request_state
*request
,
2513 const char *domain
, DNSServiceFlags flags
, mDNSu32 ifi
, DNSServiceErrorType err
)
2519 len
= sizeof(DNSServiceFlags
);
2520 len
+= sizeof(mDNSu32
);
2521 len
+= sizeof(DNSServiceErrorType
);
2522 len
+= strlen(domain
) + 1;
2524 reply
= create_reply(enumeration_reply_op
, len
, request
);
2525 reply
->rhdr
->flags
= dnssd_htonl(flags
);
2526 reply
->rhdr
->ifi
= dnssd_htonl(ifi
);
2527 reply
->rhdr
->error
= dnssd_htonl(err
);
2528 data
= (char *)&reply
->rhdr
[1];
2529 put_string(domain
, &data
);
2533 mDNSlocal
void enum_termination_callback(request_state
*request
)
2535 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
2536 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
2539 mDNSlocal
void enum_result_callback(mDNS
*const m
,
2540 DNSQuestion
*const question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2542 char domain
[MAX_ESCAPED_DOMAIN_NAME
];
2543 request_state
*request
= question
->QuestionContext
;
2544 DNSServiceFlags flags
= 0;
2548 if (answer
->rrtype
!= kDNSType_PTR
) return;
2551 if (!AuthorizedDomain(request
, &answer
->rdata
->u
.name
, request
->u
.enumeration
.flags
? AutoRegistrationDomains
: AutoBrowseDomains
)) return;
2554 // We only return add/remove events for the browse and registration lists
2555 // For the default browse and registration answers, we only give an "ADD" event
2556 if (question
== &request
->u
.enumeration
.q_default
&& !AddRecord
) return;
2560 flags
|= kDNSServiceFlagsAdd
;
2561 if (question
== &request
->u
.enumeration
.q_default
) flags
|= kDNSServiceFlagsDefault
;
2564 ConvertDomainNameToCString(&answer
->rdata
->u
.name
, domain
);
2565 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
2566 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
2567 // network, so we just pass kDNSServiceInterfaceIndexAny
2568 reply
= format_enumeration_reply(request
, domain
, flags
, kDNSServiceInterfaceIndexAny
, kDNSServiceErr_NoError
);
2569 if (!reply
) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
2571 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request
->sd
, question
->qname
.c
, AddRecord
? "Add" : "Rmv", domain
);
2573 append_reply(request
, reply
);
2576 mDNSlocal mStatus
handle_enum_request(request_state
*request
)
2579 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2580 DNSServiceFlags reg
= flags
& kDNSServiceFlagsRegistrationDomains
;
2581 mDNS_DomainType t_all
= reg
? mDNS_DomainTypeRegistration
: mDNS_DomainTypeBrowse
;
2582 mDNS_DomainType t_default
= reg
? mDNS_DomainTypeRegistrationDefault
: mDNS_DomainTypeBrowseDefault
;
2583 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2584 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2585 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
2587 if (!request
->msgptr
)
2588 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2590 // allocate context structures
2591 uDNS_RegisterSearchDomains(&mDNSStorage
);
2594 // mark which kind of enumeration we're doing so we can (de)authorize certain domains
2595 request
->u
.enumeration
.flags
= reg
;
2598 // enumeration requires multiple questions, so we must link all the context pointers so that
2599 // necessary context can be reached from the callbacks
2600 request
->u
.enumeration
.q_all
.QuestionContext
= request
;
2601 request
->u
.enumeration
.q_default
.QuestionContext
= request
;
2603 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
2604 if (!InterfaceID
) InterfaceID
= mDNSInterface_LocalOnly
;
2607 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request
->sd
, flags
,
2608 (flags
& kDNSServiceFlagsBrowseDomains
) ? "kDNSServiceFlagsBrowseDomains" :
2609 (flags
& kDNSServiceFlagsRegistrationDomains
) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
2610 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
, t_all
, NULL
, InterfaceID
, enum_result_callback
, request
);
2613 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
, t_default
, NULL
, InterfaceID
, enum_result_callback
, request
);
2614 if (err
) mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
2615 else request
->terminate
= enum_termination_callback
;
2621 // ***************************************************************************
2622 #if COMPILER_LIKES_PRAGMA_MARK
2624 #pragma mark - DNSServiceReconfirmRecord & Misc
2627 mDNSlocal mStatus
handle_reconfirm_request(request_state
*request
)
2629 mStatus status
= mStatus_BadParamErr
;
2630 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 0, 0);
2633 status
= mDNS_ReconfirmByValue(&mDNSStorage
, &rr
->resrec
);
2635 (status
== mStatus_NoError
) ?
2636 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
2637 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
2638 request
->sd
, RRDisplayString(&mDNSStorage
, &rr
->resrec
),
2639 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, rr
->resrec
.InterfaceID
), status
);
2640 freeL("AuthRecord/handle_reconfirm_request", rr
);
2645 mDNSlocal mStatus
handle_setdomain_request(request_state
*request
)
2647 char domainstr
[MAX_ESCAPED_DOMAIN_NAME
];
2649 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2650 (void)flags
; // Unused
2651 if (get_string(&request
->msgptr
, request
->msgend
, domainstr
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2652 !MakeDomainNameFromDNSNameString(&domain
, domainstr
))
2653 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2655 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request
->sd
, domain
.c
);
2656 return(mStatus_NoError
);
2659 typedef packedstruct
2664 } DaemonVersionReply
;
2666 mDNSlocal
void handle_getproperty_request(request_state
*request
)
2668 const mStatus BadParamErr
= dnssd_htonl((mDNSu32
)mStatus_BadParamErr
);
2670 if (get_string(&request
->msgptr
, request
->msgend
, prop
, sizeof(prop
)) >= 0)
2672 LogOperation("%3d: DNSServiceGetProperty(%s)", request
->sd
, prop
);
2673 if (!strcmp(prop
, kDNSServiceProperty_DaemonVersion
))
2675 DaemonVersionReply x
= { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H
) };
2676 send_all(request
->sd
, (const char *)&x
, sizeof(x
));
2681 // If we didn't recogize the requested property name, return BadParamErr
2682 send_all(request
->sd
, (const char *)&BadParamErr
, sizeof(BadParamErr
));
2685 // ***************************************************************************
2686 #if COMPILER_LIKES_PRAGMA_MARK
2688 #pragma mark - DNSServiceNATPortMappingCreate
2691 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
2693 mDNSlocal
void port_mapping_termination_callback(request_state
*request
)
2695 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP", request
->sd
,
2696 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
2697 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
);
2698 mDNS_StopNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
2701 // Called via function pointer when we get a NAT-PMP address request or port mapping response
2702 mDNSlocal
void port_mapping_create_request_callback(mDNS
*m
, NATTraversalInfo
*n
)
2704 request_state
*request
= (request_state
*)n
->clientContext
;
2709 if (!request
) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
2711 // calculate reply data length
2712 replyLen
= sizeof(DNSServiceFlags
);
2713 replyLen
+= 3 * sizeof(mDNSu32
); // if index + addr + ttl
2714 replyLen
+= sizeof(DNSServiceErrorType
);
2715 replyLen
+= 2 * sizeof(mDNSu16
); // Internal Port + External Port
2716 replyLen
+= sizeof(mDNSu8
); // protocol
2718 rep
= create_reply(port_mapping_reply_op
, replyLen
, request
);
2720 rep
->rhdr
->flags
= dnssd_htonl(0);
2721 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, n
->InterfaceID
));
2722 rep
->rhdr
->error
= dnssd_htonl(n
->Result
);
2724 data
= (char *)&rep
->rhdr
[1];
2726 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[0];
2727 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[1];
2728 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[2];
2729 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[3];
2730 *data
++ = DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
);
2731 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[0];
2732 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[1];
2733 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[0];
2734 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[1];
2735 put_uint32(request
->u
.pm
.NATinfo
.Lifetime
, &data
);
2737 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request
->sd
,
2738 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
2739 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
2740 &request
->u
.pm
.NATinfo
.ExternalAddress
, mDNSVal16(request
->u
.pm
.NATinfo
.ExternalPort
), request
->u
.pm
.NATinfo
.Lifetime
);
2742 append_reply(request
, rep
);
2745 mDNSlocal mStatus
handle_port_mapping_request(request_state
*request
)
2748 mStatus err
= mStatus_NoError
;
2750 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2751 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2752 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2753 mDNSu8 protocol
= (mDNSu8
)get_uint32(&request
->msgptr
, request
->msgend
);
2754 (void)flags
; // Unused
2755 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
2756 if (request
->msgptr
+ 8 > request
->msgend
) request
->msgptr
= NULL
;
2759 request
->u
.pm
.NATinfo
.IntPort
.b
[0] = *request
->msgptr
++;
2760 request
->u
.pm
.NATinfo
.IntPort
.b
[1] = *request
->msgptr
++;
2761 request
->u
.pm
.ReqExt
.b
[0] = *request
->msgptr
++;
2762 request
->u
.pm
.ReqExt
.b
[1] = *request
->msgptr
++;
2763 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
2766 if (!request
->msgptr
)
2767 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2769 if (protocol
== 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
2771 if (!mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
) || !mDNSIPPortIsZero(request
->u
.pm
.ReqExt
) || ttl
) return(mStatus_BadParamErr
);
2775 if (mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
)) return(mStatus_BadParamErr
);
2776 if (!(protocol
& (kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
))) return(mStatus_BadParamErr
);
2779 request
->u
.pm
.NATinfo
.Protocol
= !protocol
? NATOp_AddrRequest
: (protocol
== kDNSServiceProtocol_UDP
) ? NATOp_MapUDP
: NATOp_MapTCP
;
2780 // u.pm.NATinfo.IntPort = already set above
2781 request
->u
.pm
.NATinfo
.RequestedPort
= request
->u
.pm
.ReqExt
;
2782 request
->u
.pm
.NATinfo
.NATLease
= ttl
;
2783 request
->u
.pm
.NATinfo
.clientCallback
= port_mapping_create_request_callback
;
2784 request
->u
.pm
.NATinfo
.clientContext
= request
;
2786 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START", request
->sd
,
2787 protocol
, mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
);
2788 err
= mDNS_StartNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
2789 if (err
) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err
);
2790 else request
->terminate
= port_mapping_termination_callback
;
2795 // ***************************************************************************
2796 #if COMPILER_LIKES_PRAGMA_MARK
2798 #pragma mark - DNSServiceGetAddrInfo
2801 mDNSlocal
void addrinfo_termination_callback(request_state
*request
)
2803 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP", request
->sd
, request
->u
.addrinfo
.q4
.qname
.c
);
2805 if (request
->u
.addrinfo
.q4
.QuestionContext
)
2807 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
2808 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
2811 if (request
->u
.addrinfo
.q6
.QuestionContext
)
2813 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
2814 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
2818 mDNSlocal mStatus
handle_addrinfo_request(request_state
*request
)
2824 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2825 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2827 mDNSPlatformMemZero(&request
->u
.addrinfo
, sizeof(request
->u
.addrinfo
));
2828 request
->u
.addrinfo
.interface_id
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2829 request
->u
.addrinfo
.flags
= flags
;
2830 request
->u
.addrinfo
.protocol
= get_uint32(&request
->msgptr
, request
->msgend
);
2832 if (interfaceIndex
&& !request
->u
.addrinfo
.interface_id
) return(mStatus_BadParamErr
);
2833 if (request
->u
.addrinfo
.protocol
> (kDNSServiceProtocol_IPv4
|kDNSServiceProtocol_IPv6
)) return(mStatus_BadParamErr
);
2835 if (get_string(&request
->msgptr
, request
->msgend
, hostname
, 256) < 0) return(mStatus_BadParamErr
);
2837 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2839 if (!MakeDomainNameFromDNSNameString(&d
, hostname
))
2840 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname
); return(mStatus_BadParamErr
); }
2843 if (!AuthorizedDomain(request
, &d
, AutoBrowseDomains
)) return (mStatus_NoError
);
2846 if (!request
->u
.addrinfo
.protocol
)
2848 flags
|= kDNSServiceFlagsSuppressUnusable
;
2849 request
->u
.addrinfo
.protocol
= (kDNSServiceProtocol_IPv4
| kDNSServiceProtocol_IPv6
);
2852 request
->u
.addrinfo
.q4
.InterfaceID
= request
->u
.addrinfo
.q6
.InterfaceID
= request
->u
.addrinfo
.interface_id
;
2853 request
->u
.addrinfo
.q4
.Target
= request
->u
.addrinfo
.q6
.Target
= zeroAddr
;
2854 request
->u
.addrinfo
.q4
.qname
= request
->u
.addrinfo
.q6
.qname
= d
;
2855 request
->u
.addrinfo
.q4
.qclass
= request
->u
.addrinfo
.q6
.qclass
= kDNSServiceClass_IN
;
2856 request
->u
.addrinfo
.q4
.LongLived
= request
->u
.addrinfo
.q6
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2857 request
->u
.addrinfo
.q4
.ExpectUnique
= request
->u
.addrinfo
.q6
.ExpectUnique
= mDNSfalse
;
2858 request
->u
.addrinfo
.q4
.ForceMCast
= request
->u
.addrinfo
.q6
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2859 request
->u
.addrinfo
.q4
.ReturnIntermed
= request
->u
.addrinfo
.q6
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2860 request
->u
.addrinfo
.q4
.SuppressUnusable
= request
->u
.addrinfo
.q6
.SuppressUnusable
= (flags
& kDNSServiceFlagsSuppressUnusable
) != 0;
2862 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
)
2864 request
->u
.addrinfo
.q4
.qtype
= kDNSServiceType_A
;
2865 request
->u
.addrinfo
.q4
.QuestionCallback
= queryrecord_result_callback
;
2866 request
->u
.addrinfo
.q4
.QuestionContext
= request
;
2867 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
2868 if (err
!= mStatus_NoError
)
2870 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
2871 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
2875 if (!err
&& (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
))
2877 request
->u
.addrinfo
.q6
.qtype
= kDNSServiceType_AAAA
;
2878 request
->u
.addrinfo
.q6
.QuestionCallback
= queryrecord_result_callback
;
2879 request
->u
.addrinfo
.q6
.QuestionContext
= request
;
2880 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
2881 if (err
!= mStatus_NoError
)
2883 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
2884 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
2885 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
)
2887 // If we started a query for IPv4, we need to cancel it
2888 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
2889 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
2894 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START",
2895 request
->sd
, flags
, interfaceIndex
, request
->u
.addrinfo
.protocol
, d
.c
);
2897 if (!err
) request
->terminate
= addrinfo_termination_callback
;
2902 // ***************************************************************************
2903 #if COMPILER_LIKES_PRAGMA_MARK
2905 #pragma mark - Main Request Handler etc.
2908 mDNSlocal request_state
*NewRequest(void)
2910 request_state
**p
= &all_requests
;
2911 while (*p
) p
=&(*p
)->next
;
2912 *p
= mallocL("request_state", sizeof(request_state
));
2913 if (!*p
) FatalError("ERROR: malloc");
2914 mDNSPlatformMemZero(*p
, sizeof(request_state
));
2918 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
2919 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
2920 mDNSlocal
void read_msg(request_state
*req
)
2922 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
2923 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req
->sd
); req
->ts
= t_error
; return; }
2925 if (req
->ts
== t_complete
) // this must be death or something is wrong
2927 char buf
[4]; // dummy for death notification
2928 int nread
= udsSupportReadFD(req
->sd
, buf
, 4, 0, req
->platform_data
);
2929 if (!nread
) { req
->ts
= t_terminated
; return; }
2930 if (nread
< 0) goto rerror
;
2931 LogMsg("%3d: ERROR: read data from a completed request", req
->sd
);
2936 if (req
->ts
!= t_morecoming
)
2937 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req
->sd
, req
->ts
); req
->ts
= t_error
; return; }
2939 if (req
->hdr_bytes
< sizeof(ipc_msg_hdr
))
2941 mDNSu32 nleft
= sizeof(ipc_msg_hdr
) - req
->hdr_bytes
;
2942 int nread
= udsSupportReadFD(req
->sd
, (char *)&req
->hdr
+ req
->hdr_bytes
, nleft
, 0, req
->platform_data
);
2943 if (nread
== 0) { req
->ts
= t_terminated
; return; }
2944 if (nread
< 0) goto rerror
;
2945 req
->hdr_bytes
+= nread
;
2946 if (req
->hdr_bytes
> sizeof(ipc_msg_hdr
))
2947 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req
->sd
); req
->ts
= t_error
; return; }
2949 // only read data if header is complete
2950 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
))
2952 ConvertHeaderBytes(&req
->hdr
);
2953 if (req
->hdr
.version
!= VERSION
)
2954 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req
->sd
, req
->hdr
.version
, VERSION
); req
->ts
= t_error
; return; }
2956 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
2957 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
2958 // for other overhead, this means any message above 70kB is definitely bogus.
2959 if (req
->hdr
.datalen
> 70000)
2960 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req
->sd
, req
->hdr
.datalen
, req
->hdr
.datalen
); req
->ts
= t_error
; return; }
2961 req
->msgbuf
= mallocL("request_state msgbuf", req
->hdr
.datalen
+ MSG_PAD_BYTES
);
2962 if (!req
->msgbuf
) { my_perror("ERROR: malloc"); req
->ts
= t_error
; return; }
2963 req
->msgptr
= req
->msgbuf
;
2964 req
->msgend
= req
->msgbuf
+ req
->hdr
.datalen
;
2965 mDNSPlatformMemZero(req
->msgbuf
, req
->hdr
.datalen
+ MSG_PAD_BYTES
);
2969 // If our header is complete, but we're still needing more body data, then try to read it now
2970 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
2971 // Any time we need to get the error return socket we know we'll have at least one data byte
2972 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
2973 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
< req
->hdr
.datalen
)
2975 mDNSu32 nleft
= req
->hdr
.datalen
- req
->data_bytes
;
2977 #if !defined(_WIN32)
2978 struct iovec vec
= { req
->msgbuf
+ req
->data_bytes
, nleft
}; // Tell recvmsg where we want the bytes put
2980 struct cmsghdr
*cmsg
;
2981 char cbuf
[CMSG_SPACE(sizeof(dnssd_sock_t
))];
2983 msg
.msg_namelen
= 0;
2986 msg
.msg_control
= cbuf
;
2987 msg
.msg_controllen
= sizeof(cbuf
);
2989 nread
= recvmsg(req
->sd
, &msg
, 0);
2991 nread
= udsSupportReadFD(req
->sd
, (char *)req
->msgbuf
+ req
->data_bytes
, nleft
, 0, req
->platform_data
);
2993 if (nread
== 0) { req
->ts
= t_terminated
; return; }
2994 if (nread
< 0) goto rerror
;
2995 req
->data_bytes
+= nread
;
2996 if (req
->data_bytes
> req
->hdr
.datalen
)
2997 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req
->sd
); req
->ts
= t_error
; return; }
2998 #if !defined(_WIN32)
2999 cmsg
= CMSG_FIRSTHDR(&msg
);
3000 #if DEBUG_64BIT_SCM_RIGHTS
3001 LogMsg("%3d: Expecting %d %d %d %d", req
->sd
, sizeof(cbuf
), sizeof(cbuf
), SOL_SOCKET
, SCM_RIGHTS
);
3002 LogMsg("%3d: Got %d %d %d %d", req
->sd
, msg
.msg_controllen
, cmsg
->cmsg_len
, cmsg
->cmsg_level
, cmsg
->cmsg_type
);
3003 #endif // DEBUG_64BIT_SCM_RIGHTS
3004 if (msg
.msg_controllen
== sizeof(cbuf
) &&
3005 cmsg
->cmsg_len
== sizeof(cbuf
) &&
3006 cmsg
->cmsg_level
== SOL_SOCKET
&&
3007 cmsg
->cmsg_type
== SCM_RIGHTS
)
3009 #if APPLE_OSX_mDNSResponder
3010 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3011 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3012 // and it's convenient to repurpose the existing fd-passing code here for that task
3013 if (req
->hdr
.op
== send_bpf
)
3015 dnssd_sock_t x
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3016 LogOperation("%3d: Got BPF %d", req
->sd
, x
);
3017 mDNSPlatformReceiveBPF_fd(&mDNSStorage
, x
);
3020 #endif // APPLE_OSX_mDNSResponder
3021 req
->errsd
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3022 #if DEBUG_64BIT_SCM_RIGHTS
3023 LogMsg("%3d: read req->errsd %d", req
->sd
, req
->errsd
);
3024 #endif // DEBUG_64BIT_SCM_RIGHTS
3025 if (req
->data_bytes
< req
->hdr
.datalen
)
3027 LogMsg("%3d: Client sent error socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3028 req
->sd
, req
->errsd
, req
->data_bytes
, req
->hdr
.datalen
);
3036 // If our header and data are both complete, see if we need to make our separate error return socket
3037 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
== req
->hdr
.datalen
)
3039 if (req
->terminate
&& req
->hdr
.op
!= cancel_request
)
3041 dnssd_sockaddr_t cliaddr
;
3042 #if defined(USE_TCP_LOOPBACK)
3045 port
.b
[0] = req
->msgptr
[0];
3046 port
.b
[1] = req
->msgptr
[1];
3048 cliaddr
.sin_family
= AF_INET
;
3049 cliaddr
.sin_port
= port
.NotAnInteger
;
3050 cliaddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3052 char ctrl_path
[MAX_CTLPATH
];
3053 get_string(&req
->msgptr
, req
->msgend
, ctrl_path
, MAX_CTLPATH
); // path is first element in message buffer
3054 mDNSPlatformMemZero(&cliaddr
, sizeof(cliaddr
));
3055 cliaddr
.sun_family
= AF_LOCAL
;
3056 mDNSPlatformStrCopy(cliaddr
.sun_path
, ctrl_path
);
3057 // If the error return path UDS name is empty string, that tells us
3058 // that this is a new version of the library that's going to pass us
3059 // the error return path socket via sendmsg/recvmsg
3060 if (ctrl_path
[0] == 0)
3062 if (req
->errsd
== req
->sd
)
3063 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req
->sd
); req
->ts
= t_error
; return; }
3068 req
->errsd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3069 if (!dnssd_SocketValid(req
->errsd
)) { my_perror("ERROR: socket"); req
->ts
= t_error
; return; }
3071 if (connect(req
->errsd
, (struct sockaddr
*)&cliaddr
, sizeof(cliaddr
)) < 0)
3073 #if !defined(USE_TCP_LOOPBACK)
3075 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
3076 req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3077 if (stat(cliaddr
.sun_path
, &sb
) < 0)
3078 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3080 LogMsg("%3d: read_msg: file “%s” mode %o (octal) uid %d gid %d", req
->sd
, cliaddr
.sun_path
, sb
.st_mode
, sb
.st_uid
, sb
.st_gid
);
3086 #if !defined(USE_TCP_LOOPBACK)
3089 LogOperation("%3d: Error socket %d created %08X %08X", req
->sd
, req
->errsd
, req
->hdr
.client_context
.u32
[1], req
->hdr
.client_context
.u32
[0]);
3091 if (ioctlsocket(req
->errsd
, FIONBIO
, &opt
) != 0)
3093 if (fcntl(req
->errsd
, F_SETFL
, fcntl(req
->errsd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3096 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
3097 req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3103 req
->ts
= t_complete
;
3109 if (dnssd_errno
== dnssd_EWOULDBLOCK
|| dnssd_errno
== dnssd_EINTR
) return;
3110 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3114 #define RecordOrientedOp(X) \
3115 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3117 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3118 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3120 mDNSlocal
void request_callback(int fd
, short filter
, void *info
)
3123 request_state
*req
= info
;
3124 mDNSs32 min_size
= sizeof(DNSServiceFlags
);
3126 (void)filter
; // Unused
3129 if (req
->ts
== t_morecoming
) return;
3130 if (req
->ts
== t_terminated
|| req
->ts
== t_error
) { AbortUnlinkAndFree(req
); return; }
3131 if (req
->ts
!= t_complete
) { LogMsg("req->ts %d != t_complete", req
->ts
); AbortUnlinkAndFree(req
); return; }
3133 if (req
->hdr
.version
!= VERSION
)
3135 LogMsg("ERROR: client version %d incompatible with daemon version %d", req
->hdr
.version
, VERSION
);
3136 AbortUnlinkAndFree(req
);
3140 switch(req
->hdr
.op
) // Interface + other data
3142 case connection_request
: min_size
= 0; break;
3143 case reg_service_request
: min_size
+= sizeof(mDNSu32
) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3144 case add_record_request
: min_size
+= 4 /* type, rdlen */ + 4 /* ttl */; break;
3145 case update_record_request
: min_size
+= 2 /* rdlen */ + 4 /* ttl */; break;
3146 case remove_record_request
: break;
3147 case browse_request
: min_size
+= sizeof(mDNSu32
) + 2 /* type, domain */; break;
3148 case resolve_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
3149 case query_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 4 /* type, class*/; break;
3150 case enumeration_request
: min_size
+= sizeof(mDNSu32
); break;
3151 case reg_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
3152 case reconfirm_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */; break;
3153 case setdomain_request
: min_size
+= 1 /* domain */; break;
3154 case getproperty_request
: min_size
= 2; break;
3155 case port_mapping_request
: min_size
+= sizeof(mDNSu32
) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
3156 case addrinfo_request
: min_size
+= sizeof(mDNSu32
) + 4 /* v4/v6 */ + 1 /* hostname */; break;
3157 case send_bpf
: // Same as cancel_request below
3158 case cancel_request
: min_size
= 0; break;
3159 default: LogMsg("ERROR: validate_message - unsupported req type: %d", req
->hdr
.op
); min_size
= -1; break;
3162 if ((mDNSs32
)req
->data_bytes
< min_size
)
3163 { LogMsg("Invalid message %d bytes; min for %d is %d", req
->data_bytes
, req
->hdr
.op
, min_size
); AbortUnlinkAndFree(req
); return; }
3165 if (LightweightOp(req
->hdr
.op
) && !req
->terminate
)
3166 { LogMsg("Reg/Add/Update/Remove %d require existing connection", req
->hdr
.op
); AbortUnlinkAndFree(req
); return; }
3168 // check if client wants silent operation
3169 if (req
->hdr
.ipc_flags
& IPC_FLAGS_NOREPLY
) req
->no_reply
= 1;
3171 // If req->terminate is already set, this means this operation is sharing an existing connection
3172 if (req
->terminate
&& !LightweightOp(req
->hdr
.op
))
3174 request_state
*newreq
= NewRequest();
3175 newreq
->primary
= req
;
3176 newreq
->sd
= req
->sd
;
3177 newreq
->errsd
= req
->errsd
;
3178 newreq
->uid
= req
->uid
;
3179 newreq
->hdr
= req
->hdr
;
3180 newreq
->msgbuf
= req
->msgbuf
;
3181 newreq
->msgptr
= req
->msgptr
;
3182 newreq
->msgend
= req
->msgend
;
3186 // If we're shutting down, don't allow new client requests
3187 // We do allow "cancel" and "getproperty" during shutdown
3188 if (mDNSStorage
.ShutdownTime
&& req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
)
3190 err
= mStatus_ServiceNotRunning
;
3192 else switch(req
->hdr
.op
)
3194 // These are all operations that have their own first-class request_state object
3195 case connection_request
: LogOperation("%3d: DNSServiceCreateConnection START", req
->sd
);
3196 req
->terminate
= connection_termination
; break;
3197 case resolve_request
: err
= handle_resolve_request (req
); break;
3198 case query_request
: err
= handle_queryrecord_request (req
); break;
3199 case browse_request
: err
= handle_browse_request (req
); break;
3200 case reg_service_request
: err
= handle_regservice_request (req
); break;
3201 case enumeration_request
: err
= handle_enum_request (req
); break;
3202 case reconfirm_record_request
: err
= handle_reconfirm_request (req
); break;
3203 case setdomain_request
: err
= handle_setdomain_request (req
); break;
3204 case getproperty_request
: handle_getproperty_request (req
); break;
3205 case port_mapping_request
: err
= handle_port_mapping_request(req
); break;
3206 case addrinfo_request
: err
= handle_addrinfo_request (req
); break;
3207 case send_bpf
: /* Do nothing for send_bpf */ break;
3209 // These are all operations that work with an existing request_state object
3210 case reg_record_request
: err
= handle_regrecord_request (req
); break;
3211 case add_record_request
: err
= handle_add_request (req
); break;
3212 case update_record_request
: err
= handle_update_request (req
); break;
3213 case remove_record_request
: err
= handle_removerecord_request(req
); break;
3214 case cancel_request
: handle_cancel_request (req
); break;
3215 default: LogMsg("%3d: ERROR: Unsupported UDS req: %d", req
->sd
, req
->hdr
.op
);
3218 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3219 if (req
->msgbuf
) freeL("request_state msgbuf", req
->msgbuf
);
3221 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3222 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3223 if (req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
&& req
->hdr
.op
!= send_bpf
)
3225 const mStatus err_netorder
= dnssd_htonl(err
);
3226 send_all(req
->errsd
, (const char *)&err_netorder
, sizeof(err_netorder
));
3227 if (req
->errsd
!= req
->sd
)
3229 LogOperation("%3d: Error socket %d closed %08X %08X (%d)",
3230 req
->sd
, req
->errsd
, req
->hdr
.client_context
.u32
[1], req
->hdr
.client_context
.u32
[0], err
);
3231 dnssd_close(req
->errsd
);
3232 req
->errsd
= req
->sd
;
3233 // Also need to reset the parent's errsd, if this is a subordinate operation
3234 if (req
->primary
) req
->primary
->errsd
= req
->primary
->sd
;
3238 // Reset ready to accept the next req on this pipe
3239 if (req
->primary
) req
= req
->primary
;
3240 req
->ts
= t_morecoming
;
3242 req
->data_bytes
= 0;
3243 req
->msgbuf
= mDNSNULL
;
3244 req
->msgptr
= mDNSNULL
;
3248 mDNSlocal
void connect_callback(int fd
, short filter
, void *info
)
3250 dnssd_sockaddr_t cliaddr
;
3251 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(cliaddr
);
3252 dnssd_sock_t sd
= accept(fd
, (struct sockaddr
*) &cliaddr
, &len
);
3253 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3254 unsigned long optval
= 1;
3257 (void)filter
; // Unused
3258 (void)info
; // Unused
3260 if (!dnssd_SocketValid(sd
))
3262 if (dnssd_errno
!= dnssd_EWOULDBLOCK
) my_perror("ERROR: accept");
3267 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3268 if (setsockopt(sd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
3269 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3273 if (ioctlsocket(sd
, FIONBIO
, &optval
) != 0)
3275 if (fcntl(sd
, F_SETFL
, fcntl(sd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3278 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3284 request_state
*request
= NewRequest();
3285 request
->ts
= t_morecoming
;
3287 request
->errsd
= sd
;
3288 #if APPLE_OSX_mDNSResponder
3290 socklen_t xucredlen
= sizeof(x
);
3291 if (getsockopt(sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 && x
.cr_version
== XUCRED_VERSION
) request
->uid
= x
.cr_uid
;
3292 else my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
3293 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen
, x
.cr_version
, x
.cr_uid
, x
.cr_ngroups
);
3294 #endif // APPLE_OSX_mDNSResponder
3295 LogOperation("%3d: Adding FD for uid %u", request
->sd
, request
->uid
);
3296 udsSupportAddFDToEventLoop(sd
, request_callback
, request
, &request
->platform_data
);
3300 mDNSlocal mDNSBool
uds_socket_setup(dnssd_sock_t skt
)
3302 #if defined(SO_NP_EXTENSIONS)
3303 struct so_np_extensions sonpx
;
3304 socklen_t optlen
= sizeof(struct so_np_extensions
);
3305 sonpx
.npx_flags
= SONPX_SETOPTSHUT
;
3306 sonpx
.npx_mask
= SONPX_SETOPTSHUT
;
3307 if (setsockopt(skt
, SOL_SOCKET
, SO_NP_EXTENSIONS
, &sonpx
, optlen
) < 0)
3308 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
3311 // SEH: do we even need to do this on windows?
3312 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
3314 if (ioctlsocket(skt
, FIONBIO
, &opt
) != 0)
3316 if (fcntl(skt
, F_SETFL
, fcntl(skt
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3319 my_perror("ERROR: could not set listen socket to non-blocking mode");
3323 if (listen(skt
, LISTENQ
) != 0)
3325 my_perror("ERROR: could not listen on listen socket");
3329 if (mStatus_NoError
!= udsSupportAddFDToEventLoop(skt
, connect_callback
, (void *) NULL
, (void **) NULL
))
3331 my_perror("ERROR: could not add listen socket to event loop");
3334 else LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt
);
3339 mDNSexport
int udsserver_init(dnssd_sock_t skts
[], mDNSu32 count
)
3341 dnssd_sockaddr_t laddr
;
3345 LogInfo("udsserver_init");
3347 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
3350 FILE *fp
= fopen(PID_FILE
, "w");
3353 fprintf(fp
, "%d\n", getpid());
3360 for (i
= 0; i
< count
; i
++)
3361 if (dnssd_SocketValid(skts
[i
]) && !uds_socket_setup(skts
[i
]))
3366 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3367 if (!dnssd_SocketValid(listenfd
))
3369 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
3373 mDNSPlatformMemZero(&laddr
, sizeof(laddr
));
3375 #if defined(USE_TCP_LOOPBACK)
3377 laddr
.sin_family
= AF_INET
;
3378 laddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
3379 laddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3380 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
3383 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
3389 mode_t mask
= umask(0);
3390 unlink(MDNS_UDS_SERVERPATH
); // OK if this fails
3391 laddr
.sun_family
= AF_LOCAL
;
3392 #ifndef NOT_HAVE_SA_LEN
3393 // According to Stevens (section 3.2), there is no portable way to
3394 // determine whether sa_len is defined on a particular platform.
3395 laddr
.sun_len
= sizeof(struct sockaddr_un
);
3397 mDNSPlatformStrCopy(laddr
.sun_path
, MDNS_UDS_SERVERPATH
);
3398 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
3402 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
3408 if (!uds_socket_setup(listenfd
)) goto error
;
3411 #if !defined(PLATFORM_NO_RLIMIT)
3413 // Set maximum number of open file descriptors
3414 #define MIN_OPENFILES 10240
3415 struct rlimit maxfds
, newfds
;
3417 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
3418 // you have to get and set rlimits once before getrlimit will return sensible values
3419 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
3420 if (setrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
3422 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
3423 newfds
.rlim_max
= (maxfds
.rlim_max
> MIN_OPENFILES
) ? maxfds
.rlim_max
: MIN_OPENFILES
;
3424 newfds
.rlim_cur
= (maxfds
.rlim_cur
> MIN_OPENFILES
) ? maxfds
.rlim_cur
: MIN_OPENFILES
;
3425 if (newfds
.rlim_max
!= maxfds
.rlim_max
|| newfds
.rlim_cur
!= maxfds
.rlim_cur
)
3426 if (setrlimit(RLIMIT_NOFILE
, &newfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
3428 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
3429 debugf("maxfds.rlim_max %d", (long)maxfds
.rlim_max
);
3430 debugf("maxfds.rlim_cur %d", (long)maxfds
.rlim_cur
);
3434 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
3435 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
3436 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
3437 mDNS_GetDomains(&mDNSStorage
, &mDNSStorage
.AutomaticBrowseDomainQ
, mDNS_DomainTypeBrowseAutomatic
,
3438 mDNSNULL
, mDNSInterface_LocalOnly
, AutomaticBrowseDomainChange
, mDNSNULL
);
3440 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
3441 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeRegistration
);
3442 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeBrowse
);
3443 AddAutoBrowseDomain(0, &localdomain
);
3445 udsserver_handle_configchange(&mDNSStorage
);
3450 my_perror("ERROR: udsserver_init");
3454 mDNSexport
int udsserver_exit(void)
3456 // Cancel all outstanding client requests
3457 while (all_requests
) AbortUnlinkAndFree(all_requests
);
3459 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
3460 // created in udsserver_init, and others we created as a result of reading local configuration data
3461 while (LocalDomainEnumRecords
)
3463 ARListElem
*rem
= LocalDomainEnumRecords
;
3464 LocalDomainEnumRecords
= LocalDomainEnumRecords
->next
;
3465 mDNS_Deregister(&mDNSStorage
, &rem
->ar
);
3468 // If the launching environment created no listening socket,
3469 // that means we created it ourselves, so we should clean it up on exit
3470 if (dnssd_SocketValid(listenfd
))
3472 dnssd_close(listenfd
);
3473 #if !defined(USE_TCP_LOOPBACK)
3474 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
3475 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
3476 // It would be nice if we could find a solution to this problem
3477 if (unlink(MDNS_UDS_SERVERPATH
))
3478 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH
);
3482 if (PID_FILE
[0]) unlink(PID_FILE
);
3487 mDNSlocal
void LogClientInfo(mDNS
*const m
, const request_state
*req
)
3490 if (req
->primary
) mDNS_snprintf(prefix
, sizeof(prefix
), " -> ");
3491 else mDNS_snprintf(prefix
, sizeof(prefix
), "%3d:", req
->sd
);
3493 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
3495 if (!req
->terminate
)
3496 LogMsgNoIdent("%s No operation yet on this socket", prefix
);
3497 else if (req
->terminate
== connection_termination
)
3499 int num_records
= 0, num_ops
= 0;
3500 const registered_record_entry
*p
;
3501 const request_state
*r
;
3502 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
) num_records
++;
3503 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) num_ops
++;
3504 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s", prefix
,
3505 num_records
, num_records
!= 1 ? "s" : "",
3506 num_ops
, num_ops
!= 1 ? "s" : "");
3507 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
3508 LogMsgNoIdent(" -> DNSServiceRegisterRecord %3d %s", p
->key
, ARDisplayString(m
, p
->rr
));
3509 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) LogClientInfo(m
, r
);
3511 else if (req
->terminate
== regservice_termination_callback
)
3513 service_instance
*ptr
;
3514 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
3515 LogMsgNoIdent("%s DNSServiceRegister %##s %u/%u",
3516 (ptr
== req
->u
.servicereg
.instances
) ? prefix
: " ",
3517 ptr
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(req
->u
.servicereg
.port
), SRS_PORT(&ptr
->srs
));
3519 else if (req
->terminate
== browse_termination_callback
)
3522 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
3523 LogMsgNoIdent("%s DNSServiceBrowse %##s", (blist
== req
->u
.browser
.browsers
) ? prefix
: " ", blist
->q
.qname
.c
);
3525 else if (req
->terminate
== resolve_termination_callback
)
3526 LogMsgNoIdent("%s DNSServiceResolve %##s", prefix
, req
->u
.resolve
.qsrv
.qname
.c
);
3527 else if (req
->terminate
== queryrecord_termination_callback
)
3528 LogMsgNoIdent("%s DNSServiceQueryRecord %##s (%s)", prefix
, req
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(req
->u
.queryrecord
.q
.qtype
));
3529 else if (req
->terminate
== enum_termination_callback
)
3530 LogMsgNoIdent("%s DNSServiceEnumerateDomains %##s", prefix
, req
->u
.enumeration
.q_all
.qname
.c
);
3531 else if (req
->terminate
== port_mapping_termination_callback
)
3532 LogMsgNoIdent("%s DNSServiceNATPortMapping %.4a %s%s Int %d Req %d Ext %d Req TTL %d Granted TTL %d",
3534 &req
->u
.pm
.NATinfo
.ExternalAddress
,
3535 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
3536 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
3537 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
3538 mDNSVal16(req
->u
.pm
.ReqExt
),
3539 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
3540 req
->u
.pm
.NATinfo
.NATLease
,
3541 req
->u
.pm
.NATinfo
.Lifetime
);
3542 else if (req
->terminate
== addrinfo_termination_callback
)
3543 LogMsgNoIdent("%s DNSServiceGetAddrInfo %s%s %##s", prefix
,
3544 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
? "v4" : " ",
3545 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
? "v6" : " ",
3546 req
->u
.addrinfo
.q4
.qname
.c
);
3548 LogMsgNoIdent("%s Unrecognized operation %p", prefix
, req
->terminate
);
3551 mDNSlocal
void LogAuthRecords(mDNS
*const m
, const mDNSs32 now
, AuthRecord
*ResourceRecords
, int *proxy
)
3553 mDNSBool showheader
= mDNStrue
;
3554 const AuthRecord
*ar
;
3555 OwnerOptData owner
= zeroOwner
;
3556 for (ar
= ResourceRecords
; ar
; ar
=ar
->next
)
3558 const char *const ifname
= InterfaceNameForID(m
, ar
->resrec
.InterfaceID
);
3559 if ((ar
->WakeUp
.HMAC
.l
[0] != 0) == (proxy
!= mDNSNULL
))
3561 if (showheader
) { showheader
= mDNSfalse
; LogMsgNoIdent(" Int Next Expire State"); }
3562 if (proxy
) (*proxy
)++;
3563 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)))
3566 if (owner
.password
.l
[0])
3567 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
3568 else if (!mDNSSameEthAddress(&owner
.HMAC
, &owner
.IMAC
))
3569 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, owner
.seq
);
3571 LogMsgNoIdent("Proxying for %.6a seq %d", &owner
.HMAC
, owner
.seq
);
3573 if (AuthRecord_uDNS(ar
))
3574 LogMsgNoIdent("%7d %7d %7d %7d %s",
3575 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
3576 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
3577 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
3578 ar
->state
, ARDisplayString(m
, ar
));
3579 else if (ar
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
)
3580 LogMsgNoIdent(" LO %s", ARDisplayString(m
, ar
));
3581 else if (ar
->resrec
.InterfaceID
== mDNSInterface_P2P
)
3582 LogMsgNoIdent(" PP %s", ARDisplayString(m
, ar
));
3584 LogMsgNoIdent("%7d %7d %7d %7s %s",
3585 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
3586 ar
->AnnounceCount
? (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
: 0,
3587 ar
->TimeExpire
? (ar
->TimeExpire
- now
) / mDNSPlatformOneSecond
: 0,
3588 ifname
? ifname
: "ALL",
3589 ARDisplayString(m
, ar
));
3590 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
3593 if (showheader
) LogMsgNoIdent("<None>");
3596 mDNSexport
void udsserver_info(mDNS
*const m
)
3598 const mDNSs32 now
= mDNS_TimeNow(m
);
3599 mDNSu32 CacheUsed
= 0, CacheActive
= 0, slot
;
3600 int ProxyA
= 0, ProxyD
= 0;
3601 const CacheGroup
*cg
;
3602 const CacheRecord
*cr
;
3603 const DNSQuestion
*q
;
3604 const DNameListElem
*d
;
3605 const SearchListElem
*s
;
3607 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
3609 LogMsgNoIdent("------------ Cache -------------");
3610 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
3611 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
3612 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
3614 CacheUsed
++; // Count one cache entity for the CacheGroup object
3615 for (cr
= cg
->members
; cr
; cr
=cr
->next
)
3617 const mDNSs32 remain
= cr
->resrec
.rroriginalttl
- (now
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
3619 mDNSInterfaceID InterfaceID
= cr
->resrec
.InterfaceID
;
3620 if (!InterfaceID
&& cr
->resrec
.rDNSServer
)
3621 InterfaceID
= cr
->resrec
.rDNSServer
->interface
;
3622 ifname
= InterfaceNameForID(m
, InterfaceID
);
3624 if (cr
->CRActiveQuestion
) CacheActive
++;
3625 LogMsgNoIdent("%3d %s%8ld %-7s%s %-6s%s",
3627 cr
->CRActiveQuestion
? "*" : " ",
3629 ifname
? ifname
: "-U-",
3630 (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) ? "-" :
3631 (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ? " " : "+",
3632 DNSTypeName(cr
->resrec
.rrtype
),
3633 CRDisplayString(m
, cr
));
3634 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
3638 if (m
->rrcache_totalused
!= CacheUsed
)
3639 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m
->rrcache_totalused
, CacheUsed
);
3640 if (m
->rrcache_active
!= CacheActive
)
3641 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m
->rrcache_active
, CacheActive
);
3642 LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed
, CacheActive
);
3644 LogMsgNoIdent("--------- Auth Records ---------");
3645 LogAuthRecords(m
, now
, m
->ResourceRecords
, mDNSNULL
);
3647 LogMsgNoIdent("------ Duplicate Records -------");
3648 LogAuthRecords(m
, now
, m
->DuplicateRecords
, mDNSNULL
);
3650 LogMsgNoIdent("----- Auth Records Proxied -----");
3651 LogAuthRecords(m
, now
, m
->ResourceRecords
, &ProxyA
);
3653 LogMsgNoIdent("-- Duplicate Records Proxied ---");
3654 LogAuthRecords(m
, now
, m
->DuplicateRecords
, &ProxyD
);
3656 LogMsgNoIdent("---------- Questions -----------");
3657 if (!m
->Questions
) LogMsgNoIdent("<None>");
3662 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
3663 for (q
= m
->Questions
; q
; q
=q
->next
)
3665 mDNSs32 i
= q
->ThisQInterval
/ mDNSPlatformOneSecond
;
3666 mDNSs32 n
= (NextQSendTime(q
) - now
) / mDNSPlatformOneSecond
;
3667 char *ifname
= InterfaceNameForID(m
, q
->InterfaceID
);
3669 if (q
->ThisQInterval
) CacheActive
++;
3670 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s",
3672 ifname
? ifname
: mDNSOpaque16IsZero(q
->TargetQID
) ? "" : "-U-",
3673 mDNSOpaque16IsZero(q
->TargetQID
) ? (q
->LongLived
? "l" : " ") : (q
->LongLived
? "L" : "O"),
3674 PrivateQuery(q
) ? "P" : " ",
3675 q
->CurrentAnswers
, q
->validDNSServers
.l
[1], q
->validDNSServers
.l
[0], q
, q
->DuplicateOf
,
3676 q
->SuppressUnusable
, q
->SuppressQuery
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
3677 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
3679 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed
, CacheUsed
> 1 ? "s" : "", CacheActive
);
3682 LogMsgNoIdent("----- Local-Only Questions -----");
3683 if (!m
->LocalOnlyQuestions
) LogMsgNoIdent("<None>");
3684 else for (q
= m
->LocalOnlyQuestions
; q
; q
=q
->next
)
3685 LogMsgNoIdent(" %5d %-6s%##s%s",
3686 q
->CurrentAnswers
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
3688 LogMsgNoIdent("---- Active Client Requests ----");
3689 if (!all_requests
) LogMsgNoIdent("<None>");
3692 const request_state
*req
, *r
;
3693 for (req
= all_requests
; req
; req
=req
->next
)
3695 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
3697 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
) if (r
== req
->primary
) goto foundparent
;
3698 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req
->sd
);
3700 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
3701 LogClientInfo(m
, req
);
3706 LogMsgNoIdent("-------- NAT Traversals --------");
3707 if (!m
->NATTraversals
) LogMsgNoIdent("<None>");
3710 const NATTraversalInfo
*nat
;
3711 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
3714 LogMsgNoIdent("%p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d",
3715 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
3716 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
3717 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
3718 nat
->retryInterval
/ mDNSPlatformOneSecond
,
3719 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0);
3721 LogMsgNoIdent("%p Address Request Retry %5d Interval %5d", nat
,
3722 (m
->retryGetAddr
- now
) / mDNSPlatformOneSecond
,
3723 m
->retryIntervalGetAddr
/ mDNSPlatformOneSecond
);
3724 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
3728 LogMsgNoIdent("--------- AuthInfoList ---------");
3729 if (!m
->AuthInfoList
) LogMsgNoIdent("<None>");
3732 const DomainAuthInfo
*a
;
3733 for (a
= m
->AuthInfoList
; a
; a
= a
->next
)
3734 LogMsgNoIdent("%##s %##s%s", a
->domain
.c
, a
->keyname
.c
, a
->AutoTunnel
? " AutoTunnel" : "");
3737 #if APPLE_OSX_mDNSResponder
3738 LogMsgNoIdent("--------- TunnelClients --------");
3739 if (!m
->TunnelClients
) LogMsgNoIdent("<None>");
3742 const ClientTunnel
*c
;
3743 for (c
= m
->TunnelClients
; c
; c
= c
->next
)
3744 LogMsgNoIdent("%##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
3745 c
->dstname
.c
, &c
->loc_inner
, &c
->loc_outer
, &c
->loc_outer6
, &c
->rmt_inner
, &c
->rmt_outer
, mDNSVal16(c
->rmt_outer_port
), &c
->rmt_outer6
, c
->q
.ThisQInterval
);
3747 #endif // APPLE_OSX_mDNSResponder
3749 LogMsgNoIdent("---------- Misc State ----------");
3751 LogMsgNoIdent("PrimaryMAC: %.6a", &m
->PrimaryMAC
);
3753 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
3755 m
->SleepState
== SleepState_Awake
? "Awake" :
3756 m
->SleepState
== SleepState_Transferring
? "Transferring" :
3757 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?",
3760 if (!m
->SPSSocket
) LogMsgNoIdent("Not offering Sleep Proxy Service");
3761 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m
->SPSRecords
.RR_SRV
.resrec
.name
->c
);
3763 if (m
->ProxyRecords
== ProxyA
+ ProxyD
) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
);
3764 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
, m
->ProxyRecords
);
3766 LogMsgNoIdent("------ Auto Browse Domains -----");
3767 if (!AutoBrowseDomains
) LogMsgNoIdent("<None>");
3768 else for (d
=AutoBrowseDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
3770 LogMsgNoIdent("--- Auto Registration Domains --");
3771 if (!AutoRegistrationDomains
) LogMsgNoIdent("<None>");
3772 else for (d
=AutoRegistrationDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
3774 LogMsgNoIdent("--- Search Domains --");
3775 if (!SearchList
) LogMsgNoIdent("<None>");
3778 for (s
=SearchList
; s
; s
=s
->next
)
3780 LogMsgNoIdent("%##s", s
->domain
.c
);
3783 LogMsgNoIdent("---- Task Scheduling Timers ----");
3785 if (!m
->NewQuestions
)
3786 LogMsgNoIdent("NewQuestion <NONE>");
3788 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
3789 m
->NewQuestions
->DelayAnswering
, m
->NewQuestions
->DelayAnswering
-now
,
3790 m
->NewQuestions
->qname
.c
, DNSTypeName(m
->NewQuestions
->qtype
));
3792 if (!m
->NewLocalOnlyQuestions
)
3793 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
3795 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
3796 m
->NewLocalOnlyQuestions
->qname
.c
, DNSTypeName(m
->NewLocalOnlyQuestions
->qtype
));
3798 if (!m
->NewLocalRecords
)
3799 LogMsgNoIdent("NewLocalRecords <NONE>");
3801 LogMsgNoIdent("NewLocalRecords %02X %s", m
->NewLocalRecords
->resrec
.RecordType
, ARDisplayString(m
, m
->NewLocalRecords
));
3803 LogMsgNoIdent("SPSProxyListChanged%s", m
->SPSProxyListChanged
? "" : " <NONE>");
3804 LogMsgNoIdent("LocalRemoveEvents%s", m
->LocalRemoveEvents
? "" : " <NONE>");
3806 #define LogTimer(MSG,T) LogMsgNoIdent( MSG " %08X %11d %08X %11d", (T), (T), (T)-now, (T)-now)
3808 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
3809 LogMsgNoIdent("m->timenow %08X %11d", now
, now
);
3810 LogMsgNoIdent("m->timenow_adjust %08X %11d", m
->timenow_adjust
, m
->timenow_adjust
);
3811 LogTimer("m->NextScheduledEvent ", m
->NextScheduledEvent
);
3813 #ifndef UNICAST_DISABLED
3814 LogTimer("m->NextuDNSEvent ", m
->NextuDNSEvent
);
3815 LogTimer("m->NextSRVUpdate ", m
->NextSRVUpdate
);
3816 LogTimer("m->NextScheduledNATOp ", m
->NextScheduledNATOp
);
3817 LogTimer("m->retryGetAddr ", m
->retryGetAddr
);
3820 LogTimer("m->NextCacheCheck ", m
->NextCacheCheck
);
3821 LogTimer("m->NextScheduledSPS ", m
->NextScheduledSPS
);
3822 LogTimer("m->NextScheduledSPRetry ", m
->NextScheduledSPRetry
);
3823 LogTimer("m->DelaySleep ", m
->DelaySleep
);
3825 LogTimer("m->NextScheduledQuery ", m
->NextScheduledQuery
);
3826 LogTimer("m->NextScheduledProbe ", m
->NextScheduledProbe
);
3827 LogTimer("m->NextScheduledResponse", m
->NextScheduledResponse
);
3829 LogTimer("m->SuppressSending ", m
->SuppressSending
);
3830 LogTimer("m->SuppressProbes ", m
->SuppressProbes
);
3831 LogTimer("m->ProbeFailTime ", m
->ProbeFailTime
);
3832 LogTimer("m->DelaySleep ", m
->DelaySleep
);
3833 LogTimer("m->SleepLimit ", m
->SleepLimit
);
3834 LogMsgNoIdent("m->RegisterAutoTunnel6 %08X", m
->RegisterAutoTunnel6
);
3837 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
3838 mDNSexport
void uds_validatelists(void)
3840 const request_state
*req
, *p
;
3841 for (req
= all_requests
; req
; req
=req
->next
)
3843 if (req
->next
== (request_state
*)~0 || (req
->sd
< 0 && req
->sd
!= -2))
3844 LogMemCorruption("UDS request list: %p is garbage (%d)", req
, req
->sd
);
3846 if (req
->primary
== req
)
3847 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req
, req
->sd
);
3849 if (req
->primary
&& req
->replies
)
3850 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
3851 req
, req
->sd
, req
->primary
&& req
->replies
);
3855 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req
, p
, req
->sd
);
3856 else if (p
&& (p
->next
== (request_state
*)~0 || (p
->sd
< 0 && p
->sd
!= -2)))
3857 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req
, p
, p
->sd
);
3860 for (rep
= req
->replies
; rep
; rep
=rep
->next
)
3861 if (rep
->next
== (reply_state
*)~0)
3862 LogMemCorruption("UDS req->replies: %p is garbage", rep
);
3864 if (req
->terminate
== connection_termination
)
3866 registered_record_entry
*r
;
3867 for (r
= req
->u
.reg_recs
; r
; r
=r
->next
)
3868 if (r
->next
== (registered_record_entry
*)~0)
3869 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r
);
3871 else if (req
->terminate
== regservice_termination_callback
)
3873 service_instance
*s
;
3874 for (s
= req
->u
.servicereg
.instances
; s
; s
=s
->next
)
3875 if (s
->next
== (service_instance
*)~0)
3876 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s
);
3878 else if (req
->terminate
== browse_termination_callback
)
3881 for (b
= req
->u
.browser
.browsers
; b
; b
=b
->next
)
3882 if (b
->next
== (browser_t
*)~0)
3883 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b
);
3888 for (d
= SCPrefBrowseDomains
; d
; d
=d
->next
)
3889 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
3890 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
3893 for (b
= LocalDomainEnumRecords
; b
; b
=b
->next
)
3894 if (b
->next
== (ARListElem
*)~0 || b
->ar
.resrec
.name
->c
[0] > 63)
3895 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b
, b
->ar
.resrec
.name
->c
[0]);
3897 for (d
= AutoBrowseDomains
; d
; d
=d
->next
)
3898 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
3899 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
3901 for (d
= AutoRegistrationDomains
; d
; d
=d
->next
)
3902 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
3903 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
3905 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
3907 mDNSlocal
int send_msg(request_state
*const req
)
3909 reply_state
*const rep
= req
->replies
; // Send the first waiting reply
3911 if (req
->no_reply
) return(t_complete
);
3913 ConvertHeaderBytes(rep
->mhdr
);
3914 nwriten
= send(req
->sd
, (char *)&rep
->mhdr
+ rep
->nwriten
, rep
->totallen
- rep
->nwriten
, 0);
3915 ConvertHeaderBytes(rep
->mhdr
);
3919 if (dnssd_errno
== dnssd_EINTR
|| dnssd_errno
== dnssd_EWOULDBLOCK
) nwriten
= 0;
3922 #if !defined(PLATFORM_NO_EPIPE)
3923 if (dnssd_errno
== EPIPE
)
3924 return(req
->ts
= t_terminated
);
3928 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
3929 rep
->totallen
- rep
->nwriten
, rep
->totallen
, req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3934 rep
->nwriten
+= nwriten
;
3935 return (rep
->nwriten
== rep
->totallen
) ? t_complete
: t_morecoming
;
3938 mDNSexport mDNSs32
udsserver_idle(mDNSs32 nextevent
)
3940 mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
3941 request_state
**req
= &all_requests
;
3945 request_state
*const r
= *req
;
3947 if (r
->terminate
== resolve_termination_callback
)
3948 if (r
->u
.resolve
.ReportTime
&& now
- r
->u
.resolve
.ReportTime
>= 0)
3950 r
->u
.resolve
.ReportTime
= 0;
3951 LogMsgNoIdent("Client application bug: DNSServiceResolve(%##s) active for over two minutes. "
3952 "This places considerable burden on the network.", r
->u
.resolve
.qsrv
.qname
.c
);
3955 // Note: Only primary req's have reply lists, not subordinate req's.
3956 while (r
->replies
) // Send queued replies
3958 transfer_state result
;
3959 if (r
->replies
->next
) r
->replies
->rhdr
->flags
|= dnssd_htonl(kDNSServiceFlagsMoreComing
);
3960 result
= send_msg(r
); // Returns t_morecoming if buffer full because client is not reading
3961 if (result
== t_complete
)
3963 reply_state
*fptr
= r
->replies
;
3964 r
->replies
= r
->replies
->next
;
3965 freeL("reply_state/udsserver_idle", fptr
);
3966 r
->time_blocked
= 0; // reset failure counter after successful send
3967 r
->unresponsiveness_reports
= 0;
3970 else if (result
== t_terminated
|| result
== t_error
)
3972 LogMsg("%3d: Could not write data to client because of error - aborting connection", r
->sd
);
3973 LogClientInfo(&mDNSStorage
, r
);
3979 if (r
->replies
) // If we failed to send everything, check our time_blocked timer
3981 if (nextevent
- now
> mDNSPlatformOneSecond
) nextevent
= now
+ mDNSPlatformOneSecond
;
3983 if (mDNSStorage
.SleepState
!= SleepState_Awake
) r
->time_blocked
= 0;
3984 else if (!r
->time_blocked
) r
->time_blocked
= NonZeroTime(now
);
3985 else if (now
- r
->time_blocked
>= 10 * mDNSPlatformOneSecond
* (r
->unresponsiveness_reports
+1))
3988 struct reply_state
*x
= r
->replies
;
3989 while (x
) { num
++; x
=x
->next
; }
3990 LogMsg("%3d: Could not write data to client after %ld seconds, %d repl%s waiting",
3991 r
->sd
, (now
- r
->time_blocked
) / mDNSPlatformOneSecond
, num
, num
== 1 ? "y" : "ies");
3992 if (++r
->unresponsiveness_reports
>= 60)
3994 LogMsg("%3d: Client unresponsive; aborting connection", r
->sd
);
3995 LogClientInfo(&mDNSStorage
, r
);
4001 if (!dnssd_SocketValid(r
->sd
)) // If this request is finished, unlink it from the list and free the memory
4003 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
4005 freeL("request_state/udsserver_idle", r
);
4013 struct CompileTimeAssertionChecks_uds_daemon
4015 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4016 // other overly-large structures instead of having a pointer to them, can inadvertently
4017 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
4018 char sizecheck_request_state
[(sizeof(request_state
) <= 2000) ? 1 : -1];
4019 char sizecheck_registered_record_entry
[(sizeof(registered_record_entry
) <= 60) ? 1 : -1];
4020 char sizecheck_service_instance
[(sizeof(service_instance
) <= 6552) ? 1 : -1];
4021 char sizecheck_browser_t
[(sizeof(browser_t
) <= 1016) ? 1 : -1];
4022 char sizecheck_reply_hdr
[(sizeof(reply_hdr
) <= 12) ? 1 : -1];
4023 char sizecheck_reply_state
[(sizeof(reply_state
) <= 64) ? 1 : -1];