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 	*(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 
1598 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
1599 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
1600 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
1601 	if (interfaceIndex && !InterfaceID)
1602 		{ LogMsg("ERROR: handle_regservice_request - Couldn't find interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); }
1603 
1604 	if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
1605 		get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1606 		get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1607 		get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
1608 		{ LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
1609 
1610 	request->flags = flags;
1611 	request->u.servicereg.InterfaceID = InterfaceID;
1612 	request->u.servicereg.instances = NULL;
1613 	request->u.servicereg.txtlen  = 0;
1614 	request->u.servicereg.txtdata = NULL;
1615 	mDNSPlatformStrCopy(request->u.servicereg.type_as_string, type_as_string);
1616 
1617 	if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
1618 	else
1619 		{
1620 		request->u.servicereg.port.b[0] = *request->msgptr++;
1621 		request->u.servicereg.port.b[1] = *request->msgptr++;
1622 		}
1623 
1624 	request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
1625 	if (request->u.servicereg.txtlen)
1626 		{
1627 		request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
1628 		if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
1629 		mDNSPlatformMemCopy(request->u.servicereg.txtdata, get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen), request->u.servicereg.txtlen);
1630 		}
1631 
1632 	if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1633 
1634 	// Check for sub-types after the service type
1635 	request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string);	// Note: Modifies regtype string to remove trailing subtypes
1636 	if (request->u.servicereg.num_subtypes < 0)
1637 		{ LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); }
1638 
1639 	// Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1640 	if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
1641 		{ LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); }
1642 
1643 	if (!name[0])
1644 		{
1645 		request->u.servicereg.name = mDNSStorage.nicelabel;
1646 		request->u.servicereg.autoname = mDNStrue;
1647 		}
1648 	else
1649 		{
1650 		// If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1651 		if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
1652 			{
1653 			int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
1654 			name[newlen] = 0;
1655 			}
1656 		if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
1657 			{ LogMsg("ERROR: handle_regservice_request - name bad %s", name); return(mStatus_BadParamErr); }
1658 		request->u.servicereg.autoname = mDNSfalse;
1659 		}
1660 
1661 	if (*domain)
1662 		{
1663 		request->u.servicereg.default_domain = mDNSfalse;
1664 		if (!MakeDomainNameFromDNSNameString(&d, domain))
1665 			{ LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); return(mStatus_BadParamErr); }
1666 		}
1667 	else
1668 		{
1669 		request->u.servicereg.default_domain = mDNStrue;
1670 		MakeDomainNameFromDNSNameString(&d, "local.");
1671 		}
1672 
1673 	if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
1674 		{
1675 		LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1676 			request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); return(mStatus_BadParamErr);
1677 		}
1678 
1679 	if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
1680 		{ LogMsg("ERROR: handle_regservice_request - host bad %s", host); return(mStatus_BadParamErr); }
1681 	request->u.servicereg.autorename       = (flags & kDNSServiceFlagsNoAutoRename    ) == 0;
1682 	request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
1683 
1684 	// Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1685 	// a port number of zero. When two instances of the protected client are allowed to run on one
1686 	// machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1687 	if (!mDNSIPPortIsZero(request->u.servicereg.port))
1688 		{
1689 		int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
1690 		if (count)
1691 			LogMsg("Client application registered %d identical instances of service %##s port %u.",
1692 				count+1, srv.c, mDNSVal16(request->u.servicereg.port));
1693 		}
1694 
1695 	LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START",
1696 		request->sd, flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host, mDNSVal16(request->u.servicereg.port));
1697 
1698 	// We need to unconditionally set request->terminate, because even if we didn't successfully
1699 	// start any registrations right now, subsequent configuration changes may cause successful
1700 	// registrations to be added, and we'll need to cancel them before freeing this memory.
1701 	// We also need to set request->terminate first, before adding additional service instances,
1702 	// because the uds_validatelists uses the request->terminate function pointer to determine
1703 	// what kind of request this is, and therefore what kind of list validation is required.
1704 	request->terminate = regservice_termination_callback;
1705 
1706 	err = register_service_instance(request, &d);
1707 
1708 #if 0
1709 	err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
1710 #endif
1711 	if (!err)
1712 		{
1713 		if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
1714 
1715 		if (!*domain)
1716 			{
1717 			DNameListElem *ptr;
1718 			// Note that we don't report errors for non-local, non-explicit domains
1719 			for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
1720 				if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
1721 					register_service_instance(request, &ptr->name);
1722 			}
1723 		}
1724 
1725 	return(err);
1726 	}
1727 
1728 // ***************************************************************************
1729 #if COMPILER_LIKES_PRAGMA_MARK
1730 #pragma mark -
1731 #pragma mark - DNSServiceBrowse
1732 #endif
1733 
FoundInstance(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)1734 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
1735 	{
1736 	const DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
1737 	request_state *req = question->QuestionContext;
1738 	reply_state *rep;
1739 	(void)m; // Unused
1740 
1741 	if (answer->rrtype != kDNSType_PTR)
1742 		{ LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
1743 
1744 	if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
1745 		{
1746 		if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
1747 			{
1748 			// Special support to enable the DNSServiceBrowse call made by Bonjour Browser
1749 			// Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
1750 			GenerateBonjourBrowserResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
1751 			goto bonjourbrowserhack;
1752 			}
1753 
1754 		LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
1755 			req->sd, answer->name->c, answer->rdata->u.name.c);
1756 		return;
1757 		}
1758 
1759 bonjourbrowserhack:
1760 
1761 	LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
1762 		req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "Add" : "Rmv",
1763 		mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
1764 
1765 	append_reply(req, rep);
1766 	}
1767 
add_domain_to_browser(request_state * info,const domainname * d)1768 mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
1769 	{
1770 	browser_t *b, *p;
1771 	mStatus err;
1772 
1773 	for (p = info->u.browser.browsers; p; p = p->next)
1774 		{
1775 		if (SameDomainName(&p->domain, d))
1776 			{ debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
1777 		}
1778 
1779 	b = mallocL("browser_t", sizeof(*b));
1780 	if (!b) return mStatus_NoMemoryErr;
1781 	AssignDomainName(&b->domain, d);
1782 	err = mDNS_StartBrowse(&mDNSStorage, &b->q,
1783 		&info->u.browser.regtype, d, info->u.browser.interface_id, info->u.browser.ForceMCast, FoundInstance, info);
1784 	if (err)
1785 		{
1786 		LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
1787 		freeL("browser_t/add_domain_to_browser", b);
1788 		}
1789 	else
1790 		{
1791 		b->next = info->u.browser.browsers;
1792 		info->u.browser.browsers = b;
1793 		LogOperation("%3d: DNSServiceBrowse(%##s) START", info->sd, b->q.qname.c);
1794 		if (info->u.browser.interface_id == mDNSInterface_P2P || (!info->u.browser.interface_id && SameDomainName(&b->domain, &localdomain) && (info->flags & kDNSServiceFlagsIncludeP2P)))
1795 			{
1796 			domainname tmp;
1797 			ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
1798 			LogInfo("add_domain_to_browser: calling external_start_browsing_for_service()");
1799 			external_start_browsing_for_service(&mDNSStorage, &tmp, kDNSType_PTR);
1800 			}
1801 		}
1802 	return err;
1803 	}
1804 
browse_termination_callback(request_state * info)1805 mDNSlocal void browse_termination_callback(request_state *info)
1806 	{
1807 	while (info->u.browser.browsers)
1808 		{
1809 		browser_t *ptr = info->u.browser.browsers;
1810 
1811 		if (info->u.browser.interface_id == mDNSInterface_P2P || (!info->u.browser.interface_id && SameDomainName(&ptr->domain, &localdomain) && (info->flags & kDNSServiceFlagsIncludeP2P)))
1812 			{
1813 			domainname tmp;
1814 			ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
1815 			LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
1816 			external_stop_browsing_for_service(&mDNSStorage, &tmp, kDNSType_PTR);
1817 			}
1818 
1819 		info->u.browser.browsers = ptr->next;
1820 		LogOperation("%3d: DNSServiceBrowse(%##s) STOP", info->sd, ptr->q.qname.c);
1821 		mDNS_StopBrowse(&mDNSStorage, &ptr->q);  // no need to error-check result
1822 		freeL("browser_t/browse_termination_callback", ptr);
1823 		}
1824 	}
1825 
udsserver_automatic_browse_domain_changed(const DNameListElem * const d,const mDNSBool add)1826 mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
1827 	{
1828 	request_state *request;
1829 	debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
1830 
1831 #if APPLE_OSX_mDNSResponder
1832 	machserver_automatic_browse_domain_changed(&d->name, add);
1833 #endif // APPLE_OSX_mDNSResponder
1834 
1835 	for (request = all_requests; request; request = request->next)
1836 		{
1837 		if (request->terminate != browse_termination_callback) continue;	// Not a browse operation
1838 		if (!request->u.browser.default_domain) continue;					// Not an auto-browse operation
1839 		if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1840 			{
1841 			browser_t **ptr = &request->u.browser.browsers;
1842 			while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1843 			if (add)
1844 				{
1845 				// If we don't already have this domain in our list for this browse operation, add it now
1846 				if (!*ptr) add_domain_to_browser(request, &d->name);
1847 				else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
1848 				}
1849 			else
1850 				{
1851 				if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
1852 				else
1853 					{
1854 					DNameListElem *p;
1855 					for (p = AutoBrowseDomains; p; p=p->next)
1856 						if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1857 							if (SameDomainName(&d->name, &p->name)) break;
1858 					if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
1859 					else
1860 						{
1861 						browser_t *rem = *ptr;
1862 						*ptr = (*ptr)->next;
1863 						mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
1864 						freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
1865 						}
1866 					}
1867 				}
1868 			}
1869 		}
1870 	}
1871 
FreeARElemCallback(mDNS * const m,AuthRecord * const rr,mStatus result)1872 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
1873 	{
1874 	(void)m;  // unused
1875 	if (result == mStatus_MemFree)
1876 		{
1877 		// On shutdown, mDNS_Close automatically deregisters all records
1878 		// Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
1879 		// from the LocalDomainEnumRecords list, we do this here before we free the memory.
1880 		// (This should actually no longer be necessary, now that we do the proper cleanup in
1881 		// udsserver_exit. To confirm this, we'll log an error message if we do find a record that
1882 		// hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
1883 		ARListElem **ptr = &LocalDomainEnumRecords;
1884 		while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
1885 		if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
1886 		mDNSPlatformMemFree(rr->RecordContext);
1887 		}
1888 	}
1889 
1890 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
1891 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
1892 // We may want to turn the common code into a subroutine.
1893 
RegisterLocalOnlyDomainEnumPTR(mDNS * m,const domainname * d,int type)1894 mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
1895 	{
1896 	// allocate/register legacy and non-legacy _browse PTR record
1897 	mStatus err;
1898 	ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
1899 
1900 	debugf("Incrementing %s refcount for %##s",
1901 		(type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
1902 		(type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
1903 		(type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
1904 
1905 	mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
1906 	MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
1907 	AppendDNSNameString            (&ptr->ar.namestorage, "local");
1908 	AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
1909 	err = mDNS_Register(m, &ptr->ar);
1910 	if (err)
1911 		{
1912 		LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
1913 		mDNSPlatformMemFree(ptr);
1914 		}
1915 	else
1916 		{
1917 		ptr->next = LocalDomainEnumRecords;
1918 		LocalDomainEnumRecords = ptr;
1919 		}
1920 	}
1921 
DeregisterLocalOnlyDomainEnumPTR(mDNS * m,const domainname * d,int type)1922 mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
1923 	{
1924 	ARListElem **ptr = &LocalDomainEnumRecords;
1925 	domainname lhs; // left-hand side of PTR, for comparison
1926 
1927 	debugf("Decrementing %s refcount for %##s",
1928 		(type == mDNS_DomainTypeBrowse         ) ? "browse domain   " :
1929 		(type == mDNS_DomainTypeRegistration   ) ? "registration dom" :
1930 		(type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
1931 
1932 	MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
1933 	AppendDNSNameString            (&lhs, "local");
1934 
1935 	while (*ptr)
1936 		{
1937 		if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
1938 			{
1939 			ARListElem *rem = *ptr;
1940 			*ptr = (*ptr)->next;
1941 			mDNS_Deregister(m, &rem->ar);
1942 			return;
1943 			}
1944 		else ptr = &(*ptr)->next;
1945 		}
1946 	}
1947 
AddAutoBrowseDomain(const mDNSu32 uid,const domainname * const name)1948 mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
1949 	{
1950 	DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
1951 	if (!new) { LogMsg("ERROR: malloc"); return; }
1952 	AssignDomainName(&new->name, name);
1953 	new->uid = uid;
1954 	new->next = AutoBrowseDomains;
1955 	AutoBrowseDomains = new;
1956 	udsserver_automatic_browse_domain_changed(new, mDNStrue);
1957 	}
1958 
RmvAutoBrowseDomain(const mDNSu32 uid,const domainname * const name)1959 mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
1960 	{
1961 	DNameListElem **p = &AutoBrowseDomains;
1962 	while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
1963 	if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
1964 	else
1965 		{
1966 		DNameListElem *ptr = *p;
1967 		*p = ptr->next;
1968 		udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
1969 		mDNSPlatformMemFree(ptr);
1970 		}
1971 	}
1972 
SetPrefsBrowseDomains(mDNS * m,DNameListElem * browseDomains,mDNSBool add)1973 mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
1974 	{
1975 	DNameListElem *d;
1976 	for (d = browseDomains; d; d = d->next)
1977 		{
1978 		if (add)
1979 			{
1980 			RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
1981 			AddAutoBrowseDomain(d->uid, &d->name);
1982 			}
1983 		else
1984 			{
1985 			DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
1986 			RmvAutoBrowseDomain(d->uid, &d->name);
1987 			}
1988 		}
1989 	}
1990 
UpdateDeviceInfoRecord(mDNS * const m)1991 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
1992 	{
1993 	int num_autoname = 0;
1994 	request_state *req;
1995 	for (req = all_requests; req; req = req->next)
1996 		if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname)
1997 			num_autoname++;
1998 
1999 	// If DeviceInfo record is currently registered, see if we need to deregister it
2000 	if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
2001 		if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
2002 			{
2003 			LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
2004 			mDNS_Deregister(m, &m->DeviceInfo);
2005 			}
2006 
2007 	// If DeviceInfo record is not currently registered, see if we need to register it
2008 	if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
2009 		if (num_autoname > 0)
2010 			{
2011 			mDNSu8 len = m->HIHardware.c[0] < 255 - 6 ? m->HIHardware.c[0] : 255 - 6;
2012 			mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
2013 			ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
2014 			mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 1, "model=", 6);
2015 			mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 7, m->HIHardware.c + 1, len);
2016 			m->DeviceInfo.resrec.rdata->u.data[0] = 6 + len;	// "model=" plus the device string
2017 			m->DeviceInfo.resrec.rdlength         = 7 + len;	// One extra for the length byte at the start of the string
2018 			LogOperation("UpdateDeviceInfoRecord   Register %##s", m->DeviceInfo.resrec.name);
2019 			mDNS_Register(m, &m->DeviceInfo);
2020 			}
2021 	}
2022 
udsserver_handle_configchange(mDNS * const m)2023 mDNSexport void udsserver_handle_configchange(mDNS *const m)
2024 	{
2025 	request_state *req;
2026 	service_instance *ptr;
2027 	DNameListElem *RegDomains = NULL;
2028 	DNameListElem *BrowseDomains = NULL;
2029 	DNameListElem *p;
2030 
2031 	UpdateDeviceInfoRecord(m);
2032 
2033 	// For autoname services, see if the default service name has changed, necessitating an automatic update
2034 	for (req = all_requests; req; req = req->next)
2035 		if (req->terminate == regservice_termination_callback)
2036 			if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
2037 				{
2038 				req->u.servicereg.name = m->nicelabel;
2039 				for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
2040 					{
2041 					ptr->renameonmemfree = 1;
2042 					if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
2043 					LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
2044 					if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
2045 						regservice_callback(m, &ptr->srs, mStatus_MemFree);	// If service deregistered already, we can re-register immediately
2046 					}
2047 				}
2048 
2049 	// Let the platform layer get the current DNS information
2050 	mDNS_Lock(m);
2051 	mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains);
2052 	mDNS_Unlock(m);
2053 
2054 	// Any automatic registration domains are also implicitly automatic browsing domains
2055 	if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue);								// Add the new list first
2056 	if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse);	// Then clear the old list
2057 
2058 	// Add any new domains not already in our AutoRegistrationDomains list
2059 	for (p=RegDomains; p; p=p->next)
2060 		{
2061 		DNameListElem **pp = &AutoRegistrationDomains;
2062 		while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
2063 		if (!*pp)		// If not found in our existing list, this is a new default registration domain
2064 			{
2065 			RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
2066 			udsserver_default_reg_domain_changed(p, mDNStrue);
2067 			}
2068 		else			// else found same domainname in both old and new lists, so no change, just delete old copy
2069 			{
2070 			DNameListElem *del = *pp;
2071 			*pp = (*pp)->next;
2072 			mDNSPlatformMemFree(del);
2073 			}
2074 		}
2075 
2076 	// Delete any domains in our old AutoRegistrationDomains list that are now gone
2077 	while (AutoRegistrationDomains)
2078 		{
2079 		DNameListElem *del = AutoRegistrationDomains;
2080 		AutoRegistrationDomains = AutoRegistrationDomains->next;		// Cut record from list FIRST,
2081 		DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
2082 		udsserver_default_reg_domain_changed(del, mDNSfalse);			// before calling udsserver_default_reg_domain_changed()
2083 		mDNSPlatformMemFree(del);
2084 		}
2085 
2086 	// Now we have our new updated automatic registration domain list
2087 	AutoRegistrationDomains = RegDomains;
2088 
2089 	// Add new browse domains to internal list
2090 	if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
2091 
2092 	// Remove old browse domains from internal list
2093 	if (SCPrefBrowseDomains)
2094 		{
2095 		SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
2096 		while (SCPrefBrowseDomains)
2097 			{
2098 			DNameListElem *fptr = SCPrefBrowseDomains;
2099 			SCPrefBrowseDomains = SCPrefBrowseDomains->next;
2100 			mDNSPlatformMemFree(fptr);
2101 			}
2102 		}
2103 
2104 	// Replace the old browse domains array with the new array
2105 	SCPrefBrowseDomains = BrowseDomains;
2106 	}
2107 
AutomaticBrowseDomainChange(mDNS * const m,DNSQuestion * q,const ResourceRecord * const answer,QC_result AddRecord)2108 mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
2109 	{
2110 	(void)m; // unused;
2111 	(void)q; // unused
2112 
2113 	LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2114 		AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
2115 
2116 	if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
2117 	else           RmvAutoBrowseDomain(0, &answer->rdata->u.name);
2118 	}
2119 
handle_sethost_request(request_state * request)2120 mDNSlocal mStatus handle_sethost_request(request_state *request)
2121 {
2122 	get_flags(&request->msgptr, request->msgend);
2123 	char hostName[MAX_DOMAIN_LABEL];
2124 	int len = 0;
2125 	if (get_string(&request->msgptr, request->msgend, hostName,
2126 		MAX_DOMAIN_LABEL) < 0) return (mStatus_BadParamErr);
2127 	LogOperation("%3d: DNSSetHostname(%X, %d, nonstr ) START",
2128 		request->sd, request->flags);
2129 	// if we start using this as a callback for notification when the
2130 	// hostname changes we may need to cleanup from it
2131 	//  request->terminate = sethost_termination_callback;
2132 	if(hostName[0] == 0) return mStatus_BadParamErr;
2133 		while (len < MAX_DOMAIN_LABEL && hostName[len+1]
2134 			&& hostName[len+1] != '.') len++;
2135 	strncpy(&(mDNSStorage.nicelabel.c[1]), hostName, len);
2136 	mDNSStorage.nicelabel.c[0] = len;
2137 	strncpy(&(mDNSStorage.hostlabel.c[1]), hostName, len);
2138 	mDNSStorage.hostlabel.c[0] = len;
2139 	mDNS_SetFQDN(&mDNSStorage);
2140 	return mStatus_NoError;
2141 }
2142 
handle_browse_request(request_state * request)2143 mDNSlocal mStatus handle_browse_request(request_state *request)
2144 	{
2145 	char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2146 	domainname typedn, d, temp;
2147 	mDNSs32 NumSubTypes;
2148 	mStatus err = mStatus_NoError;
2149 
2150 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2151 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2152 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2153 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
2154 
2155 	if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2156 		get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
2157 
2158 	if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2159 
2160 	if (domain[0] == '\0') uDNS_SetupSearchDomains(&mDNSStorage, UDNS_START_WAB_QUERY);
2161 
2162 	request->flags = flags;
2163 	typedn.c[0] = 0;
2164 	NumSubTypes = ChopSubTypes(regtype);	// Note: Modifies regtype string to remove trailing subtypes
2165 	if (NumSubTypes < 0 || NumSubTypes > 1) return(mStatus_BadParamErr);
2166 	if (NumSubTypes == 1 && !AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1)) return(mStatus_BadParamErr);
2167 
2168 	if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
2169 
2170 	if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
2171 	// For over-long service types, we only allow domain "local"
2172 	if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrCopy(domain, "local.");
2173 
2174 	// Set up browser info
2175 	request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
2176 	request->u.browser.interface_id = InterfaceID;
2177 	AssignDomainName(&request->u.browser.regtype, &typedn);
2178 	request->u.browser.default_domain = !domain[0];
2179 	request->u.browser.browsers = NULL;
2180 
2181 	LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START",
2182 			request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain);
2183 
2184 	// We need to unconditionally set request->terminate, because even if we didn't successfully
2185 	// start any browses right now, subsequent configuration changes may cause successful
2186 	// browses to be added, and we'll need to cancel them before freeing this memory.
2187 	request->terminate = browse_termination_callback;
2188 
2189 	if (domain[0])
2190 		{
2191 		if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
2192 		err = add_domain_to_browser(request, &d);
2193 #if 0
2194 		err = AuthorizedDomain(request, &d, AutoBrowseDomains) ? add_domain_to_browser(request, &d) : mStatus_NoError;
2195 #endif
2196 		}
2197 	else
2198 		{
2199 		DNameListElem *sdom;
2200 		for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
2201 			if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
2202 				{
2203 				err = add_domain_to_browser(request, &sdom->name);
2204 				if (err)
2205 					{
2206 					if (SameDomainName(&sdom->name, &localdomain)) break;
2207 					else err = mStatus_NoError;  // suppress errors for non-local "default" domains
2208 					}
2209 				}
2210 		}
2211 
2212 	return(err);
2213 	}
2214 
2215 // ***************************************************************************
2216 #if COMPILER_LIKES_PRAGMA_MARK
2217 #pragma mark -
2218 #pragma mark - DNSServiceResolve
2219 #endif
2220 
resolve_result_callback(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)2221 mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2222 	{
2223 	size_t len = 0;
2224 	char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME];
2225 	char *data;
2226 	reply_state *rep;
2227 	request_state *req = question->QuestionContext;
2228 	(void)m; // Unused
2229 
2230 	LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req->sd, question->qname.c, AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
2231 
2232 	if (!AddRecord)
2233 		{
2234 		if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
2235 		if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
2236 		return;
2237 		}
2238 
2239 	if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
2240 	if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
2241 
2242 	if (!req->u.resolve.txt || !req->u.resolve.srv) return;		// only deliver result to client if we have both answers
2243 
2244 	ConvertDomainNameToCString(answer->name, fullname);
2245 	ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
2246 
2247 	// calculate reply length
2248 	len += sizeof(DNSServiceFlags);
2249 	len += sizeof(mDNSu32);  // interface index
2250 	len += sizeof(DNSServiceErrorType);
2251 	len += strlen(fullname) + 1;
2252 	len += strlen(target) + 1;
2253 	len += 2 * sizeof(mDNSu16);  // port, txtLen
2254 	len += req->u.resolve.txt->rdlength;
2255 
2256 	// allocate/init reply header
2257 	rep = create_reply(resolve_reply_op, len, req);
2258 	rep->rhdr->flags = dnssd_htonl(0);
2259 	rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
2260 	rep->rhdr->error = dnssd_htonl(kDNSServiceErr_NoError);
2261 
2262 	data = (char *)&rep->rhdr[1];
2263 
2264 	// write reply data to message
2265 	put_string(fullname, &data);
2266 	put_string(target, &data);
2267 	*data++ =  req->u.resolve.srv->rdata->u.srv.port.b[0];
2268 	*data++ =  req->u.resolve.srv->rdata->u.srv.port.b[1];
2269 	put_uint16(req->u.resolve.txt->rdlength, &data);
2270 	put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
2271 
2272 	LogOperation("%3d: DNSServiceResolve(%s) RESULT   %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
2273 	append_reply(req, rep);
2274 	}
2275 
resolve_termination_callback(request_state * request)2276 mDNSlocal void resolve_termination_callback(request_state *request)
2277 	{
2278 	LogOperation("%3d: DNSServiceResolve(%##s) STOP", request->sd, request->u.resolve.qtxt.qname.c);
2279 	mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
2280 	mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2281 	if (request->u.resolve.external_advertise) external_stop_resolving_service(&request->u.resolve.qsrv.qname);
2282 	}
2283 
handle_resolve_request(request_state * request)2284 mDNSlocal mStatus handle_resolve_request(request_state *request)
2285 	{
2286 	char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2287 	domainname fqdn;
2288 	mStatus err;
2289 
2290 	// extract the data from the message
2291 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2292 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2293 	mDNSInterfaceID InterfaceID;
2294 	mDNSBool wasP2P = (interfaceIndex == kDNSServiceInterfaceIndexP2P);
2295 
2296 
2297 	request->flags = flags;
2298 	if (wasP2P) interfaceIndex = kDNSServiceInterfaceIndexAny;
2299 
2300 	InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2301 	if (interfaceIndex && !InterfaceID)
2302 		{ LogMsg("ERROR: handle_resolve_request bad interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); }
2303 
2304 	if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
2305 		get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2306 		get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
2307 		{ LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2308 
2309 	if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2310 
2311 	if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
2312 		{ LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
2313 
2314 	mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
2315 
2316 	// format questions
2317 	request->u.resolve.qsrv.InterfaceID      = InterfaceID;
2318 	request->u.resolve.qsrv.Target           = zeroAddr;
2319 	AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
2320 	request->u.resolve.qsrv.qtype            = kDNSType_SRV;
2321 	request->u.resolve.qsrv.qclass           = kDNSClass_IN;
2322 	request->u.resolve.qsrv.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2323 	request->u.resolve.qsrv.ExpectUnique     = mDNStrue;
2324 	request->u.resolve.qsrv.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
2325 	request->u.resolve.qsrv.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2326 	request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
2327 	request->u.resolve.qsrv.SearchListIndex  = 0;
2328 	request->u.resolve.qsrv.AppendSearchDomains = 0;
2329 	request->u.resolve.qsrv.RetryWithSearchDomains = mDNSfalse;
2330 	request->u.resolve.qsrv.TimeoutQuestion  = 0;
2331 	request->u.resolve.qsrv.WakeOnResolve    = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
2332 	request->u.resolve.qsrv.qnameOrig        = mDNSNULL;
2333 	request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
2334 	request->u.resolve.qsrv.QuestionContext  = request;
2335 
2336 	request->u.resolve.qtxt.InterfaceID      = InterfaceID;
2337 	request->u.resolve.qtxt.Target           = zeroAddr;
2338 	AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn);
2339 	request->u.resolve.qtxt.qtype            = kDNSType_TXT;
2340 	request->u.resolve.qtxt.qclass           = kDNSClass_IN;
2341 	request->u.resolve.qtxt.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2342 	request->u.resolve.qtxt.ExpectUnique     = mDNStrue;
2343 	request->u.resolve.qtxt.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
2344 	request->u.resolve.qtxt.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2345 	request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
2346 	request->u.resolve.qtxt.SearchListIndex  = 0;
2347 	request->u.resolve.qtxt.AppendSearchDomains = 0;
2348 	request->u.resolve.qtxt.RetryWithSearchDomains = mDNSfalse;
2349 	request->u.resolve.qtxt.TimeoutQuestion  = 0;
2350 	request->u.resolve.qtxt.WakeOnResolve    = 0;
2351 	request->u.resolve.qtxt.qnameOrig        = mDNSNULL;
2352 	request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
2353 	request->u.resolve.qtxt.QuestionContext  = request;
2354 
2355 	request->u.resolve.ReportTime            = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
2356 
2357 	request->u.resolve.external_advertise    = mDNSfalse;
2358 
2359 #if 0
2360 	if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains))	return(mStatus_NoError);
2361 #endif
2362 
2363 	// ask the questions
2364 	LogOperation("%3d: DNSServiceResolve(%##s) START", request->sd, request->u.resolve.qsrv.qname.c);
2365 	err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);
2366 	if (!err)
2367 		{
2368 		err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
2369 		if (err) mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2370 		else
2371 			{
2372 			request->terminate = resolve_termination_callback;
2373 			// If the user explicitly passed in P2P, we don't restrict the domain in which we resolve.
2374 			if (wasP2P || (!InterfaceID && IsLocalDomain(&fqdn) && (request->flags & kDNSServiceFlagsIncludeP2P)))
2375 				{
2376 				request->u.resolve.external_advertise    = mDNStrue;
2377 				LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2378 				external_start_resolving_service(&fqdn);
2379 				}
2380 			}
2381 		}
2382 
2383 	return(err);
2384 	}
2385 
2386 // ***************************************************************************
2387 #if COMPILER_LIKES_PRAGMA_MARK
2388 #pragma mark -
2389 #pragma mark - DNSServiceQueryRecord
2390 #endif
2391 
2392 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2393 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2394 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2395 // the mDNSCore operation if the client dies or closes its socket.
2396 
2397 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2398 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2399 // Returns 0 when there are no more search domains and the caller should reissue the query
AppendNewSearchDomain(mDNS * const m,DNSQuestion * question)2400 mDNSlocal int AppendNewSearchDomain(mDNS *const m, DNSQuestion *question)
2401 	{
2402 	domainname *sd;
2403 	mStatus err;
2404 
2405 	// Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2406 	// the domains and should try the single label query directly on the wire.
2407 	if (question->SearchListIndex == -1)
2408 		{
2409 		LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question->qname.c, DNSTypeName(question->qtype));
2410 		return -1;
2411 		}
2412 
2413 	if (!question->AppendSearchDomains)
2414 		{
2415 		LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question->qname.c, DNSTypeName(question->qtype));
2416 		return -1;
2417 		}
2418 
2419 	// Save the original name, before we modify them below.
2420 	if (!question->qnameOrig)
2421 		{
2422 		question->qnameOrig =  mallocL("AppendNewSearchDomain", sizeof(domainname));
2423 		if (!question->qnameOrig) { LogMsg("AppendNewSearchDomain: ERROR!!  malloc failure"); return -1; }
2424 		question->qnameOrig->c[0] = 0;
2425 		AssignDomainName(question->qnameOrig, &question->qname);
2426 		LogInfo("AppendSearchDomain: qnameOrig %##s", question->qnameOrig->c);
2427 		}
2428 
2429 	sd = uDNS_GetNextSearchDomain(m, question->InterfaceID, &question->SearchListIndex, !question->AppendLocalSearchDomains);
2430 	// We use -1 to indicate that we have searched all the domains and should try the single label
2431 	// query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2432 	if (question->SearchListIndex == -1)
2433 		{
2434 		LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2435 		return -1;
2436 		}
2437 
2438 	// Not a common case. Perhaps, we should try the next search domain if it exceeds ?
2439 	if (sd && (DomainNameLength(question->qnameOrig) + DomainNameLength(sd)) > MAX_DOMAIN_NAME)
2440 		{
2441 		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));
2442 		return -1;
2443 		}
2444 
2445 	// if there are no more search domains and we have already tried this question
2446 	// without appending search domains, then we are done.
2447 	if (!sd && !ApplySearchDomainsFirst(question))
2448 		{
2449 		LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question->qname.c, DNSTypeName(question->qtype));
2450 		return -1;
2451 		}
2452 
2453 	// Stop the question before changing the name as negative cache entries could be pointing at this question.
2454 	// Even if we don't change the question in the case of returning 0, the caller is going to restart the
2455 	// question.
2456 	err = mDNS_StopQuery(&mDNSStorage, question);
2457 	if (err) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question->qname.c, DNSTypeName(question->qtype), (int)err); }
2458 
2459 	AssignDomainName(&question->qname, question->qnameOrig);
2460 	if (sd)
2461 		{
2462 		AppendDomainName(&question->qname, sd);
2463 		LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question->qname.c, question->SearchListIndex);
2464 		return 1;
2465 		}
2466 
2467 	// Try the question as single label
2468 	LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question->qname.c, DNSTypeName(question->qtype));
2469 	return 0;
2470 	}
2471 
2472 #if APPLE_OSX_mDNSResponder
2473 
DomainInSearchList(domainname * domain)2474 mDNSlocal mDNSBool DomainInSearchList(domainname *domain)
2475 	{
2476 	const SearchListElem *s;
2477  	for (s=SearchList; s; s=s->next)
2478 		if (SameDomainName(&s->domain, domain)) return mDNStrue;
2479 	return mDNSfalse;
2480 	}
2481 
2482 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
2483 // top-level domain
SendAdditionalQuery(DNSQuestion * q,request_state * request,mStatus err)2484 mDNSlocal mStatus SendAdditionalQuery(DNSQuestion *q, request_state *request, mStatus err)
2485 	{
2486 	extern domainname ActiveDirectoryPrimaryDomain;
2487 	DNSQuestion **question2;
2488 	#define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
2489 	#define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
2490 
2491 	question2 = mDNSNULL;
2492 	if (request->hdr.op == query_request)
2493 		question2 = &request->u.queryrecord.q2;
2494 	else if (request->hdr.op == addrinfo_request)
2495 		{
2496 		if (q->qtype == kDNSType_A)
2497 			question2 = &request->u.addrinfo.q42;
2498 		else if (q->qtype == kDNSType_AAAA)
2499 			question2 = &request->u.addrinfo.q62;
2500 		}
2501 	if (!question2)
2502 		{
2503 		LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2504 		return mStatus_BadParamErr;
2505 		}
2506 
2507 	// Sanity check: If we already sent an additonal query, we don't need to send one more.
2508 	//
2509 	// 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
2510 	// is called to see whether a unicast query should be sent or not.
2511 	//
2512 	// 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
2513 	// was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
2514 	// send the additional query.
2515 	//
2516 	// Thus, it should not be called more than once.
2517 	if (*question2)
2518 		{
2519 		LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q->qname.c, DNSTypeName(q->qtype));
2520 		return err;
2521 		}
2522 
2523 	if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
2524 		if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q))
2525 			{
2526 			DNSQuestion *q2;
2527 			int labels = CountLabels(&q->qname);
2528 			q2 = mallocL("DNSQuestion", sizeof(DNSQuestion));
2529 			if (!q2) FatalError("ERROR: SendAdditionalQuery malloc");
2530 			*question2        = q2;
2531 			*q2               = *q;
2532 			q2->InterfaceID   = mDNSInterface_Unicast;
2533 			q2->ExpectUnique  = mDNStrue;
2534 			// If the query starts as a single label e.g., somehost, and we have search domains with .local,
2535 			// queryrecord_result_callback calls this function when .local is appended to "somehost".
2536 			// At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
2537 			// "somehost". We need to copy that information so that when we retry with a different search
2538 			// domain e.g., mycompany.local, we get "somehost.mycompany.local".
2539 			if (q->qnameOrig)
2540 				{
2541 				(*question2)->qnameOrig =  mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
2542 				if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!!  malloc failure"); return mStatus_NoMemoryErr; }
2543 				(*question2)->qnameOrig->c[0] = 0;
2544 				AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
2545 				LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
2546 				}
2547 			// For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
2548 			// For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
2549 			// If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
2550 			// "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
2551 			// then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
2552 			// site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
2553 			// for names in the "local" domain will be safely answered privately before they hit the root name servers.
2554 			// Note that in the "my-small-company.local" example above there will typically be an SOA record for
2555 			// "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
2556 			// We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
2557 			// of those, we don't want do the SOA check for the local
2558 			if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname))
2559 				{
2560 				AssignDomainName(&q2->qname, &localdomain);
2561 				q2->qtype          = kDNSType_SOA;
2562 				q2->LongLived      = mDNSfalse;
2563 				q2->ForceMCast     = mDNSfalse;
2564 				q2->ReturnIntermed = mDNStrue;
2565 				// Don't append search domains for the .local SOA query
2566 				q2->AppendSearchDomains = 0;
2567 				q2->AppendLocalSearchDomains = 0;
2568 				q2->RetryWithSearchDomains = mDNSfalse;
2569 				q2->SearchListIndex = 0;
2570 				q2->TimeoutQuestion = 0;
2571 				}
2572 			LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
2573 			err = mDNS_StartQuery(&mDNSStorage, q2);
2574 			if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
2575 			}
2576 	return(err);
2577 	}
2578 #endif // APPLE_OSX_mDNSResponder
2579 
2580 // 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)2581 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(mDNS *const m, DNSQuestion *question, request_state *req)
2582 	{
2583 	int result;
2584 	// RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
2585 	// answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
2586 	// that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
2587 	// RetryWithSearchDomains which may or may not be set.
2588 	//
2589 	// If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
2590 	// is a valid question for appending search domains, retry by appending domains
2591 
2592 	if (!question->SuppressQuery && question->SearchListIndex != -1 && question->AppendSearchDomains)
2593 		{
2594 		question->RetryWithSearchDomains = 0;
2595 		result = AppendNewSearchDomain(m, question);
2596 		// As long as the result is either zero or 1, we retry the question. If we exahaust the search
2597 		// domains (result is zero) we try the original query (as it was before appending the search
2598 		// domains) as such on the wire as a last resort if we have not tried them before. For queries
2599 		// with more than one label, we have already tried them before appending search domains and
2600 		// hence don't retry again
2601 		if (result != -1)
2602 			{
2603 			mStatus err;
2604 			err = mDNS_StartQuery(m, question);
2605 			if (!err)
2606 				{
2607 				LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
2608 				// If the result was zero, it meant that there are no search domains and we just retried the question
2609 				// as a single label and we should not retry with search domains anymore.
2610 				if (!result) question->SearchListIndex = -1;
2611 				return mDNStrue;
2612 				}
2613 			else
2614 				{
2615 				LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
2616 				// We have already stopped the query and could not restart. Reset the appropriate pointers
2617 				// so that we don't call stop again when the question terminates
2618 				question->QuestionContext = mDNSNULL;
2619 				}
2620 			}
2621 		}
2622 	else
2623 		{
2624 		LogInfo("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, question->SuppressQuery, question->SearchListIndex, question->AppendSearchDomains);
2625 		}
2626 	return mDNSfalse;
2627 	}
2628 
queryrecord_result_callback(mDNS * const m,DNSQuestion * question,const ResourceRecord * const answer,QC_result AddRecord)2629 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2630 	{
2631 	char name[MAX_ESCAPED_DOMAIN_NAME];
2632 	request_state *req = question->QuestionContext;
2633 	reply_state *rep;
2634 	char *data;
2635 	size_t len;
2636 	DNSServiceErrorType error = kDNSServiceErr_NoError;
2637 	DNSQuestion *q = mDNSNULL;
2638 
2639 #if APPLE_OSX_mDNSResponder
2640 	{
2641 	// Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
2642 	// get any callbacks from the core after this.
2643 	if (!req)
2644 		{
2645 		LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
2646 		return;
2647 		}
2648 	if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
2649 		q = &req->u.queryrecord.q;
2650 	else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
2651 		q = &req->u.addrinfo.q4;
2652 	else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
2653 		q = &req->u.addrinfo.q6;
2654 
2655 	if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
2656 		{
2657 		mStatus err;
2658 		domainname *orig = question->qnameOrig;
2659 
2660 		LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
2661 		mDNS_StopQuery(m, question);
2662 		question->QuestionContext = mDNSNULL;
2663 
2664 		// We got a negative response for the SOA record indicating that .local does not exist.
2665 		// But we might have other search domains (that does not end in .local) that can be
2666 		// appended to this question. In that case, we want to retry the question. Otherwise,
2667 		// we don't want to try this question as unicast.
2668 		if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
2669 			{
2670 			LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
2671 			return;
2672 			}
2673 
2674 		// If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
2675 		//
2676 		// Note: When we copy the original question, we copy everything including the AppendSearchDomains,
2677 		// RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
2678 		// e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
2679 		// SendAdditionalQuery as to how qnameOrig gets initialized.
2680 		*question              = *q;
2681 		question->InterfaceID  = mDNSInterface_Unicast;
2682 		question->ExpectUnique = mDNStrue;
2683 		question->qnameOrig    = orig;
2684 
2685 		LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
2686 
2687 		// If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
2688 		// Hence, we need to set it explicitly here.
2689 		question->QuestionContext = req;
2690 		err = mDNS_StartQuery(m, question);
2691 		if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
2692 
2693 		// If we got a positive response to local SOA, then try the .local question as unicast
2694 		if (answer->RecordType != kDNSRecordTypePacketNegative) return;
2695 
2696 		// Fall through and get the next search domain. The question is pointing at .local
2697 		// and we don't want to try that. Try the next search domain. Don't try with local
2698 		// search domains for the unicast question anymore.
2699 		//
2700 		// Note: we started the question above which will be stopped immediately (never sent on the wire)
2701 		// before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
2702 		// question has already started.
2703 		question->AppendLocalSearchDomains = 0;
2704 		}
2705 
2706 	if (q && AddRecord && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
2707 		{
2708 		// If we get a negative response to the unicast query that we sent above, retry after appending search domains
2709 		// Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
2710 		// As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
2711 		// To keep things simple, we handle unicast ".local" separately here.
2712 		LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
2713 		if (RetryQuestionWithSearchDomains(m, question, req))
2714 			return;
2715 		if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
2716 			{
2717 			// If "local" is the last search domain, we need to stop the question so that we don't send the "local"
2718 			// question on the wire as we got a negative response for the local SOA. But, we can't stop the question
2719 			// yet as we may have to timeout the question (done by the "core") for which we need to leave the question
2720 			// in the list. We leave it disabled so that it does not hit the wire.
2721 			LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
2722 			question->ThisQInterval = 0;
2723 			}
2724 		}
2725 	// 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
2726 	// domains to append for "q2". In all cases, fall through and deliver the response
2727 	}
2728 #endif // APPLE_OSX_mDNSResponder
2729 
2730 	if (answer->RecordType == kDNSRecordTypePacketNegative)
2731 		{
2732 		// If this question needs to be timed out and we have reached the stop time, mark
2733 		// the error as timeout. It is possible that we might get a negative response from an
2734 		// external DNS server at the same time when this question reaches its stop time. We
2735 		// can't tell the difference as there is no indication in the callback. This should
2736 		// be okay as we will be timing out this query anyway.
2737 		mDNS_Lock(m);
2738 		if (question->TimeoutQuestion)
2739 			{
2740 			if ((m->timenow - question->StopTime) >= 0)
2741 				{
2742 				LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2743 				error = kDNSServiceErr_Timeout;
2744 				}
2745 			}
2746 		mDNS_Unlock(m);
2747 		// When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
2748 		// Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
2749 		// answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
2750 		// server is going to assert that pretty much every single multicast name doesn't exist.
2751 		//
2752 		// If we are timing out this query, we need to deliver the negative answer to the application
2753 		if (error != kDNSServiceErr_Timeout)
2754 			{
2755 			if (!answer->InterfaceID && IsLocalDomain(answer->name))
2756 				{
2757 				LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with unicast", question->qname.c, DNSTypeName(question->qtype));
2758 				return;
2759 				}
2760 			error = kDNSServiceErr_NoSuchRecord;
2761 			}
2762 		AddRecord = mDNStrue;
2763 		}
2764 	// If we get a negative answer, try appending search domains. Don't append search domains
2765 	// - if we are timing out this question
2766 	// - if the negative response was received as a result of a multicast query
2767 	// - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
2768 	if (error != kDNSServiceErr_Timeout)
2769 		{
2770 		if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord)
2771 			{
2772 			// If the original question did not end in .local, we did not send an SOA query
2773 			// to figure out whether we should send an additional unicast query or not. If we just
2774 			// appended .local, we need to see if we need to send an additional query. This should
2775 			// normally happen just once because after we append .local, we ignore all negative
2776 			// responses for .local above.
2777 			LogInfo("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
2778 			if (RetryQuestionWithSearchDomains(m, question, req))
2779 				{
2780 				// Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
2781 				// be anywhere in the search domain list.
2782 #if APPLE_OSX_mDNSResponder
2783 				mStatus err = mStatus_NoError;
2784 				err = SendAdditionalQuery(question, req, err);
2785 				if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
2786 #endif // APPLE_OSX_mDNSResponder
2787 				return;
2788 				}
2789 			}
2790 		}
2791 
2792 	ConvertDomainNameToCString(answer->name, name);
2793 
2794 	LogOperation("%3d: %s(%##s, %s) %s %s", req->sd,
2795 		req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
2796 		question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
2797 
2798 	len = sizeof(DNSServiceFlags);	// calculate reply data length
2799 	len += sizeof(mDNSu32);		// interface index
2800 	len += sizeof(DNSServiceErrorType);
2801 	len += strlen(name) + 1;
2802 	len += 3 * sizeof(mDNSu16);	// type, class, rdlen
2803 	len += answer->rdlength;
2804 	len += sizeof(mDNSu32);		// TTL
2805 
2806 	rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
2807 
2808 	rep->rhdr->flags = dnssd_htonl(AddRecord ? kDNSServiceFlagsAdd : 0);
2809 	// Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
2810 	// InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
2811 	// to be stopped and started including  *this* one. Normally the InterfaceID is valid. But when we
2812 	// are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
2813 	// mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
2814 	// mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
2815 	// should not have existed to answer this question if the corresponding interface is not valid.
2816 	rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
2817 	rep->rhdr->error = dnssd_htonl(error);
2818 
2819 	data = (char *)&rep->rhdr[1];
2820 
2821 	put_string(name,             &data);
2822 	put_uint16(answer->rrtype,   &data);
2823 	put_uint16(answer->rrclass,  &data);
2824 	put_uint16(answer->rdlength, &data);
2825 	// We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2826 	// function just does a blind memory copy without regard to structures that may have holes in them.
2827 	if (answer->rdlength)
2828 		if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
2829 			LogMsg("queryrecord_result_callback putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
2830 	data += answer->rdlength;
2831 	put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
2832 
2833 	append_reply(req, rep);
2834 	// Stop the question, if we just timed out
2835 	if (error == kDNSServiceErr_Timeout)
2836 		{
2837 		mDNS_StopQuery(m, question);
2838 		// Reset the pointers so that we don't call stop on termination
2839 		question->QuestionContext = mDNSNULL;
2840 		}
2841 #if APPLE_OSX_mDNSResponder
2842 #if ! NO_WCF
2843 	CHECK_WCF_FUNCTION(WCFIsServerRunning)
2844 		{
2845 		struct xucred x;
2846 		socklen_t xucredlen = sizeof(x);
2847 
2848 		if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
2849 			{
2850 			if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
2851 				(x.cr_version == XUCRED_VERSION))
2852 				{
2853 				struct sockaddr_storage addr;
2854 				const RDataBody2 *const rdb = (RDataBody2 *)answer->rdata->u.data;
2855 				addr.ss_len = 0;
2856 				if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
2857 					{
2858 					if (answer->rrtype == kDNSType_A)
2859 						{
2860 						struct sockaddr_in *sin = (struct sockaddr_in *)&addr;
2861 						sin->sin_port = 0;
2862 						if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(rdb->ipv4)), answer))
2863 							LogMsg("queryrecord_result_callback: WCF AF_INET putRData failed");
2864 						else
2865 							{
2866 							addr.ss_len = sizeof (struct sockaddr_in);
2867 							addr.ss_family = AF_INET;
2868 							}
2869 						}
2870 					else if (answer->rrtype == kDNSType_AAAA)
2871 						{
2872 						struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&addr;
2873 						sin6->sin6_port = 0;
2874 						if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(rdb->ipv6)), answer))
2875 							LogMsg("queryrecord_result_callback: WCF AF_INET6 putRData failed");
2876 						else
2877 							{
2878 							addr.ss_len = sizeof (struct sockaddr_in6);
2879 							addr.ss_family = AF_INET6;
2880 							}
2881 						}
2882 					if (addr.ss_len)
2883 						{
2884 						debugf("queryrecord_result_callback: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
2885 						CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
2886 							{
2887 							WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
2888 							}
2889 						}
2890 					}
2891 				else if (answer->rrtype == kDNSType_CNAME)
2892 					{
2893 					domainname cname;
2894 					char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
2895 					if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
2896 							LogMsg("queryrecord_result_callback: WCF CNAME putRData failed");
2897 					else
2898 						{
2899 						ConvertDomainNameToCString(&cname, cname_cstr);
2900 						CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
2901 							{
2902 							WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
2903 							}
2904 						}
2905 					}
2906 				}
2907 			else my_perror("queryrecord_result_callback: ERROR: getsockopt LOCAL_PEERCRED");
2908 			}
2909 		}
2910 #endif
2911 #endif
2912 	}
2913 
queryrecord_termination_callback(request_state * request)2914 mDNSlocal void queryrecord_termination_callback(request_state *request)
2915 	{
2916 	LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP",
2917 		request->sd, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype));
2918 	if (request->u.queryrecord.q.QuestionContext)
2919 		{
2920 		mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q);  // no need to error check
2921 		request->u.queryrecord.q.QuestionContext = mDNSNULL;
2922 		}
2923 	else
2924 		{
2925 		DNSQuestion *question = &request->u.queryrecord.q;
2926 		LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2927 		}
2928 
2929 	if (request->u.queryrecord.q.qnameOrig)
2930 		{
2931 		freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
2932 		request->u.queryrecord.q.qnameOrig = mDNSNULL;
2933 		}
2934 	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)))
2935 		{
2936 		LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
2937 		external_stop_browsing_for_service(&mDNSStorage, &request->u.queryrecord.q.qname, request->u.queryrecord.q.qtype);
2938 		}
2939   	if (request->u.queryrecord.q2)
2940   		{
2941  		if (request->u.queryrecord.q2->QuestionContext)
2942  			{
2943  			LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
2944  			mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
2945  			}
2946 		else
2947 			{
2948 			DNSQuestion *question = request->u.queryrecord.q2;
2949 			LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2950 			}
2951  		if (request->u.queryrecord.q2->qnameOrig)
2952  			{
2953  			LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
2954  			freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
2955  			request->u.queryrecord.q2->qnameOrig = mDNSNULL;
2956  			}
2957   		freeL("queryrecord Q2", request->u.queryrecord.q2);
2958   		request->u.queryrecord.q2 = mDNSNULL;
2959   		}
2960 	}
2961 
handle_queryrecord_request(request_state * request)2962 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
2963 	{
2964 	DNSQuestion *const q = &request->u.queryrecord.q;
2965 	char name[256];
2966 	mDNSu16 rrtype, rrclass;
2967 	mStatus err;
2968 
2969 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2970 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2971 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2972 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
2973 
2974 	if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
2975 	rrtype  = get_uint16(&request->msgptr, request->msgend);
2976 	rrclass = get_uint16(&request->msgptr, request->msgend);
2977 
2978 	if (!request->msgptr)
2979 		{ LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2980 
2981 	request->flags = flags;
2982 	mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
2983 
2984 	q->InterfaceID      = InterfaceID;
2985 	q->Target           = zeroAddr;
2986 	if (!MakeDomainNameFromDNSNameString(&q->qname, name)) 			return(mStatus_BadParamErr);
2987 #if 0
2988 	if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains))	return (mStatus_NoError);
2989 #endif
2990 	q->qtype            = rrtype;
2991 	q->qclass           = rrclass;
2992 	q->LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
2993 	q->ExpectUnique     = mDNSfalse;
2994 	q->ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
2995 	q->ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2996 	q->SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable   ) != 0;
2997 	q->TimeoutQuestion  = (flags & kDNSServiceFlagsTimeout            ) != 0;
2998 	q->WakeOnResolve    = 0;
2999 	q->QuestionCallback = queryrecord_result_callback;
3000 	q->QuestionContext  = request;
3001 	q->SearchListIndex  = 0;
3002 
3003 	// Don't append search domains for fully qualified domain names including queries
3004 	// such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3005 	// we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3006 	// append search domains or not.  So, we record that information in AppendSearchDomains.
3007 	//
3008 	// We append search domains only for queries that are a single label. If overriden using
3009 	// command line argument "AlwaysAppendSearchDomains", then we do it for any query which
3010 	// is not fully qualified.
3011 
3012 	if ((rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && name[strlen(name) - 1] != '.' &&
3013 		(AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3014 		{
3015 		q->AppendSearchDomains = 1;
3016 		q->AppendLocalSearchDomains = 1;
3017 		}
3018 	else
3019 		{
3020 		q->AppendSearchDomains = 0;
3021 		q->AppendLocalSearchDomains = 0;
3022 		}
3023 
3024 	// For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3025 	// search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3026 	// tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3027 	// the cache
3028 	q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3029 	q->qnameOrig        = mDNSNULL;
3030 
3031 	LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START", request->sd, flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype));
3032 	err = mDNS_StartQuery(&mDNSStorage, q);
3033 	if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3034 	else
3035 		{
3036 		request->terminate = queryrecord_termination_callback;
3037 		if (q->InterfaceID == mDNSInterface_P2P || (!q->InterfaceID && SameDomainName((const domainname *)LastLabel(&q->qname), &localdomain) && (flags & kDNSServiceFlagsIncludeP2P)))
3038 			{
3039 			LogInfo("handle_queryrecord_request: calling external_start_browsing_for_service()");
3040 			external_start_browsing_for_service(&mDNSStorage, &q->qname, q->qtype);
3041 			}
3042 		}
3043 
3044 #if APPLE_OSX_mDNSResponder
3045 	err = SendAdditionalQuery(q, request, err);
3046 #endif // APPLE_OSX_mDNSResponder
3047 
3048 	return(err);
3049 	}
3050 
3051 // ***************************************************************************
3052 #if COMPILER_LIKES_PRAGMA_MARK
3053 #pragma mark -
3054 #pragma mark - DNSServiceEnumerateDomains
3055 #endif
3056 
format_enumeration_reply(request_state * request,const char * domain,DNSServiceFlags flags,mDNSu32 ifi,DNSServiceErrorType err)3057 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3058 	const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3059 	{
3060 	size_t len;
3061 	reply_state *reply;
3062 	char *data;
3063 
3064 	len = sizeof(DNSServiceFlags);
3065 	len += sizeof(mDNSu32);
3066 	len += sizeof(DNSServiceErrorType);
3067 	len += strlen(domain) + 1;
3068 
3069 	reply = create_reply(enumeration_reply_op, len, request);
3070 	reply->rhdr->flags = dnssd_htonl(flags);
3071 	reply->rhdr->ifi   = dnssd_htonl(ifi);
3072 	reply->rhdr->error = dnssd_htonl(err);
3073 	data = (char *)&reply->rhdr[1];
3074 	put_string(domain, &data);
3075 	return reply;
3076 	}
3077 
enum_termination_callback(request_state * request)3078 mDNSlocal void enum_termination_callback(request_state *request)
3079 	{
3080 	mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3081 	mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3082 	}
3083 
enum_result_callback(mDNS * const m,DNSQuestion * const question,const ResourceRecord * const answer,QC_result AddRecord)3084 mDNSlocal void enum_result_callback(mDNS *const m,
3085 	DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3086 	{
3087 	char domain[MAX_ESCAPED_DOMAIN_NAME];
3088 	request_state *request = question->QuestionContext;
3089 	DNSServiceFlags flags = 0;
3090 	reply_state *reply;
3091 	(void)m; // Unused
3092 
3093 	if (answer->rrtype != kDNSType_PTR) return;
3094 
3095 #if 0
3096 	if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3097 #endif
3098 
3099 	// We only return add/remove events for the browse and registration lists
3100 	// For the default browse and registration answers, we only give an "ADD" event
3101 	if (question == &request->u.enumeration.q_default && !AddRecord) return;
3102 
3103 	if (AddRecord)
3104 		{
3105 		flags |= kDNSServiceFlagsAdd;
3106 		if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3107 		}
3108 
3109 	ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3110 	// Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3111 	// a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3112 	// network, so we just pass kDNSServiceInterfaceIndexAny
3113 	reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3114 	if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3115 
3116 	LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "Add" : "Rmv", domain);
3117 
3118 	append_reply(request, reply);
3119 	}
3120 
handle_enum_request(request_state * request)3121 mDNSlocal mStatus handle_enum_request(request_state *request)
3122 	{
3123 	mStatus err;
3124 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3125 	DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3126 	mDNS_DomainType t_all     = reg ? mDNS_DomainTypeRegistration        : mDNS_DomainTypeBrowse;
3127 	mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3128 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3129 	mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3130 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3131 
3132 	if (!request->msgptr)
3133 		{ LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3134 
3135 	// allocate context structures
3136 	uDNS_SetupSearchDomains(&mDNSStorage, UDNS_START_WAB_QUERY);
3137 
3138 #if 0
3139 	// mark which kind of enumeration we're doing so we can (de)authorize certain domains
3140 	request->u.enumeration.flags = reg;
3141 #endif
3142 
3143 	// enumeration requires multiple questions, so we must link all the context pointers so that
3144 	// necessary context can be reached from the callbacks
3145 	request->u.enumeration.q_all    .QuestionContext = request;
3146 	request->u.enumeration.q_default.QuestionContext = request;
3147 
3148 	// if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3149 	if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
3150 
3151 	// make the calls
3152 	LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
3153 		(flags & kDNSServiceFlagsBrowseDomains      ) ? "kDNSServiceFlagsBrowseDomains" :
3154 		(flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3155 	err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
3156 	if (!err)
3157 		{
3158 		err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
3159 		if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3160 		else request->terminate = enum_termination_callback;
3161 		}
3162 
3163 	return(err);
3164 	}
3165 
3166 // ***************************************************************************
3167 #if COMPILER_LIKES_PRAGMA_MARK
3168 #pragma mark -
3169 #pragma mark - DNSServiceReconfirmRecord & Misc
3170 #endif
3171 
handle_reconfirm_request(request_state * request)3172 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
3173 	{
3174 	mStatus status = mStatus_BadParamErr;
3175 	AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
3176 	if (rr)
3177 		{
3178 		status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
3179 		LogOperation(
3180 			(status == mStatus_NoError) ?
3181 			"%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
3182 			"%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
3183 			request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
3184 			mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse), status);
3185 		freeL("AuthRecord/handle_reconfirm_request", rr);
3186 		}
3187 	return(status);
3188 	}
3189 
handle_setdomain_request(request_state * request)3190 mDNSlocal mStatus handle_setdomain_request(request_state *request)
3191 	{
3192 	char domainstr[MAX_ESCAPED_DOMAIN_NAME];
3193 	domainname domain;
3194 	DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3195 	(void)flags; // Unused
3196 	if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3197 		!MakeDomainNameFromDNSNameString(&domain, domainstr))
3198 		{ LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3199 
3200 	LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
3201 	return(mStatus_NoError);
3202 	}
3203 
3204 typedef packedstruct
3205 	{
3206 	mStatus err;
3207 	mDNSu32 len;
3208 	mDNSu32 vers;
3209 	} DaemonVersionReply;
3210 
handle_getproperty_request(request_state * request)3211 mDNSlocal void handle_getproperty_request(request_state *request)
3212 	{
3213 	const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
3214 	char prop[256];
3215 	if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
3216 		{
3217 		LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
3218 		if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
3219 			{
3220 			DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
3221 			send_all(request->sd, (const char *)&x, sizeof(x));
3222 			return;
3223 			}
3224 		}
3225 
3226 	// If we didn't recogize the requested property name, return BadParamErr
3227 	send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
3228 	}
3229 
3230 // ***************************************************************************
3231 #if COMPILER_LIKES_PRAGMA_MARK
3232 #pragma mark -
3233 #pragma mark - DNSServiceNATPortMappingCreate
3234 #endif
3235 
3236 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
3237 
port_mapping_termination_callback(request_state * request)3238 mDNSlocal void port_mapping_termination_callback(request_state *request)
3239 	{
3240 	LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP", request->sd,
3241 		DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
3242 		mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease);
3243 	mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
3244 	}
3245 
3246 // 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)3247 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
3248 	{
3249 	request_state *request = (request_state *)n->clientContext;
3250 	reply_state *rep;
3251 	int replyLen;
3252 	char *data;
3253 
3254 	if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
3255 
3256 	// calculate reply data length
3257 	replyLen = sizeof(DNSServiceFlags);
3258 	replyLen += 3 * sizeof(mDNSu32);  // if index + addr + ttl
3259 	replyLen += sizeof(DNSServiceErrorType);
3260 	replyLen += 2 * sizeof(mDNSu16);  // Internal Port + External Port
3261 	replyLen += sizeof(mDNSu8);       // protocol
3262 
3263 	rep = create_reply(port_mapping_reply_op, replyLen, request);
3264 
3265 	rep->rhdr->flags = dnssd_htonl(0);
3266 	rep->rhdr->ifi   = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
3267 	rep->rhdr->error = dnssd_htonl(n->Result);
3268 
3269 	data = (char *)&rep->rhdr[1];
3270 
3271 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
3272 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
3273 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
3274 	*data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
3275 	*data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
3276 	*data++ = request->u.pm.NATinfo.IntPort.b[0];
3277 	*data++ = request->u.pm.NATinfo.IntPort.b[1];
3278 	*data++ = request->u.pm.NATinfo.ExternalPort.b[0];
3279 	*data++ = request->u.pm.NATinfo.ExternalPort.b[1];
3280 	put_uint32(request->u.pm.NATinfo.Lifetime, &data);
3281 
3282 	LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
3283 		DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
3284 		mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
3285 		&request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
3286 
3287 	append_reply(request, rep);
3288 	}
3289 
handle_port_mapping_request(request_state * request)3290 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
3291 	{
3292 	mDNSu32 ttl = 0;
3293 	mStatus err = mStatus_NoError;
3294 
3295 	DNSServiceFlags flags          = get_flags(&request->msgptr, request->msgend);
3296 	mDNSu32         interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3297 	mDNSInterfaceID InterfaceID    = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3298 	mDNSu8          protocol       = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
3299 	(void)flags; // Unused
3300 	if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3301 	if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
3302 	else
3303 		{
3304 		request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
3305 		request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
3306 		request->u.pm.ReqExt.b[0]          = *request->msgptr++;
3307 		request->u.pm.ReqExt.b[1]          = *request->msgptr++;
3308 		ttl = get_uint32(&request->msgptr, request->msgend);
3309 		}
3310 
3311 	if (!request->msgptr)
3312 		{ LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3313 
3314 	if (protocol == 0)	// If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
3315 		{
3316 		if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
3317 		}
3318 	else
3319 		{
3320 		if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
3321 		if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
3322 		}
3323 
3324 	request->u.pm.NATinfo.Protocol       = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
3325 	//       u.pm.NATinfo.IntPort        = already set above
3326 	request->u.pm.NATinfo.RequestedPort  = request->u.pm.ReqExt;
3327 	request->u.pm.NATinfo.NATLease       = ttl;
3328 	request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
3329 	request->u.pm.NATinfo.clientContext  = request;
3330 
3331 	LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START", request->sd,
3332 		protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease);
3333 	err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
3334 	if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
3335 	else request->terminate = port_mapping_termination_callback;
3336 
3337 	return(err);
3338 	}
3339 
3340 // ***************************************************************************
3341 #if COMPILER_LIKES_PRAGMA_MARK
3342 #pragma mark -
3343 #pragma mark - DNSServiceGetAddrInfo
3344 #endif
3345 
addrinfo_termination_callback(request_state * request)3346 mDNSlocal void addrinfo_termination_callback(request_state *request)
3347 	{
3348 	LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP", request->sd, request->u.addrinfo.q4.qname.c);
3349 
3350 	if (request->u.addrinfo.q4.QuestionContext)
3351 		{
3352 		mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
3353 		request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3354 		}
3355 	if (request->u.addrinfo.q4.qnameOrig)
3356 		{
3357 		freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
3358 		request->u.addrinfo.q4.qnameOrig = mDNSNULL;
3359 		}
3360 	if (request->u.addrinfo.q42)
3361 		{
3362 		if (request->u.addrinfo.q42->QuestionContext)
3363 			{
3364 			LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
3365 			mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
3366 			}
3367 		if (request->u.addrinfo.q42->qnameOrig)
3368 			{
3369 			LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
3370 			freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
3371 			request->u.addrinfo.q42->qnameOrig = mDNSNULL;
3372 			}
3373 		freeL("addrinfo Q42", request->u.addrinfo.q42);
3374 		request->u.addrinfo.q42 = mDNSNULL;
3375 		}
3376 
3377 	if (request->u.addrinfo.q6.QuestionContext)
3378 		{
3379 		mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
3380 		request->u.addrinfo.q6.QuestionContext = mDNSNULL;
3381 		}
3382 	if (request->u.addrinfo.q6.qnameOrig)
3383 		{
3384 		freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
3385 		request->u.addrinfo.q6.qnameOrig = mDNSNULL;
3386 		}
3387 	if (request->u.addrinfo.q62)
3388 		{
3389 		if (request->u.addrinfo.q62->QuestionContext)
3390 			{
3391 			LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
3392 			mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
3393 			}
3394 		if (request->u.addrinfo.q62->qnameOrig)
3395 			{
3396 			LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
3397 			freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
3398 			request->u.addrinfo.q62->qnameOrig = mDNSNULL;
3399 			}
3400 		freeL("addrinfo Q62", request->u.addrinfo.q62);
3401 		request->u.addrinfo.q62 = mDNSNULL;
3402 		}
3403 	}
3404 
handle_addrinfo_request(request_state * request)3405 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
3406 	{
3407 	char hostname[256];
3408 	domainname d;
3409 	mStatus err = 0;
3410 
3411 	DNSServiceFlags flags  = get_flags(&request->msgptr, request->msgend);
3412 	mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3413 
3414 	mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
3415 	request->u.addrinfo.interface_id = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3416 	request->u.addrinfo.flags        = flags;
3417 	request->u.addrinfo.protocol     = get_uint32(&request->msgptr, request->msgend);
3418 
3419 	if (interfaceIndex && !request->u.addrinfo.interface_id) return(mStatus_BadParamErr);
3420 	if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
3421 
3422 	if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
3423 
3424 	if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3425 
3426 	if (!MakeDomainNameFromDNSNameString(&d, hostname))
3427 		{ LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
3428 
3429 #if 0
3430 	if (!AuthorizedDomain(request, &d, AutoBrowseDomains))	return (mStatus_NoError);
3431 #endif
3432 
3433 	if (!request->u.addrinfo.protocol)
3434 		{
3435 		flags |= kDNSServiceFlagsSuppressUnusable;
3436 		request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
3437 		}
3438 
3439 	request->u.addrinfo.q4.InterfaceID      = request->u.addrinfo.q6.InterfaceID      = request->u.addrinfo.interface_id;
3440 	request->u.addrinfo.q4.Target           = request->u.addrinfo.q6.Target           = zeroAddr;
3441 	request->u.addrinfo.q4.qname            = request->u.addrinfo.q6.qname            = d;
3442 	request->u.addrinfo.q4.qclass           = request->u.addrinfo.q6.qclass           = kDNSServiceClass_IN;
3443 	request->u.addrinfo.q4.LongLived        = request->u.addrinfo.q6.LongLived        = (flags & kDNSServiceFlagsLongLivedQuery     ) != 0;
3444 	request->u.addrinfo.q4.ExpectUnique     = request->u.addrinfo.q6.ExpectUnique     = mDNSfalse;
3445 	request->u.addrinfo.q4.ForceMCast       = request->u.addrinfo.q6.ForceMCast       = (flags & kDNSServiceFlagsForceMulticast     ) != 0;
3446 	request->u.addrinfo.q4.ReturnIntermed   = request->u.addrinfo.q6.ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3447 	request->u.addrinfo.q4.SuppressUnusable = request->u.addrinfo.q6.SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable   ) != 0;
3448 	request->u.addrinfo.q4.TimeoutQuestion  = request->u.addrinfo.q6.TimeoutQuestion  = (flags & kDNSServiceFlagsTimeout            ) != 0;
3449 	request->u.addrinfo.q4.WakeOnResolve    = request->u.addrinfo.q6.WakeOnResolve    = 0;
3450 	request->u.addrinfo.q4.qnameOrig        = request->u.addrinfo.q6.qnameOrig        = mDNSNULL;
3451 
3452 	if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
3453 		{
3454 		request->u.addrinfo.q4.qtype            = kDNSServiceType_A;
3455 		request->u.addrinfo.q4.SearchListIndex  = 0;
3456 
3457 		// We append search domains only for queries that are a single label. If overriden using
3458 		// command line argument "AlwaysAppendSearchDomains", then we do it for any query which
3459 		// is not fully qualified.
3460 		if (hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
3461 			{
3462 			request->u.addrinfo.q4.AppendSearchDomains = 1;
3463 			request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
3464 			}
3465 		else
3466 			{
3467 			request->u.addrinfo.q4.AppendSearchDomains = 0;
3468 			request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
3469 			}
3470 		request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
3471 		request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
3472 		request->u.addrinfo.q4.QuestionContext  = request;
3473 		err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
3474 		if (err != mStatus_NoError)
3475 			{
3476 			LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
3477 			request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3478 			}
3479 		#if APPLE_OSX_mDNSResponder
3480 		err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
3481 		#endif // APPLE_OSX_mDNSResponder
3482 		}
3483 
3484 	if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6))
3485 		{
3486 		request->u.addrinfo.q6.qtype            = kDNSServiceType_AAAA;
3487 		request->u.addrinfo.q6.SearchListIndex  = 0;
3488 		if (hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
3489 			{
3490 			request->u.addrinfo.q6.AppendSearchDomains = 1;
3491 			request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
3492 			}
3493 		else
3494 			{
3495 			request->u.addrinfo.q6.AppendSearchDomains = 0;
3496 			request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
3497 			}
3498 		request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
3499 		request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
3500 		request->u.addrinfo.q6.QuestionContext  = request;
3501 		err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
3502 		if (err != mStatus_NoError)
3503 			{
3504 			LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
3505 			request->u.addrinfo.q6.QuestionContext = mDNSNULL;
3506 			if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
3507 				{
3508 				// If we started a query for IPv4, we need to cancel it
3509 				mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
3510 				request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3511 				}
3512 			}
3513 		#if APPLE_OSX_mDNSResponder
3514 		err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
3515 		#endif // APPLE_OSX_mDNSResponder
3516 		}
3517 
3518 	LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START",
3519 		request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c);
3520 
3521 	if (!err) request->terminate = addrinfo_termination_callback;
3522 
3523 	return(err);
3524 	}
3525 
3526 // ***************************************************************************
3527 #if COMPILER_LIKES_PRAGMA_MARK
3528 #pragma mark -
3529 #pragma mark - Main Request Handler etc.
3530 #endif
3531 
NewRequest(void)3532 mDNSlocal request_state *NewRequest(void)
3533 	{
3534 	request_state **p = &all_requests;
3535 	while (*p) p=&(*p)->next;
3536 	*p = mallocL("request_state", sizeof(request_state));
3537 	if (!*p) FatalError("ERROR: malloc");
3538 	mDNSPlatformMemZero(*p, sizeof(request_state));
3539 	return(*p);
3540 	}
3541 
3542 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
3543 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
read_msg(request_state * req)3544 mDNSlocal void read_msg(request_state *req)
3545 	{
3546 	if (req->ts == t_terminated || req->ts == t_error)
3547 		{ LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
3548 
3549 	if (req->ts == t_complete)	// this must be death or something is wrong
3550 		{
3551 		char buf[4];	// dummy for death notification
3552 		int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
3553 		if (!nread) { req->ts = t_terminated; return; }
3554 		if (nread < 0) goto rerror;
3555 		LogMsg("%3d: ERROR: read data from a completed request", req->sd);
3556 		req->ts = t_error;
3557 		return;
3558 		}
3559 
3560 	if (req->ts != t_morecoming)
3561 		{ LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
3562 
3563 	if (req->hdr_bytes < sizeof(ipc_msg_hdr))
3564 		{
3565 		mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
3566 		int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
3567 		if (nread == 0) { req->ts = t_terminated; return; }
3568 		if (nread < 0) goto rerror;
3569 		req->hdr_bytes += nread;
3570 		if (req->hdr_bytes > sizeof(ipc_msg_hdr))
3571 			{ LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
3572 
3573 		// only read data if header is complete
3574 		if (req->hdr_bytes == sizeof(ipc_msg_hdr))
3575 			{
3576 			ConvertHeaderBytes(&req->hdr);
3577 			if (req->hdr.version != VERSION)
3578 				{ LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
3579 
3580 			// Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
3581 			// with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
3582 			// for other overhead, this means any message above 70kB is definitely bogus.
3583 			if (req->hdr.datalen > 70000)
3584 				{ LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
3585 			req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
3586 			if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
3587 			req->msgptr = req->msgbuf;
3588 			req->msgend = req->msgbuf + req->hdr.datalen;
3589 			mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
3590 			}
3591 		}
3592 
3593 	// If our header is complete, but we're still needing more body data, then try to read it now
3594 	// Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
3595 	// Any time we need to get the error return socket we know we'll have at least one data byte
3596 	// (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
3597 	if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
3598 		{
3599 		mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
3600 		int nread;
3601 #if !defined(_WIN32)
3602 		struct iovec vec = { req->msgbuf + req->data_bytes, nleft };	// Tell recvmsg where we want the bytes put
3603 		struct msghdr msg;
3604 		struct cmsghdr *cmsg;
3605 		char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
3606 		msg.msg_name       = 0;
3607 		msg.msg_namelen    = 0;
3608 		msg.msg_iov        = &vec;
3609 		msg.msg_iovlen     = 1;
3610 		msg.msg_control    = cbuf;
3611 		msg.msg_controllen = sizeof(cbuf);
3612 		msg.msg_flags      = 0;
3613 		nread = recvmsg(req->sd, &msg, 0);
3614 #else
3615 		nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
3616 #endif
3617 		if (nread == 0) { req->ts = t_terminated; return; }
3618 		if (nread < 0) goto rerror;
3619 		req->data_bytes += nread;
3620 		if (req->data_bytes > req->hdr.datalen)
3621 			{ LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
3622 #if !defined(_WIN32)
3623 		cmsg = CMSG_FIRSTHDR(&msg);
3624 #if DEBUG_64BIT_SCM_RIGHTS
3625 		LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf),       sizeof(cbuf),   SOL_SOCKET,       SCM_RIGHTS);
3626 		LogMsg("%3d: Got       %d %d %d %d", req->sd, msg.msg_controllen, cmsg->cmsg_len, cmsg->cmsg_level, cmsg->cmsg_type);
3627 #endif // DEBUG_64BIT_SCM_RIGHTS
3628 		if (msg.msg_controllen == sizeof(cbuf) &&
3629 			cmsg->cmsg_len     == CMSG_LEN(sizeof(dnssd_sock_t)) &&
3630 			cmsg->cmsg_level   == SOL_SOCKET   &&
3631 			cmsg->cmsg_type    == SCM_RIGHTS)
3632 			{
3633 #if APPLE_OSX_mDNSResponder
3634 			// Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3635 			// of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3636 			// and it's convenient to repurpose the existing fd-passing code here for that task
3637 			if (req->hdr.op == send_bpf)
3638 				{
3639 				dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
3640 				LogOperation("%3d: Got BPF %d", req->sd, x);
3641 				mDNSPlatformReceiveBPF_fd(&mDNSStorage, x);
3642 				}
3643 			else
3644 #endif // APPLE_OSX_mDNSResponder
3645 				req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
3646 #if DEBUG_64BIT_SCM_RIGHTS
3647 			LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
3648 #endif // DEBUG_64BIT_SCM_RIGHTS
3649 			if (req->data_bytes < req->hdr.datalen)
3650 				{
3651 				LogMsg("%3d: Client sent error socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3652 					req->sd, req->errsd, req->data_bytes, req->hdr.datalen);
3653 				req->ts = t_error;
3654 				return;
3655 				}
3656 			}
3657 #endif
3658 		}
3659 
3660 	// If our header and data are both complete, see if we need to make our separate error return socket
3661 	if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
3662 		{
3663 		if (req->terminate && req->hdr.op != cancel_request)
3664 			{
3665 			dnssd_sockaddr_t cliaddr;
3666 #if defined(USE_TCP_LOOPBACK)
3667 			mDNSOpaque16 port;
3668 			u_long opt = 1;
3669 			port.b[0] = req->msgptr[0];
3670 			port.b[1] = req->msgptr[1];
3671 			req->msgptr += 2;
3672 			cliaddr.sin_family      = AF_INET;
3673 			cliaddr.sin_port        = port.NotAnInteger;
3674 			cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
3675 #else
3676 			char ctrl_path[MAX_CTLPATH];
3677 			get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH);	// path is first element in message buffer
3678 			mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
3679 			cliaddr.sun_family = AF_LOCAL;
3680 			mDNSPlatformStrCopy(cliaddr.sun_path, ctrl_path);
3681 			// If the error return path UDS name is empty string, that tells us
3682 			// that this is a new version of the library that's going to pass us
3683 			// the error return path socket via sendmsg/recvmsg
3684 			if (ctrl_path[0] == 0)
3685 				{
3686 				if (req->errsd == req->sd)
3687 					{ LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
3688 				goto got_errfd;
3689 				}
3690 #endif
3691 
3692 			req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
3693 			if (!dnssd_SocketValid(req->errsd)) { my_perror("ERROR: socket"); req->ts = t_error; return; }
3694 
3695 			if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
3696 				{
3697 #if !defined(USE_TCP_LOOPBACK)
3698 				struct stat sb;
3699 				LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
3700 					req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
3701 				if (stat(cliaddr.sun_path, &sb) < 0)
3702 					LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
3703 				else
3704 					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);
3705 #endif
3706 				req->ts = t_error;
3707 				return;
3708 				}
3709 
3710 #if !defined(USE_TCP_LOOPBACK)
3711 got_errfd:
3712 #endif
3713 			LogOperation("%3d: Error socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
3714 #if defined(_WIN32)
3715 			if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
3716 #else
3717 			if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
3718 #endif
3719 				{
3720 				LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
3721 					req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3722 				req->ts = t_error;
3723 				return;
3724 				}
3725 			}
3726 
3727 		req->ts = t_complete;
3728 		}
3729 
3730 	return;
3731 
3732 rerror:
3733 	if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
3734 	LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3735 	req->ts = t_error;
3736 	}
3737 
3738 #define RecordOrientedOp(X) \
3739 	((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3740 
3741 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3742 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3743 
request_callback(int fd,short filter,void * info)3744 mDNSlocal void request_callback(int fd, short filter, void *info)
3745 	{
3746 	mStatus err = 0;
3747 	request_state *req = info;
3748 	mDNSs32 min_size = sizeof(DNSServiceFlags);
3749 	(void)fd; // Unused
3750 	(void)filter; // Unused
3751 
3752 	for (;;)
3753 		{
3754 		read_msg(req);
3755 		if (req->ts == t_morecoming) return;
3756 		if (req->ts == t_terminated || req->ts == t_error) { AbortUnlinkAndFree(req); return; }
3757 		if (req->ts != t_complete) { LogMsg("req->ts %d != t_complete", req->ts); AbortUnlinkAndFree(req); return; }
3758 
3759 		if (req->hdr.version != VERSION)
3760 			{
3761 			LogMsg("ERROR: client version %d incompatible with daemon version %d", req->hdr.version, VERSION);
3762 			AbortUnlinkAndFree(req);
3763 			return;
3764 			}
3765 
3766 		switch(req->hdr.op)            //          Interface       + other data
3767 			{
3768 			case connection_request:       min_size = 0;                                                                           break;
3769 			case reg_service_request:      min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3770 			case add_record_request:       min_size +=                   4 /* type, rdlen */              + 4 /* ttl */;           break;
3771 			case update_record_request:    min_size +=                   2 /* rdlen */                    + 4 /* ttl */;           break;
3772 			case remove_record_request:                                                                                            break;
3773 			case browse_request:           min_size += sizeof(mDNSu32) + 2 /* type, domain */;                                     break;
3774 			case resolve_request:          min_size += sizeof(mDNSu32) + 3 /* type, type, domain */;                               break;
3775 			case query_request:            min_size += sizeof(mDNSu32) + 1 /* name */                     + 4 /* type, class*/;    break;
3776 			case enumeration_request:      min_size += sizeof(mDNSu32);                                                            break;
3777 			case reg_record_request:       min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */;  break;
3778 			case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */;                break;
3779 			case setdomain_request:        min_size +=                   1 /* domain */;                                           break;
3780 			case getproperty_request:      min_size = 2;                                                                           break;
3781 			case port_mapping_request:     min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */    + 4 /* ttl */;  break;
3782 			case addrinfo_request:         min_size += sizeof(mDNSu32) + 4 /* v4/v6 */   + 1 /* hostname */;                       break;
3783 			case send_bpf:                 // Same as cancel_request below
3784 			case cancel_request:           min_size = 0;									       break;
3785 			case sethost_request:          min_size = sizeof(mDNSu32) + 1 /* hostname */;                                          break;
3786 			default: LogMsg("ERROR: validate_message - unsupported req type: %d", req->hdr.op); min_size = -1;                     break;
3787 			}
3788 
3789 		if ((mDNSs32)req->data_bytes < min_size)
3790 			{ LogMsg("Invalid message %d bytes; min for %d is %d", req->data_bytes, req->hdr.op, min_size); AbortUnlinkAndFree(req); return; }
3791 
3792 		if (LightweightOp(req->hdr.op) && !req->terminate)
3793 			{ LogMsg("Reg/Add/Update/Remove %d require existing connection", req->hdr.op);                  AbortUnlinkAndFree(req); return; }
3794 
3795 		// check if client wants silent operation
3796 		if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
3797 
3798 		// If req->terminate is already set, this means this operation is sharing an existing connection
3799 		if (req->terminate && !LightweightOp(req->hdr.op))
3800 			{
3801 			request_state *newreq = NewRequest();
3802 			newreq->primary = req;
3803 			newreq->sd      = req->sd;
3804 			newreq->errsd   = req->errsd;
3805 			newreq->uid     = req->uid;
3806 			newreq->hdr     = req->hdr;
3807 			newreq->msgbuf  = req->msgbuf;
3808 			newreq->msgptr  = req->msgptr;
3809 			newreq->msgend  = req->msgend;
3810 			req = newreq;
3811 			}
3812 
3813 		// If we're shutting down, don't allow new client requests
3814 		// We do allow "cancel" and "getproperty" during shutdown
3815 		if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
3816 			{
3817 			err = mStatus_ServiceNotRunning;
3818 			}
3819 		else switch(req->hdr.op)
3820 			{
3821 			// These are all operations that have their own first-class request_state object
3822 			case connection_request:           LogOperation("%3d: DNSServiceCreateConnection START", req->sd);
3823 											   req->terminate = connection_termination; break;
3824 			case resolve_request:              err = handle_resolve_request     (req);  break;
3825 			case query_request:                err = handle_queryrecord_request (req);  break;
3826 			case browse_request:               err = handle_browse_request      (req);  break;
3827 			case reg_service_request:          err = handle_regservice_request  (req);  break;
3828 			case enumeration_request:          err = handle_enum_request        (req);  break;
3829 			case reconfirm_record_request:     err = handle_reconfirm_request   (req);  break;
3830 			case setdomain_request:            err = handle_setdomain_request   (req);  break;
3831 			case getproperty_request:                handle_getproperty_request (req);  break;
3832 			case port_mapping_request:         err = handle_port_mapping_request(req);  break;
3833 			case addrinfo_request:             err = handle_addrinfo_request    (req);  break;
3834 			case send_bpf:                     /* Do nothing for send_bpf */            break;
3835 
3836 			// These are all operations that work with an existing request_state object
3837 			case reg_record_request:           err = handle_regrecord_request   (req);  break;
3838 			case add_record_request:           err = handle_add_request         (req);  break;
3839 			case update_record_request:        err = handle_update_request      (req);  break;
3840 			case remove_record_request:        err = handle_removerecord_request(req);  break;
3841 			case cancel_request:                     handle_cancel_request      (req);  break;
3842 			case sethost_request:              err = handle_sethost_request     (req);  break;
3843 			default: LogMsg("%3d: ERROR: Unsupported UDS req: %d", req->sd, req->hdr.op);
3844 			}
3845 
3846 		// req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3847 		if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
3848 
3849 		// There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3850 		// For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3851 		if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf)
3852 			{
3853 			const mStatus err_netorder = dnssd_htonl(err);
3854 			send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
3855 			if (req->errsd != req->sd)
3856 				{
3857 				LogOperation("%3d: Error socket %d closed  %08X %08X (%d)",
3858 					req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
3859 				dnssd_close(req->errsd);
3860 				req->errsd = req->sd;
3861 				// Also need to reset the parent's errsd, if this is a subordinate operation
3862 				if (req->primary) req->primary->errsd = req->primary->sd;
3863 				}
3864 			}
3865 
3866 		// Reset ready to accept the next req on this pipe
3867 		if (req->primary) req = req->primary;
3868 		req->ts         = t_morecoming;
3869 		req->hdr_bytes  = 0;
3870 		req->data_bytes = 0;
3871 		req->msgbuf     = mDNSNULL;
3872 		req->msgptr     = mDNSNULL;
3873 		req->msgend     = 0;
3874 		}
3875 	}
3876 
connect_callback(int fd,short filter,void * info)3877 mDNSlocal void connect_callback(int fd, short filter, void *info)
3878 	{
3879 	dnssd_sockaddr_t cliaddr;
3880 	dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
3881 	dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
3882 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3883 	unsigned long optval = 1;
3884 #endif
3885 
3886 	(void)filter; // Unused
3887 	(void)info; // Unused
3888 
3889 	if (!dnssd_SocketValid(sd))
3890 		{
3891 		if (dnssd_errno != dnssd_EWOULDBLOCK) my_perror("ERROR: accept");
3892 		return;
3893 		}
3894 
3895 #ifdef SO_NOSIGPIPE
3896 	// Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3897 	if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
3898 		LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3899 #endif
3900 
3901 #if defined(_WIN32)
3902 	if (ioctlsocket(sd, FIONBIO, &optval) != 0)
3903 #else
3904 	if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
3905 #endif
3906 		{
3907 		my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3908 		dnssd_close(sd);
3909 		return;
3910 		}
3911 	else
3912 		{
3913 		request_state *request = NewRequest();
3914 		request->ts    = t_morecoming;
3915 		request->sd    = sd;
3916 		request->errsd = sd;
3917 #if APPLE_OSX_mDNSResponder
3918 		struct xucred x;
3919 		socklen_t xucredlen = sizeof(x);
3920 		if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION) request->uid = x.cr_uid;
3921 		else my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
3922 		debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
3923 #endif // APPLE_OSX_mDNSResponder
3924 		LogOperation("%3d: Adding FD for uid %u", request->sd, request->uid);
3925 		udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
3926 		}
3927 	}
3928 
uds_socket_setup(dnssd_sock_t skt)3929 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
3930 	{
3931 #if defined(SO_NP_EXTENSIONS)
3932 	struct		so_np_extensions sonpx;
3933 	socklen_t 	optlen = sizeof(struct so_np_extensions);
3934 	sonpx.npx_flags = SONPX_SETOPTSHUT;
3935 	sonpx.npx_mask  = SONPX_SETOPTSHUT;
3936 	if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
3937 		my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
3938 #endif
3939 #if defined(_WIN32)
3940 	// SEH: do we even need to do this on windows?
3941 	// This socket will be given to WSAEventSelect which will automatically set it to non-blocking
3942 	u_long opt = 1;
3943 	if (ioctlsocket(skt, FIONBIO, &opt) != 0)
3944 #else
3945 	if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
3946 #endif
3947 		{
3948 		my_perror("ERROR: could not set listen socket to non-blocking mode");
3949 		return mDNSfalse;
3950 		}
3951 
3952 	if (listen(skt, LISTENQ) != 0)
3953 		{
3954 		my_perror("ERROR: could not listen on listen socket");
3955 		return mDNSfalse;
3956 		}
3957 
3958 	if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
3959 		{
3960 		my_perror("ERROR: could not add listen socket to event loop");
3961 		return mDNSfalse;
3962 		}
3963 	else LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
3964 
3965 	return mDNStrue;
3966 	}
3967 
udsserver_init(dnssd_sock_t skts[],mDNSu32 count)3968 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
3969 	{
3970 	dnssd_sockaddr_t laddr;
3971 	int ret;
3972 	mDNSu32 i = 0;
3973 
3974 	LogInfo("udsserver_init");
3975 
3976 	// If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
3977 	if (PID_FILE[0])
3978 		{
3979 		FILE *fp = fopen(PID_FILE, "w");
3980 		if (fp != NULL)
3981 			{
3982 			fprintf(fp, "%d\n", getpid());
3983 			fclose(fp);
3984 			}
3985 		}
3986 
3987 	if (skts)
3988 		{
3989 		for (i = 0; i < count; i++)
3990 			if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
3991 				goto error;
3992 		}
3993 	else
3994 		{
3995 		listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
3996 		if (!dnssd_SocketValid(listenfd))
3997 			{
3998 			my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
3999 			goto error;
4000 			}
4001 
4002 		mDNSPlatformMemZero(&laddr, sizeof(laddr));
4003 
4004 		#if defined(USE_TCP_LOOPBACK)
4005 			{
4006 			laddr.sin_family = AF_INET;
4007 			laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
4008 			laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4009 			ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
4010 			if (ret < 0)
4011 				{
4012 				my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4013 				goto error;
4014 				}
4015 			}
4016 		#else
4017 			{
4018 			mode_t mask = umask(0);
4019 			unlink(MDNS_UDS_SERVERPATH);  // OK if this fails
4020 			laddr.sun_family = AF_LOCAL;
4021 			#ifndef NOT_HAVE_SA_LEN
4022 			// According to Stevens (section 3.2), there is no portable way to
4023 			// determine whether sa_len is defined on a particular platform.
4024 			laddr.sun_len = sizeof(struct sockaddr_un);
4025 			#endif
4026 			if (strlen(MDNS_UDS_SERVERPATH) >= sizeof(laddr.sun_path))
4027 				{
4028 					LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
4029 					goto error;
4030 				}
4031 			mDNSPlatformStrCopy(laddr.sun_path, MDNS_UDS_SERVERPATH);
4032 			ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
4033 			umask(mask);
4034 			if (ret < 0)
4035 				{
4036 				my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4037 				goto error;
4038 				}
4039 			}
4040 		#endif
4041 
4042 		if (!uds_socket_setup(listenfd)) goto error;
4043 		}
4044 
4045 #if !defined(PLATFORM_NO_RLIMIT)
4046 	{
4047 	// Set maximum number of open file descriptors
4048 	#define MIN_OPENFILES 10240
4049 	struct rlimit maxfds, newfds;
4050 
4051 	// Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
4052 	// you have to get and set rlimits once before getrlimit will return sensible values
4053 	if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4054 	if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4055 
4056 	if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4057 	newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
4058 	newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
4059 	if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
4060 		if (setrlimit(RLIMIT_NOFILE, &newfds) < 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 	debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
4064 	debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
4065 	}
4066 #endif
4067 
4068 	// We start a "LocalOnly" query looking for Automatic Browse Domain records.
4069 	// When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
4070 	// creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
4071 	mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
4072 		mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
4073 
4074 	// Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
4075 	RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
4076 	RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
4077 	AddAutoBrowseDomain(0, &localdomain);
4078 
4079 	udsserver_handle_configchange(&mDNSStorage);
4080 	return 0;
4081 
4082 error:
4083 
4084 	my_perror("ERROR: udsserver_init");
4085 	return -1;
4086 	}
4087 
udsserver_exit(void)4088 mDNSexport int udsserver_exit(void)
4089 	{
4090 	// Cancel all outstanding client requests
4091 	while (all_requests) AbortUnlinkAndFree(all_requests);
4092 
4093 	// Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
4094 	// created in udsserver_init, and others we created as a result of reading local configuration data
4095 	while (LocalDomainEnumRecords)
4096 		{
4097 		ARListElem *rem = LocalDomainEnumRecords;
4098 		LocalDomainEnumRecords = LocalDomainEnumRecords->next;
4099 		mDNS_Deregister(&mDNSStorage, &rem->ar);
4100 		}
4101 
4102 	// If the launching environment created no listening socket,
4103 	// that means we created it ourselves, so we should clean it up on exit
4104 	if (dnssd_SocketValid(listenfd))
4105 		{
4106 		dnssd_close(listenfd);
4107 #if !defined(USE_TCP_LOOPBACK)
4108 		// Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
4109 		// to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
4110 		// It would be nice if we could find a solution to this problem
4111 		if (unlink(MDNS_UDS_SERVERPATH))
4112 			debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
4113 #endif
4114 		}
4115 
4116 	if (PID_FILE[0]) unlink(PID_FILE);
4117 
4118 	return 0;
4119 	}
4120 
LogClientInfo(mDNS * const m,const request_state * req)4121 mDNSlocal void LogClientInfo(mDNS *const m, const request_state *req)
4122 	{
4123 	char prefix[16];
4124 	if (req->primary) mDNS_snprintf(prefix, sizeof(prefix), " -> ");
4125 	else mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
4126 
4127 	usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4128 
4129 	if (!req->terminate)
4130 		LogMsgNoIdent("%s No operation yet on this socket", prefix);
4131 	else if (req->terminate == connection_termination)
4132 		{
4133 		int num_records = 0, num_ops = 0;
4134 		const registered_record_entry *p;
4135 		const request_state *r;
4136 		for (p = req->u.reg_recs; p; p=p->next) num_records++;
4137 		for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
4138 		LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s", prefix,
4139 			num_records, num_records != 1 ? "s" : "",
4140 			num_ops,     num_ops     != 1 ? "s" : "");
4141 		for (p = req->u.reg_recs; p; p=p->next)
4142 			LogMsgNoIdent(" ->  DNSServiceRegisterRecord %3d %s", p->key, ARDisplayString(m, p->rr));
4143 		for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(m, r);
4144 		}
4145 	else if (req->terminate == regservice_termination_callback)
4146 		{
4147 		service_instance *ptr;
4148 		for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
4149 			LogMsgNoIdent("%s DNSServiceRegister         %##s %u/%u",
4150 				(ptr == req->u.servicereg.instances) ? prefix : "    ",
4151 				ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port), SRS_PORT(&ptr->srs));
4152 		}
4153 	else if (req->terminate == browse_termination_callback)
4154 		{
4155 		browser_t *blist;
4156 		for (blist = req->u.browser.browsers; blist; blist = blist->next)
4157 			LogMsgNoIdent("%s DNSServiceBrowse           %##s", (blist == req->u.browser.browsers) ? prefix : "    ", blist->q.qname.c);
4158 		}
4159 	else if (req->terminate == resolve_termination_callback)
4160 		LogMsgNoIdent("%s DNSServiceResolve          %##s", prefix, req->u.resolve.qsrv.qname.c);
4161 	else if (req->terminate == queryrecord_termination_callback)
4162 		LogMsgNoIdent("%s DNSServiceQueryRecord      %##s (%s)", prefix, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype));
4163 	else if (req->terminate == enum_termination_callback)
4164 		LogMsgNoIdent("%s DNSServiceEnumerateDomains %##s", prefix, req->u.enumeration.q_all.qname.c);
4165 	else if (req->terminate == port_mapping_termination_callback)
4166 		LogMsgNoIdent("%s DNSServiceNATPortMapping   %.4a %s%s Int %d Req %d Ext %d Req TTL %d Granted TTL %d",
4167 			prefix,
4168 			&req->u.pm.NATinfo.ExternalAddress,
4169 			req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : "   ",
4170 			req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : "   ",
4171 			mDNSVal16(req->u.pm.NATinfo.IntPort),
4172 			mDNSVal16(req->u.pm.ReqExt),
4173 			mDNSVal16(req->u.pm.NATinfo.ExternalPort),
4174 			req->u.pm.NATinfo.NATLease,
4175 			req->u.pm.NATinfo.Lifetime);
4176 	else if (req->terminate == addrinfo_termination_callback)
4177 		LogMsgNoIdent("%s DNSServiceGetAddrInfo      %s%s %##s", prefix,
4178 			req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : "  ",
4179 			req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : "  ",
4180 			req->u.addrinfo.q4.qname.c);
4181 	else
4182 		LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
4183 	}
4184 
RecordTypeName(mDNSu8 rtype)4185 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
4186 	{
4187 	switch (rtype)
4188 		{
4189 		case kDNSRecordTypeUnregistered:  return ("Unregistered ");
4190 		case kDNSRecordTypeDeregistering: return ("Deregistering");
4191 		case kDNSRecordTypeUnique:        return ("Unique       ");
4192 		case kDNSRecordTypeAdvisory:      return ("Advisory     ");
4193 		case kDNSRecordTypeShared:        return ("Shared       ");
4194 		case kDNSRecordTypeVerified:      return ("Verified     ");
4195 		case kDNSRecordTypeKnownUnique:   return ("KnownUnique  ");
4196 		default: return("Unknown");
4197 		}
4198 	}
4199 
LogEtcHosts(mDNS * const m)4200 mDNSlocal void LogEtcHosts(mDNS *const m)
4201 	{
4202 	mDNSBool showheader = mDNStrue;
4203 	const AuthRecord *ar;
4204 	mDNSu32 slot;
4205 	AuthGroup *ag;
4206 	int count = 0;
4207 	int authslot = 0;
4208 	mDNSBool truncated = 0;
4209 
4210 	for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4211 		{
4212 		if (m->rrauth.rrauth_hash[slot]) authslot++;
4213 		for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4214 			for (ar = ag->members; ar; ar = ar->next)
4215 				{
4216 				if (ar->RecordCallback != FreeEtcHosts) continue;
4217 				if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("  State       Interface"); }
4218 
4219 				// Print a maximum of 50 records
4220 				if (count++ >= 50) { truncated = mDNStrue; continue; }
4221 				if (ar->ARType == AuthRecordLocalOnly)
4222 					{
4223 					if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
4224 						LogMsgNoIdent(" %s   LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4225 					else
4226 						{
4227 						mDNSu32 scopeid  = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
4228 						LogMsgNoIdent(" %s   %u  %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
4229 						}
4230 					}
4231 				usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4232 				}
4233 		}
4234 
4235 	if (showheader) LogMsgNoIdent("<None>");
4236 	else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
4237 	}
4238 
LogLocalOnlyAuthRecords(mDNS * const m)4239 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
4240 	{
4241 	mDNSBool showheader = mDNStrue;
4242 	const AuthRecord *ar;
4243 	mDNSu32 slot;
4244 	AuthGroup *ag;
4245 
4246 	for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4247 		{
4248 		for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4249 			for (ar = ag->members; ar; ar = ar->next)
4250 				{
4251 				if (ar->RecordCallback == FreeEtcHosts) continue;
4252 				if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("  State       Interface"); }
4253 
4254 				// Print a maximum of 400 records
4255 				if (ar->ARType == AuthRecordLocalOnly)
4256 					LogMsgNoIdent(" %s   LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4257 				else if (ar->ARType == AuthRecordP2P)
4258 					LogMsgNoIdent(" %s   PP %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4259 				usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4260 				}
4261 		}
4262 
4263 	if (showheader) LogMsgNoIdent("<None>");
4264 	}
4265 
LogAuthRecords(mDNS * const m,const mDNSs32 now,AuthRecord * ResourceRecords,int * proxy)4266 mDNSlocal void LogAuthRecords(mDNS *const m, const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
4267 	{
4268 	mDNSBool showheader = mDNStrue;
4269 	const AuthRecord *ar;
4270 	OwnerOptData owner = zeroOwner;
4271 	for (ar = ResourceRecords; ar; ar=ar->next)
4272 		{
4273 		const char *const ifname = InterfaceNameForID(m, ar->resrec.InterfaceID);
4274 		if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
4275 			{
4276 			if (showheader) { showheader = mDNSfalse; LogMsgNoIdent("    Int    Next  Expire   State"); }
4277 			if (proxy) (*proxy)++;
4278 			if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
4279 				{
4280 				owner = ar->WakeUp;
4281 				if (owner.password.l[0])
4282 					LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
4283 				else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
4284 					LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d",               &owner.HMAC, &owner.IMAC,                  owner.seq);
4285 				else
4286 					LogMsgNoIdent("Proxying for %.6a seq %d",                                &owner.HMAC,                               owner.seq);
4287 				}
4288 			if (AuthRecord_uDNS(ar))
4289 				LogMsgNoIdent("%7d %7d %7d %7d %s",
4290 					ar->ThisAPInterval / mDNSPlatformOneSecond,
4291 					(ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
4292 					ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
4293 					ar->state, ARDisplayString(m, ar));
4294 			else if (ar->ARType == AuthRecordLocalOnly)
4295 				LogMsgNoIdent("                             LO %s", ARDisplayString(m, ar));
4296 			else if (ar->ARType == AuthRecordP2P)
4297 				LogMsgNoIdent("                             PP %s", ARDisplayString(m, ar));
4298 			else
4299 				LogMsgNoIdent("%7d %7d %7d %7s %s",
4300 					ar->ThisAPInterval / mDNSPlatformOneSecond,
4301 					ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
4302 					ar->TimeExpire    ? (ar->TimeExpire                      - now) / mDNSPlatformOneSecond : 0,
4303 					ifname ? ifname : "ALL",
4304 					ARDisplayString(m, ar));
4305 			usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4306 			}
4307 		}
4308 	if (showheader) LogMsgNoIdent("<None>");
4309 	}
4310 
udsserver_info(mDNS * const m)4311 mDNSexport void udsserver_info(mDNS *const m)
4312 	{
4313 	const mDNSs32 now = mDNS_TimeNow(m);
4314 	mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
4315 	int ProxyA = 0, ProxyD = 0;
4316 	const CacheGroup *cg;
4317 	const CacheRecord *cr;
4318 	const DNSQuestion *q;
4319 	const DNameListElem *d;
4320 	const SearchListElem *s;
4321 
4322 	LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
4323 
4324 	LogMsgNoIdent("------------ Cache -------------");
4325 	LogMsgNoIdent("Slt Q     TTL if     U Type rdlen");
4326 	for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4327 		for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
4328 			{
4329 			CacheUsed++;	// Count one cache entity for the CacheGroup object
4330 			for (cr = cg->members; cr; cr=cr->next)
4331 				{
4332 				const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
4333 				const char *ifname;
4334 				mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
4335 				if (!InterfaceID && cr->resrec.rDNSServer)
4336 					InterfaceID = cr->resrec.rDNSServer->interface;
4337 				ifname = InterfaceNameForID(m, InterfaceID);
4338 				CacheUsed++;
4339 				if (cr->CRActiveQuestion) CacheActive++;
4340 				LogMsgNoIdent("%3d %s%8ld %-7s%s %-6s%s",
4341 					slot,
4342 					cr->CRActiveQuestion ? "*" : " ",
4343 					remain,
4344 					ifname ? ifname : "-U-",
4345 					(cr->resrec.RecordType == kDNSRecordTypePacketNegative)  ? "-" :
4346 					(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
4347 					DNSTypeName(cr->resrec.rrtype),
4348 					CRDisplayString(m, cr));
4349 				usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4350 				}
4351 			}
4352 
4353 	if (m->rrcache_totalused != CacheUsed)
4354 		LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
4355 	if (m->rrcache_active != CacheActive)
4356 		LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
4357 	LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed, CacheActive);
4358 
4359 	LogMsgNoIdent("--------- Auth Records ---------");
4360 	LogAuthRecords(m, now, m->ResourceRecords, mDNSNULL);
4361 
4362 	LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
4363 	LogLocalOnlyAuthRecords(m);
4364 
4365 	LogMsgNoIdent("--------- /etc/hosts ---------");
4366 	LogEtcHosts(m);
4367 
4368 	LogMsgNoIdent("------ Duplicate Records -------");
4369 	LogAuthRecords(m, now, m->DuplicateRecords, mDNSNULL);
4370 
4371 	LogMsgNoIdent("----- Auth Records Proxied -----");
4372 	LogAuthRecords(m, now, m->ResourceRecords, &ProxyA);
4373 
4374 	LogMsgNoIdent("-- Duplicate Records Proxied ---");
4375 	LogAuthRecords(m, now, m->DuplicateRecords, &ProxyD);
4376 
4377 	LogMsgNoIdent("---------- Questions -----------");
4378 	if (!m->Questions) LogMsgNoIdent("<None>");
4379 	else
4380 		{
4381 		CacheUsed = 0;
4382 		CacheActive = 0;
4383 		LogMsgNoIdent("   Int  Next if     T  NumAns VDNS    Qptr     DupOf    SU SQ Type Name");
4384 		for (q = m->Questions; q; q=q->next)
4385 			{
4386 			mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
4387 			mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
4388 			char *ifname = InterfaceNameForID(m, q->InterfaceID);
4389 			CacheUsed++;
4390 			if (q->ThisQInterval) CacheActive++;
4391 			LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s",
4392 				i, n,
4393 				ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
4394 				mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
4395 				PrivateQuery(q)    ? "P" : " ",
4396 				q->CurrentAnswers, q->validDNSServers.l[1], q->validDNSServers.l[0], q, q->DuplicateOf,
4397 				q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
4398 			usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4399 			}
4400 		LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
4401 		}
4402 
4403 	LogMsgNoIdent("----- Local-Only Questions -----");
4404 	if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
4405 	else for (q = m->LocalOnlyQuestions; q; q=q->next)
4406 		LogMsgNoIdent("                       %5d  %-6s%##s%s",
4407 			q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
4408 
4409 	LogMsgNoIdent("---- Active Client Requests ----");
4410 	if (!all_requests) LogMsgNoIdent("<None>");
4411 	else
4412 		{
4413 		const request_state *req, *r;
4414 		for (req = all_requests; req; req=req->next)
4415 			{
4416 			if (req->primary)	// If this is a subbordinate operation, check that the parent is in the list
4417 				{
4418 				for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
4419 				LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
4420 				}
4421 			// For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
4422 			LogClientInfo(m, req);
4423 			foundparent:;
4424 			}
4425 		}
4426 
4427 	LogMsgNoIdent("-------- NAT Traversals --------");
4428 	if (!m->NATTraversals) LogMsgNoIdent("<None>");
4429 	else
4430 		{
4431 		const NATTraversalInfo *nat;
4432 		for (nat = m->NATTraversals; nat; nat=nat->next)
4433 			{
4434 			if (nat->Protocol)
4435 				LogMsgNoIdent("%p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d",
4436 					nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
4437 					mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
4438 					nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
4439 					nat->retryInterval / mDNSPlatformOneSecond,
4440 					nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0);
4441 			else
4442 				LogMsgNoIdent("%p Address Request               Retry %5d Interval %5d", nat,
4443 					(m->retryGetAddr - now) / mDNSPlatformOneSecond,
4444 					m->retryIntervalGetAddr / mDNSPlatformOneSecond);
4445 			usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4446 			}
4447 		}
4448 
4449 	LogMsgNoIdent("--------- AuthInfoList ---------");
4450 	if (!m->AuthInfoList) LogMsgNoIdent("<None>");
4451 	else
4452 		{
4453 		const DomainAuthInfo *a;
4454 		for (a = m->AuthInfoList; a; a = a->next)
4455 			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 : "");
4456 		}
4457 
4458 	#if APPLE_OSX_mDNSResponder
4459 	LogMsgNoIdent("--------- TunnelClients --------");
4460 	if (!m->TunnelClients) LogMsgNoIdent("<None>");
4461 	else
4462 		{
4463 		const ClientTunnel *c;
4464 		for (c = m->TunnelClients; c; c = c->next)
4465 			LogMsgNoIdent("%s %##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
4466 				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);
4467 		}
4468 	#endif // APPLE_OSX_mDNSResponder
4469 
4470 	LogMsgNoIdent("---------- Misc State ----------");
4471 
4472 	LogMsgNoIdent("PrimaryMAC:   %.6a", &m->PrimaryMAC);
4473 
4474 	LogMsgNoIdent("m->SleepState %d (%s) seq %d",
4475 		m->SleepState,
4476 		m->SleepState == SleepState_Awake        ? "Awake"        :
4477 		m->SleepState == SleepState_Transferring ? "Transferring" :
4478 		m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?",
4479 		m->SleepSeqNum);
4480 
4481 	if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
4482 	else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
4483 
4484 	if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
4485 	else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
4486 
4487 	LogMsgNoIdent("------ Auto Browse Domains -----");
4488 	if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
4489 	else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
4490 
4491 	LogMsgNoIdent("--- Auto Registration Domains --");
4492 	if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
4493 	else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
4494 
4495  	LogMsgNoIdent("--- Search Domains --");
4496  	if (!SearchList) LogMsgNoIdent("<None>");
4497  	else
4498  		{
4499  		for (s=SearchList; s; s=s->next)
4500  			{
4501  			char *ifname = InterfaceNameForID(m, s->InterfaceID);
4502  			LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
4503  			}
4504  		}
4505 
4506 	LogMsgNoIdent("---- Task Scheduling Timers ----");
4507 
4508 	if (!m->NewQuestions)
4509 		LogMsgNoIdent("NewQuestion <NONE>");
4510 	else
4511 		LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
4512 			m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
4513 			m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
4514 
4515 	if (!m->NewLocalOnlyQuestions)
4516 		LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
4517 	else
4518 		LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
4519 			m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
4520 
4521 	if (!m->NewLocalRecords)
4522 		LogMsgNoIdent("NewLocalRecords <NONE>");
4523 	else
4524 		LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
4525 
4526 	LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
4527 	LogMsgNoIdent("LocalRemoveEvents%s",   m->LocalRemoveEvents   ? "" : " <NONE>");
4528 	LogMsgNoIdent("m->RegisterAutoTunnel6  %08X", m->RegisterAutoTunnel6);
4529 	LogMsgNoIdent("m->AutoTunnelRelayAddrIn  %.16a", &m->AutoTunnelRelayAddrIn);
4530 	LogMsgNoIdent("m->AutoTunnelRelayAddrOut  %.16a", &m->AutoTunnelRelayAddrOut);
4531 
4532 #define LogTimer(MSG,T) LogMsgNoIdent( MSG " %08X %11d  %08X %11d", (T), (T), (T)-now, (T)-now)
4533 
4534 	LogMsgNoIdent("                         ABS (hex)  ABS (dec)  REL (hex)  REL (dec)");
4535 	LogMsgNoIdent("m->timenow               %08X %11d", now, now);
4536 	LogMsgNoIdent("m->timenow_adjust        %08X %11d", m->timenow_adjust, m->timenow_adjust);
4537 	LogTimer("m->NextScheduledEvent   ", m->NextScheduledEvent);
4538 
4539 #ifndef UNICAST_DISABLED
4540 	LogTimer("m->NextuDNSEvent        ", m->NextuDNSEvent);
4541 	LogTimer("m->NextSRVUpdate        ", m->NextSRVUpdate);
4542 	LogTimer("m->NextScheduledNATOp   ", m->NextScheduledNATOp);
4543 	LogTimer("m->retryGetAddr         ", m->retryGetAddr);
4544 #endif
4545 
4546 	LogTimer("m->NextCacheCheck       ", m->NextCacheCheck);
4547 	LogTimer("m->NextScheduledSPS     ", m->NextScheduledSPS);
4548 	LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
4549 	LogTimer("m->DelaySleep           ", m->DelaySleep);
4550 
4551 	LogTimer("m->NextScheduledQuery   ", m->NextScheduledQuery);
4552 	LogTimer("m->NextScheduledProbe   ", m->NextScheduledProbe);
4553 	LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
4554 
4555 	LogTimer("m->SuppressSending      ", m->SuppressSending);
4556 	LogTimer("m->SuppressProbes       ", m->SuppressProbes);
4557 	LogTimer("m->ProbeFailTime        ", m->ProbeFailTime);
4558 	LogTimer("m->DelaySleep           ", m->DelaySleep);
4559 	LogTimer("m->SleepLimit           ", m->SleepLimit);
4560 	LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
4561 	}
4562 
4563 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
uds_validatelists(void)4564 mDNSexport void uds_validatelists(void)
4565 	{
4566 	const request_state *req, *p;
4567 	for (req = all_requests; req; req=req->next)
4568 		{
4569 		if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
4570 			LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
4571 
4572 		if (req->primary == req)
4573 			LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
4574 
4575 		if (req->primary && req->replies)
4576 			LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
4577 				req, req->sd, req->primary && req->replies);
4578 
4579 		p = req->primary;
4580 		if ((long)p & 3)
4581 			LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
4582 		else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
4583 			LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
4584 
4585 		reply_state *rep;
4586 		for (rep = req->replies; rep; rep=rep->next)
4587 		  if (rep->next == (reply_state *)~0)
4588 			LogMemCorruption("UDS req->replies: %p is garbage", rep);
4589 
4590 		if (req->terminate == connection_termination)
4591 			{
4592 			registered_record_entry *r;
4593 			for (r = req->u.reg_recs; r; r=r->next)
4594 				if (r->next == (registered_record_entry *)~0)
4595 					LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
4596 			}
4597 		else if (req->terminate == regservice_termination_callback)
4598 			{
4599 			service_instance *s;
4600 			for (s = req->u.servicereg.instances; s; s=s->next)
4601 				if (s->next == (service_instance *)~0)
4602 					LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
4603 			}
4604 		else if (req->terminate == browse_termination_callback)
4605 			{
4606 			browser_t *b;
4607 			for (b = req->u.browser.browsers; b; b=b->next)
4608 				if (b->next == (browser_t *)~0)
4609 					LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
4610 			}
4611 		}
4612 
4613 	DNameListElem *d;
4614 	for (d = SCPrefBrowseDomains; d; d=d->next)
4615 		if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4616 			LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
4617 
4618 	ARListElem *b;
4619 	for (b = LocalDomainEnumRecords; b; b=b->next)
4620 		if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
4621 			LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
4622 
4623 	for (d = AutoBrowseDomains; d; d=d->next)
4624 		if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4625 			LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
4626 
4627 	for (d = AutoRegistrationDomains; d; d=d->next)
4628 		if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4629 			LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
4630 	}
4631 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4632 
send_msg(request_state * const req)4633 mDNSlocal int send_msg(request_state *const req)
4634 	{
4635 	reply_state *const rep = req->replies;		// Send the first waiting reply
4636 	ssize_t nwriten;
4637 	if (req->no_reply) return(t_complete);
4638 
4639 	ConvertHeaderBytes(rep->mhdr);
4640 	nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
4641 	ConvertHeaderBytes(rep->mhdr);
4642 
4643 	if (nwriten < 0)
4644 		{
4645 		if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
4646 		else
4647 			{
4648 #if !defined(PLATFORM_NO_EPIPE)
4649 			if (dnssd_errno == EPIPE)
4650 				return(req->ts = t_terminated);
4651 			else
4652 #endif
4653 				{
4654 				LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
4655 					rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4656 				return(t_error);
4657 				}
4658 			}
4659 		}
4660 	rep->nwriten += nwriten;
4661 	return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
4662 	}
4663 
udsserver_idle(mDNSs32 nextevent)4664 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
4665 	{
4666 	mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
4667 	request_state **req = &all_requests;
4668 
4669 	while (*req)
4670 		{
4671 		request_state *const r = *req;
4672 
4673 		if (r->terminate == resolve_termination_callback)
4674 			if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
4675 				{
4676 				r->u.resolve.ReportTime = 0;
4677 				LogMsgNoIdent("Client application bug: DNSServiceResolve(%##s) active for over two minutes. "
4678 					"This places considerable burden on the network.", r->u.resolve.qsrv.qname.c);
4679 				}
4680 
4681 		// Note: Only primary req's have reply lists, not subordinate req's.
4682 		while (r->replies)		// Send queued replies
4683 			{
4684 			transfer_state result;
4685 			if (r->replies->next) r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
4686 			result = send_msg(r);	// Returns t_morecoming if buffer full because client is not reading
4687 			if (result == t_complete)
4688 				{
4689 				reply_state *fptr = r->replies;
4690 				r->replies = r->replies->next;
4691 				freeL("reply_state/udsserver_idle", fptr);
4692 				r->time_blocked = 0; // reset failure counter after successful send
4693 				r->unresponsiveness_reports = 0;
4694 				continue;
4695 				}
4696 			else if (result == t_terminated || result == t_error)
4697 				{
4698 				LogMsg("%3d: Could not write data to client because of error - aborting connection", r->sd);
4699 				LogClientInfo(&mDNSStorage, r);
4700 				abort_request(r);
4701 				}
4702 			break;
4703 			}
4704 
4705 		if (r->replies)		// If we failed to send everything, check our time_blocked timer
4706 			{
4707 			if (nextevent - now > mDNSPlatformOneSecond) nextevent = now + mDNSPlatformOneSecond;
4708 
4709 			if (mDNSStorage.SleepState != SleepState_Awake) r->time_blocked = 0;
4710 			else if (!r->time_blocked) r->time_blocked = NonZeroTime(now);
4711 			else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
4712 				{
4713 				int num = 0;
4714 				struct reply_state *x = r->replies;
4715 				while (x) { num++; x=x->next; }
4716 				LogMsg("%3d: Could not write data to client after %ld seconds, %d repl%s waiting",
4717 					r->sd, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
4718 				if (++r->unresponsiveness_reports >= 60)
4719 					{
4720 					LogMsg("%3d: Client unresponsive; aborting connection", r->sd);
4721 					LogClientInfo(&mDNSStorage, r);
4722 					abort_request(r);
4723 					}
4724 				}
4725 			}
4726 
4727 		if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
4728 			{
4729 			// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
4730 			*req = r->next;
4731 			freeL("request_state/udsserver_idle", r);
4732 			}
4733 		else
4734 			req = &r->next;
4735 		}
4736 	return nextevent;
4737 	}
4738 
4739 struct CompileTimeAssertionChecks_uds_daemon
4740 	{
4741 	// Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4742 	// other overly-large structures instead of having a pointer to them, can inadvertently
4743 	// cause structure sizes (and therefore memory usage) to balloon unreasonably.
4744 	char sizecheck_request_state          [(sizeof(request_state)           <= 1784) ? 1 : -1];
4745 	char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <=   60) ? 1 : -1];
4746 	char sizecheck_service_instance       [(sizeof(service_instance)        <= 6552) ? 1 : -1];
4747 	char sizecheck_browser_t              [(sizeof(browser_t)               <= 1050) ? 1 : -1];
4748 	char sizecheck_reply_hdr              [(sizeof(reply_hdr)               <=   12) ? 1 : -1];
4749 	char sizecheck_reply_state            [(sizeof(reply_state)             <=   64) ? 1 : -1];
4750 	};
4751