1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2011 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 // Normally we append search domains only for queries with a single label that are not
39 // fully qualified. This can be overridden to apply search domains for queries (that are
40 // not fully qualified) with any number of labels e.g., moon, moon.cs, moon.cs.be, etc.
41 mDNSBool AlwaysAppendSearchDomains
= mDNSfalse
;
43 // Apple-specific functionality, not required for other platforms
44 #if APPLE_OSX_mDNSResponder
45 #include <sys/ucred.h>
51 #if APPLE_OSX_mDNSResponder
52 #include <WebFilterDNS/WebFilterDNS.h>
56 int WCFIsServerRunning(WCFConnection
*conn
) __attribute__((weak_import
));
57 int WCFNameResolvesToAddr(WCFConnection
*conn
, char* domainName
, struct sockaddr
* address
, uid_t userid
) __attribute__((weak_import
));
58 int WCFNameResolvesToName(WCFConnection
*conn
, char* fromName
, char* toName
, uid_t userid
) __attribute__((weak_import
));
60 // Do we really need to define a macro for "if"?
61 #define CHECK_WCF_FUNCTION(X) if (X)
66 #endif // APPLE_OSX_mDNSResponder
68 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
69 // User IDs for real user accounts start at 501 and count up from there
70 #define SystemUID(X) ((X) <= 500)
72 // ***************************************************************************
73 #if COMPILER_LIKES_PRAGMA_MARK
75 #pragma mark - Types and Data Structures
87 typedef struct request_state request_state
;
89 typedef void (*req_termination_fn
)(request_state
*request
);
91 typedef struct registered_record_entry
93 struct registered_record_entry
*next
;
95 client_context_t regrec_client_context
;
96 request_state
*request
;
97 mDNSBool external_advertise
;
98 mDNSInterfaceID origInterfaceID
;
99 AuthRecord
*rr
; // Pointer to variable-sized AuthRecord (Why a pointer? Why not just embed it here?)
100 } registered_record_entry
;
102 // A single registered service: ServiceRecordSet + bookkeeping
103 // Note that we duplicate some fields from parent service_info object
104 // to facilitate cleanup, when instances and parent may be deallocated at different times.
105 typedef struct service_instance
107 struct service_instance
*next
;
108 request_state
*request
;
109 AuthRecord
*subtypes
;
110 mDNSBool renameonmemfree
; // Set on config change when we deregister original name
111 mDNSBool clientnotified
; // Has client been notified of successful registration yet?
112 mDNSBool default_local
; // is this the "local." from an empty-string registration?
113 mDNSBool external_advertise
; // is this is being advertised externally?
115 ServiceRecordSet srs
; // note -- variable-sized object -- must be last field in struct
118 // for multi-domain default browsing
119 typedef struct browser_t
121 struct browser_t
*next
;
129 request_state
*primary
; // If this operation is on a shared socket, pointer to primary
130 // request_state for the original DNSServiceCreateConnection() operation
134 void * platform_data
;
136 // Note: On a shared connection these fields in the primary structure, including hdr, are re-used
137 // for each new request. This is because, until we've read the ipc_msg_hdr to find out what the
138 // operation is, we don't know if we're going to need to allocate a new request_state or not.
140 mDNSu32 hdr_bytes
; // bytes of header already read
142 mDNSu32 data_bytes
; // bytes of message data already read
143 char *msgbuf
; // pointer to data storage to pass to free()
144 const char *msgptr
; // pointer to data to be read from (may be modified)
145 char *msgend
; // pointer to byte after last byte of message
147 // reply, termination, error, and client context info
148 int no_reply
; // don't send asynchronous replies to client
149 mDNSs32 time_blocked
; // record time of a blocked client
150 int unresponsiveness_reports
;
151 struct reply_state
*replies
; // corresponding (active) reply list
152 req_termination_fn terminate
;
153 DNSServiceFlags flags
;
157 registered_record_entry
*reg_recs
; // list of registrations for a connection-oriented request
160 mDNSInterfaceID interface_id
;
161 mDNSBool default_domain
;
168 mDNSInterfaceID InterfaceID
;
173 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
];
175 mDNSBool default_domain
;
177 mDNSBool autoname
; // Set if this name is tied to the Computer Name
178 mDNSBool autorename
; // Set if this client wants us to automatically rename on conflict
179 mDNSBool allowremotequery
; // Respond to unicast queries from outside the local link?
181 service_instance
*instances
;
185 mDNSInterfaceID interface_id
;
195 mDNSIPPort ReqExt
; // External port we originally requested, for logging purposes
196 NATTraversalInfo NATinfo
;
201 DNSServiceFlags flags
;
204 DNSQuestion q_default
;
215 const ResourceRecord
*txt
;
216 const ResourceRecord
*srv
;
218 mDNSBool external_advertise
;
223 // struct physically sits between ipc message header and call-specific fields in the message buffer
226 DNSServiceFlags flags
; // Note: This field is in NETWORK byte order
227 mDNSu32 ifi
; // Note: This field is in NETWORK byte order
228 DNSServiceErrorType error
; // Note: This field is in NETWORK byte order
231 typedef struct reply_state
233 struct reply_state
*next
; // If there are multiple unsent replies
240 // ***************************************************************************
241 #if COMPILER_LIKES_PRAGMA_MARK
243 #pragma mark - Globals
247 mDNSexport mDNS mDNSStorage
;
248 mDNSexport
const char ProgramName
[] = "mDNSResponder";
250 static dnssd_sock_t listenfd
= dnssd_InvalidSocket
;
251 static request_state
*all_requests
= NULL
;
253 // Note asymmetry here between registration and browsing.
254 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
255 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
256 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
257 // 1. SCPrefBrowseDomains (local configuration data)
258 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
259 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
260 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
262 mDNSexport DNameListElem
*AutoRegistrationDomains
; // Domains where we automatically register for empty-string registrations
264 static DNameListElem
*SCPrefBrowseDomains
; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
265 static ARListElem
*LocalDomainEnumRecords
; // List of locally-generated PTR records to augment those we learn from the network
266 mDNSexport DNameListElem
*AutoBrowseDomains
; // List created from those local-only PTR records plus records we get from the network
268 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
269 // n get_string() calls w/o buffer overrun
270 // initialization, setup/teardown functions
272 // If a platform specifies its own PID file name, we use that
274 #define PID_FILE "/var/run/mDNSResponder.pid"
277 // ***************************************************************************
278 #if COMPILER_LIKES_PRAGMA_MARK
280 #pragma mark - General Utility Functions
283 mDNSlocal
void FatalError(char *errmsg
)
286 LogMsg("%s: %s", errmsg
, dnssd_strerror(dnssd_errno
));
287 *ptr
= 0; // On OS X abort() doesn't generate a crash log, but writing to zero does
288 abort(); // On platforms where writing to zero doesn't generate an exception, abort instead
291 mDNSlocal mDNSu32
dnssd_htonl(mDNSu32 l
)
294 char *data
= (char*) &ret
;
295 put_uint32(l
, &data
);
299 // hack to search-replace perror's to LogMsg's
300 mDNSlocal
void my_perror(char *errmsg
)
302 LogMsg("%s: %d (%s)", errmsg
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
305 mDNSlocal
void abort_request(request_state
*req
)
307 if (req
->terminate
== (req_termination_fn
)~0)
308 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req
, req
->terminate
); return; }
310 // First stop whatever mDNSCore operation we were doing
311 // If this is actually a shared connection operation, then its req->terminate function will scan
312 // the all_requests list and terminate any subbordinate operations sharing this file descriptor
313 if (req
->terminate
) req
->terminate(req
);
315 if (!dnssd_SocketValid(req
->sd
))
316 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req
, req
->sd
); return; }
318 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
321 if (req
->errsd
!= req
->sd
) LogOperation("%3d: Removing FD and closing errsd %d", req
->sd
, req
->errsd
);
322 else LogOperation("%3d: Removing FD", req
->sd
);
323 udsSupportRemoveFDFromEventLoop(req
->sd
, req
->platform_data
); // Note: This also closes file descriptor req->sd for us
324 if (req
->errsd
!= req
->sd
) { dnssd_close(req
->errsd
); req
->errsd
= req
->sd
; }
326 while (req
->replies
) // free pending replies
328 reply_state
*ptr
= req
->replies
;
329 req
->replies
= req
->replies
->next
;
330 freeL("reply_state (abort)", ptr
);
334 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
335 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
336 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
337 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
338 req
->sd
= req
->errsd
= -2;
340 req
->sd
= req
->errsd
= dnssd_InvalidSocket
;
342 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
343 req
->terminate
= (req_termination_fn
)~0;
346 mDNSlocal
void AbortUnlinkAndFree(request_state
*req
)
348 request_state
**p
= &all_requests
;
350 while (*p
&& *p
!= req
) p
=&(*p
)->next
;
351 if (*p
) { *p
= req
->next
; freeL("request_state/AbortUnlinkAndFree", req
); }
352 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req
);
355 mDNSlocal reply_state
*create_reply(const reply_op_t op
, const size_t datalen
, request_state
*const request
)
359 if ((unsigned)datalen
< sizeof(reply_hdr
))
361 LogMsg("ERROR: create_reply - data length less than length of required fields");
365 reply
= mallocL("reply_state", sizeof(reply_state
) + datalen
- sizeof(reply_hdr
));
366 if (!reply
) FatalError("ERROR: malloc");
368 reply
->next
= mDNSNULL
;
369 reply
->totallen
= (mDNSu32
)datalen
+ sizeof(ipc_msg_hdr
);
372 reply
->mhdr
->version
= VERSION
;
373 reply
->mhdr
->datalen
= (mDNSu32
)datalen
;
374 reply
->mhdr
->ipc_flags
= 0;
375 reply
->mhdr
->op
= op
;
376 reply
->mhdr
->client_context
= request
->hdr
.client_context
;
377 reply
->mhdr
->reg_index
= 0;
382 // Append a reply to the list in a request object
383 // If our request is sharing a connection, then we append our reply_state onto the primary's list
384 mDNSlocal
void append_reply(request_state
*req
, reply_state
*rep
)
386 request_state
*r
= req
->primary
? req
->primary
: req
;
387 reply_state
**ptr
= &r
->replies
;
388 while (*ptr
) ptr
= &(*ptr
)->next
;
393 // Generates a response message giving name, type, domain, plus interface index,
394 // suitable for a browse result or service registration result.
395 // On successful completion rep is set to point to a malloc'd reply_state struct
396 mDNSlocal mStatus
GenerateNTDResponse(const domainname
*const servicename
, const mDNSInterfaceID id
,
397 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
400 domainname type
, dom
;
402 if (!DeconstructServiceName(servicename
, &name
, &type
, &dom
))
403 return kDNSServiceErr_Invalid
;
406 char namestr
[MAX_DOMAIN_LABEL
+1];
407 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
408 char domstr
[MAX_ESCAPED_DOMAIN_NAME
];
412 ConvertDomainLabelToCString_unescaped(&name
, namestr
);
413 ConvertDomainNameToCString(&type
, typestr
);
414 ConvertDomainNameToCString(&dom
, domstr
);
416 // Calculate reply data length
417 len
= sizeof(DNSServiceFlags
);
418 len
+= sizeof(mDNSu32
); // if index
419 len
+= sizeof(DNSServiceErrorType
);
420 len
+= (int) (strlen(namestr
) + 1);
421 len
+= (int) (strlen(typestr
) + 1);
422 len
+= (int) (strlen(domstr
) + 1);
424 // Build reply header
425 *rep
= create_reply(op
, len
, request
);
426 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
427 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
, mDNSfalse
));
428 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
431 data
= (char *)&(*rep
)->rhdr
[1];
432 put_string(namestr
, &data
);
433 put_string(typestr
, &data
);
434 put_string(domstr
, &data
);
436 return mStatus_NoError
;
440 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
441 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
442 mDNSlocal
void GenerateBonjourBrowserResponse(const domainname
*const servicename
, const mDNSInterfaceID id
,
443 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
445 char namestr
[MAX_DOMAIN_LABEL
+1];
446 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
447 static const char domstr
[] = ".";
453 // 1. Put first label in namestr
454 ConvertDomainLabelToCString_unescaped((const domainlabel
*)servicename
, namestr
);
456 // 2. Put second label and "local" into typestr
457 mDNS_snprintf(typestr
, sizeof(typestr
), "%#s.local.", SecondLabel(servicename
));
459 // Calculate reply data length
460 len
= sizeof(DNSServiceFlags
);
461 len
+= sizeof(mDNSu32
); // if index
462 len
+= sizeof(DNSServiceErrorType
);
463 len
+= (int) (strlen(namestr
) + 1);
464 len
+= (int) (strlen(typestr
) + 1);
465 len
+= (int) (strlen(domstr
) + 1);
467 // Build reply header
468 *rep
= create_reply(op
, len
, request
);
469 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
470 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
, mDNSfalse
));
471 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
474 data
= (char *)&(*rep
)->rhdr
[1];
475 put_string(namestr
, &data
);
476 put_string(typestr
, &data
);
477 put_string(domstr
, &data
);
480 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
481 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
482 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
483 mDNSlocal AuthRecord
*read_rr_from_ipc_msg(request_state
*request
, int GetTTL
, int validate_flags
)
485 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
486 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
488 int str_err
= get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
));
489 mDNSu16 type
= get_uint16(&request
->msgptr
, request
->msgend
);
490 mDNSu16
class = get_uint16(&request
->msgptr
, request
->msgend
);
491 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
492 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
493 mDNSu32 ttl
= GetTTL
? get_uint32(&request
->msgptr
, request
->msgend
) : 0;
494 int storage_size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
496 mDNSInterfaceID InterfaceID
;
499 request
->flags
= flags
;
501 if (str_err
) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL
; }
503 if (!request
->msgptr
) { LogMsg("Error reading Resource Record from client"); return NULL
; }
505 if (validate_flags
&&
506 !((flags
& kDNSServiceFlagsShared
) == kDNSServiceFlagsShared
) &&
507 !((flags
& kDNSServiceFlagsUnique
) == kDNSServiceFlagsUnique
))
509 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
513 rr
= mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord
) - sizeof(RDataBody
) + storage_size
);
514 if (!rr
) FatalError("ERROR: malloc");
516 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
517 if (InterfaceID
== mDNSInterface_LocalOnly
)
518 artype
= AuthRecordLocalOnly
;
519 else if (InterfaceID
== mDNSInterface_P2P
)
520 artype
= AuthRecordP2P
;
521 else if ((InterfaceID
== mDNSInterface_Any
) && (flags
& kDNSServiceFlagsIncludeP2P
))
522 artype
= AuthRecordAnyIncludeP2P
;
524 artype
= AuthRecordAny
;
526 mDNS_SetupResourceRecord(rr
, mDNSNULL
, InterfaceID
, type
, 0,
527 (mDNSu8
) ((flags
& kDNSServiceFlagsShared
) ? kDNSRecordTypeShared
: kDNSRecordTypeUnique
), artype
, mDNSNULL
, mDNSNULL
);
529 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, name
))
531 LogMsg("ERROR: bad name: %s", name
);
532 freeL("AuthRecord/read_rr_from_ipc_msg", rr
);
536 if (flags
& kDNSServiceFlagsAllowRemoteQuery
) rr
->AllowRemoteQuery
= mDNStrue
;
537 rr
->resrec
.rrclass
= class;
538 rr
->resrec
.rdlength
= rdlen
;
539 rr
->resrec
.rdata
->MaxRDLength
= rdlen
;
540 mDNSPlatformMemCopy(rr
->resrec
.rdata
->u
.data
, rdata
, rdlen
);
541 if (GetTTL
) rr
->resrec
.rroriginalttl
= ttl
;
542 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
543 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Sets rr->rdatahash for us
547 mDNSlocal
int build_domainname_from_strings(domainname
*srv
, char *name
, char *regtype
, char *domain
)
552 if (!MakeDomainLabelFromLiteralString(&n
, name
)) return -1;
553 if (!MakeDomainNameFromDNSNameString(&t
, regtype
)) return -1;
554 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return -1;
555 if (!ConstructServiceName(srv
, &n
, &t
, &d
)) return -1;
559 mDNSlocal
void send_all(dnssd_sock_t s
, const char *ptr
, int len
)
561 int n
= send(s
, ptr
, len
, 0);
562 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
563 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
564 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
566 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
567 s
, n
, len
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
571 mDNSlocal mDNSBool
AuthorizedDomain(const request_state
* const request
, const domainname
* const d
, const DNameListElem
* const doms
)
573 const DNameListElem
*delem
= mDNSNULL
;
574 int bestDelta
= -1; // the delta of the best match, lower is better
576 mDNSBool allow
= mDNSfalse
;
578 if (SystemUID(request
->uid
)) return mDNStrue
;
580 dLabels
= CountLabels(d
);
581 for (delem
= doms
; delem
; delem
= delem
->next
)
585 int delemLabels
= CountLabels(&delem
->name
);
586 int delta
= dLabels
- delemLabels
;
587 if ((bestDelta
== -1 || delta
<= bestDelta
) && SameDomainName(&delem
->name
, SkipLeadingLabels(d
, delta
)))
590 allow
= (allow
|| (delem
->uid
== request
->uid
));
595 return bestDelta
== -1 ? mDNStrue
: allow
;
599 // ***************************************************************************
600 #if COMPILER_LIKES_PRAGMA_MARK
602 #pragma mark - external helpers
605 mDNSlocal
void external_start_advertising_helper(service_instance
*const instance
)
607 AuthRecord
*st
= instance
->subtypes
;
608 ExtraResourceRecord
*e
;
611 if (mDNSIPPortIsZero(instance
->request
->u
.servicereg
.port
))
613 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
617 #if APPLE_OSX_mDNSResponder
618 // Update packet filter if p2p interface already exists, otherwise,
619 // if will be updated when we get the KEV_DL_IF_ATTACHED event for
620 // the interface. Called here since we don't call external_start_advertising_service()
621 // with the SRV record when advertising a service.
622 mDNSInitPacketFilter();
623 #endif // APPLE_OSX_mDNSResponder
625 if (instance
->external_advertise
) LogMsg("external_start_advertising_helper: external_advertise already set!");
627 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
628 external_start_advertising_service(&st
[i
].resrec
);
630 external_start_advertising_service(&instance
->srs
.RR_PTR
.resrec
);
631 external_start_advertising_service(&instance
->srs
.RR_TXT
.resrec
);
633 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
634 external_start_advertising_service(&e
->r
.resrec
);
636 instance
->external_advertise
= mDNStrue
;
639 mDNSlocal
void external_stop_advertising_helper(service_instance
*const instance
)
641 AuthRecord
*st
= instance
->subtypes
;
642 ExtraResourceRecord
*e
;
645 if (!instance
->external_advertise
) return;
647 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
649 for ( i
= 0; i
< instance
->request
->u
.servicereg
.num_subtypes
; i
++)
650 external_stop_advertising_service(&st
[i
].resrec
);
652 external_stop_advertising_service(&instance
->srs
.RR_PTR
.resrec
);
653 external_stop_advertising_service(&instance
->srs
.RR_TXT
.resrec
);
655 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
)
656 external_stop_advertising_service(&e
->r
.resrec
);
658 instance
->external_advertise
= mDNSfalse
;
661 // ***************************************************************************
662 #if COMPILER_LIKES_PRAGMA_MARK
664 #pragma mark - DNSServiceRegister
667 mDNSexport
void FreeExtraRR(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
669 ExtraResourceRecord
*extra
= (ExtraResourceRecord
*)rr
->RecordContext
;
672 if (result
!= mStatus_MemFree
) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result
); return; }
674 LogInfo(" FreeExtraRR %s", RRDisplayString(m
, &rr
->resrec
));
676 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
)
677 freeL("Extra RData", rr
->resrec
.rdata
);
678 freeL("ExtraResourceRecord/FreeExtraRR", extra
);
681 mDNSlocal
void unlink_and_free_service_instance(service_instance
*srv
)
683 ExtraResourceRecord
*e
= srv
->srs
.Extras
, *tmp
;
685 external_stop_advertising_helper(srv
);
687 // clear pointers from parent struct
690 service_instance
**p
= &srv
->request
->u
.servicereg
.instances
;
693 if (*p
== srv
) { *p
= (*p
)->next
; break; }
700 e
->r
.RecordContext
= e
;
703 FreeExtraRR(&mDNSStorage
, &tmp
->r
, mStatus_MemFree
);
706 if (srv
->srs
.RR_TXT
.resrec
.rdata
!= &srv
->srs
.RR_TXT
.rdatastorage
)
707 freeL("TXT RData", srv
->srs
.RR_TXT
.resrec
.rdata
);
709 if (srv
->subtypes
) { freeL("ServiceSubTypes", srv
->subtypes
); srv
->subtypes
= NULL
; }
710 freeL("service_instance", srv
);
713 // Count how many other service records we have locally with the same name, but different rdata.
714 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
715 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
716 mDNSexport
int CountPeerRegistrations(mDNS
*const m
, ServiceRecordSet
*const srs
)
719 ResourceRecord
*r
= &srs
->RR_SRV
.resrec
;
722 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
723 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& SameDomainName(rr
->resrec
.name
, r
->name
) && !IdenticalSameNameRecord(&rr
->resrec
, r
))
726 verbosedebugf("%d peer registrations for %##s", count
, r
->name
->c
);
730 mDNSexport
int CountExistingRegistrations(domainname
*srv
, mDNSIPPort port
)
734 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
735 if (rr
->resrec
.rrtype
== kDNSType_SRV
&&
736 mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, port
) &&
737 SameDomainName(rr
->resrec
.name
, srv
))
742 mDNSlocal
void SendServiceRemovalNotification(ServiceRecordSet
*const srs
)
745 service_instance
*instance
= srs
->ServiceContext
;
746 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, 0, mStatus_NoError
) != mStatus_NoError
)
747 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
748 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNSfalse
; }
751 // service registration callback performs three duties - frees memory for deregistered services,
752 // handles name conflicts, and delivers completed registration information to the client
753 mDNSlocal
void regservice_callback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
756 mDNSBool SuppressError
= mDNSfalse
;
757 service_instance
*instance
;
761 if (!srs
) { LogMsg("regservice_callback: srs is NULL %d", result
); return; }
763 instance
= srs
->ServiceContext
;
764 if (!instance
) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result
); return; }
766 // don't send errors up to client for wide-area, empty-string registrations
767 if (instance
->request
&&
768 instance
->request
->u
.servicereg
.default_domain
&&
769 !instance
->default_local
)
770 SuppressError
= mDNStrue
;
772 if (mDNS_LoggingEnabled
)
774 const char *const fmt
=
775 (result
== mStatus_NoError
) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
776 (result
== mStatus_MemFree
) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
777 (result
== mStatus_NameConflict
) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
778 "%s DNSServiceRegister(%##s, %u) %s %d";
779 char prefix
[16] = "---:";
780 if (instance
->request
) mDNS_snprintf(prefix
, sizeof(prefix
), "%3d:", instance
->request
->sd
);
781 LogOperation(fmt
, prefix
, srs
->RR_SRV
.resrec
.name
->c
, mDNSVal16(srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
),
782 SuppressError
? "suppressed error" : "CALLBACK", result
);
785 if (!instance
->request
&& result
!= mStatus_MemFree
) { LogMsg("regservice_callback: instance->request is NULL %d", result
); return; }
787 if (result
== mStatus_NoError
)
789 if (instance
->request
->u
.servicereg
.allowremotequery
)
791 ExtraResourceRecord
*e
;
792 srs
->RR_ADV
.AllowRemoteQuery
= mDNStrue
;
793 srs
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
794 srs
->RR_SRV
.AllowRemoteQuery
= mDNStrue
;
795 srs
->RR_TXT
.AllowRemoteQuery
= mDNStrue
;
796 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
) e
->r
.AllowRemoteQuery
= mDNStrue
;
799 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
800 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
801 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
803 if (instance
->request
->u
.servicereg
.InterfaceID
== mDNSInterface_P2P
|| (!instance
->request
->u
.servicereg
.InterfaceID
&& SameDomainName(&instance
->domain
, &localdomain
) && (instance
->request
->flags
& kDNSServiceFlagsIncludeP2P
)))
805 LogInfo("regservice_callback: calling external_start_advertising_helper()");
806 external_start_advertising_helper(instance
);
808 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(m
, srs
) == 0)
809 RecordUpdatedNiceLabel(m
, 0); // Successfully got new name, tell user immediately
811 else if (result
== mStatus_MemFree
)
813 if (instance
->request
&& instance
->renameonmemfree
)
815 external_stop_advertising_helper(instance
);
816 instance
->renameonmemfree
= 0;
817 err
= mDNS_RenameAndReregisterService(m
, srs
, &instance
->request
->u
.servicereg
.name
);
818 if (err
) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err
);
819 // error should never happen - safest to log and continue
822 unlink_and_free_service_instance(instance
);
824 else if (result
== mStatus_NameConflict
)
826 if (instance
->request
->u
.servicereg
.autorename
)
828 external_stop_advertising_helper(instance
);
829 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(m
, srs
) == 0)
831 // On conflict for an autoname service, rename and reregister *all* autoname services
832 IncrementLabelSuffix(&m
->nicelabel
, mDNStrue
);
833 mDNS_ConfigChanged(m
); // Will call back into udsserver_handle_configchange()
835 else // On conflict for a non-autoname service, rename and reregister just that one service
837 if (instance
->clientnotified
) SendServiceRemovalNotification(srs
);
838 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
845 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
846 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
847 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
849 unlink_and_free_service_instance(instance
);
852 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
856 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
857 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
858 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
863 mDNSlocal
void regrecord_callback(mDNS
*const m
, AuthRecord
*rr
, mStatus result
)
866 if (!rr
->RecordContext
) // parent struct already freed by termination callback
868 if (result
== mStatus_NoError
)
869 LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m
, rr
));
872 if (result
!= mStatus_MemFree
) LogMsg("regrecord_callback: error %d received after parent termination", result
);
874 // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
875 // If the record has been updated, we need to free the rdata. Everytime we call mDNS_Update, it calls update_callback
876 // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
877 // to free the latest rdata for which the update_callback was never called with.
878 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
) freeL("RData/regrecord_callback", rr
->resrec
.rdata
);
879 freeL("AuthRecord/regrecord_callback", rr
);
884 registered_record_entry
*re
= rr
->RecordContext
;
885 request_state
*request
= re
->request
;
887 if (mDNS_LoggingEnabled
)
889 char *fmt
= (result
== mStatus_NoError
) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
890 (result
== mStatus_MemFree
) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
891 (result
== mStatus_NameConflict
) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
892 "%3d: DNSServiceRegisterRecord(%u %s) %d";
893 LogOperation(fmt
, request
->sd
, re
->key
, RRDisplayString(m
, &rr
->resrec
), result
);
896 if (result
!= mStatus_MemFree
)
898 int len
= sizeof(DNSServiceFlags
) + sizeof(mDNSu32
) + sizeof(DNSServiceErrorType
);
899 reply_state
*reply
= create_reply(reg_record_reply_op
, len
, request
);
900 reply
->mhdr
->client_context
= re
->regrec_client_context
;
901 reply
->rhdr
->flags
= dnssd_htonl(0);
902 reply
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, rr
->resrec
.InterfaceID
, mDNSfalse
));
903 reply
->rhdr
->error
= dnssd_htonl(result
);
904 append_reply(request
, reply
);
909 // unlink from list, free memory
910 registered_record_entry
**ptr
= &request
->u
.reg_recs
;
911 while (*ptr
&& (*ptr
) != re
) ptr
= &(*ptr
)->next
;
912 if (!*ptr
) { LogMsg("regrecord_callback - record not in list!"); return; }
914 freeL("registered_record_entry AuthRecord regrecord_callback", re
->rr
);
915 freeL("registered_record_entry regrecord_callback", re
);
919 if (re
->external_advertise
) LogMsg("regrecord_callback: external_advertise already set!");
921 if (re
->origInterfaceID
== mDNSInterface_P2P
|| (!re
->origInterfaceID
&& IsLocalDomain(&rr
->namestorage
) && (request
->flags
& kDNSServiceFlagsIncludeP2P
)))
923 LogInfo("regrecord_callback: calling external_start_advertising_service");
924 external_start_advertising_service(&rr
->resrec
);
925 re
->external_advertise
= mDNStrue
;
931 mDNSlocal
void connection_termination(request_state
*request
)
933 // When terminating a shared connection, we need to scan the all_requests list
934 // and terminate any subbordinate operations sharing this file descriptor
935 request_state
**req
= &all_requests
;
937 LogOperation("%3d: DNSServiceCreateConnection STOP", request
->sd
);
941 if ((*req
)->primary
== request
)
943 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
944 request_state
*tmp
= *req
;
945 if (tmp
->primary
== tmp
) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp
, tmp
->sd
);
946 if (tmp
->replies
) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp
, tmp
->sd
);
949 freeL("request_state/connection_termination", tmp
);
955 while (request
->u
.reg_recs
)
957 registered_record_entry
*ptr
= request
->u
.reg_recs
;
958 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP", request
->sd
, ptr
->key
, RRDisplayString(&mDNSStorage
, &ptr
->rr
->resrec
));
959 request
->u
.reg_recs
= request
->u
.reg_recs
->next
;
960 ptr
->rr
->RecordContext
= NULL
;
961 if (ptr
->external_advertise
)
963 ptr
->external_advertise
= mDNSfalse
;
964 external_stop_advertising_service(&ptr
->rr
->resrec
);
966 mDNS_Deregister(&mDNSStorage
, ptr
->rr
); // Will free ptr->rr for us
967 freeL("registered_record_entry/connection_termination", ptr
);
971 mDNSlocal
void handle_cancel_request(request_state
*request
)
973 request_state
**req
= &all_requests
;
974 LogOperation("%3d: Cancel %08X %08X", request
->sd
, request
->hdr
.client_context
.u32
[1], request
->hdr
.client_context
.u32
[0]);
977 if ((*req
)->primary
== request
&&
978 (*req
)->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
979 (*req
)->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1])
981 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
982 request_state
*tmp
= *req
;
985 freeL("request_state/handle_cancel_request", tmp
);
992 mDNSlocal mStatus
handle_regrecord_request(request_state
*request
)
994 mStatus err
= mStatus_BadParamErr
;
995 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 1, 1);
998 registered_record_entry
*re
;
999 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1000 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1001 if (rr
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
&& !IsLocalDomain(rr
->resrec
.name
) &&
1002 rr
->resrec
.rrclass
== kDNSClass_IN
&& (rr
->resrec
.rrtype
== kDNSType_A
|| rr
->resrec
.rrtype
== kDNSType_AAAA
||
1003 rr
->resrec
.rrtype
== kDNSType_CNAME
))
1005 freeL("AuthRecord/handle_regrecord_request", rr
);
1006 return (mStatus_BadParamErr
);
1008 // allocate registration entry, link into list
1009 re
= mallocL("registered_record_entry", sizeof(registered_record_entry
));
1010 if (!re
) FatalError("ERROR: malloc");
1011 re
->key
= request
->hdr
.reg_index
;
1013 re
->regrec_client_context
= request
->hdr
.client_context
;
1014 re
->request
= request
;
1015 re
->external_advertise
= mDNSfalse
;
1016 rr
->RecordContext
= re
;
1017 rr
->RecordCallback
= regrecord_callback
;
1019 re
->origInterfaceID
= rr
->resrec
.InterfaceID
;
1020 if (rr
->resrec
.InterfaceID
== mDNSInterface_P2P
) rr
->resrec
.InterfaceID
= mDNSInterface_Any
;
1022 if (!AuthorizedDomain(request
, rr
->resrec
.name
, AutoRegistrationDomains
)) return (mStatus_NoError
);
1024 if (rr
->resrec
.rroriginalttl
== 0)
1025 rr
->resrec
.rroriginalttl
= DefaultTTLforRRType(rr
->resrec
.rrtype
);
1027 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START", request
->sd
, re
->key
, RRDisplayString(&mDNSStorage
, &rr
->resrec
));
1028 err
= mDNS_Register(&mDNSStorage
, rr
);
1031 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request
->sd
, re
->key
, RRDisplayString(&mDNSStorage
, &rr
->resrec
), err
);
1032 freeL("registered_record_entry", re
);
1033 freeL("registered_record_entry/AuthRecord", rr
);
1037 re
->next
= request
->u
.reg_recs
;
1038 request
->u
.reg_recs
= re
;
1044 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
);
1046 mDNSlocal
void regservice_termination_callback(request_state
*request
)
1048 if (!request
) { LogMsg("regservice_termination_callback context is NULL"); return; }
1049 while (request
->u
.servicereg
.instances
)
1051 service_instance
*p
= request
->u
.servicereg
.instances
;
1052 request
->u
.servicereg
.instances
= request
->u
.servicereg
.instances
->next
;
1053 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1054 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP",
1055 request
->sd
, p
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(p
->srs
.RR_SRV
.resrec
.rdata
->u
.srv
.port
));
1057 external_stop_advertising_helper(p
);
1059 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1060 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1061 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1062 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1063 // because by then we might have already freed p
1065 if (mDNS_DeregisterService(&mDNSStorage
, &p
->srs
)) unlink_and_free_service_instance(p
);
1066 // Don't touch service_instance *p after this -- it's likely to have been freed already
1068 if (request
->u
.servicereg
.txtdata
)
1069 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1070 if (request
->u
.servicereg
.autoname
)
1072 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1073 request
->u
.servicereg
.autoname
= mDNSfalse
;
1074 UpdateDeviceInfoRecord(&mDNSStorage
);
1078 mDNSlocal request_state
*LocateSubordinateRequest(request_state
*request
)
1081 for (req
= all_requests
; req
; req
= req
->next
)
1082 if (req
->primary
== request
&&
1083 req
->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1084 req
->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1]) return(req
);
1088 mDNSlocal mStatus
add_record_to_service(request_state
*request
, service_instance
*instance
, mDNSu16 rrtype
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
)
1090 ServiceRecordSet
*srs
= &instance
->srs
;
1092 int size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1093 ExtraResourceRecord
*extra
= mallocL("ExtraResourceRecord", sizeof(*extra
) - sizeof(RDataBody
) + size
);
1094 if (!extra
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1096 mDNSPlatformMemZero(extra
, sizeof(ExtraResourceRecord
)); // OK if oversized rdata not zero'd
1097 extra
->r
.resrec
.rrtype
= rrtype
;
1098 extra
->r
.rdatastorage
.MaxRDLength
= (mDNSu16
) size
;
1099 extra
->r
.resrec
.rdlength
= rdlen
;
1100 mDNSPlatformMemCopy(&extra
->r
.rdatastorage
.u
.data
, rdata
, rdlen
);
1102 result
= mDNS_AddRecordToService(&mDNSStorage
, srs
, extra
, &extra
->r
.rdatastorage
, ttl
,
1103 (request
->flags
& kDNSServiceFlagsIncludeP2P
) ? 1: 0);
1104 if (result
) { freeL("ExtraResourceRecord/add_record_to_service", extra
); return result
; }
1106 extra
->ClientID
= request
->hdr
.reg_index
;
1107 if (instance
->external_advertise
&& (instance
->request
->u
.servicereg
.InterfaceID
== mDNSInterface_P2P
|| (!instance
->request
->u
.servicereg
.InterfaceID
&& SameDomainName(&instance
->domain
, &localdomain
) && (instance
->request
->flags
& kDNSServiceFlagsIncludeP2P
))))
1109 LogInfo("add_record_to_service: calling external_start_advertising_service");
1110 external_start_advertising_service(&extra
->r
.resrec
);
1115 mDNSlocal mStatus
handle_add_request(request_state
*request
)
1117 service_instance
*i
;
1118 mStatus result
= mStatus_UnknownErr
;
1119 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
);
1120 mDNSu16 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
1121 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1122 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1123 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1124 if (!ttl
) ttl
= DefaultTTLforRRType(rrtype
);
1125 (void)flags
; // Unused
1127 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1129 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1130 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1132 if (request
->terminate
!= regservice_termination_callback
)
1133 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1135 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1136 // in the application. See radar://9165807.
1137 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1138 { LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request
->sd
); return(mStatus_BadParamErr
); }
1140 LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d)", request
->sd
, flags
,
1141 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
, DNSTypeName(rrtype
), rdlen
);
1143 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1145 result
= add_record_to_service(request
, i
, rrtype
, rdlen
, rdata
, ttl
);
1146 if (result
&& i
->default_local
) break;
1147 else result
= mStatus_NoError
; // suppress non-local default errors
1153 mDNSlocal
void update_callback(mDNS
*const m
, AuthRecord
*const rr
, RData
*oldrd
, mDNSu16 oldrdlen
)
1155 mDNSBool external_advertise
= (rr
->UpdateContext
) ? *((mDNSBool
*)rr
->UpdateContext
) : mDNSfalse
;
1158 // There are three cases.
1160 // 1. We have updated the primary TXT record of the service
1161 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1162 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1164 // external_advertise is set if we have advertised at least once during the initial addition
1165 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1166 // checks during the first time and hence we don't do any checks here
1167 if (external_advertise
)
1169 ResourceRecord ext
= rr
->resrec
;
1170 if (ext
.rdlength
== oldrdlen
&& mDNSPlatformMemSame(&ext
.rdata
->u
, &oldrd
->u
, oldrdlen
)) goto exit
;
1171 SetNewRData(&ext
, oldrd
, oldrdlen
);
1172 external_stop_advertising_service(&ext
);
1173 LogInfo("update_callback: calling external_start_advertising_service");
1174 external_start_advertising_service(&rr
->resrec
);
1177 if (oldrd
!= &rr
->rdatastorage
) freeL("RData/update_callback", oldrd
);
1180 mDNSlocal mStatus
update_record(AuthRecord
*rr
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
, const mDNSBool
*const external_advertise
)
1183 const int rdsize
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1184 RData
*newrd
= mallocL("RData/update_record", sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
1185 if (!newrd
) FatalError("ERROR: malloc");
1186 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
1187 mDNSPlatformMemCopy(&newrd
->u
, rdata
, rdlen
);
1189 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1190 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1191 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1192 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rdlen
== 0) { rdlen
= 1; newrd
->u
.txt
.c
[0] = 0; }
1194 if (external_advertise
) rr
->UpdateContext
= (void *)external_advertise
;
1196 result
= mDNS_Update(&mDNSStorage
, rr
, ttl
, rdlen
, newrd
, update_callback
);
1197 if (result
) { LogMsg("update_record: Error %d for %s", (int)result
, ARDisplayString(&mDNSStorage
, rr
)); freeL("RData/update_record", newrd
); }
1201 mDNSlocal mStatus
handle_update_request(request_state
*request
)
1203 const ipc_msg_hdr
*const hdr
= &request
->hdr
;
1204 mStatus result
= mStatus_BadReferenceErr
;
1205 service_instance
*i
;
1206 AuthRecord
*rr
= NULL
;
1208 // get the message data
1209 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
); // flags unused
1210 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1211 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1212 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1213 (void)flags
; // Unused
1215 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1217 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1218 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1220 if (request
->terminate
== connection_termination
)
1222 // update an individually registered record
1223 registered_record_entry
*reptr
;
1224 for (reptr
= request
->u
.reg_recs
; reptr
; reptr
= reptr
->next
)
1226 if (reptr
->key
== hdr
->reg_index
)
1228 result
= update_record(reptr
->rr
, rdlen
, rdata
, ttl
, &reptr
->external_advertise
);
1229 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)",
1230 request
->sd
, reptr
->rr
->resrec
.name
->c
, reptr
->rr
? DNSTypeName(reptr
->rr
->resrec
.rrtype
) : "<NONE>");
1234 result
= mStatus_BadReferenceErr
;
1238 if (request
->terminate
!= regservice_termination_callback
)
1239 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1241 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1242 if (mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1243 { LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request
->sd
); return(mStatus_BadParamErr
); }
1245 // update the saved off TXT data for the service
1246 if (hdr
->reg_index
== TXT_RECORD_INDEX
)
1248 if (request
->u
.servicereg
.txtdata
)
1249 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1252 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", rdlen
);
1253 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_update_request - malloc");
1254 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, rdata
, rdlen
);
1256 request
->u
.servicereg
.txtlen
= rdlen
;
1259 // update a record from a service record set
1260 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1262 if (hdr
->reg_index
== TXT_RECORD_INDEX
) rr
= &i
->srs
.RR_TXT
;
1265 ExtraResourceRecord
*e
;
1266 for (e
= i
->srs
.Extras
; e
; e
= e
->next
)
1267 if (e
->ClientID
== hdr
->reg_index
) { rr
= &e
->r
; break; }
1270 if (!rr
) { result
= mStatus_BadReferenceErr
; goto end
; }
1271 result
= update_record(rr
, rdlen
, rdata
, ttl
, &i
->external_advertise
);
1272 if (result
&& i
->default_local
) goto end
;
1273 else result
= mStatus_NoError
; // suppress non-local default errors
1277 if (request
->terminate
== regservice_termination_callback
)
1278 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request
->sd
,
1279 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1280 rr
? DNSTypeName(rr
->resrec
.rrtype
) : "<NONE>");
1285 // remove a resource record registered via DNSServiceRegisterRecord()
1286 mDNSlocal mStatus
remove_record(request_state
*request
)
1288 mStatus err
= mStatus_UnknownErr
;
1289 registered_record_entry
*e
, **ptr
= &request
->u
.reg_recs
;
1291 while (*ptr
&& (*ptr
)->key
!= request
->hdr
.reg_index
) ptr
= &(*ptr
)->next
;
1292 if (!*ptr
) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request
->sd
, request
->hdr
.reg_index
); return mStatus_BadReferenceErr
; }
1294 *ptr
= e
->next
; // unlink
1296 LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request
->sd
, e
->key
, RRDisplayString(&mDNSStorage
, &e
->rr
->resrec
));
1297 e
->rr
->RecordContext
= NULL
;
1298 if (e
->external_advertise
)
1300 external_stop_advertising_service(&e
->rr
->resrec
);
1301 e
->external_advertise
= mDNSfalse
;
1303 err
= mDNS_Deregister(&mDNSStorage
, e
->rr
); // Will free e->rr for us; we're responsible for freeing e
1306 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err
);
1307 freeL("registered_record_entry AuthRecord remove_record", e
->rr
);
1310 freeL("registered_record_entry remove_record", e
);
1314 mDNSlocal mStatus
remove_extra(const request_state
*const request
, service_instance
*const serv
, mDNSu16
*const rrtype
)
1316 mStatus err
= mStatus_BadReferenceErr
;
1317 ExtraResourceRecord
*ptr
;
1319 for (ptr
= serv
->srs
.Extras
; ptr
; ptr
= ptr
->next
)
1321 if (ptr
->ClientID
== request
->hdr
.reg_index
) // found match
1323 *rrtype
= ptr
->r
.resrec
.rrtype
;
1324 if (serv
->external_advertise
) external_stop_advertising_service(&ptr
->r
.resrec
);
1325 err
= mDNS_RemoveRecordFromService(&mDNSStorage
, &serv
->srs
, ptr
, FreeExtraRR
, ptr
);
1332 mDNSlocal mStatus
handle_removerecord_request(request_state
*request
)
1334 mStatus err
= mStatus_BadReferenceErr
;
1335 get_flags(&request
->msgptr
, request
->msgend
); // flags unused
1337 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1339 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1340 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1342 if (request
->terminate
== connection_termination
)
1343 err
= remove_record(request
); // remove individually registered record
1344 else if (request
->terminate
!= regservice_termination_callback
)
1345 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1348 service_instance
*i
;
1350 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request
->sd
,
1351 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1352 rrtype
? DNSTypeName(rrtype
) : "<NONE>");
1353 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1355 err
= remove_extra(request
, i
, &rrtype
);
1356 if (err
&& i
->default_local
) break;
1357 else err
= mStatus_NoError
; // suppress non-local default errors
1364 // If there's a comma followed by another character,
1365 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1366 // Otherwise, it returns a pointer to the final nul at the end of the string
1367 mDNSlocal
char *FindFirstSubType(char *p
)
1371 if (p
[0] == '\\' && p
[1]) p
+= 2;
1372 else if (p
[0] == ',' && p
[1]) { *p
++ = 0; return(p
); }
1378 // If there's a comma followed by another character,
1379 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1380 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1381 // Otherwise, it returns a pointer to the final nul at the end of the string
1382 mDNSlocal
char *FindNextSubType(char *p
)
1386 if (p
[0] == '\\' && p
[1]) // If escape character
1387 p
+= 2; // ignore following character
1388 else if (p
[0] == ',') // If we found a comma
1393 else if (p
[0] == '.')
1400 // Returns -1 if illegal subtype found
1401 mDNSexport mDNSs32
ChopSubTypes(char *regtype
)
1403 mDNSs32 NumSubTypes
= 0;
1404 char *stp
= FindFirstSubType(regtype
);
1405 while (stp
&& *stp
) // If we found a comma...
1407 if (*stp
== ',') return(-1);
1409 stp
= FindNextSubType(stp
);
1411 if (!stp
) return(-1);
1412 return(NumSubTypes
);
1415 mDNSexport AuthRecord
*AllocateSubTypes(mDNSs32 NumSubTypes
, char *p
)
1417 AuthRecord
*st
= mDNSNULL
;
1421 st
= mallocL("ServiceSubTypes", NumSubTypes
* sizeof(AuthRecord
));
1422 if (!st
) return(mDNSNULL
);
1423 for (i
= 0; i
< NumSubTypes
; i
++)
1425 mDNS_SetupResourceRecord(&st
[i
], mDNSNULL
, mDNSInterface_Any
, kDNSQType_ANY
, kStandardTTL
, 0, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
1428 if (!MakeDomainNameFromDNSNameString(&st
[i
].namestorage
, p
))
1429 { freeL("ServiceSubTypes", st
); return(mDNSNULL
); }
1435 mDNSlocal mStatus
register_service_instance(request_state
*request
, const domainname
*domain
)
1437 service_instance
**ptr
, *instance
;
1438 const int extra_size
= (request
->u
.servicereg
.txtlen
> sizeof(RDataBody
)) ? (request
->u
.servicereg
.txtlen
- sizeof(RDataBody
)) : 0;
1439 const mDNSBool DomainIsLocal
= SameDomainName(domain
, &localdomain
);
1441 mDNSInterfaceID interfaceID
= request
->u
.servicereg
.InterfaceID
;
1442 mDNSu32 regFlags
= 0;
1444 if (interfaceID
== mDNSInterface_P2P
)
1446 interfaceID
= mDNSInterface_Any
;
1447 regFlags
|= regFlagIncludeP2P
;
1449 else if (request
->flags
& kDNSServiceFlagsIncludeP2P
)
1450 regFlags
|= regFlagIncludeP2P
;
1452 // client guarantees that record names are unique
1453 if (request
->flags
& kDNSServiceFlagsForce
)
1454 regFlags
|= regFlagKnownUnique
;
1456 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1457 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1458 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1459 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1460 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1461 if (request
->u
.servicereg
.default_domain
&& !DomainIsLocal
) interfaceID
= mDNSInterface_Any
;
1463 for (ptr
= &request
->u
.servicereg
.instances
; *ptr
; ptr
= &(*ptr
)->next
)
1465 if (SameDomainName(&(*ptr
)->domain
, domain
))
1467 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1468 domain
->c
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
);
1469 return mStatus_AlreadyRegistered
;
1473 if (mDNSStorage
.KnownBugs
& mDNS_KnownBug_LimitedIPv6
)
1475 // Special-case hack: On Mac OS X 10.6.x and earlier we don't advertise SMB service in AutoTunnel domains,
1476 // because AutoTunnel services have to support IPv6, and in Mac OS X 10.6.x the SMB server does not.
1477 // <rdar://problem/5482322> BTMM: Don't advertise SMB with BTMM because it doesn't support IPv6
1478 if (SameDomainName(&request
->u
.servicereg
.type
, (const domainname
*) "\x4" "_smb" "\x4" "_tcp"))
1480 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName(&mDNSStorage
, domain
);
1481 if (AuthInfo
&& AuthInfo
->AutoTunnel
) return(kDNSServiceErr_Unsupported
);
1485 instance
= mallocL("service_instance", sizeof(*instance
) + extra_size
);
1486 if (!instance
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1488 instance
->next
= mDNSNULL
;
1489 instance
->request
= request
;
1490 instance
->subtypes
= AllocateSubTypes(request
->u
.servicereg
.num_subtypes
, request
->u
.servicereg
.type_as_string
);
1491 instance
->renameonmemfree
= 0;
1492 instance
->clientnotified
= mDNSfalse
;
1493 instance
->default_local
= (request
->u
.servicereg
.default_domain
&& DomainIsLocal
);
1494 instance
->external_advertise
= mDNSfalse
;
1495 AssignDomainName(&instance
->domain
, domain
);
1497 if (request
->u
.servicereg
.num_subtypes
&& !instance
->subtypes
)
1498 { unlink_and_free_service_instance(instance
); instance
= NULL
; FatalError("ERROR: malloc"); }
1500 result
= mDNS_RegisterService(&mDNSStorage
, &instance
->srs
,
1501 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
,
1502 request
->u
.servicereg
.host
.c
[0] ? &request
->u
.servicereg
.host
: NULL
,
1503 request
->u
.servicereg
.port
,
1504 request
->u
.servicereg
.txtdata
, request
->u
.servicereg
.txtlen
,
1505 instance
->subtypes
, request
->u
.servicereg
.num_subtypes
,
1506 interfaceID
, regservice_callback
, instance
, regFlags
);
1510 *ptr
= instance
; // Append this to the end of our request->u.servicereg.instances list
1511 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED",
1512 instance
->request
->sd
, instance
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(request
->u
.servicereg
.port
));
1516 LogMsg("register_service_instance %#s.%##s%##s error %d",
1517 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
->c
, result
);
1518 unlink_and_free_service_instance(instance
);
1524 mDNSlocal
void udsserver_default_reg_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
1526 request_state
*request
;
1528 #if APPLE_OSX_mDNSResponder
1529 machserver_automatic_registration_domain_changed(&d
->name
, add
);
1530 #endif // APPLE_OSX_mDNSResponder
1532 LogMsg("%s registration domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
1533 for (request
= all_requests
; request
; request
= request
->next
)
1535 if (request
->terminate
!= regservice_termination_callback
) continue;
1536 if (!request
->u
.servicereg
.default_domain
) continue;
1537 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
1539 service_instance
**ptr
= &request
->u
.servicereg
.instances
;
1540 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
1543 // If we don't already have this domain in our list for this registration, add it now
1544 if (!*ptr
) register_service_instance(request
, &d
->name
);
1545 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d
->name
);
1549 // Normally we should not fail to find the specified instance
1550 // One case where this can happen is if a uDNS update fails for some reason,
1551 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1553 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1554 &d
->name
, request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type_as_string
);
1558 for (p
= AutoRegistrationDomains
; p
; p
=p
->next
)
1559 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
1560 if (SameDomainName(&d
->name
, &p
->name
)) break;
1561 if (p
) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d
->name
);
1565 service_instance
*si
= *ptr
;
1567 if (si
->clientnotified
) SendServiceRemovalNotification(&si
->srs
); // Do this *before* clearing si->request backpointer
1568 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1569 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1570 // process of completing asynchronously, the client cancels the entire operation, so
1571 // regservice_termination_callback then runs through the whole list deregistering each
1572 // instance, clearing the backpointers, and then disposing the parent request_state object.
1573 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1574 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1575 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1576 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1578 err
= mDNS_DeregisterService(&mDNSStorage
, &si
->srs
);
1579 if (err
) { LogMsg("udsserver_default_reg_domain_changed err %d", err
); unlink_and_free_service_instance(si
); }
1587 mDNSlocal mStatus
handle_regservice_request(request_state
*request
)
1589 char name
[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1590 char domain
[MAX_ESCAPED_DOMAIN_NAME
], host
[MAX_ESCAPED_DOMAIN_NAME
];
1591 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
];
1595 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
1596 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
1597 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
1598 if (interfaceIndex
&& !InterfaceID
)
1599 { LogMsg("ERROR: handle_regservice_request - Couldn't find interfaceIndex %d", interfaceIndex
); return(mStatus_BadParamErr
); }
1601 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
1602 get_string(&request
->msgptr
, request
->msgend
, type_as_string
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
1603 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
1604 get_string(&request
->msgptr
, request
->msgend
, host
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
1605 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
1607 request
->flags
= flags
;
1608 request
->u
.servicereg
.InterfaceID
= InterfaceID
;
1609 request
->u
.servicereg
.instances
= NULL
;
1610 request
->u
.servicereg
.txtlen
= 0;
1611 request
->u
.servicereg
.txtdata
= NULL
;
1612 mDNSPlatformStrCopy(request
->u
.servicereg
.type_as_string
, type_as_string
);
1614 if (request
->msgptr
+ 2 > request
->msgend
) request
->msgptr
= NULL
;
1617 request
->u
.servicereg
.port
.b
[0] = *request
->msgptr
++;
1618 request
->u
.servicereg
.port
.b
[1] = *request
->msgptr
++;
1621 request
->u
.servicereg
.txtlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1622 if (request
->u
.servicereg
.txtlen
)
1624 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", request
->u
.servicereg
.txtlen
);
1625 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_regservice_request - malloc");
1626 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, get_rdata(&request
->msgptr
, request
->msgend
, request
->u
.servicereg
.txtlen
), request
->u
.servicereg
.txtlen
);
1629 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1631 // Check for sub-types after the service type
1632 request
->u
.servicereg
.num_subtypes
= ChopSubTypes(request
->u
.servicereg
.type_as_string
); // Note: Modifies regtype string to remove trailing subtypes
1633 if (request
->u
.servicereg
.num_subtypes
< 0)
1634 { LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request
->u
.servicereg
.type_as_string
); return(mStatus_BadParamErr
); }
1636 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1637 if (!*request
->u
.servicereg
.type_as_string
|| !MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.type
, request
->u
.servicereg
.type_as_string
))
1638 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request
->u
.servicereg
.type_as_string
); return(mStatus_BadParamErr
); }
1642 request
->u
.servicereg
.name
= mDNSStorage
.nicelabel
;
1643 request
->u
.servicereg
.autoname
= mDNStrue
;
1647 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1648 if ((flags
& kDNSServiceFlagsNoAutoRename
) == 0)
1650 int newlen
= TruncateUTF8ToLength((mDNSu8
*)name
, mDNSPlatformStrLen(name
), MAX_DOMAIN_LABEL
);
1653 if (!MakeDomainLabelFromLiteralString(&request
->u
.servicereg
.name
, name
))
1654 { LogMsg("ERROR: handle_regservice_request - name bad %s", name
); return(mStatus_BadParamErr
); }
1655 request
->u
.servicereg
.autoname
= mDNSfalse
;
1660 request
->u
.servicereg
.default_domain
= mDNSfalse
;
1661 if (!MakeDomainNameFromDNSNameString(&d
, domain
))
1662 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain
); return(mStatus_BadParamErr
); }
1666 request
->u
.servicereg
.default_domain
= mDNStrue
;
1667 MakeDomainNameFromDNSNameString(&d
, "local.");
1670 if (!ConstructServiceName(&srv
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, &d
))
1672 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1673 request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type
.c
, d
.c
); return(mStatus_BadParamErr
);
1676 if (!MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.host
, host
))
1677 { LogMsg("ERROR: handle_regservice_request - host bad %s", host
); return(mStatus_BadParamErr
); }
1678 request
->u
.servicereg
.autorename
= (flags
& kDNSServiceFlagsNoAutoRename
) == 0;
1679 request
->u
.servicereg
.allowremotequery
= (flags
& kDNSServiceFlagsAllowRemoteQuery
) != 0;
1681 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1682 // a port number of zero. When two instances of the protected client are allowed to run on one
1683 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1684 if (!mDNSIPPortIsZero(request
->u
.servicereg
.port
))
1686 int count
= CountExistingRegistrations(&srv
, request
->u
.servicereg
.port
);
1688 LogMsg("Client application registered %d identical instances of service %##s port %u.",
1689 count
+1, srv
.c
, mDNSVal16(request
->u
.servicereg
.port
));
1692 LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START",
1693 request
->sd
, flags
, interfaceIndex
, name
, request
->u
.servicereg
.type_as_string
, domain
, host
, mDNSVal16(request
->u
.servicereg
.port
));
1695 // We need to unconditionally set request->terminate, because even if we didn't successfully
1696 // start any registrations right now, subsequent configuration changes may cause successful
1697 // registrations to be added, and we'll need to cancel them before freeing this memory.
1698 // We also need to set request->terminate first, before adding additional service instances,
1699 // because the uds_validatelists uses the request->terminate function pointer to determine
1700 // what kind of request this is, and therefore what kind of list validation is required.
1701 request
->terminate
= regservice_termination_callback
;
1703 err
= register_service_instance(request
, &d
);
1706 err
= AuthorizedDomain(request
, &d
, AutoRegistrationDomains
) ? register_service_instance(request
, &d
) : mStatus_NoError
;
1710 if (request
->u
.servicereg
.autoname
) UpdateDeviceInfoRecord(&mDNSStorage
);
1715 // Note that we don't report errors for non-local, non-explicit domains
1716 for (ptr
= AutoRegistrationDomains
; ptr
; ptr
= ptr
->next
)
1717 if (!ptr
->uid
|| SystemUID(request
->uid
) || request
->uid
== ptr
->uid
)
1718 register_service_instance(request
, &ptr
->name
);
1725 // ***************************************************************************
1726 #if COMPILER_LIKES_PRAGMA_MARK
1728 #pragma mark - DNSServiceBrowse
1731 mDNSlocal
void FoundInstance(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
1733 const DNSServiceFlags flags
= AddRecord
? kDNSServiceFlagsAdd
: 0;
1734 request_state
*req
= question
->QuestionContext
;
1738 if (answer
->rrtype
!= kDNSType_PTR
)
1739 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req
->sd
, answer
->rrtype
); return; }
1741 if (GenerateNTDResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
) != mStatus_NoError
)
1743 if (SameDomainName(&req
->u
.browser
.regtype
, (const domainname
*)"\x09_services\x07_dns-sd\x04_udp"))
1745 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
1746 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
1747 GenerateBonjourBrowserResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
);
1748 goto bonjourbrowserhack
;
1751 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
1752 req
->sd
, answer
->name
->c
, answer
->rdata
->u
.name
.c
);
1758 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
1759 req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "Add" : "Rmv",
1760 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
), RRDisplayString(m
, answer
));
1762 append_reply(req
, rep
);
1765 mDNSlocal mStatus
add_domain_to_browser(request_state
*info
, const domainname
*d
)
1770 for (p
= info
->u
.browser
.browsers
; p
; p
= p
->next
)
1772 if (SameDomainName(&p
->domain
, d
))
1773 { debugf("add_domain_to_browser %##s already in list", d
->c
); return mStatus_AlreadyRegistered
; }
1776 b
= mallocL("browser_t", sizeof(*b
));
1777 if (!b
) return mStatus_NoMemoryErr
;
1778 AssignDomainName(&b
->domain
, d
);
1779 err
= mDNS_StartBrowse(&mDNSStorage
, &b
->q
,
1780 &info
->u
.browser
.regtype
, d
, info
->u
.browser
.interface_id
, info
->u
.browser
.ForceMCast
, FoundInstance
, info
);
1783 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err
, info
->u
.browser
.regtype
.c
, d
->c
);
1784 freeL("browser_t/add_domain_to_browser", b
);
1788 b
->next
= info
->u
.browser
.browsers
;
1789 info
->u
.browser
.browsers
= b
;
1790 LogOperation("%3d: DNSServiceBrowse(%##s) START", info
->sd
, b
->q
.qname
.c
);
1791 if (info
->u
.browser
.interface_id
== mDNSInterface_P2P
|| (!info
->u
.browser
.interface_id
&& SameDomainName(&b
->domain
, &localdomain
) && (info
->flags
& kDNSServiceFlagsIncludeP2P
)))
1794 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &b
->domain
);
1795 LogInfo("add_domain_to_browser: calling external_start_browsing_for_service()");
1796 external_start_browsing_for_service(&mDNSStorage
, &tmp
, kDNSType_PTR
);
1802 mDNSlocal
void browse_termination_callback(request_state
*info
)
1804 while (info
->u
.browser
.browsers
)
1806 browser_t
*ptr
= info
->u
.browser
.browsers
;
1808 if (info
->u
.browser
.interface_id
== mDNSInterface_P2P
|| (!info
->u
.browser
.interface_id
&& SameDomainName(&ptr
->domain
, &localdomain
) && (info
->flags
& kDNSServiceFlagsIncludeP2P
)))
1811 ConstructServiceName(&tmp
, NULL
, &info
->u
.browser
.regtype
, &ptr
->domain
);
1812 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
1813 external_stop_browsing_for_service(&mDNSStorage
, &tmp
, kDNSType_PTR
);
1816 info
->u
.browser
.browsers
= ptr
->next
;
1817 LogOperation("%3d: DNSServiceBrowse(%##s) STOP", info
->sd
, ptr
->q
.qname
.c
);
1818 mDNS_StopBrowse(&mDNSStorage
, &ptr
->q
); // no need to error-check result
1819 freeL("browser_t/browse_termination_callback", ptr
);
1823 mDNSlocal
void udsserver_automatic_browse_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
1825 request_state
*request
;
1826 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
1828 #if APPLE_OSX_mDNSResponder
1829 machserver_automatic_browse_domain_changed(&d
->name
, add
);
1830 #endif // APPLE_OSX_mDNSResponder
1832 for (request
= all_requests
; request
; request
= request
->next
)
1834 if (request
->terminate
!= browse_termination_callback
) continue; // Not a browse operation
1835 if (!request
->u
.browser
.default_domain
) continue; // Not an auto-browse operation
1836 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
1838 browser_t
**ptr
= &request
->u
.browser
.browsers
;
1839 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
1842 // If we don't already have this domain in our list for this browse operation, add it now
1843 if (!*ptr
) add_domain_to_browser(request
, &d
->name
);
1844 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d
->name
);
1848 if (!*ptr
) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d
->name
);
1852 for (p
= AutoBrowseDomains
; p
; p
=p
->next
)
1853 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
1854 if (SameDomainName(&d
->name
, &p
->name
)) break;
1855 if (p
) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d
->name
);
1858 browser_t
*rem
= *ptr
;
1859 *ptr
= (*ptr
)->next
;
1860 mDNS_StopQueryWithRemoves(&mDNSStorage
, &rem
->q
);
1861 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem
);
1869 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
1872 if (result
== mStatus_MemFree
)
1874 // On shutdown, mDNS_Close automatically deregisters all records
1875 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
1876 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
1877 // (This should actually no longer be necessary, now that we do the proper cleanup in
1878 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
1879 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
1880 ARListElem
**ptr
= &LocalDomainEnumRecords
;
1881 while (*ptr
&& &(*ptr
)->ar
!= rr
) ptr
= &(*ptr
)->next
;
1882 if (*ptr
) { *ptr
= (*ptr
)->next
; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m
, rr
)); }
1883 mDNSPlatformMemFree(rr
->RecordContext
);
1887 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
1888 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
1889 // We may want to turn the common code into a subroutine.
1891 mDNSlocal
void RegisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
1893 // allocate/register legacy and non-legacy _browse PTR record
1895 ARListElem
*ptr
= mDNSPlatformMemAllocate(sizeof(*ptr
));
1897 debugf("Incrementing %s refcount for %##s",
1898 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
1899 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
1900 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
1902 mDNS_SetupResourceRecord(&ptr
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, AuthRecordLocalOnly
, FreeARElemCallback
, ptr
);
1903 MakeDomainNameFromDNSNameString(&ptr
->ar
.namestorage
, mDNS_DomainTypeNames
[type
]);
1904 AppendDNSNameString (&ptr
->ar
.namestorage
, "local");
1905 AssignDomainName(&ptr
->ar
.resrec
.rdata
->u
.name
, d
);
1906 err
= mDNS_Register(m
, &ptr
->ar
);
1909 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err
);
1910 mDNSPlatformMemFree(ptr
);
1914 ptr
->next
= LocalDomainEnumRecords
;
1915 LocalDomainEnumRecords
= ptr
;
1919 mDNSlocal
void DeregisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
1921 ARListElem
**ptr
= &LocalDomainEnumRecords
;
1922 domainname lhs
; // left-hand side of PTR, for comparison
1924 debugf("Decrementing %s refcount for %##s",
1925 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
1926 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
1927 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
1929 MakeDomainNameFromDNSNameString(&lhs
, mDNS_DomainTypeNames
[type
]);
1930 AppendDNSNameString (&lhs
, "local");
1934 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, d
) && SameDomainName((*ptr
)->ar
.resrec
.name
, &lhs
))
1936 ARListElem
*rem
= *ptr
;
1937 *ptr
= (*ptr
)->next
;
1938 mDNS_Deregister(m
, &rem
->ar
);
1941 else ptr
= &(*ptr
)->next
;
1945 mDNSlocal
void AddAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
1947 DNameListElem
*new = mDNSPlatformMemAllocate(sizeof(DNameListElem
));
1948 if (!new) { LogMsg("ERROR: malloc"); return; }
1949 AssignDomainName(&new->name
, name
);
1951 new->next
= AutoBrowseDomains
;
1952 AutoBrowseDomains
= new;
1953 udsserver_automatic_browse_domain_changed(new, mDNStrue
);
1956 mDNSlocal
void RmvAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
1958 DNameListElem
**p
= &AutoBrowseDomains
;
1959 while (*p
&& (!SameDomainName(&(*p
)->name
, name
) || (*p
)->uid
!= uid
)) p
= &(*p
)->next
;
1960 if (!*p
) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name
->c
);
1963 DNameListElem
*ptr
= *p
;
1965 udsserver_automatic_browse_domain_changed(ptr
, mDNSfalse
);
1966 mDNSPlatformMemFree(ptr
);
1970 mDNSlocal
void SetPrefsBrowseDomains(mDNS
*m
, DNameListElem
*browseDomains
, mDNSBool add
)
1973 for (d
= browseDomains
; d
; d
= d
->next
)
1977 RegisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
1978 AddAutoBrowseDomain(d
->uid
, &d
->name
);
1982 DeregisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
1983 RmvAutoBrowseDomain(d
->uid
, &d
->name
);
1988 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
1990 int num_autoname
= 0;
1992 for (req
= all_requests
; req
; req
= req
->next
)
1993 if (req
->terminate
== regservice_termination_callback
&& req
->u
.servicereg
.autoname
)
1996 // If DeviceInfo record is currently registered, see if we need to deregister it
1997 if (m
->DeviceInfo
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
)
1998 if (num_autoname
== 0 || !SameDomainLabelCS(m
->DeviceInfo
.resrec
.name
->c
, m
->nicelabel
.c
))
2000 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m
->DeviceInfo
.resrec
.name
);
2001 mDNS_Deregister(m
, &m
->DeviceInfo
);
2004 // If DeviceInfo record is not currently registered, see if we need to register it
2005 if (m
->DeviceInfo
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2006 if (num_autoname
> 0)
2008 mDNSu8 len
= m
->HIHardware
.c
[0] < 255 - 6 ? m
->HIHardware
.c
[0] : 255 - 6;
2009 mDNS_SetupResourceRecord(&m
->DeviceInfo
, mDNSNULL
, mDNSNULL
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeAdvisory
, AuthRecordAny
, mDNSNULL
, mDNSNULL
);
2010 ConstructServiceName(&m
->DeviceInfo
.namestorage
, &m
->nicelabel
, &DeviceInfoName
, &localdomain
);
2011 mDNSPlatformMemCopy(m
->DeviceInfo
.resrec
.rdata
->u
.data
+ 1, "model=", 6);
2012 mDNSPlatformMemCopy(m
->DeviceInfo
.resrec
.rdata
->u
.data
+ 7, m
->HIHardware
.c
+ 1, len
);
2013 m
->DeviceInfo
.resrec
.rdata
->u
.data
[0] = 6 + len
; // "model=" plus the device string
2014 m
->DeviceInfo
.resrec
.rdlength
= 7 + len
; // One extra for the length byte at the start of the string
2015 LogOperation("UpdateDeviceInfoRecord Register %##s", m
->DeviceInfo
.resrec
.name
);
2016 mDNS_Register(m
, &m
->DeviceInfo
);
2020 mDNSexport
void udsserver_handle_configchange(mDNS
*const m
)
2023 service_instance
*ptr
;
2024 DNameListElem
*RegDomains
= NULL
;
2025 DNameListElem
*BrowseDomains
= NULL
;
2028 UpdateDeviceInfoRecord(m
);
2030 // For autoname services, see if the default service name has changed, necessitating an automatic update
2031 for (req
= all_requests
; req
; req
= req
->next
)
2032 if (req
->terminate
== regservice_termination_callback
)
2033 if (req
->u
.servicereg
.autoname
&& !SameDomainLabelCS(req
->u
.servicereg
.name
.c
, m
->nicelabel
.c
))
2035 req
->u
.servicereg
.name
= m
->nicelabel
;
2036 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
2038 ptr
->renameonmemfree
= 1;
2039 if (ptr
->clientnotified
) SendServiceRemovalNotification(&ptr
->srs
);
2040 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr
->srs
.RR_PTR
.resrec
.name
->c
);
2041 if (mDNS_DeregisterService_drt(m
, &ptr
->srs
, mDNS_Dereg_rapid
))
2042 regservice_callback(m
, &ptr
->srs
, mStatus_MemFree
); // If service deregistered already, we can re-register immediately
2046 // Let the platform layer get the current DNS information
2048 mDNSPlatformSetDNSConfig(m
, mDNSfalse
, mDNSfalse
, mDNSNULL
, &RegDomains
, &BrowseDomains
);
2051 // Any automatic registration domains are also implicitly automatic browsing domains
2052 if (RegDomains
) SetPrefsBrowseDomains(m
, RegDomains
, mDNStrue
); // Add the new list first
2053 if (AutoRegistrationDomains
) SetPrefsBrowseDomains(m
, AutoRegistrationDomains
, mDNSfalse
); // Then clear the old list
2055 // Add any new domains not already in our AutoRegistrationDomains list
2056 for (p
=RegDomains
; p
; p
=p
->next
)
2058 DNameListElem
**pp
= &AutoRegistrationDomains
;
2059 while (*pp
&& ((*pp
)->uid
!= p
->uid
|| !SameDomainName(&(*pp
)->name
, &p
->name
))) pp
= &(*pp
)->next
;
2060 if (!*pp
) // If not found in our existing list, this is a new default registration domain
2062 RegisterLocalOnlyDomainEnumPTR(m
, &p
->name
, mDNS_DomainTypeRegistration
);
2063 udsserver_default_reg_domain_changed(p
, mDNStrue
);
2065 else // else found same domainname in both old and new lists, so no change, just delete old copy
2067 DNameListElem
*del
= *pp
;
2069 mDNSPlatformMemFree(del
);
2073 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2074 while (AutoRegistrationDomains
)
2076 DNameListElem
*del
= AutoRegistrationDomains
;
2077 AutoRegistrationDomains
= AutoRegistrationDomains
->next
; // Cut record from list FIRST,
2078 DeregisterLocalOnlyDomainEnumPTR(m
, &del
->name
, mDNS_DomainTypeRegistration
);
2079 udsserver_default_reg_domain_changed(del
, mDNSfalse
); // before calling udsserver_default_reg_domain_changed()
2080 mDNSPlatformMemFree(del
);
2083 // Now we have our new updated automatic registration domain list
2084 AutoRegistrationDomains
= RegDomains
;
2086 // Add new browse domains to internal list
2087 if (BrowseDomains
) SetPrefsBrowseDomains(m
, BrowseDomains
, mDNStrue
);
2089 // Remove old browse domains from internal list
2090 if (SCPrefBrowseDomains
)
2092 SetPrefsBrowseDomains(m
, SCPrefBrowseDomains
, mDNSfalse
);
2093 while (SCPrefBrowseDomains
)
2095 DNameListElem
*fptr
= SCPrefBrowseDomains
;
2096 SCPrefBrowseDomains
= SCPrefBrowseDomains
->next
;
2097 mDNSPlatformMemFree(fptr
);
2101 // Replace the old browse domains array with the new array
2102 SCPrefBrowseDomains
= BrowseDomains
;
2105 mDNSlocal
void AutomaticBrowseDomainChange(mDNS
*const m
, DNSQuestion
*q
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2110 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2111 AddRecord
? "Adding" : "Removing", answer
->rdata
->u
.name
.c
);
2113 if (AddRecord
) AddAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2114 else RmvAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2117 mDNSlocal mStatus
handle_browse_request(request_state
*request
)
2119 char regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2120 domainname typedn
, d
, temp
;
2121 mDNSs32 NumSubTypes
;
2122 mStatus err
= mStatus_NoError
;
2124 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2125 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2126 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2127 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
2129 if (get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2130 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0) return(mStatus_BadParamErr
);
2132 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2134 if (domain
[0] == '\0') uDNS_SetupSearchDomains(&mDNSStorage
, UDNS_START_WAB_QUERY
);
2136 request
->flags
= flags
;
2138 NumSubTypes
= ChopSubTypes(regtype
); // Note: Modifies regtype string to remove trailing subtypes
2139 if (NumSubTypes
< 0 || NumSubTypes
> 1) return(mStatus_BadParamErr
);
2140 if (NumSubTypes
== 1 && !AppendDNSNameString(&typedn
, regtype
+ strlen(regtype
) + 1)) return(mStatus_BadParamErr
);
2142 if (!regtype
[0] || !AppendDNSNameString(&typedn
, regtype
)) return(mStatus_BadParamErr
);
2144 if (!MakeDomainNameFromDNSNameString(&temp
, regtype
)) return(mStatus_BadParamErr
);
2145 // For over-long service types, we only allow domain "local"
2146 if (temp
.c
[0] > 15 && domain
[0] == 0) mDNSPlatformStrCopy(domain
, "local.");
2148 // Set up browser info
2149 request
->u
.browser
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2150 request
->u
.browser
.interface_id
= InterfaceID
;
2151 AssignDomainName(&request
->u
.browser
.regtype
, &typedn
);
2152 request
->u
.browser
.default_domain
= !domain
[0];
2153 request
->u
.browser
.browsers
= NULL
;
2155 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START",
2156 request
->sd
, request
->flags
, interfaceIndex
, request
->u
.browser
.regtype
.c
, domain
);
2158 // We need to unconditionally set request->terminate, because even if we didn't successfully
2159 // start any browses right now, subsequent configuration changes may cause successful
2160 // browses to be added, and we'll need to cancel them before freeing this memory.
2161 request
->terminate
= browse_termination_callback
;
2165 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return(mStatus_BadParamErr
);
2166 err
= add_domain_to_browser(request
, &d
);
2168 err
= AuthorizedDomain(request
, &d
, AutoBrowseDomains
) ? add_domain_to_browser(request
, &d
) : mStatus_NoError
;
2173 DNameListElem
*sdom
;
2174 for (sdom
= AutoBrowseDomains
; sdom
; sdom
= sdom
->next
)
2175 if (!sdom
->uid
|| SystemUID(request
->uid
) || request
->uid
== sdom
->uid
)
2177 err
= add_domain_to_browser(request
, &sdom
->name
);
2180 if (SameDomainName(&sdom
->name
, &localdomain
)) break;
2181 else err
= mStatus_NoError
; // suppress errors for non-local "default" domains
2189 // ***************************************************************************
2190 #if COMPILER_LIKES_PRAGMA_MARK
2192 #pragma mark - DNSServiceResolve
2195 mDNSlocal
void resolve_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2198 char fullname
[MAX_ESCAPED_DOMAIN_NAME
], target
[MAX_ESCAPED_DOMAIN_NAME
];
2201 request_state
*req
= question
->QuestionContext
;
2204 LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req
->sd
, question
->qname
.c
, AddRecord
? "ADD" : "RMV", RRDisplayString(m
, answer
));
2208 if (req
->u
.resolve
.srv
== answer
) req
->u
.resolve
.srv
= mDNSNULL
;
2209 if (req
->u
.resolve
.txt
== answer
) req
->u
.resolve
.txt
= mDNSNULL
;
2213 if (answer
->rrtype
== kDNSType_SRV
) req
->u
.resolve
.srv
= answer
;
2214 if (answer
->rrtype
== kDNSType_TXT
) req
->u
.resolve
.txt
= answer
;
2216 if (!req
->u
.resolve
.txt
|| !req
->u
.resolve
.srv
) return; // only deliver result to client if we have both answers
2218 ConvertDomainNameToCString(answer
->name
, fullname
);
2219 ConvertDomainNameToCString(&req
->u
.resolve
.srv
->rdata
->u
.srv
.target
, target
);
2221 // calculate reply length
2222 len
+= sizeof(DNSServiceFlags
);
2223 len
+= sizeof(mDNSu32
); // interface index
2224 len
+= sizeof(DNSServiceErrorType
);
2225 len
+= strlen(fullname
) + 1;
2226 len
+= strlen(target
) + 1;
2227 len
+= 2 * sizeof(mDNSu16
); // port, txtLen
2228 len
+= req
->u
.resolve
.txt
->rdlength
;
2230 // allocate/init reply header
2231 rep
= create_reply(resolve_reply_op
, len
, req
);
2232 rep
->rhdr
->flags
= dnssd_htonl(0);
2233 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNSfalse
));
2234 rep
->rhdr
->error
= dnssd_htonl(kDNSServiceErr_NoError
);
2236 data
= (char *)&rep
->rhdr
[1];
2238 // write reply data to message
2239 put_string(fullname
, &data
);
2240 put_string(target
, &data
);
2241 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[0];
2242 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[1];
2243 put_uint16(req
->u
.resolve
.txt
->rdlength
, &data
);
2244 put_rdata (req
->u
.resolve
.txt
->rdlength
, req
->u
.resolve
.txt
->rdata
->u
.data
, &data
);
2246 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req
->sd
, fullname
, target
, mDNSVal16(req
->u
.resolve
.srv
->rdata
->u
.srv
.port
));
2247 append_reply(req
, rep
);
2250 mDNSlocal
void resolve_termination_callback(request_state
*request
)
2252 LogOperation("%3d: DNSServiceResolve(%##s) STOP", request
->sd
, request
->u
.resolve
.qtxt
.qname
.c
);
2253 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2254 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2255 if (request
->u
.resolve
.external_advertise
) external_stop_resolving_service(&request
->u
.resolve
.qsrv
.qname
);
2258 mDNSlocal mStatus
handle_resolve_request(request_state
*request
)
2260 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2264 // extract the data from the message
2265 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2266 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2267 mDNSInterfaceID InterfaceID
;
2268 mDNSBool wasP2P
= (interfaceIndex
== kDNSServiceInterfaceIndexP2P
);
2271 request
->flags
= flags
;
2272 if (wasP2P
) interfaceIndex
= kDNSServiceInterfaceIndexAny
;
2274 InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2275 if (interfaceIndex
&& !InterfaceID
)
2276 { LogMsg("ERROR: handle_resolve_request bad interfaceIndex %d", interfaceIndex
); return(mStatus_BadParamErr
); }
2278 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0 ||
2279 get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2280 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
2281 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
2283 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2285 if (build_domainname_from_strings(&fqdn
, name
, regtype
, domain
) < 0)
2286 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name
, regtype
, domain
); return(mStatus_BadParamErr
); }
2288 mDNSPlatformMemZero(&request
->u
.resolve
, sizeof(request
->u
.resolve
));
2291 request
->u
.resolve
.qsrv
.InterfaceID
= InterfaceID
;
2292 request
->u
.resolve
.qsrv
.Target
= zeroAddr
;
2293 AssignDomainName(&request
->u
.resolve
.qsrv
.qname
, &fqdn
);
2294 request
->u
.resolve
.qsrv
.qtype
= kDNSType_SRV
;
2295 request
->u
.resolve
.qsrv
.qclass
= kDNSClass_IN
;
2296 request
->u
.resolve
.qsrv
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2297 request
->u
.resolve
.qsrv
.ExpectUnique
= mDNStrue
;
2298 request
->u
.resolve
.qsrv
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2299 request
->u
.resolve
.qsrv
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2300 request
->u
.resolve
.qsrv
.SuppressUnusable
= mDNSfalse
;
2301 request
->u
.resolve
.qsrv
.SearchListIndex
= 0;
2302 request
->u
.resolve
.qsrv
.AppendSearchDomains
= 0;
2303 request
->u
.resolve
.qsrv
.RetryWithSearchDomains
= mDNSfalse
;
2304 request
->u
.resolve
.qsrv
.TimeoutQuestion
= 0;
2305 request
->u
.resolve
.qsrv
.WakeOnResolve
= (flags
& kDNSServiceFlagsWakeOnResolve
) != 0;
2306 request
->u
.resolve
.qsrv
.qnameOrig
= mDNSNULL
;
2307 request
->u
.resolve
.qsrv
.QuestionCallback
= resolve_result_callback
;
2308 request
->u
.resolve
.qsrv
.QuestionContext
= request
;
2310 request
->u
.resolve
.qtxt
.InterfaceID
= InterfaceID
;
2311 request
->u
.resolve
.qtxt
.Target
= zeroAddr
;
2312 AssignDomainName(&request
->u
.resolve
.qtxt
.qname
, &fqdn
);
2313 request
->u
.resolve
.qtxt
.qtype
= kDNSType_TXT
;
2314 request
->u
.resolve
.qtxt
.qclass
= kDNSClass_IN
;
2315 request
->u
.resolve
.qtxt
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2316 request
->u
.resolve
.qtxt
.ExpectUnique
= mDNStrue
;
2317 request
->u
.resolve
.qtxt
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2318 request
->u
.resolve
.qtxt
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2319 request
->u
.resolve
.qtxt
.SuppressUnusable
= mDNSfalse
;
2320 request
->u
.resolve
.qtxt
.SearchListIndex
= 0;
2321 request
->u
.resolve
.qtxt
.AppendSearchDomains
= 0;
2322 request
->u
.resolve
.qtxt
.RetryWithSearchDomains
= mDNSfalse
;
2323 request
->u
.resolve
.qtxt
.TimeoutQuestion
= 0;
2324 request
->u
.resolve
.qtxt
.WakeOnResolve
= 0;
2325 request
->u
.resolve
.qtxt
.qnameOrig
= mDNSNULL
;
2326 request
->u
.resolve
.qtxt
.QuestionCallback
= resolve_result_callback
;
2327 request
->u
.resolve
.qtxt
.QuestionContext
= request
;
2329 request
->u
.resolve
.ReportTime
= NonZeroTime(mDNS_TimeNow(&mDNSStorage
) + 130 * mDNSPlatformOneSecond
);
2331 request
->u
.resolve
.external_advertise
= mDNSfalse
;
2334 if (!AuthorizedDomain(request
, &fqdn
, AutoBrowseDomains
)) return(mStatus_NoError
);
2337 // ask the questions
2338 LogOperation("%3d: DNSServiceResolve(%X %d %##s) START", request
->sd
, flags
, interfaceIndex
, request
->u
.resolve
.qsrv
.qname
.c
);
2339 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2342 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2343 if (err
) mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2346 request
->terminate
= resolve_termination_callback
;
2347 // If the user explicitly passed in P2P, we don't restrict the domain in which we resolve.
2348 if (wasP2P
|| (!InterfaceID
&& IsLocalDomain(&fqdn
) && (request
->flags
& kDNSServiceFlagsIncludeP2P
)))
2350 request
->u
.resolve
.external_advertise
= mDNStrue
;
2351 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2352 external_start_resolving_service(&fqdn
);
2360 // ***************************************************************************
2361 #if COMPILER_LIKES_PRAGMA_MARK
2363 #pragma mark - DNSServiceQueryRecord
2366 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2367 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2368 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2369 // the mDNSCore operation if the client dies or closes its socket.
2371 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2372 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2373 // Returns 0 when there are no more search domains and the caller should reissue the query
2374 mDNSlocal
int AppendNewSearchDomain(mDNS
*const m
, DNSQuestion
*question
)
2379 // Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2380 // the domains and should try the single label query directly on the wire.
2381 if (question
->SearchListIndex
== -1)
2383 LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question
->qname
.c
, DNSTypeName(question
->qtype
));
2387 if (!question
->AppendSearchDomains
)
2389 LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question
->qname
.c
, DNSTypeName(question
->qtype
));
2393 // Save the original name, before we modify them below.
2394 if (!question
->qnameOrig
)
2396 question
->qnameOrig
= mallocL("AppendNewSearchDomain", sizeof(domainname
));
2397 if (!question
->qnameOrig
) { LogMsg("AppendNewSearchDomain: ERROR!! malloc failure"); return -1; }
2398 question
->qnameOrig
->c
[0] = 0;
2399 AssignDomainName(question
->qnameOrig
, &question
->qname
);
2400 LogInfo("AppendSearchDomain: qnameOrig %##s", question
->qnameOrig
->c
);
2403 sd
= uDNS_GetNextSearchDomain(m
, question
->InterfaceID
, &question
->SearchListIndex
, !question
->AppendLocalSearchDomains
);
2404 // We use -1 to indicate that we have searched all the domains and should try the single label
2405 // query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2406 if (question
->SearchListIndex
== -1)
2408 LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2412 // Not a common case. Perhaps, we should try the next search domain if it exceeds ?
2413 if (sd
&& (DomainNameLength(question
->qnameOrig
) + DomainNameLength(sd
)) > MAX_DOMAIN_NAME
)
2415 LogMsg("AppendNewSearchDomain: ERROR!! exceeding max domain length for %##s (%s) SearchDomain %##s length %d, Question name length %d", question
->qnameOrig
->c
, DNSTypeName(question
->qtype
), sd
->c
, DomainNameLength(question
->qnameOrig
), DomainNameLength(sd
));
2419 // if there are no more search domains and we have already tried this question
2420 // without appending search domains, then we are done.
2421 if (!sd
&& !ApplySearchDomainsFirst(question
))
2423 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question
->qname
.c
, DNSTypeName(question
->qtype
));
2427 // Stop the question before changing the name as negative cache entries could be pointing at this question.
2428 // Even if we don't change the question in the case of returning 0, the caller is going to restart the
2430 err
= mDNS_StopQuery(&mDNSStorage
, question
);
2431 if (err
) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
); }
2433 AssignDomainName(&question
->qname
, question
->qnameOrig
);
2436 AppendDomainName(&question
->qname
, sd
);
2437 LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question
->qname
.c
, question
->SearchListIndex
);
2441 // Try the question as single label
2442 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question
->qname
.c
, DNSTypeName(question
->qtype
));
2446 #if APPLE_OSX_mDNSResponder
2448 mDNSlocal mDNSBool
DomainInSearchList(domainname
*domain
)
2450 const SearchListElem
*s
;
2451 for (s
=SearchList
; s
; s
=s
->next
)
2452 if (SameDomainName(&s
->domain
, domain
)) return mDNStrue
;
2456 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
2458 mDNSlocal mStatus
SendAdditionalQuery(DNSQuestion
*q
, request_state
*request
, mStatus err
)
2460 extern domainname ActiveDirectoryPrimaryDomain
;
2461 DNSQuestion
**question2
;
2462 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
2463 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
2465 question2
= mDNSNULL
;
2466 if (request
->hdr
.op
== query_request
)
2467 question2
= &request
->u
.queryrecord
.q2
;
2468 else if (request
->hdr
.op
== addrinfo_request
)
2470 if (q
->qtype
== kDNSType_A
)
2471 question2
= &request
->u
.addrinfo
.q42
;
2472 else if (q
->qtype
== kDNSType_AAAA
)
2473 question2
= &request
->u
.addrinfo
.q62
;
2477 LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q
->qname
.c
, DNSTypeName(q
->qtype
));
2478 return mStatus_BadParamErr
;
2481 // Sanity check: If we already sent an additonal query, we don't need to send one more.
2483 // 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
2484 // is called to see whether a unicast query should be sent or not.
2486 // 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
2487 // was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
2488 // send the additional query.
2490 // Thus, it should not be called more than once.
2493 LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q
->qname
.c
, DNSTypeName(q
->qtype
));
2497 if (!q
->ForceMCast
&& SameDomainLabel(LastLabel(&q
->qname
), (const mDNSu8
*)&localdomain
))
2498 if (q
->qtype
== kDNSType_A
|| q
->qtype
== kDNSType_AAAA
|| VALID_MSAD_SRV(q
))
2501 int labels
= CountLabels(&q
->qname
);
2502 q2
= mallocL("DNSQuestion", sizeof(DNSQuestion
));
2503 if (!q2
) FatalError("ERROR: SendAdditionalQuery malloc");
2506 q2
->InterfaceID
= mDNSInterface_Unicast
;
2507 q2
->ExpectUnique
= mDNStrue
;
2508 // If the query starts as a single label e.g., somehost, and we have search domains with .local,
2509 // queryrecord_result_callback calls this function when .local is appended to "somehost".
2510 // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
2511 // "somehost". We need to copy that information so that when we retry with a different search
2512 // domain e.g., mycompany.local, we get "somehost.mycompany.local".
2515 (*question2
)->qnameOrig
= mallocL("SendAdditionalQuery", DomainNameLength(q
->qnameOrig
));
2516 if (!(*question2
)->qnameOrig
) { LogMsg("SendAdditionalQuery: ERROR!! malloc failure"); return mStatus_NoMemoryErr
; }
2517 (*question2
)->qnameOrig
->c
[0] = 0;
2518 AssignDomainName((*question2
)->qnameOrig
, q
->qnameOrig
);
2519 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2
)->qnameOrig
->c
);
2521 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
2522 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
2523 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
2524 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
2525 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
2526 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
2527 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
2528 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
2529 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
2530 // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
2531 // of those, we don't want do the SOA check for the local
2532 if (labels
== 2 && !SameDomainName(&q
->qname
, &ActiveDirectoryPrimaryDomain
) && !DomainInSearchList(&q
->qname
))
2534 AssignDomainName(&q2
->qname
, &localdomain
);
2535 q2
->qtype
= kDNSType_SOA
;
2536 q2
->LongLived
= mDNSfalse
;
2537 q2
->ForceMCast
= mDNSfalse
;
2538 q2
->ReturnIntermed
= mDNStrue
;
2539 // Don't append search domains for the .local SOA query
2540 q2
->AppendSearchDomains
= 0;
2541 q2
->AppendLocalSearchDomains
= 0;
2542 q2
->RetryWithSearchDomains
= mDNSfalse
;
2543 q2
->SearchListIndex
= 0;
2544 q2
->TimeoutQuestion
= 0;
2546 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
));
2547 err
= mDNS_StartQuery(&mDNSStorage
, q2
);
2548 if (err
) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
), (int)err
);
2552 #endif // APPLE_OSX_mDNSResponder
2554 // This function tries to append a search domain if valid and possible. If so, returns true.
2555 mDNSlocal mDNSBool
RetryQuestionWithSearchDomains(mDNS
*const m
, DNSQuestion
*question
, request_state
*req
)
2558 // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
2559 // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
2560 // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
2561 // RetryWithSearchDomains which may or may not be set.
2563 // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
2564 // is a valid question for appending search domains, retry by appending domains
2566 if (!question
->SuppressQuery
&& question
->SearchListIndex
!= -1 && question
->AppendSearchDomains
)
2568 question
->RetryWithSearchDomains
= 0;
2569 result
= AppendNewSearchDomain(m
, question
);
2570 // As long as the result is either zero or 1, we retry the question. If we exahaust the search
2571 // domains (result is zero) we try the original query (as it was before appending the search
2572 // domains) as such on the wire as a last resort if we have not tried them before. For queries
2573 // with more than one label, we have already tried them before appending search domains and
2574 // hence don't retry again
2578 err
= mDNS_StartQuery(m
, question
);
2581 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
));
2582 // If the result was zero, it meant that there are no search domains and we just retried the question
2583 // as a single label and we should not retry with search domains anymore.
2584 if (!result
) question
->SearchListIndex
= -1;
2589 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
);
2590 // We have already stopped the query and could not restart. Reset the appropriate pointers
2591 // so that we don't call stop again when the question terminates
2592 question
->QuestionContext
= mDNSNULL
;
2598 LogInfo("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req
->sd
, question
->SuppressQuery
, question
->SearchListIndex
, question
->AppendSearchDomains
);
2603 mDNSlocal
void queryrecord_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2605 char name
[MAX_ESCAPED_DOMAIN_NAME
];
2606 request_state
*req
= question
->QuestionContext
;
2610 DNSServiceErrorType error
= kDNSServiceErr_NoError
;
2611 DNSQuestion
*q
= mDNSNULL
;
2613 #if APPLE_OSX_mDNSResponder
2615 // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
2616 // get any callbacks from the core after this.
2619 LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
2622 if (req
->hdr
.op
== query_request
&& question
== req
->u
.queryrecord
.q2
)
2623 q
= &req
->u
.queryrecord
.q
;
2624 else if (req
->hdr
.op
== addrinfo_request
&& question
== req
->u
.addrinfo
.q42
)
2625 q
= &req
->u
.addrinfo
.q4
;
2626 else if (req
->hdr
.op
== addrinfo_request
&& question
== req
->u
.addrinfo
.q62
)
2627 q
= &req
->u
.addrinfo
.q6
;
2629 if (q
&& question
->qtype
!= q
->qtype
&& !SameDomainName(&question
->qname
, &q
->qname
))
2632 domainname
*orig
= question
->qnameOrig
;
2634 LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question
->qname
.c
);
2635 mDNS_StopQuery(m
, question
);
2636 question
->QuestionContext
= mDNSNULL
;
2638 // We got a negative response for the SOA record indicating that .local does not exist.
2639 // But we might have other search domains (that does not end in .local) that can be
2640 // appended to this question. In that case, we want to retry the question. Otherwise,
2641 // we don't want to try this question as unicast.
2642 if (answer
->RecordType
== kDNSRecordTypePacketNegative
&& !q
->AppendSearchDomains
)
2644 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q
->qname
.c
);
2648 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
2650 // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
2651 // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
2652 // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
2653 // SendAdditionalQuery as to how qnameOrig gets initialized.
2655 question
->InterfaceID
= mDNSInterface_Unicast
;
2656 question
->ExpectUnique
= mDNStrue
;
2657 question
->qnameOrig
= orig
;
2659 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), question
->QuestionContext
);
2661 // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
2662 // Hence, we need to set it explicitly here.
2663 question
->QuestionContext
= req
;
2664 err
= mDNS_StartQuery(m
, question
);
2665 if (err
) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
);
2667 // If we got a positive response to local SOA, then try the .local question as unicast
2668 if (answer
->RecordType
!= kDNSRecordTypePacketNegative
) return;
2670 // Fall through and get the next search domain. The question is pointing at .local
2671 // and we don't want to try that. Try the next search domain. Don't try with local
2672 // search domains for the unicast question anymore.
2674 // Note: we started the question above which will be stopped immediately (never sent on the wire)
2675 // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
2676 // question has already started.
2677 question
->AppendLocalSearchDomains
= 0;
2680 if (q
&& AddRecord
&& (question
->InterfaceID
== mDNSInterface_Unicast
) && !answer
->rdlength
)
2682 // If we get a negative response to the unicast query that we sent above, retry after appending search domains
2683 // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
2684 // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
2685 // To keep things simple, we handle unicast ".local" separately here.
2686 LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question
->qname
.c
, DNSTypeName(question
->qtype
));
2687 if (RetryQuestionWithSearchDomains(m
, question
, req
))
2689 if (question
->AppendSearchDomains
&& !question
->AppendLocalSearchDomains
&& IsLocalDomain(&question
->qname
))
2691 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
2692 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
2693 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
2694 // in the list. We leave it disabled so that it does not hit the wire.
2695 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
));
2696 question
->ThisQInterval
= 0;
2699 // If we are here it means that either "question" is not "q2" OR we got a positive response for "q2" OR we have no more search
2700 // domains to append for "q2". In all cases, fall through and deliver the response
2702 #endif // APPLE_OSX_mDNSResponder
2704 if (answer
->RecordType
== kDNSRecordTypePacketNegative
)
2706 // If this question needs to be timed out and we have reached the stop time, mark
2707 // the error as timeout. It is possible that we might get a negative response from an
2708 // external DNS server at the same time when this question reaches its stop time. We
2709 // can't tell the difference as there is no indication in the callback. This should
2710 // be okay as we will be timing out this query anyway.
2712 if (question
->TimeoutQuestion
)
2714 if ((m
->timenow
- question
->StopTime
) >= 0)
2716 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
);
2717 error
= kDNSServiceErr_Timeout
;
2721 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
2722 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
2723 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
2724 // server is going to assert that pretty much every single multicast name doesn't exist.
2726 // If we are timing out this query, we need to deliver the negative answer to the application
2727 if (error
!= kDNSServiceErr_Timeout
)
2729 if (!answer
->InterfaceID
&& IsLocalDomain(answer
->name
))
2731 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with unicast", question
->qname
.c
, DNSTypeName(question
->qtype
));
2734 error
= kDNSServiceErr_NoSuchRecord
;
2736 AddRecord
= mDNStrue
;
2738 // If we get a negative answer, try appending search domains. Don't append search domains
2739 // - if we are timing out this question
2740 // - if the negative response was received as a result of a multicast query
2741 // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
2742 if (error
!= kDNSServiceErr_Timeout
)
2744 if (!q
&& !answer
->InterfaceID
&& !answer
->rdlength
&& AddRecord
)
2746 // If the original question did not end in .local, we did not send an SOA query
2747 // to figure out whether we should send an additional unicast query or not. If we just
2748 // appended .local, we need to see if we need to send an additional query. This should
2749 // normally happen just once because after we append .local, we ignore all negative
2750 // responses for .local above.
2751 LogInfo("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question
->qname
.c
, DNSTypeName(question
->qtype
));
2752 if (RetryQuestionWithSearchDomains(m
, question
, req
))
2754 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
2755 // be anywhere in the search domain list.
2756 #if APPLE_OSX_mDNSResponder
2757 mStatus err
= mStatus_NoError
;
2758 err
= SendAdditionalQuery(question
, req
, err
);
2759 if (err
) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
2760 #endif // APPLE_OSX_mDNSResponder
2766 ConvertDomainNameToCString(answer
->name
, name
);
2768 LogOperation("%3d: %s(%##s, %s) %s %s", req
->sd
,
2769 req
->hdr
.op
== query_request
? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
2770 question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "ADD" : "RMV", RRDisplayString(m
, answer
));
2772 len
= sizeof(DNSServiceFlags
); // calculate reply data length
2773 len
+= sizeof(mDNSu32
); // interface index
2774 len
+= sizeof(DNSServiceErrorType
);
2775 len
+= strlen(name
) + 1;
2776 len
+= 3 * sizeof(mDNSu16
); // type, class, rdlen
2777 len
+= answer
->rdlength
;
2778 len
+= sizeof(mDNSu32
); // TTL
2780 rep
= create_reply(req
->hdr
.op
== query_request
? query_reply_op
: addrinfo_reply_op
, len
, req
);
2782 rep
->rhdr
->flags
= dnssd_htonl(AddRecord
? kDNSServiceFlagsAdd
: 0);
2783 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
2784 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
2785 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
2786 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
2787 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
2788 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
2789 // should not have existed to answer this question if the corresponding interface is not valid.
2790 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
, mDNStrue
));
2791 rep
->rhdr
->error
= dnssd_htonl(error
);
2793 data
= (char *)&rep
->rhdr
[1];
2795 put_string(name
, &data
);
2796 put_uint16(answer
->rrtype
, &data
);
2797 put_uint16(answer
->rrclass
, &data
);
2798 put_uint16(answer
->rdlength
, &data
);
2799 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2800 // function just does a blind memory copy without regard to structures that may have holes in them.
2801 if (answer
->rdlength
)
2802 if (!putRData(mDNSNULL
, (mDNSu8
*)data
, (mDNSu8
*)rep
->rhdr
+ len
, answer
))
2803 LogMsg("queryrecord_result_callback putRData failed %d", (mDNSu8
*)rep
->rhdr
+ len
- (mDNSu8
*)data
);
2804 data
+= answer
->rdlength
;
2805 put_uint32(AddRecord
? answer
->rroriginalttl
: 0, &data
);
2807 append_reply(req
, rep
);
2808 // Stop the question, if we just timed out
2809 if (error
== kDNSServiceErr_Timeout
)
2811 mDNS_StopQuery(m
, question
);
2812 // Reset the pointers so that we don't call stop on termination
2813 question
->QuestionContext
= mDNSNULL
;
2815 #if APPLE_OSX_mDNSResponder
2817 CHECK_WCF_FUNCTION(WCFIsServerRunning
)
2820 socklen_t xucredlen
= sizeof(x
);
2822 if (WCFIsServerRunning((WCFConnection
*)m
->WCF
) && answer
->rdlength
!= 0)
2824 if (getsockopt(req
->sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 &&
2825 (x
.cr_version
== XUCRED_VERSION
))
2827 struct sockaddr_storage addr
;
2828 const RDataBody2
*const rdb
= (RDataBody2
*)answer
->rdata
->u
.data
;
2830 if (answer
->rrtype
== kDNSType_A
|| answer
->rrtype
== kDNSType_AAAA
)
2832 if (answer
->rrtype
== kDNSType_A
)
2834 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&addr
;
2836 if (!putRData(mDNSNULL
, (mDNSu8
*)&sin
->sin_addr
, (mDNSu8
*)(&sin
->sin_addr
+ sizeof(rdb
->ipv4
)), answer
))
2837 LogMsg("queryrecord_result_callback: WCF AF_INET putRData failed");
2840 addr
.ss_len
= sizeof (struct sockaddr_in
);
2841 addr
.ss_family
= AF_INET
;
2844 else if (answer
->rrtype
== kDNSType_AAAA
)
2846 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&addr
;
2847 sin6
->sin6_port
= 0;
2848 if (!putRData(mDNSNULL
, (mDNSu8
*)&sin6
->sin6_addr
, (mDNSu8
*)(&sin6
->sin6_addr
+ sizeof(rdb
->ipv6
)), answer
))
2849 LogMsg("queryrecord_result_callback: WCF AF_INET6 putRData failed");
2852 addr
.ss_len
= sizeof (struct sockaddr_in6
);
2853 addr
.ss_family
= AF_INET6
;
2858 debugf("queryrecord_result_callback: Name %s, uid %u, addr length %d", name
, x
.cr_uid
, addr
.ss_len
);
2859 CHECK_WCF_FUNCTION((WCFConnection
*)WCFNameResolvesToAddr
)
2861 WCFNameResolvesToAddr(m
->WCF
, name
, (struct sockaddr
*)&addr
, x
.cr_uid
);
2865 else if (answer
->rrtype
== kDNSType_CNAME
)
2868 char cname_cstr
[MAX_ESCAPED_DOMAIN_NAME
];
2869 if (!putRData(mDNSNULL
, cname
.c
, (mDNSu8
*)(cname
.c
+ MAX_DOMAIN_NAME
), answer
))
2870 LogMsg("queryrecord_result_callback: WCF CNAME putRData failed");
2873 ConvertDomainNameToCString(&cname
, cname_cstr
);
2874 CHECK_WCF_FUNCTION((WCFConnection
*)WCFNameResolvesToAddr
)
2876 WCFNameResolvesToName(m
->WCF
, name
, cname_cstr
, x
.cr_uid
);
2881 else my_perror("queryrecord_result_callback: ERROR: getsockopt LOCAL_PEERCRED");
2888 mDNSlocal
void queryrecord_termination_callback(request_state
*request
)
2890 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP",
2891 request
->sd
, request
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(request
->u
.queryrecord
.q
.qtype
));
2892 if (request
->u
.queryrecord
.q
.QuestionContext
)
2894 mDNS_StopQuery(&mDNSStorage
, &request
->u
.queryrecord
.q
); // no need to error check
2895 request
->u
.queryrecord
.q
.QuestionContext
= mDNSNULL
;
2899 DNSQuestion
*question
= &request
->u
.queryrecord
.q
;
2900 LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
);
2903 if (request
->u
.queryrecord
.q
.qnameOrig
)
2905 freeL("QueryTermination", request
->u
.queryrecord
.q
.qnameOrig
);
2906 request
->u
.queryrecord
.q
.qnameOrig
= mDNSNULL
;
2908 if (request
->u
.queryrecord
.q
.InterfaceID
== mDNSInterface_P2P
|| (!request
->u
.queryrecord
.q
.InterfaceID
&& SameDomainName((const domainname
*)LastLabel(&request
->u
.queryrecord
.q
.qname
), &localdomain
) && (request
->flags
& kDNSServiceFlagsIncludeP2P
)))
2910 LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
2911 external_stop_browsing_for_service(&mDNSStorage
, &request
->u
.queryrecord
.q
.qname
, request
->u
.queryrecord
.q
.qtype
);
2913 if (request
->u
.queryrecord
.q2
)
2915 if (request
->u
.queryrecord
.q2
->QuestionContext
)
2917 LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request
->u
.queryrecord
.q2
->qname
.c
);
2918 mDNS_StopQuery(&mDNSStorage
, request
->u
.queryrecord
.q2
);
2922 DNSQuestion
*question
= request
->u
.queryrecord
.q2
;
2923 LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question
->qname
.c
, DNSTypeName(question
->qtype
), question
->InterfaceID
);
2925 if (request
->u
.queryrecord
.q2
->qnameOrig
)
2927 LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request
->u
.queryrecord
.q2
->qnameOrig
->c
);
2928 freeL("QueryTermination q2", request
->u
.queryrecord
.q2
->qnameOrig
);
2929 request
->u
.queryrecord
.q2
->qnameOrig
= mDNSNULL
;
2931 freeL("queryrecord Q2", request
->u
.queryrecord
.q2
);
2932 request
->u
.queryrecord
.q2
= mDNSNULL
;
2936 mDNSlocal mStatus
handle_queryrecord_request(request_state
*request
)
2938 DNSQuestion
*const q
= &request
->u
.queryrecord
.q
;
2940 mDNSu16 rrtype
, rrclass
;
2943 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2944 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2945 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2946 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
2948 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0) return(mStatus_BadParamErr
);
2949 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
2950 rrclass
= get_uint16(&request
->msgptr
, request
->msgend
);
2952 if (!request
->msgptr
)
2953 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2955 request
->flags
= flags
;
2956 mDNSPlatformMemZero(&request
->u
.queryrecord
, sizeof(request
->u
.queryrecord
));
2958 q
->InterfaceID
= InterfaceID
;
2959 q
->Target
= zeroAddr
;
2960 if (!MakeDomainNameFromDNSNameString(&q
->qname
, name
)) return(mStatus_BadParamErr
);
2962 if (!AuthorizedDomain(request
, &q
->qname
, AutoBrowseDomains
)) return (mStatus_NoError
);
2965 q
->qclass
= rrclass
;
2966 q
->LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2967 q
->ExpectUnique
= mDNSfalse
;
2968 q
->ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2969 q
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2970 q
->SuppressUnusable
= (flags
& kDNSServiceFlagsSuppressUnusable
) != 0;
2971 q
->TimeoutQuestion
= (flags
& kDNSServiceFlagsTimeout
) != 0;
2972 q
->WakeOnResolve
= 0;
2973 q
->QuestionCallback
= queryrecord_result_callback
;
2974 q
->QuestionContext
= request
;
2975 q
->SearchListIndex
= 0;
2977 // Don't append search domains for fully qualified domain names including queries
2978 // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
2979 // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
2980 // append search domains or not. So, we record that information in AppendSearchDomains.
2982 // We append search domains only for queries that are a single label. If overriden using
2983 // command line argument "AlwaysAppendSearchDomains", then we do it for any query which
2984 // is not fully qualified.
2986 if ((rrtype
== kDNSType_A
|| rrtype
== kDNSType_AAAA
) && name
[strlen(name
) - 1] != '.' &&
2987 (AlwaysAppendSearchDomains
|| CountLabels(&q
->qname
) == 1))
2989 q
->AppendSearchDomains
= 1;
2990 q
->AppendLocalSearchDomains
= 1;
2994 q
->AppendSearchDomains
= 0;
2995 q
->AppendLocalSearchDomains
= 0;
2998 // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
2999 // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3000 // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3002 q
->RetryWithSearchDomains
= ApplySearchDomainsFirst(q
) ? 1 : 0;
3003 q
->qnameOrig
= mDNSNULL
;
3005 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START", request
->sd
, flags
, interfaceIndex
, q
->qname
.c
, DNSTypeName(q
->qtype
));
3006 err
= mDNS_StartQuery(&mDNSStorage
, q
);
3007 if (err
) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q
->qname
.c
, DNSTypeName(q
->qtype
), (int)err
);
3010 request
->terminate
= queryrecord_termination_callback
;
3011 if (q
->InterfaceID
== mDNSInterface_P2P
|| (!q
->InterfaceID
&& SameDomainName((const domainname
*)LastLabel(&q
->qname
), &localdomain
) && (flags
& kDNSServiceFlagsIncludeP2P
)))
3013 LogInfo("handle_queryrecord_request: calling external_start_browsing_for_service()");
3014 external_start_browsing_for_service(&mDNSStorage
, &q
->qname
, q
->qtype
);
3018 #if APPLE_OSX_mDNSResponder
3019 err
= SendAdditionalQuery(q
, request
, err
);
3020 #endif // APPLE_OSX_mDNSResponder
3025 // ***************************************************************************
3026 #if COMPILER_LIKES_PRAGMA_MARK
3028 #pragma mark - DNSServiceEnumerateDomains
3031 mDNSlocal reply_state
*format_enumeration_reply(request_state
*request
,
3032 const char *domain
, DNSServiceFlags flags
, mDNSu32 ifi
, DNSServiceErrorType err
)
3038 len
= sizeof(DNSServiceFlags
);
3039 len
+= sizeof(mDNSu32
);
3040 len
+= sizeof(DNSServiceErrorType
);
3041 len
+= strlen(domain
) + 1;
3043 reply
= create_reply(enumeration_reply_op
, len
, request
);
3044 reply
->rhdr
->flags
= dnssd_htonl(flags
);
3045 reply
->rhdr
->ifi
= dnssd_htonl(ifi
);
3046 reply
->rhdr
->error
= dnssd_htonl(err
);
3047 data
= (char *)&reply
->rhdr
[1];
3048 put_string(domain
, &data
);
3052 mDNSlocal
void enum_termination_callback(request_state
*request
)
3054 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3055 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3058 mDNSlocal
void enum_result_callback(mDNS
*const m
,
3059 DNSQuestion
*const question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
3061 char domain
[MAX_ESCAPED_DOMAIN_NAME
];
3062 request_state
*request
= question
->QuestionContext
;
3063 DNSServiceFlags flags
= 0;
3067 if (answer
->rrtype
!= kDNSType_PTR
) return;
3070 if (!AuthorizedDomain(request
, &answer
->rdata
->u
.name
, request
->u
.enumeration
.flags
? AutoRegistrationDomains
: AutoBrowseDomains
)) return;
3073 // We only return add/remove events for the browse and registration lists
3074 // For the default browse and registration answers, we only give an "ADD" event
3075 if (question
== &request
->u
.enumeration
.q_default
&& !AddRecord
) return;
3079 flags
|= kDNSServiceFlagsAdd
;
3080 if (question
== &request
->u
.enumeration
.q_default
) flags
|= kDNSServiceFlagsDefault
;
3083 ConvertDomainNameToCString(&answer
->rdata
->u
.name
, domain
);
3084 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3085 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3086 // network, so we just pass kDNSServiceInterfaceIndexAny
3087 reply
= format_enumeration_reply(request
, domain
, flags
, kDNSServiceInterfaceIndexAny
, kDNSServiceErr_NoError
);
3088 if (!reply
) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3090 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request
->sd
, question
->qname
.c
, AddRecord
? "Add" : "Rmv", domain
);
3092 append_reply(request
, reply
);
3095 mDNSlocal mStatus
handle_enum_request(request_state
*request
)
3098 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3099 DNSServiceFlags reg
= flags
& kDNSServiceFlagsRegistrationDomains
;
3100 mDNS_DomainType t_all
= reg
? mDNS_DomainTypeRegistration
: mDNS_DomainTypeBrowse
;
3101 mDNS_DomainType t_default
= reg
? mDNS_DomainTypeRegistrationDefault
: mDNS_DomainTypeBrowseDefault
;
3102 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3103 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3104 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3106 if (!request
->msgptr
)
3107 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3109 // allocate context structures
3110 uDNS_SetupSearchDomains(&mDNSStorage
, UDNS_START_WAB_QUERY
);
3113 // mark which kind of enumeration we're doing so we can (de)authorize certain domains
3114 request
->u
.enumeration
.flags
= reg
;
3117 // enumeration requires multiple questions, so we must link all the context pointers so that
3118 // necessary context can be reached from the callbacks
3119 request
->u
.enumeration
.q_all
.QuestionContext
= request
;
3120 request
->u
.enumeration
.q_default
.QuestionContext
= request
;
3122 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3123 if (!InterfaceID
) InterfaceID
= mDNSInterface_LocalOnly
;
3126 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request
->sd
, flags
,
3127 (flags
& kDNSServiceFlagsBrowseDomains
) ? "kDNSServiceFlagsBrowseDomains" :
3128 (flags
& kDNSServiceFlagsRegistrationDomains
) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3129 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
, t_all
, NULL
, InterfaceID
, enum_result_callback
, request
);
3132 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
, t_default
, NULL
, InterfaceID
, enum_result_callback
, request
);
3133 if (err
) mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3134 else request
->terminate
= enum_termination_callback
;
3140 // ***************************************************************************
3141 #if COMPILER_LIKES_PRAGMA_MARK
3143 #pragma mark - DNSServiceReconfirmRecord & Misc
3146 mDNSlocal mStatus
handle_reconfirm_request(request_state
*request
)
3148 mStatus status
= mStatus_BadParamErr
;
3149 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 0, 0);
3152 status
= mDNS_ReconfirmByValue(&mDNSStorage
, &rr
->resrec
);
3154 (status
== mStatus_NoError
) ?
3155 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
3156 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
3157 request
->sd
, RRDisplayString(&mDNSStorage
, &rr
->resrec
),
3158 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, rr
->resrec
.InterfaceID
, mDNSfalse
), status
);
3159 freeL("AuthRecord/handle_reconfirm_request", rr
);
3164 mDNSlocal mStatus
handle_setdomain_request(request_state
*request
)
3166 char domainstr
[MAX_ESCAPED_DOMAIN_NAME
];
3168 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3169 (void)flags
; // Unused
3170 if (get_string(&request
->msgptr
, request
->msgend
, domainstr
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
3171 !MakeDomainNameFromDNSNameString(&domain
, domainstr
))
3172 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3174 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request
->sd
, domain
.c
);
3175 return(mStatus_NoError
);
3178 typedef packedstruct
3183 } DaemonVersionReply
;
3185 mDNSlocal
void handle_getproperty_request(request_state
*request
)
3187 const mStatus BadParamErr
= dnssd_htonl((mDNSu32
)mStatus_BadParamErr
);
3189 if (get_string(&request
->msgptr
, request
->msgend
, prop
, sizeof(prop
)) >= 0)
3191 LogOperation("%3d: DNSServiceGetProperty(%s)", request
->sd
, prop
);
3192 if (!strcmp(prop
, kDNSServiceProperty_DaemonVersion
))
3194 DaemonVersionReply x
= { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H
) };
3195 send_all(request
->sd
, (const char *)&x
, sizeof(x
));
3200 // If we didn't recogize the requested property name, return BadParamErr
3201 send_all(request
->sd
, (const char *)&BadParamErr
, sizeof(BadParamErr
));
3204 // ***************************************************************************
3205 #if COMPILER_LIKES_PRAGMA_MARK
3207 #pragma mark - DNSServiceNATPortMappingCreate
3210 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
3212 mDNSlocal
void port_mapping_termination_callback(request_state
*request
)
3214 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP", request
->sd
,
3215 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3216 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
);
3217 mDNS_StopNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3220 // Called via function pointer when we get a NAT-PMP address request or port mapping response
3221 mDNSlocal
void port_mapping_create_request_callback(mDNS
*m
, NATTraversalInfo
*n
)
3223 request_state
*request
= (request_state
*)n
->clientContext
;
3228 if (!request
) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
3230 // calculate reply data length
3231 replyLen
= sizeof(DNSServiceFlags
);
3232 replyLen
+= 3 * sizeof(mDNSu32
); // if index + addr + ttl
3233 replyLen
+= sizeof(DNSServiceErrorType
);
3234 replyLen
+= 2 * sizeof(mDNSu16
); // Internal Port + External Port
3235 replyLen
+= sizeof(mDNSu8
); // protocol
3237 rep
= create_reply(port_mapping_reply_op
, replyLen
, request
);
3239 rep
->rhdr
->flags
= dnssd_htonl(0);
3240 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, n
->InterfaceID
, mDNSfalse
));
3241 rep
->rhdr
->error
= dnssd_htonl(n
->Result
);
3243 data
= (char *)&rep
->rhdr
[1];
3245 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[0];
3246 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[1];
3247 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[2];
3248 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[3];
3249 *data
++ = DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
);
3250 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[0];
3251 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[1];
3252 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[0];
3253 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[1];
3254 put_uint32(request
->u
.pm
.NATinfo
.Lifetime
, &data
);
3256 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request
->sd
,
3257 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3258 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
3259 &request
->u
.pm
.NATinfo
.ExternalAddress
, mDNSVal16(request
->u
.pm
.NATinfo
.ExternalPort
), request
->u
.pm
.NATinfo
.Lifetime
);
3261 append_reply(request
, rep
);
3264 mDNSlocal mStatus
handle_port_mapping_request(request_state
*request
)
3267 mStatus err
= mStatus_NoError
;
3269 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3270 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3271 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3272 mDNSu8 protocol
= (mDNSu8
)get_uint32(&request
->msgptr
, request
->msgend
);
3273 (void)flags
; // Unused
3274 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3275 if (request
->msgptr
+ 8 > request
->msgend
) request
->msgptr
= NULL
;
3278 request
->u
.pm
.NATinfo
.IntPort
.b
[0] = *request
->msgptr
++;
3279 request
->u
.pm
.NATinfo
.IntPort
.b
[1] = *request
->msgptr
++;
3280 request
->u
.pm
.ReqExt
.b
[0] = *request
->msgptr
++;
3281 request
->u
.pm
.ReqExt
.b
[1] = *request
->msgptr
++;
3282 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
3285 if (!request
->msgptr
)
3286 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3288 if (protocol
== 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
3290 if (!mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
) || !mDNSIPPortIsZero(request
->u
.pm
.ReqExt
) || ttl
) return(mStatus_BadParamErr
);
3294 if (mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
)) return(mStatus_BadParamErr
);
3295 if (!(protocol
& (kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
))) return(mStatus_BadParamErr
);
3298 request
->u
.pm
.NATinfo
.Protocol
= !protocol
? NATOp_AddrRequest
: (protocol
== kDNSServiceProtocol_UDP
) ? NATOp_MapUDP
: NATOp_MapTCP
;
3299 // u.pm.NATinfo.IntPort = already set above
3300 request
->u
.pm
.NATinfo
.RequestedPort
= request
->u
.pm
.ReqExt
;
3301 request
->u
.pm
.NATinfo
.NATLease
= ttl
;
3302 request
->u
.pm
.NATinfo
.clientCallback
= port_mapping_create_request_callback
;
3303 request
->u
.pm
.NATinfo
.clientContext
= request
;
3305 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START", request
->sd
,
3306 protocol
, mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
);
3307 err
= mDNS_StartNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3308 if (err
) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err
);
3309 else request
->terminate
= port_mapping_termination_callback
;
3314 // ***************************************************************************
3315 #if COMPILER_LIKES_PRAGMA_MARK
3317 #pragma mark - DNSServiceGetAddrInfo
3320 mDNSlocal
void addrinfo_termination_callback(request_state
*request
)
3322 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP", request
->sd
, request
->u
.addrinfo
.q4
.qname
.c
);
3324 if (request
->u
.addrinfo
.q4
.QuestionContext
)
3326 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
3327 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
3329 if (request
->u
.addrinfo
.q4
.qnameOrig
)
3331 freeL("QueryTermination", request
->u
.addrinfo
.q4
.qnameOrig
);
3332 request
->u
.addrinfo
.q4
.qnameOrig
= mDNSNULL
;
3334 if (request
->u
.addrinfo
.q42
)
3336 if (request
->u
.addrinfo
.q42
->QuestionContext
)
3338 LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request
->u
.addrinfo
.q42
->qname
.c
);
3339 mDNS_StopQuery(&mDNSStorage
, request
->u
.addrinfo
.q42
);
3341 if (request
->u
.addrinfo
.q42
->qnameOrig
)
3343 LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request
->u
.addrinfo
.q42
->qnameOrig
->c
);
3344 freeL("QueryTermination q42", request
->u
.addrinfo
.q42
->qnameOrig
);
3345 request
->u
.addrinfo
.q42
->qnameOrig
= mDNSNULL
;
3347 freeL("addrinfo Q42", request
->u
.addrinfo
.q42
);
3348 request
->u
.addrinfo
.q42
= mDNSNULL
;
3351 if (request
->u
.addrinfo
.q6
.QuestionContext
)
3353 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
3354 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
3356 if (request
->u
.addrinfo
.q6
.qnameOrig
)
3358 freeL("QueryTermination", request
->u
.addrinfo
.q6
.qnameOrig
);
3359 request
->u
.addrinfo
.q6
.qnameOrig
= mDNSNULL
;
3361 if (request
->u
.addrinfo
.q62
)
3363 if (request
->u
.addrinfo
.q62
->QuestionContext
)
3365 LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request
->u
.addrinfo
.q62
->qname
.c
);
3366 mDNS_StopQuery(&mDNSStorage
, request
->u
.addrinfo
.q62
);
3368 if (request
->u
.addrinfo
.q62
->qnameOrig
)
3370 LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request
->u
.addrinfo
.q62
->qnameOrig
->c
);
3371 freeL("QueryTermination q62", request
->u
.addrinfo
.q62
->qnameOrig
);
3372 request
->u
.addrinfo
.q62
->qnameOrig
= mDNSNULL
;
3374 freeL("addrinfo Q62", request
->u
.addrinfo
.q62
);
3375 request
->u
.addrinfo
.q62
= mDNSNULL
;
3379 mDNSlocal mStatus
handle_addrinfo_request(request_state
*request
)
3385 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3386 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3388 mDNSPlatformMemZero(&request
->u
.addrinfo
, sizeof(request
->u
.addrinfo
));
3389 request
->u
.addrinfo
.interface_id
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3390 request
->u
.addrinfo
.flags
= flags
;
3391 request
->u
.addrinfo
.protocol
= get_uint32(&request
->msgptr
, request
->msgend
);
3393 if (interfaceIndex
&& !request
->u
.addrinfo
.interface_id
) return(mStatus_BadParamErr
);
3394 if (request
->u
.addrinfo
.protocol
> (kDNSServiceProtocol_IPv4
|kDNSServiceProtocol_IPv6
)) return(mStatus_BadParamErr
);
3396 if (get_string(&request
->msgptr
, request
->msgend
, hostname
, 256) < 0) return(mStatus_BadParamErr
);
3398 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3400 if (!MakeDomainNameFromDNSNameString(&d
, hostname
))
3401 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname
); return(mStatus_BadParamErr
); }
3404 if (!AuthorizedDomain(request
, &d
, AutoBrowseDomains
)) return (mStatus_NoError
);
3407 if (!request
->u
.addrinfo
.protocol
)
3409 flags
|= kDNSServiceFlagsSuppressUnusable
;
3410 request
->u
.addrinfo
.protocol
= (kDNSServiceProtocol_IPv4
| kDNSServiceProtocol_IPv6
);
3413 request
->u
.addrinfo
.q4
.InterfaceID
= request
->u
.addrinfo
.q6
.InterfaceID
= request
->u
.addrinfo
.interface_id
;
3414 request
->u
.addrinfo
.q4
.Target
= request
->u
.addrinfo
.q6
.Target
= zeroAddr
;
3415 request
->u
.addrinfo
.q4
.qname
= request
->u
.addrinfo
.q6
.qname
= d
;
3416 request
->u
.addrinfo
.q4
.qclass
= request
->u
.addrinfo
.q6
.qclass
= kDNSServiceClass_IN
;
3417 request
->u
.addrinfo
.q4
.LongLived
= request
->u
.addrinfo
.q6
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
3418 request
->u
.addrinfo
.q4
.ExpectUnique
= request
->u
.addrinfo
.q6
.ExpectUnique
= mDNSfalse
;
3419 request
->u
.addrinfo
.q4
.ForceMCast
= request
->u
.addrinfo
.q6
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
3420 request
->u
.addrinfo
.q4
.ReturnIntermed
= request
->u
.addrinfo
.q6
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
3421 request
->u
.addrinfo
.q4
.SuppressUnusable
= request
->u
.addrinfo
.q6
.SuppressUnusable
= (flags
& kDNSServiceFlagsSuppressUnusable
) != 0;
3422 request
->u
.addrinfo
.q4
.TimeoutQuestion
= request
->u
.addrinfo
.q6
.TimeoutQuestion
= (flags
& kDNSServiceFlagsTimeout
) != 0;
3423 request
->u
.addrinfo
.q4
.WakeOnResolve
= request
->u
.addrinfo
.q6
.WakeOnResolve
= 0;
3424 request
->u
.addrinfo
.q4
.qnameOrig
= request
->u
.addrinfo
.q6
.qnameOrig
= mDNSNULL
;
3426 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
)
3428 request
->u
.addrinfo
.q4
.qtype
= kDNSServiceType_A
;
3429 request
->u
.addrinfo
.q4
.SearchListIndex
= 0;
3431 // We append search domains only for queries that are a single label. If overriden using
3432 // command line argument "AlwaysAppendSearchDomains", then we do it for any query which
3433 // is not fully qualified.
3434 if (hostname
[strlen(hostname
) - 1] != '.' && (AlwaysAppendSearchDomains
|| CountLabels(&d
) == 1))
3436 request
->u
.addrinfo
.q4
.AppendSearchDomains
= 1;
3437 request
->u
.addrinfo
.q4
.AppendLocalSearchDomains
= 1;
3441 request
->u
.addrinfo
.q4
.AppendSearchDomains
= 0;
3442 request
->u
.addrinfo
.q4
.AppendLocalSearchDomains
= 0;
3444 request
->u
.addrinfo
.q4
.RetryWithSearchDomains
= (ApplySearchDomainsFirst(&request
->u
.addrinfo
.q4
) ? 1 : 0);
3445 request
->u
.addrinfo
.q4
.QuestionCallback
= queryrecord_result_callback
;
3446 request
->u
.addrinfo
.q4
.QuestionContext
= request
;
3447 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
3448 if (err
!= mStatus_NoError
)
3450 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
3451 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
3453 #if APPLE_OSX_mDNSResponder
3454 err
= SendAdditionalQuery(&request
->u
.addrinfo
.q4
, request
, err
);
3455 #endif // APPLE_OSX_mDNSResponder
3458 if (!err
&& (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
))
3460 request
->u
.addrinfo
.q6
.qtype
= kDNSServiceType_AAAA
;
3461 request
->u
.addrinfo
.q6
.SearchListIndex
= 0;
3462 if (hostname
[strlen(hostname
) - 1] != '.' && (AlwaysAppendSearchDomains
|| CountLabels(&d
) == 1))
3464 request
->u
.addrinfo
.q6
.AppendSearchDomains
= 1;
3465 request
->u
.addrinfo
.q6
.AppendLocalSearchDomains
= 1;
3469 request
->u
.addrinfo
.q6
.AppendSearchDomains
= 0;
3470 request
->u
.addrinfo
.q6
.AppendLocalSearchDomains
= 0;
3472 request
->u
.addrinfo
.q6
.RetryWithSearchDomains
= (ApplySearchDomainsFirst(&request
->u
.addrinfo
.q6
) ? 1 : 0);
3473 request
->u
.addrinfo
.q6
.QuestionCallback
= queryrecord_result_callback
;
3474 request
->u
.addrinfo
.q6
.QuestionContext
= request
;
3475 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
3476 if (err
!= mStatus_NoError
)
3478 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
3479 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
3480 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
)
3482 // If we started a query for IPv4, we need to cancel it
3483 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
3484 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
3487 #if APPLE_OSX_mDNSResponder
3488 err
= SendAdditionalQuery(&request
->u
.addrinfo
.q6
, request
, err
);
3489 #endif // APPLE_OSX_mDNSResponder
3492 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START",
3493 request
->sd
, flags
, interfaceIndex
, request
->u
.addrinfo
.protocol
, d
.c
);
3495 if (!err
) request
->terminate
= addrinfo_termination_callback
;
3500 // ***************************************************************************
3501 #if COMPILER_LIKES_PRAGMA_MARK
3503 #pragma mark - Main Request Handler etc.
3506 mDNSlocal request_state
*NewRequest(void)
3508 request_state
**p
= &all_requests
;
3509 while (*p
) p
=&(*p
)->next
;
3510 *p
= mallocL("request_state", sizeof(request_state
));
3511 if (!*p
) FatalError("ERROR: malloc");
3512 mDNSPlatformMemZero(*p
, sizeof(request_state
));
3516 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
3517 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
3518 mDNSlocal
void read_msg(request_state
*req
)
3520 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
3521 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req
->sd
); req
->ts
= t_error
; return; }
3523 if (req
->ts
== t_complete
) // this must be death or something is wrong
3525 char buf
[4]; // dummy for death notification
3526 int nread
= udsSupportReadFD(req
->sd
, buf
, 4, 0, req
->platform_data
);
3527 if (!nread
) { req
->ts
= t_terminated
; return; }
3528 if (nread
< 0) goto rerror
;
3529 LogMsg("%3d: ERROR: read data from a completed request", req
->sd
);
3534 if (req
->ts
!= t_morecoming
)
3535 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req
->sd
, req
->ts
); req
->ts
= t_error
; return; }
3537 if (req
->hdr_bytes
< sizeof(ipc_msg_hdr
))
3539 mDNSu32 nleft
= sizeof(ipc_msg_hdr
) - req
->hdr_bytes
;
3540 int nread
= udsSupportReadFD(req
->sd
, (char *)&req
->hdr
+ req
->hdr_bytes
, nleft
, 0, req
->platform_data
);
3541 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3542 if (nread
< 0) goto rerror
;
3543 req
->hdr_bytes
+= nread
;
3544 if (req
->hdr_bytes
> sizeof(ipc_msg_hdr
))
3545 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req
->sd
); req
->ts
= t_error
; return; }
3547 // only read data if header is complete
3548 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
))
3550 ConvertHeaderBytes(&req
->hdr
);
3551 if (req
->hdr
.version
!= VERSION
)
3552 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req
->sd
, req
->hdr
.version
, VERSION
); req
->ts
= t_error
; return; }
3554 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
3555 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
3556 // for other overhead, this means any message above 70kB is definitely bogus.
3557 if (req
->hdr
.datalen
> 70000)
3558 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req
->sd
, req
->hdr
.datalen
, req
->hdr
.datalen
); req
->ts
= t_error
; return; }
3559 req
->msgbuf
= mallocL("request_state msgbuf", req
->hdr
.datalen
+ MSG_PAD_BYTES
);
3560 if (!req
->msgbuf
) { my_perror("ERROR: malloc"); req
->ts
= t_error
; return; }
3561 req
->msgptr
= req
->msgbuf
;
3562 req
->msgend
= req
->msgbuf
+ req
->hdr
.datalen
;
3563 mDNSPlatformMemZero(req
->msgbuf
, req
->hdr
.datalen
+ MSG_PAD_BYTES
);
3567 // If our header is complete, but we're still needing more body data, then try to read it now
3568 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
3569 // Any time we need to get the error return socket we know we'll have at least one data byte
3570 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
3571 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
< req
->hdr
.datalen
)
3573 mDNSu32 nleft
= req
->hdr
.datalen
- req
->data_bytes
;
3575 #if !defined(_WIN32)
3576 struct iovec vec
= { req
->msgbuf
+ req
->data_bytes
, nleft
}; // Tell recvmsg where we want the bytes put
3578 struct cmsghdr
*cmsg
;
3579 char cbuf
[CMSG_SPACE(sizeof(dnssd_sock_t
))];
3581 msg
.msg_namelen
= 0;
3584 msg
.msg_control
= cbuf
;
3585 msg
.msg_controllen
= sizeof(cbuf
);
3587 nread
= recvmsg(req
->sd
, &msg
, 0);
3589 nread
= udsSupportReadFD(req
->sd
, (char *)req
->msgbuf
+ req
->data_bytes
, nleft
, 0, req
->platform_data
);
3591 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3592 if (nread
< 0) goto rerror
;
3593 req
->data_bytes
+= nread
;
3594 if (req
->data_bytes
> req
->hdr
.datalen
)
3595 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req
->sd
); req
->ts
= t_error
; return; }
3596 #if !defined(_WIN32)
3597 cmsg
= CMSG_FIRSTHDR(&msg
);
3598 #if DEBUG_64BIT_SCM_RIGHTS
3599 LogMsg("%3d: Expecting %d %d %d %d", req
->sd
, sizeof(cbuf
), sizeof(cbuf
), SOL_SOCKET
, SCM_RIGHTS
);
3600 LogMsg("%3d: Got %d %d %d %d", req
->sd
, msg
.msg_controllen
, cmsg
->cmsg_len
, cmsg
->cmsg_level
, cmsg
->cmsg_type
);
3601 #endif // DEBUG_64BIT_SCM_RIGHTS
3602 if (msg
.msg_controllen
== sizeof(cbuf
) &&
3603 cmsg
->cmsg_len
== CMSG_LEN(sizeof(dnssd_sock_t
)) &&
3604 cmsg
->cmsg_level
== SOL_SOCKET
&&
3605 cmsg
->cmsg_type
== SCM_RIGHTS
)
3607 #if APPLE_OSX_mDNSResponder
3608 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3609 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3610 // and it's convenient to repurpose the existing fd-passing code here for that task
3611 if (req
->hdr
.op
== send_bpf
)
3613 dnssd_sock_t x
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3614 LogOperation("%3d: Got BPF %d", req
->sd
, x
);
3615 mDNSPlatformReceiveBPF_fd(&mDNSStorage
, x
);
3618 #endif // APPLE_OSX_mDNSResponder
3619 req
->errsd
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3620 #if DEBUG_64BIT_SCM_RIGHTS
3621 LogMsg("%3d: read req->errsd %d", req
->sd
, req
->errsd
);
3622 #endif // DEBUG_64BIT_SCM_RIGHTS
3623 if (req
->data_bytes
< req
->hdr
.datalen
)
3625 LogMsg("%3d: Client sent error socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3626 req
->sd
, req
->errsd
, req
->data_bytes
, req
->hdr
.datalen
);
3634 // If our header and data are both complete, see if we need to make our separate error return socket
3635 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
== req
->hdr
.datalen
)
3637 if (req
->terminate
&& req
->hdr
.op
!= cancel_request
)
3639 dnssd_sockaddr_t cliaddr
;
3640 #if defined(USE_TCP_LOOPBACK)
3643 port
.b
[0] = req
->msgptr
[0];
3644 port
.b
[1] = req
->msgptr
[1];
3646 cliaddr
.sin_family
= AF_INET
;
3647 cliaddr
.sin_port
= port
.NotAnInteger
;
3648 cliaddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3650 char ctrl_path
[MAX_CTLPATH
];
3651 get_string(&req
->msgptr
, req
->msgend
, ctrl_path
, MAX_CTLPATH
); // path is first element in message buffer
3652 mDNSPlatformMemZero(&cliaddr
, sizeof(cliaddr
));
3653 cliaddr
.sun_family
= AF_LOCAL
;
3654 mDNSPlatformStrCopy(cliaddr
.sun_path
, ctrl_path
);
3655 // If the error return path UDS name is empty string, that tells us
3656 // that this is a new version of the library that's going to pass us
3657 // the error return path socket via sendmsg/recvmsg
3658 if (ctrl_path
[0] == 0)
3660 if (req
->errsd
== req
->sd
)
3661 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req
->sd
); req
->ts
= t_error
; return; }
3666 req
->errsd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3667 if (!dnssd_SocketValid(req
->errsd
)) { my_perror("ERROR: socket"); req
->ts
= t_error
; return; }
3669 if (connect(req
->errsd
, (struct sockaddr
*)&cliaddr
, sizeof(cliaddr
)) < 0)
3671 #if !defined(USE_TCP_LOOPBACK)
3673 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
3674 req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3675 if (stat(cliaddr
.sun_path
, &sb
) < 0)
3676 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3678 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
);
3684 #if !defined(USE_TCP_LOOPBACK)
3687 LogOperation("%3d: Error socket %d created %08X %08X", req
->sd
, req
->errsd
, req
->hdr
.client_context
.u32
[1], req
->hdr
.client_context
.u32
[0]);
3689 if (ioctlsocket(req
->errsd
, FIONBIO
, &opt
) != 0)
3691 if (fcntl(req
->errsd
, F_SETFL
, fcntl(req
->errsd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3694 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
3695 req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3701 req
->ts
= t_complete
;
3707 if (dnssd_errno
== dnssd_EWOULDBLOCK
|| dnssd_errno
== dnssd_EINTR
) return;
3708 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3712 #define RecordOrientedOp(X) \
3713 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3715 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3716 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3718 mDNSlocal
void request_callback(int fd
, short filter
, void *info
)
3721 request_state
*req
= info
;
3722 mDNSs32 min_size
= sizeof(DNSServiceFlags
);
3724 (void)filter
; // Unused
3729 if (req
->ts
== t_morecoming
) return;
3730 if (req
->ts
== t_terminated
|| req
->ts
== t_error
) { AbortUnlinkAndFree(req
); return; }
3731 if (req
->ts
!= t_complete
) { LogMsg("req->ts %d != t_complete", req
->ts
); AbortUnlinkAndFree(req
); return; }
3733 if (req
->hdr
.version
!= VERSION
)
3735 LogMsg("ERROR: client version %d incompatible with daemon version %d", req
->hdr
.version
, VERSION
);
3736 AbortUnlinkAndFree(req
);
3740 switch(req
->hdr
.op
) // Interface + other data
3742 case connection_request
: min_size
= 0; break;
3743 case reg_service_request
: min_size
+= sizeof(mDNSu32
) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3744 case add_record_request
: min_size
+= 4 /* type, rdlen */ + 4 /* ttl */; break;
3745 case update_record_request
: min_size
+= 2 /* rdlen */ + 4 /* ttl */; break;
3746 case remove_record_request
: break;
3747 case browse_request
: min_size
+= sizeof(mDNSu32
) + 2 /* type, domain */; break;
3748 case resolve_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
3749 case query_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 4 /* type, class*/; break;
3750 case enumeration_request
: min_size
+= sizeof(mDNSu32
); break;
3751 case reg_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
3752 case reconfirm_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */; break;
3753 case setdomain_request
: min_size
+= 1 /* domain */; break;
3754 case getproperty_request
: min_size
= 2; break;
3755 case port_mapping_request
: min_size
+= sizeof(mDNSu32
) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
3756 case addrinfo_request
: min_size
+= sizeof(mDNSu32
) + 4 /* v4/v6 */ + 1 /* hostname */; break;
3757 case send_bpf
: // Same as cancel_request below
3758 case cancel_request
: min_size
= 0; break;
3759 default: LogMsg("ERROR: validate_message - unsupported req type: %d", req
->hdr
.op
); min_size
= -1; break;
3762 if ((mDNSs32
)req
->data_bytes
< min_size
)
3763 { LogMsg("Invalid message %d bytes; min for %d is %d", req
->data_bytes
, req
->hdr
.op
, min_size
); AbortUnlinkAndFree(req
); return; }
3765 if (LightweightOp(req
->hdr
.op
) && !req
->terminate
)
3766 { LogMsg("Reg/Add/Update/Remove %d require existing connection", req
->hdr
.op
); AbortUnlinkAndFree(req
); return; }
3768 // check if client wants silent operation
3769 if (req
->hdr
.ipc_flags
& IPC_FLAGS_NOREPLY
) req
->no_reply
= 1;
3771 // If req->terminate is already set, this means this operation is sharing an existing connection
3772 if (req
->terminate
&& !LightweightOp(req
->hdr
.op
))
3774 request_state
*newreq
= NewRequest();
3775 newreq
->primary
= req
;
3776 newreq
->sd
= req
->sd
;
3777 newreq
->errsd
= req
->errsd
;
3778 newreq
->uid
= req
->uid
;
3779 newreq
->hdr
= req
->hdr
;
3780 newreq
->msgbuf
= req
->msgbuf
;
3781 newreq
->msgptr
= req
->msgptr
;
3782 newreq
->msgend
= req
->msgend
;
3786 // If we're shutting down, don't allow new client requests
3787 // We do allow "cancel" and "getproperty" during shutdown
3788 if (mDNSStorage
.ShutdownTime
&& req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
)
3790 err
= mStatus_ServiceNotRunning
;
3792 else switch(req
->hdr
.op
)
3794 // These are all operations that have their own first-class request_state object
3795 case connection_request
: LogOperation("%3d: DNSServiceCreateConnection START", req
->sd
);
3796 req
->terminate
= connection_termination
; break;
3797 case resolve_request
: err
= handle_resolve_request (req
); break;
3798 case query_request
: err
= handle_queryrecord_request (req
); break;
3799 case browse_request
: err
= handle_browse_request (req
); break;
3800 case reg_service_request
: err
= handle_regservice_request (req
); break;
3801 case enumeration_request
: err
= handle_enum_request (req
); break;
3802 case reconfirm_record_request
: err
= handle_reconfirm_request (req
); break;
3803 case setdomain_request
: err
= handle_setdomain_request (req
); break;
3804 case getproperty_request
: handle_getproperty_request (req
); break;
3805 case port_mapping_request
: err
= handle_port_mapping_request(req
); break;
3806 case addrinfo_request
: err
= handle_addrinfo_request (req
); break;
3807 case send_bpf
: /* Do nothing for send_bpf */ break;
3809 // These are all operations that work with an existing request_state object
3810 case reg_record_request
: err
= handle_regrecord_request (req
); break;
3811 case add_record_request
: err
= handle_add_request (req
); break;
3812 case update_record_request
: err
= handle_update_request (req
); break;
3813 case remove_record_request
: err
= handle_removerecord_request(req
); break;
3814 case cancel_request
: handle_cancel_request (req
); break;
3815 default: LogMsg("%3d: ERROR: Unsupported UDS req: %d", req
->sd
, req
->hdr
.op
);
3818 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3819 if (req
->msgbuf
) freeL("request_state msgbuf", req
->msgbuf
);
3821 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3822 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3823 if (req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
&& req
->hdr
.op
!= send_bpf
)
3825 const mStatus err_netorder
= dnssd_htonl(err
);
3826 send_all(req
->errsd
, (const char *)&err_netorder
, sizeof(err_netorder
));
3827 if (req
->errsd
!= req
->sd
)
3829 LogOperation("%3d: Error socket %d closed %08X %08X (%d)",
3830 req
->sd
, req
->errsd
, req
->hdr
.client_context
.u32
[1], req
->hdr
.client_context
.u32
[0], err
);
3831 dnssd_close(req
->errsd
);
3832 req
->errsd
= req
->sd
;
3833 // Also need to reset the parent's errsd, if this is a subordinate operation
3834 if (req
->primary
) req
->primary
->errsd
= req
->primary
->sd
;
3838 // Reset ready to accept the next req on this pipe
3839 if (req
->primary
) req
= req
->primary
;
3840 req
->ts
= t_morecoming
;
3842 req
->data_bytes
= 0;
3843 req
->msgbuf
= mDNSNULL
;
3844 req
->msgptr
= mDNSNULL
;
3849 mDNSlocal
void connect_callback(int fd
, short filter
, void *info
)
3851 dnssd_sockaddr_t cliaddr
;
3852 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(cliaddr
);
3853 dnssd_sock_t sd
= accept(fd
, (struct sockaddr
*) &cliaddr
, &len
);
3854 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3855 unsigned long optval
= 1;
3858 (void)filter
; // Unused
3859 (void)info
; // Unused
3861 if (!dnssd_SocketValid(sd
))
3863 if (dnssd_errno
!= dnssd_EWOULDBLOCK
) my_perror("ERROR: accept");
3868 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3869 if (setsockopt(sd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
3870 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3874 if (ioctlsocket(sd
, FIONBIO
, &optval
) != 0)
3876 if (fcntl(sd
, F_SETFL
, fcntl(sd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3879 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3885 request_state
*request
= NewRequest();
3886 request
->ts
= t_morecoming
;
3888 request
->errsd
= sd
;
3889 #if APPLE_OSX_mDNSResponder
3891 socklen_t xucredlen
= sizeof(x
);
3892 if (getsockopt(sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 && x
.cr_version
== XUCRED_VERSION
) request
->uid
= x
.cr_uid
;
3893 else my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
3894 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen
, x
.cr_version
, x
.cr_uid
, x
.cr_ngroups
);
3895 #endif // APPLE_OSX_mDNSResponder
3896 LogOperation("%3d: Adding FD for uid %u", request
->sd
, request
->uid
);
3897 udsSupportAddFDToEventLoop(sd
, request_callback
, request
, &request
->platform_data
);
3901 mDNSlocal mDNSBool
uds_socket_setup(dnssd_sock_t skt
)
3903 #if defined(SO_NP_EXTENSIONS)
3904 struct so_np_extensions sonpx
;
3905 socklen_t optlen
= sizeof(struct so_np_extensions
);
3906 sonpx
.npx_flags
= SONPX_SETOPTSHUT
;
3907 sonpx
.npx_mask
= SONPX_SETOPTSHUT
;
3908 if (setsockopt(skt
, SOL_SOCKET
, SO_NP_EXTENSIONS
, &sonpx
, optlen
) < 0)
3909 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
3912 // SEH: do we even need to do this on windows?
3913 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
3915 if (ioctlsocket(skt
, FIONBIO
, &opt
) != 0)
3917 if (fcntl(skt
, F_SETFL
, fcntl(skt
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3920 my_perror("ERROR: could not set listen socket to non-blocking mode");
3924 if (listen(skt
, LISTENQ
) != 0)
3926 my_perror("ERROR: could not listen on listen socket");
3930 if (mStatus_NoError
!= udsSupportAddFDToEventLoop(skt
, connect_callback
, (void *) NULL
, (void **) NULL
))
3932 my_perror("ERROR: could not add listen socket to event loop");
3935 else LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt
);
3940 mDNSexport
int udsserver_init(dnssd_sock_t skts
[], mDNSu32 count
)
3942 dnssd_sockaddr_t laddr
;
3946 LogInfo("udsserver_init");
3948 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
3951 FILE *fp
= fopen(PID_FILE
, "w");
3954 fprintf(fp
, "%d\n", getpid());
3961 for (i
= 0; i
< count
; i
++)
3962 if (dnssd_SocketValid(skts
[i
]) && !uds_socket_setup(skts
[i
]))
3967 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3968 if (!dnssd_SocketValid(listenfd
))
3970 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
3974 mDNSPlatformMemZero(&laddr
, sizeof(laddr
));
3976 #if defined(USE_TCP_LOOPBACK)
3978 laddr
.sin_family
= AF_INET
;
3979 laddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
3980 laddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3981 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
3984 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
3990 mode_t mask
= umask(0);
3991 unlink(MDNS_UDS_SERVERPATH
); // OK if this fails
3992 laddr
.sun_family
= AF_LOCAL
;
3993 #ifndef NOT_HAVE_SA_LEN
3994 // According to Stevens (section 3.2), there is no portable way to
3995 // determine whether sa_len is defined on a particular platform.
3996 laddr
.sun_len
= sizeof(struct sockaddr_un
);
3998 mDNSPlatformStrCopy(laddr
.sun_path
, MDNS_UDS_SERVERPATH
);
3999 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
4003 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4009 if (!uds_socket_setup(listenfd
)) goto error
;
4012 #if !defined(PLATFORM_NO_RLIMIT)
4014 // Set maximum number of open file descriptors
4015 #define MIN_OPENFILES 10240
4016 struct rlimit maxfds
, newfds
;
4018 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
4019 // you have to get and set rlimits once before getrlimit will return sensible values
4020 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4021 if (setrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4023 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4024 newfds
.rlim_max
= (maxfds
.rlim_max
> MIN_OPENFILES
) ? maxfds
.rlim_max
: MIN_OPENFILES
;
4025 newfds
.rlim_cur
= (maxfds
.rlim_cur
> MIN_OPENFILES
) ? maxfds
.rlim_cur
: MIN_OPENFILES
;
4026 if (newfds
.rlim_max
!= maxfds
.rlim_max
|| newfds
.rlim_cur
!= maxfds
.rlim_cur
)
4027 if (setrlimit(RLIMIT_NOFILE
, &newfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4029 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4030 debugf("maxfds.rlim_max %d", (long)maxfds
.rlim_max
);
4031 debugf("maxfds.rlim_cur %d", (long)maxfds
.rlim_cur
);
4035 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
4036 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
4037 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
4038 mDNS_GetDomains(&mDNSStorage
, &mDNSStorage
.AutomaticBrowseDomainQ
, mDNS_DomainTypeBrowseAutomatic
,
4039 mDNSNULL
, mDNSInterface_LocalOnly
, AutomaticBrowseDomainChange
, mDNSNULL
);
4041 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
4042 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeRegistration
);
4043 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeBrowse
);
4044 AddAutoBrowseDomain(0, &localdomain
);
4046 udsserver_handle_configchange(&mDNSStorage
);
4051 my_perror("ERROR: udsserver_init");
4055 mDNSexport
int udsserver_exit(void)
4057 // Cancel all outstanding client requests
4058 while (all_requests
) AbortUnlinkAndFree(all_requests
);
4060 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
4061 // created in udsserver_init, and others we created as a result of reading local configuration data
4062 while (LocalDomainEnumRecords
)
4064 ARListElem
*rem
= LocalDomainEnumRecords
;
4065 LocalDomainEnumRecords
= LocalDomainEnumRecords
->next
;
4066 mDNS_Deregister(&mDNSStorage
, &rem
->ar
);
4069 // If the launching environment created no listening socket,
4070 // that means we created it ourselves, so we should clean it up on exit
4071 if (dnssd_SocketValid(listenfd
))
4073 dnssd_close(listenfd
);
4074 #if !defined(USE_TCP_LOOPBACK)
4075 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
4076 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
4077 // It would be nice if we could find a solution to this problem
4078 if (unlink(MDNS_UDS_SERVERPATH
))
4079 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH
);
4083 if (PID_FILE
[0]) unlink(PID_FILE
);
4088 mDNSlocal
void LogClientInfo(mDNS
*const m
, const request_state
*req
)
4091 if (req
->primary
) mDNS_snprintf(prefix
, sizeof(prefix
), " -> ");
4092 else mDNS_snprintf(prefix
, sizeof(prefix
), "%3d:", req
->sd
);
4094 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4096 if (!req
->terminate
)
4097 LogMsgNoIdent("%s No operation yet on this socket", prefix
);
4098 else if (req
->terminate
== connection_termination
)
4100 int num_records
= 0, num_ops
= 0;
4101 const registered_record_entry
*p
;
4102 const request_state
*r
;
4103 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
) num_records
++;
4104 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) num_ops
++;
4105 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s", prefix
,
4106 num_records
, num_records
!= 1 ? "s" : "",
4107 num_ops
, num_ops
!= 1 ? "s" : "");
4108 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4109 LogMsgNoIdent(" -> DNSServiceRegisterRecord %3d %s", p
->key
, ARDisplayString(m
, p
->rr
));
4110 for (r
= req
->next
; r
; r
=r
->next
) if (r
->primary
== req
) LogClientInfo(m
, r
);
4112 else if (req
->terminate
== regservice_termination_callback
)
4114 service_instance
*ptr
;
4115 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4116 LogMsgNoIdent("%s DNSServiceRegister %##s %u/%u",
4117 (ptr
== req
->u
.servicereg
.instances
) ? prefix
: " ",
4118 ptr
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(req
->u
.servicereg
.port
), SRS_PORT(&ptr
->srs
));
4120 else if (req
->terminate
== browse_termination_callback
)
4123 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4124 LogMsgNoIdent("%s DNSServiceBrowse %##s", (blist
== req
->u
.browser
.browsers
) ? prefix
: " ", blist
->q
.qname
.c
);
4126 else if (req
->terminate
== resolve_termination_callback
)
4127 LogMsgNoIdent("%s DNSServiceResolve %##s", prefix
, req
->u
.resolve
.qsrv
.qname
.c
);
4128 else if (req
->terminate
== queryrecord_termination_callback
)
4129 LogMsgNoIdent("%s DNSServiceQueryRecord %##s (%s)", prefix
, req
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(req
->u
.queryrecord
.q
.qtype
));
4130 else if (req
->terminate
== enum_termination_callback
)
4131 LogMsgNoIdent("%s DNSServiceEnumerateDomains %##s", prefix
, req
->u
.enumeration
.q_all
.qname
.c
);
4132 else if (req
->terminate
== port_mapping_termination_callback
)
4133 LogMsgNoIdent("%s DNSServiceNATPortMapping %.4a %s%s Int %d Req %d Ext %d Req TTL %d Granted TTL %d",
4135 &req
->u
.pm
.NATinfo
.ExternalAddress
,
4136 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
4137 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
4138 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
4139 mDNSVal16(req
->u
.pm
.ReqExt
),
4140 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
4141 req
->u
.pm
.NATinfo
.NATLease
,
4142 req
->u
.pm
.NATinfo
.Lifetime
);
4143 else if (req
->terminate
== addrinfo_termination_callback
)
4144 LogMsgNoIdent("%s DNSServiceGetAddrInfo %s%s %##s", prefix
,
4145 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4146 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4147 req
->u
.addrinfo
.q4
.qname
.c
);
4149 LogMsgNoIdent("%s Unrecognized operation %p", prefix
, req
->terminate
);
4152 mDNSlocal
char *RecordTypeName(mDNSu8 rtype
)
4156 case kDNSRecordTypeUnregistered
: return ("Unregistered ");
4157 case kDNSRecordTypeDeregistering
: return ("Deregistering");
4158 case kDNSRecordTypeUnique
: return ("Unique ");
4159 case kDNSRecordTypeAdvisory
: return ("Advisory ");
4160 case kDNSRecordTypeShared
: return ("Shared ");
4161 case kDNSRecordTypeVerified
: return ("Verified ");
4162 case kDNSRecordTypeKnownUnique
: return ("KnownUnique ");
4163 default: return("Unknown");
4167 mDNSlocal
void LogEtcHosts(mDNS
*const m
)
4169 mDNSBool showheader
= mDNStrue
;
4170 const AuthRecord
*ar
;
4175 mDNSBool truncated
= 0;
4177 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4179 if (m
->rrauth
.rrauth_hash
[slot
]) authslot
++;
4180 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4181 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
4183 if (ar
->RecordCallback
!= FreeEtcHosts
) continue;
4184 if (showheader
) { showheader
= mDNSfalse
; LogMsgNoIdent(" State Interface"); }
4186 // Print a maximum of 50 records
4187 if (count
++ >= 50) { truncated
= mDNStrue
; continue; }
4188 if (ar
->ARType
== AuthRecordLocalOnly
)
4190 if (ar
->resrec
.InterfaceID
== mDNSInterface_LocalOnly
)
4191 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4194 mDNSu32 scopeid
= (mDNSu32
)(uintptr_t)ar
->resrec
.InterfaceID
;
4195 LogMsgNoIdent(" %s %u %s", RecordTypeName(ar
->resrec
.RecordType
), scopeid
, ARDisplayString(m
, ar
));
4198 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4202 if (showheader
) LogMsgNoIdent("<None>");
4203 else if (truncated
) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count
, m
->rrauth
.rrauth_totalused
, authslot
);
4206 mDNSlocal
void LogLocalOnlyAuthRecords(mDNS
*const m
)
4208 mDNSBool showheader
= mDNStrue
;
4209 const AuthRecord
*ar
;
4213 for (slot
= 0; slot
< AUTH_HASH_SLOTS
; slot
++)
4215 for (ag
= m
->rrauth
.rrauth_hash
[slot
]; ag
; ag
= ag
->next
)
4216 for (ar
= ag
->members
; ar
; ar
= ar
->next
)
4218 if (ar
->RecordCallback
== FreeEtcHosts
) continue;
4219 if (showheader
) { showheader
= mDNSfalse
; LogMsgNoIdent(" State Interface"); }
4221 // Print a maximum of 400 records
4222 if (ar
->ARType
== AuthRecordLocalOnly
)
4223 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4224 else if (ar
->ARType
== AuthRecordP2P
)
4225 LogMsgNoIdent(" %s PP %s", RecordTypeName(ar
->resrec
.RecordType
), ARDisplayString(m
, ar
));
4226 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4230 if (showheader
) LogMsgNoIdent("<None>");
4233 mDNSlocal
void LogAuthRecords(mDNS
*const m
, const mDNSs32 now
, AuthRecord
*ResourceRecords
, int *proxy
)
4235 mDNSBool showheader
= mDNStrue
;
4236 const AuthRecord
*ar
;
4237 OwnerOptData owner
= zeroOwner
;
4238 for (ar
= ResourceRecords
; ar
; ar
=ar
->next
)
4240 const char *const ifname
= InterfaceNameForID(m
, ar
->resrec
.InterfaceID
);
4241 if ((ar
->WakeUp
.HMAC
.l
[0] != 0) == (proxy
!= mDNSNULL
))
4243 if (showheader
) { showheader
= mDNSfalse
; LogMsgNoIdent(" Int Next Expire State"); }
4244 if (proxy
) (*proxy
)++;
4245 if (!mDNSPlatformMemSame(&owner
, &ar
->WakeUp
, sizeof(owner
)))
4248 if (owner
.password
.l
[0])
4249 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, &owner
.password
, owner
.seq
);
4250 else if (!mDNSSameEthAddress(&owner
.HMAC
, &owner
.IMAC
))
4251 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner
.HMAC
, &owner
.IMAC
, owner
.seq
);
4253 LogMsgNoIdent("Proxying for %.6a seq %d", &owner
.HMAC
, owner
.seq
);
4255 if (AuthRecord_uDNS(ar
))
4256 LogMsgNoIdent("%7d %7d %7d %7d %s",
4257 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4258 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
4259 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
4260 ar
->state
, ARDisplayString(m
, ar
));
4261 else if (ar
->ARType
== AuthRecordLocalOnly
)
4262 LogMsgNoIdent(" LO %s", ARDisplayString(m
, ar
));
4263 else if (ar
->ARType
== AuthRecordP2P
)
4264 LogMsgNoIdent(" PP %s", ARDisplayString(m
, ar
));
4266 LogMsgNoIdent("%7d %7d %7d %7s %s",
4267 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4268 ar
->AnnounceCount
? (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
: 0,
4269 ar
->TimeExpire
? (ar
->TimeExpire
- now
) / mDNSPlatformOneSecond
: 0,
4270 ifname
? ifname
: "ALL",
4271 ARDisplayString(m
, ar
));
4272 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4275 if (showheader
) LogMsgNoIdent("<None>");
4278 mDNSexport
void udsserver_info(mDNS
*const m
)
4280 const mDNSs32 now
= mDNS_TimeNow(m
);
4281 mDNSu32 CacheUsed
= 0, CacheActive
= 0, slot
;
4282 int ProxyA
= 0, ProxyD
= 0;
4283 const CacheGroup
*cg
;
4284 const CacheRecord
*cr
;
4285 const DNSQuestion
*q
;
4286 const DNameListElem
*d
;
4287 const SearchListElem
*s
;
4289 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
4291 LogMsgNoIdent("------------ Cache -------------");
4292 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
4293 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4294 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
4296 CacheUsed
++; // Count one cache entity for the CacheGroup object
4297 for (cr
= cg
->members
; cr
; cr
=cr
->next
)
4299 const mDNSs32 remain
= cr
->resrec
.rroriginalttl
- (now
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
4301 mDNSInterfaceID InterfaceID
= cr
->resrec
.InterfaceID
;
4302 if (!InterfaceID
&& cr
->resrec
.rDNSServer
)
4303 InterfaceID
= cr
->resrec
.rDNSServer
->interface
;
4304 ifname
= InterfaceNameForID(m
, InterfaceID
);
4306 if (cr
->CRActiveQuestion
) CacheActive
++;
4307 LogMsgNoIdent("%3d %s%8ld %-7s%s %-6s%s",
4309 cr
->CRActiveQuestion
? "*" : " ",
4311 ifname
? ifname
: "-U-",
4312 (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) ? "-" :
4313 (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ? " " : "+",
4314 DNSTypeName(cr
->resrec
.rrtype
),
4315 CRDisplayString(m
, cr
));
4316 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4320 if (m
->rrcache_totalused
!= CacheUsed
)
4321 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m
->rrcache_totalused
, CacheUsed
);
4322 if (m
->rrcache_active
!= CacheActive
)
4323 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m
->rrcache_active
, CacheActive
);
4324 LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed
, CacheActive
);
4326 LogMsgNoIdent("--------- Auth Records ---------");
4327 LogAuthRecords(m
, now
, m
->ResourceRecords
, mDNSNULL
);
4329 LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
4330 LogLocalOnlyAuthRecords(m
);
4332 LogMsgNoIdent("--------- /etc/hosts ---------");
4335 LogMsgNoIdent("------ Duplicate Records -------");
4336 LogAuthRecords(m
, now
, m
->DuplicateRecords
, mDNSNULL
);
4338 LogMsgNoIdent("----- Auth Records Proxied -----");
4339 LogAuthRecords(m
, now
, m
->ResourceRecords
, &ProxyA
);
4341 LogMsgNoIdent("-- Duplicate Records Proxied ---");
4342 LogAuthRecords(m
, now
, m
->DuplicateRecords
, &ProxyD
);
4344 LogMsgNoIdent("---------- Questions -----------");
4345 if (!m
->Questions
) LogMsgNoIdent("<None>");
4350 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
4351 for (q
= m
->Questions
; q
; q
=q
->next
)
4353 mDNSs32 i
= q
->ThisQInterval
/ mDNSPlatformOneSecond
;
4354 mDNSs32 n
= (NextQSendTime(q
) - now
) / mDNSPlatformOneSecond
;
4355 char *ifname
= InterfaceNameForID(m
, q
->InterfaceID
);
4357 if (q
->ThisQInterval
) CacheActive
++;
4358 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s",
4360 ifname
? ifname
: mDNSOpaque16IsZero(q
->TargetQID
) ? "" : "-U-",
4361 mDNSOpaque16IsZero(q
->TargetQID
) ? (q
->LongLived
? "l" : " ") : (q
->LongLived
? "L" : "O"),
4362 PrivateQuery(q
) ? "P" : " ",
4363 q
->CurrentAnswers
, q
->validDNSServers
.l
[1], q
->validDNSServers
.l
[0], q
, q
->DuplicateOf
,
4364 q
->SuppressUnusable
, q
->SuppressQuery
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
4365 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4367 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed
, CacheUsed
> 1 ? "s" : "", CacheActive
);
4370 LogMsgNoIdent("----- Local-Only Questions -----");
4371 if (!m
->LocalOnlyQuestions
) LogMsgNoIdent("<None>");
4372 else for (q
= m
->LocalOnlyQuestions
; q
; q
=q
->next
)
4373 LogMsgNoIdent(" %5d %-6s%##s%s",
4374 q
->CurrentAnswers
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
4376 LogMsgNoIdent("---- Active Client Requests ----");
4377 if (!all_requests
) LogMsgNoIdent("<None>");
4380 const request_state
*req
, *r
;
4381 for (req
= all_requests
; req
; req
=req
->next
)
4383 if (req
->primary
) // If this is a subbordinate operation, check that the parent is in the list
4385 for (r
= all_requests
; r
&& r
!= req
; r
=r
->next
) if (r
== req
->primary
) goto foundparent
;
4386 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req
->sd
);
4388 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
4389 LogClientInfo(m
, req
);
4394 LogMsgNoIdent("-------- NAT Traversals --------");
4395 if (!m
->NATTraversals
) LogMsgNoIdent("<None>");
4398 const NATTraversalInfo
*nat
;
4399 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
4402 LogMsgNoIdent("%p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d",
4403 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
4404 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
4405 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
4406 nat
->retryInterval
/ mDNSPlatformOneSecond
,
4407 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0);
4409 LogMsgNoIdent("%p Address Request Retry %5d Interval %5d", nat
,
4410 (m
->retryGetAddr
- now
) / mDNSPlatformOneSecond
,
4411 m
->retryIntervalGetAddr
/ mDNSPlatformOneSecond
);
4412 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4416 LogMsgNoIdent("--------- AuthInfoList ---------");
4417 if (!m
->AuthInfoList
) LogMsgNoIdent("<None>");
4420 const DomainAuthInfo
*a
;
4421 for (a
= m
->AuthInfoList
; a
; a
= a
->next
)
4422 LogMsgNoIdent("%##s %##s %##s %d %s", a
->domain
.c
, a
->keyname
.c
, a
->hostname
.c
, (a
->port
.b
[0] << 8 | a
->port
.b
[1]), a
->AutoTunnel
? a
->AutoTunnel
: "");
4425 #if APPLE_OSX_mDNSResponder
4426 LogMsgNoIdent("--------- TunnelClients --------");
4427 if (!m
->TunnelClients
) LogMsgNoIdent("<None>");
4430 const ClientTunnel
*c
;
4431 for (c
= m
->TunnelClients
; c
; c
= c
->next
)
4432 LogMsgNoIdent("%s %##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
4433 c
->prefix
, 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
);
4435 #endif // APPLE_OSX_mDNSResponder
4437 LogMsgNoIdent("---------- Misc State ----------");
4439 LogMsgNoIdent("PrimaryMAC: %.6a", &m
->PrimaryMAC
);
4441 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
4443 m
->SleepState
== SleepState_Awake
? "Awake" :
4444 m
->SleepState
== SleepState_Transferring
? "Transferring" :
4445 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?",
4448 if (!m
->SPSSocket
) LogMsgNoIdent("Not offering Sleep Proxy Service");
4449 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m
->SPSRecords
.RR_SRV
.resrec
.name
->c
);
4451 if (m
->ProxyRecords
== ProxyA
+ ProxyD
) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
);
4452 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
, m
->ProxyRecords
);
4454 LogMsgNoIdent("------ Auto Browse Domains -----");
4455 if (!AutoBrowseDomains
) LogMsgNoIdent("<None>");
4456 else for (d
=AutoBrowseDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
4458 LogMsgNoIdent("--- Auto Registration Domains --");
4459 if (!AutoRegistrationDomains
) LogMsgNoIdent("<None>");
4460 else for (d
=AutoRegistrationDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
4462 LogMsgNoIdent("--- Search Domains --");
4463 if (!SearchList
) LogMsgNoIdent("<None>");
4466 for (s
=SearchList
; s
; s
=s
->next
)
4468 char *ifname
= InterfaceNameForID(m
, s
->InterfaceID
);
4469 LogMsgNoIdent("%##s %s", s
->domain
.c
, ifname
? ifname
: "");
4473 LogMsgNoIdent("---- Task Scheduling Timers ----");
4475 if (!m
->NewQuestions
)
4476 LogMsgNoIdent("NewQuestion <NONE>");
4478 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
4479 m
->NewQuestions
->DelayAnswering
, m
->NewQuestions
->DelayAnswering
-now
,
4480 m
->NewQuestions
->qname
.c
, DNSTypeName(m
->NewQuestions
->qtype
));
4482 if (!m
->NewLocalOnlyQuestions
)
4483 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
4485 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
4486 m
->NewLocalOnlyQuestions
->qname
.c
, DNSTypeName(m
->NewLocalOnlyQuestions
->qtype
));
4488 if (!m
->NewLocalRecords
)
4489 LogMsgNoIdent("NewLocalRecords <NONE>");
4491 LogMsgNoIdent("NewLocalRecords %02X %s", m
->NewLocalRecords
->resrec
.RecordType
, ARDisplayString(m
, m
->NewLocalRecords
));
4493 LogMsgNoIdent("SPSProxyListChanged%s", m
->SPSProxyListChanged
? "" : " <NONE>");
4494 LogMsgNoIdent("LocalRemoveEvents%s", m
->LocalRemoveEvents
? "" : " <NONE>");
4495 LogMsgNoIdent("m->RegisterAutoTunnel6 %08X", m
->RegisterAutoTunnel6
);
4496 LogMsgNoIdent("m->AutoTunnelRelayAddrIn %.16a", &m
->AutoTunnelRelayAddrIn
);
4497 LogMsgNoIdent("m->AutoTunnelRelayAddrOut %.16a", &m
->AutoTunnelRelayAddrOut
);
4499 #define LogTimer(MSG,T) LogMsgNoIdent( MSG " %08X %11d %08X %11d", (T), (T), (T)-now, (T)-now)
4501 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
4502 LogMsgNoIdent("m->timenow %08X %11d", now
, now
);
4503 LogMsgNoIdent("m->timenow_adjust %08X %11d", m
->timenow_adjust
, m
->timenow_adjust
);
4504 LogTimer("m->NextScheduledEvent ", m
->NextScheduledEvent
);
4506 #ifndef UNICAST_DISABLED
4507 LogTimer("m->NextuDNSEvent ", m
->NextuDNSEvent
);
4508 LogTimer("m->NextSRVUpdate ", m
->NextSRVUpdate
);
4509 LogTimer("m->NextScheduledNATOp ", m
->NextScheduledNATOp
);
4510 LogTimer("m->retryGetAddr ", m
->retryGetAddr
);
4513 LogTimer("m->NextCacheCheck ", m
->NextCacheCheck
);
4514 LogTimer("m->NextScheduledSPS ", m
->NextScheduledSPS
);
4515 LogTimer("m->NextScheduledSPRetry ", m
->NextScheduledSPRetry
);
4516 LogTimer("m->DelaySleep ", m
->DelaySleep
);
4518 LogTimer("m->NextScheduledQuery ", m
->NextScheduledQuery
);
4519 LogTimer("m->NextScheduledProbe ", m
->NextScheduledProbe
);
4520 LogTimer("m->NextScheduledResponse", m
->NextScheduledResponse
);
4522 LogTimer("m->SuppressSending ", m
->SuppressSending
);
4523 LogTimer("m->SuppressProbes ", m
->SuppressProbes
);
4524 LogTimer("m->ProbeFailTime ", m
->ProbeFailTime
);
4525 LogTimer("m->DelaySleep ", m
->DelaySleep
);
4526 LogTimer("m->SleepLimit ", m
->SleepLimit
);
4527 LogTimer("m->NextScheduledStopTime ", m
->NextScheduledStopTime
);
4530 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4531 mDNSexport
void uds_validatelists(void)
4533 const request_state
*req
, *p
;
4534 for (req
= all_requests
; req
; req
=req
->next
)
4536 if (req
->next
== (request_state
*)~0 || (req
->sd
< 0 && req
->sd
!= -2))
4537 LogMemCorruption("UDS request list: %p is garbage (%d)", req
, req
->sd
);
4539 if (req
->primary
== req
)
4540 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req
, req
->sd
);
4542 if (req
->primary
&& req
->replies
)
4543 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
4544 req
, req
->sd
, req
->primary
&& req
->replies
);
4548 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req
, p
, req
->sd
);
4549 else if (p
&& (p
->next
== (request_state
*)~0 || (p
->sd
< 0 && p
->sd
!= -2)))
4550 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req
, p
, p
->sd
);
4553 for (rep
= req
->replies
; rep
; rep
=rep
->next
)
4554 if (rep
->next
== (reply_state
*)~0)
4555 LogMemCorruption("UDS req->replies: %p is garbage", rep
);
4557 if (req
->terminate
== connection_termination
)
4559 registered_record_entry
*r
;
4560 for (r
= req
->u
.reg_recs
; r
; r
=r
->next
)
4561 if (r
->next
== (registered_record_entry
*)~0)
4562 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r
);
4564 else if (req
->terminate
== regservice_termination_callback
)
4566 service_instance
*s
;
4567 for (s
= req
->u
.servicereg
.instances
; s
; s
=s
->next
)
4568 if (s
->next
== (service_instance
*)~0)
4569 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s
);
4571 else if (req
->terminate
== browse_termination_callback
)
4574 for (b
= req
->u
.browser
.browsers
; b
; b
=b
->next
)
4575 if (b
->next
== (browser_t
*)~0)
4576 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b
);
4581 for (d
= SCPrefBrowseDomains
; d
; d
=d
->next
)
4582 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
4583 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
4586 for (b
= LocalDomainEnumRecords
; b
; b
=b
->next
)
4587 if (b
->next
== (ARListElem
*)~0 || b
->ar
.resrec
.name
->c
[0] > 63)
4588 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b
, b
->ar
.resrec
.name
->c
[0]);
4590 for (d
= AutoBrowseDomains
; d
; d
=d
->next
)
4591 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
4592 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
4594 for (d
= AutoRegistrationDomains
; d
; d
=d
->next
)
4595 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
4596 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
4598 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4600 mDNSlocal
int send_msg(request_state
*const req
)
4602 reply_state
*const rep
= req
->replies
; // Send the first waiting reply
4604 if (req
->no_reply
) return(t_complete
);
4606 ConvertHeaderBytes(rep
->mhdr
);
4607 nwriten
= send(req
->sd
, (char *)&rep
->mhdr
+ rep
->nwriten
, rep
->totallen
- rep
->nwriten
, 0);
4608 ConvertHeaderBytes(rep
->mhdr
);
4612 if (dnssd_errno
== dnssd_EINTR
|| dnssd_errno
== dnssd_EWOULDBLOCK
) nwriten
= 0;
4615 #if !defined(PLATFORM_NO_EPIPE)
4616 if (dnssd_errno
== EPIPE
)
4617 return(req
->ts
= t_terminated
);
4621 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
4622 rep
->totallen
- rep
->nwriten
, rep
->totallen
, req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
4627 rep
->nwriten
+= nwriten
;
4628 return (rep
->nwriten
== rep
->totallen
) ? t_complete
: t_morecoming
;
4631 mDNSexport mDNSs32
udsserver_idle(mDNSs32 nextevent
)
4633 mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
4634 request_state
**req
= &all_requests
;
4638 request_state
*const r
= *req
;
4640 if (r
->terminate
== resolve_termination_callback
)
4641 if (r
->u
.resolve
.ReportTime
&& now
- r
->u
.resolve
.ReportTime
>= 0)
4643 r
->u
.resolve
.ReportTime
= 0;
4644 LogMsgNoIdent("Client application bug: DNSServiceResolve(%##s) active for over two minutes. "
4645 "This places considerable burden on the network.", r
->u
.resolve
.qsrv
.qname
.c
);
4648 // Note: Only primary req's have reply lists, not subordinate req's.
4649 while (r
->replies
) // Send queued replies
4651 transfer_state result
;
4652 if (r
->replies
->next
) r
->replies
->rhdr
->flags
|= dnssd_htonl(kDNSServiceFlagsMoreComing
);
4653 result
= send_msg(r
); // Returns t_morecoming if buffer full because client is not reading
4654 if (result
== t_complete
)
4656 reply_state
*fptr
= r
->replies
;
4657 r
->replies
= r
->replies
->next
;
4658 freeL("reply_state/udsserver_idle", fptr
);
4659 r
->time_blocked
= 0; // reset failure counter after successful send
4660 r
->unresponsiveness_reports
= 0;
4663 else if (result
== t_terminated
|| result
== t_error
)
4665 LogMsg("%3d: Could not write data to client because of error - aborting connection", r
->sd
);
4666 LogClientInfo(&mDNSStorage
, r
);
4672 if (r
->replies
) // If we failed to send everything, check our time_blocked timer
4674 if (nextevent
- now
> mDNSPlatformOneSecond
) nextevent
= now
+ mDNSPlatformOneSecond
;
4676 if (mDNSStorage
.SleepState
!= SleepState_Awake
) r
->time_blocked
= 0;
4677 else if (!r
->time_blocked
) r
->time_blocked
= NonZeroTime(now
);
4678 else if (now
- r
->time_blocked
>= 10 * mDNSPlatformOneSecond
* (r
->unresponsiveness_reports
+1))
4681 struct reply_state
*x
= r
->replies
;
4682 while (x
) { num
++; x
=x
->next
; }
4683 LogMsg("%3d: Could not write data to client after %ld seconds, %d repl%s waiting",
4684 r
->sd
, (now
- r
->time_blocked
) / mDNSPlatformOneSecond
, num
, num
== 1 ? "y" : "ies");
4685 if (++r
->unresponsiveness_reports
>= 60)
4687 LogMsg("%3d: Client unresponsive; aborting connection", r
->sd
);
4688 LogClientInfo(&mDNSStorage
, r
);
4694 if (!dnssd_SocketValid(r
->sd
)) // If this request is finished, unlink it from the list and free the memory
4696 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
4698 freeL("request_state/udsserver_idle", r
);
4706 struct CompileTimeAssertionChecks_uds_daemon
4708 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4709 // other overly-large structures instead of having a pointer to them, can inadvertently
4710 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
4711 char sizecheck_request_state
[(sizeof(request_state
) <= 2000) ? 1 : -1];
4712 char sizecheck_registered_record_entry
[(sizeof(registered_record_entry
) <= 60) ? 1 : -1];
4713 char sizecheck_service_instance
[(sizeof(service_instance
) <= 6552) ? 1 : -1];
4714 char sizecheck_browser_t
[(sizeof(browser_t
) <= 1050) ? 1 : -1];
4715 char sizecheck_reply_hdr
[(sizeof(reply_hdr
) <= 12) ? 1 : -1];
4716 char sizecheck_reply_state
[(sizeof(reply_state
) <= 64) ? 1 : -1];