• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2003-2006 Apple Computer, Inc. All rights reserved.
4  *
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17 
18 #if defined(_WIN32)
19 #include <process.h>
20 #define usleep(X) Sleep(((X)+999)/1000)
21 #else
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
26 #include <sys/time.h>
27 #include <sys/resource.h>
28 #endif
29 
30 #include <stdlib.h>
31 #include <stdio.h>
32 
33 #include "mDNSEmbeddedAPI.h"
34 #include "DNSCommon.h"
35 #include "uDNS.h"
36 #include "uds_daemon.h"
37 
38 #ifdef __ANDROID__
39 #include "cutils/sockets.h"
40 #endif
41 
42 // Normally we append search domains only for queries with a single label that are not
43 // fully qualified. This can be overridden to apply search domains for queries (that are
44 // not fully qualified) with any number of labels e.g., moon, moon.cs, moon.cs.be, etc.
45 mDNSBool AlwaysAppendSearchDomains = mDNSfalse;
46 
47 // Apple-specific functionality, not required for other platforms
48 #if APPLE_OSX_mDNSResponder
49 #include <sys/ucred.h>
50 #ifndef PID_FILE
51 #define PID_FILE ""
52 #endif
53 #endif
54 
55 #if APPLE_OSX_mDNSResponder
56 #include <WebFilterDNS/WebFilterDNS.h>
57 
58 #if ! NO_WCF
59 
60 int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
61 int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
62 int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
63 
64 // Do we really need to define a macro for "if"?
65 #define CHECK_WCF_FUNCTION(X) if (X)
66 #endif // ! NO_WCF
67 
68 #else
69 #define NO_WCF 1
70 #endif // APPLE_OSX_mDNSResponder
71 
72 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
73 // User IDs for real user accounts start at 501 and count up from there
74 #define SystemUID(X) ((X) <= 500)
75 
76 // ***************************************************************************
77 #if COMPILER_LIKES_PRAGMA_MARK
78 #pragma mark -
79 #pragma mark - Types and Data Structures
80 #endif
81 
82 typedef enum
83 	{
84 	t_uninitialized,
85 	t_morecoming,
86 	t_complete,
87 	t_error,
88 	t_terminated
89 	} transfer_state;
90 
91 typedef struct request_state request_state;
92 
93 typedef void (*req_termination_fn)(request_state *request);
94 
95 typedef struct registered_record_entry
96 	{
97 	struct registered_record_entry *next;
98 	mDNSu32 key;
99 	client_context_t regrec_client_context;
100 	request_state *request;
101 	mDNSBool external_advertise;
102 	mDNSInterfaceID origInterfaceID;
103 	AuthRecord *rr;				// Pointer to variable-sized AuthRecord (Why a pointer? Why not just embed it here?)
104 	} registered_record_entry;
105 
106 // A single registered service: ServiceRecordSet + bookkeeping
107 // Note that we duplicate some fields from parent service_info object
108 // to facilitate cleanup, when instances and parent may be deallocated at different times.
109 typedef struct service_instance
110 	{
111 	struct service_instance *next;
112 	request_state *request;
113 	AuthRecord *subtypes;
114 	mDNSBool renameonmemfree;  		// Set on config change when we deregister original name
115     mDNSBool clientnotified;		// Has client been notified of successful registration yet?
116 	mDNSBool default_local;			// is this the "local." from an empty-string registration?
117 	mDNSBool external_advertise;	// is this is being advertised externally?
118 	domainname domain;
119 	ServiceRecordSet srs;			// note -- variable-sized object -- must be last field in struct
120 	} service_instance;
121 
122 // for multi-domain default browsing
123 typedef struct browser_t
124 	{
125 	struct browser_t *next;
126 	domainname domain;
127 	DNSQuestion q;
128 	} browser_t;
129 
130 struct request_state
131 	{
132 	request_state *next;
133 	request_state *primary;			// If this operation is on a shared socket, pointer to primary
134 									// request_state for the original DNSServiceCreateConnection() operation
135 	dnssd_sock_t sd;
136 	dnssd_sock_t errsd;
137 	mDNSu32 uid;
138 	void * platform_data;
139 
140 	// Note: On a shared connection these fields in the primary structure, including hdr, are re-used
141 	// for each new request. This is because, until we've read the ipc_msg_hdr to find out what the
142 	// operation is, we don't know if we're going to need to allocate a new request_state or not.
143 	transfer_state ts;
144 	mDNSu32        hdr_bytes;		// bytes of header already read
145 	ipc_msg_hdr    hdr;
146 	mDNSu32        data_bytes;		// bytes of message data already read
147 	char          *msgbuf;			// pointer to data storage to pass to free()
148 	const char    *msgptr;			// pointer to data to be read from (may be modified)
149 	char          *msgend;			// pointer to byte after last byte of message
150 
151 	// reply, termination, error, and client context info
152 	int no_reply;					// don't send asynchronous replies to client
153 	mDNSs32 time_blocked;			// record time of a blocked client
154 	int unresponsiveness_reports;
155 	struct reply_state *replies;	// corresponding (active) reply list
156 	req_termination_fn terminate;
157 	DNSServiceFlags		flags;
158 
159 	union
160 		{
161 		registered_record_entry *reg_recs;  // list of registrations for a connection-oriented request
162 		struct
163 			{
164 			mDNSInterfaceID interface_id;
165 			mDNSBool default_domain;
166 			mDNSBool ForceMCast;
167 			domainname regtype;
168 			browser_t *browsers;
169 			} browser;
170 		struct
171 			{
172 			mDNSInterfaceID InterfaceID;
173 			mDNSu16 txtlen;
174 			void *txtdata;
175 			mDNSIPPort port;
176 			domainlabel name;
177 			char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
178 			domainname type;
179 			mDNSBool default_domain;
180 			domainname host;
181 			mDNSBool autoname;				// Set if this name is tied to the Computer Name
182 			mDNSBool autorename;			// Set if this client wants us to automatically rename on conflict
183 			mDNSBool allowremotequery;		// Respond to unicast queries from outside the local link?
184 			int num_subtypes;
185 			service_instance *instances;
186 			} servicereg;
187 		struct
188 			{
189 			mDNSInterfaceID      interface_id;
190 			mDNSu32              flags;
191 			mDNSu32              protocol;
192 			DNSQuestion          q4;
193 			DNSQuestion          *q42;
194 			DNSQuestion          q6;
195 			DNSQuestion          *q62;
196 			} addrinfo;
197 		struct
198 			{
199 			mDNSIPPort           ReqExt;	// External port we originally requested, for logging purposes
200 			NATTraversalInfo     NATinfo;
201 			} pm;
202 		struct
203 			{
204 #if 0
205 			DNSServiceFlags flags;
206 #endif
207 			DNSQuestion q_all;
208 			DNSQuestion q_default;
209 			} enumeration;
210 		struct
211 			{
212 			DNSQuestion q;
213 			DNSQuestion *q2;
214 			} queryrecord;
215 		struct
216 			{
217 			DNSQuestion qtxt;
218 			DNSQuestion qsrv;
219 			const ResourceRecord *txt;
220 			const ResourceRecord *srv;
221 			mDNSs32 ReportTime;
222 			mDNSBool external_advertise;
223 			} resolve;
224 		} u;
225 	};
226 
227 // struct physically sits between ipc message header and call-specific fields in the message buffer
228 typedef struct
229 	{
230 	DNSServiceFlags flags;			// Note: This field is in NETWORK byte order
231 	mDNSu32 ifi;					// Note: This field is in NETWORK byte order
232 	DNSServiceErrorType error;		// Note: This field is in NETWORK byte order
233 	} reply_hdr;
234 
235 typedef struct reply_state
236 	{
237 	struct reply_state *next;		// If there are multiple unsent replies
238 	mDNSu32 totallen;
239 	mDNSu32 nwriten;
240 	ipc_msg_hdr mhdr[1];
241 	reply_hdr rhdr[1];
242 	} reply_state;
243 
244 // ***************************************************************************
245 #if COMPILER_LIKES_PRAGMA_MARK
246 #pragma mark -
247 #pragma mark - Globals
248 #endif
249 
250 // globals
251 mDNSexport mDNS mDNSStorage;
252 mDNSexport const char ProgramName[] = "mDNSResponder";
253 
254 static dnssd_sock_t listenfd = dnssd_InvalidSocket;
255 static request_state *all_requests = NULL;
256 
257 // Note asymmetry here between registration and browsing.
258 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
259 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
260 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
261 // 1. SCPrefBrowseDomains (local configuration data)
262 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
263 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
264 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
265 
266 mDNSexport DNameListElem *AutoRegistrationDomains;	// Domains where we automatically register for empty-string registrations
267 
268 static DNameListElem *SCPrefBrowseDomains;			// List of automatic browsing domains read from SCPreferences for "empty string" browsing
269 static ARListElem    *LocalDomainEnumRecords;		// List of locally-generated PTR records to augment those we learn from the network
270 mDNSexport DNameListElem *AutoBrowseDomains;		// List created from those local-only PTR records plus records we get from the network
271 
272 #define MSG_PAD_BYTES 5		// pad message buffer (read from client) with n zero'd bytes to guarantee
273 							// n get_string() calls w/o buffer overrun
274 // initialization, setup/teardown functions
275 
276 // If a platform specifies its own PID file name, we use that
277 #ifndef PID_FILE
278 #define PID_FILE "/var/run/mDNSResponder.pid"
279 #endif
280 
281 // ***************************************************************************
282 #if COMPILER_LIKES_PRAGMA_MARK
283 #pragma mark -
284 #pragma mark - General Utility Functions
285 #endif
286 
FatalError(char * errmsg)287 mDNSlocal void FatalError(char *errmsg)
288 	{
289 	LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
290 	*(volatile long*)0 = 0;	// On OS X abort() doesn't generate a crash log, but writing to zero does
291 	abort();		// On platforms where writing to zero doesn't generate an exception, abort instead
292 	}
293 
dnssd_htonl(mDNSu32 l)294 mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
295 	{
296 	mDNSu32 ret;
297 	char *data = (char*) &ret;
298 	put_uint32(l, &data);
299 	return ret;
300 	}
301 
302 // hack to search-replace perror's to LogMsg's
my_perror(char * errmsg)303 mDNSlocal void my_perror(char *errmsg)
304 	{
305 	LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
306 	}
307 
abort_request(request_state * req)308 mDNSlocal void abort_request(request_state *req)
309 	{
310 	if (req->terminate == (req_termination_fn)~0)
311 		{ LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
312 
313 	// First stop whatever mDNSCore operation we were doing
314 	// If this is actually a shared connection operation, then its req->terminate function will scan
315 	// the all_requests list and terminate any subbordinate operations sharing this file descriptor
316 	if (req->terminate) req->terminate(req);
317 
318 	if (!dnssd_SocketValid(req->sd))
319 		{ LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d",     req, req->sd);        return; }
320 
321 	// Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
322 	if (!req->primary)
323 		{
324 		if (req->errsd != req->sd) LogOperation("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
325 		else                       LogOperation("%3d: Removing FD", req->sd);
326 		udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data);		// Note: This also closes file descriptor req->sd for us
327 		if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
328 
329 		while (req->replies)	// free pending replies
330 			{
331 			reply_state *ptr = req->replies;
332 			req->replies = req->replies->next;
333 			freeL("reply_state (abort)", ptr);
334 			}
335 		}
336 
337 	// Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
338 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
339 	// Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
340 	// for detecting when the memory for an object is inadvertently freed while the object is still on some list
341 	req->sd = req->errsd = -2;
342 #else
343 	req->sd = req->errsd = dnssd_InvalidSocket;
344 #endif
345 	// We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
346 	req->terminate = (req_termination_fn)~0;
347 	}
348 
AbortUnlinkAndFree(request_state * req)349 mDNSlocal void AbortUnlinkAndFree(request_state *req)
350 	{
351 	request_state **p = &all_requests;
352 	abort_request(req);
353 	while (*p && *p != req) p=&(*p)->next;
354 	if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
355 	else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
356 	}
357 
create_reply(const reply_op_t op,const size_t datalen,request_state * const request)358 mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
359 	{
360 	reply_state *reply;
361 
362 	if ((unsigned)datalen < sizeof(reply_hdr))
363 		{
364 		LogMsg("ERROR: create_reply - data length less than length of required fields");
365 		return NULL;
366 		}
367 
368 	reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
369 	if (!reply) FatalError("ERROR: malloc");
370 
371 	reply->next     = mDNSNULL;
372 	reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
373 	reply->nwriten  = 0;
374 
375 	reply->mhdr->version        = VERSION;
376 	reply->mhdr->datalen        = (mDNSu32)datalen;
377 	reply->mhdr->ipc_flags      = 0;
378 	reply->mhdr->op             = op;
379 	reply->mhdr->client_context = request->hdr.client_context;
380 	reply->mhdr->reg_index      = 0;
381 
382 	return reply;
383 	}
384 
385 // Append a reply to the list in a request object
386 // If our request is sharing a connection, then we append our reply_state onto the primary's list
append_reply(request_state * req,reply_state * rep)387 mDNSlocal void append_reply(request_state *req, reply_state *rep)
388 	{
389 	request_state *r = req->primary ? req->primary : req;
390 	reply_state **ptr = &r->replies;
391 	while (*ptr) ptr = &(*ptr)->next;
392 	*ptr = rep;
393 	rep->next = NULL;
394 	}
395 
396 // Generates a response message giving name, type, domain, plus interface index,
397 // suitable for a browse result or service registration result.
398 // On successful completion rep is set to point to a malloc'd reply_state struct
GenerateNTDResponse(const domainname * const servicename,const mDNSInterfaceID id,request_state * const request,reply_state ** const rep,reply_op_t op,DNSServiceFlags flags,mStatus err)399 mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
400 	request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
401 	{
402 	domainlabel name;
403 	domainname type, dom;
404 	*rep = NULL;
405 	if (!DeconstructServiceName(servicename, &name, &type, &dom))
406 		return kDNSServiceErr_Invalid;
407 	else
408 		{
409 		char namestr[MAX_DOMAIN_LABEL+1];
410 		char typestr[MAX_ESCAPED_DOMAIN_NAME];
411 		char domstr [MAX_ESCAPED_DOMAIN_NAME];
412 		int len;
413 		char *data;
414 
415 		ConvertDomainLabelToCString_unescaped(&name, namestr);
416 		ConvertDomainNameToCString(&type, typestr);
417 		ConvertDomainNameToCString(&dom, domstr);
418 
419 		// Calculate reply data length
420 		len = sizeof(DNSServiceFlags);
421 		len += sizeof(mDNSu32);  // if index
422 		len += sizeof(DNSServiceErrorType);
423 		len += (int) (strlen(namestr) + 1);
424 		len += (int) (strlen(typestr) + 1);
425 		len += (int) (strlen(domstr) + 1);
426 
427 		// Build reply header
428 		*rep = create_reply(op, len, request);
429 		(*rep)->rhdr->flags = dnssd_htonl(flags);
430 		(*rep)->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
431 		(*rep)->rhdr->error = dnssd_htonl(err);
432 
433 		// Build reply body
434 		data = (char *)&(*rep)->rhdr[1];
435 		put_string(namestr, &data);
436 		put_string(typestr, &data);
437 		put_string(domstr, &data);
438 
439 		return mStatus_NoError;
440 		}
441 	}
442 
443 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
444 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
GenerateBonjourBrowserResponse(const domainname * const servicename,const mDNSInterfaceID id,request_state * const request,reply_state ** const rep,reply_op_t op,DNSServiceFlags flags,mStatus err)445 mDNSlocal void GenerateBonjourBrowserResponse(const domainname *const servicename, const mDNSInterfaceID id,
446 	request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
447 	{
448 	char namestr[MAX_DOMAIN_LABEL+1];
449 	char typestr[MAX_ESCAPED_DOMAIN_NAME];
450 	static const char domstr[] = ".";
451 	int len;
452 	char *data;
453 
454 	*rep = NULL;
455 
456 	// 1. Put first label in namestr
457 	ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
458 
459 	// 2. Put second label and "local" into typestr
460 	mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
461 
462 	// Calculate reply data length
463 	len = sizeof(DNSServiceFlags);
464 	len += sizeof(mDNSu32);  // if index
465 	len += sizeof(DNSServiceErrorType);
466 	len += (int) (strlen(namestr) + 1);
467 	len += (int) (strlen(typestr) + 1);
468 	len += (int) (strlen(domstr) + 1);
469 
470 	// Build reply header
471 	*rep = create_reply(op, len, request);
472 	(*rep)->rhdr->flags = dnssd_htonl(flags);
473 	(*rep)->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
474 	(*rep)->rhdr->error = dnssd_htonl(err);
475 
476 	// Build reply body
477 	data = (char *)&(*rep)->rhdr[1];
478 	put_string(namestr, &data);
479 	put_string(typestr, &data);
480 	put_string(domstr, &data);
481 	}
482 
483 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
484 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
485 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
read_rr_from_ipc_msg(request_state * request,int GetTTL,int validate_flags)486 mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
487 	{
488 	DNSServiceFlags flags  = get_flags(&request->msgptr, request->msgend);
489 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
490 	char name[256];
491 	int         str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
492 	mDNSu16     type    = get_uint16(&request->msgptr, request->msgend);
493 	mDNSu16     class   = get_uint16(&request->msgptr, request->msgend);
494 	mDNSu16     rdlen   = get_uint16(&request->msgptr, request->msgend);
495 	const char *rdata   = get_rdata (&request->msgptr, request->msgend, rdlen);
496 	mDNSu32 ttl   = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
497 	int storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
498 	AuthRecord *rr;
499 	mDNSInterfaceID InterfaceID;
500 	AuthRecType artype;
501 
502 	request->flags = flags;
503 
504 	if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
505 
506 	if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
507 
508 	if (validate_flags &&
509 		!((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
510 		!((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
511 		{
512 		LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
513 		return NULL;
514 		}
515 
516 	rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
517 	if (!rr) FatalError("ERROR: malloc");
518 
519 	InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
520 	if (InterfaceID == mDNSInterface_LocalOnly)
521 		artype = AuthRecordLocalOnly;
522 	else if (InterfaceID == mDNSInterface_P2P)
523 		artype = AuthRecordP2P;
524 	else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
525 		artype = AuthRecordAnyIncludeP2P;
526 	else
527 		artype = AuthRecordAny;
528 
529 	mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
530 		(mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
531 
532 	if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
533 		{
534 		LogMsg("ERROR: bad name: %s", name);
535 		freeL("AuthRecord/read_rr_from_ipc_msg", rr);
536 		return NULL;
537 		}
538 
539 	if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
540 	rr->resrec.rrclass = class;
541 	rr->resrec.rdlength = rdlen;
542 	rr->resrec.rdata->MaxRDLength = rdlen;
543 	mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
544 	if (GetTTL) rr->resrec.rroriginalttl = ttl;
545 	rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
546 	SetNewRData(&rr->resrec, mDNSNULL, 0);	// Sets rr->rdatahash for us
547 	return rr;
548 	}
549 
build_domainname_from_strings(domainname * srv,char * name,char * regtype,char * domain)550 mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
551 	{
552 	domainlabel n;
553 	domainname d, t;
554 
555 	if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
556 	if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
557 	if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
558 	if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
559 	return 0;
560 	}
561 
send_all(dnssd_sock_t s,const char * ptr,int len)562 mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
563 	{
564 	int n = send(s, ptr, len, 0);
565 	// On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
566 	// (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
567 	// If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
568 	if (n < len)
569 		LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
570 			s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
571 	}
572 
573 #if 0
574 mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
575 {
576 	const 		DNameListElem 	*delem = mDNSNULL;
577 	int 		bestDelta 	= -1; 					// the delta of the best match, lower is better
578 	int 		dLabels 	= 0;
579 	mDNSBool	allow 		= mDNSfalse;
580 
581 	if (SystemUID(request->uid)) return mDNStrue;
582 
583 	dLabels = CountLabels(d);
584 	for (delem = doms; delem; delem = delem->next)
585 		{
586 		if (delem->uid)
587 			{
588 			int	delemLabels = CountLabels(&delem->name);
589 			int delta 		= dLabels - delemLabels;
590 			if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
591 				{
592 				bestDelta = delta;
593 				allow = (allow || (delem->uid == request->uid));
594 				}
595 			}
596 		}
597 
598 	return bestDelta == -1 ? mDNStrue : allow;
599 }
600 #endif
601 
602 // ***************************************************************************
603 #if COMPILER_LIKES_PRAGMA_MARK
604 #pragma mark -
605 #pragma mark - external helpers
606 #endif
607 
external_start_advertising_helper(service_instance * const instance)608 mDNSlocal void external_start_advertising_helper(service_instance *const instance)
609 	{
610 	AuthRecord *st = instance->subtypes;
611 	ExtraResourceRecord *e;
612 	int i;
613 
614 	if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
615 		{
616 		LogInfo("external_start_advertising_helper: Not registering service with port number zero");
617 		return;
618 		}
619 
620 #if APPLE_OSX_mDNSResponder
621 	// Update packet filter if p2p interface already exists, otherwise,
622 	// if will be updated when we get the KEV_DL_IF_ATTACHED event for
623 	// the interface.  Called here since we don't call external_start_advertising_service()
624 	// with the SRV record when advertising a service.
625 	mDNSInitPacketFilter();
626 #endif // APPLE_OSX_mDNSResponder
627 
628 	if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
629 
630 	for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
631 		external_start_advertising_service(&st[i].resrec);
632 
633 	external_start_advertising_service(&instance->srs.RR_PTR.resrec);
634 	external_start_advertising_service(&instance->srs.RR_TXT.resrec);
635 
636 	for (e = instance->srs.Extras; e; e = e->next)
637 		external_start_advertising_service(&e->r.resrec);
638 
639 	instance->external_advertise = mDNStrue;
640 	}
641 
external_stop_advertising_helper(service_instance * const instance)642 mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
643 	{
644 	AuthRecord *st = instance->subtypes;
645 	ExtraResourceRecord *e;
646 	int i;
647 
648 	if (!instance->external_advertise) return;
649 
650 	LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
651 
652 	for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
653 		external_stop_advertising_service(&st[i].resrec);
654 
655 	external_stop_advertising_service(&instance->srs.RR_PTR.resrec);
656 	external_stop_advertising_service(&instance->srs.RR_TXT.resrec);
657 
658 	for (e = instance->srs.Extras; e; e = e->next)
659 		external_stop_advertising_service(&e->r.resrec);
660 
661 	instance->external_advertise = mDNSfalse;
662 	}
663 
664 // ***************************************************************************
665 #if COMPILER_LIKES_PRAGMA_MARK
666 #pragma mark -
667 #pragma mark - DNSServiceRegister
668 #endif
669 
FreeExtraRR(mDNS * const m,AuthRecord * const rr,mStatus result)670 mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
671 	{
672 	ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
673 	(void)m;  // Unused
674 
675 	if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
676 
677 	LogInfo("     FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
678 
679 	if (rr->resrec.rdata != &rr->rdatastorage)
680 		freeL("Extra RData", rr->resrec.rdata);
681 	freeL("ExtraResourceRecord/FreeExtraRR", extra);
682 	}
683 
unlink_and_free_service_instance(service_instance * srv)684 mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
685 	{
686 	ExtraResourceRecord *e = srv->srs.Extras, *tmp;
687 
688 	external_stop_advertising_helper(srv);
689 
690 	// clear pointers from parent struct
691 	if (srv->request)
692 		{
693 		service_instance **p = &srv->request->u.servicereg.instances;
694 		while (*p)
695 			{
696 			if (*p == srv) { *p = (*p)->next; break; }
697 			p = &(*p)->next;
698 			}
699 		}
700 
701 	while (e)
702 		{
703 		e->r.RecordContext = e;
704 		tmp = e;
705 		e = e->next;
706 		FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
707 		}
708 
709 	if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
710 		freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
711 
712 	if (srv->subtypes) { freeL("ServiceSubTypes", srv->subtypes); srv->subtypes = NULL; }
713 	freeL("service_instance", srv);
714 	}
715 
716 // Count how many other service records we have locally with the same name, but different rdata.
717 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
718 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
CountPeerRegistrations(mDNS * const m,ServiceRecordSet * const srs)719 mDNSexport int CountPeerRegistrations(mDNS *const m, ServiceRecordSet *const srs)
720 	{
721 	int count = 0;
722 	ResourceRecord *r = &srs->RR_SRV.resrec;
723 	AuthRecord *rr;
724 
725 	for (rr = m->ResourceRecords; rr; rr=rr->next)
726 		if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
727 			count++;
728 
729 	verbosedebugf("%d peer registrations for %##s", count, r->name->c);
730 	return(count);
731 	}
732 
CountExistingRegistrations(domainname * srv,mDNSIPPort port)733 mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
734 	{
735 	int count = 0;
736 	AuthRecord *rr;
737 	for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
738 		if (rr->resrec.rrtype == kDNSType_SRV &&
739 			mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
740 			SameDomainName(rr->resrec.name, srv))
741 			count++;
742 	return(count);
743 	}
744 
SendServiceRemovalNotification(ServiceRecordSet * const srs)745 mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
746 	{
747 	reply_state *rep;
748 	service_instance *instance = srs->ServiceContext;
749 	if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
750 		LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
751 	else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
752 	}
753 
754 // service registration callback performs three duties - frees memory for deregistered services,
755 // handles name conflicts, and delivers completed registration information to the client
regservice_callback(mDNS * const m,ServiceRecordSet * const srs,mStatus result)756 mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
757 	{
758 	mStatus err;
759 	mDNSBool SuppressError = mDNSfalse;
760 	service_instance *instance;
761 	reply_state         *rep;
762 	(void)m; // Unused
763 
764 	if (!srs)      { LogMsg("regservice_callback: srs is NULL %d",                 result); return; }
765 
766 	instance = srs->ServiceContext;
767 	if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
768 
769 	// don't send errors up to client for wide-area, empty-string registrations
770 	if (instance->request &&
771 		instance->request->u.servicereg.default_domain &&
772 		!instance->default_local)
773 		SuppressError = mDNStrue;
774 
775 	if (mDNS_LoggingEnabled)
776 		{
777 		const char *const fmt =
778 			(result == mStatus_NoError)      ? "%s DNSServiceRegister(%##s, %u) REGISTERED"    :
779 			(result == mStatus_MemFree)      ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED"  :
780 			(result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
781 			                                   "%s DNSServiceRegister(%##s, %u) %s %d";
782 		char prefix[16] = "---:";
783 		if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
784 		LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
785 			SuppressError ? "suppressed error" : "CALLBACK", result);
786 		}
787 
788 	if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
789 
790 	if (result == mStatus_NoError)
791 		{
792 		if (instance->request->u.servicereg.allowremotequery)
793 			{
794 			ExtraResourceRecord *e;
795 			srs->RR_ADV.AllowRemoteQuery = mDNStrue;
796 			srs->RR_PTR.AllowRemoteQuery = mDNStrue;
797 			srs->RR_SRV.AllowRemoteQuery = mDNStrue;
798 			srs->RR_TXT.AllowRemoteQuery = mDNStrue;
799 			for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
800 			}
801 
802 		if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
803 			LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
804 		else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
805 
806 		if (instance->request->u.servicereg.InterfaceID == mDNSInterface_P2P || (!instance->request->u.servicereg.InterfaceID && SameDomainName(&instance->domain, &localdomain) && (instance->request->flags & kDNSServiceFlagsIncludeP2P)))
807 			{
808 			LogInfo("regservice_callback: calling external_start_advertising_helper()");
809 			external_start_advertising_helper(instance);
810 			}
811 		if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
812 			RecordUpdatedNiceLabel(m, 0);	// Successfully got new name, tell user immediately
813 		}
814 	else if (result == mStatus_MemFree)
815 		{
816 		if (instance->request && instance->renameonmemfree)
817 			{
818 			external_stop_advertising_helper(instance);
819 			instance->renameonmemfree = 0;
820 			err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
821 			if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
822 			// error should never happen - safest to log and continue
823 			}
824 		else
825 			unlink_and_free_service_instance(instance);
826 		}
827 	else if (result == mStatus_NameConflict)
828 		{
829 		if (instance->request->u.servicereg.autorename)
830 			{
831 			external_stop_advertising_helper(instance);
832 			if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
833 				{
834 				// On conflict for an autoname service, rename and reregister *all* autoname services
835 				IncrementLabelSuffix(&m->nicelabel, mDNStrue);
836 				mDNS_ConfigChanged(m);	// Will call back into udsserver_handle_configchange()
837 				}
838 			else	// On conflict for a non-autoname service, rename and reregister just that one service
839 				{
840 				if (instance->clientnotified) SendServiceRemovalNotification(srs);
841 				mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
842 				}
843 			}
844 		else
845 			{
846 			if (!SuppressError)
847 				{
848 				if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
849 					LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
850 				else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
851 				}
852 			unlink_and_free_service_instance(instance);
853 			}
854 		}
855 	else		// Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
856 		{
857 		if (!SuppressError)
858 			{
859 			if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
860 				LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
861 			else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
862 			}
863 		}
864 	}
865 
regrecord_callback(mDNS * const m,AuthRecord * rr,mStatus result)866 mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
867 	{
868 	(void)m; // Unused
869 	if (!rr->RecordContext)		// parent struct already freed by termination callback
870 		{
871 		if (result == mStatus_NoError)
872 			LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
873 		else
874 			{
875 			if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
876 
877 			// We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
878 			// If the record has been updated, we need to free the rdata. Everytime we call mDNS_Update, it calls update_callback
879 			// with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
880 			// to free the latest rdata for which the update_callback was never called with.
881 			if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
882 			freeL("AuthRecord/regrecord_callback", rr);
883 			}
884 		}
885 	else
886 		{
887 		registered_record_entry *re = rr->RecordContext;
888 		request_state *request = re->request;
889 
890 		if (mDNS_LoggingEnabled)
891 			{
892 			char *fmt = (result == mStatus_NoError)      ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED"    :
893 						(result == mStatus_MemFree)      ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED"  :
894 						(result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
895 														   "%3d: DNSServiceRegisterRecord(%u %s) %d";
896 			LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
897 			}
898 
899 		if (result != mStatus_MemFree)
900 			{
901 			int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
902 			reply_state *reply = create_reply(reg_record_reply_op, len, request);
903 			reply->mhdr->client_context = re->regrec_client_context;
904 			reply->rhdr->flags = dnssd_htonl(0);
905 			reply->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
906 			reply->rhdr->error = dnssd_htonl(result);
907 			append_reply(request, reply);
908 			}
909 
910 		if (result)
911 			{
912 			// unlink from list, free memory
913 			registered_record_entry **ptr = &request->u.reg_recs;
914 			while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
915 			if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
916 			*ptr = (*ptr)->next;
917 			freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
918 			freeL("registered_record_entry regrecord_callback", re);
919 			}
920 		else
921 			{
922 			if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
923 
924 			if (re->origInterfaceID == mDNSInterface_P2P || (!re->origInterfaceID && IsLocalDomain(&rr->namestorage) && (request->flags & kDNSServiceFlagsIncludeP2P)))
925 				{
926 				LogInfo("regrecord_callback: calling external_start_advertising_service");
927 				external_start_advertising_service(&rr->resrec);
928 				re->external_advertise = mDNStrue;
929 				}
930 			}
931 		}
932 	}
933 
connection_termination(request_state * request)934 mDNSlocal void connection_termination(request_state *request)
935 	{
936 	// When terminating a shared connection, we need to scan the all_requests list
937 	// and terminate any subbordinate operations sharing this file descriptor
938 	request_state **req = &all_requests;
939 
940 	LogOperation("%3d: DNSServiceCreateConnection STOP", request->sd);
941 
942 	while (*req)
943 		{
944 		if ((*req)->primary == request)
945 			{
946 			// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
947 			request_state *tmp = *req;
948 			if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d",                  tmp, tmp->sd);
949 			if (tmp->replies)        LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
950 			abort_request(tmp);
951 			*req = tmp->next;
952 			freeL("request_state/connection_termination", tmp);
953 			}
954 		else
955 			req = &(*req)->next;
956 		}
957 
958 	while (request->u.reg_recs)
959 		{
960 		registered_record_entry *ptr = request->u.reg_recs;
961 		LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec));
962 		request->u.reg_recs = request->u.reg_recs->next;
963 		ptr->rr->RecordContext = NULL;
964 		if (ptr->external_advertise)
965 			{
966 			ptr->external_advertise = mDNSfalse;
967 			external_stop_advertising_service(&ptr->rr->resrec);
968 			}
969 		mDNS_Deregister(&mDNSStorage, ptr->rr);		// Will free ptr->rr for us
970 		freeL("registered_record_entry/connection_termination", ptr);
971 		}
972 	}
973 
handle_cancel_request(request_state * request)974 mDNSlocal void handle_cancel_request(request_state *request)
975 	{
976 	request_state **req = &all_requests;
977 	LogOperation("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
978 	while (*req)
979 		{
980 		if ((*req)->primary == request &&
981 			(*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
982 			(*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
983 			{
984 			// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
985 			request_state *tmp = *req;
986 			abort_request(tmp);
987 			*req = tmp->next;
988 			freeL("request_state/handle_cancel_request", tmp);
989 			}
990 		else
991 			req = &(*req)->next;
992 		}
993 	}
994 
handle_regrecord_request(request_state * request)995 mDNSlocal mStatus handle_regrecord_request(request_state *request)
996 	{
997 	mStatus err = mStatus_BadParamErr;
998 	AuthRecord *rr = read_rr_from_ipc_msg(request, 1, 1);
999 	if (rr)
1000 		{
1001 		registered_record_entry *re;
1002 		// Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1003 		// clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1004 		if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
1005 			rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
1006 			rr->resrec.rrtype == kDNSType_CNAME))
1007 			{
1008 			freeL("AuthRecord/handle_regrecord_request", rr);
1009 			return (mStatus_BadParamErr);
1010 			}
1011 		// allocate registration entry, link into list
1012 		re = mallocL("registered_record_entry", sizeof(registered_record_entry));
1013 		if (!re) FatalError("ERROR: malloc");
1014 		re->key                   = request->hdr.reg_index;
1015 		re->rr                    = rr;
1016 		re->regrec_client_context = request->hdr.client_context;
1017 		re->request               = request;
1018 		re->external_advertise    = mDNSfalse;
1019 		rr->RecordContext         = re;
1020 		rr->RecordCallback        = regrecord_callback;
1021 
1022 		re->origInterfaceID = rr->resrec.InterfaceID;
1023 		if (rr->resrec.InterfaceID == mDNSInterface_P2P) rr->resrec.InterfaceID = mDNSInterface_Any;
1024 #if 0
1025 		if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains))	return (mStatus_NoError);
1026 #endif
1027 		if (rr->resrec.rroriginalttl == 0)
1028 			rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);
1029 
1030 		LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec));
1031 		err = mDNS_Register(&mDNSStorage, rr);
1032 		if (err)
1033 			{
1034 			LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec), err);
1035 			freeL("registered_record_entry", re);
1036 			freeL("registered_record_entry/AuthRecord", rr);
1037 			}
1038 		else
1039 			{
1040 			re->next = request->u.reg_recs;
1041 			request->u.reg_recs = re;
1042 			}
1043 		}
1044 	return(err);
1045 	}
1046 
1047 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);
1048 
regservice_termination_callback(request_state * request)1049 mDNSlocal void regservice_termination_callback(request_state *request)
1050 	{
1051 	if (!request) { LogMsg("regservice_termination_callback context is NULL"); return; }
1052 	while (request->u.servicereg.instances)
1053 		{
1054 		service_instance *p = request->u.servicereg.instances;
1055 		request->u.servicereg.instances = request->u.servicereg.instances->next;
1056 		// only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1057 		LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP",
1058 			request->sd, p->srs.RR_SRV.resrec.name->c, mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port));
1059 
1060 		external_stop_advertising_helper(p);
1061 
1062 		// Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1063 		// We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1064 		// request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1065 		// We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1066 		// because by then we might have already freed p
1067 		p->request = NULL;
1068 		if (mDNS_DeregisterService(&mDNSStorage, &p->srs)) unlink_and_free_service_instance(p);
1069 		// Don't touch service_instance *p after this -- it's likely to have been freed already
1070 		}
1071 	if (request->u.servicereg.txtdata)
1072 		{ freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
1073 	if (request->u.servicereg.autoname)
1074 		{
1075 		// Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1076 		request->u.servicereg.autoname = mDNSfalse;
1077 		UpdateDeviceInfoRecord(&mDNSStorage);
1078 		}
1079 	}
1080 
LocateSubordinateRequest(request_state * request)1081 mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
1082 	{
1083 	request_state *req;
1084 	for (req = all_requests; req; req = req->next)
1085 		if (req->primary == request &&
1086 			req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1087 			req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
1088 	return(request);
1089 	}
1090 
add_record_to_service(request_state * request,service_instance * instance,mDNSu16 rrtype,mDNSu16 rdlen,const char * rdata,mDNSu32 ttl)1091 mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl)
1092 	{
1093 	ServiceRecordSet *srs = &instance->srs;
1094 	mStatus result;
1095 	int size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1096 	ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
1097 	if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1098 
1099 	mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord));  // OK if oversized rdata not zero'd
1100 	extra->r.resrec.rrtype = rrtype;
1101 	extra->r.rdatastorage.MaxRDLength = (mDNSu16) size;
1102 	extra->r.resrec.rdlength = rdlen;
1103 	mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen);
1104 
1105 	result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl,
1106 					(request->flags & kDNSServiceFlagsIncludeP2P) ? 1: 0);
1107 	if (result) { freeL("ExtraResourceRecord/add_record_to_service", extra); return result; }
1108 
1109 	extra->ClientID = request->hdr.reg_index;
1110 	if (instance->external_advertise && (instance->request->u.servicereg.InterfaceID == mDNSInterface_P2P || (!instance->request->u.servicereg.InterfaceID && SameDomainName(&instance->domain, &localdomain) && (instance->request->flags & kDNSServiceFlagsIncludeP2P))))
1111 		{
1112 		LogInfo("add_record_to_service: calling external_start_advertising_service");
1113 		external_start_advertising_service(&extra->r.resrec);
1114 		}
1115 	return result;
1116 	}
1117 
handle_add_request(request_state * request)1118 mDNSlocal mStatus handle_add_request(request_state *request)
1119 	{
1120 	service_instance *i;
1121 	mStatus result = mStatus_UnknownErr;
1122 	DNSServiceFlags flags  = get_flags (&request->msgptr, request->msgend);
1123 	mDNSu16         rrtype = get_uint16(&request->msgptr, request->msgend);
1124 	mDNSu16         rdlen  = get_uint16(&request->msgptr, request->msgend);
1125 	const char     *rdata  = get_rdata (&request->msgptr, request->msgend, rdlen);
1126 	mDNSu32         ttl    = get_uint32(&request->msgptr, request->msgend);
1127 	if (!ttl) ttl = DefaultTTLforRRType(rrtype);
1128 	(void)flags; // Unused
1129 
1130 	if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1131 
1132 	// If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1133 	if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1134 
1135 	if (request->terminate != regservice_termination_callback)
1136 		{ LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1137 
1138 	// For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1139 	// in the application. See radar://9165807.
1140 	if (mDNSIPPortIsZero(request->u.servicereg.port))
1141 		{ LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1142 
1143 	LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d)", request->sd, flags,
1144 		(request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen);
1145 
1146 	for (i = request->u.servicereg.instances; i; i = i->next)
1147 		{
1148 		result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
1149 		if (result && i->default_local) break;
1150 		else result = mStatus_NoError;  // suppress non-local default errors
1151 		}
1152 
1153 	return(result);
1154 	}
1155 
update_callback(mDNS * const m,AuthRecord * const rr,RData * oldrd,mDNSu16 oldrdlen)1156 mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
1157 	{
1158 	mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
1159 	(void)m; // Unused
1160 
1161 	// There are three cases.
1162 	//
1163 	// 1. We have updated the primary TXT record of the service
1164 	// 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1165 	// 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1166 	//
1167 	// external_advertise is set if we have advertised at least once during the initial addition
1168 	// of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1169 	// checks during the first time and hence we don't do any checks here
1170 	if (external_advertise)
1171 		{
1172 		ResourceRecord ext = rr->resrec;
1173 		if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
1174 		SetNewRData(&ext, oldrd, oldrdlen);
1175 		external_stop_advertising_service(&ext);
1176 		LogInfo("update_callback: calling external_start_advertising_service");
1177 		external_start_advertising_service(&rr->resrec);
1178 		}
1179 exit:
1180 	if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
1181 	}
1182 
update_record(AuthRecord * rr,mDNSu16 rdlen,const char * rdata,mDNSu32 ttl,const mDNSBool * const external_advertise)1183 mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl, const mDNSBool *const external_advertise)
1184 	{
1185 	mStatus result;
1186 	const int rdsize = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1187 	RData *newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize);
1188 	if (!newrd) FatalError("ERROR: malloc");
1189 	newrd->MaxRDLength = (mDNSu16) rdsize;
1190 	mDNSPlatformMemCopy(&newrd->u, rdata, rdlen);
1191 
1192 	// BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1193 	// since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1194 	// Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1195 	if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }
1196 
1197 	if (external_advertise) rr->UpdateContext = (void *)external_advertise;
1198 
1199 	result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback);
1200 	if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, rr)); freeL("RData/update_record", newrd); }
1201 	return result;
1202 	}
1203 
handle_update_request(request_state * request)1204 mDNSlocal mStatus handle_update_request(request_state *request)
1205 	{
1206 	const ipc_msg_hdr *const hdr = &request->hdr;
1207 	mStatus result = mStatus_BadReferenceErr;
1208 	service_instance *i;
1209 	AuthRecord *rr = NULL;
1210 
1211 	// get the message data
1212 	DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);	// flags unused
1213 	mDNSu16         rdlen = get_uint16(&request->msgptr, request->msgend);
1214 	const char     *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1215 	mDNSu32         ttl   = get_uint32(&request->msgptr, request->msgend);
1216 	(void)flags; // Unused
1217 
1218 	if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1219 
1220 	// If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1221 	if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1222 
1223 	if (request->terminate == connection_termination)
1224 		{
1225 		// update an individually registered record
1226 		registered_record_entry *reptr;
1227 		for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
1228 			{
1229 			if (reptr->key == hdr->reg_index)
1230 				{
1231 				result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise);
1232 				LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)",
1233 					request->sd, reptr->rr->resrec.name->c, reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>");
1234 				goto end;
1235 				}
1236 			}
1237 		result = mStatus_BadReferenceErr;
1238 		goto end;
1239 		}
1240 
1241 	if (request->terminate != regservice_termination_callback)
1242 		{ LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1243 
1244 	// For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1245 	if (mDNSIPPortIsZero(request->u.servicereg.port))
1246 		{ LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1247 
1248 	// update the saved off TXT data for the service
1249 	if (hdr->reg_index == TXT_RECORD_INDEX)
1250 		{
1251 		if (request->u.servicereg.txtdata)
1252 			{ freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
1253 		if (rdlen > 0)
1254 			{
1255 			request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
1256 			if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
1257 			mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
1258 			}
1259 		request->u.servicereg.txtlen = rdlen;
1260 		}
1261 
1262 	// update a record from a service record set
1263 	for (i = request->u.servicereg.instances; i; i = i->next)
1264 		{
1265 		if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
1266 		else
1267 			{
1268 			ExtraResourceRecord *e;
1269 			for (e = i->srs.Extras; e; e = e->next)
1270 				if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
1271 			}
1272 
1273 		if (!rr) { result = mStatus_BadReferenceErr; goto end; }
1274 		result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise);
1275 		if (result && i->default_local) goto end;
1276 		else result = mStatus_NoError;  // suppress non-local default errors
1277 		}
1278 
1279 end:
1280 	if (request->terminate == regservice_termination_callback)
1281 		LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request->sd,
1282 			(request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1283 			rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>");
1284 
1285 	return(result);
1286 	}
1287 
1288 // remove a resource record registered via DNSServiceRegisterRecord()
remove_record(request_state * request)1289 mDNSlocal mStatus remove_record(request_state *request)
1290 	{
1291 	mStatus err = mStatus_UnknownErr;
1292 	registered_record_entry *e, **ptr = &request->u.reg_recs;
1293 
1294 	while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
1295 	if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
1296 	e = *ptr;
1297 	*ptr = e->next; // unlink
1298 
1299 	LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec));
1300 	e->rr->RecordContext = NULL;
1301 	if (e->external_advertise)
1302 		{
1303 		external_stop_advertising_service(&e->rr->resrec);
1304 		e->external_advertise = mDNSfalse;
1305 		}
1306 	err = mDNS_Deregister(&mDNSStorage, e->rr);		// Will free e->rr for us; we're responsible for freeing e
1307 	if (err)
1308 		{
1309 		LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
1310 		freeL("registered_record_entry AuthRecord remove_record", e->rr);
1311 		}
1312 
1313 	freeL("registered_record_entry remove_record", e);
1314 	return err;
1315 	}
1316 
remove_extra(const request_state * const request,service_instance * const serv,mDNSu16 * const rrtype)1317 mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
1318 	{
1319 	mStatus err = mStatus_BadReferenceErr;
1320 	ExtraResourceRecord *ptr;
1321 
1322 	for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
1323 		{
1324 		if (ptr->ClientID == request->hdr.reg_index) // found match
1325 			{
1326 			*rrtype = ptr->r.resrec.rrtype;
1327 			if (serv->external_advertise) external_stop_advertising_service(&ptr->r.resrec);
1328 			err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
1329 			break;
1330 			}
1331 		}
1332 	return err;
1333 	}
1334 
handle_removerecord_request(request_state * request)1335 mDNSlocal mStatus handle_removerecord_request(request_state *request)
1336 	{
1337 	mStatus err = mStatus_BadReferenceErr;
1338 	get_flags(&request->msgptr, request->msgend);	// flags unused
1339 
1340 	if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1341 
1342 	// If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1343 	if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1344 
1345 	if (request->terminate == connection_termination)
1346 		err = remove_record(request);  // remove individually registered record
1347 	else if (request->terminate != regservice_termination_callback)
1348 		{ LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1349 	else
1350 		{
1351 		service_instance *i;
1352 		mDNSu16 rrtype = 0;
1353 		LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request->sd,
1354 			(request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1355 			rrtype ? DNSTypeName(rrtype) : "<NONE>");
1356 		for (i = request->u.servicereg.instances; i; i = i->next)
1357 			{
1358 			err = remove_extra(request, i, &rrtype);
1359 			if (err && i->default_local) break;
1360 			else err = mStatus_NoError;  // suppress non-local default errors
1361 			}
1362 		}
1363 
1364 	return(err);
1365 	}
1366 
1367 // If there's a comma followed by another character,
1368 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1369 // Otherwise, it returns a pointer to the final nul at the end of the string
FindFirstSubType(char * p)1370 mDNSlocal char *FindFirstSubType(char *p)
1371 	{
1372 	while (*p)
1373 		{
1374 		if (p[0] == '\\' && p[1]) p += 2;
1375 		else if (p[0] == ',' && p[1]) { *p++ = 0; return(p); }
1376 		else p++;
1377 		}
1378 	return(p);
1379 	}
1380 
1381 // If there's a comma followed by another character,
1382 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1383 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1384 // Otherwise, it returns a pointer to the final nul at the end of the string
FindNextSubType(char * p)1385 mDNSlocal char *FindNextSubType(char *p)
1386 	{
1387 	while (*p)
1388 		{
1389 		if (p[0] == '\\' && p[1])		// If escape character
1390 			p += 2;						// ignore following character
1391 		else if (p[0] == ',')			// If we found a comma
1392 			{
1393 			if (p[1]) *p++ = 0;
1394 			return(p);
1395 			}
1396 		else if (p[0] == '.')
1397 			return(mDNSNULL);
1398 		else p++;
1399 		}
1400 	return(p);
1401 	}
1402 
1403 // Returns -1 if illegal subtype found
ChopSubTypes(char * regtype)1404 mDNSexport mDNSs32 ChopSubTypes(char *regtype)
1405 	{
1406 	mDNSs32 NumSubTypes = 0;
1407 	char *stp = FindFirstSubType(regtype);
1408 	while (stp && *stp)					// If we found a comma...
1409 		{
1410 		if (*stp == ',') return(-1);
1411 		NumSubTypes++;
1412 		stp = FindNextSubType(stp);
1413 		}
1414 	if (!stp) return(-1);
1415 	return(NumSubTypes);
1416 	}
1417 
AllocateSubTypes(mDNSs32 NumSubTypes,char * p)1418 mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p)
1419 	{
1420 	AuthRecord *st = mDNSNULL;
1421 	if (NumSubTypes)
1422 		{
1423 		mDNSs32 i;
1424 		st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
1425 		if (!st) return(mDNSNULL);
1426 		for (i = 0; i < NumSubTypes; i++)
1427 			{
1428 			mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
1429 			while (*p) p++;
1430 			p++;
1431 			if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
1432 				{ freeL("ServiceSubTypes", st); return(mDNSNULL); }
1433 			}
1434 		}
1435 	return(st);
1436 	}
1437 
register_service_instance(request_state * request,const domainname * domain)1438 mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
1439 	{
1440 	service_instance **ptr, *instance;
1441 	const int extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
1442 	const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
1443 	mStatus result;
1444 	mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;
1445 	mDNSu32 regFlags = 0;
1446 
1447 	if (interfaceID == mDNSInterface_P2P)
1448 		{
1449 		interfaceID = mDNSInterface_Any;
1450 		regFlags |= regFlagIncludeP2P;
1451 		}
1452 	else if (request->flags & kDNSServiceFlagsIncludeP2P)
1453 		regFlags |= regFlagIncludeP2P;
1454 
1455 	// client guarantees that record names are unique
1456 	if (request->flags & kDNSServiceFlagsForce)
1457 		regFlags |= regFlagKnownUnique;
1458 
1459 	// If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1460 	// registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1461 	// registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1462 	// (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1463 	// currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1464 	if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;
1465 
1466 	for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
1467 		{
1468 		if (SameDomainName(&(*ptr)->domain, domain))
1469 			{
1470 			LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1471 				domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
1472 			return mStatus_AlreadyRegistered;
1473 			}
1474 		}
1475 
1476 	if (mDNSStorage.KnownBugs & mDNS_KnownBug_LimitedIPv6)
1477 		{
1478 		// Special-case hack: On Mac OS X 10.6.x and earlier we don't advertise SMB service in AutoTunnel domains,
1479 		// because AutoTunnel services have to support IPv6, and in Mac OS X 10.6.x the SMB server does not.
1480 		// <rdar://problem/5482322> BTMM: Don't advertise SMB with BTMM because it doesn't support IPv6
1481 		if (SameDomainName(&request->u.servicereg.type, (const domainname *) "\x4" "_smb" "\x4" "_tcp"))
1482 			{
1483 			DomainAuthInfo *AuthInfo = GetAuthInfoForName(&mDNSStorage, domain);
1484 			if (AuthInfo && AuthInfo->AutoTunnel) return(kDNSServiceErr_Unsupported);
1485 			}
1486 		}
1487 
1488 	instance = mallocL("service_instance", sizeof(*instance) + extra_size);
1489 	if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1490 
1491 	instance->next							= mDNSNULL;
1492 	instance->request						= request;
1493 	instance->subtypes						= AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string);
1494 	instance->renameonmemfree				= 0;
1495 	instance->clientnotified				= mDNSfalse;
1496 	instance->default_local					= (request->u.servicereg.default_domain && DomainIsLocal);
1497 	instance->external_advertise            = mDNSfalse;
1498 	AssignDomainName(&instance->domain, domain);
1499 
1500 	if (request->u.servicereg.num_subtypes && !instance->subtypes)
1501 		{ unlink_and_free_service_instance(instance); instance = NULL; FatalError("ERROR: malloc"); }
1502 
1503 	result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
1504 		&request->u.servicereg.name, &request->u.servicereg.type, domain,
1505 		request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
1506 		request->u.servicereg.port,
1507 		request->u.servicereg.txtdata, request->u.servicereg.txtlen,
1508 		instance->subtypes, request->u.servicereg.num_subtypes,
1509 		interfaceID, regservice_callback, instance, regFlags);
1510 
1511 	if (!result)
1512 		{
1513 		*ptr = instance;		// Append this to the end of our request->u.servicereg.instances list
1514 		LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED",
1515 			instance->request->sd, instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
1516 		}
1517 	else
1518 		{
1519 		LogMsg("register_service_instance %#s.%##s%##s error %d",
1520 			&request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
1521 		unlink_and_free_service_instance(instance);
1522 		}
1523 
1524 	return result;
1525 	}
1526 
udsserver_default_reg_domain_changed(const DNameListElem * const d,const mDNSBool add)1527 mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
1528 	{
1529 	request_state *request;
1530 
1531 #if APPLE_OSX_mDNSResponder
1532 	machserver_automatic_registration_domain_changed(&d->name, add);
1533 #endif // APPLE_OSX_mDNSResponder
1534 
1535 	LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
1536 	for (request = all_requests; request; request = request->next)
1537 		{
1538 		if (request->terminate != regservice_termination_callback) continue;
1539 		if (!request->u.servicereg.default_domain) continue;
1540 		if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1541 			{
1542 			service_instance **ptr = &request->u.servicereg.instances;
1543 			while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1544 			if (add)
1545 				{
1546 				// If we don't already have this domain in our list for this registration, add it now
1547 				if (!*ptr) register_service_instance(request, &d->name);
1548 				else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
1549 				}
1550 			else
1551 				{
1552 				// Normally we should not fail to find the specified instance
1553 				// One case where this can happen is if a uDNS update fails for some reason,
1554 				// and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1555 				if (!*ptr)
1556 					LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1557 						&d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
1558 				else
1559 					{
1560 					DNameListElem *p;
1561 					for (p = AutoRegistrationDomains; p; p=p->next)
1562 						if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1563 							if (SameDomainName(&d->name, &p->name)) break;
1564 					if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
1565 					else
1566 						{
1567 						mStatus err;
1568 						service_instance *si = *ptr;
1569 						*ptr = si->next;
1570 						if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
1571 						// Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1572 						// Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1573 						// process of completing asynchronously, the client cancels the entire operation, so
1574 						// regservice_termination_callback then runs through the whole list deregistering each
1575 						// instance, clearing the backpointers, and then disposing the parent request_state object.
1576 						// However, because this service_instance isn't in the list any more, regservice_termination_callback
1577 						// has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1578 						// completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1579 						// a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1580 						si->request = NULL;
1581 						err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
1582 						if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
1583 						}
1584 					}
1585 				}
1586 			}
1587 		}
1588 	}
1589 
handle_regservice_request(request_state * request)1590 mDNSlocal mStatus handle_regservice_request(request_state *request)
1591 	{
1592 	char name[256];	// Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1593 	char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
1594 	char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
1595 	domainname d, srv;
1596 	mStatus err;
1597 	const char *msgTXTData;
1598 
1599 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
1600 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
1601 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
1602 	if (interfaceIndex && !InterfaceID)
1603 		{ LogMsg("ERROR: handle_regservice_request - Couldn't find interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); }
1604 
1605 	if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
1606 		get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1607 		get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1608 		get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
1609 		{ LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
1610 
1611 	request->flags = flags;
1612 	request->u.servicereg.InterfaceID = InterfaceID;
1613 	request->u.servicereg.instances = NULL;
1614 	request->u.servicereg.txtlen  = 0;
1615 	request->u.servicereg.txtdata = NULL;
1616 	mDNSPlatformStrLCopy(request->u.servicereg.type_as_string, type_as_string, sizeof(request->u.servicereg.type_as_string));
1617 
1618 	if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
1619 	else
1620 		{
1621 		request->u.servicereg.port.b[0] = *request->msgptr++;
1622 		request->u.servicereg.port.b[1] = *request->msgptr++;
1623 		}
1624 
1625 	request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
1626 	msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);
1627 	if (!request->msgptr)
1628 		{
1629 		LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd);
1630 		return(mStatus_BadParamErr);
1631 		}
1632 
1633 	if (request->u.servicereg.txtlen)
1634 		{
1635 		request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
1636 		if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
1637 		mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
1638 		}
1639 
1640 	// Check for sub-types after the service type
1641 	request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string);	// Note: Modifies regtype string to remove trailing subtypes
1642 	if (request->u.servicereg.num_subtypes < 0)
1643 		{ LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); }
1644 
1645 	// Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1646 	if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
1647 		{ LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); }
1648 
1649 	if (!name[0])
1650 		{
1651 		request->u.servicereg.name = mDNSStorage.nicelabel;
1652 		request->u.servicereg.autoname = mDNStrue;
1653 		}
1654 	else
1655 		{
1656 		// If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1657 		if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
1658 			{
1659 			int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
1660 			name[newlen] = 0;
1661 			}
1662 		if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
1663 			{ LogMsg("ERROR: handle_regservice_request - name bad %s", name); return(mStatus_BadParamErr); }
1664 		request->u.servicereg.autoname = mDNSfalse;
1665 		}
1666 
1667 	if (*domain)
1668 		{
1669 		request->u.servicereg.default_domain = mDNSfalse;
1670 		if (!MakeDomainNameFromDNSNameString(&d, domain))
1671 			{ LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); return(mStatus_BadParamErr); }
1672 		}
1673 	else
1674 		{
1675 		request->u.servicereg.default_domain = mDNStrue;
1676 		MakeDomainNameFromDNSNameString(&d, "local.");
1677 		}
1678 
1679 	if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
1680 		{
1681 		LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1682 			request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); return(mStatus_BadParamErr);
1683 		}
1684 
1685 	if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
1686 		{ LogMsg("ERROR: handle_regservice_request - host bad %s", host); return(mStatus_BadParamErr); }
1687 	request->u.servicereg.autorename       = (flags & kDNSServiceFlagsNoAutoRename    ) == 0;
1688 	request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
1689 
1690 	// Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1691 	// a port number of zero. When two instances of the protected client are allowed to run on one
1692 	// machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1693 	if (!mDNSIPPortIsZero(request->u.servicereg.port))
1694 		{
1695 		int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
1696 		if (count)
1697 			LogMsg("Client application registered %d identical instances of service %##s port %u.",
1698 				count+1, srv.c, mDNSVal16(request->u.servicereg.port));
1699 		}
1700 
1701 	LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START",
1702 		request->sd, flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host, mDNSVal16(request->u.servicereg.port));
1703 
1704 	// We need to unconditionally set request->terminate, because even if we didn't successfully
1705 	// start any registrations right now, subsequent configuration changes may cause successful
1706 	// registrations to be added, and we'll need to cancel them before freeing this memory.
1707 	// We also need to set request->terminate first, before adding additional service instances,
1708 	// because the uds_validatelists uses the request->terminate function pointer to determine
1709 	// what kind of request this is, and therefore what kind of list validation is required.
1710 	request->terminate = regservice_termination_callback;
1711 
1712 	err = register_service_instance(request, &d);
1713 
1714 #if 0
1715 	err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
1716 #endif
1717 	if (!err)
1718 		{
1719 		if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
1720 
1721 		if (!*domain)
1722 			{
1723 			DNameListElem *ptr;
1724 			// Note that we don't report errors for non-local, non-explicit domains
1725 			for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
1726 				if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
1727 					register_service_instance(request, &ptr->name);
1728 			}
1729 		}
1730 
1731 	return(err);
1732 	}
1733 
1734 // ***************************************************************************
1735 #if COMPILER_LIKES_PRAGMA_MARK
1736 #pragma mark -
1737 #pragma mark - DNSServiceBrowse
1738 #endif
1739 
FoundInstance(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)1740 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
1741 	{
1742 	const DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
1743 	request_state *req = question->QuestionContext;
1744 	reply_state *rep;
1745 	(void)m; // Unused
1746 
1747 	if (answer->rrtype != kDNSType_PTR)
1748 		{ LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
1749 
1750 	if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
1751 		{
1752 		if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
1753 			{
1754 			// Special support to enable the DNSServiceBrowse call made by Bonjour Browser
1755 			// Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
1756 			GenerateBonjourBrowserResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
1757 			goto bonjourbrowserhack;
1758 			}
1759 
1760 		LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
1761 			req->sd, answer->name->c, answer->rdata->u.name.c);
1762 		return;
1763 		}
1764 
1765 bonjourbrowserhack:
1766 
1767 	LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
1768 		req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "Add" : "Rmv",
1769 		mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
1770 
1771 	append_reply(req, rep);
1772 	}
1773 
add_domain_to_browser(request_state * info,const domainname * d)1774 mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
1775 	{
1776 	browser_t *b, *p;
1777 	mStatus err;
1778 
1779 	for (p = info->u.browser.browsers; p; p = p->next)
1780 		{
1781 		if (SameDomainName(&p->domain, d))
1782 			{ debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
1783 		}
1784 
1785 	b = mallocL("browser_t", sizeof(*b));
1786 	if (!b) return mStatus_NoMemoryErr;
1787 	AssignDomainName(&b->domain, d);
1788 	err = mDNS_StartBrowse(&mDNSStorage, &b->q,
1789 		&info->u.browser.regtype, d, info->u.browser.interface_id, info->u.browser.ForceMCast, FoundInstance, info);
1790 	if (err)
1791 		{
1792 		LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
1793 		freeL("browser_t/add_domain_to_browser", b);
1794 		}
1795 	else
1796 		{
1797 		b->next = info->u.browser.browsers;
1798 		info->u.browser.browsers = b;
1799 		LogOperation("%3d: DNSServiceBrowse(%##s) START", info->sd, b->q.qname.c);
1800 		if (info->u.browser.interface_id == mDNSInterface_P2P || (!info->u.browser.interface_id && SameDomainName(&b->domain, &localdomain) && (info->flags & kDNSServiceFlagsIncludeP2P)))
1801 			{
1802 			domainname tmp;
1803 			ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
1804 			LogInfo("add_domain_to_browser: calling external_start_browsing_for_service()");
1805 			external_start_browsing_for_service(&mDNSStorage, &tmp, kDNSType_PTR);
1806 			}
1807 		}
1808 	return err;
1809 	}
1810 
browse_termination_callback(request_state * info)1811 mDNSlocal void browse_termination_callback(request_state *info)
1812 	{
1813 	while (info->u.browser.browsers)
1814 		{
1815 		browser_t *ptr = info->u.browser.browsers;
1816 
1817 		if (info->u.browser.interface_id == mDNSInterface_P2P || (!info->u.browser.interface_id && SameDomainName(&ptr->domain, &localdomain) && (info->flags & kDNSServiceFlagsIncludeP2P)))
1818 			{
1819 			domainname tmp;
1820 			ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
1821 			LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
1822 			external_stop_browsing_for_service(&mDNSStorage, &tmp, kDNSType_PTR);
1823 			}
1824 
1825 		info->u.browser.browsers = ptr->next;
1826 		LogOperation("%3d: DNSServiceBrowse(%##s) STOP", info->sd, ptr->q.qname.c);
1827 		mDNS_StopBrowse(&mDNSStorage, &ptr->q);  // no need to error-check result
1828 		freeL("browser_t/browse_termination_callback", ptr);
1829 		}
1830 	}
1831 
udsserver_automatic_browse_domain_changed(const DNameListElem * const d,const mDNSBool add)1832 mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
1833 	{
1834 	request_state *request;
1835 	debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
1836 
1837 #if APPLE_OSX_mDNSResponder
1838 	machserver_automatic_browse_domain_changed(&d->name, add);
1839 #endif // APPLE_OSX_mDNSResponder
1840 
1841 	for (request = all_requests; request; request = request->next)
1842 		{
1843 		if (request->terminate != browse_termination_callback) continue;	// Not a browse operation
1844 		if (!request->u.browser.default_domain) continue;					// Not an auto-browse operation
1845 		if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1846 			{
1847 			browser_t **ptr = &request->u.browser.browsers;
1848 			while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1849 			if (add)
1850 				{
1851 				// If we don't already have this domain in our list for this browse operation, add it now
1852 				if (!*ptr) add_domain_to_browser(request, &d->name);
1853 				else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
1854 				}
1855 			else
1856 				{
1857 				if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
1858 				else
1859 					{
1860 					DNameListElem *p;
1861 					for (p = AutoBrowseDomains; p; p=p->next)
1862 						if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1863 							if (SameDomainName(&d->name, &p->name)) break;
1864 					if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
1865 					else
1866 						{
1867 						browser_t *rem = *ptr;
1868 						*ptr = (*ptr)->next;
1869 						mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
1870 						freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
1871 						}
1872 					}
1873 				}
1874 			}
1875 		}
1876 	}
1877 
FreeARElemCallback(mDNS * const m,AuthRecord * const rr,mStatus result)1878 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
1879 	{
1880 	(void)m;  // unused
1881 	if (result == mStatus_MemFree)
1882 		{
1883 		// On shutdown, mDNS_Close automatically deregisters all records
1884 		// Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
1885 		// from the LocalDomainEnumRecords list, we do this here before we free the memory.
1886 		// (This should actually no longer be necessary, now that we do the proper cleanup in
1887 		// udsserver_exit. To confirm this, we'll log an error message if we do find a record that
1888 		// hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
1889 		ARListElem **ptr = &LocalDomainEnumRecords;
1890 		while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
1891 		if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
1892 		mDNSPlatformMemFree(rr->RecordContext);
1893 		}
1894 	}
1895 
1896 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
1897 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
1898 // We may want to turn the common code into a subroutine.
1899 
RegisterLocalOnlyDomainEnumPTR(mDNS * m,const domainname * d,int type)1900 mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
1901 	{
1902 	// allocate/register legacy and non-legacy _browse PTR record
1903 	mStatus err;
1904 	ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
1905 
1906 	debugf("Incrementing %s refcount for %##s",
1907 		(type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
1908 		(type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
1909 		(type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
1910 
1911 	mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
1912 	MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
1913 	AppendDNSNameString            (&ptr->ar.namestorage, "local");
1914 	AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
1915 	err = mDNS_Register(m, &ptr->ar);
1916 	if (err)
1917 		{
1918 		LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
1919 		mDNSPlatformMemFree(ptr);
1920 		}
1921 	else
1922 		{
1923 		ptr->next = LocalDomainEnumRecords;
1924 		LocalDomainEnumRecords = ptr;
1925 		}
1926 	}
1927 
DeregisterLocalOnlyDomainEnumPTR(mDNS * m,const domainname * d,int type)1928 mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
1929 	{
1930 	ARListElem **ptr = &LocalDomainEnumRecords;
1931 	domainname lhs; // left-hand side of PTR, for comparison
1932 
1933 	debugf("Decrementing %s refcount for %##s",
1934 		(type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
1935 		(type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
1936 		(type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
1937 
1938 	MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
1939 	AppendDNSNameString            (&lhs, "local");
1940 
1941 	while (*ptr)
1942 		{
1943 		if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
1944 			{
1945 			ARListElem *rem = *ptr;
1946 			*ptr = (*ptr)->next;
1947 			mDNS_Deregister(m, &rem->ar);
1948 			return;
1949 			}
1950 		else ptr = &(*ptr)->next;
1951 		}
1952 	}
1953 
AddAutoBrowseDomain(const mDNSu32 uid,const domainname * const name)1954 mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
1955 	{
1956 	DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
1957 	if (!new) { LogMsg("ERROR: malloc"); return; }
1958 	AssignDomainName(&new->name, name);
1959 	new->uid = uid;
1960 	new->next = AutoBrowseDomains;
1961 	AutoBrowseDomains = new;
1962 	udsserver_automatic_browse_domain_changed(new, mDNStrue);
1963 	}
1964 
RmvAutoBrowseDomain(const mDNSu32 uid,const domainname * const name)1965 mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
1966 	{
1967 	DNameListElem **p = &AutoBrowseDomains;
1968 	while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
1969 	if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
1970 	else
1971 		{
1972 		DNameListElem *ptr = *p;
1973 		*p = ptr->next;
1974 		udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
1975 		mDNSPlatformMemFree(ptr);
1976 		}
1977 	}
1978 
SetPrefsBrowseDomains(mDNS * m,DNameListElem * browseDomains,mDNSBool add)1979 mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
1980 	{
1981 	DNameListElem *d;
1982 	for (d = browseDomains; d; d = d->next)
1983 		{
1984 		if (add)
1985 			{
1986 			RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
1987 			AddAutoBrowseDomain(d->uid, &d->name);
1988 			}
1989 		else
1990 			{
1991 			DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
1992 			RmvAutoBrowseDomain(d->uid, &d->name);
1993 			}
1994 		}
1995 	}
1996 
UpdateDeviceInfoRecord(mDNS * const m)1997 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
1998 	{
1999 	int num_autoname = 0;
2000 	request_state *req;
2001 	for (req = all_requests; req; req = req->next)
2002 		if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname)
2003 			num_autoname++;
2004 
2005 	// If DeviceInfo record is currently registered, see if we need to deregister it
2006 	if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
2007 		if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
2008 			{
2009 			LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
2010 			mDNS_Deregister(m, &m->DeviceInfo);
2011 			}
2012 
2013 	// If DeviceInfo record is not currently registered, see if we need to register it
2014 	if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
2015 		if (num_autoname > 0)
2016 			{
2017 			mDNSu8 len = m->HIHardware.c[0] < 255 - 6 ? m->HIHardware.c[0] : 255 - 6;
2018 			mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
2019 			ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
2020 			mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 1, "model=", 6);
2021 			mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 7, m->HIHardware.c + 1, len);
2022 			m->DeviceInfo.resrec.rdata->u.data[0] = 6 + len;	// "model=" plus the device string
2023 			m->DeviceInfo.resrec.rdlength         = 7 + len;	// One extra for the length byte at the start of the string
2024 			LogOperation("UpdateDeviceInfoRecord   Register %##s", m->DeviceInfo.resrec.name);
2025 			mDNS_Register(m, &m->DeviceInfo);
2026 			}
2027 	}
2028 
udsserver_handle_configchange(mDNS * const m)2029 mDNSexport void udsserver_handle_configchange(mDNS *const m)
2030 	{
2031 	request_state *req;
2032 	service_instance *ptr;
2033 	DNameListElem *RegDomains = NULL;
2034 	DNameListElem *BrowseDomains = NULL;
2035 	DNameListElem *p;
2036 
2037 	UpdateDeviceInfoRecord(m);
2038 
2039 	// For autoname services, see if the default service name has changed, necessitating an automatic update
2040 	for (req = all_requests; req; req = req->next)
2041 		if (req->terminate == regservice_termination_callback)
2042 			if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
2043 				{
2044 				req->u.servicereg.name = m->nicelabel;
2045 				for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
2046 					{
2047 					ptr->renameonmemfree = 1;
2048 					if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
2049 					LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
2050 					if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
2051 						regservice_callback(m, &ptr->srs, mStatus_MemFree);	// If service deregistered already, we can re-register immediately
2052 					}
2053 				}
2054 
2055 	// Let the platform layer get the current DNS information
2056 	mDNS_Lock(m);
2057 	mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains);
2058 	mDNS_Unlock(m);
2059 
2060 	// Any automatic registration domains are also implicitly automatic browsing domains
2061 	if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue);								// Add the new list first
2062 	if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse);	// Then clear the old list
2063 
2064 	// Add any new domains not already in our AutoRegistrationDomains list
2065 	for (p=RegDomains; p; p=p->next)
2066 		{
2067 		DNameListElem **pp = &AutoRegistrationDomains;
2068 		while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
2069 		if (!*pp)		// If not found in our existing list, this is a new default registration domain
2070 			{
2071 			RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
2072 			udsserver_default_reg_domain_changed(p, mDNStrue);
2073 			}
2074 		else			// else found same domainname in both old and new lists, so no change, just delete old copy
2075 			{
2076 			DNameListElem *del = *pp;
2077 			*pp = (*pp)->next;
2078 			mDNSPlatformMemFree(del);
2079 			}
2080 		}
2081 
2082 	// Delete any domains in our old AutoRegistrationDomains list that are now gone
2083 	while (AutoRegistrationDomains)
2084 		{
2085 		DNameListElem *del = AutoRegistrationDomains;
2086 		AutoRegistrationDomains = AutoRegistrationDomains->next;		// Cut record from list FIRST,
2087 		DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
2088 		udsserver_default_reg_domain_changed(del, mDNSfalse);			// before calling udsserver_default_reg_domain_changed()
2089 		mDNSPlatformMemFree(del);
2090 		}
2091 
2092 	// Now we have our new updated automatic registration domain list
2093 	AutoRegistrationDomains = RegDomains;
2094 
2095 	// Add new browse domains to internal list
2096 	if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
2097 
2098 	// Remove old browse domains from internal list
2099 	if (SCPrefBrowseDomains)
2100 		{
2101 		SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
2102 		while (SCPrefBrowseDomains)
2103 			{
2104 			DNameListElem *fptr = SCPrefBrowseDomains;
2105 			SCPrefBrowseDomains = SCPrefBrowseDomains->next;
2106 			mDNSPlatformMemFree(fptr);
2107 			}
2108 		}
2109 
2110 	// Replace the old browse domains array with the new array
2111 	SCPrefBrowseDomains = BrowseDomains;
2112 	}
2113 
AutomaticBrowseDomainChange(mDNS * const m,DNSQuestion * q,const ResourceRecord * const answer,QC_result AddRecord)2114 mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
2115 	{
2116 	(void)m; // unused;
2117 	(void)q; // unused
2118 
2119 	LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2120 		AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
2121 
2122 	if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
2123 	else           RmvAutoBrowseDomain(0, &answer->rdata->u.name);
2124 	}
2125 
handle_sethost_request(request_state * request)2126 mDNSlocal mStatus handle_sethost_request(request_state *request)
2127 {
2128 	get_flags(&request->msgptr, request->msgend);
2129 	char hostName[MAX_DOMAIN_LABEL];
2130 	int len = 0;
2131 	if (get_string(&request->msgptr, request->msgend, hostName,
2132 		MAX_DOMAIN_LABEL) < 0) return (mStatus_BadParamErr);
2133 	LogOperation("%3d: DNSSetHostname(%X, %d, nonstr ) START",
2134 		request->sd, request->flags);
2135 	// if we start using this as a callback for notification when the
2136 	// hostname changes we may need to cleanup from it
2137 	//  request->terminate = sethost_termination_callback;
2138 	if(hostName[0] == 0) return mStatus_BadParamErr;
2139 		while (len < MAX_DOMAIN_LABEL && hostName[len+1]
2140 			&& hostName[len+1] != '.') len++;
2141 	strncpy(&(mDNSStorage.nicelabel.c[1]), hostName, len);
2142 	mDNSStorage.nicelabel.c[0] = len;
2143 	strncpy(&(mDNSStorage.hostlabel.c[1]), hostName, len);
2144 	mDNSStorage.hostlabel.c[0] = len;
2145 	mDNS_SetFQDN(&mDNSStorage);
2146 	return mStatus_NoError;
2147 }
2148 
handle_browse_request(request_state * request)2149 mDNSlocal mStatus handle_browse_request(request_state *request)
2150 	{
2151 	char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2152 	domainname typedn, d, temp;
2153 	mDNSs32 NumSubTypes;
2154 	mStatus err = mStatus_NoError;
2155 
2156 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2157 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2158 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2159 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
2160 
2161 	if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2162 		get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
2163 
2164 	if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2165 
2166 	if (domain[0] == '\0') uDNS_SetupSearchDomains(&mDNSStorage, UDNS_START_WAB_QUERY);
2167 
2168 	request->flags = flags;
2169 	typedn.c[0] = 0;
2170 	NumSubTypes = ChopSubTypes(regtype);	// Note: Modifies regtype string to remove trailing subtypes
2171 	if (NumSubTypes < 0 || NumSubTypes > 1) return(mStatus_BadParamErr);
2172 	if (NumSubTypes == 1 && !AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1)) return(mStatus_BadParamErr);
2173 
2174 	if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
2175 
2176 	if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
2177 	// For over-long service types, we only allow domain "local"
2178 	if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrLCopy(domain, "local.", sizeof(domain));
2179 
2180 	// Set up browser info
2181 	request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
2182 	request->u.browser.interface_id = InterfaceID;
2183 	AssignDomainName(&request->u.browser.regtype, &typedn);
2184 	request->u.browser.default_domain = !domain[0];
2185 	request->u.browser.browsers = NULL;
2186 
2187 	LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START",
2188 			request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain);
2189 
2190 	// We need to unconditionally set request->terminate, because even if we didn't successfully
2191 	// start any browses right now, subsequent configuration changes may cause successful
2192 	// browses to be added, and we'll need to cancel them before freeing this memory.
2193 	request->terminate = browse_termination_callback;
2194 
2195 	if (domain[0])
2196 		{
2197 		if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
2198 		err = add_domain_to_browser(request, &d);
2199 #if 0
2200 		err = AuthorizedDomain(request, &d, AutoBrowseDomains) ? add_domain_to_browser(request, &d) : mStatus_NoError;
2201 #endif
2202 		}
2203 	else
2204 		{
2205 		DNameListElem *sdom;
2206 		for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
2207 			if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
2208 				{
2209 				err = add_domain_to_browser(request, &sdom->name);
2210 				if (err)
2211 					{
2212 					if (SameDomainName(&sdom->name, &localdomain)) break;
2213 					else err = mStatus_NoError;  // suppress errors for non-local "default" domains
2214 					}
2215 				}
2216 		}
2217 
2218 	return(err);
2219 	}
2220 
2221 // ***************************************************************************
2222 #if COMPILER_LIKES_PRAGMA_MARK
2223 #pragma mark -
2224 #pragma mark - DNSServiceResolve
2225 #endif
2226 
resolve_result_callback(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)2227 mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2228 	{
2229 	size_t len = 0;
2230 	char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME];
2231 	char *data;
2232 	reply_state *rep;
2233 	request_state *req = question->QuestionContext;
2234 	(void)m; // Unused
2235 
2236 	LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req->sd, question->qname.c, AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
2237 
2238 	if (!AddRecord)
2239 		{
2240 		if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
2241 		if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
2242 		return;
2243 		}
2244 
2245 	if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
2246 	if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
2247 
2248 	if (!req->u.resolve.txt || !req->u.resolve.srv) return;		// only deliver result to client if we have both answers
2249 
2250 	ConvertDomainNameToCString(answer->name, fullname);
2251 	ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
2252 
2253 	// calculate reply length
2254 	len += sizeof(DNSServiceFlags);
2255 	len += sizeof(mDNSu32);  // interface index
2256 	len += sizeof(DNSServiceErrorType);
2257 	len += strlen(fullname) + 1;
2258 	len += strlen(target) + 1;
2259 	len += 2 * sizeof(mDNSu16);  // port, txtLen
2260 	len += req->u.resolve.txt->rdlength;
2261 
2262 	// allocate/init reply header
2263 	rep = create_reply(resolve_reply_op, len, req);
2264 	rep->rhdr->flags = dnssd_htonl(0);
2265 	rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
2266 	rep->rhdr->error = dnssd_htonl(kDNSServiceErr_NoError);
2267 
2268 	data = (char *)&rep->rhdr[1];
2269 
2270 	// write reply data to message
2271 	put_string(fullname, &data);
2272 	put_string(target, &data);
2273 	*data++ =  req->u.resolve.srv->rdata->u.srv.port.b[0];
2274 	*data++ =  req->u.resolve.srv->rdata->u.srv.port.b[1];
2275 	put_uint16(req->u.resolve.txt->rdlength, &data);
2276 	put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
2277 
2278 	LogOperation("%3d: DNSServiceResolve(%s) RESULT   %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
2279 	append_reply(req, rep);
2280 	}
2281 
resolve_termination_callback(request_state * request)2282 mDNSlocal void resolve_termination_callback(request_state *request)
2283 	{
2284 	LogOperation("%3d: DNSServiceResolve(%##s) STOP", request->sd, request->u.resolve.qtxt.qname.c);
2285 	mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
2286 	mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2287 	if (request->u.resolve.external_advertise) external_stop_resolving_service(&request->u.resolve.qsrv.qname);
2288 	}
2289 
handle_resolve_request(request_state * request)2290 mDNSlocal mStatus handle_resolve_request(request_state *request)
2291 	{
2292 	char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2293 	domainname fqdn;
2294 	mStatus err;
2295 
2296 	// extract the data from the message
2297 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2298 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2299 	mDNSInterfaceID InterfaceID;
2300 	mDNSBool wasP2P = (interfaceIndex == kDNSServiceInterfaceIndexP2P);
2301 
2302 
2303 	request->flags = flags;
2304 	if (wasP2P) interfaceIndex = kDNSServiceInterfaceIndexAny;
2305 
2306 	InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2307 	if (interfaceIndex && !InterfaceID)
2308 		{ LogMsg("ERROR: handle_resolve_request bad interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); }
2309 
2310 	if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
2311 		get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2312 		get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
2313 		{ LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2314 
2315 	if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2316 
2317 	if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
2318 		{ LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
2319 
2320 	mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
2321 
2322 	// format questions
2323 	request->u.resolve.qsrv.InterfaceID      = InterfaceID;
2324 	request->u.resolve.qsrv.Target           = zeroAddr;
2325 	AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
2326 	request->u.resolve.qsrv.qtype            = kDNSType_SRV;
2327 	request->u.resolve.qsrv.qclass           = kDNSClass_IN;
2328 	request->u.resolve.qsrv.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2329 	request->u.resolve.qsrv.ExpectUnique     = mDNStrue;
2330 	request->u.resolve.qsrv.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
2331 	request->u.resolve.qsrv.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2332 	request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
2333 	request->u.resolve.qsrv.SearchListIndex  = 0;
2334 	request->u.resolve.qsrv.AppendSearchDomains = 0;
2335 	request->u.resolve.qsrv.RetryWithSearchDomains = mDNSfalse;
2336 	request->u.resolve.qsrv.TimeoutQuestion  = 0;
2337 	request->u.resolve.qsrv.WakeOnResolve    = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
2338 	request->u.resolve.qsrv.qnameOrig        = mDNSNULL;
2339 	request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
2340 	request->u.resolve.qsrv.QuestionContext  = request;
2341 
2342 	request->u.resolve.qtxt.InterfaceID      = InterfaceID;
2343 	request->u.resolve.qtxt.Target           = zeroAddr;
2344 	AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn);
2345 	request->u.resolve.qtxt.qtype            = kDNSType_TXT;
2346 	request->u.resolve.qtxt.qclass           = kDNSClass_IN;
2347 	request->u.resolve.qtxt.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2348 	request->u.resolve.qtxt.ExpectUnique     = mDNStrue;
2349 	request->u.resolve.qtxt.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
2350 	request->u.resolve.qtxt.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2351 	request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
2352 	request->u.resolve.qtxt.SearchListIndex  = 0;
2353 	request->u.resolve.qtxt.AppendSearchDomains = 0;
2354 	request->u.resolve.qtxt.RetryWithSearchDomains = mDNSfalse;
2355 	request->u.resolve.qtxt.TimeoutQuestion  = 0;
2356 	request->u.resolve.qtxt.WakeOnResolve    = 0;
2357 	request->u.resolve.qtxt.qnameOrig        = mDNSNULL;
2358 	request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
2359 	request->u.resolve.qtxt.QuestionContext  = request;
2360 
2361 	request->u.resolve.ReportTime            = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
2362 
2363 	request->u.resolve.external_advertise    = mDNSfalse;
2364 
2365 #if 0
2366 	if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains))	return(mStatus_NoError);
2367 #endif
2368 
2369 	// ask the questions
2370 	LogOperation("%3d: DNSServiceResolve(%##s) START", request->sd, request->u.resolve.qsrv.qname.c);
2371 	err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);
2372 	if (!err)
2373 		{
2374 		err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
2375 		if (err) mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2376 		else
2377 			{
2378 			request->terminate = resolve_termination_callback;
2379 			// If the user explicitly passed in P2P, we don't restrict the domain in which we resolve.
2380 			if (wasP2P || (!InterfaceID && IsLocalDomain(&fqdn) && (request->flags & kDNSServiceFlagsIncludeP2P)))
2381 				{
2382 				request->u.resolve.external_advertise    = mDNStrue;
2383 				LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2384 				external_start_resolving_service(&fqdn);
2385 				}
2386 			}
2387 		}
2388 
2389 	return(err);
2390 	}
2391 
2392 // ***************************************************************************
2393 #if COMPILER_LIKES_PRAGMA_MARK
2394 #pragma mark -
2395 #pragma mark - DNSServiceQueryRecord
2396 #endif
2397 
2398 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2399 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2400 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2401 // the mDNSCore operation if the client dies or closes its socket.
2402 
2403 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2404 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2405 // Returns 0 when there are no more search domains and the caller should reissue the query
AppendNewSearchDomain(mDNS * const m,DNSQuestion * question)2406 mDNSlocal int AppendNewSearchDomain(mDNS *const m, DNSQuestion *question)
2407 	{
2408 	domainname *sd;
2409 	mStatus err;
2410 
2411 	// Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2412 	// the domains and should try the single label query directly on the wire.
2413 	if (question->SearchListIndex == -1)
2414 		{
2415 		LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question->qname.c, DNSTypeName(question->qtype));
2416 		return -1;
2417 		}
2418 
2419 	if (!question->AppendSearchDomains)
2420 		{
2421 		LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question->qname.c, DNSTypeName(question->qtype));
2422 		return -1;
2423 		}
2424 
2425 	// Save the original name, before we modify them below.
2426 	if (!question->qnameOrig)
2427 		{
2428 		question->qnameOrig =  mallocL("AppendNewSearchDomain", sizeof(domainname));
2429 		if (!question->qnameOrig) { LogMsg("AppendNewSearchDomain: ERROR!!  malloc failure"); return -1; }
2430 		question->qnameOrig->c[0] = 0;
2431 		AssignDomainName(question->qnameOrig, &question->qname);
2432 		LogInfo("AppendSearchDomain: qnameOrig %##s", question->qnameOrig->c);
2433 		}
2434 
2435 	sd = uDNS_GetNextSearchDomain(m, question->InterfaceID, &question->SearchListIndex, !question->AppendLocalSearchDomains);
2436 	// We use -1 to indicate that we have searched all the domains and should try the single label
2437 	// query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2438 	if (question->SearchListIndex == -1)
2439 		{
2440 		LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2441 		return -1;
2442 		}
2443 
2444 	// Not a common case. Perhaps, we should try the next search domain if it exceeds ?
2445 	if (sd && (DomainNameLength(question->qnameOrig) + DomainNameLength(sd)) > MAX_DOMAIN_NAME)
2446 		{
2447 		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));
2448 		return -1;
2449 		}
2450 
2451 	// if there are no more search domains and we have already tried this question
2452 	// without appending search domains, then we are done.
2453 	if (!sd && !ApplySearchDomainsFirst(question))
2454 		{
2455 		LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question->qname.c, DNSTypeName(question->qtype));
2456 		return -1;
2457 		}
2458 
2459 	// Stop the question before changing the name as negative cache entries could be pointing at this question.
2460 	// Even if we don't change the question in the case of returning 0, the caller is going to restart the
2461 	// question.
2462 	err = mDNS_StopQuery(&mDNSStorage, question);
2463 	if (err) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question->qname.c, DNSTypeName(question->qtype), (int)err); }
2464 
2465 	AssignDomainName(&question->qname, question->qnameOrig);
2466 	if (sd)
2467 		{
2468 		AppendDomainName(&question->qname, sd);
2469 		LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question->qname.c, question->SearchListIndex);
2470 		return 1;
2471 		}
2472 
2473 	// Try the question as single label
2474 	LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question->qname.c, DNSTypeName(question->qtype));
2475 	return 0;
2476 	}
2477 
2478 #if APPLE_OSX_mDNSResponder
2479 
DomainInSearchList(domainname * domain)2480 mDNSlocal mDNSBool DomainInSearchList(domainname *domain)
2481 	{
2482 	const SearchListElem *s;
2483  	for (s=SearchList; s; s=s->next)
2484 		if (SameDomainName(&s->domain, domain)) return mDNStrue;
2485 	return mDNSfalse;
2486 	}
2487 
2488 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
2489 // top-level domain
SendAdditionalQuery(DNSQuestion * q,request_state * request,mStatus err)2490 mDNSlocal mStatus SendAdditionalQuery(DNSQuestion *q, request_state *request, mStatus err)
2491 	{
2492 	extern domainname ActiveDirectoryPrimaryDomain;
2493 	DNSQuestion **question2;
2494 	#define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
2495 	#define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
2496 
2497 	question2 = mDNSNULL;
2498 	if (request->hdr.op == query_request)
2499 		question2 = &request->u.queryrecord.q2;
2500 	else if (request->hdr.op == addrinfo_request)
2501 		{
2502 		if (q->qtype == kDNSType_A)
2503 			question2 = &request->u.addrinfo.q42;
2504 		else if (q->qtype == kDNSType_AAAA)
2505 			question2 = &request->u.addrinfo.q62;
2506 		}
2507 	if (!question2)
2508 		{
2509 		LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2510 		return mStatus_BadParamErr;
2511 		}
2512 
2513 	// Sanity check: If we already sent an additonal query, we don't need to send one more.
2514 	//
2515 	// 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
2516 	// is called to see whether a unicast query should be sent or not.
2517 	//
2518 	// 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
2519 	// was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
2520 	// send the additional query.
2521 	//
2522 	// Thus, it should not be called more than once.
2523 	if (*question2)
2524 		{
2525 		LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q->qname.c, DNSTypeName(q->qtype));
2526 		return err;
2527 		}
2528 
2529 	if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
2530 		if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q))
2531 			{
2532 			DNSQuestion *q2;
2533 			int labels = CountLabels(&q->qname);
2534 			q2 = mallocL("DNSQuestion", sizeof(DNSQuestion));
2535 			if (!q2) FatalError("ERROR: SendAdditionalQuery malloc");
2536 			*question2        = q2;
2537 			*q2               = *q;
2538 			q2->InterfaceID   = mDNSInterface_Unicast;
2539 			q2->ExpectUnique  = mDNStrue;
2540 			// If the query starts as a single label e.g., somehost, and we have search domains with .local,
2541 			// queryrecord_result_callback calls this function when .local is appended to "somehost".
2542 			// At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
2543 			// "somehost". We need to copy that information so that when we retry with a different search
2544 			// domain e.g., mycompany.local, we get "somehost.mycompany.local".
2545 			if (q->qnameOrig)
2546 				{
2547 				(*question2)->qnameOrig =  mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
2548 				if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!!  malloc failure"); return mStatus_NoMemoryErr; }
2549 				(*question2)->qnameOrig->c[0] = 0;
2550 				AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
2551 				LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
2552 				}
2553 			// For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
2554 			// For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
2555 			// If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
2556 			// "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
2557 			// then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
2558 			// site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
2559 			// for names in the "local" domain will be safely answered privately before they hit the root name servers.
2560 			// Note that in the "my-small-company.local" example above there will typically be an SOA record for
2561 			// "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
2562 			// We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
2563 			// of those, we don't want do the SOA check for the local
2564 			if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname))
2565 				{
2566 				AssignDomainName(&q2->qname, &localdomain);
2567 				q2->qtype          = kDNSType_SOA;
2568 				q2->LongLived      = mDNSfalse;
2569 				q2->ForceMCast     = mDNSfalse;
2570 				q2->ReturnIntermed = mDNStrue;
2571 				// Don't append search domains for the .local SOA query
2572 				q2->AppendSearchDomains = 0;
2573 				q2->AppendLocalSearchDomains = 0;
2574 				q2->RetryWithSearchDomains = mDNSfalse;
2575 				q2->SearchListIndex = 0;
2576 				q2->TimeoutQuestion = 0;
2577 				}
2578 			LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
2579 			err = mDNS_StartQuery(&mDNSStorage, q2);
2580 			if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
2581 			}
2582 	return(err);
2583 	}
2584 #endif // APPLE_OSX_mDNSResponder
2585 
2586 // This function tries to append a search domain if valid and possible. If so, returns true.
RetryQuestionWithSearchDomains(mDNS * const m,DNSQuestion * question,request_state * req)2587 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(mDNS *const m, DNSQuestion *question, request_state *req)
2588 	{
2589 	int result;
2590 	// RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
2591 	// answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
2592 	// that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
2593 	// RetryWithSearchDomains which may or may not be set.
2594 	//
2595 	// If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
2596 	// is a valid question for appending search domains, retry by appending domains
2597 
2598 	if (!question->SuppressQuery && question->SearchListIndex != -1 && question->AppendSearchDomains)
2599 		{
2600 		question->RetryWithSearchDomains = 0;
2601 		result = AppendNewSearchDomain(m, question);
2602 		// As long as the result is either zero or 1, we retry the question. If we exahaust the search
2603 		// domains (result is zero) we try the original query (as it was before appending the search
2604 		// domains) as such on the wire as a last resort if we have not tried them before. For queries
2605 		// with more than one label, we have already tried them before appending search domains and
2606 		// hence don't retry again
2607 		if (result != -1)
2608 			{
2609 			mStatus err;
2610 			err = mDNS_StartQuery(m, question);
2611 			if (!err)
2612 				{
2613 				LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
2614 				// If the result was zero, it meant that there are no search domains and we just retried the question
2615 				// as a single label and we should not retry with search domains anymore.
2616 				if (!result) question->SearchListIndex = -1;
2617 				return mDNStrue;
2618 				}
2619 			else
2620 				{
2621 				LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
2622 				// We have already stopped the query and could not restart. Reset the appropriate pointers
2623 				// so that we don't call stop again when the question terminates
2624 				question->QuestionContext = mDNSNULL;
2625 				}
2626 			}
2627 		}
2628 	else
2629 		{
2630 		LogInfo("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, question->SuppressQuery, question->SearchListIndex, question->AppendSearchDomains);
2631 		}
2632 	return mDNSfalse;
2633 	}
2634 
queryrecord_result_callback(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)2635 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2636 	{
2637 	char name[MAX_ESCAPED_DOMAIN_NAME];
2638 	request_state *req = question->QuestionContext;
2639 	reply_state *rep;
2640 	char *data;
2641 	size_t len;
2642 	DNSServiceErrorType error = kDNSServiceErr_NoError;
2643 	DNSQuestion *q = mDNSNULL;
2644 
2645 #if APPLE_OSX_mDNSResponder
2646 	{
2647 	// Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
2648 	// get any callbacks from the core after this.
2649 	if (!req)
2650 		{
2651 		LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
2652 		return;
2653 		}
2654 	if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
2655 		q = &req->u.queryrecord.q;
2656 	else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
2657 		q = &req->u.addrinfo.q4;
2658 	else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
2659 		q = &req->u.addrinfo.q6;
2660 
2661 	if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
2662 		{
2663 		mStatus err;
2664 		domainname *orig = question->qnameOrig;
2665 
2666 		LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
2667 		mDNS_StopQuery(m, question);
2668 		question->QuestionContext = mDNSNULL;
2669 
2670 		// We got a negative response for the SOA record indicating that .local does not exist.
2671 		// But we might have other search domains (that does not end in .local) that can be
2672 		// appended to this question. In that case, we want to retry the question. Otherwise,
2673 		// we don't want to try this question as unicast.
2674 		if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
2675 			{
2676 			LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
2677 			return;
2678 			}
2679 
2680 		// If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
2681 		//
2682 		// Note: When we copy the original question, we copy everything including the AppendSearchDomains,
2683 		// RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
2684 		// e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
2685 		// SendAdditionalQuery as to how qnameOrig gets initialized.
2686 		*question              = *q;
2687 		question->InterfaceID  = mDNSInterface_Unicast;
2688 		question->ExpectUnique = mDNStrue;
2689 		question->qnameOrig    = orig;
2690 
2691 		LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
2692 
2693 		// If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
2694 		// Hence, we need to set it explicitly here.
2695 		question->QuestionContext = req;
2696 		err = mDNS_StartQuery(m, question);
2697 		if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
2698 
2699 		// If we got a positive response to local SOA, then try the .local question as unicast
2700 		if (answer->RecordType != kDNSRecordTypePacketNegative) return;
2701 
2702 		// Fall through and get the next search domain. The question is pointing at .local
2703 		// and we don't want to try that. Try the next search domain. Don't try with local
2704 		// search domains for the unicast question anymore.
2705 		//
2706 		// Note: we started the question above which will be stopped immediately (never sent on the wire)
2707 		// before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
2708 		// question has already started.
2709 		question->AppendLocalSearchDomains = 0;
2710 		}
2711 
2712 	if (q && AddRecord && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
2713 		{
2714 		// If we get a negative response to the unicast query that we sent above, retry after appending search domains
2715 		// Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
2716 		// As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
2717 		// To keep things simple, we handle unicast ".local" separately here.
2718 		LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
2719 		if (RetryQuestionWithSearchDomains(m, question, req))
2720 			return;
2721 		if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
2722 			{
2723 			// If "local" is the last search domain, we need to stop the question so that we don't send the "local"
2724 			// question on the wire as we got a negative response for the local SOA. But, we can't stop the question
2725 			// yet as we may have to timeout the question (done by the "core") for which we need to leave the question
2726 			// in the list. We leave it disabled so that it does not hit the wire.
2727 			LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
2728 			question->ThisQInterval = 0;
2729 			}
2730 		}
2731 	// 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
2732 	// domains to append for "q2". In all cases, fall through and deliver the response
2733 	}
2734 #endif // APPLE_OSX_mDNSResponder
2735 
2736 	if (answer->RecordType == kDNSRecordTypePacketNegative)
2737 		{
2738 		// If this question needs to be timed out and we have reached the stop time, mark
2739 		// the error as timeout. It is possible that we might get a negative response from an
2740 		// external DNS server at the same time when this question reaches its stop time. We
2741 		// can't tell the difference as there is no indication in the callback. This should
2742 		// be okay as we will be timing out this query anyway.
2743 		mDNS_Lock(m);
2744 		if (question->TimeoutQuestion)
2745 			{
2746 			if ((m->timenow - question->StopTime) >= 0)
2747 				{
2748 				LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2749 				error = kDNSServiceErr_Timeout;
2750 				}
2751 			}
2752 		mDNS_Unlock(m);
2753 		// When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
2754 		// Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
2755 		// answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
2756 		// server is going to assert that pretty much every single multicast name doesn't exist.
2757 		//
2758 		// If we are timing out this query, we need to deliver the negative answer to the application
2759 		if (error != kDNSServiceErr_Timeout)
2760 			{
2761 			if (!answer->InterfaceID && IsLocalDomain(answer->name))
2762 				{
2763 				LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with unicast", question->qname.c, DNSTypeName(question->qtype));
2764 				return;
2765 				}
2766 			error = kDNSServiceErr_NoSuchRecord;
2767 			}
2768 		AddRecord = mDNStrue;
2769 		}
2770 	// If we get a negative answer, try appending search domains. Don't append search domains
2771 	// - if we are timing out this question
2772 	// - if the negative response was received as a result of a multicast query
2773 	// - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
2774 	if (error != kDNSServiceErr_Timeout)
2775 		{
2776 		if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord)
2777 			{
2778 			// If the original question did not end in .local, we did not send an SOA query
2779 			// to figure out whether we should send an additional unicast query or not. If we just
2780 			// appended .local, we need to see if we need to send an additional query. This should
2781 			// normally happen just once because after we append .local, we ignore all negative
2782 			// responses for .local above.
2783 			LogInfo("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
2784 			if (RetryQuestionWithSearchDomains(m, question, req))
2785 				{
2786 				// Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
2787 				// be anywhere in the search domain list.
2788 #if APPLE_OSX_mDNSResponder
2789 				mStatus err = mStatus_NoError;
2790 				err = SendAdditionalQuery(question, req, err);
2791 				if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
2792 #endif // APPLE_OSX_mDNSResponder
2793 				return;
2794 				}
2795 			}
2796 		}
2797 
2798 	ConvertDomainNameToCString(answer->name, name);
2799 
2800 	LogOperation("%3d: %s(%##s, %s) %s %s", req->sd,
2801 		req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
2802 		question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
2803 
2804 	len = sizeof(DNSServiceFlags);	// calculate reply data length
2805 	len += sizeof(mDNSu32);		// interface index
2806 	len += sizeof(DNSServiceErrorType);
2807 	len += strlen(name) + 1;
2808 	len += 3 * sizeof(mDNSu16);	// type, class, rdlen
2809 	len += answer->rdlength;
2810 	len += sizeof(mDNSu32);		// TTL
2811 
2812 	rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
2813 
2814 	rep->rhdr->flags = dnssd_htonl(AddRecord ? kDNSServiceFlagsAdd : 0);
2815 	// Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
2816 	// InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
2817 	// to be stopped and started including  *this* one. Normally the InterfaceID is valid. But when we
2818 	// are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
2819 	// mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
2820 	// mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
2821 	// should not have existed to answer this question if the corresponding interface is not valid.
2822 	rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
2823 	rep->rhdr->error = dnssd_htonl(error);
2824 
2825 	data = (char *)&rep->rhdr[1];
2826 
2827 	put_string(name,             &data);
2828 	put_uint16(answer->rrtype,   &data);
2829 	put_uint16(answer->rrclass,  &data);
2830 	put_uint16(answer->rdlength, &data);
2831 	// We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2832 	// function just does a blind memory copy without regard to structures that may have holes in them.
2833 	if (answer->rdlength)
2834 		if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
2835 			LogMsg("queryrecord_result_callback putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
2836 	data += answer->rdlength;
2837 	put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
2838 
2839 	append_reply(req, rep);
2840 	// Stop the question, if we just timed out
2841 	if (error == kDNSServiceErr_Timeout)
2842 		{
2843 		mDNS_StopQuery(m, question);
2844 		// Reset the pointers so that we don't call stop on termination
2845 		question->QuestionContext = mDNSNULL;
2846 		}
2847 #if APPLE_OSX_mDNSResponder
2848 #if ! NO_WCF
2849 	CHECK_WCF_FUNCTION(WCFIsServerRunning)
2850 		{
2851 		struct xucred x;
2852 		socklen_t xucredlen = sizeof(x);
2853 
2854 		if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
2855 			{
2856 			if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
2857 				(x.cr_version == XUCRED_VERSION))
2858 				{
2859 				struct sockaddr_storage addr;
2860 				const RDataBody2 *const rdb = (RDataBody2 *)answer->rdata->u.data;
2861 				addr.ss_len = 0;
2862 				if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
2863 					{
2864 					if (answer->rrtype == kDNSType_A)
2865 						{
2866 						struct sockaddr_in *sin = (struct sockaddr_in *)&addr;
2867 						sin->sin_port = 0;
2868 						if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(rdb->ipv4)), answer))
2869 							LogMsg("queryrecord_result_callback: WCF AF_INET putRData failed");
2870 						else
2871 							{
2872 							addr.ss_len = sizeof (struct sockaddr_in);
2873 							addr.ss_family = AF_INET;
2874 							}
2875 						}
2876 					else if (answer->rrtype == kDNSType_AAAA)
2877 						{
2878 						struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&addr;
2879 						sin6->sin6_port = 0;
2880 						if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(rdb->ipv6)), answer))
2881 							LogMsg("queryrecord_result_callback: WCF AF_INET6 putRData failed");
2882 						else
2883 							{
2884 							addr.ss_len = sizeof (struct sockaddr_in6);
2885 							addr.ss_family = AF_INET6;
2886 							}
2887 						}
2888 					if (addr.ss_len)
2889 						{
2890 						debugf("queryrecord_result_callback: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
2891 						CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
2892 							{
2893 							WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
2894 							}
2895 						}
2896 					}
2897 				else if (answer->rrtype == kDNSType_CNAME)
2898 					{
2899 					domainname cname;
2900 					char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
2901 					if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
2902 							LogMsg("queryrecord_result_callback: WCF CNAME putRData failed");
2903 					else
2904 						{
2905 						ConvertDomainNameToCString(&cname, cname_cstr);
2906 						CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
2907 							{
2908 							WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
2909 							}
2910 						}
2911 					}
2912 				}
2913 			else my_perror("queryrecord_result_callback: ERROR: getsockopt LOCAL_PEERCRED");
2914 			}
2915 		}
2916 #endif
2917 #endif
2918 	}
2919 
queryrecord_termination_callback(request_state * request)2920 mDNSlocal void queryrecord_termination_callback(request_state *request)
2921 	{
2922 	LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP",
2923 		request->sd, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype));
2924 	if (request->u.queryrecord.q.QuestionContext)
2925 		{
2926 		mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q);  // no need to error check
2927 		request->u.queryrecord.q.QuestionContext = mDNSNULL;
2928 		}
2929 	else
2930 		{
2931 		DNSQuestion *question = &request->u.queryrecord.q;
2932 		LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2933 		}
2934 
2935 	if (request->u.queryrecord.q.qnameOrig)
2936 		{
2937 		freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
2938 		request->u.queryrecord.q.qnameOrig = mDNSNULL;
2939 		}
2940 	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)))
2941 		{
2942 		LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
2943 		external_stop_browsing_for_service(&mDNSStorage, &request->u.queryrecord.q.qname, request->u.queryrecord.q.qtype);
2944 		}
2945   	if (request->u.queryrecord.q2)
2946   		{
2947  		if (request->u.queryrecord.q2->QuestionContext)
2948  			{
2949  			LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
2950  			mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
2951  			}
2952 		else
2953 			{
2954 			DNSQuestion *question = request->u.queryrecord.q2;
2955 			LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2956 			}
2957  		if (request->u.queryrecord.q2->qnameOrig)
2958  			{
2959  			LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
2960  			freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
2961  			request->u.queryrecord.q2->qnameOrig = mDNSNULL;
2962  			}
2963   		freeL("queryrecord Q2", request->u.queryrecord.q2);
2964   		request->u.queryrecord.q2 = mDNSNULL;
2965   		}
2966 	}
2967 
handle_queryrecord_request(request_state * request)2968 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
2969 	{
2970 	DNSQuestion *const q = &request->u.queryrecord.q;
2971 	char name[256];
2972 	mDNSu16 rrtype, rrclass;
2973 	mStatus err;
2974 
2975 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2976 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2977 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2978 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
2979 
2980 	if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
2981 	rrtype  = get_uint16(&request->msgptr, request->msgend);
2982 	rrclass = get_uint16(&request->msgptr, request->msgend);
2983 
2984 	if (!request->msgptr)
2985 		{ LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2986 
2987 	request->flags = flags;
2988 	mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
2989 
2990 	q->InterfaceID      = InterfaceID;
2991 	q->Target           = zeroAddr;
2992 	if (!MakeDomainNameFromDNSNameString(&q->qname, name)) 			return(mStatus_BadParamErr);
2993 #if 0
2994 	if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains))	return (mStatus_NoError);
2995 #endif
2996 	q->qtype            = rrtype;
2997 	q->qclass           = rrclass;
2998 	q->LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2999 	q->ExpectUnique     = mDNSfalse;
3000 	q->ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
3001 	q->ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3002 	q->SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable   ) != 0;
3003 	q->TimeoutQuestion  = (flags & kDNSServiceFlagsTimeout            ) != 0;
3004 	q->WakeOnResolve    = 0;
3005 	q->QuestionCallback = queryrecord_result_callback;
3006 	q->QuestionContext  = request;
3007 	q->SearchListIndex  = 0;
3008 
3009 	// Don't append search domains for fully qualified domain names including queries
3010 	// such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3011 	// we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3012 	// append search domains or not.  So, we record that information in AppendSearchDomains.
3013 	//
3014 	// We append search domains only for queries that are a single label. If overriden using
3015 	// command line argument "AlwaysAppendSearchDomains", then we do it for any query which
3016 	// is not fully qualified.
3017 
3018 	if ((rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && name[strlen(name) - 1] != '.' &&
3019 		(AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3020 		{
3021 		q->AppendSearchDomains = 1;
3022 		q->AppendLocalSearchDomains = 1;
3023 		}
3024 	else
3025 		{
3026 		q->AppendSearchDomains = 0;
3027 		q->AppendLocalSearchDomains = 0;
3028 		}
3029 
3030 	// For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3031 	// search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3032 	// tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3033 	// the cache
3034 	q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3035 	q->qnameOrig        = mDNSNULL;
3036 
3037 	LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START", request->sd, flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype));
3038 	err = mDNS_StartQuery(&mDNSStorage, q);
3039 	if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3040 	else
3041 		{
3042 		request->terminate = queryrecord_termination_callback;
3043 		if (q->InterfaceID == mDNSInterface_P2P || (!q->InterfaceID && SameDomainName((const domainname *)LastLabel(&q->qname), &localdomain) && (flags & kDNSServiceFlagsIncludeP2P)))
3044 			{
3045 			LogInfo("handle_queryrecord_request: calling external_start_browsing_for_service()");
3046 			external_start_browsing_for_service(&mDNSStorage, &q->qname, q->qtype);
3047 			}
3048 		}
3049 
3050 #if APPLE_OSX_mDNSResponder
3051 	err = SendAdditionalQuery(q, request, err);
3052 #endif // APPLE_OSX_mDNSResponder
3053 
3054 	return(err);
3055 	}
3056 
3057 // ***************************************************************************
3058 #if COMPILER_LIKES_PRAGMA_MARK
3059 #pragma mark -
3060 #pragma mark - DNSServiceEnumerateDomains
3061 #endif
3062 
format_enumeration_reply(request_state * request,const char * domain,DNSServiceFlags flags,mDNSu32 ifi,DNSServiceErrorType err)3063 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3064 	const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3065 	{
3066 	size_t len;
3067 	reply_state *reply;
3068 	char *data;
3069 
3070 	len = sizeof(DNSServiceFlags);
3071 	len += sizeof(mDNSu32);
3072 	len += sizeof(DNSServiceErrorType);
3073 	len += strlen(domain) + 1;
3074 
3075 	reply = create_reply(enumeration_reply_op, len, request);
3076 	reply->rhdr->flags = dnssd_htonl(flags);
3077 	reply->rhdr->ifi   = dnssd_htonl(ifi);
3078 	reply->rhdr->error = dnssd_htonl(err);
3079 	data = (char *)&reply->rhdr[1];
3080 	put_string(domain, &data);
3081 	return reply;
3082 	}
3083 
enum_termination_callback(request_state * request)3084 mDNSlocal void enum_termination_callback(request_state *request)
3085 	{
3086 	mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3087 	mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3088 	}
3089 
enum_result_callback(mDNS * const m,DNSQuestion * const question,const ResourceRecord * const answer,QC_result AddRecord)3090 mDNSlocal void enum_result_callback(mDNS *const m,
3091 	DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3092 	{
3093 	char domain[MAX_ESCAPED_DOMAIN_NAME];
3094 	request_state *request = question->QuestionContext;
3095 	DNSServiceFlags flags = 0;
3096 	reply_state *reply;
3097 	(void)m; // Unused
3098 
3099 	if (answer->rrtype != kDNSType_PTR) return;
3100 
3101 #if 0
3102 	if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3103 #endif
3104 
3105 	// We only return add/remove events for the browse and registration lists
3106 	// For the default browse and registration answers, we only give an "ADD" event
3107 	if (question == &request->u.enumeration.q_default && !AddRecord) return;
3108 
3109 	if (AddRecord)
3110 		{
3111 		flags |= kDNSServiceFlagsAdd;
3112 		if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3113 		}
3114 
3115 	ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3116 	// Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3117 	// a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3118 	// network, so we just pass kDNSServiceInterfaceIndexAny
3119 	reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3120 	if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3121 
3122 	LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "Add" : "Rmv", domain);
3123 
3124 	append_reply(request, reply);
3125 	}
3126 
handle_enum_request(request_state * request)3127 mDNSlocal mStatus handle_enum_request(request_state *request)
3128 	{
3129 	mStatus err;
3130 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3131 	DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3132 	mDNS_DomainType t_all     = reg ? mDNS_DomainTypeRegistration        : mDNS_DomainTypeBrowse;
3133 	mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3134 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3135 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3136 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3137 
3138 	if (!request->msgptr)
3139 		{ LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3140 
3141 	// allocate context structures
3142 	uDNS_SetupSearchDomains(&mDNSStorage, UDNS_START_WAB_QUERY);
3143 
3144 #if 0
3145 	// mark which kind of enumeration we're doing so we can (de)authorize certain domains
3146 	request->u.enumeration.flags = reg;
3147 #endif
3148 
3149 	// enumeration requires multiple questions, so we must link all the context pointers so that
3150 	// necessary context can be reached from the callbacks
3151 	request->u.enumeration.q_all    .QuestionContext = request;
3152 	request->u.enumeration.q_default.QuestionContext = request;
3153 
3154 	// if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3155 	if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
3156 
3157 	// make the calls
3158 	LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
3159 		(flags & kDNSServiceFlagsBrowseDomains      ) ? "kDNSServiceFlagsBrowseDomains" :
3160 		(flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3161 	err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
3162 	if (!err)
3163 		{
3164 		err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
3165 		if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3166 		else request->terminate = enum_termination_callback;
3167 		}
3168 
3169 	return(err);
3170 	}
3171 
3172 // ***************************************************************************
3173 #if COMPILER_LIKES_PRAGMA_MARK
3174 #pragma mark -
3175 #pragma mark - DNSServiceReconfirmRecord & Misc
3176 #endif
3177 
handle_reconfirm_request(request_state * request)3178 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
3179 	{
3180 	mStatus status = mStatus_BadParamErr;
3181 	AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
3182 	if (rr)
3183 		{
3184 		status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
3185 		LogOperation(
3186 			(status == mStatus_NoError) ?
3187 			"%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
3188 			"%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
3189 			request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
3190 			mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse), status);
3191 		freeL("AuthRecord/handle_reconfirm_request", rr);
3192 		}
3193 	return(status);
3194 	}
3195 
handle_setdomain_request(request_state * request)3196 mDNSlocal mStatus handle_setdomain_request(request_state *request)
3197 	{
3198 	char domainstr[MAX_ESCAPED_DOMAIN_NAME];
3199 	domainname domain;
3200 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3201 	(void)flags; // Unused
3202 	if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3203 		!MakeDomainNameFromDNSNameString(&domain, domainstr))
3204 		{ LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3205 
3206 	LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
3207 	return(mStatus_NoError);
3208 	}
3209 
3210 typedef packedstruct
3211 	{
3212 	mStatus err;
3213 	mDNSu32 len;
3214 	mDNSu32 vers;
3215 	} DaemonVersionReply;
3216 
handle_getproperty_request(request_state * request)3217 mDNSlocal void handle_getproperty_request(request_state *request)
3218 	{
3219 	const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
3220 	char prop[256];
3221 	if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
3222 		{
3223 		LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
3224 		if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
3225 			{
3226 			DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
3227 			send_all(request->sd, (const char *)&x, sizeof(x));
3228 			return;
3229 			}
3230 		}
3231 
3232 	// If we didn't recogize the requested property name, return BadParamErr
3233 	send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
3234 	}
3235 
3236 // ***************************************************************************
3237 #if COMPILER_LIKES_PRAGMA_MARK
3238 #pragma mark -
3239 #pragma mark - DNSServiceNATPortMappingCreate
3240 #endif
3241 
3242 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
3243 
port_mapping_termination_callback(request_state * request)3244 mDNSlocal void port_mapping_termination_callback(request_state *request)
3245 	{
3246 	LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP", request->sd,
3247 		DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
3248 		mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease);
3249 	mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
3250 	}
3251 
3252 // Called via function pointer when we get a NAT-PMP address request or port mapping response
port_mapping_create_request_callback(mDNS * m,NATTraversalInfo * n)3253 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
3254 	{
3255 	request_state *request = (request_state *)n->clientContext;
3256 	reply_state *rep;
3257 	int replyLen;
3258 	char *data;
3259 
3260 	if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
3261 
3262 	// calculate reply data length
3263 	replyLen = sizeof(DNSServiceFlags);
3264 	replyLen += 3 * sizeof(mDNSu32);  // if index + addr + ttl
3265 	replyLen += sizeof(DNSServiceErrorType);
3266 	replyLen += 2 * sizeof(mDNSu16);  // Internal Port + External Port
3267 	replyLen += sizeof(mDNSu8);       // protocol
3268 
3269 	rep = create_reply(port_mapping_reply_op, replyLen, request);
3270 
3271 	rep->rhdr->flags = dnssd_htonl(0);
3272 	rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
3273 	rep->rhdr->error = dnssd_htonl(n->Result);
3274 
3275 	data = (char *)&rep->rhdr[1];
3276 
3277 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
3278 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
3279 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
3280 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
3281 	*data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
3282 	*data++ = request->u.pm.NATinfo.IntPort.b[0];
3283 	*data++ = request->u.pm.NATinfo.IntPort.b[1];
3284 	*data++ = request->u.pm.NATinfo.ExternalPort.b[0];
3285 	*data++ = request->u.pm.NATinfo.ExternalPort.b[1];
3286 	put_uint32(request->u.pm.NATinfo.Lifetime, &data);
3287 
3288 	LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
3289 		DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
3290 		mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
3291 		&request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
3292 
3293 	append_reply(request, rep);
3294 	}
3295 
handle_port_mapping_request(request_state * request)3296 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
3297 	{
3298 	mDNSu32 ttl = 0;
3299 	mStatus err = mStatus_NoError;
3300 
3301 	DNSServiceFlags flags          = get_flags(&request->msgptr, request->msgend);
3302 	mDNSu32         interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3303 	mDNSInterfaceID InterfaceID    = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3304 	mDNSu8          protocol       = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
3305 	(void)flags; // Unused
3306 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3307 	if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
3308 	else
3309 		{
3310 		request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
3311 		request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
3312 		request->u.pm.ReqExt.b[0]          = *request->msgptr++;
3313 		request->u.pm.ReqExt.b[1]          = *request->msgptr++;
3314 		ttl = get_uint32(&request->msgptr, request->msgend);
3315 		}
3316 
3317 	if (!request->msgptr)
3318 		{ LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3319 
3320 	if (protocol == 0)	// If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
3321 		{
3322 		if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
3323 		}
3324 	else
3325 		{
3326 		if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
3327 		if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
3328 		}
3329 
3330 	request->u.pm.NATinfo.Protocol       = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
3331 	//       u.pm.NATinfo.IntPort        = already set above
3332 	request->u.pm.NATinfo.RequestedPort  = request->u.pm.ReqExt;
3333 	request->u.pm.NATinfo.NATLease       = ttl;
3334 	request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
3335 	request->u.pm.NATinfo.clientContext  = request;
3336 
3337 	LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START", request->sd,
3338 		protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease);
3339 	err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
3340 	if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
3341 	else request->terminate = port_mapping_termination_callback;
3342 
3343 	return(err);
3344 	}
3345 
3346 // ***************************************************************************
3347 #if COMPILER_LIKES_PRAGMA_MARK
3348 #pragma mark -
3349 #pragma mark - DNSServiceGetAddrInfo
3350 #endif
3351 
addrinfo_termination_callback(request_state * request)3352 mDNSlocal void addrinfo_termination_callback(request_state *request)
3353 	{
3354 	LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP", request->sd, request->u.addrinfo.q4.qname.c);
3355 
3356 	if (request->u.addrinfo.q4.QuestionContext)
3357 		{
3358 		mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
3359 		request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3360 		}
3361 	if (request->u.addrinfo.q4.qnameOrig)
3362 		{
3363 		freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
3364 		request->u.addrinfo.q4.qnameOrig = mDNSNULL;
3365 		}
3366 	if (request->u.addrinfo.q42)
3367 		{
3368 		if (request->u.addrinfo.q42->QuestionContext)
3369 			{
3370 			LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
3371 			mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
3372 			}
3373 		if (request->u.addrinfo.q42->qnameOrig)
3374 			{
3375 			LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
3376 			freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
3377 			request->u.addrinfo.q42->qnameOrig = mDNSNULL;
3378 			}
3379 		freeL("addrinfo Q42", request->u.addrinfo.q42);
3380 		request->u.addrinfo.q42 = mDNSNULL;
3381 		}
3382 
3383 	if (request->u.addrinfo.q6.QuestionContext)
3384 		{
3385 		mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
3386 		request->u.addrinfo.q6.QuestionContext = mDNSNULL;
3387 		}
3388 	if (request->u.addrinfo.q6.qnameOrig)
3389 		{
3390 		freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
3391 		request->u.addrinfo.q6.qnameOrig = mDNSNULL;
3392 		}
3393 	if (request->u.addrinfo.q62)
3394 		{
3395 		if (request->u.addrinfo.q62->QuestionContext)
3396 			{
3397 			LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
3398 			mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
3399 			}
3400 		if (request->u.addrinfo.q62->qnameOrig)
3401 			{
3402 			LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
3403 			freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
3404 			request->u.addrinfo.q62->qnameOrig = mDNSNULL;
3405 			}
3406 		freeL("addrinfo Q62", request->u.addrinfo.q62);
3407 		request->u.addrinfo.q62 = mDNSNULL;
3408 		}
3409 	}
3410 
handle_addrinfo_request(request_state * request)3411 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
3412 	{
3413 	char hostname[256];
3414 	domainname d;
3415 	mStatus err = 0;
3416 
3417 	DNSServiceFlags flags  = get_flags(&request->msgptr, request->msgend);
3418 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3419 
3420 	mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
3421 	request->u.addrinfo.interface_id = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3422 	request->u.addrinfo.flags        = flags;
3423 	request->u.addrinfo.protocol     = get_uint32(&request->msgptr, request->msgend);
3424 
3425 	if (interfaceIndex && !request->u.addrinfo.interface_id) return(mStatus_BadParamErr);
3426 	if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
3427 
3428 	if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
3429 
3430 	if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3431 
3432 	if (!MakeDomainNameFromDNSNameString(&d, hostname))
3433 		{ LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
3434 
3435 #if 0
3436 	if (!AuthorizedDomain(request, &d, AutoBrowseDomains))	return (mStatus_NoError);
3437 #endif
3438 
3439 	if (!request->u.addrinfo.protocol)
3440 		{
3441 		flags |= kDNSServiceFlagsSuppressUnusable;
3442 		request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
3443 		}
3444 
3445 	request->u.addrinfo.q4.InterfaceID      = request->u.addrinfo.q6.InterfaceID      = request->u.addrinfo.interface_id;
3446 	request->u.addrinfo.q4.Target           = request->u.addrinfo.q6.Target           = zeroAddr;
3447 	request->u.addrinfo.q4.qname            = request->u.addrinfo.q6.qname            = d;
3448 	request->u.addrinfo.q4.qclass           = request->u.addrinfo.q6.qclass           = kDNSServiceClass_IN;
3449 	request->u.addrinfo.q4.LongLived        = request->u.addrinfo.q6.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
3450 	request->u.addrinfo.q4.ExpectUnique     = request->u.addrinfo.q6.ExpectUnique     = mDNSfalse;
3451 	request->u.addrinfo.q4.ForceMCast       = request->u.addrinfo.q6.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
3452 	request->u.addrinfo.q4.ReturnIntermed   = request->u.addrinfo.q6.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3453 	request->u.addrinfo.q4.SuppressUnusable = request->u.addrinfo.q6.SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable   ) != 0;
3454 	request->u.addrinfo.q4.TimeoutQuestion  = request->u.addrinfo.q6.TimeoutQuestion  = (flags & kDNSServiceFlagsTimeout            ) != 0;
3455 	request->u.addrinfo.q4.WakeOnResolve    = request->u.addrinfo.q6.WakeOnResolve    = 0;
3456 	request->u.addrinfo.q4.qnameOrig        = request->u.addrinfo.q6.qnameOrig        = mDNSNULL;
3457 
3458 	if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
3459 		{
3460 		request->u.addrinfo.q4.qtype            = kDNSServiceType_A;
3461 		request->u.addrinfo.q4.SearchListIndex  = 0;
3462 
3463 		// We append search domains only for queries that are a single label. If overriden using
3464 		// command line argument "AlwaysAppendSearchDomains", then we do it for any query which
3465 		// is not fully qualified.
3466 		if (hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
3467 			{
3468 			request->u.addrinfo.q4.AppendSearchDomains = 1;
3469 			request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
3470 			}
3471 		else
3472 			{
3473 			request->u.addrinfo.q4.AppendSearchDomains = 0;
3474 			request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
3475 			}
3476 		request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
3477 		request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
3478 		request->u.addrinfo.q4.QuestionContext  = request;
3479 		err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
3480 		if (err != mStatus_NoError)
3481 			{
3482 			LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
3483 			request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3484 			}
3485 		#if APPLE_OSX_mDNSResponder
3486 		err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
3487 		#endif // APPLE_OSX_mDNSResponder
3488 		}
3489 
3490 	if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6))
3491 		{
3492 		request->u.addrinfo.q6.qtype            = kDNSServiceType_AAAA;
3493 		request->u.addrinfo.q6.SearchListIndex  = 0;
3494 		if (hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
3495 			{
3496 			request->u.addrinfo.q6.AppendSearchDomains = 1;
3497 			request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
3498 			}
3499 		else
3500 			{
3501 			request->u.addrinfo.q6.AppendSearchDomains = 0;
3502 			request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
3503 			}
3504 		request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
3505 		request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
3506 		request->u.addrinfo.q6.QuestionContext  = request;
3507 		err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
3508 		if (err != mStatus_NoError)
3509 			{
3510 			LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
3511 			request->u.addrinfo.q6.QuestionContext = mDNSNULL;
3512 			if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
3513 				{
3514 				// If we started a query for IPv4, we need to cancel it
3515 				mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
3516 				request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3517 				}
3518 			}
3519 		#if APPLE_OSX_mDNSResponder
3520 		err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
3521 		#endif // APPLE_OSX_mDNSResponder
3522 		}
3523 
3524 	LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START",
3525 		request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c);
3526 
3527 	if (!err) request->terminate = addrinfo_termination_callback;
3528 
3529 	return(err);
3530 	}
3531 
3532 // ***************************************************************************
3533 #if COMPILER_LIKES_PRAGMA_MARK
3534 #pragma mark -
3535 #pragma mark - Main Request Handler etc.
3536 #endif
3537 
NewRequest(void)3538 mDNSlocal request_state *NewRequest(void)
3539 	{
3540 	request_state **p = &all_requests;
3541 	while (*p) p=&(*p)->next;
3542 	*p = mallocL("request_state", sizeof(request_state));
3543 	if (!*p) FatalError("ERROR: malloc");
3544 	mDNSPlatformMemZero(*p, sizeof(request_state));
3545 	return(*p);
3546 	}
3547 
3548 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
3549 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
read_msg(request_state * req)3550 mDNSlocal void read_msg(request_state *req)
3551 	{
3552 	if (req->ts == t_terminated || req->ts == t_error)
3553 		{ LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
3554 
3555 	if (req->ts == t_complete)	// this must be death or something is wrong
3556 		{
3557 		char buf[4];	// dummy for death notification
3558 		int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
3559 		if (!nread) { req->ts = t_terminated; return; }
3560 		if (nread < 0) goto rerror;
3561 		LogMsg("%3d: ERROR: read data from a completed request", req->sd);
3562 		req->ts = t_error;
3563 		return;
3564 		}
3565 
3566 	if (req->ts != t_morecoming)
3567 		{ LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
3568 
3569 	if (req->hdr_bytes < sizeof(ipc_msg_hdr))
3570 		{
3571 		mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
3572 		int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
3573 		if (nread == 0) { req->ts = t_terminated; return; }
3574 		if (nread < 0) goto rerror;
3575 		req->hdr_bytes += nread;
3576 		if (req->hdr_bytes > sizeof(ipc_msg_hdr))
3577 			{ LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
3578 
3579 		// only read data if header is complete
3580 		if (req->hdr_bytes == sizeof(ipc_msg_hdr))
3581 			{
3582 			ConvertHeaderBytes(&req->hdr);
3583 			if (req->hdr.version != VERSION)
3584 				{ LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
3585 
3586 			// Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
3587 			// with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
3588 			// for other overhead, this means any message above 70kB is definitely bogus.
3589 			if (req->hdr.datalen > 70000)
3590 				{ LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
3591 			req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
3592 			if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
3593 			req->msgptr = req->msgbuf;
3594 			req->msgend = req->msgbuf + req->hdr.datalen;
3595 			mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
3596 			}
3597 		}
3598 
3599 	// If our header is complete, but we're still needing more body data, then try to read it now
3600 	// Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
3601 	// Any time we need to get the error return socket we know we'll have at least one data byte
3602 	// (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
3603 	if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
3604 		{
3605 		mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
3606 		int nread;
3607 #if !defined(_WIN32)
3608 		struct iovec vec = { req->msgbuf + req->data_bytes, nleft };	// Tell recvmsg where we want the bytes put
3609 		struct msghdr msg;
3610 		struct cmsghdr *cmsg;
3611 		char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
3612 		msg.msg_name       = 0;
3613 		msg.msg_namelen    = 0;
3614 		msg.msg_iov        = &vec;
3615 		msg.msg_iovlen     = 1;
3616 		msg.msg_control    = cbuf;
3617 		msg.msg_controllen = sizeof(cbuf);
3618 		msg.msg_flags      = 0;
3619 		nread = recvmsg(req->sd, &msg, 0);
3620 #else
3621 		nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
3622 #endif
3623 		if (nread == 0) { req->ts = t_terminated; return; }
3624 		if (nread < 0) goto rerror;
3625 		req->data_bytes += nread;
3626 		if (req->data_bytes > req->hdr.datalen)
3627 			{ LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
3628 #if !defined(_WIN32)
3629 		cmsg = CMSG_FIRSTHDR(&msg);
3630 #if DEBUG_64BIT_SCM_RIGHTS
3631 		LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf),       sizeof(cbuf),   SOL_SOCKET,       SCM_RIGHTS);
3632 		LogMsg("%3d: Got       %d %d %d %d", req->sd, msg.msg_controllen, cmsg->cmsg_len, cmsg->cmsg_level, cmsg->cmsg_type);
3633 #endif // DEBUG_64BIT_SCM_RIGHTS
3634 		if (msg.msg_controllen == sizeof(cbuf) &&
3635 			cmsg->cmsg_len     == CMSG_LEN(sizeof(dnssd_sock_t)) &&
3636 			cmsg->cmsg_level   == SOL_SOCKET   &&
3637 			cmsg->cmsg_type    == SCM_RIGHTS)
3638 			{
3639 #if APPLE_OSX_mDNSResponder
3640 			// Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3641 			// of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3642 			// and it's convenient to repurpose the existing fd-passing code here for that task
3643 			if (req->hdr.op == send_bpf)
3644 				{
3645 				dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
3646 				LogOperation("%3d: Got BPF %d", req->sd, x);
3647 				mDNSPlatformReceiveBPF_fd(&mDNSStorage, x);
3648 				}
3649 			else
3650 #endif // APPLE_OSX_mDNSResponder
3651 				req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
3652 #if DEBUG_64BIT_SCM_RIGHTS
3653 			LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
3654 #endif // DEBUG_64BIT_SCM_RIGHTS
3655 			if (req->data_bytes < req->hdr.datalen)
3656 				{
3657 				LogMsg("%3d: Client sent error socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3658 					req->sd, req->errsd, req->data_bytes, req->hdr.datalen);
3659 				req->ts = t_error;
3660 				return;
3661 				}
3662 			}
3663 #endif
3664 		}
3665 
3666 	// If our header and data are both complete, see if we need to make our separate error return socket
3667 	if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
3668 		{
3669 		if (req->terminate && req->hdr.op != cancel_request)
3670 			{
3671 			dnssd_sockaddr_t cliaddr;
3672 #if defined(USE_TCP_LOOPBACK)
3673 			mDNSOpaque16 port;
3674 			u_long opt = 1;
3675 			port.b[0] = req->msgptr[0];
3676 			port.b[1] = req->msgptr[1];
3677 			req->msgptr += 2;
3678 			cliaddr.sin_family      = AF_INET;
3679 			cliaddr.sin_port        = port.NotAnInteger;
3680 			cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
3681 #else
3682 			char ctrl_path[MAX_CTLPATH];
3683 			get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH);	// path is first element in message buffer
3684 			mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
3685 			cliaddr.sun_family = AF_LOCAL;
3686 			mDNSPlatformStrCopy(cliaddr.sun_path, ctrl_path);
3687 			// If the error return path UDS name is empty string, that tells us
3688 			// that this is a new version of the library that's going to pass us
3689 			// the error return path socket via sendmsg/recvmsg
3690 			if (ctrl_path[0] == 0)
3691 				{
3692 				if (req->errsd == req->sd)
3693 					{ LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
3694 				goto got_errfd;
3695 				}
3696 #endif
3697 
3698 			req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
3699 			if (!dnssd_SocketValid(req->errsd)) { my_perror("ERROR: socket"); req->ts = t_error; return; }
3700 
3701 			if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
3702 				{
3703 #if !defined(USE_TCP_LOOPBACK)
3704 				struct stat sb;
3705 				LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
3706 					req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
3707 				if (stat(cliaddr.sun_path, &sb) < 0)
3708 					LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
3709 				else
3710 					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);
3711 #endif
3712 				req->ts = t_error;
3713 				return;
3714 				}
3715 
3716 #if !defined(USE_TCP_LOOPBACK)
3717 got_errfd:
3718 #endif
3719 			LogOperation("%3d: Error socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
3720 #if defined(_WIN32)
3721 			if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
3722 #else
3723 			if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
3724 #endif
3725 				{
3726 				LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
3727 					req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3728 				req->ts = t_error;
3729 				return;
3730 				}
3731 			}
3732 
3733 		req->ts = t_complete;
3734 		}
3735 
3736 	return;
3737 
3738 rerror:
3739 	if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
3740 	LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3741 	req->ts = t_error;
3742 	}
3743 
3744 #define RecordOrientedOp(X) \
3745 	((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3746 
3747 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3748 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3749 
request_callback(int fd,short filter,void * info)3750 mDNSlocal void request_callback(int fd, short filter, void *info)
3751 	{
3752 	mStatus err = 0;
3753 	request_state *req = info;
3754 	mDNSs32 min_size = sizeof(DNSServiceFlags);
3755 	(void)fd; // Unused
3756 	(void)filter; // Unused
3757 
3758 	for (;;)
3759 		{
3760 		read_msg(req);
3761 		if (req->ts == t_morecoming) return;
3762 		if (req->ts == t_terminated || req->ts == t_error) { AbortUnlinkAndFree(req); return; }
3763 		if (req->ts != t_complete) { LogMsg("req->ts %d != t_complete", req->ts); AbortUnlinkAndFree(req); return; }
3764 
3765 		if (req->hdr.version != VERSION)
3766 			{
3767 			LogMsg("ERROR: client version %d incompatible with daemon version %d", req->hdr.version, VERSION);
3768 			AbortUnlinkAndFree(req);
3769 			return;
3770 			}
3771 
3772 		switch(req->hdr.op)            //          Interface       + other data
3773 			{
3774 			case connection_request:       min_size = 0;                                                                           break;
3775 			case reg_service_request:      min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3776 			case add_record_request:       min_size +=                   4 /* type, rdlen */              + 4 /* ttl */;           break;
3777 			case update_record_request:    min_size +=                   2 /* rdlen */                    + 4 /* ttl */;           break;
3778 			case remove_record_request:                                                                                            break;
3779 			case browse_request:           min_size += sizeof(mDNSu32) + 2 /* type, domain */;                                     break;
3780 			case resolve_request:          min_size += sizeof(mDNSu32) + 3 /* type, type, domain */;                               break;
3781 			case query_request:            min_size += sizeof(mDNSu32) + 1 /* name */                     + 4 /* type, class*/;    break;
3782 			case enumeration_request:      min_size += sizeof(mDNSu32);                                                            break;
3783 			case reg_record_request:       min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */;  break;
3784 			case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */;                break;
3785 			case setdomain_request:        min_size +=                   1 /* domain */;                                           break;
3786 			case getproperty_request:      min_size = 2;                                                                           break;
3787 			case port_mapping_request:     min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */    + 4 /* ttl */;  break;
3788 			case addrinfo_request:         min_size += sizeof(mDNSu32) + 4 /* v4/v6 */   + 1 /* hostname */;                       break;
3789 			case send_bpf:                 // Same as cancel_request below
3790 			case cancel_request:           min_size = 0;									       break;
3791 			case sethost_request:          min_size = sizeof(mDNSu32) + 1 /* hostname */;                                          break;
3792 			default: LogMsg("ERROR: validate_message - unsupported req type: %d", req->hdr.op); min_size = -1;                     break;
3793 			}
3794 
3795 		if ((mDNSs32)req->data_bytes < min_size)
3796 			{ LogMsg("Invalid message %d bytes; min for %d is %d", req->data_bytes, req->hdr.op, min_size); AbortUnlinkAndFree(req); return; }
3797 
3798 		if (LightweightOp(req->hdr.op) && !req->terminate)
3799 			{ LogMsg("Reg/Add/Update/Remove %d require existing connection", req->hdr.op);                  AbortUnlinkAndFree(req); return; }
3800 
3801 		// check if client wants silent operation
3802 		if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
3803 
3804 		// If req->terminate is already set, this means this operation is sharing an existing connection
3805 		if (req->terminate && !LightweightOp(req->hdr.op))
3806 			{
3807 			request_state *newreq = NewRequest();
3808 			newreq->primary = req;
3809 			newreq->sd      = req->sd;
3810 			newreq->errsd   = req->errsd;
3811 			newreq->uid     = req->uid;
3812 			newreq->hdr     = req->hdr;
3813 			newreq->msgbuf  = req->msgbuf;
3814 			newreq->msgptr  = req->msgptr;
3815 			newreq->msgend  = req->msgend;
3816 			req = newreq;
3817 			}
3818 
3819 		// If we're shutting down, don't allow new client requests
3820 		// We do allow "cancel" and "getproperty" during shutdown
3821 		if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
3822 			{
3823 			err = mStatus_ServiceNotRunning;
3824 			}
3825 		else switch(req->hdr.op)
3826 			{
3827 			// These are all operations that have their own first-class request_state object
3828 			case connection_request:           LogOperation("%3d: DNSServiceCreateConnection START", req->sd);
3829 											   req->terminate = connection_termination; break;
3830 			case resolve_request:              err = handle_resolve_request     (req);  break;
3831 			case query_request:                err = handle_queryrecord_request (req);  break;
3832 			case browse_request:               err = handle_browse_request      (req);  break;
3833 			case reg_service_request:          err = handle_regservice_request  (req);  break;
3834 			case enumeration_request:          err = handle_enum_request        (req);  break;
3835 			case reconfirm_record_request:     err = handle_reconfirm_request   (req);  break;
3836 			case setdomain_request:            err = handle_setdomain_request   (req);  break;
3837 			case getproperty_request:                handle_getproperty_request (req);  break;
3838 			case port_mapping_request:         err = handle_port_mapping_request(req);  break;
3839 			case addrinfo_request:             err = handle_addrinfo_request    (req);  break;
3840 			case send_bpf:                     /* Do nothing for send_bpf */            break;
3841 
3842 			// These are all operations that work with an existing request_state object
3843 			case reg_record_request:           err = handle_regrecord_request   (req);  break;
3844 			case add_record_request:           err = handle_add_request         (req);  break;
3845 			case update_record_request:        err = handle_update_request      (req);  break;
3846 			case remove_record_request:        err = handle_removerecord_request(req);  break;
3847 			case cancel_request:                     handle_cancel_request      (req);  break;
3848 			case sethost_request:              err = handle_sethost_request     (req);  break;
3849 			default: LogMsg("%3d: ERROR: Unsupported UDS req: %d", req->sd, req->hdr.op);
3850 			}
3851 
3852 		// req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3853 		if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
3854 
3855 		// There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3856 		// For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3857 		if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf)
3858 			{
3859 			const mStatus err_netorder = dnssd_htonl(err);
3860 			send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
3861 			if (req->errsd != req->sd)
3862 				{
3863 				LogOperation("%3d: Error socket %d closed  %08X %08X (%d)",
3864 					req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
3865 				dnssd_close(req->errsd);
3866 				req->errsd = req->sd;
3867 				// Also need to reset the parent's errsd, if this is a subordinate operation
3868 				if (req->primary) req->primary->errsd = req->primary->sd;
3869 				}
3870 			}
3871 
3872 		// Reset ready to accept the next req on this pipe
3873 		if (req->primary) req = req->primary;
3874 		req->ts         = t_morecoming;
3875 		req->hdr_bytes  = 0;
3876 		req->data_bytes = 0;
3877 		req->msgbuf     = mDNSNULL;
3878 		req->msgptr     = mDNSNULL;
3879 		req->msgend     = 0;
3880 		}
3881 	}
3882 
connect_callback(int fd,short filter,void * info)3883 mDNSlocal void connect_callback(int fd, short filter, void *info)
3884 	{
3885 	dnssd_sockaddr_t cliaddr;
3886 	dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
3887 	dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
3888 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3889 	unsigned long optval = 1;
3890 #endif
3891 
3892 	(void)filter; // Unused
3893 	(void)info; // Unused
3894 
3895 	if (!dnssd_SocketValid(sd))
3896 		{
3897 		if (dnssd_errno != dnssd_EWOULDBLOCK) my_perror("ERROR: accept");
3898 		return;
3899 		}
3900 
3901 #ifdef SO_NOSIGPIPE
3902 	// Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3903 	if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
3904 		LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3905 #endif
3906 
3907 #if defined(_WIN32)
3908 	if (ioctlsocket(sd, FIONBIO, &optval) != 0)
3909 #else
3910 	if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
3911 #endif
3912 		{
3913 		my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3914 		dnssd_close(sd);
3915 		return;
3916 		}
3917 	else
3918 		{
3919 		request_state *request = NewRequest();
3920 		request->ts    = t_morecoming;
3921 		request->sd    = sd;
3922 		request->errsd = sd;
3923 #if APPLE_OSX_mDNSResponder
3924 		struct xucred x;
3925 		socklen_t xucredlen = sizeof(x);
3926 		if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION) request->uid = x.cr_uid;
3927 		else my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
3928 		debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
3929 #endif // APPLE_OSX_mDNSResponder
3930 		LogOperation("%3d: Adding FD for uid %u", request->sd, request->uid);
3931 		udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
3932 		}
3933 	}
3934 
uds_socket_setup(dnssd_sock_t skt)3935 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
3936 	{
3937 #if defined(SO_NP_EXTENSIONS)
3938 	struct		so_np_extensions sonpx;
3939 	socklen_t 	optlen = sizeof(struct so_np_extensions);
3940 	sonpx.npx_flags = SONPX_SETOPTSHUT;
3941 	sonpx.npx_mask  = SONPX_SETOPTSHUT;
3942 	if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
3943 		my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
3944 #endif
3945 #if defined(_WIN32)
3946 	// SEH: do we even need to do this on windows?
3947 	// This socket will be given to WSAEventSelect which will automatically set it to non-blocking
3948 	u_long opt = 1;
3949 	if (ioctlsocket(skt, FIONBIO, &opt) != 0)
3950 #else
3951 	if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
3952 #endif
3953 		{
3954 		my_perror("ERROR: could not set listen socket to non-blocking mode");
3955 		return mDNSfalse;
3956 		}
3957 
3958 	if (listen(skt, LISTENQ) != 0)
3959 		{
3960 		my_perror("ERROR: could not listen on listen socket");
3961 		return mDNSfalse;
3962 		}
3963 
3964 	if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
3965 		{
3966 		my_perror("ERROR: could not add listen socket to event loop");
3967 		return mDNSfalse;
3968 		}
3969 	else LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
3970 
3971 	return mDNStrue;
3972 	}
3973 
udsserver_init(dnssd_sock_t skts[],mDNSu32 count)3974 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
3975 	{
3976 	dnssd_sockaddr_t laddr;
3977 	int ret;
3978 	mDNSu32 i = 0;
3979 
3980 	LogInfo("udsserver_init");
3981 
3982 	// If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
3983 	if (PID_FILE[0])
3984 		{
3985 		FILE *fp = fopen(PID_FILE, "w");
3986 		if (fp != NULL)
3987 			{
3988 			fprintf(fp, "%d\n", getpid());
3989 			fclose(fp);
3990 			}
3991 		}
3992 
3993 	if (skts)
3994 		{
3995 		for (i = 0; i < count; i++)
3996 			if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
3997 				goto error;
3998 		}
3999 	else
4000 		{
4001 		listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
4002 		if (!dnssd_SocketValid(listenfd))
4003 			{
4004 			my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
4005 			goto error;
4006 			}
4007 
4008 		mDNSPlatformMemZero(&laddr, sizeof(laddr));
4009 
4010 		#if defined(USE_TCP_LOOPBACK)
4011 			{
4012 			laddr.sin_family = AF_INET;
4013 			laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
4014 			laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4015 			ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
4016 			if (ret < 0)
4017 				{
4018 				my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4019 				goto error;
4020 				}
4021 			}
4022 		#else
4023 			{
4024 			mode_t mask = umask(0);
4025 			unlink(MDNS_UDS_SERVERPATH);  // OK if this fails
4026 			laddr.sun_family = AF_LOCAL;
4027 			#ifndef NOT_HAVE_SA_LEN
4028 			// According to Stevens (section 3.2), there is no portable way to
4029 			// determine whether sa_len is defined on a particular platform.
4030 			laddr.sun_len = sizeof(struct sockaddr_un);
4031 			#endif
4032 			if (strlen(MDNS_UDS_SERVERPATH) >= sizeof(laddr.sun_path))
4033 				{
4034 					LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
4035 					goto error;
4036 				}
4037 			mDNSPlatformStrCopy(laddr.sun_path, MDNS_UDS_SERVERPATH);
4038 			ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
4039 			umask(mask);
4040 			if (ret < 0)
4041 				{
4042 				my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4043 				goto error;
4044 				}
4045 			}
4046 		#endif
4047 
4048 		if (!uds_socket_setup(listenfd)) goto error;
4049 		}
4050 
4051 #if !defined(PLATFORM_NO_RLIMIT)
4052 	{
4053 	// Set maximum number of open file descriptors
4054 	#define MIN_OPENFILES 10240
4055 	struct rlimit maxfds, newfds;
4056 
4057 	// Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
4058 	// you have to get and set rlimits once before getrlimit will return sensible values
4059 	if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4060 	if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4061 
4062 	if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4063 	newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
4064 	newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
4065 	if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
4066 		if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4067 
4068 	if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4069 	debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
4070 	debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
4071 	}
4072 #endif
4073 
4074 	// We start a "LocalOnly" query looking for Automatic Browse Domain records.
4075 	// When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
4076 	// creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
4077 	mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
4078 		mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
4079 
4080 	// Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
4081 	RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
4082 	RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
4083 	AddAutoBrowseDomain(0, &localdomain);
4084 
4085 	udsserver_handle_configchange(&mDNSStorage);
4086 	return 0;
4087 
4088 error:
4089 
4090 	my_perror("ERROR: udsserver_init");
4091 	return -1;
4092 	}
4093 
udsserver_exit(void)4094 mDNSexport int udsserver_exit(void)
4095 	{
4096 	// Cancel all outstanding client requests
4097 	while (all_requests) AbortUnlinkAndFree(all_requests);
4098 
4099 	// Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
4100 	// created in udsserver_init, and others we created as a result of reading local configuration data
4101 	while (LocalDomainEnumRecords)
4102 		{
4103 		ARListElem *rem = LocalDomainEnumRecords;
4104 		LocalDomainEnumRecords = LocalDomainEnumRecords->next;
4105 		mDNS_Deregister(&mDNSStorage, &rem->ar);
4106 		}
4107 
4108 	// If the launching environment created no listening socket,
4109 	// that means we created it ourselves, so we should clean it up on exit
4110 	if (dnssd_SocketValid(listenfd))
4111 		{
4112 		dnssd_close(listenfd);
4113 #if !defined(USE_TCP_LOOPBACK)
4114 		// Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
4115 		// to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
4116 		// It would be nice if we could find a solution to this problem
4117 		if (unlink(MDNS_UDS_SERVERPATH))
4118 			debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
4119 #endif
4120 		}
4121 
4122 	if (PID_FILE[0]) unlink(PID_FILE);
4123 
4124 	return 0;
4125 	}
4126 
LogClientInfo(mDNS * const m,const request_state * req)4127 mDNSlocal void LogClientInfo(mDNS *const m, const request_state *req)
4128 	{
4129 	char prefix[16];
4130 	if (req->primary) mDNS_snprintf(prefix, sizeof(prefix), " -> ");
4131 	else mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
4132 
4133 	usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4134 
4135 	if (!req->terminate)
4136 		LogMsgNoIdent("%s No operation yet on this socket", prefix);
4137 	else if (req->terminate == connection_termination)
4138 		{
4139 		int num_records = 0, num_ops = 0;
4140 		const registered_record_entry *p;
4141 		const request_state *r;
4142 		for (p = req->u.reg_recs; p; p=p->next) num_records++;
4143 		for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
4144 		LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s", prefix,
4145 			num_records, num_records != 1 ? "s" : "",
4146 			num_ops,     num_ops     != 1 ? "s" : "");
4147 		for (p = req->u.reg_recs; p; p=p->next)
4148 			LogMsgNoIdent(" ->  DNSServiceRegisterRecord %3d %s", p->key, ARDisplayString(m, p->rr));
4149 		for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(m, r);
4150 		}
4151 	else if (req->terminate == regservice_termination_callback)
4152 		{
4153 		service_instance *ptr;
4154 		for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
4155 			LogMsgNoIdent("%s DNSServiceRegister         %##s %u/%u",
4156 				(ptr == req->u.servicereg.instances) ? prefix : "    ",
4157 				ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port), SRS_PORT(&ptr->srs));
4158 		}
4159 	else if (req->terminate == browse_termination_callback)
4160 		{
4161 		browser_t *blist;
4162 		for (blist = req->u.browser.browsers; blist; blist = blist->next)
4163 			LogMsgNoIdent("%s DNSServiceBrowse           %##s", (blist == req->u.browser.browsers) ? prefix : "    ", blist->q.qname.c);
4164 		}
4165 	else if (req->terminate == resolve_termination_callback)
4166 		LogMsgNoIdent("%s DNSServiceResolve          %##s", prefix, req->u.resolve.qsrv.qname.c);
4167 	else if (req->terminate == queryrecord_termination_callback)
4168 		LogMsgNoIdent("%s DNSServiceQueryRecord      %##s (%s)", prefix, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype));
4169 	else if (req->terminate == enum_termination_callback)
4170 		LogMsgNoIdent("%s DNSServiceEnumerateDomains %##s", prefix, req->u.enumeration.q_all.qname.c);
4171 	else if (req->terminate == port_mapping_termination_callback)
4172 		LogMsgNoIdent("%s DNSServiceNATPortMapping   %.4a %s%s Int %d Req %d Ext %d Req TTL %d Granted TTL %d",
4173 			prefix,
4174 			&req->u.pm.NATinfo.ExternalAddress,
4175 			req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : "   ",
4176 			req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : "   ",
4177 			mDNSVal16(req->u.pm.NATinfo.IntPort),
4178 			mDNSVal16(req->u.pm.ReqExt),
4179 			mDNSVal16(req->u.pm.NATinfo.ExternalPort),
4180 			req->u.pm.NATinfo.NATLease,
4181 			req->u.pm.NATinfo.Lifetime);
4182 	else if (req->terminate == addrinfo_termination_callback)
4183 		LogMsgNoIdent("%s DNSServiceGetAddrInfo      %s%s %##s", prefix,
4184 			req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : "  ",
4185 			req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : "  ",
4186 			req->u.addrinfo.q4.qname.c);
4187 	else
4188 		LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
4189 	}
4190 
RecordTypeName(mDNSu8 rtype)4191 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
4192 	{
4193 	switch (rtype)
4194 		{
4195 		case kDNSRecordTypeUnregistered:  return ("Unregistered ");
4196 		case kDNSRecordTypeDeregistering: return ("Deregistering");
4197 		case kDNSRecordTypeUnique:        return ("Unique       ");
4198 		case kDNSRecordTypeAdvisory:      return ("Advisory     ");
4199 		case kDNSRecordTypeShared:        return ("Shared       ");
4200 		case kDNSRecordTypeVerified:      return ("Verified     ");
4201 		case kDNSRecordTypeKnownUnique:   return ("KnownUnique  ");
4202 		default: return("Unknown");
4203 		}
4204 	}
4205 
LogEtcHosts(mDNS * const m)4206 mDNSlocal void LogEtcHosts(mDNS *const m)
4207 	{
4208 	mDNSBool showheader = mDNStrue;
4209 	const AuthRecord *ar;
4210 	mDNSu32 slot;
4211 	AuthGroup *ag;
4212 	int count = 0;
4213 	int authslot = 0;
4214 	mDNSBool truncated = 0;
4215 
4216 	for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4217 		{
4218 		if (m->rrauth.rrauth_hash[slot]) authslot++;
4219 		for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4220 			for (ar = ag->members; ar; ar = ar->next)
4221 				{
4222 				if (ar->RecordCallback != FreeEtcHosts) continue;
4223 				if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("  State       Interface"); }
4224 
4225 				// Print a maximum of 50 records
4226 				if (count++ >= 50) { truncated = mDNStrue; continue; }
4227 				if (ar->ARType == AuthRecordLocalOnly)
4228 					{
4229 					if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
4230 						LogMsgNoIdent(" %s   LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4231 					else
4232 						{
4233 						mDNSu32 scopeid  = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
4234 						LogMsgNoIdent(" %s   %u  %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
4235 						}
4236 					}
4237 				usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4238 				}
4239 		}
4240 
4241 	if (showheader) LogMsgNoIdent("<None>");
4242 	else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
4243 	}
4244 
LogLocalOnlyAuthRecords(mDNS * const m)4245 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
4246 	{
4247 	mDNSBool showheader = mDNStrue;
4248 	const AuthRecord *ar;
4249 	mDNSu32 slot;
4250 	AuthGroup *ag;
4251 
4252 	for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4253 		{
4254 		for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4255 			for (ar = ag->members; ar; ar = ar->next)
4256 				{
4257 				if (ar->RecordCallback == FreeEtcHosts) continue;
4258 				if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("  State       Interface"); }
4259 
4260 				// Print a maximum of 400 records
4261 				if (ar->ARType == AuthRecordLocalOnly)
4262 					LogMsgNoIdent(" %s   LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4263 				else if (ar->ARType == AuthRecordP2P)
4264 					LogMsgNoIdent(" %s   PP %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4265 				usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4266 				}
4267 		}
4268 
4269 	if (showheader) LogMsgNoIdent("<None>");
4270 	}
4271 
LogAuthRecords(mDNS * const m,const mDNSs32 now,AuthRecord * ResourceRecords,int * proxy)4272 mDNSlocal void LogAuthRecords(mDNS *const m, const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
4273 	{
4274 	mDNSBool showheader = mDNStrue;
4275 	const AuthRecord *ar;
4276 	OwnerOptData owner = zeroOwner;
4277 	for (ar = ResourceRecords; ar; ar=ar->next)
4278 		{
4279 		const char *const ifname = InterfaceNameForID(m, ar->resrec.InterfaceID);
4280 		if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
4281 			{
4282 			if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("    Int    Next  Expire   State"); }
4283 			if (proxy) (*proxy)++;
4284 			if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
4285 				{
4286 				owner = ar->WakeUp;
4287 				if (owner.password.l[0])
4288 					LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
4289 				else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
4290 					LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d",               &owner.HMAC, &owner.IMAC,                  owner.seq);
4291 				else
4292 					LogMsgNoIdent("Proxying for %.6a seq %d",                                &owner.HMAC,                               owner.seq);
4293 				}
4294 			if (AuthRecord_uDNS(ar))
4295 				LogMsgNoIdent("%7d %7d %7d %7d %s",
4296 					ar->ThisAPInterval / mDNSPlatformOneSecond,
4297 					(ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
4298 					ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
4299 					ar->state, ARDisplayString(m, ar));
4300 			else if (ar->ARType == AuthRecordLocalOnly)
4301 				LogMsgNoIdent("                             LO %s", ARDisplayString(m, ar));
4302 			else if (ar->ARType == AuthRecordP2P)
4303 				LogMsgNoIdent("                             PP %s", ARDisplayString(m, ar));
4304 			else
4305 				LogMsgNoIdent("%7d %7d %7d %7s %s",
4306 					ar->ThisAPInterval / mDNSPlatformOneSecond,
4307 					ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
4308 					ar->TimeExpire    ? (ar->TimeExpire                      - now) / mDNSPlatformOneSecond : 0,
4309 					ifname ? ifname : "ALL",
4310 					ARDisplayString(m, ar));
4311 			usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4312 			}
4313 		}
4314 	if (showheader) LogMsgNoIdent("<None>");
4315 	}
4316 
udsserver_info(mDNS * const m)4317 mDNSexport void udsserver_info(mDNS *const m)
4318 	{
4319 	const mDNSs32 now = mDNS_TimeNow(m);
4320 	mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
4321 	int ProxyA = 0, ProxyD = 0;
4322 	const CacheGroup *cg;
4323 	const CacheRecord *cr;
4324 	const DNSQuestion *q;
4325 	const DNameListElem *d;
4326 	const SearchListElem *s;
4327 
4328 	LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
4329 
4330 	LogMsgNoIdent("------------ Cache -------------");
4331 	LogMsgNoIdent("Slt Q     TTL if     U Type rdlen");
4332 	for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4333 		for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
4334 			{
4335 			CacheUsed++;	// Count one cache entity for the CacheGroup object
4336 			for (cr = cg->members; cr; cr=cr->next)
4337 				{
4338 				const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
4339 				const char *ifname;
4340 				mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
4341 				if (!InterfaceID && cr->resrec.rDNSServer)
4342 					InterfaceID = cr->resrec.rDNSServer->interface;
4343 				ifname = InterfaceNameForID(m, InterfaceID);
4344 				CacheUsed++;
4345 				if (cr->CRActiveQuestion) CacheActive++;
4346 				LogMsgNoIdent("%3d %s%8ld %-7s%s %-6s%s",
4347 					slot,
4348 					cr->CRActiveQuestion ? "*" : " ",
4349 					remain,
4350 					ifname ? ifname : "-U-",
4351 					(cr->resrec.RecordType == kDNSRecordTypePacketNegative)  ? "-" :
4352 					(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
4353 					DNSTypeName(cr->resrec.rrtype),
4354 					CRDisplayString(m, cr));
4355 				usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4356 				}
4357 			}
4358 
4359 	if (m->rrcache_totalused != CacheUsed)
4360 		LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
4361 	if (m->rrcache_active != CacheActive)
4362 		LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
4363 	LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed, CacheActive);
4364 
4365 	LogMsgNoIdent("--------- Auth Records ---------");
4366 	LogAuthRecords(m, now, m->ResourceRecords, mDNSNULL);
4367 
4368 	LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
4369 	LogLocalOnlyAuthRecords(m);
4370 
4371 	LogMsgNoIdent("--------- /etc/hosts ---------");
4372 	LogEtcHosts(m);
4373 
4374 	LogMsgNoIdent("------ Duplicate Records -------");
4375 	LogAuthRecords(m, now, m->DuplicateRecords, mDNSNULL);
4376 
4377 	LogMsgNoIdent("----- Auth Records Proxied -----");
4378 	LogAuthRecords(m, now, m->ResourceRecords, &ProxyA);
4379 
4380 	LogMsgNoIdent("-- Duplicate Records Proxied ---");
4381 	LogAuthRecords(m, now, m->DuplicateRecords, &ProxyD);
4382 
4383 	LogMsgNoIdent("---------- Questions -----------");
4384 	if (!m->Questions) LogMsgNoIdent("<None>");
4385 	else
4386 		{
4387 		CacheUsed = 0;
4388 		CacheActive = 0;
4389 		LogMsgNoIdent("   Int  Next if     T  NumAns VDNS    Qptr     DupOf    SU SQ Type Name");
4390 		for (q = m->Questions; q; q=q->next)
4391 			{
4392 			mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
4393 			mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
4394 			char *ifname = InterfaceNameForID(m, q->InterfaceID);
4395 			CacheUsed++;
4396 			if (q->ThisQInterval) CacheActive++;
4397 			LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s",
4398 				i, n,
4399 				ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
4400 				mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
4401 				PrivateQuery(q)    ? "P" : " ",
4402 				q->CurrentAnswers, q->validDNSServers.l[1], q->validDNSServers.l[0], q, q->DuplicateOf,
4403 				q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
4404 			usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4405 			}
4406 		LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
4407 		}
4408 
4409 	LogMsgNoIdent("----- Local-Only Questions -----");
4410 	if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
4411 	else for (q = m->LocalOnlyQuestions; q; q=q->next)
4412 		LogMsgNoIdent("                       %5d  %-6s%##s%s",
4413 			q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
4414 
4415 	LogMsgNoIdent("---- Active Client Requests ----");
4416 	if (!all_requests) LogMsgNoIdent("<None>");
4417 	else
4418 		{
4419 		const request_state *req, *r;
4420 		for (req = all_requests; req; req=req->next)
4421 			{
4422 			if (req->primary)	// If this is a subbordinate operation, check that the parent is in the list
4423 				{
4424 				for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
4425 				LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
4426 				}
4427 			// For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
4428 			LogClientInfo(m, req);
4429 			foundparent:;
4430 			}
4431 		}
4432 
4433 	LogMsgNoIdent("-------- NAT Traversals --------");
4434 	if (!m->NATTraversals) LogMsgNoIdent("<None>");
4435 	else
4436 		{
4437 		const NATTraversalInfo *nat;
4438 		for (nat = m->NATTraversals; nat; nat=nat->next)
4439 			{
4440 			if (nat->Protocol)
4441 				LogMsgNoIdent("%p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d",
4442 					nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
4443 					mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
4444 					nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
4445 					nat->retryInterval / mDNSPlatformOneSecond,
4446 					nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0);
4447 			else
4448 				LogMsgNoIdent("%p Address Request               Retry %5d Interval %5d", nat,
4449 					(m->retryGetAddr - now) / mDNSPlatformOneSecond,
4450 					m->retryIntervalGetAddr / mDNSPlatformOneSecond);
4451 			usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4452 			}
4453 		}
4454 
4455 	LogMsgNoIdent("--------- AuthInfoList ---------");
4456 	if (!m->AuthInfoList) LogMsgNoIdent("<None>");
4457 	else
4458 		{
4459 		const DomainAuthInfo *a;
4460 		for (a = m->AuthInfoList; a; a = a->next)
4461 			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 : "");
4462 		}
4463 
4464 	#if APPLE_OSX_mDNSResponder
4465 	LogMsgNoIdent("--------- TunnelClients --------");
4466 	if (!m->TunnelClients) LogMsgNoIdent("<None>");
4467 	else
4468 		{
4469 		const ClientTunnel *c;
4470 		for (c = m->TunnelClients; c; c = c->next)
4471 			LogMsgNoIdent("%s %##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
4472 				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);
4473 		}
4474 	#endif // APPLE_OSX_mDNSResponder
4475 
4476 	LogMsgNoIdent("---------- Misc State ----------");
4477 
4478 	LogMsgNoIdent("PrimaryMAC:   %.6a", &m->PrimaryMAC);
4479 
4480 	LogMsgNoIdent("m->SleepState %d (%s) seq %d",
4481 		m->SleepState,
4482 		m->SleepState == SleepState_Awake        ? "Awake"        :
4483 		m->SleepState == SleepState_Transferring ? "Transferring" :
4484 		m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?",
4485 		m->SleepSeqNum);
4486 
4487 	if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
4488 	else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
4489 
4490 	if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
4491 	else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
4492 
4493 	LogMsgNoIdent("------ Auto Browse Domains -----");
4494 	if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
4495 	else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
4496 
4497 	LogMsgNoIdent("--- Auto Registration Domains --");
4498 	if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
4499 	else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
4500 
4501  	LogMsgNoIdent("--- Search Domains --");
4502  	if (!SearchList) LogMsgNoIdent("<None>");
4503  	else
4504  		{
4505  		for (s=SearchList; s; s=s->next)
4506  			{
4507  			char *ifname = InterfaceNameForID(m, s->InterfaceID);
4508  			LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
4509  			}
4510  		}
4511 
4512 	LogMsgNoIdent("---- Task Scheduling Timers ----");
4513 
4514 	if (!m->NewQuestions)
4515 		LogMsgNoIdent("NewQuestion <NONE>");
4516 	else
4517 		LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
4518 			m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
4519 			m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
4520 
4521 	if (!m->NewLocalOnlyQuestions)
4522 		LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
4523 	else
4524 		LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
4525 			m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
4526 
4527 	if (!m->NewLocalRecords)
4528 		LogMsgNoIdent("NewLocalRecords <NONE>");
4529 	else
4530 		LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
4531 
4532 	LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
4533 	LogMsgNoIdent("LocalRemoveEvents%s",   m->LocalRemoveEvents   ? "" : " <NONE>");
4534 	LogMsgNoIdent("m->RegisterAutoTunnel6  %08X", m->RegisterAutoTunnel6);
4535 	LogMsgNoIdent("m->AutoTunnelRelayAddrIn  %.16a", &m->AutoTunnelRelayAddrIn);
4536 	LogMsgNoIdent("m->AutoTunnelRelayAddrOut  %.16a", &m->AutoTunnelRelayAddrOut);
4537 
4538 #define LogTimer(MSG,T) LogMsgNoIdent( MSG " %08X %11d  %08X %11d", (T), (T), (T)-now, (T)-now)
4539 
4540 	LogMsgNoIdent("                         ABS (hex)  ABS (dec)  REL (hex)  REL (dec)");
4541 	LogMsgNoIdent("m->timenow               %08X %11d", now, now);
4542 	LogMsgNoIdent("m->timenow_adjust        %08X %11d", m->timenow_adjust, m->timenow_adjust);
4543 	LogTimer("m->NextScheduledEvent   ", m->NextScheduledEvent);
4544 
4545 #ifndef UNICAST_DISABLED
4546 	LogTimer("m->NextuDNSEvent        ", m->NextuDNSEvent);
4547 	LogTimer("m->NextSRVUpdate        ", m->NextSRVUpdate);
4548 	LogTimer("m->NextScheduledNATOp   ", m->NextScheduledNATOp);
4549 	LogTimer("m->retryGetAddr         ", m->retryGetAddr);
4550 #endif
4551 
4552 	LogTimer("m->NextCacheCheck       ", m->NextCacheCheck);
4553 	LogTimer("m->NextScheduledSPS     ", m->NextScheduledSPS);
4554 	LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
4555 	LogTimer("m->DelaySleep           ", m->DelaySleep);
4556 
4557 	LogTimer("m->NextScheduledQuery   ", m->NextScheduledQuery);
4558 	LogTimer("m->NextScheduledProbe   ", m->NextScheduledProbe);
4559 	LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
4560 
4561 	LogTimer("m->SuppressSending      ", m->SuppressSending);
4562 	LogTimer("m->SuppressProbes       ", m->SuppressProbes);
4563 	LogTimer("m->ProbeFailTime        ", m->ProbeFailTime);
4564 	LogTimer("m->DelaySleep           ", m->DelaySleep);
4565 	LogTimer("m->SleepLimit           ", m->SleepLimit);
4566 	LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
4567 	}
4568 
4569 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
uds_validatelists(void)4570 mDNSexport void uds_validatelists(void)
4571 	{
4572 	const request_state *req, *p;
4573 	for (req = all_requests; req; req=req->next)
4574 		{
4575 		if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
4576 			LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
4577 
4578 		if (req->primary == req)
4579 			LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
4580 
4581 		if (req->primary && req->replies)
4582 			LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
4583 				req, req->sd, req->primary && req->replies);
4584 
4585 		p = req->primary;
4586 		if ((long)p & 3)
4587 			LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
4588 		else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
4589 			LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
4590 
4591 		reply_state *rep;
4592 		for (rep = req->replies; rep; rep=rep->next)
4593 		  if (rep->next == (reply_state *)~0)
4594 			LogMemCorruption("UDS req->replies: %p is garbage", rep);
4595 
4596 		if (req->terminate == connection_termination)
4597 			{
4598 			registered_record_entry *r;
4599 			for (r = req->u.reg_recs; r; r=r->next)
4600 				if (r->next == (registered_record_entry *)~0)
4601 					LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
4602 			}
4603 		else if (req->terminate == regservice_termination_callback)
4604 			{
4605 			service_instance *s;
4606 			for (s = req->u.servicereg.instances; s; s=s->next)
4607 				if (s->next == (service_instance *)~0)
4608 					LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
4609 			}
4610 		else if (req->terminate == browse_termination_callback)
4611 			{
4612 			browser_t *b;
4613 			for (b = req->u.browser.browsers; b; b=b->next)
4614 				if (b->next == (browser_t *)~0)
4615 					LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
4616 			}
4617 		}
4618 
4619 	DNameListElem *d;
4620 	for (d = SCPrefBrowseDomains; d; d=d->next)
4621 		if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4622 			LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
4623 
4624 	ARListElem *b;
4625 	for (b = LocalDomainEnumRecords; b; b=b->next)
4626 		if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
4627 			LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
4628 
4629 	for (d = AutoBrowseDomains; d; d=d->next)
4630 		if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4631 			LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
4632 
4633 	for (d = AutoRegistrationDomains; d; d=d->next)
4634 		if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4635 			LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
4636 	}
4637 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4638 
send_msg(request_state * const req)4639 mDNSlocal int send_msg(request_state *const req)
4640 	{
4641 	reply_state *const rep = req->replies;		// Send the first waiting reply
4642 	ssize_t nwriten;
4643 	if (req->no_reply) return(t_complete);
4644 
4645 	ConvertHeaderBytes(rep->mhdr);
4646 	nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
4647 	ConvertHeaderBytes(rep->mhdr);
4648 
4649 	if (nwriten < 0)
4650 		{
4651 		if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
4652 		else
4653 			{
4654 #if !defined(PLATFORM_NO_EPIPE)
4655 			if (dnssd_errno == EPIPE)
4656 				return(req->ts = t_terminated);
4657 			else
4658 #endif
4659 				{
4660 				LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
4661 					rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4662 				return(t_error);
4663 				}
4664 			}
4665 		}
4666 	rep->nwriten += nwriten;
4667 	return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
4668 	}
4669 
udsserver_idle(mDNSs32 nextevent)4670 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
4671 	{
4672 	mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
4673 	request_state **req = &all_requests;
4674 
4675 	while (*req)
4676 		{
4677 		request_state *const r = *req;
4678 
4679 		if (r->terminate == resolve_termination_callback)
4680 			if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
4681 				{
4682 				r->u.resolve.ReportTime = 0;
4683 				LogMsgNoIdent("Client application bug: DNSServiceResolve(%##s) active for over two minutes. "
4684 					"This places considerable burden on the network.", r->u.resolve.qsrv.qname.c);
4685 				}
4686 
4687 		// Note: Only primary req's have reply lists, not subordinate req's.
4688 		while (r->replies)		// Send queued replies
4689 			{
4690 			transfer_state result;
4691 			if (r->replies->next) r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
4692 			result = send_msg(r);	// Returns t_morecoming if buffer full because client is not reading
4693 			if (result == t_complete)
4694 				{
4695 				reply_state *fptr = r->replies;
4696 				r->replies = r->replies->next;
4697 				freeL("reply_state/udsserver_idle", fptr);
4698 				r->time_blocked = 0; // reset failure counter after successful send
4699 				r->unresponsiveness_reports = 0;
4700 				continue;
4701 				}
4702 			else if (result == t_terminated || result == t_error)
4703 				{
4704 				LogMsg("%3d: Could not write data to client because of error - aborting connection", r->sd);
4705 				LogClientInfo(&mDNSStorage, r);
4706 				abort_request(r);
4707 				}
4708 			break;
4709 			}
4710 
4711 		if (r->replies)		// If we failed to send everything, check our time_blocked timer
4712 			{
4713 			if (nextevent - now > mDNSPlatformOneSecond) nextevent = now + mDNSPlatformOneSecond;
4714 
4715 			if (mDNSStorage.SleepState != SleepState_Awake) r->time_blocked = 0;
4716 			else if (!r->time_blocked) r->time_blocked = NonZeroTime(now);
4717 			else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
4718 				{
4719 				int num = 0;
4720 				struct reply_state *x = r->replies;
4721 				while (x) { num++; x=x->next; }
4722 				LogMsg("%3d: Could not write data to client after %ld seconds, %d repl%s waiting",
4723 					r->sd, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
4724 				if (++r->unresponsiveness_reports >= 60)
4725 					{
4726 					LogMsg("%3d: Client unresponsive; aborting connection", r->sd);
4727 					LogClientInfo(&mDNSStorage, r);
4728 					abort_request(r);
4729 					}
4730 				}
4731 			}
4732 
4733 		if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
4734 			{
4735 			// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
4736 			*req = r->next;
4737 			freeL("request_state/udsserver_idle", r);
4738 			}
4739 		else
4740 			req = &r->next;
4741 		}
4742 	return nextevent;
4743 	}
4744 
4745 struct CompileTimeAssertionChecks_uds_daemon
4746 	{
4747 	// Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4748 	// other overly-large structures instead of having a pointer to them, can inadvertently
4749 	// cause structure sizes (and therefore memory usage) to balloon unreasonably.
4750 	char sizecheck_request_state          [(sizeof(request_state)           <= 1784) ? 1 : -1];
4751 	char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <=   60) ? 1 : -1];
4752 	char sizecheck_service_instance       [(sizeof(service_instance)        <= 6552) ? 1 : -1];
4753 	char sizecheck_browser_t              [(sizeof(browser_t)               <= 1050) ? 1 : -1];
4754 	char sizecheck_reply_hdr              [(sizeof(reply_hdr)               <=   12) ? 1 : -1];
4755 	char sizecheck_reply_state            [(sizeof(reply_state)             <=   64) ? 1 : -1];
4756 	};
4757