]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSShared/uds_daemon.c
mDNSResponder-878.200.35.tar.gz
[apple/mdnsresponder.git] / mDNSShared / uds_daemon.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2003-2018 Apple 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 #include "dns_sd_internal.h"
38
39 // Normally we append search domains only for queries with a single label that are not
40 // fully qualified. This can be overridden to apply search domains for queries (that are
41 // not fully qualified) with any number of labels e.g., moon, moon.cs, moon.cs.be, etc.
42 mDNSBool AlwaysAppendSearchDomains = mDNSfalse;
43
44 // Control enabling ioptimistic DNS
45 mDNSBool EnableAllowExpired = mDNStrue;
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 #ifdef LOCAL_PEEREPID
56 #include <sys/un.h> // for LOCAL_PEEREPID
57 #include <sys/socket.h> // for getsockopt
58 #include <sys/proc_info.h> // for struct proc_bsdshortinfo
59 #include <libproc.h> // for proc_pidinfo()
60 #endif //LOCAL_PEEREPID
61
62 #ifdef UNIT_TEST
63 #include "unittest.h"
64 #endif
65
66 #if APPLE_OSX_mDNSResponder
67 #include <WebFilterDNS/WebFilterDNS.h>
68 #include "BLE.h"
69
70 #if !NO_WCF
71
72 int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
73 int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
74 int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
75
76 // Do we really need to define a macro for "if"?
77 #define CHECK_WCF_FUNCTION(X) if (X)
78 #endif // ! NO_WCF
79
80 #else
81 #define NO_WCF 1
82 #endif // APPLE_OSX_mDNSResponder
83
84 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
85 // User IDs for real user accounts start at 501 and count up from there
86 #define SystemUID(X) ((X) <= 500)
87
88 #define MAX_ANONYMOUS_DATA 256
89
90 // ***************************************************************************
91 #if COMPILER_LIKES_PRAGMA_MARK
92 #pragma mark -
93 #pragma mark - Globals
94 #endif
95
96 // globals
97 mDNSexport mDNS mDNSStorage;
98 mDNSexport const char ProgramName[] = "mDNSResponder";
99
100 #if defined(USE_TCP_LOOPBACK)
101 static char* boundPath = NULL;
102 #else
103 static char* boundPath = MDNS_UDS_SERVERPATH;
104 #endif
105 #if DEBUG
106 #define MDNS_UDS_SERVERPATH_DEBUG "/var/tmp/mDNSResponder"
107 #endif
108 static dnssd_sock_t listenfd = dnssd_InvalidSocket;
109 static request_state *all_requests = NULL;
110 #ifdef LOCAL_PEEREPID
111 struct proc_bsdshortinfo proc;
112 #endif //LOCAL_PEEREPID
113 mDNSlocal void set_peer_pid(request_state *request);
114 mDNSlocal void LogMcastClientInfo(request_state *req);
115 mDNSlocal void GetMcastClients(request_state *req);
116 static mDNSu32 mcount; // tracks the current active mcast operations for McastLogging
117 static mDNSu32 i_mcount; // sets mcount when McastLogging is enabled(PROF signal is sent)
118 static mDNSu32 n_mrecords; // tracks the current active mcast records for McastLogging
119 static mDNSu32 n_mquests; // tracks the current active mcast questions for McastLogging
120
121
122 #if TARGET_OS_EMBEDDED
123 mDNSu32 curr_num_regservices = 0;
124 mDNSu32 max_num_regservices = 0;
125 #endif
126
127
128 // Note asymmetry here between registration and browsing.
129 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
130 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
131 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
132 // 1. SCPrefBrowseDomains (local configuration data)
133 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
134 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
135 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
136
137 mDNSexport DNameListElem *AutoRegistrationDomains; // Domains where we automatically register for empty-string registrations
138
139 static DNameListElem *SCPrefBrowseDomains; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
140 static ARListElem *LocalDomainEnumRecords; // List of locally-generated PTR records to augment those we learn from the network
141 mDNSexport DNameListElem *AutoBrowseDomains; // List created from those local-only PTR records plus records we get from the network
142
143 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
144 // n get_string() calls w/o buffer overrun
145 // initialization, setup/teardown functions
146
147 // If a platform specifies its own PID file name, we use that
148 #ifndef PID_FILE
149 #define PID_FILE "/var/run/mDNSResponder.pid"
150 #endif
151
152 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen);
153
154 // ***************************************************************************
155 #if COMPILER_LIKES_PRAGMA_MARK
156 #pragma mark -
157 #pragma mark - General Utility Functions
158 #endif
159
160 mDNSlocal void FatalError(char *errmsg)
161 {
162 LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
163 abort();
164 }
165
166 mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
167 {
168 mDNSu32 ret;
169 char *data = (char*) &ret;
170 put_uint32(l, &data);
171 return ret;
172 }
173
174 // hack to search-replace perror's to LogMsg's
175 mDNSlocal void my_perror(char *errmsg)
176 {
177 LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
178 }
179
180 // Throttled version of my_perror: Logs once every 250 msgs
181 mDNSlocal void my_throttled_perror(char *err_msg)
182 {
183 static int uds_throttle_count = 0;
184 if ((uds_throttle_count++ % 250) == 0)
185 my_perror(err_msg);
186 }
187
188 // LogMcastQuestion/LogMcastQ should be called after the DNSQuestion struct is initialized(especially for q->TargetQID)
189 // Hence all calls are made after mDNS_StartQuery()/mDNS_StopQuery()/mDNS_StopBrowse() is called.
190 mDNSlocal void LogMcastQuestion(const DNSQuestion *const q, request_state *req, q_state status)
191 {
192 if (mDNSOpaque16IsZero(q->TargetQID)) // Check for Mcast Query
193 {
194 mDNSBool mflag = mDNSfalse;
195 if (status == q_start)
196 {
197 if (++mcount == 1)
198 mflag = mDNStrue;
199 }
200 else
201 {
202 mcount--;
203 }
204 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Question" : "-Question", q->qname.c, DNSTypeName(q->qtype),
205 q->InterfaceID == mDNSInterface_LocalOnly ? "lo" :
206 q->InterfaceID == mDNSInterface_P2P ? "p2p" :
207 q->InterfaceID == mDNSInterface_BLE ? "BLE" :
208 q->InterfaceID == mDNSInterface_Any ? "any" : InterfaceNameForID(&mDNSStorage, q->InterfaceID),
209 req->process_id, req->pid_name);
210 LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
211 }
212 return;
213 }
214
215 // LogMcastService/LogMcastS should be called after the AuthRecord struct is initialized
216 // Hence all calls are made after mDNS_Register()/ just before mDNS_Deregister()
217 mDNSlocal void LogMcastService(const AuthRecord *const ar, request_state *req, reg_state status)
218 {
219 if (!AuthRecord_uDNS(ar)) // Check for Mcast Service
220 {
221 mDNSBool mflag = mDNSfalse;
222 if (status == reg_start)
223 {
224 if (++mcount == 1)
225 mflag = mDNStrue;
226 }
227 else
228 {
229 mcount--;
230 }
231 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Service" : "-Service", ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype),
232 ar->resrec.InterfaceID == mDNSInterface_LocalOnly ? "lo" :
233 ar->resrec.InterfaceID == mDNSInterface_P2P ? "p2p" :
234 ar->resrec.InterfaceID == mDNSInterface_BLE ? "BLE" :
235 ar->resrec.InterfaceID == mDNSInterface_Any ? "all" : InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID),
236 req->process_id, req->pid_name);
237 LogMcastStateInfo(mflag, mDNSfalse, mDNSfalse);
238 }
239 return;
240 }
241
242 // For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
243 mDNSexport void LogMcastStateInfo(mDNSBool mflag, mDNSBool start, mDNSBool mstatelog)
244 {
245 mDNS *const m = &mDNSStorage;
246 if (!mstatelog)
247 {
248 if (!all_requests)
249 {
250 LogMcastNoIdent("<None>");
251 }
252 else
253 {
254 request_state *req, *r;
255 for (req = all_requests; req; req=req->next)
256 {
257 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
258 {
259 for (r = all_requests; r && r != req; r=r->next)
260 if (r == req->primary)
261 goto foundpar;
262 }
263 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
264 GetMcastClients(req);
265 foundpar:;
266 }
267 LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords, n_mquests);
268 n_mrecords = n_mquests = 0; // Reset the values
269 }
270 }
271 else
272 {
273 static mDNSu32 i_mpktnum;
274 i_mcount = 0;
275 if (start)
276 mcount = 0;
277 // mcount is initialized to 0 when the PROF signal is sent since mcount could have
278 // wrong value if MulticastLogging is disabled and then re-enabled
279 LogMcastNoIdent("--- START MCAST STATE LOG ---");
280 if (!all_requests)
281 {
282 mcount = 0;
283 LogMcastNoIdent("<None>");
284 }
285 else
286 {
287 request_state *req, *r;
288 for (req = all_requests; req; req=req->next)
289 {
290 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
291 {
292 for (r = all_requests; r && r != req; r=r->next)
293 if (r == req->primary)
294 goto foundparent;
295 LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req->sd);
296 }
297 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
298 LogMcastClientInfo(req);
299 foundparent:;
300 }
301 if(!mcount) // To initially set mcount
302 mcount = i_mcount;
303 }
304 if (mcount == 0)
305 {
306 i_mpktnum = m->MPktNum;
307 LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount, i_mpktnum);
308 }
309 if (mflag)
310 LogMcastNoIdent("--- MCOUNT[%d]: CMPKTNUM[%d] - IMPKTNUM[%d] = [%d]PKTS ---", mcount, m->MPktNum, i_mpktnum, (m->MPktNum - i_mpktnum));
311 LogMcastNoIdent("--- END MCAST STATE LOG ---");
312 }
313 }
314
315 mDNSlocal void abort_request(request_state *req)
316 {
317 if (req->terminate == (req_termination_fn) ~0)
318 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
319
320 // First stop whatever mDNSCore operation we were doing
321 // If this is actually a shared connection operation, then its req->terminate function will scan
322 // the all_requests list and terminate any subbordinate operations sharing this file descriptor
323 if (req->terminate) req->terminate(req);
324
325 if (!dnssd_SocketValid(req->sd))
326 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req, req->sd); return; }
327
328 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
329 if (!req->primary)
330 {
331 if (req->errsd != req->sd) LogDebug("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
332 else LogDebug("%3d: Removing FD", req->sd);
333 udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data); // Note: This also closes file descriptor req->sd for us
334 if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
335
336 while (req->replies) // free pending replies
337 {
338 reply_state *ptr = req->replies;
339 req->replies = req->replies->next;
340 freeL("reply_state (abort)", ptr);
341 }
342 }
343
344 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
345 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
346 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
347 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
348 req->sd = req->errsd = -2;
349 #else
350 req->sd = req->errsd = dnssd_InvalidSocket;
351 #endif
352 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
353 req->terminate = (req_termination_fn) ~0;
354 }
355
356 #if DEBUG
357 mDNSexport void SetDebugBoundPath(void)
358 {
359 #if !defined(USE_TCP_LOOPBACK)
360 boundPath = MDNS_UDS_SERVERPATH_DEBUG;
361 #endif
362 }
363
364 mDNSexport int IsDebugSocketInUse(void)
365 {
366 #if !defined(USE_TCP_LOOPBACK)
367 return !strcmp(boundPath, MDNS_UDS_SERVERPATH_DEBUG);
368 #else
369 return mDNSfalse;
370 #endif
371 }
372 #endif
373
374 mDNSlocal void AbortUnlinkAndFree(request_state *req)
375 {
376 request_state **p = &all_requests;
377 abort_request(req);
378 while (*p && *p != req) p=&(*p)->next;
379 if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
380 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
381 }
382
383 mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
384 {
385 reply_state *reply;
386
387 if ((unsigned)datalen < sizeof(reply_hdr))
388 {
389 LogMsg("ERROR: create_reply - data length less than length of required fields");
390 return NULL;
391 }
392
393 reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
394 if (!reply) FatalError("ERROR: malloc");
395
396 reply->next = mDNSNULL;
397 reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
398 reply->nwriten = 0;
399
400 reply->mhdr->version = VERSION;
401 reply->mhdr->datalen = (mDNSu32)datalen;
402 reply->mhdr->ipc_flags = 0;
403 reply->mhdr->op = op;
404 reply->mhdr->client_context = request->hdr.client_context;
405 reply->mhdr->reg_index = 0;
406
407 return reply;
408 }
409
410 // Append a reply to the list in a request object
411 // If our request is sharing a connection, then we append our reply_state onto the primary's list
412 // If the request does not want asynchronous replies, then the reply is freed instead of being appended to any list.
413 mDNSlocal void append_reply(request_state *req, reply_state *rep)
414 {
415 request_state *r;
416 reply_state **ptr;
417
418 if (req->no_reply)
419 {
420 freeL("reply_state/append_reply", rep);
421 return;
422 }
423
424 r = req->primary ? req->primary : req;
425 ptr = &r->replies;
426 while (*ptr) ptr = &(*ptr)->next;
427 *ptr = rep;
428 rep->next = NULL;
429 }
430
431 // Generates a response message giving name, type, domain, plus interface index,
432 // suitable for a browse result or service registration result.
433 // On successful completion rep is set to point to a malloc'd reply_state struct
434 mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
435 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
436 {
437 domainlabel name;
438 domainname type, dom;
439 *rep = NULL;
440 if (!DeconstructServiceName(servicename, &name, &type, &dom))
441 return kDNSServiceErr_Invalid;
442 else
443 {
444 char namestr[MAX_DOMAIN_LABEL+1];
445 char typestr[MAX_ESCAPED_DOMAIN_NAME];
446 char domstr [MAX_ESCAPED_DOMAIN_NAME];
447 int len;
448 char *data;
449
450 ConvertDomainLabelToCString_unescaped(&name, namestr);
451 ConvertDomainNameToCString(&type, typestr);
452 ConvertDomainNameToCString(&dom, domstr);
453
454 // Calculate reply data length
455 len = sizeof(DNSServiceFlags);
456 len += sizeof(mDNSu32); // if index
457 len += sizeof(DNSServiceErrorType);
458 len += (int) (strlen(namestr) + 1);
459 len += (int) (strlen(typestr) + 1);
460 len += (int) (strlen(domstr) + 1);
461
462 // Build reply header
463 *rep = create_reply(op, len, request);
464 (*rep)->rhdr->flags = dnssd_htonl(flags);
465 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
466 (*rep)->rhdr->error = dnssd_htonl(err);
467
468 // Build reply body
469 data = (char *)&(*rep)->rhdr[1];
470 put_string(namestr, &data);
471 put_string(typestr, &data);
472 put_string(domstr, &data);
473
474 return mStatus_NoError;
475 }
476 }
477
478 mDNSlocal void GenerateBrowseReply(const domainname *const servicename, const mDNSInterfaceID id,
479 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
480 {
481 char namestr[MAX_DOMAIN_LABEL+1];
482 char typestr[MAX_ESCAPED_DOMAIN_NAME];
483 static const char domstr[] = ".";
484 int len;
485 char *data;
486
487 *rep = NULL;
488
489 // 1. Put first label in namestr
490 ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
491
492 // 2. Put second label and "local" into typestr
493 mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
494
495 // Calculate reply data length
496 len = sizeof(DNSServiceFlags);
497 len += sizeof(mDNSu32); // if index
498 len += sizeof(DNSServiceErrorType);
499 len += (int) (strlen(namestr) + 1);
500 len += (int) (strlen(typestr) + 1);
501 len += (int) (strlen(domstr) + 1);
502
503 // Build reply header
504 *rep = create_reply(op, len, request);
505 (*rep)->rhdr->flags = dnssd_htonl(flags);
506 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
507 (*rep)->rhdr->error = dnssd_htonl(err);
508
509 // Build reply body
510 data = (char *)&(*rep)->rhdr[1];
511 put_string(namestr, &data);
512 put_string(typestr, &data);
513 put_string(domstr, &data);
514 }
515
516 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
517 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
518 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
519 mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
520 {
521 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
522 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
523 char name[256];
524 int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
525 mDNSu16 type = get_uint16(&request->msgptr, request->msgend);
526 mDNSu16 class = get_uint16(&request->msgptr, request->msgend);
527 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
528 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
529 mDNSu32 ttl = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
530 size_t storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
531 AuthRecord *rr;
532 mDNSInterfaceID InterfaceID;
533 AuthRecType artype;
534
535 request->flags = flags;
536 request->interfaceIndex = interfaceIndex;
537
538 if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
539
540 if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
541
542 if (validate_flags &&
543 !((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
544 !((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
545 {
546 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
547 return NULL;
548 }
549
550 rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
551 if (!rr) FatalError("ERROR: malloc");
552
553 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
554 if (InterfaceID == mDNSInterface_LocalOnly)
555 artype = AuthRecordLocalOnly;
556 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
557 artype = AuthRecordP2P;
558 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
559 && (flags & kDNSServiceFlagsIncludeAWDL))
560 artype = AuthRecordAnyIncludeAWDLandP2P;
561 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
562 artype = AuthRecordAnyIncludeP2P;
563 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
564 artype = AuthRecordAnyIncludeAWDL;
565 else
566 artype = AuthRecordAny;
567
568 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
569 (mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
570
571 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
572 {
573 LogMsg("ERROR: bad name: %s", name);
574 freeL("AuthRecord/read_rr_from_ipc_msg", rr);
575 return NULL;
576 }
577
578 if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
579 rr->resrec.rrclass = class;
580 rr->resrec.rdlength = rdlen;
581 rr->resrec.rdata->MaxRDLength = rdlen;
582 mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
583 if (GetTTL) rr->resrec.rroriginalttl = ttl;
584 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
585 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
586 return rr;
587 }
588
589 mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
590 {
591 domainlabel n;
592 domainname d, t;
593
594 if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
595 if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
596 if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
597 if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
598 return 0;
599 }
600
601 mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
602 {
603 int n = send(s, ptr, len, 0);
604 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
605 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
606 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
607 if (n < len)
608 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
609 s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
610 }
611
612 #if 0
613 mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
614 {
615 const DNameListElem *delem = mDNSNULL;
616 int bestDelta = -1; // the delta of the best match, lower is better
617 int dLabels = 0;
618 mDNSBool allow = mDNSfalse;
619
620 if (SystemUID(request->uid)) return mDNStrue;
621
622 dLabels = CountLabels(d);
623 for (delem = doms; delem; delem = delem->next)
624 {
625 if (delem->uid)
626 {
627 int delemLabels = CountLabels(&delem->name);
628 int delta = dLabels - delemLabels;
629 if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
630 {
631 bestDelta = delta;
632 allow = (allow || (delem->uid == request->uid));
633 }
634 }
635 }
636
637 return bestDelta == -1 ? mDNStrue : allow;
638 }
639 #endif
640
641 // ***************************************************************************
642 #if COMPILER_LIKES_PRAGMA_MARK
643 #pragma mark -
644 #pragma mark - external helpers
645 #endif
646
647 mDNSexport mDNSBool callExternalHelpers(mDNSInterfaceID InterfaceID, const domainname *const domain, DNSServiceFlags flags)
648 {
649 #if APPLE_OSX_mDNSResponder
650
651 // Only call D2D layer routines if request applies to a D2D interface and the domain is "local".
652 if ( (((InterfaceID == mDNSInterface_Any) && (flags & (kDNSServiceFlagsIncludeP2P | kDNSServiceFlagsIncludeAWDL | kDNSServiceFlagsAutoTrigger)))
653 || mDNSPlatformInterfaceIsD2D(InterfaceID) || (InterfaceID == mDNSInterface_BLE))
654 && IsLocalDomain(domain))
655 {
656 return mDNStrue;
657 }
658 else
659 return mDNSfalse;
660
661 #else
662 (void) InterfaceID;
663 (void) domain;
664 (void) flags;
665
666 return mDNSfalse;
667 #endif // APPLE_OSX_mDNSResponder
668 }
669
670 mDNSlocal void external_start_advertising_helper(service_instance *const instance)
671 {
672 AuthRecord *st = instance->subtypes;
673 ExtraResourceRecord *e;
674 int i;
675
676 if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
677 {
678 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
679 return;
680 }
681
682 if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
683
684 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
685 external_start_advertising_service(&st[i].resrec, instance->request->flags);
686
687 external_start_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
688 external_start_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
689
690 external_start_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
691
692 for (e = instance->srs.Extras; e; e = e->next)
693 external_start_advertising_service(&e->r.resrec, instance->request->flags);
694
695 instance->external_advertise = mDNStrue;
696 }
697
698 mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
699 {
700 AuthRecord *st = instance->subtypes;
701 ExtraResourceRecord *e;
702 int i;
703
704 if (!instance->external_advertise) return;
705
706 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
707
708 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
709 external_stop_advertising_service(&st[i].resrec, instance->request->flags);
710
711 external_stop_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
712 external_stop_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
713 external_stop_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
714
715 for (e = instance->srs.Extras; e; e = e->next)
716 external_stop_advertising_service(&e->r.resrec, instance->request->flags);
717
718 instance->external_advertise = mDNSfalse;
719 }
720
721 // ***************************************************************************
722 #if COMPILER_LIKES_PRAGMA_MARK
723 #pragma mark -
724 #pragma mark - DNSServiceRegister
725 #endif
726
727 mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
728 {
729 ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
730 (void)m; // Unused
731
732 if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
733
734 LogInfo(" FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
735
736 if (rr->resrec.rdata != &rr->rdatastorage)
737 freeL("Extra RData", rr->resrec.rdata);
738 freeL("ExtraResourceRecord/FreeExtraRR", extra);
739 }
740
741 mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
742 {
743 ExtraResourceRecord *e = srv->srs.Extras, *tmp;
744
745 external_stop_advertising_helper(srv);
746
747 // clear pointers from parent struct
748 if (srv->request)
749 {
750 service_instance **p = &srv->request->u.servicereg.instances;
751 while (*p)
752 {
753 if (*p == srv) { *p = (*p)->next; break; }
754 p = &(*p)->next;
755 }
756 }
757
758 while (e)
759 {
760 e->r.RecordContext = e;
761 tmp = e;
762 e = e->next;
763 FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
764 }
765
766 if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
767 freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
768
769 if (srv->subtypes)
770 {
771 freeL("ServiceSubTypes", srv->subtypes);
772 srv->subtypes = NULL;
773 }
774 if (srv->srs.AnonData)
775 {
776 freeL("Anonymous", (void *)srv->srs.AnonData);
777 srv->srs.AnonData = NULL;
778 }
779 freeL("service_instance", srv);
780 }
781
782 // Count how many other service records we have locally with the same name, but different rdata.
783 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
784 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
785 mDNSexport int CountPeerRegistrations(ServiceRecordSet *const srs)
786 {
787 int count = 0;
788 ResourceRecord *r = &srs->RR_SRV.resrec;
789 AuthRecord *rr;
790
791 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
792 if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
793 count++;
794
795 verbosedebugf("%d peer registrations for %##s", count, r->name->c);
796 return(count);
797 }
798
799 mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
800 {
801 int count = 0;
802 AuthRecord *rr;
803 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
804 if (rr->resrec.rrtype == kDNSType_SRV &&
805 mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
806 SameDomainName(rr->resrec.name, srv))
807 count++;
808 return(count);
809 }
810
811 mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
812 {
813 reply_state *rep;
814 service_instance *instance = srs->ServiceContext;
815 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
816 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
817 else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
818 }
819
820 // service registration callback performs three duties - frees memory for deregistered services,
821 // handles name conflicts, and delivers completed registration information to the client
822 mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
823 {
824 mStatus err;
825 mDNSBool SuppressError = mDNSfalse;
826 service_instance *instance;
827 reply_state *rep;
828 (void)m; // Unused
829
830 if (!srs) { LogMsg("regservice_callback: srs is NULL %d", result); return; }
831
832 instance = srs->ServiceContext;
833 if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
834
835 // don't send errors up to client for wide-area, empty-string registrations
836 if (instance->request &&
837 instance->request->u.servicereg.default_domain &&
838 !instance->default_local)
839 SuppressError = mDNStrue;
840
841 if (mDNS_LoggingEnabled)
842 {
843 const char *const fmt =
844 (result == mStatus_NoError) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
845 (result == mStatus_MemFree) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
846 (result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
847 "%s DNSServiceRegister(%##s, %u) %s %d";
848 char prefix[16] = "---:";
849 if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
850 LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
851 SuppressError ? "suppressed error" : "CALLBACK", result);
852 }
853
854 if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
855
856 if (result == mStatus_NoError)
857 {
858 if (instance->request->u.servicereg.allowremotequery)
859 {
860 ExtraResourceRecord *e;
861 srs->RR_ADV.AllowRemoteQuery = mDNStrue;
862 srs->RR_PTR.AllowRemoteQuery = mDNStrue;
863 srs->RR_SRV.AllowRemoteQuery = mDNStrue;
864 srs->RR_TXT.AllowRemoteQuery = mDNStrue;
865 for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
866 }
867
868 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
869 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
870 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
871
872 if (callExternalHelpers(instance->request->u.servicereg.InterfaceID, &instance->domain, instance->request->flags))
873 {
874 LogInfo("regservice_callback: calling external_start_advertising_helper()");
875 external_start_advertising_helper(instance);
876 }
877 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
878 RecordUpdatedNiceLabel(0); // Successfully got new name, tell user immediately
879 }
880 else if (result == mStatus_MemFree)
881 {
882 #if TARGET_OS_EMBEDDED
883 curr_num_regservices--;
884 #endif
885 if (instance->request && instance->renameonmemfree)
886 {
887 external_stop_advertising_helper(instance);
888 instance->renameonmemfree = 0;
889 err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
890 if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
891 // error should never happen - safest to log and continue
892 }
893 else
894 unlink_and_free_service_instance(instance);
895 }
896 else if (result == mStatus_NameConflict)
897 {
898 if (instance->request->u.servicereg.autorename)
899 {
900 external_stop_advertising_helper(instance);
901 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(srs) == 0)
902 {
903 // On conflict for an autoname service, rename and reregister *all* autoname services
904 IncrementLabelSuffix(&m->nicelabel, mDNStrue);
905 mDNS_ConfigChanged(m); // Will call back into udsserver_handle_configchange()
906 }
907 else // On conflict for a non-autoname service, rename and reregister just that one service
908 {
909 if (instance->clientnotified) SendServiceRemovalNotification(srs);
910 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
911 }
912 }
913 else
914 {
915 if (!SuppressError)
916 {
917 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
918 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
919 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
920 }
921 unlink_and_free_service_instance(instance);
922 }
923 }
924 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
925 {
926 if (!SuppressError)
927 {
928 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
929 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
930 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
931 }
932 }
933 }
934
935 mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
936 {
937 (void)m; // Unused
938 if (!rr->RecordContext) // parent struct already freed by termination callback
939 {
940 if (result == mStatus_NoError)
941 LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
942 else
943 {
944 if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
945
946 // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
947 // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
948 // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
949 // to free the latest rdata for which the update_callback was never called with.
950 if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
951 freeL("AuthRecord/regrecord_callback", rr);
952 }
953 }
954 else
955 {
956 registered_record_entry *re = rr->RecordContext;
957 request_state *request = re->request;
958
959 if (mDNS_LoggingEnabled)
960 {
961 char *fmt = (result == mStatus_NoError) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
962 (result == mStatus_MemFree) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
963 (result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
964 "%3d: DNSServiceRegisterRecord(%u %s) %d";
965 LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
966 }
967
968 if (result != mStatus_MemFree)
969 {
970 int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
971 reply_state *reply = create_reply(reg_record_reply_op, len, request);
972 reply->mhdr->client_context = re->regrec_client_context;
973 reply->rhdr->flags = dnssd_htonl(0);
974 reply->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
975 reply->rhdr->error = dnssd_htonl(result);
976 append_reply(request, reply);
977 }
978
979 if (result)
980 {
981 // If this is a callback to a keepalive record, do not free it.
982 if (result == mStatus_BadStateErr)
983 {
984 LogInfo("regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.");
985 }
986 else
987 {
988 // unlink from list, free memory
989 registered_record_entry **ptr = &request->u.reg_recs;
990 while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
991 if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
992 *ptr = (*ptr)->next;
993 freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
994 freeL("registered_record_entry regrecord_callback", re);
995 }
996 }
997 else
998 {
999 if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
1000
1001 if (callExternalHelpers(re->origInterfaceID, &rr->namestorage, request->flags))
1002 {
1003 LogInfo("regrecord_callback: calling external_start_advertising_service");
1004 external_start_advertising_service(&rr->resrec, request->flags);
1005 re->external_advertise = mDNStrue;
1006 }
1007 }
1008 }
1009 }
1010
1011 // set_peer_pid() is called after mem is allocated for each new request in NewRequest()
1012 // This accounts for 2 places (connect_callback, request_callback)
1013 mDNSlocal void set_peer_pid(request_state *request)
1014 {
1015 pid_t p = (pid_t) -1;
1016 socklen_t len = sizeof(p);
1017 request->pid_name[0] = '\0';
1018 request->process_id = -1;
1019 #ifdef LOCAL_PEEREPID
1020 if (request->sd < 0)
1021 return;
1022 // to extract the effective pid value
1023 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &p, &len) != 0)
1024 return;
1025 // to extract the process name from the pid value
1026 if (proc_pidinfo(p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
1027 return;
1028 mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
1029 request->process_id = p;
1030 debugf("set_peer_pid: Client PEEREPID is %d %s", p, request->pid_name);
1031 #else // !LOCAL_PEEREPID
1032 len = 0;
1033 LogInfo("set_peer_pid: Not Supported on this version of OS");
1034 if (request->sd < 0)
1035 return;
1036 #endif // LOCAL_PEEREPID
1037 }
1038
1039 mDNSlocal void connection_termination(request_state *request)
1040 {
1041 // When terminating a shared connection, we need to scan the all_requests list
1042 // and terminate any subbordinate operations sharing this file descriptor
1043 request_state **req = &all_requests;
1044
1045 LogOperation("%3d: DNSServiceCreateConnection STOP PID[%d](%s)", request->sd, request->process_id, request->pid_name);
1046
1047 while (*req)
1048 {
1049 if ((*req)->primary == request)
1050 {
1051 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1052 request_state *tmp = *req;
1053 if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp, tmp->sd);
1054 if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
1055 abort_request(tmp);
1056 *req = tmp->next;
1057 freeL("request_state/connection_termination", tmp);
1058 }
1059 else
1060 req = &(*req)->next;
1061 }
1062
1063 while (request->u.reg_recs)
1064 {
1065 registered_record_entry *ptr = request->u.reg_recs;
1066 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP PID[%d](%s)", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec), request->process_id, request->pid_name);
1067 request->u.reg_recs = request->u.reg_recs->next;
1068 ptr->rr->RecordContext = NULL;
1069 if (ptr->external_advertise)
1070 {
1071 ptr->external_advertise = mDNSfalse;
1072 external_stop_advertising_service(&ptr->rr->resrec, request->flags);
1073 }
1074 LogMcastS(ptr->rr, request, reg_stop);
1075 mDNS_Deregister(&mDNSStorage, ptr->rr); // Will free ptr->rr for us
1076 freeL("registered_record_entry/connection_termination", ptr);
1077 }
1078 }
1079
1080 mDNSlocal void handle_cancel_request(request_state *request)
1081 {
1082 request_state **req = &all_requests;
1083 LogDebug("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
1084 while (*req)
1085 {
1086 if ((*req)->primary == request &&
1087 (*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1088 (*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
1089 {
1090 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1091 request_state *tmp = *req;
1092 abort_request(tmp);
1093 *req = tmp->next;
1094 freeL("request_state/handle_cancel_request", tmp);
1095 }
1096 else
1097 req = &(*req)->next;
1098 }
1099 }
1100
1101 mDNSlocal mStatus handle_regrecord_request(request_state *request)
1102 {
1103 mStatus err = mStatus_BadParamErr;
1104 AuthRecord *rr;
1105
1106 if (request->terminate != connection_termination)
1107 { LogMsg("%3d: DNSServiceRegisterRecord(not a shared connection ref)", request->sd); return(err); }
1108
1109 rr = read_rr_from_ipc_msg(request, 1, 1);
1110 if (rr)
1111 {
1112 registered_record_entry *re;
1113 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1114 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1115 if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
1116 rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
1117 rr->resrec.rrtype == kDNSType_CNAME))
1118 {
1119 freeL("AuthRecord/handle_regrecord_request", rr);
1120 return (mStatus_BadParamErr);
1121 }
1122 // allocate registration entry, link into list
1123 re = mallocL("registered_record_entry", sizeof(registered_record_entry));
1124 if (!re)
1125 FatalError("ERROR: malloc");
1126 re->key = request->hdr.reg_index;
1127 re->rr = rr;
1128 re->regrec_client_context = request->hdr.client_context;
1129 re->request = request;
1130 re->external_advertise = mDNSfalse;
1131 rr->RecordContext = re;
1132 rr->RecordCallback = regrecord_callback;
1133
1134 re->origInterfaceID = rr->resrec.InterfaceID;
1135 if (rr->resrec.InterfaceID == mDNSInterface_P2P)
1136 rr->resrec.InterfaceID = mDNSInterface_Any;
1137 #if 0
1138 if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError);
1139 #endif
1140 if (rr->resrec.rroriginalttl == 0)
1141 rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);
1142
1143 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START PID[%d](%s)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec),
1144 request->process_id, request->pid_name);
1145
1146 err = mDNS_Register(&mDNSStorage, rr);
1147 if (err)
1148 {
1149 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec), err);
1150 freeL("registered_record_entry", re);
1151 freeL("registered_record_entry/AuthRecord", rr);
1152 }
1153 else
1154 {
1155 LogMcastS(rr, request, reg_start);
1156 re->next = request->u.reg_recs;
1157 request->u.reg_recs = re;
1158 }
1159 }
1160 return(err);
1161 }
1162
1163 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);
1164
1165 mDNSlocal void regservice_termination_callback(request_state *request)
1166 {
1167 if (!request)
1168 {
1169 LogMsg("regservice_termination_callback context is NULL");
1170 return;
1171 }
1172 while (request->u.servicereg.instances)
1173 {
1174 service_instance *p = request->u.servicereg.instances;
1175 request->u.servicereg.instances = request->u.servicereg.instances->next;
1176 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1177 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP PID[%d](%s)", request->sd, p->srs.RR_SRV.resrec.name->c,
1178 mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port), request->process_id, request->pid_name);
1179
1180 external_stop_advertising_helper(p);
1181
1182 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1183 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1184 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1185 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1186 // because by then we might have already freed p
1187 p->request = NULL;
1188 LogMcastS(&p->srs.RR_SRV, request, reg_stop);
1189 if (mDNS_DeregisterService(&mDNSStorage, &p->srs))
1190 {
1191 unlink_and_free_service_instance(p);
1192 // Don't touch service_instance *p after this -- it's likely to have been freed already
1193 }
1194 }
1195 if (request->u.servicereg.txtdata)
1196 {
1197 freeL("service_info txtdata", request->u.servicereg.txtdata);
1198 request->u.servicereg.txtdata = NULL;
1199 }
1200 if (request->u.servicereg.autoname)
1201 {
1202 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1203 request->u.servicereg.autoname = mDNSfalse;
1204 UpdateDeviceInfoRecord(&mDNSStorage);
1205 }
1206 }
1207
1208 mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
1209 {
1210 request_state *req;
1211 for (req = all_requests; req; req = req->next)
1212 if (req->primary == request &&
1213 req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1214 req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
1215 return(request);
1216 }
1217
1218 mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl)
1219 {
1220 ServiceRecordSet *srs = &instance->srs;
1221 mStatus result;
1222 size_t size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1223 ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
1224 if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1225
1226 mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord)); // OK if oversized rdata not zero'd
1227 extra->r.resrec.rrtype = rrtype;
1228 extra->r.rdatastorage.MaxRDLength = (mDNSu16) size;
1229 extra->r.resrec.rdlength = rdlen;
1230 mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen);
1231 // use InterfaceID value from DNSServiceRegister() call that created the original service
1232 extra->r.resrec.InterfaceID = request->u.servicereg.InterfaceID;
1233
1234 result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl, request->flags);
1235 if (result)
1236 {
1237 freeL("ExtraResourceRecord/add_record_to_service", extra);
1238 return result;
1239 }
1240 LogMcastS(&srs->RR_PTR, request, reg_start);
1241
1242 extra->ClientID = request->hdr.reg_index;
1243 if ( instance->external_advertise
1244 && callExternalHelpers(request->u.servicereg.InterfaceID, &instance->domain, request->flags))
1245 {
1246 LogInfo("add_record_to_service: calling external_start_advertising_service");
1247 external_start_advertising_service(&extra->r.resrec, request->flags);
1248 }
1249 return result;
1250 }
1251
1252 mDNSlocal mStatus handle_add_request(request_state *request)
1253 {
1254 service_instance *i;
1255 mStatus result = mStatus_UnknownErr;
1256 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);
1257 mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend);
1258 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1259 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1260 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1261 if (!ttl) ttl = DefaultTTLforRRType(rrtype);
1262 (void)flags; // Unused
1263
1264 if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1265
1266 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1267 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1268
1269 if (request->terminate != regservice_termination_callback)
1270 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1271
1272 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1273 // in the application. See radar://9165807.
1274 if (mDNSIPPortIsZero(request->u.servicereg.port))
1275 { LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1276
1277 LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d) PID[%d](%s)", request->sd, flags,
1278 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen,
1279 request->process_id, request->pid_name);
1280
1281 for (i = request->u.servicereg.instances; i; i = i->next)
1282 {
1283 result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
1284 if (result && i->default_local) break;
1285 else result = mStatus_NoError; // suppress non-local default errors
1286 }
1287
1288 return(result);
1289 }
1290
1291 mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
1292 {
1293 mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
1294 (void)m; // Unused
1295
1296 // There are three cases.
1297 //
1298 // 1. We have updated the primary TXT record of the service
1299 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1300 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1301 //
1302 // external_advertise is set if we have advertised at least once during the initial addition
1303 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1304 // checks during the first time and hence we don't do any checks here
1305 if (external_advertise)
1306 {
1307 ResourceRecord ext = rr->resrec;
1308 DNSServiceFlags flags = deriveD2DFlagsFromAuthRecType(rr->ARType);
1309
1310 if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
1311 SetNewRData(&ext, oldrd, oldrdlen);
1312 external_stop_advertising_service(&ext, flags);
1313 LogInfo("update_callback: calling external_start_advertising_service");
1314 external_start_advertising_service(&rr->resrec, flags);
1315 }
1316 exit:
1317 if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
1318 }
1319
1320 mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl, const mDNSBool *const external_advertise)
1321 {
1322 mStatus result;
1323 const size_t rdsize = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1324 RData *newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize);
1325 if (!newrd) FatalError("ERROR: malloc");
1326 newrd->MaxRDLength = (mDNSu16) rdsize;
1327 mDNSPlatformMemCopy(&newrd->u, rdata, rdlen);
1328
1329 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1330 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1331 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1332 if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }
1333
1334 if (external_advertise) rr->UpdateContext = (void *)external_advertise;
1335
1336 result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback);
1337 if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, rr)); freeL("RData/update_record", newrd); }
1338 return result;
1339 }
1340
1341 mDNSlocal mStatus handle_update_request(request_state *request)
1342 {
1343 const ipc_msg_hdr *const hdr = &request->hdr;
1344 mStatus result = mStatus_BadReferenceErr;
1345 service_instance *i;
1346 AuthRecord *rr = NULL;
1347
1348 // get the message data
1349 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend); // flags unused
1350 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1351 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1352 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1353 (void)flags; // Unused
1354
1355 if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1356
1357 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1358 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1359
1360 if (request->terminate == connection_termination)
1361 {
1362 // update an individually registered record
1363 registered_record_entry *reptr;
1364 for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
1365 {
1366 if (reptr->key == hdr->reg_index)
1367 {
1368 result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise);
1369 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)",
1370 request->sd, reptr->rr->resrec.name->c, reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>",
1371 request->process_id, request->pid_name);
1372 goto end;
1373 }
1374 }
1375 result = mStatus_BadReferenceErr;
1376 goto end;
1377 }
1378
1379 if (request->terminate != regservice_termination_callback)
1380 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1381
1382 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1383 if (mDNSIPPortIsZero(request->u.servicereg.port))
1384 { LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1385
1386 // update the saved off TXT data for the service
1387 if (hdr->reg_index == TXT_RECORD_INDEX)
1388 {
1389 if (request->u.servicereg.txtdata)
1390 { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
1391 if (rdlen > 0)
1392 {
1393 request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
1394 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
1395 mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
1396 }
1397 request->u.servicereg.txtlen = rdlen;
1398 }
1399
1400 // update a record from a service record set
1401 for (i = request->u.servicereg.instances; i; i = i->next)
1402 {
1403 if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
1404 else
1405 {
1406 ExtraResourceRecord *e;
1407 for (e = i->srs.Extras; e; e = e->next)
1408 if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
1409 }
1410
1411 if (!rr) { result = mStatus_BadReferenceErr; goto end; }
1412 result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise);
1413 if (result && i->default_local) goto end;
1414 else result = mStatus_NoError; // suppress non-local default errors
1415 }
1416
1417 end:
1418 if (request->terminate == regservice_termination_callback)
1419 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s) PID[%d](%s)", request->sd,
1420 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1421 rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>",
1422 request->process_id, request->pid_name);
1423
1424 return(result);
1425 }
1426
1427 // remove a resource record registered via DNSServiceRegisterRecord()
1428 mDNSlocal mStatus remove_record(request_state *request)
1429 {
1430 mStatus err = mStatus_UnknownErr;
1431 registered_record_entry *e, **ptr = &request->u.reg_recs;
1432
1433 while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
1434 if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
1435 e = *ptr;
1436 *ptr = e->next; // unlink
1437
1438 LogOperation("%3d: DNSServiceRemoveRecord(%u %s) PID[%d](%s)",
1439 request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec), request->process_id, request->pid_name);
1440 e->rr->RecordContext = NULL;
1441 if (e->external_advertise)
1442 {
1443 external_stop_advertising_service(&e->rr->resrec, request->flags);
1444 e->external_advertise = mDNSfalse;
1445 }
1446 LogMcastS(e->rr, request, reg_stop);
1447 err = mDNS_Deregister(&mDNSStorage, e->rr); // Will free e->rr for us; we're responsible for freeing e
1448 if (err)
1449 {
1450 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
1451 freeL("registered_record_entry AuthRecord remove_record", e->rr);
1452 }
1453 freeL("registered_record_entry remove_record", e);
1454 return err;
1455 }
1456
1457 mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
1458 {
1459 mStatus err = mStatus_BadReferenceErr;
1460 ExtraResourceRecord *ptr;
1461
1462 for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
1463 {
1464 if (ptr->ClientID == request->hdr.reg_index) // found match
1465 {
1466 *rrtype = ptr->r.resrec.rrtype;
1467 if (serv->external_advertise) external_stop_advertising_service(&ptr->r.resrec, request->flags);
1468 err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
1469 break;
1470 }
1471 }
1472 return err;
1473 }
1474
1475 mDNSlocal mStatus handle_removerecord_request(request_state *request)
1476 {
1477 mStatus err = mStatus_BadReferenceErr;
1478 get_flags(&request->msgptr, request->msgend); // flags unused
1479
1480 if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1481
1482 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1483 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1484
1485 if (request->terminate == connection_termination)
1486 err = remove_record(request); // remove individually registered record
1487 else if (request->terminate != regservice_termination_callback)
1488 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1489 else
1490 {
1491 service_instance *i;
1492 mDNSu16 rrtype = 0;
1493 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s) PID[%d](%s)", request->sd,
1494 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1495 rrtype ? DNSTypeName(rrtype) : "<NONE>", request->process_id, request->pid_name);
1496 for (i = request->u.servicereg.instances; i; i = i->next)
1497 {
1498 err = remove_extra(request, i, &rrtype);
1499 if (err && i->default_local) break;
1500 else err = mStatus_NoError; // suppress non-local default errors
1501 }
1502 }
1503
1504 return(err);
1505 }
1506
1507 // If there's a comma followed by another character,
1508 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1509 // Otherwise, it returns a pointer to the final nul at the end of the string
1510 mDNSlocal char *FindFirstSubType(char *p, char **AnonData)
1511 {
1512 while (*p)
1513 {
1514 if (p[0] == '\\' && p[1])
1515 {
1516 p += 2;
1517 }
1518 else if (p[0] == ',' && p[1])
1519 {
1520 *p++ = 0;
1521 return(p);
1522 }
1523 else if (p[0] == ':' && p[1])
1524 {
1525 *p++ = 0;
1526 *AnonData = p;
1527 }
1528 else
1529 {
1530 p++;
1531 }
1532 }
1533 return(p);
1534 }
1535
1536 // If there's a comma followed by another character,
1537 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1538 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1539 // Otherwise, it returns a pointer to the final nul at the end of the string
1540 mDNSlocal char *FindNextSubType(char *p)
1541 {
1542 while (*p)
1543 {
1544 if (p[0] == '\\' && p[1]) // If escape character
1545 p += 2; // ignore following character
1546 else if (p[0] == ',') // If we found a comma
1547 {
1548 if (p[1]) *p++ = 0;
1549 return(p);
1550 }
1551 else if (p[0] == '.')
1552 return(mDNSNULL);
1553 else p++;
1554 }
1555 return(p);
1556 }
1557
1558 // Returns -1 if illegal subtype found
1559 mDNSexport mDNSs32 ChopSubTypes(char *regtype, char **AnonData)
1560 {
1561 mDNSs32 NumSubTypes = 0;
1562 char *stp = FindFirstSubType(regtype, AnonData);
1563 while (stp && *stp) // If we found a comma...
1564 {
1565 if (*stp == ',') return(-1);
1566 NumSubTypes++;
1567 stp = FindNextSubType(stp);
1568 }
1569 if (!stp) return(-1);
1570 return(NumSubTypes);
1571 }
1572
1573 mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p, char **AnonData)
1574 {
1575 AuthRecord *st = mDNSNULL;
1576 //
1577 // "p" is pointing at the regtype e.g., _http._tcp followed by ":<AnonData>" indicated
1578 // by AnonData being non-NULL which is in turn follwed by ",<SubTypes>" indicated by
1579 // NumSubTypes being non-zero. We need to skip the initial regtype to get to the actual
1580 // data that we want. When we come here, ChopSubTypes has null terminated like this e.g.,
1581 //
1582 // _http._tcp<NULL><AnonData><NULL><SubType1><NULL><SubType2><NULL> etc.
1583 //
1584 // 1. If we have Anonymous data and subtypes, skip the regtype (e.g., "_http._tcp")
1585 // to get the AnonData and then skip the AnonData to get to the SubType.
1586 //
1587 // 2. If we have only SubTypes, skip the regtype to get to the SubType data.
1588 //
1589 // 3. If we have only AnonData, skip the regtype to get to the AnonData.
1590 //
1591 // 4. If we don't have AnonData or NumStypes, it is a noop.
1592 //
1593 if (AnonData)
1594 {
1595 int len;
1596
1597 // Skip the regtype
1598 while (*p) p++;
1599 p++;
1600
1601 len = strlen(p) + 1;
1602 *AnonData = mallocL("Anonymous", len);
1603 if (!(*AnonData))
1604 {
1605 return (mDNSNULL);
1606 }
1607 mDNSPlatformMemCopy(*AnonData, p, len);
1608 }
1609 if (NumSubTypes)
1610 {
1611 mDNSs32 i;
1612 st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
1613 if (!st) return(mDNSNULL);
1614 for (i = 0; i < NumSubTypes; i++)
1615 {
1616 mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
1617 // First time through we skip the regtype or AnonData. Subsequently, the
1618 // previous subtype.
1619 while (*p) p++;
1620 p++;
1621 if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
1622 {
1623 freeL("ServiceSubTypes", st);
1624 if (AnonData && *AnonData)
1625 freeL("AnonymousData", *AnonData);
1626 return(mDNSNULL);
1627 }
1628 }
1629 }
1630 // If NumSubTypes is zero and AnonData is non-NULL, we still return NULL but AnonData has been
1631 // initialized. The caller knows how to handle this.
1632 return(st);
1633 }
1634
1635 mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
1636 {
1637 service_instance **ptr, *instance;
1638 size_t extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
1639 const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
1640 mStatus result;
1641 mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;
1642
1643 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1644 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1645 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1646 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1647 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1648 if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;
1649
1650 for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
1651 {
1652 if (SameDomainName(&(*ptr)->domain, domain))
1653 {
1654 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1655 domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
1656 return mStatus_AlreadyRegistered;
1657 }
1658 }
1659
1660 instance = mallocL("service_instance", sizeof(*instance) + extra_size);
1661 if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1662
1663 instance->next = mDNSNULL;
1664 instance->request = request;
1665 instance->renameonmemfree = 0;
1666 instance->clientnotified = mDNSfalse;
1667 instance->default_local = (request->u.servicereg.default_domain && DomainIsLocal);
1668 instance->external_advertise = mDNSfalse;
1669 AssignDomainName(&instance->domain, domain);
1670
1671 instance->srs.AnonData = mDNSNULL;
1672 if (!request->u.servicereg.AnonData)
1673 {
1674 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, mDNSNULL);
1675 }
1676 else
1677 {
1678 char *AnonData = mDNSNULL;
1679 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, &AnonData);
1680 if (AnonData)
1681 instance->srs.AnonData = (const mDNSu8 *)AnonData;
1682 }
1683
1684 if (request->u.servicereg.num_subtypes && !instance->subtypes)
1685 {
1686 unlink_and_free_service_instance(instance);
1687 instance = NULL;
1688 FatalError("ERROR: malloc");
1689 }
1690
1691 result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
1692 &request->u.servicereg.name, &request->u.servicereg.type, domain,
1693 request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
1694 request->u.servicereg.port,
1695 mDNSNULL, request->u.servicereg.txtdata, request->u.servicereg.txtlen,
1696 instance->subtypes, request->u.servicereg.num_subtypes,
1697 interfaceID, regservice_callback, instance, request->flags);
1698
1699 if (!result)
1700 {
1701 *ptr = instance; // Append this to the end of our request->u.servicereg.instances list
1702 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance->request->sd,
1703 instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
1704 LogMcastS(&instance->srs.RR_SRV, request, reg_start);
1705 }
1706 else
1707 {
1708 LogMsg("register_service_instance %#s.%##s%##s error %d",
1709 &request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
1710 unlink_and_free_service_instance(instance);
1711 }
1712
1713 return result;
1714 }
1715
1716 mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
1717 {
1718 request_state *request;
1719
1720 LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
1721 for (request = all_requests; request; request = request->next)
1722 {
1723 if (request->terminate != regservice_termination_callback) continue;
1724 if (!request->u.servicereg.default_domain) continue;
1725 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1726 {
1727 service_instance **ptr = &request->u.servicereg.instances;
1728 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1729 if (add)
1730 {
1731 // If we don't already have this domain in our list for this registration, add it now
1732 if (!*ptr) register_service_instance(request, &d->name);
1733 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
1734 }
1735 else
1736 {
1737 // Normally we should not fail to find the specified instance
1738 // One case where this can happen is if a uDNS update fails for some reason,
1739 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1740 if (!*ptr)
1741 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1742 &d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
1743 else
1744 {
1745 DNameListElem *p;
1746 for (p = AutoRegistrationDomains; p; p=p->next)
1747 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1748 if (SameDomainName(&d->name, &p->name)) break;
1749 if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
1750 else
1751 {
1752 mStatus err;
1753 service_instance *si = *ptr;
1754 *ptr = si->next;
1755 if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
1756 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1757 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1758 // process of completing asynchronously, the client cancels the entire operation, so
1759 // regservice_termination_callback then runs through the whole list deregistering each
1760 // instance, clearing the backpointers, and then disposing the parent request_state object.
1761 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1762 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1763 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1764 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1765 si->request = NULL;
1766 err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
1767 if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
1768 }
1769 }
1770 }
1771 }
1772 }
1773 }
1774
1775 // Don't allow normal and anonymous registration to coexist.
1776 mDNSlocal mDNSBool CheckForMixedRegistrations(domainname *regtype, domainname *domain, mDNSBool AnonData)
1777 {
1778 request_state *request;
1779
1780 // We only care about local domains where the anonymous extension is
1781 // implemented.
1782 if (!SameDomainName(domain, (const domainname *) "\x5" "local"))
1783 {
1784 return mDNStrue;
1785 }
1786
1787 for (request = all_requests; request; request = request->next)
1788 {
1789 service_instance *ptr;
1790
1791 if (request->terminate != regservice_termination_callback) continue;
1792 for (ptr = request->u.servicereg.instances; ptr ; ptr = ptr->next)
1793 {
1794 if (!SameDomainName(&ptr->domain, (const domainname *)"\x5" "local") ||
1795 !SameDomainName(&request->u.servicereg.type, regtype))
1796 {
1797 continue;
1798 }
1799
1800 // If we are about to register a anonymous registraion, we dont't want to
1801 // allow the regular ones and vice versa.
1802 if (AnonData)
1803 {
1804 if (!ptr->srs.AnonData)
1805 {
1806 LogMsg("CheckForMixedRegistrations: Normal registration already exists for %##s", regtype->c);
1807 return mDNSfalse;
1808 }
1809 }
1810 else
1811 {
1812 // Allow multiple regular registrations
1813 if (ptr->srs.AnonData)
1814 {
1815 LogMsg("CheckForMixedRegistrations: Anonymous registration already exists for %##s", regtype->c);
1816 return mDNSfalse;
1817 }
1818 }
1819 }
1820 }
1821 return mDNStrue;
1822 }
1823
1824 // Returns true if the interfaceIndex value matches one of the pre-defined
1825 // special values listed in the switch statement below.
1826 mDNSlocal mDNSBool PreDefinedInterfaceIndex(mDNSu32 interfaceIndex)
1827 {
1828 switch(interfaceIndex)
1829 {
1830 case kDNSServiceInterfaceIndexAny:
1831 case kDNSServiceInterfaceIndexLocalOnly:
1832 case kDNSServiceInterfaceIndexUnicast:
1833 case kDNSServiceInterfaceIndexP2P:
1834 case kDNSServiceInterfaceIndexBLE:
1835 return mDNStrue;
1836 default:
1837 return mDNSfalse;
1838 }
1839 }
1840
1841 mDNSlocal mStatus handle_regservice_request(request_state *request)
1842 {
1843 char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
1844 char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
1845 char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
1846 domainname d, srv;
1847 mStatus err;
1848 char *AnonData = mDNSNULL;
1849 const char *msgTXTData;
1850
1851 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
1852 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
1853 mDNSInterfaceID InterfaceID;
1854
1855 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
1856 // kDNSServiceFlagsIncludeP2P flag set.
1857 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
1858 {
1859 LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
1860 flags |= kDNSServiceFlagsIncludeP2P;
1861 interfaceIndex = kDNSServiceInterfaceIndexAny;
1862 }
1863
1864 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
1865
1866 // The registration is scoped to a specific interface index, but the
1867 // interface is not currently in our list.
1868 if (interfaceIndex && !InterfaceID)
1869 {
1870 // If it's one of the specially defined inteface index values, just return an error.
1871 if (PreDefinedInterfaceIndex(interfaceIndex))
1872 {
1873 LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex);
1874 return(mStatus_BadParamErr);
1875 }
1876
1877 // Otherwise, use the specified interface index value and the registration will
1878 // be applied to that interface when it comes up.
1879 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
1880 LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex);
1881 }
1882
1883 if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
1884 get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1885 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
1886 get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
1887 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
1888
1889 request->flags = flags;
1890 request->interfaceIndex = interfaceIndex;
1891 request->u.servicereg.InterfaceID = InterfaceID;
1892 request->u.servicereg.instances = NULL;
1893 request->u.servicereg.txtlen = 0;
1894 request->u.servicereg.txtdata = NULL;
1895 mDNSPlatformStrLCopy(request->u.servicereg.type_as_string, type_as_string, sizeof(request->u.servicereg.type_as_string));
1896
1897 if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
1898 else
1899 {
1900 request->u.servicereg.port.b[0] = *request->msgptr++;
1901 request->u.servicereg.port.b[1] = *request->msgptr++;
1902 }
1903
1904 request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
1905 msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);
1906
1907 if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1908
1909 if (request->u.servicereg.txtlen)
1910 {
1911 request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
1912 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
1913 mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
1914 }
1915
1916 // Check for sub-types after the service type
1917 request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
1918 if (request->u.servicereg.num_subtypes < 0)
1919 {
1920 LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string);
1921 goto bad_param;
1922 }
1923 if (AnonData)
1924 {
1925 int AnonDataLen = strlen(AnonData);
1926 if (AnonDataLen > MAX_ANONYMOUS_DATA)
1927 {
1928 LogMsg("ERROR: handle_regservice_request: AnonDataLen %d", AnonDataLen);
1929 goto bad_param;
1930 }
1931 request->u.servicereg.AnonData = mDNStrue;
1932 }
1933 else
1934 {
1935 request->u.servicereg.AnonData = mDNSfalse;
1936 }
1937
1938 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
1939 if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
1940 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); goto bad_param; }
1941
1942 if (!name[0])
1943 {
1944 request->u.servicereg.name = mDNSStorage.nicelabel;
1945 request->u.servicereg.autoname = mDNStrue;
1946 }
1947 else
1948 {
1949 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
1950 if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
1951 {
1952 int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
1953 name[newlen] = 0;
1954 }
1955 if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
1956 { LogMsg("ERROR: handle_regservice_request - name bad %s", name); goto bad_param; }
1957 request->u.servicereg.autoname = mDNSfalse;
1958 }
1959
1960 if (*domain)
1961 {
1962 request->u.servicereg.default_domain = mDNSfalse;
1963 if (!MakeDomainNameFromDNSNameString(&d, domain))
1964 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); goto bad_param; }
1965 }
1966 else
1967 {
1968 request->u.servicereg.default_domain = mDNStrue;
1969 MakeDomainNameFromDNSNameString(&d, "local.");
1970 }
1971
1972 // We don't allow the anonymous and the regular ones to coexist
1973 if (!CheckForMixedRegistrations(&request->u.servicereg.type, &d, request->u.servicereg.AnonData)) { goto bad_param; }
1974
1975 if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
1976 {
1977 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
1978 request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); goto bad_param;
1979 }
1980
1981 if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
1982 { LogMsg("ERROR: handle_regservice_request - host bad %s", host); goto bad_param; }
1983 request->u.servicereg.autorename = (flags & kDNSServiceFlagsNoAutoRename ) == 0;
1984 request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
1985
1986 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1987 // a port number of zero. When two instances of the protected client are allowed to run on one
1988 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1989 if (!mDNSIPPortIsZero(request->u.servicereg.port))
1990 {
1991 int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
1992 if (count)
1993 LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request->process_id,
1994 request->pid_name, count+1, srv.c, mDNSVal16(request->u.servicereg.port));
1995 }
1996
1997 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
1998 // Determine if this request should be promoted to use BLE triggered feature.
1999 if (shouldUseBLE(InterfaceID, 0, &request->u.servicereg.type, &d))
2000 {
2001 request->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2002 LogInfo("handle_regservice_request: registration promoted to use kDNSServiceFlagsAutoTrigger");
2003 }
2004 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2005
2006 LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START PID[%d](%s)",
2007 request->sd, request->flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host,
2008 mDNSVal16(request->u.servicereg.port), request->process_id, request->pid_name);
2009
2010 // We need to unconditionally set request->terminate, because even if we didn't successfully
2011 // start any registrations right now, subsequent configuration changes may cause successful
2012 // registrations to be added, and we'll need to cancel them before freeing this memory.
2013 // We also need to set request->terminate first, before adding additional service instances,
2014 // because the uds_validatelists uses the request->terminate function pointer to determine
2015 // what kind of request this is, and therefore what kind of list validation is required.
2016 request->terminate = regservice_termination_callback;
2017
2018 err = register_service_instance(request, &d);
2019
2020 #if TARGET_OS_EMBEDDED
2021 ++curr_num_regservices;
2022 if (curr_num_regservices > max_num_regservices)
2023 max_num_regservices = curr_num_regservices;
2024 #endif
2025
2026 #if 0
2027 err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
2028 #endif
2029 if (!err)
2030 {
2031 if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
2032
2033 if (!*domain)
2034 {
2035 DNameListElem *ptr;
2036 // Note that we don't report errors for non-local, non-explicit domains
2037 for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
2038 if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
2039 register_service_instance(request, &ptr->name);
2040 }
2041 }
2042
2043 return(err);
2044
2045 bad_param:
2046 freeL("handle_regservice_request (txtdata)", request->u.servicereg.txtdata);
2047 request->u.servicereg.txtdata = NULL;
2048 return mStatus_BadParamErr;
2049 }
2050
2051 // ***************************************************************************
2052 #if COMPILER_LIKES_PRAGMA_MARK
2053 #pragma mark -
2054 #pragma mark - DNSServiceBrowse
2055 #endif
2056
2057 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2058 {
2059 DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
2060 request_state *req = question->QuestionContext;
2061 reply_state *rep;
2062 (void)m; // Unused
2063
2064 if (answer->rrtype != kDNSType_PTR)
2065 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
2066
2067 if (mDNSOpaque16IsZero(question->TargetQID) && (question->BrowseThreshold > 0) && (question->CurrentAnswers >= question->BrowseThreshold))
2068 {
2069 flags |= kDNSServiceFlagsThresholdReached;
2070 }
2071
2072 // if returning a negative answer, then use question's name in reply
2073 if (answer->RecordType == kDNSRecordTypePacketNegative)
2074 {
2075 GenerateBrowseReply(&question->qname, answer->InterfaceID, req, &rep, browse_reply_op, flags, kDNSServiceErr_NoSuchRecord);
2076 goto validReply;
2077 }
2078
2079 if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
2080 {
2081 if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
2082 {
2083 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2084 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2085 GenerateBrowseReply(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
2086 goto validReply;
2087 }
2088
2089 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2090 req->sd, answer->name->c, answer->rdata->u.name.c);
2091 return;
2092 }
2093
2094 validReply:
2095
2096 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s interface %d: %s",
2097 req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV",
2098 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2099
2100 append_reply(req, rep);
2101 }
2102
2103 mDNSlocal void SetQuestionPolicy(DNSQuestion *q, request_state *req)
2104 {
2105 q->euid = req->uid;
2106 // The policy is either based on pid or UUID. Pass a zero pid
2107 // to the "core" if the UUID is valid. If we always pass the pid,
2108 // then the "core" needs to determine whether the uuid is valid
2109 // by examining all the 16 bytes at the time of the policy
2110 // check and also when setting the delegate socket option. Also, it
2111 // requires that we zero out the uuid wherever the question is
2112 // initialized to make sure that it is not interpreted as valid.
2113 // To prevent these intrusive changes, just pass a zero pid to indicate
2114 // that pid is not valid when uuid is valid. In future if we need the
2115 // pid in the question, we will reevaluate this strategy.
2116 if (req->validUUID)
2117 {
2118 mDNSPlatformMemCopy(q->uuid, req->uuid, UUID_SIZE);
2119 q->pid = 0;
2120 }
2121 else
2122 {
2123 q->pid = req->process_id;
2124 }
2125
2126 //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
2127 }
2128
2129 mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
2130 {
2131 browser_t *b, *p;
2132 mStatus err;
2133
2134 for (p = info->u.browser.browsers; p; p = p->next)
2135 {
2136 if (SameDomainName(&p->domain, d))
2137 { debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
2138 }
2139
2140 b = mallocL("browser_t", sizeof(*b));
2141 if (!b) return mStatus_NoMemoryErr;
2142 mDNSPlatformMemZero(b, sizeof(*b));
2143 AssignDomainName(&b->domain, d);
2144 SetQuestionPolicy(&b->q, info);
2145 err = mDNS_StartBrowse(&mDNSStorage, &b->q, &info->u.browser.regtype, d, info->u.browser.AnonData, info->u.browser.interface_id, info->flags,
2146 info->u.browser.ForceMCast, (info->flags & kDNSServiceFlagsBackgroundTrafficClass) != 0, FoundInstance, info);
2147 if (err)
2148 {
2149 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
2150 freeL("browser_t/add_domain_to_browser", b);
2151 }
2152 else
2153 {
2154 b->next = info->u.browser.browsers;
2155 info->u.browser.browsers = b;
2156
2157 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2158 // Determine if this request should be promoted to use BLE triggered discovery.
2159 if (shouldUseBLE(info->u.browser.interface_id, 0, &info->u.browser.regtype, (domainname *) d))
2160 {
2161 info->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2162 b->q.flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2163 LogInfo("add_domain_to_browser: request promoted to use kDNSServiceFlagsAutoTrigger");
2164 }
2165 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2166
2167 LogMcastQ(&b->q, info, q_start);
2168 if (callExternalHelpers(info->u.browser.interface_id, &b->domain, info->flags))
2169 {
2170 domainname tmp;
2171 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
2172 LogDebug("add_domain_to_browser: calling external_start_browsing_for_service()");
2173 external_start_browsing_for_service(info->u.browser.interface_id, &tmp, kDNSType_PTR, info->flags);
2174 }
2175 }
2176 return err;
2177 }
2178
2179 mDNSlocal void browse_termination_callback(request_state *info)
2180 {
2181 if (info->u.browser.default_domain)
2182 {
2183 // Stop the domain enumeration queries to discover the WAB legacy browse domains
2184 LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info->sd, info->process_id, info->pid_name);
2185 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2186 }
2187 if (info->u.browser.AnonData)
2188 freeL("Anonymous", (void *)info->u.browser.AnonData);
2189 while (info->u.browser.browsers)
2190 {
2191 browser_t *ptr = info->u.browser.browsers;
2192
2193 if (callExternalHelpers(ptr->q.InterfaceID, &ptr->domain, ptr->q.flags))
2194 {
2195 domainname tmp;
2196 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
2197 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2198 external_stop_browsing_for_service(ptr->q.InterfaceID, &tmp, kDNSType_PTR, ptr->q.flags);
2199 }
2200
2201 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\") STOP PID[%d](%s)",
2202 info->sd, info->flags, info->interfaceIndex, ptr->q.qname.c, info->process_id, info->pid_name);
2203
2204 info->u.browser.browsers = ptr->next;
2205 mDNS_StopBrowse(&mDNSStorage, &ptr->q); // no need to error-check result
2206 LogMcastQ(&ptr->q, info, q_stop);
2207 freeL("browser_t/browse_termination_callback", ptr);
2208 }
2209 }
2210
2211 mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
2212 {
2213 request_state *request;
2214 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
2215
2216 for (request = all_requests; request; request = request->next)
2217 {
2218 if (request->terminate != browse_termination_callback) continue; // Not a browse operation
2219 if (!request->u.browser.default_domain) continue; // Not an auto-browse operation
2220 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
2221 {
2222 browser_t **ptr = &request->u.browser.browsers;
2223 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
2224 if (add)
2225 {
2226 // If we don't already have this domain in our list for this browse operation, add it now
2227 if (!*ptr) add_domain_to_browser(request, &d->name);
2228 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
2229 }
2230 else
2231 {
2232 if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
2233 else
2234 {
2235 DNameListElem *p;
2236 for (p = AutoBrowseDomains; p; p=p->next)
2237 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
2238 if (SameDomainName(&d->name, &p->name)) break;
2239 if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
2240 else
2241 {
2242 browser_t *rem = *ptr;
2243 *ptr = (*ptr)->next;
2244 mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
2245 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
2246 }
2247 }
2248 }
2249 }
2250 }
2251 }
2252
2253 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
2254 {
2255 (void)m; // unused
2256 if (result == mStatus_MemFree)
2257 {
2258 // On shutdown, mDNS_Close automatically deregisters all records
2259 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2260 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2261 // (This should actually no longer be necessary, now that we do the proper cleanup in
2262 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2263 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2264 ARListElem **ptr = &LocalDomainEnumRecords;
2265 while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
2266 if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
2267 mDNSPlatformMemFree(rr->RecordContext);
2268 }
2269 }
2270
2271 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2272 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2273 // We may want to turn the common code into a subroutine.
2274
2275 mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2276 {
2277 // allocate/register legacy and non-legacy _browse PTR record
2278 mStatus err;
2279 ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
2280
2281 debugf("Incrementing %s refcount for %##s",
2282 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2283 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2284 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2285
2286 mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
2287 MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
2288 AppendDNSNameString (&ptr->ar.namestorage, "local");
2289 AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
2290 err = mDNS_Register(m, &ptr->ar);
2291 if (err)
2292 {
2293 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
2294 mDNSPlatformMemFree(ptr);
2295 }
2296 else
2297 {
2298 ptr->next = LocalDomainEnumRecords;
2299 LocalDomainEnumRecords = ptr;
2300 }
2301 }
2302
2303 mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2304 {
2305 ARListElem **ptr = &LocalDomainEnumRecords;
2306 domainname lhs; // left-hand side of PTR, for comparison
2307
2308 debugf("Decrementing %s refcount for %##s",
2309 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2310 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2311 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2312
2313 MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
2314 AppendDNSNameString (&lhs, "local");
2315
2316 while (*ptr)
2317 {
2318 if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
2319 {
2320 ARListElem *rem = *ptr;
2321 *ptr = (*ptr)->next;
2322 mDNS_Deregister(m, &rem->ar);
2323 return;
2324 }
2325 else ptr = &(*ptr)->next;
2326 }
2327 }
2328
2329 mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2330 {
2331 DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
2332 if (!new) { LogMsg("ERROR: malloc"); return; }
2333 AssignDomainName(&new->name, name);
2334 new->uid = uid;
2335 new->next = AutoBrowseDomains;
2336 AutoBrowseDomains = new;
2337 udsserver_automatic_browse_domain_changed(new, mDNStrue);
2338 }
2339
2340 mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2341 {
2342 DNameListElem **p = &AutoBrowseDomains;
2343 while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
2344 if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
2345 else
2346 {
2347 DNameListElem *ptr = *p;
2348 *p = ptr->next;
2349 udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
2350 mDNSPlatformMemFree(ptr);
2351 }
2352 }
2353
2354 mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
2355 {
2356 DNameListElem *d;
2357 for (d = browseDomains; d; d = d->next)
2358 {
2359 if (add)
2360 {
2361 RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2362 AddAutoBrowseDomain(d->uid, &d->name);
2363 }
2364 else
2365 {
2366 DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2367 RmvAutoBrowseDomain(d->uid, &d->name);
2368 }
2369 }
2370 }
2371
2372 #if APPLE_OSX_mDNSResponder
2373
2374 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2375 {
2376 int num_autoname = 0;
2377 request_state *req;
2378
2379 // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2380 for (req = all_requests; req; req = req->next)
2381 {
2382 if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname && req->interfaceIndex != kDNSServiceInterfaceIndexLocalOnly)
2383 num_autoname++;
2384 }
2385
2386 // If DeviceInfo record is currently registered, see if we need to deregister it
2387 if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
2388 if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
2389 {
2390 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
2391 mDNS_Deregister(m, &m->DeviceInfo);
2392 }
2393
2394 // If DeviceInfo record is not currently registered, see if we need to register it
2395 if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
2396 if (num_autoname > 0)
2397 {
2398 mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
2399 ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
2400 m->DeviceInfo.resrec.rdlength = initializeDeviceInfoTXT(m, m->DeviceInfo.resrec.rdata->u.data);
2401 LogOperation("UpdateDeviceInfoRecord Register %##s", m->DeviceInfo.resrec.name);
2402 mDNS_Register(m, &m->DeviceInfo);
2403 }
2404 }
2405 #else // APPLE_OSX_mDNSResponder
2406 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2407 {
2408 (void)m; // unused
2409 }
2410 #endif // APPLE_OSX_mDNSResponder
2411
2412 mDNSexport void udsserver_handle_configchange(mDNS *const m)
2413 {
2414 request_state *req;
2415 service_instance *ptr;
2416 DNameListElem *RegDomains = NULL;
2417 DNameListElem *BrowseDomains = NULL;
2418 DNameListElem *p;
2419
2420 UpdateDeviceInfoRecord(m);
2421
2422 // For autoname services, see if the default service name has changed, necessitating an automatic update
2423 for (req = all_requests; req; req = req->next)
2424 if (req->terminate == regservice_termination_callback)
2425 if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
2426 {
2427 req->u.servicereg.name = m->nicelabel;
2428 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
2429 {
2430 ptr->renameonmemfree = 1;
2431 if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
2432 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
2433 if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
2434 regservice_callback(m, &ptr->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
2435 }
2436 }
2437
2438 // Let the platform layer get the current DNS information
2439 mDNS_Lock(m);
2440 mDNSPlatformSetDNSConfig(mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains, mDNSfalse);
2441 mDNS_Unlock(m);
2442
2443 // Any automatic registration domains are also implicitly automatic browsing domains
2444 if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue); // Add the new list first
2445 if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse); // Then clear the old list
2446
2447 // Add any new domains not already in our AutoRegistrationDomains list
2448 for (p=RegDomains; p; p=p->next)
2449 {
2450 DNameListElem **pp = &AutoRegistrationDomains;
2451 while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
2452 if (!*pp) // If not found in our existing list, this is a new default registration domain
2453 {
2454 RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
2455 udsserver_default_reg_domain_changed(p, mDNStrue);
2456 }
2457 else // else found same domainname in both old and new lists, so no change, just delete old copy
2458 {
2459 DNameListElem *del = *pp;
2460 *pp = (*pp)->next;
2461 mDNSPlatformMemFree(del);
2462 }
2463 }
2464
2465 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2466 while (AutoRegistrationDomains)
2467 {
2468 DNameListElem *del = AutoRegistrationDomains;
2469 AutoRegistrationDomains = AutoRegistrationDomains->next; // Cut record from list FIRST,
2470 DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
2471 udsserver_default_reg_domain_changed(del, mDNSfalse); // before calling udsserver_default_reg_domain_changed()
2472 mDNSPlatformMemFree(del);
2473 }
2474
2475 // Now we have our new updated automatic registration domain list
2476 AutoRegistrationDomains = RegDomains;
2477
2478 // Add new browse domains to internal list
2479 if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
2480
2481 // Remove old browse domains from internal list
2482 if (SCPrefBrowseDomains)
2483 {
2484 SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
2485 while (SCPrefBrowseDomains)
2486 {
2487 DNameListElem *fptr = SCPrefBrowseDomains;
2488 SCPrefBrowseDomains = SCPrefBrowseDomains->next;
2489 mDNSPlatformMemFree(fptr);
2490 }
2491 }
2492
2493 // Replace the old browse domains array with the new array
2494 SCPrefBrowseDomains = BrowseDomains;
2495 }
2496
2497 mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
2498 {
2499 (void)m; // unused;
2500 (void)q; // unused
2501
2502 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2503 AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
2504
2505 if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
2506 else RmvAutoBrowseDomain(0, &answer->rdata->u.name);
2507 }
2508
2509 mDNSlocal mStatus handle_browse_request(request_state *request)
2510 {
2511 char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2512 domainname typedn, d, temp;
2513 mDNSs32 NumSubTypes;
2514 char *AnonData = mDNSNULL;
2515 mStatus err = mStatus_NoError;
2516 int AnonDataLen;
2517
2518 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2519 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2520 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2521
2522 // The browse is scoped to a specific interface index, but the
2523 // interface is not currently in our list.
2524 if (interfaceIndex && !InterfaceID)
2525 {
2526 // If it's one of the specially defined inteface index values, just return an error.
2527 if (PreDefinedInterfaceIndex(interfaceIndex))
2528 {
2529 LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex);
2530 return(mStatus_BadParamErr);
2531 }
2532
2533 // Otherwise, use the specified interface index value and the browse will
2534 // be applied to that interface when it comes up.
2535 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2536 LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex);
2537 }
2538
2539 if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2540 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
2541
2542 if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2543
2544 request->flags = flags;
2545 request->interfaceIndex = interfaceIndex;
2546 typedn.c[0] = 0;
2547 NumSubTypes = ChopSubTypes(regtype, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
2548 if (NumSubTypes < 0 || NumSubTypes > 1)
2549 return(mStatus_BadParamErr);
2550 AnonDataLen = 0;
2551 if (AnonData)
2552 {
2553 AnonDataLen = strlen(AnonData);
2554 if (AnonDataLen > MAX_ANONYMOUS_DATA)
2555 {
2556 LogMsg("handle_browse_request: AnonDataLen %d", AnonDataLen);
2557 return(mStatus_BadParamErr);
2558 }
2559 // Account for the null byte
2560 AnonDataLen += 1;
2561 }
2562 if (NumSubTypes == 1)
2563 {
2564 if (!AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1 + AnonDataLen))
2565 return(mStatus_BadParamErr);
2566 }
2567
2568 if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
2569
2570 if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
2571 // For over-long service types, we only allow domain "local"
2572 if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrLCopy(domain, "local.", sizeof(domain));
2573
2574 // Set up browser info
2575 request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
2576 request->u.browser.interface_id = InterfaceID;
2577 AssignDomainName(&request->u.browser.regtype, &typedn);
2578 request->u.browser.default_domain = !domain[0];
2579 request->u.browser.browsers = NULL;
2580
2581 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START PID[%d](%s)",
2582 request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain, request->process_id, request->pid_name);
2583
2584 if (request->u.browser.default_domain)
2585 {
2586 // Start the domain enumeration queries to discover the WAB browse domains
2587 LogInfo("%3d: DNSServiceBrowse Start WAB PID[%d](%s)", request->sd, request->process_id, request->pid_name);
2588 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2589 }
2590 request->u.browser.AnonData = mDNSNULL;
2591 if (AnonData)
2592 {
2593 int len = strlen(AnonData) + 1;
2594 request->u.browser.AnonData = mallocL("Anonymous", len);
2595 if (!request->u.browser.AnonData)
2596 return mStatus_NoMemoryErr;
2597 else
2598 mDNSPlatformMemCopy((void *)request->u.browser.AnonData, AnonData, len);
2599 }
2600 // We need to unconditionally set request->terminate, because even if we didn't successfully
2601 // start any browses right now, subsequent configuration changes may cause successful
2602 // browses to be added, and we'll need to cancel them before freeing this memory.
2603 request->terminate = browse_termination_callback;
2604
2605 if (domain[0])
2606 {
2607 if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
2608 err = add_domain_to_browser(request, &d);
2609 }
2610 else
2611 {
2612 DNameListElem *sdom;
2613 for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
2614 if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
2615 {
2616 err = add_domain_to_browser(request, &sdom->name);
2617 if (err)
2618 {
2619 if (SameDomainName(&sdom->name, &localdomain)) break;
2620 else err = mStatus_NoError; // suppress errors for non-local "default" domains
2621 }
2622 }
2623 }
2624
2625 return(err);
2626 }
2627
2628 // ***************************************************************************
2629 #if COMPILER_LIKES_PRAGMA_MARK
2630 #pragma mark -
2631 #pragma mark - DNSServiceResolve
2632 #endif
2633
2634 mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2635 {
2636 size_t len = 0;
2637 char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME] = "0";
2638 char *data;
2639 reply_state *rep;
2640 request_state *req = question->QuestionContext;
2641 const DNSServiceErrorType error =
2642 (answer->RecordType == kDNSRecordTypePacketNegative) ? kDNSServiceErr_NoSuchRecord : kDNSServiceErr_NoError;
2643 (void)m; // Unused
2644
2645 LogOperation("%3d: DNSServiceResolve(%##s) %s interface %d: %s",
2646 req->sd, question->qname.c, AddRecord ? "ADD" : "RMV",
2647 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2648
2649 if (!AddRecord)
2650 {
2651 if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
2652 if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
2653 return;
2654 }
2655
2656 if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
2657 if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
2658
2659 if (!req->u.resolve.txt || !req->u.resolve.srv) return; // only deliver result to client if we have both answers
2660
2661 ConvertDomainNameToCString(answer->name, fullname);
2662
2663 if (answer->RecordType != kDNSRecordTypePacketNegative)
2664 ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
2665
2666 // calculate reply length
2667 len += sizeof(DNSServiceFlags);
2668 len += sizeof(mDNSu32); // interface index
2669 len += sizeof(DNSServiceErrorType);
2670 len += strlen(fullname) + 1;
2671 len += strlen(target) + 1;
2672 len += 2 * sizeof(mDNSu16); // port, txtLen
2673 len += req->u.resolve.txt->rdlength;
2674
2675 // allocate/init reply header
2676 rep = create_reply(resolve_reply_op, len, req);
2677 rep->rhdr->flags = dnssd_htonl(0);
2678 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
2679 rep->rhdr->error = dnssd_htonl(error);
2680
2681 data = (char *)&rep->rhdr[1];
2682
2683 // write reply data to message
2684 put_string(fullname, &data);
2685 put_string(target, &data);
2686 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[0];
2687 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[1];
2688 put_uint16(req->u.resolve.txt->rdlength, &data);
2689 put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
2690
2691 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
2692 append_reply(req, rep);
2693 }
2694
2695 mDNSlocal void resolve_termination_callback(request_state *request)
2696 {
2697 LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") STOP PID[%d](%s)",
2698 request->sd, request->flags, request->interfaceIndex, request->u.resolve.qtxt.qname.c, request->process_id, request->pid_name);
2699 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
2700 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2701 LogMcastQ(&request->u.resolve.qsrv, request, q_stop);
2702 if (request->u.resolve.external_advertise)
2703 external_stop_resolving_service(request->u.resolve.qsrv.InterfaceID, &request->u.resolve.qsrv.qname, request->flags);
2704 }
2705
2706 mDNSlocal mStatus handle_resolve_request(request_state *request)
2707 {
2708 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2709 domainname fqdn;
2710 mStatus err;
2711
2712 // extract the data from the message
2713 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2714 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2715 mDNSInterfaceID InterfaceID;
2716
2717 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2718 // flag set so that the resolve will run over P2P interfaces that are not yet created.
2719 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
2720 {
2721 LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2722 flags |= kDNSServiceFlagsIncludeP2P;
2723 interfaceIndex = kDNSServiceInterfaceIndexAny;
2724 }
2725
2726 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2727
2728 // The operation is scoped to a specific interface index, but the
2729 // interface is not currently in our list.
2730 if (interfaceIndex && !InterfaceID)
2731 {
2732 // If it's one of the specially defined inteface index values, just return an error.
2733 if (PreDefinedInterfaceIndex(interfaceIndex))
2734 {
2735 LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex);
2736 return(mStatus_BadParamErr);
2737 }
2738
2739 // Otherwise, use the specified interface index value and the operation will
2740 // be applied to that interface when it comes up.
2741 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2742 LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex);
2743 }
2744
2745 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
2746 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2747 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
2748 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2749
2750 if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2751
2752 if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
2753 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
2754
2755 mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
2756
2757 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2758 // Determine if this request should be promoted to use BLE triggered discovery.
2759 if (shouldUseBLE(InterfaceID, 0, (domainname *)SkipLeadingLabels(&fqdn, 1), &fqdn))
2760 {
2761 flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
2762 LogInfo("handle_resolve_request: request promoted to use kDNSServiceFlagsAutoTrigger");
2763 }
2764 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
2765
2766 request->flags = flags;
2767 request->interfaceIndex = interfaceIndex;
2768
2769 // format questions
2770 request->u.resolve.qsrv.InterfaceID = InterfaceID;
2771 request->u.resolve.qsrv.flags = flags;
2772 request->u.resolve.qsrv.Target = zeroAddr;
2773 AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
2774 request->u.resolve.qsrv.qtype = kDNSType_SRV;
2775 request->u.resolve.qsrv.qclass = kDNSClass_IN;
2776 request->u.resolve.qsrv.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2777 request->u.resolve.qsrv.ExpectUnique = mDNStrue;
2778 request->u.resolve.qsrv.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2779 request->u.resolve.qsrv.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2780 request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
2781 request->u.resolve.qsrv.SearchListIndex = 0;
2782 request->u.resolve.qsrv.AppendSearchDomains = 0;
2783 request->u.resolve.qsrv.RetryWithSearchDomains = mDNSfalse;
2784 request->u.resolve.qsrv.TimeoutQuestion = 0;
2785 request->u.resolve.qsrv.WakeOnResolve = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
2786 request->u.resolve.qsrv.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2787 request->u.resolve.qsrv.ValidationRequired = 0;
2788 request->u.resolve.qsrv.ValidatingResponse = 0;
2789 request->u.resolve.qsrv.ProxyQuestion = 0;
2790 request->u.resolve.qsrv.qnameOrig = mDNSNULL;
2791 request->u.resolve.qsrv.AnonInfo = mDNSNULL;
2792 request->u.resolve.qsrv.pid = request->process_id;
2793 request->u.resolve.qsrv.euid = request->uid;
2794 request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
2795 request->u.resolve.qsrv.QuestionContext = request;
2796
2797 request->u.resolve.qtxt.InterfaceID = InterfaceID;
2798 request->u.resolve.qtxt.flags = flags;
2799 request->u.resolve.qtxt.Target = zeroAddr;
2800 AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn);
2801 request->u.resolve.qtxt.qtype = kDNSType_TXT;
2802 request->u.resolve.qtxt.qclass = kDNSClass_IN;
2803 request->u.resolve.qtxt.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2804 request->u.resolve.qtxt.ExpectUnique = mDNStrue;
2805 request->u.resolve.qtxt.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2806 request->u.resolve.qtxt.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2807 request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
2808 request->u.resolve.qtxt.SearchListIndex = 0;
2809 request->u.resolve.qtxt.AppendSearchDomains = 0;
2810 request->u.resolve.qtxt.RetryWithSearchDomains = mDNSfalse;
2811 request->u.resolve.qtxt.TimeoutQuestion = 0;
2812 request->u.resolve.qtxt.WakeOnResolve = 0;
2813 request->u.resolve.qtxt.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2814 request->u.resolve.qtxt.ValidationRequired = 0;
2815 request->u.resolve.qtxt.ValidatingResponse = 0;
2816 request->u.resolve.qtxt.ProxyQuestion = 0;
2817 request->u.resolve.qtxt.qnameOrig = mDNSNULL;
2818 request->u.resolve.qtxt.AnonInfo = mDNSNULL;
2819 request->u.resolve.qtxt.pid = request->process_id;
2820 request->u.resolve.qtxt.euid = request->uid;
2821 request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
2822 request->u.resolve.qtxt.QuestionContext = request;
2823
2824 request->u.resolve.ReportTime = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
2825
2826 request->u.resolve.external_advertise = mDNSfalse;
2827
2828 #if 0
2829 if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains)) return(mStatus_NoError);
2830 #endif
2831
2832 // ask the questions
2833 LogOperation("%3d: DNSServiceResolve(%X, %d, \"%##s\") START PID[%d](%s)", request->sd, flags, interfaceIndex,
2834 request->u.resolve.qsrv.qname.c, request->process_id, request->pid_name);
2835
2836 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);
2837
2838 if (!err)
2839 {
2840 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
2841 if (err)
2842 {
2843 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2844 }
2845 else
2846 {
2847 request->terminate = resolve_termination_callback;
2848 LogMcastQ(&request->u.resolve.qsrv, request, q_start);
2849 if (callExternalHelpers(InterfaceID, &fqdn, flags))
2850 {
2851 request->u.resolve.external_advertise = mDNStrue;
2852 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
2853 external_start_resolving_service(InterfaceID, &fqdn, flags);
2854 }
2855 }
2856 }
2857
2858 return(err);
2859 }
2860
2861 // ***************************************************************************
2862 #if COMPILER_LIKES_PRAGMA_MARK
2863 #pragma mark -
2864 #pragma mark - DNSServiceQueryRecord
2865 #endif
2866
2867 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2868 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2869 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2870 // the mDNSCore operation if the client dies or closes its socket.
2871
2872 // Returns -1 to tell the caller that it should not try to reissue the query anymore
2873 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
2874 // Returns 0 when there are no more search domains and the caller should reissue the query
2875 mDNSlocal int AppendNewSearchDomain(DNSQuestion *question)
2876 {
2877 domainname *sd;
2878 mStatus err;
2879
2880 // Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
2881 // the domains and should try the single label query directly on the wire.
2882 if (question->SearchListIndex == -1)
2883 {
2884 LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question->qname.c, DNSTypeName(question->qtype));
2885 return -1;
2886 }
2887
2888 if (!question->AppendSearchDomains)
2889 {
2890 LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question->qname.c, DNSTypeName(question->qtype));
2891 return -1;
2892 }
2893
2894 // Save the original name, before we modify them below.
2895 if (!question->qnameOrig)
2896 {
2897 question->qnameOrig = mallocL("AppendNewSearchDomain", sizeof(domainname));
2898 if (!question->qnameOrig) { LogMsg("AppendNewSearchDomain: ERROR!! malloc failure"); return -1; }
2899 question->qnameOrig->c[0] = 0;
2900 AssignDomainName(question->qnameOrig, &question->qname);
2901 LogInfo("AppendSearchDomain: qnameOrig %##s", question->qnameOrig->c);
2902 }
2903
2904 sd = uDNS_GetNextSearchDomain(question->InterfaceID, &question->SearchListIndex, !question->AppendLocalSearchDomains);
2905 // We use -1 to indicate that we have searched all the domains and should try the single label
2906 // query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
2907 if (question->SearchListIndex == -1)
2908 {
2909 LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
2910 return -1;
2911 }
2912
2913 // Not a common case. Perhaps, we should try the next search domain if it exceeds ?
2914 if (sd && (DomainNameLength(question->qnameOrig) + DomainNameLength(sd)) > MAX_DOMAIN_NAME)
2915 {
2916 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));
2917 return -1;
2918 }
2919
2920 // if there are no more search domains and we have already tried this question
2921 // without appending search domains, then we are done.
2922 if (!sd && !ApplySearchDomainsFirst(question))
2923 {
2924 LogInfo("AppendNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question->qname.c, DNSTypeName(question->qtype));
2925 return -1;
2926 }
2927
2928 // Stop the question before changing the name as negative cache entries could be pointing at this question.
2929 // Even if we don't change the question in the case of returning 0, the caller is going to restart the
2930 // question.
2931 err = mDNS_StopQuery(&mDNSStorage, question);
2932 if (err) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question->qname.c, DNSTypeName(question->qtype), (int)err); }
2933
2934 AssignDomainName(&question->qname, question->qnameOrig);
2935 if (sd)
2936 {
2937 AppendDomainName(&question->qname, sd);
2938 LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question->qname.c, question->SearchListIndex);
2939 return 1;
2940 }
2941
2942 // Try the question as single label
2943 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question->qname.c, DNSTypeName(question->qtype));
2944 return 0;
2945 }
2946
2947 #if APPLE_OSX_mDNSResponder
2948
2949 mDNSlocal mDNSBool DomainInSearchList(const domainname *domain, mDNSBool excludeLocal)
2950 {
2951 const SearchListElem *s;
2952 int qcount, scount;
2953
2954 qcount = CountLabels(domain);
2955 for (s=SearchList; s; s=s->next)
2956 {
2957 if (excludeLocal && SameDomainName(&s->domain, &localdomain))
2958 continue;
2959 scount = CountLabels(&s->domain);
2960 if (qcount >= scount)
2961 {
2962 // Note: When qcount == scount, we do a complete match of the domain
2963 // which is expected by the callers.
2964 const domainname *d = SkipLeadingLabels(domain, (qcount - scount));
2965 if (SameDomainName(&s->domain, d))
2966 {
2967 return mDNStrue;
2968 }
2969 }
2970 }
2971 return mDNSfalse;
2972 }
2973
2974 // The caller already checks that this is a dotlocal question.
2975 mDNSlocal mDNSBool ShouldDeliverNegativeResponse(DNSQuestion *question)
2976 {
2977 mDNSu16 qtype;
2978
2979 // If the question matches the search domain exactly or the search domain is a
2980 // subdomain of the question, it is most likely a valid unicast domain and hence
2981 // don't suppress negative responses.
2982 //
2983 // If the user has configured ".local" as a search domain, we don't want
2984 // to deliver a negative response for names ending in ".local" as that would
2985 // prevent bonjour discovery. Passing mDNStrue for the last argument excludes
2986 // ".local" search domains.
2987 if (DomainInSearchList(&question->qname, mDNStrue))
2988 {
2989 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) in SearchList", question->qname.c, DNSTypeName(question->qtype));
2990 return mDNStrue;
2991 }
2992
2993 // Deliver negative response for A/AAAA if there was a positive response for AAAA/A respectively.
2994 if (question->qtype != kDNSType_A && question->qtype != kDNSType_AAAA)
2995 {
2996 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) not answering local question with negative unicast response",
2997 question->qname.c, DNSTypeName(question->qtype));
2998 return mDNSfalse;
2999 }
3000 qtype = (question->qtype == kDNSType_A ? kDNSType_AAAA : kDNSType_A);
3001 if (!mDNS_CheckForCacheRecord(&mDNSStorage, question, qtype))
3002 {
3003 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) not answering local question with negative unicast response"
3004 " (can't find positive record)", question->qname.c, DNSTypeName(question->qtype));
3005 return mDNSfalse;
3006 }
3007 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) answering local with negative unicast response (found positive record)",
3008 question->qname.c, DNSTypeName(question->qtype));
3009 return mDNStrue;
3010 }
3011
3012 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
3013 // top-level domain
3014 mDNSlocal mStatus SendAdditionalQuery(DNSQuestion *q, request_state *request, mStatus err)
3015 {
3016 #ifndef UNICAST_DISABLED
3017 extern domainname ActiveDirectoryPrimaryDomain;
3018 DNSQuestion **question2;
3019 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
3020 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
3021
3022 question2 = mDNSNULL;
3023 if (request->hdr.op == query_request)
3024 question2 = &request->u.queryrecord.q2;
3025 else if (request->hdr.op == addrinfo_request)
3026 {
3027 if (q->qtype == kDNSType_A)
3028 question2 = &request->u.addrinfo.q42;
3029 else if (q->qtype == kDNSType_AAAA)
3030 question2 = &request->u.addrinfo.q62;
3031 }
3032 if (!question2)
3033 {
3034 LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3035 return mStatus_BadParamErr;
3036 }
3037
3038 // Sanity check: If we already sent an additonal query, we don't need to send one more.
3039 //
3040 // 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
3041 // is called to see whether a unicast query should be sent or not.
3042 //
3043 // 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
3044 // was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
3045 // send the additional query.
3046 //
3047 // Thus, it should not be called more than once.
3048 if (*question2)
3049 {
3050 LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q->qname.c, DNSTypeName(q->qtype));
3051 return err;
3052 }
3053
3054 if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
3055 if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q))
3056 {
3057 DNSQuestion *q2;
3058 int labels = CountLabels(&q->qname);
3059 q2 = mallocL("DNSQuestion", sizeof(DNSQuestion));
3060 if (!q2) FatalError("ERROR: SendAdditionalQuery malloc");
3061 *question2 = q2;
3062 *q2 = *q;
3063 q2->InterfaceID = mDNSInterface_Unicast;
3064 q2->ExpectUnique = mDNStrue;
3065 // Always set the QuestionContext to indicate that this question should be stopped
3066 // before freeing. Don't rely on "q".
3067 q2->QuestionContext = request;
3068 // If the query starts as a single label e.g., somehost, and we have search domains with .local,
3069 // queryrecord_result_callback calls this function when .local is appended to "somehost".
3070 // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
3071 // "somehost". We need to copy that information so that when we retry with a different search
3072 // domain e.g., mycompany.local, we get "somehost.mycompany.local".
3073 if (q->qnameOrig)
3074 {
3075 (*question2)->qnameOrig = mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
3076 if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!! malloc failure"); return mStatus_NoMemoryErr; }
3077 (*question2)->qnameOrig->c[0] = 0;
3078 AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
3079 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
3080 }
3081 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
3082 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
3083 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
3084 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
3085 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
3086 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
3087 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
3088 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
3089 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
3090 // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
3091 // of those, we don't want do the SOA check for the local
3092 if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname, mDNSfalse))
3093 {
3094 AssignDomainName(&q2->qname, &localdomain);
3095 q2->qtype = kDNSType_SOA;
3096 q2->LongLived = mDNSfalse;
3097 q2->ForceMCast = mDNSfalse;
3098 q2->ReturnIntermed = mDNStrue;
3099 // Don't append search domains for the .local SOA query
3100 q2->AppendSearchDomains = 0;
3101 q2->AppendLocalSearchDomains = 0;
3102 q2->RetryWithSearchDomains = mDNSfalse;
3103 q2->SearchListIndex = 0;
3104 q2->TimeoutQuestion = 0;
3105 q2->AnonInfo = mDNSNULL;
3106 q2->pid = request->process_id;
3107 q2->euid = request->uid;
3108 }
3109 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
3110 err = mDNS_StartQuery(&mDNSStorage, q2);
3111 if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
3112 }
3113 return(err);
3114 #else // !UNICAST_DISABLED
3115 (void) q;
3116 (void) request;
3117 (void) err;
3118
3119 return mStatus_NoError;
3120 #endif // !UNICAST_DISABLED
3121 }
3122 #endif // APPLE_OSX_mDNSResponder
3123
3124 // This function tries to append a search domain if valid and possible. If so, returns true.
3125 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(DNSQuestion *question, request_state *req, QC_result AddRecord)
3126 {
3127 int result;
3128 // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
3129 // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
3130 // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
3131 // RetryWithSearchDomains which may or may not be set.
3132 //
3133 // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
3134 // is a valid question for appending search domains, retry by appending domains
3135
3136 if ((AddRecord != QC_suppressed) && question->SearchListIndex != -1 && question->AppendSearchDomains)
3137 {
3138 question->RetryWithSearchDomains = 0;
3139 result = AppendNewSearchDomain(question);
3140 // As long as the result is either zero or 1, we retry the question. If we exahaust the search
3141 // domains (result is zero) we try the original query (as it was before appending the search
3142 // domains) as such on the wire as a last resort if we have not tried them before. For queries
3143 // with more than one label, we have already tried them before appending search domains and
3144 // hence don't retry again
3145 if (result != -1)
3146 {
3147 mStatus err;
3148 err = mDNS_StartQuery(&mDNSStorage, question);
3149 if (!err)
3150 {
3151 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
3152 // If the result was zero, it meant that there are no search domains and we just retried the question
3153 // as a single label and we should not retry with search domains anymore.
3154 if (!result) question->SearchListIndex = -1;
3155 return mDNStrue;
3156 }
3157 else
3158 {
3159 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3160 // We have already stopped the query and could not restart. Reset the appropriate pointers
3161 // so that we don't call stop again when the question terminates
3162 question->QuestionContext = mDNSNULL;
3163 }
3164 }
3165 }
3166 else
3167 {
3168 LogDebug("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, AddRecord, question->SearchListIndex, question->AppendSearchDomains);
3169 }
3170 return mDNSfalse;
3171 }
3172
3173 mDNSlocal void queryrecord_result_reply(mDNS *const m, request_state *req, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord,
3174 DNSServiceErrorType error)
3175 {
3176 char name[MAX_ESCAPED_DOMAIN_NAME];
3177 size_t len;
3178 DNSServiceFlags flags = 0;
3179 reply_state *rep;
3180 char *data;
3181
3182 ConvertDomainNameToCString(answer->name, name);
3183
3184 LogOperation("%3d: %s(%##s, %s) RESULT %s interface %d: (%s)%s", req->sd,
3185 req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
3186 question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV",
3187 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse),
3188 MortalityDisplayString(answer->mortality), RRDisplayString(m, answer));
3189
3190 len = sizeof(DNSServiceFlags); // calculate reply data length
3191 len += sizeof(mDNSu32); // interface index
3192 len += sizeof(DNSServiceErrorType);
3193 len += strlen(name) + 1;
3194 len += 3 * sizeof(mDNSu16); // type, class, rdlen
3195 len += answer->rdlength;
3196 len += sizeof(mDNSu32); // TTL
3197
3198 rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
3199
3200 if (AddRecord)
3201 flags |= kDNSServiceFlagsAdd;
3202 if (answer->mortality == Mortality_Ghost)
3203 flags |= kDNSServiceFlagsExpiredAnswer;
3204 if (question->ValidationStatus != 0)
3205 {
3206 error = kDNSServiceErr_NoError;
3207 if (question->ValidationRequired && question->ValidationState == DNSSECValDone)
3208 {
3209 switch (question->ValidationStatus) //Set the dnssec flags to be passed on to the Apps here
3210 {
3211 case DNSSEC_Secure:
3212 flags |= kDNSServiceFlagsSecure;
3213 break;
3214 case DNSSEC_Insecure:
3215 flags |= kDNSServiceFlagsInsecure;
3216 break;
3217 case DNSSEC_Indeterminate:
3218 flags |= kDNSServiceFlagsIndeterminate;
3219 break;
3220 case DNSSEC_Bogus:
3221 flags |= kDNSServiceFlagsBogus;
3222 break;
3223 default:
3224 LogMsg("queryrecord_result_reply unknown status %d for %##s", question->ValidationStatus, question->qname.c);
3225 }
3226 }
3227 }
3228
3229 rep->rhdr->flags = dnssd_htonl(flags);
3230 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
3231 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
3232 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
3233 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
3234 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
3235 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
3236 // should not have existed to answer this question if the corresponding interface is not valid.
3237 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
3238 rep->rhdr->error = dnssd_htonl(error);
3239
3240 data = (char *)&rep->rhdr[1];
3241
3242 put_string(name, &data);
3243 put_uint16(answer->rrtype, &data);
3244 put_uint16(answer->rrclass, &data);
3245 put_uint16(answer->rdlength, &data);
3246 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
3247 // function just does a blind memory copy without regard to structures that may have holes in them.
3248 if (answer->rdlength)
3249 if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
3250 LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
3251 data += answer->rdlength;
3252 put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
3253
3254 append_reply(req, rep);
3255 // Stop the question, if we just timed out
3256 if (error == kDNSServiceErr_Timeout)
3257 {
3258 mDNS_StopQuery(m, question);
3259 // Reset the pointers so that we don't call stop on termination
3260 question->QuestionContext = mDNSNULL;
3261 }
3262 else if ((AddRecord == QC_add) && req->hdr.op == addrinfo_request)
3263 {
3264 // Note: We count all answers including LocalOnly e.g., /etc/hosts. If we
3265 // exclude that, v4ans/v6ans will be zero and we would wrongly think that
3266 // we did not answer questions and setup the status to deliver triggers.
3267 if (question->qtype == kDNSType_A)
3268 req->u.addrinfo.v4ans = 1;
3269 if (question->qtype == kDNSType_AAAA)
3270 req->u.addrinfo.v6ans = 1;
3271 }
3272 else if ((AddRecord == QC_add) && req->hdr.op == query_request)
3273 {
3274 if (question->qtype == kDNSType_A || question->qtype == kDNSType_AAAA)
3275 req->u.queryrecord.ans = 1;
3276 }
3277
3278 #if APPLE_OSX_mDNSResponder
3279 #if !NO_WCF
3280 CHECK_WCF_FUNCTION(WCFIsServerRunning)
3281 {
3282 struct xucred x;
3283 socklen_t xucredlen = sizeof(x);
3284
3285 if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
3286 {
3287 if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
3288 (x.cr_version == XUCRED_VERSION))
3289 {
3290 struct sockaddr_storage addr;
3291 addr.ss_len = 0;
3292 if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
3293 {
3294 if (answer->rrtype == kDNSType_A)
3295 {
3296 struct sockaddr_in *const sin = (struct sockaddr_in *)&addr;
3297 sin->sin_port = 0;
3298 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3299 // sin->sin_addr.s_addr = answer->rdata->u.ipv4.NotAnInteger;
3300 if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(mDNSv4Addr)), answer))
3301 LogMsg("queryrecord_result_reply: WCF AF_INET putRData failed");
3302 else
3303 {
3304 addr.ss_len = sizeof (struct sockaddr_in);
3305 addr.ss_family = AF_INET;
3306 }
3307 }
3308 else if (answer->rrtype == kDNSType_AAAA)
3309 {
3310 struct sockaddr_in6 *const sin6 = (struct sockaddr_in6 *)&addr;
3311 sin6->sin6_port = 0;
3312 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3313 // sin6->sin6_addr.__u6_addr.__u6_addr32[0] = answer->rdata->u.ipv6.l[0];
3314 // sin6->sin6_addr.__u6_addr.__u6_addr32[1] = answer->rdata->u.ipv6.l[1];
3315 // sin6->sin6_addr.__u6_addr.__u6_addr32[2] = answer->rdata->u.ipv6.l[2];
3316 // sin6->sin6_addr.__u6_addr.__u6_addr32[3] = answer->rdata->u.ipv6.l[3];
3317 if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(mDNSv6Addr)), answer))
3318 LogMsg("queryrecord_result_reply: WCF AF_INET6 putRData failed");
3319 else
3320 {
3321 addr.ss_len = sizeof (struct sockaddr_in6);
3322 addr.ss_family = AF_INET6;
3323 }
3324 }
3325 if (addr.ss_len)
3326 {
3327 debugf("queryrecord_result_reply: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
3328 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3329 {
3330 WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
3331 }
3332 }
3333 }
3334 else if (answer->rrtype == kDNSType_CNAME)
3335 {
3336 domainname cname;
3337 char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
3338 if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
3339 LogMsg("queryrecord_result_reply: WCF CNAME putRData failed");
3340 else
3341 {
3342 ConvertDomainNameToCString(&cname, cname_cstr);
3343 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3344 {
3345 WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
3346 }
3347 }
3348 }
3349 }
3350 else my_perror("queryrecord_result_reply: ERROR: getsockopt LOCAL_PEERCRED");
3351 }
3352 }
3353 #endif
3354 #endif
3355 }
3356
3357 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
3358 {
3359 request_state *req = question->QuestionContext;
3360 DNSServiceErrorType error = kDNSServiceErr_NoError;
3361 DNSQuestion *q = mDNSNULL;
3362
3363 #if APPLE_OSX_mDNSResponder
3364 {
3365 // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
3366 // get any callbacks from the core after this.
3367 if (!req)
3368 {
3369 LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3370 return;
3371 }
3372 if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
3373 q = &req->u.queryrecord.q;
3374 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
3375 q = &req->u.addrinfo.q4;
3376 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
3377 q = &req->u.addrinfo.q6;
3378
3379 if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
3380 {
3381 mStatus err;
3382 domainname *orig = question->qnameOrig;
3383
3384 LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
3385 mDNS_StopQuery(m, question);
3386 question->QuestionContext = mDNSNULL;
3387
3388 // We got a negative response for the SOA record indicating that .local does not exist.
3389 // But we might have other search domains (that does not end in .local) that can be
3390 // appended to this question. In that case, we want to retry the question. Otherwise,
3391 // we don't want to try this question as unicast.
3392 if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
3393 {
3394 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
3395 return;
3396 }
3397
3398 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
3399 //
3400 // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
3401 // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
3402 // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
3403 // SendAdditionalQuery as to how qnameOrig gets initialized.
3404 *question = *q;
3405 question->InterfaceID = mDNSInterface_Unicast;
3406 question->ExpectUnique = mDNStrue;
3407 question->qnameOrig = orig;
3408
3409 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
3410
3411 // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
3412 // Hence, we need to set it explicitly here.
3413 question->QuestionContext = req;
3414 err = mDNS_StartQuery(m, question);
3415 if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3416
3417 // If we got a positive response to local SOA, then try the .local question as unicast
3418 if (answer->RecordType != kDNSRecordTypePacketNegative) return;
3419
3420 // Fall through and get the next search domain. The question is pointing at .local
3421 // and we don't want to try that. Try the next search domain. Don't try with local
3422 // search domains for the unicast question anymore.
3423 //
3424 // Note: we started the question above which will be stopped immediately (never sent on the wire)
3425 // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
3426 // question has already started.
3427 question->AppendLocalSearchDomains = 0;
3428 }
3429
3430 if (q && AddRecord && AddRecord != QC_dnssec && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
3431 {
3432 // If we get a negative response to the unicast query that we sent above, retry after appending search domains
3433 // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
3434 // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
3435 // To keep things simple, we handle unicast ".local" separately here.
3436 LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3437 if (RetryQuestionWithSearchDomains(question, req, AddRecord))
3438 return;
3439 if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
3440 {
3441 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
3442 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
3443 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
3444 // in the list. We leave it disabled so that it does not hit the wire.
3445 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3446 question->ThisQInterval = 0;
3447 }
3448 }
3449 // 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
3450 // domains to append for "q2". In all cases, fall through and deliver the response
3451 }
3452 #endif // APPLE_OSX_mDNSResponder
3453
3454 // If a query is being suppressed for some reason, we don't have to do any other
3455 // processing.
3456 //
3457 // Note: We don't check for "SuppressQuery" and instead use QC_suppressed because
3458 // the "core" needs to temporarily turn off SuppressQuery to answer this query.
3459 if (AddRecord == QC_suppressed)
3460 {
3461 LogDebug("queryrecord_result_callback: Suppressed question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3462 queryrecord_result_reply(m, req, question, answer, AddRecord, kDNSServiceErr_NoSuchRecord);
3463 return;
3464 }
3465
3466 if (answer->RecordType == kDNSRecordTypePacketNegative)
3467 {
3468 // If this question needs to be timed out and we have reached the stop time, mark
3469 // the error as timeout. It is possible that we might get a negative response from an
3470 // external DNS server at the same time when this question reaches its stop time. We
3471 // can't tell the difference as there is no indication in the callback. This should
3472 // be okay as we will be timing out this query anyway.
3473 mDNS_Lock(m);
3474 if (question->TimeoutQuestion)
3475 {
3476 if ((m->timenow - question->StopTime) >= 0)
3477 {
3478 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3479 error = kDNSServiceErr_Timeout;
3480 }
3481 }
3482 mDNS_Unlock(m);
3483 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
3484 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
3485 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
3486 // server is going to assert that pretty much every single multicast name doesn't exist.
3487 //
3488 // If we are timing out this query, we need to deliver the negative answer to the application
3489 if (error != kDNSServiceErr_Timeout)
3490 {
3491 if (!answer->InterfaceID && IsLocalDomain(answer->name))
3492 {
3493 // Sanity check: "q" will be set only if "question" is the .local unicast query.
3494 if (!q)
3495 {
3496 LogMsg("queryrecord_result_callback: ERROR!! answering multicast question %s with unicast cache record",
3497 RRDisplayString(m, answer));
3498 return;
3499 }
3500 #if APPLE_OSX_mDNSResponder
3501 if (!ShouldDeliverNegativeResponse(question))
3502 {
3503 return;
3504 }
3505 #endif // APPLE_OSX_mDNSResponder
3506 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with negative unicast response", question->qname.c,
3507 DNSTypeName(question->qtype));
3508 }
3509 error = kDNSServiceErr_NoSuchRecord;
3510 }
3511 }
3512 // If we get a negative answer, try appending search domains. Don't append search domains
3513 // - if we are timing out this question
3514 // - if the negative response was received as a result of a multicast query
3515 // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
3516 // - if this response is forced e.g., dnssec validation result
3517 if (error != kDNSServiceErr_Timeout)
3518 {
3519 if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord && AddRecord != QC_dnssec)
3520 {
3521 // If the original question did not end in .local, we did not send an SOA query
3522 // to figure out whether we should send an additional unicast query or not. If we just
3523 // appended .local, we need to see if we need to send an additional query. This should
3524 // normally happen just once because after we append .local, we ignore all negative
3525 // responses for .local above.
3526 LogDebug("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3527 if (RetryQuestionWithSearchDomains(question, req, AddRecord))
3528 {
3529 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
3530 // be anywhere in the search domain list.
3531 #if APPLE_OSX_mDNSResponder
3532 mStatus err = mStatus_NoError;
3533 err = SendAdditionalQuery(question, req, err);
3534 if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
3535 #endif // APPLE_OSX_mDNSResponder
3536 return;
3537 }
3538 }
3539 }
3540 queryrecord_result_reply(m, req, question, answer, AddRecord, error);
3541 }
3542
3543 mDNSlocal void queryrecord_termination_callback(request_state *request)
3544 {
3545 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) STOP PID[%d](%s)",
3546 request->sd, request->flags, request->interfaceIndex, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype), request->process_id, request->pid_name);
3547 if (request->u.queryrecord.q.QuestionContext)
3548 {
3549 mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q); // no need to error check
3550 LogMcastQ(&request->u.queryrecord.q, request, q_stop);
3551 request->u.queryrecord.q.QuestionContext = mDNSNULL;
3552 }
3553 else
3554 {
3555 DNSQuestion *question = &request->u.queryrecord.q;
3556 LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3557 }
3558
3559 if (request->u.queryrecord.q.qnameOrig)
3560 {
3561 freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
3562 request->u.queryrecord.q.qnameOrig = mDNSNULL;
3563 }
3564
3565 if (callExternalHelpers(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->u.queryrecord.q.flags))
3566 {
3567 LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
3568 external_stop_browsing_for_service(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->u.queryrecord.q.qtype, request->u.queryrecord.q.flags);
3569 }
3570 if (request->u.queryrecord.q2)
3571 {
3572 if (request->u.queryrecord.q2->QuestionContext)
3573 {
3574 LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
3575 mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
3576 LogMcastQ(request->u.queryrecord.q2, request, q_stop);
3577 }
3578 else
3579 {
3580 DNSQuestion *question = request->u.queryrecord.q2;
3581 LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3582 }
3583 if (request->u.queryrecord.q2->qnameOrig)
3584 {
3585 LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
3586 freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
3587 request->u.queryrecord.q2->qnameOrig = mDNSNULL;
3588 }
3589 freeL("queryrecord Q2", request->u.queryrecord.q2);
3590 request->u.queryrecord.q2 = mDNSNULL;
3591 }
3592 #if APPLE_OSX_mDNSResponder
3593 {
3594 if (request->u.queryrecord.ans)
3595 {
3596 DNSQuestion *v4q, *v6q;
3597 // If we are receiving poisitive answers, provide the hint to the
3598 // upper layer.
3599 v4q = v6q = mDNSNULL;
3600 if (request->u.queryrecord.q.qtype == kDNSType_A)
3601 v4q = &request->u.queryrecord.q;
3602 else if (request->u.queryrecord.q.qtype == kDNSType_AAAA)
3603 v6q = &request->u.queryrecord.q;
3604 mDNSPlatformTriggerDNSRetry(v4q, v6q);
3605 }
3606 }
3607 #endif // APPLE_OSX_mDNSResponder
3608 }
3609
3610 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
3611 {
3612 DNSQuestion *const q = &request->u.queryrecord.q;
3613 char name[256];
3614 size_t nameLen;
3615 mDNSu16 rrtype, rrclass;
3616 mStatus err;
3617
3618 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3619 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3620 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3621
3622 // The request is scoped to a specific interface index, but the
3623 // interface is not currently in our list.
3624 if (interfaceIndex && !InterfaceID)
3625 {
3626 if (interfaceIndex > 1)
3627 LogMsg("handle_queryrecord_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
3628 interfaceIndex, request->process_id, request->pid_name);
3629 // If it's one of the specially defined inteface index values, just return an error.
3630 // Also, caller should return an error immediately if lo0 (index 1) is not configured
3631 // into the current active interfaces. See background in Radar 21967160.
3632 if (PreDefinedInterfaceIndex(interfaceIndex) || interfaceIndex == 1)
3633 {
3634 LogInfo("handle_queryrecord_request: bad interfaceIndex %d", interfaceIndex);
3635 return(mStatus_BadParamErr);
3636 }
3637
3638 // Otherwise, use the specified interface index value and the request will
3639 // be applied to that interface when it comes up.
3640 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
3641 LogInfo("handle_queryrecord_request: query pending for interface index %d", interfaceIndex);
3642 }
3643
3644 if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
3645 rrtype = get_uint16(&request->msgptr, request->msgend);
3646 rrclass = get_uint16(&request->msgptr, request->msgend);
3647
3648 if (!request->msgptr)
3649 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3650
3651 request->flags = flags;
3652 request->interfaceIndex = interfaceIndex;
3653 mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
3654
3655 q->InterfaceID = InterfaceID;
3656 q->flags = flags;
3657 q->Target = zeroAddr;
3658 if (!MakeDomainNameFromDNSNameString(&q->qname, name)) return(mStatus_BadParamErr);
3659 #if 0
3660 if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains)) return (mStatus_NoError);
3661 #endif
3662 q->qtype = rrtype;
3663 q->qclass = rrclass;
3664 q->LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
3665 q->ExpectUnique = mDNSfalse;
3666 q->ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
3667 q->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3668 q->SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
3669 q->TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
3670 q->allowExpired = (EnableAllowExpired && (flags & kDNSServiceFlagsAllowExpiredAnswers) != 0) ? AllowExpired_AllowExpiredAnswers : AllowExpired_None;
3671 q->WakeOnResolve = 0;
3672 q->UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
3673 if ((flags & kDNSServiceFlagsValidate) != 0)
3674 q->ValidationRequired = DNSSEC_VALIDATION_SECURE;
3675 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
3676 q->ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
3677 q->ValidatingResponse = 0;
3678 q->ProxyQuestion = 0;
3679 q->AnonInfo = mDNSNULL;
3680 q->QuestionCallback = queryrecord_result_callback;
3681 q->QuestionContext = request;
3682 q->SearchListIndex = 0;
3683 q->StopTime = 0;
3684
3685 q->DNSSECAuthInfo = mDNSNULL;
3686 q->DAIFreeCallback = mDNSNULL;
3687
3688 //Turn off dnssec validation for local domains and Question Types: RRSIG/ANY(ANY Type is not supported yet)
3689 if ((IsLocalDomain(&q->qname)) || (q->qtype == kDNSServiceType_RRSIG) || (q->qtype == kDNSServiceType_ANY))
3690 q->ValidationRequired = 0;
3691
3692 // Don't append search domains for fully qualified domain names including queries
3693 // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3694 // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3695 // append search domains or not. So, we record that information in AppendSearchDomains.
3696 //
3697 // We append search domains only for queries that are a single label. If overriden using command line
3698 // argument "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
3699 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
3700
3701 nameLen = strlen(name);
3702 if ((!(q->ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(q->ValidationRequired == DNSSEC_VALIDATION_INSECURE))
3703 && (rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && ((nameLen == 0) || (name[nameLen - 1] != '.')) &&
3704 (AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3705 {
3706 q->AppendSearchDomains = 1;
3707 q->AppendLocalSearchDomains = 1;
3708 }
3709 else
3710 {
3711 q->AppendSearchDomains = 0;
3712 q->AppendLocalSearchDomains = 0;
3713 }
3714
3715 // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3716 // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3717 // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3718 // the cache
3719 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3720 q->qnameOrig = mDNSNULL;
3721 SetQuestionPolicy(q, request);
3722
3723 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3724 // Determine if this request should be promoted to use BLE triggered discovery.
3725 if (shouldUseBLE(InterfaceID, rrtype, (domainname *)SkipLeadingLabels(&q->qname, 1), &q->qname))
3726 {
3727 q->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
3728 request->flags |= (kDNSServiceFlagsAutoTrigger | kDNSServiceFlagsIncludeAWDL);
3729 LogInfo("handle_queryrecord_request: request promoted to use kDNSServiceFlagsAutoTrigger");
3730 }
3731 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
3732
3733 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START PID[%d](%s)",
3734 request->sd, request->flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype), request->process_id, request->pid_name);
3735 err = mDNS_StartQuery(&mDNSStorage, q);
3736
3737 if (err)
3738 {
3739 LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3740 }
3741 else
3742 {
3743 request->terminate = queryrecord_termination_callback;
3744 LogMcastQ(q, request, q_start);
3745 if (callExternalHelpers(q->InterfaceID, &q->qname, q->flags))
3746 {
3747 LogDebug("handle_queryrecord_request: calling external_start_browsing_for_service()");
3748 external_start_browsing_for_service(q->InterfaceID, &q->qname, q->qtype, q->flags);
3749 }
3750 }
3751
3752 #if APPLE_OSX_mDNSResponder
3753 err = SendAdditionalQuery(q, request, err);
3754 #endif // APPLE_OSX_mDNSResponder
3755
3756 return(err);
3757 }
3758
3759 // ***************************************************************************
3760 #if COMPILER_LIKES_PRAGMA_MARK
3761 #pragma mark -
3762 #pragma mark - DNSServiceEnumerateDomains
3763 #endif
3764
3765 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3766 const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3767 {
3768 size_t len;
3769 reply_state *reply;
3770 char *data;
3771
3772 len = sizeof(DNSServiceFlags);
3773 len += sizeof(mDNSu32);
3774 len += sizeof(DNSServiceErrorType);
3775 len += strlen(domain) + 1;
3776
3777 reply = create_reply(enumeration_reply_op, len, request);
3778 reply->rhdr->flags = dnssd_htonl(flags);
3779 reply->rhdr->ifi = dnssd_htonl(ifi);
3780 reply->rhdr->error = dnssd_htonl(err);
3781 data = (char *)&reply->rhdr[1];
3782 put_string(domain, &data);
3783 return reply;
3784 }
3785
3786 mDNSlocal void enum_termination_callback(request_state *request)
3787 {
3788 // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3789 if (request->u.enumeration.flags & kDNSServiceFlagsRegistrationDomains)
3790 {
3791 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3792 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3793 }
3794 else
3795 {
3796 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3797 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
3798 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_autoall);
3799 }
3800 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3801 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3802 }
3803
3804 mDNSlocal void enum_result_callback(mDNS *const m,
3805 DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3806 {
3807 char domain[MAX_ESCAPED_DOMAIN_NAME];
3808 request_state *request = question->QuestionContext;
3809 DNSServiceFlags flags = 0;
3810 reply_state *reply;
3811 (void)m; // Unused
3812
3813 if (answer->rrtype != kDNSType_PTR) return;
3814
3815 #if 0
3816 if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3817 #endif
3818
3819 // We only return add/remove events for the browse and registration lists
3820 // For the default browse and registration answers, we only give an "ADD" event
3821 if (question == &request->u.enumeration.q_default && !AddRecord) return;
3822
3823 if (AddRecord)
3824 {
3825 flags |= kDNSServiceFlagsAdd;
3826 if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3827 }
3828
3829 ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3830 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3831 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3832 // network, so we just pass kDNSServiceInterfaceIndexAny
3833 reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3834 if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3835
3836 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "ADD" : "RMV", domain);
3837
3838 append_reply(request, reply);
3839 }
3840
3841 mDNSlocal mStatus handle_enum_request(request_state *request)
3842 {
3843 mStatus err;
3844 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3845 DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3846 mDNS_DomainType t_all = reg ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse;
3847 mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3848 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3849 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3850 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3851
3852 if (!request->msgptr)
3853 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3854
3855 request->flags = flags;
3856 request->interfaceIndex = interfaceIndex;
3857
3858 // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
3859 request->u.enumeration.flags = reg;
3860
3861 // enumeration requires multiple questions, so we must link all the context pointers so that
3862 // necessary context can be reached from the callbacks
3863 request->u.enumeration.q_all.QuestionContext = request;
3864 request->u.enumeration.q_default.QuestionContext = request;
3865 if (!reg) request->u.enumeration.q_autoall.QuestionContext = request;
3866
3867 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3868 if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
3869
3870 // make the calls
3871 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
3872 (flags & kDNSServiceFlagsBrowseDomains ) ? "kDNSServiceFlagsBrowseDomains" :
3873 (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3874 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
3875 if (!err)
3876 {
3877 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
3878 if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3879 else if (!reg)
3880 {
3881 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_autoall, mDNS_DomainTypeBrowseAutomatic, NULL, InterfaceID, enum_result_callback, request);
3882 if (err)
3883 {
3884 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3885 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3886 }
3887 }
3888 if (!err) request->terminate = enum_termination_callback;
3889 }
3890 if (!err)
3891 {
3892 // Start the domain enumeration queries to discover the WAB Browse/Registration domains
3893 if (reg)
3894 {
3895 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3896 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3897 }
3898 else
3899 {
3900 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3901 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
3902 }
3903 }
3904
3905 return(err);
3906 }
3907
3908 // ***************************************************************************
3909 #if COMPILER_LIKES_PRAGMA_MARK
3910 #pragma mark -
3911 #pragma mark - DNSServiceReconfirmRecord & Misc
3912 #endif
3913
3914 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
3915 {
3916 mStatus status = mStatus_BadParamErr;
3917 AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
3918 if (rr)
3919 {
3920 status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
3921 LogOperation(
3922 (status == mStatus_NoError) ?
3923 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated PID[%d](%s)" :
3924 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed PID[%d](%s) status %d",
3925 request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
3926 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse),
3927 request->process_id, request->pid_name, status);
3928 freeL("AuthRecord/handle_reconfirm_request", rr);
3929 }
3930 return(status);
3931 }
3932
3933 #if APPLE_OSX_mDNSResponder
3934
3935 mDNSlocal mStatus handle_release_request(request_state *request)
3936 {
3937 mStatus err = 0;
3938 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
3939 domainname instance;
3940
3941 // extract the data from the message
3942 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3943
3944 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
3945 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3946 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
3947 {
3948 LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
3949 return(mStatus_BadParamErr);
3950 }
3951
3952 if (!request->msgptr)
3953 {
3954 LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request->sd);
3955 return(mStatus_BadParamErr);
3956 }
3957
3958 if (build_domainname_from_strings(&instance, name, regtype, domain) < 0)
3959 {
3960 LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name, regtype, domain);
3961 return(mStatus_BadParamErr);
3962 }
3963
3964 LogOperation("%3d: PeerConnectionRelease(%X %##s) START PID[%d](%s)",
3965 request->sd, flags, instance.c, request->process_id, request->pid_name);
3966
3967 external_connection_release(&instance);
3968 return(err);
3969 }
3970
3971 #else // APPLE_OSX_mDNSResponder
3972
3973 mDNSlocal mStatus handle_release_request(request_state *request)
3974 {
3975 (void) request;
3976 return mStatus_UnsupportedErr;
3977 }
3978
3979 #endif // APPLE_OSX_mDNSResponder
3980
3981 mDNSlocal mStatus handle_setdomain_request(request_state *request)
3982 {
3983 char domainstr[MAX_ESCAPED_DOMAIN_NAME];
3984 domainname domain;
3985 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3986 (void)flags; // Unused
3987 if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3988 !MakeDomainNameFromDNSNameString(&domain, domainstr))
3989 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3990
3991 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
3992 return(mStatus_NoError);
3993 }
3994
3995 typedef packedstruct
3996 {
3997 mStatus err;
3998 mDNSu32 len;
3999 mDNSu32 vers;
4000 } DaemonVersionReply;
4001
4002 mDNSlocal void handle_getproperty_request(request_state *request)
4003 {
4004 const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
4005 char prop[256];
4006 if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
4007 {
4008 LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
4009 if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
4010 {
4011 DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
4012 send_all(request->sd, (const char *)&x, sizeof(x));
4013 return;
4014 }
4015 }
4016
4017 // If we didn't recogize the requested property name, return BadParamErr
4018 send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
4019 }
4020
4021 #ifdef APPLE_OSX_mDNSResponder
4022 // The caller can specify either the pid or the uuid. If the pid is not specified,
4023 // update the effective uuid. Don't overwrite the pid which is used for debugging
4024 // purposes and initialized when the socket is opened.
4025 mDNSlocal void handle_connection_delegate_request(request_state *request)
4026 {
4027 mDNSs32 pid;
4028 socklen_t len;
4029
4030 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4031 request->sd, request->process_id, request->pid_name);
4032 request->terminate = connection_termination;
4033
4034 len = 0;
4035 pid = get_uint32(&request->msgptr, request->msgend);
4036 #ifdef LOCAL_PEEREPID
4037 if (pid)
4038 {
4039 len = sizeof(pid);
4040 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &request->process_id, &len) != 0)
4041 {
4042 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno, strerror(errno));
4043 return;
4044 }
4045 // to extract the process name from the pid value
4046 if (proc_pidinfo(request->process_id, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
4047 return;
4048 mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
4049 debugf("handle_connection_delegate_request: process id %d, name %s", request->process_id, request->pid_name);
4050 }
4051 #endif
4052 #ifdef LOCAL_PEEREUUID
4053 if (!pid)
4054 {
4055 len = UUID_SIZE;
4056 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREUUID, request->uuid, &len) != 0)
4057 {
4058 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno, strerror(errno));
4059 return;
4060 }
4061 request->validUUID = mDNStrue;
4062 }
4063 #endif
4064 }
4065 #else
4066 mDNSlocal void handle_connection_delegate_request(request_state *request)
4067 {
4068 (void) request;
4069 }
4070 #endif
4071
4072 typedef packedstruct
4073 {
4074 mStatus err;
4075 mDNSs32 pid;
4076 } PIDInfo;
4077
4078 mDNSlocal void handle_getpid_request(request_state *request)
4079 {
4080 const request_state *req;
4081 mDNSs32 pid = -1;
4082 mDNSu16 srcport = get_uint16(&request->msgptr, request->msgend);
4083 const DNSQuestion *q = NULL;
4084 PIDInfo pi;
4085
4086 LogMsg("%3d: DNSServiceGetPID START", request->sd);
4087
4088 for (req = all_requests; req; req=req->next)
4089 {
4090 if (req->hdr.op == query_request)
4091 q = &req->u.queryrecord.q;
4092 else if (req->hdr.op == addrinfo_request)
4093 q = &req->u.addrinfo.q4;
4094 else if (req->hdr.op == addrinfo_request)
4095 q = &req->u.addrinfo.q6;
4096
4097 if (q && q->LocalSocket != NULL)
4098 {
4099 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4100 if (port == srcport)
4101 {
4102 pid = req->process_id;
4103 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s] question %##s", htons(srcport), pid, req->pid_name, q->qname.c);
4104 break;
4105 }
4106 }
4107 }
4108 // If we cannot find in the client requests, look to see if this was
4109 // started by mDNSResponder.
4110 if (pid == -1)
4111 {
4112 for (q = mDNSStorage.Questions; q; q = q->next)
4113 {
4114 if (q && q->LocalSocket != NULL)
4115 {
4116 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4117 if (port == srcport)
4118 {
4119 #if APPLE_OSX_mDNSResponder
4120 pid = getpid();
4121 #endif // APPLE_OSX_mDNSResponder
4122 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s], question %##s", htons(srcport), pid, "_mDNSResponder", q->qname.c);
4123 break;
4124 }
4125 }
4126 }
4127 }
4128
4129 pi.err = 0;
4130 pi.pid = pid;
4131 send_all(request->sd, (const char *)&pi, sizeof(PIDInfo));
4132 LogMsg("%3d: DNSServiceGetPID STOP", request->sd);
4133 }
4134
4135 // ***************************************************************************
4136 #if COMPILER_LIKES_PRAGMA_MARK
4137 #pragma mark -
4138 #pragma mark - DNSServiceNATPortMappingCreate
4139 #endif
4140
4141 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
4142
4143 mDNSlocal void port_mapping_termination_callback(request_state *request)
4144 {
4145 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](%s)", request->sd,
4146 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4147 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4148 request->process_id, request->pid_name);
4149 mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4150 }
4151
4152 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
4153 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
4154 {
4155 request_state *request = (request_state *)n->clientContext;
4156 reply_state *rep;
4157 int replyLen;
4158 char *data;
4159
4160 if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
4161
4162 // calculate reply data length
4163 replyLen = sizeof(DNSServiceFlags);
4164 replyLen += 3 * sizeof(mDNSu32); // if index + addr + ttl
4165 replyLen += sizeof(DNSServiceErrorType);
4166 replyLen += 2 * sizeof(mDNSu16); // Internal Port + External Port
4167 replyLen += sizeof(mDNSu8); // protocol
4168
4169 rep = create_reply(port_mapping_reply_op, replyLen, request);
4170
4171 rep->rhdr->flags = dnssd_htonl(0);
4172 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
4173 rep->rhdr->error = dnssd_htonl(n->Result);
4174
4175 data = (char *)&rep->rhdr[1];
4176
4177 *data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
4178 *data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
4179 *data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
4180 *data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
4181 *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
4182 *data++ = request->u.pm.NATinfo.IntPort.b[0];
4183 *data++ = request->u.pm.NATinfo.IntPort.b[1];
4184 *data++ = request->u.pm.NATinfo.ExternalPort.b[0];
4185 *data++ = request->u.pm.NATinfo.ExternalPort.b[1];
4186 put_uint32(request->u.pm.NATinfo.Lifetime, &data);
4187
4188 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
4189 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4190 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4191 &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
4192
4193 append_reply(request, rep);
4194 }
4195
4196 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
4197 {
4198 mDNSu32 ttl = 0;
4199 mStatus err = mStatus_NoError;
4200
4201 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4202 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4203 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4204 mDNSu8 protocol = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
4205 (void)flags; // Unused
4206 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
4207 if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
4208 else
4209 {
4210 request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
4211 request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
4212 request->u.pm.ReqExt.b[0] = *request->msgptr++;
4213 request->u.pm.ReqExt.b[1] = *request->msgptr++;
4214 ttl = get_uint32(&request->msgptr, request->msgend);
4215 }
4216
4217 if (!request->msgptr)
4218 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4219
4220 if (protocol == 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
4221 {
4222 if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
4223 }
4224 else
4225 {
4226 if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
4227 if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
4228 }
4229
4230 request->flags = flags;
4231 request->interfaceIndex = interfaceIndex;
4232 request->u.pm.NATinfo.Protocol = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
4233 // u.pm.NATinfo.IntPort = already set above
4234 request->u.pm.NATinfo.RequestedPort = request->u.pm.ReqExt;
4235 request->u.pm.NATinfo.NATLease = ttl;
4236 request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
4237 request->u.pm.NATinfo.clientContext = request;
4238
4239 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](%s)", request->sd,
4240 protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4241 request->process_id, request->pid_name);
4242 err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4243 if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
4244 else request->terminate = port_mapping_termination_callback;
4245
4246 return(err);
4247 }
4248
4249 // ***************************************************************************
4250 #if COMPILER_LIKES_PRAGMA_MARK
4251 #pragma mark -
4252 #pragma mark - DNSServiceGetAddrInfo
4253 #endif
4254
4255 mDNSlocal void addrinfo_termination_callback(request_state *request)
4256 {
4257 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP PID[%d](%s)", request->sd, request->u.addrinfo.q4.qname.c,
4258 request->process_id, request->pid_name);
4259
4260 if (request->u.addrinfo.q4.QuestionContext)
4261 {
4262 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
4263 LogMcastQ(&request->u.addrinfo.q4, request, q_stop);
4264 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4265
4266 if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, request->flags))
4267 {
4268 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for A record");
4269 external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, kDNSServiceType_A, request->flags);
4270 }
4271 }
4272 if (request->u.addrinfo.q4.qnameOrig)
4273 {
4274 freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
4275 request->u.addrinfo.q4.qnameOrig = mDNSNULL;
4276 }
4277 if (request->u.addrinfo.q42)
4278 {
4279 if (request->u.addrinfo.q42->QuestionContext)
4280 {
4281 LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
4282 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
4283 LogMcastQ(request->u.addrinfo.q42, request, q_stop);
4284 }
4285 if (request->u.addrinfo.q42->qnameOrig)
4286 {
4287 LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
4288 freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
4289 request->u.addrinfo.q42->qnameOrig = mDNSNULL;
4290 }
4291 freeL("addrinfo Q42", request->u.addrinfo.q42);
4292 request->u.addrinfo.q42 = mDNSNULL;
4293 }
4294
4295 if (request->u.addrinfo.q6.QuestionContext)
4296 {
4297 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4298 LogMcastQ(&request->u.addrinfo.q6, request, q_stop);
4299 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4300
4301 if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, request->flags))
4302 {
4303 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for AAAA record");
4304 external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, kDNSServiceType_AAAA, request->flags);
4305 }
4306 }
4307 if (request->u.addrinfo.q6.qnameOrig)
4308 {
4309 freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
4310 request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4311 }
4312 if (request->u.addrinfo.q62)
4313 {
4314 if (request->u.addrinfo.q62->QuestionContext)
4315 {
4316 LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
4317 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
4318 LogMcastQ(request->u.addrinfo.q62, request, q_stop);
4319 }
4320 if (request->u.addrinfo.q62->qnameOrig)
4321 {
4322 LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
4323 freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
4324 request->u.addrinfo.q62->qnameOrig = mDNSNULL;
4325 }
4326 freeL("addrinfo Q62", request->u.addrinfo.q62);
4327 request->u.addrinfo.q62 = mDNSNULL;
4328 }
4329 #if APPLE_OSX_mDNSResponder
4330 {
4331 DNSQuestion *v4q, *v6q;
4332 v4q = v6q = mDNSNULL;
4333 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
4334 {
4335 // If we are not delivering answers, we may be timing out prematurely.
4336 // Note down the current state so that we know to retry when we see a
4337 // valid response again.
4338 if (request->u.addrinfo.q4.TimeoutQuestion && !request->u.addrinfo.v4ans)
4339 {
4340 mDNSPlatformUpdateDNSStatus(&request->u.addrinfo.q4);
4341 }
4342 // If we have a v4 answer and if we timed out prematurely before, provide
4343 // a trigger to the upper layer so that it can retry questions if needed.
4344 if (request->u.addrinfo.v4ans)
4345 v4q = &request->u.addrinfo.q4;
4346 }
4347 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4348 {
4349 if (request->u.addrinfo.q6.TimeoutQuestion && !request->u.addrinfo.v6ans)
4350 {
4351 mDNSPlatformUpdateDNSStatus(&request->u.addrinfo.q6);
4352 }
4353 if (request->u.addrinfo.v6ans)
4354 v6q = &request->u.addrinfo.q6;
4355 }
4356 mDNSPlatformTriggerDNSRetry(v4q, v6q);
4357 }
4358 #endif // APPLE_OSX_mDNSResponder
4359 }
4360
4361 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
4362 {
4363 char hostname[256];
4364 size_t hostnameLen;
4365 domainname d;
4366 mStatus err = 0;
4367 mDNSs32 serviceIndex = -1; // default unscoped value for ServiceID is -1
4368 mDNSInterfaceID InterfaceID;
4369
4370 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4371
4372 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4373
4374 if (flags & kDNSServiceFlagsServiceIndex)
4375 {
4376 // NOTE: kDNSServiceFlagsServiceIndex flag can only be set for DNSServiceGetAddrInfo()
4377 LogInfo("DNSServiceGetAddrInfo: kDNSServiceFlagsServiceIndex is SET by the client");
4378 // if kDNSServiceFlagsServiceIndex is SET,
4379 // interpret the interfaceID as the serviceId and set the interfaceID to 0.
4380 serviceIndex = interfaceIndex;
4381 interfaceIndex = 0;
4382 }
4383
4384 mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
4385
4386 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4387
4388 // The request is scoped to a specific interface index, but the
4389 // interface is not currently in our list.
4390 if (interfaceIndex && !InterfaceID)
4391 {
4392 if (interfaceIndex > 1)
4393 LogMsg("handle_addrinfo_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
4394 interfaceIndex, request->process_id, request->pid_name);
4395 // If it's one of the specially defined inteface index values, just return an error.
4396 if (PreDefinedInterfaceIndex(interfaceIndex))
4397 {
4398 LogInfo("handle_addrinfo_request: bad interfaceIndex %d", interfaceIndex);
4399 return(mStatus_BadParamErr);
4400 }
4401
4402 // Otherwise, use the specified interface index value and the request will
4403 // be applied to that interface when it comes up.
4404 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
4405 LogInfo("handle_addrinfo_request: query pending for interface index %d", interfaceIndex);
4406 }
4407
4408 request->flags = flags;
4409 request->interfaceIndex = interfaceIndex;
4410 request->u.addrinfo.interface_id = InterfaceID;
4411 request->u.addrinfo.flags = flags;
4412 request->u.addrinfo.protocol = get_uint32(&request->msgptr, request->msgend);
4413
4414 if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
4415
4416 if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
4417
4418 if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4419
4420 if (!MakeDomainNameFromDNSNameString(&d, hostname))
4421 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
4422
4423 #if 0
4424 if (!AuthorizedDomain(request, &d, AutoBrowseDomains)) return (mStatus_NoError);
4425 #endif
4426
4427 if (!request->u.addrinfo.protocol)
4428 {
4429 flags |= kDNSServiceFlagsSuppressUnusable;
4430 request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
4431 }
4432
4433 request->u.addrinfo.q4.InterfaceID = request->u.addrinfo.q6.InterfaceID = request->u.addrinfo.interface_id;
4434 request->u.addrinfo.q4.ServiceID = request->u.addrinfo.q6.ServiceID = serviceIndex;
4435 request->u.addrinfo.q4.flags = request->u.addrinfo.q6.flags = flags;
4436 request->u.addrinfo.q4.Target = request->u.addrinfo.q6.Target = zeroAddr;
4437 request->u.addrinfo.q4.qname = request->u.addrinfo.q6.qname = d;
4438 request->u.addrinfo.q4.qclass = request->u.addrinfo.q6.qclass = kDNSServiceClass_IN;
4439 request->u.addrinfo.q4.LongLived = request->u.addrinfo.q6.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
4440 request->u.addrinfo.q4.ExpectUnique = request->u.addrinfo.q6.ExpectUnique = mDNSfalse;
4441 request->u.addrinfo.q4.ForceMCast = request->u.addrinfo.q6.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
4442 request->u.addrinfo.q4.ReturnIntermed = request->u.addrinfo.q6.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
4443 request->u.addrinfo.q4.SuppressUnusable = request->u.addrinfo.q6.SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
4444 request->u.addrinfo.q4.TimeoutQuestion = request->u.addrinfo.q6.TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
4445 request->u.addrinfo.q4.allowExpired = request->u.addrinfo.q6.allowExpired = (EnableAllowExpired && (flags & kDNSServiceFlagsAllowExpiredAnswers) != 0) ? AllowExpired_AllowExpiredAnswers : AllowExpired_None;
4446 request->u.addrinfo.q4.WakeOnResolve = request->u.addrinfo.q6.WakeOnResolve = 0;
4447 request->u.addrinfo.q4.UseBackgroundTrafficClass = request->u.addrinfo.q6.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
4448 if ((flags & kDNSServiceFlagsValidate) != 0)
4449 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE;
4450 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
4451 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
4452 request->u.addrinfo.q4.ValidatingResponse = request->u.addrinfo.q6.ValidatingResponse = 0;
4453 request->u.addrinfo.q4.ProxyQuestion = request->u.addrinfo.q6.ProxyQuestion = 0;
4454 request->u.addrinfo.q4.qnameOrig = request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4455 request->u.addrinfo.q4.AnonInfo = request->u.addrinfo.q6.AnonInfo = mDNSNULL;
4456
4457 SetQuestionPolicy(&request->u.addrinfo.q4, request);
4458 SetQuestionPolicy(&request->u.addrinfo.q6, request);
4459
4460 request->u.addrinfo.q4.StopTime = request->u.addrinfo.q6.StopTime = 0;
4461
4462 request->u.addrinfo.q4.DNSSECAuthInfo = request->u.addrinfo.q6.DNSSECAuthInfo = mDNSNULL;
4463 request->u.addrinfo.q4.DAIFreeCallback = request->u.addrinfo.q6.DAIFreeCallback = mDNSNULL;
4464
4465 //Turn off dnssec validation for local domains
4466 if (IsLocalDomain(&d))
4467 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = 0;
4468
4469 hostnameLen = strlen(hostname);
4470
4471 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START PID[%d](%s)",
4472 request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c, request->process_id, request->pid_name);
4473
4474 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4475 {
4476 request->u.addrinfo.q6.qtype = kDNSServiceType_AAAA;
4477 request->u.addrinfo.q6.SearchListIndex = 0;
4478 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set
4479 if ((!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4480 && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4481 {
4482 request->u.addrinfo.q6.AppendSearchDomains = 1;
4483 request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
4484 }
4485 else
4486 {
4487 request->u.addrinfo.q6.AppendSearchDomains = 0;
4488 request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
4489 }
4490 request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
4491 request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
4492 request->u.addrinfo.q6.QuestionContext = request;
4493 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
4494 if (err != mStatus_NoError)
4495 {
4496 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4497 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4498 }
4499 #if APPLE_OSX_mDNSResponder
4500 err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
4501 #endif // APPLE_OSX_mDNSResponder
4502 if (!err)
4503 {
4504 request->terminate = addrinfo_termination_callback;
4505 LogMcastQ(&request->u.addrinfo.q6, request, q_start);
4506 if (callExternalHelpers(InterfaceID, &d, flags))
4507 {
4508 LogDebug("handle_addrinfo_request: calling external_start_browsing_for_service() for AAAA record");
4509 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags);
4510 }
4511 }
4512 }
4513
4514 if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4))
4515 {
4516 request->u.addrinfo.q4.qtype = kDNSServiceType_A;
4517 request->u.addrinfo.q4.SearchListIndex = 0;
4518
4519 // We append search domains only for queries that are a single label. If overriden using cmd line arg
4520 // "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
4521 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
4522
4523 if ((!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4524 && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4525 {
4526 request->u.addrinfo.q4.AppendSearchDomains = 1;
4527 request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
4528 }
4529 else
4530 {
4531 request->u.addrinfo.q4.AppendSearchDomains = 0;
4532 request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
4533 }
4534 request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
4535 request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
4536 request->u.addrinfo.q4.QuestionContext = request;
4537 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
4538 if (err != mStatus_NoError)
4539 {
4540 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4541 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4542 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4543 {
4544 // If we started a query for IPv6, we need to cancel it
4545 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4546 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4547
4548 if (callExternalHelpers(InterfaceID, &d, flags))
4549 {
4550 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for AAAA record");
4551 external_stop_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags);
4552 }
4553 }
4554 }
4555 #if APPLE_OSX_mDNSResponder
4556 err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
4557 #endif // APPLE_OSX_mDNSResponder
4558 if (!err)
4559 {
4560 request->terminate = addrinfo_termination_callback;
4561 LogMcastQ(&request->u.addrinfo.q4, request, q_start);
4562 if (callExternalHelpers(InterfaceID, &d, flags))
4563 {
4564 LogDebug("handle_addrinfo_request: calling external_start_browsing_for_service() for A record");
4565 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_A, flags);
4566 }
4567 }
4568 }
4569
4570 return(err);
4571 }
4572
4573 // ***************************************************************************
4574 #if COMPILER_LIKES_PRAGMA_MARK
4575 #pragma mark -
4576 #pragma mark - Main Request Handler etc.
4577 #endif
4578
4579 mDNSlocal request_state *NewRequest(void)
4580 {
4581 request_state **p = &all_requests;
4582 while (*p)
4583 p=&(*p)->next;
4584 *p = mallocL("request_state", sizeof(request_state));
4585 if (!*p)
4586 FatalError("ERROR: malloc");
4587 mDNSPlatformMemZero(*p, sizeof(request_state));
4588 return(*p);
4589 }
4590
4591 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
4592 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
4593 mDNSlocal void read_msg(request_state *req)
4594 {
4595 if (req->ts == t_terminated || req->ts == t_error)
4596 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
4597
4598 if (req->ts == t_complete) // this must be death or something is wrong
4599 {
4600 char buf[4]; // dummy for death notification
4601 int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
4602 if (!nread) { req->ts = t_terminated; return; }
4603 if (nread < 0) goto rerror;
4604 LogMsg("%3d: ERROR: read data from a completed request", req->sd);
4605 req->ts = t_error;
4606 return;
4607 }
4608
4609 if (req->ts != t_morecoming)
4610 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
4611
4612 if (req->hdr_bytes < sizeof(ipc_msg_hdr))
4613 {
4614 mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
4615 int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
4616 if (nread == 0) { req->ts = t_terminated; return; }
4617 if (nread < 0) goto rerror;
4618 req->hdr_bytes += nread;
4619 if (req->hdr_bytes > sizeof(ipc_msg_hdr))
4620 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
4621
4622 // only read data if header is complete
4623 if (req->hdr_bytes == sizeof(ipc_msg_hdr))
4624 {
4625 ConvertHeaderBytes(&req->hdr);
4626 if (req->hdr.version != VERSION)
4627 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
4628
4629 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
4630 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
4631 // for other overhead, this means any message above 70kB is definitely bogus.
4632 if (req->hdr.datalen > 70000)
4633 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
4634 req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
4635 if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
4636 req->msgptr = req->msgbuf;
4637 req->msgend = req->msgbuf + req->hdr.datalen;
4638 mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
4639 }
4640 }
4641
4642 // If our header is complete, but we're still needing more body data, then try to read it now
4643 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
4644 // Any time we need to get the error return socket we know we'll have at least one data byte
4645 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
4646 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
4647 {
4648 mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
4649 int nread;
4650 #if !defined(_WIN32)
4651 struct iovec vec = { req->msgbuf + req->data_bytes, nleft }; // Tell recvmsg where we want the bytes put
4652 struct msghdr msg;
4653 struct cmsghdr *cmsg;
4654 char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
4655 msg.msg_name = 0;
4656 msg.msg_namelen = 0;
4657 msg.msg_iov = &vec;
4658 msg.msg_iovlen = 1;
4659 msg.msg_control = cbuf;
4660 msg.msg_controllen = sizeof(cbuf);
4661 msg.msg_flags = 0;
4662 nread = recvmsg(req->sd, &msg, 0);
4663 #else
4664 nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
4665 #endif
4666 if (nread == 0) { req->ts = t_terminated; return; }
4667 if (nread < 0) goto rerror;
4668 req->data_bytes += nread;
4669 if (req->data_bytes > req->hdr.datalen)
4670 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
4671 #if !defined(_WIN32)
4672 cmsg = CMSG_FIRSTHDR(&msg);
4673 #if DEBUG_64BIT_SCM_RIGHTS
4674 LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf), sizeof(cbuf), SOL_SOCKET, SCM_RIGHTS);
4675 LogMsg("%3d: Got %d %d %d %d", req->sd, msg.msg_controllen, cmsg ? cmsg->cmsg_len : -1, cmsg ? cmsg->cmsg_level : -1, cmsg ? cmsg->cmsg_type : -1);
4676 #endif // DEBUG_64BIT_SCM_RIGHTS
4677 if (cmsg && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
4678 {
4679 #if APPLE_OSX_mDNSResponder
4680 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
4681 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
4682 // and it's convenient to repurpose the existing fd-passing code here for that task
4683 if (req->hdr.op == send_bpf)
4684 {
4685 dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4686 LogOperation("%3d: Got len %d, BPF %d", req->sd, cmsg->cmsg_len, x);
4687 mDNSPlatformReceiveBPF_fd(x);
4688 }
4689 else
4690 #endif // APPLE_OSX_mDNSResponder
4691 req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4692 #if DEBUG_64BIT_SCM_RIGHTS
4693 LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
4694 #endif // DEBUG_64BIT_SCM_RIGHTS
4695 if (req->data_bytes < req->hdr.datalen)
4696 {
4697 LogMsg("%3d: Client(PID [%d](%s)) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
4698 req->sd, req->process_id, req->pid_name, req->errsd, req->data_bytes, req->hdr.datalen);
4699 req->ts = t_error;
4700 return;
4701 }
4702 }
4703 #endif
4704 }
4705
4706 // If our header and data are both complete, see if we need to make our separate error return socket
4707 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
4708 {
4709 if (req->terminate && req->hdr.op != cancel_request)
4710 {
4711 dnssd_sockaddr_t cliaddr;
4712 #if defined(USE_TCP_LOOPBACK)
4713 mDNSOpaque16 port;
4714 u_long opt = 1;
4715 port.b[0] = req->msgptr[0];
4716 port.b[1] = req->msgptr[1];
4717 req->msgptr += 2;
4718 cliaddr.sin_family = AF_INET;
4719 cliaddr.sin_port = port.NotAnInteger;
4720 cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4721 #else
4722 char ctrl_path[MAX_CTLPATH];
4723 get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH); // path is first element in message buffer
4724 mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
4725 cliaddr.sun_family = AF_LOCAL;
4726 mDNSPlatformStrLCopy(cliaddr.sun_path, ctrl_path, sizeof(cliaddr.sun_path));
4727 // If the error return path UDS name is empty string, that tells us
4728 // that this is a new version of the library that's going to pass us
4729 // the error return path socket via sendmsg/recvmsg
4730 if (ctrl_path[0] == 0)
4731 {
4732 if (req->errsd == req->sd)
4733 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
4734 goto got_errfd;
4735 }
4736 #endif
4737
4738 req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
4739 if (!dnssd_SocketValid(req->errsd))
4740 {
4741 my_throttled_perror("ERROR: socket");
4742 req->ts = t_error;
4743 return;
4744 }
4745
4746 if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
4747 {
4748 #if !defined(USE_TCP_LOOPBACK)
4749 struct stat sb;
4750 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
4751 req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4752 if (stat(cliaddr.sun_path, &sb) < 0)
4753 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4754 else
4755 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);
4756 #endif
4757 req->ts = t_error;
4758 return;
4759 }
4760
4761 #if !defined(USE_TCP_LOOPBACK)
4762 got_errfd:
4763 #endif
4764 LogDebug("%3d: Result code socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
4765 #if defined(_WIN32)
4766 if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
4767 #else
4768 if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
4769 #endif
4770 {
4771 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
4772 req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4773 req->ts = t_error;
4774 return;
4775 }
4776 }
4777
4778 req->ts = t_complete;
4779 }
4780
4781 return;
4782
4783 rerror:
4784 if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
4785 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4786 req->ts = t_error;
4787 }
4788
4789 mDNSlocal mStatus handle_client_request(request_state *req)
4790 {
4791 mStatus err = mStatus_NoError;
4792 switch(req->hdr.op)
4793 {
4794 // These are all operations that have their own first-class request_state object
4795 case connection_request:
4796 LogOperation("%3d: DNSServiceCreateConnection START PID[%d](%s)",
4797 req->sd, req->process_id, req->pid_name);
4798 req->terminate = connection_termination;
4799 break;
4800 case connection_delegate_request:
4801 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
4802 req->sd, req->process_id, req->pid_name);
4803 req->terminate = connection_termination;
4804 handle_connection_delegate_request(req);
4805 break;
4806 case resolve_request: err = handle_resolve_request (req); break;
4807 case query_request: err = handle_queryrecord_request (req); break;
4808 case browse_request: err = handle_browse_request (req); break;
4809 case reg_service_request: err = handle_regservice_request (req); break;
4810 case enumeration_request: err = handle_enum_request (req); break;
4811 case reconfirm_record_request: err = handle_reconfirm_request (req); break;
4812 case setdomain_request: err = handle_setdomain_request (req); break;
4813 case getproperty_request: handle_getproperty_request (req); break;
4814 case getpid_request: handle_getpid_request (req); break;
4815 case port_mapping_request: err = handle_port_mapping_request(req); break;
4816 case addrinfo_request: err = handle_addrinfo_request (req); break;
4817 case send_bpf: /* Do nothing for send_bpf */ break;
4818
4819 // These are all operations that work with an existing request_state object
4820 case reg_record_request: err = handle_regrecord_request (req); break;
4821 case add_record_request: err = handle_add_request (req); break;
4822 case update_record_request: err = handle_update_request (req); break;
4823 case remove_record_request: err = handle_removerecord_request(req); break;
4824 case cancel_request: handle_cancel_request (req); break;
4825 case release_request: err = handle_release_request (req); break;
4826 default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
4827 req->sd, req->hdr.op, req->process_id, req->pid_name);
4828 err = mStatus_BadParamErr;
4829 break;
4830 }
4831
4832 return err;
4833 }
4834
4835 #define RecordOrientedOp(X) \
4836 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
4837
4838 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
4839 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
4840
4841 mDNSlocal void request_callback(int fd, short filter, void *info)
4842 {
4843 mStatus err = 0;
4844 request_state *req = info;
4845 mDNSs32 min_size = sizeof(DNSServiceFlags);
4846 (void)fd; // Unused
4847 (void)filter; // Unused
4848
4849 for (;;)
4850 {
4851 read_msg(req);
4852 if (req->ts == t_morecoming)
4853 return;
4854 if (req->ts == t_terminated || req->ts == t_error)
4855 {
4856 AbortUnlinkAndFree(req);
4857 return;
4858 }
4859 if (req->ts != t_complete)
4860 {
4861 LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req->ts, req->process_id, req->pid_name);
4862 AbortUnlinkAndFree(req);
4863 return;
4864 }
4865
4866 switch(req->hdr.op) // Interface + other data
4867 {
4868 case connection_request: min_size = 0; break;
4869 case connection_delegate_request: min_size = 4; /* pid */ break;
4870 case reg_service_request: min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
4871 case add_record_request: min_size += 4 /* type, rdlen */ + 4 /* ttl */; break;
4872 case update_record_request: min_size += 2 /* rdlen */ + 4 /* ttl */; break;
4873 case remove_record_request: break;
4874 case browse_request: min_size += sizeof(mDNSu32) + 2 /* type, domain */; break;
4875 case resolve_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4876 case query_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 4 /* type, class*/; break;
4877 case enumeration_request: min_size += sizeof(mDNSu32); break;
4878 case reg_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
4879 case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */; break;
4880 case setdomain_request: min_size += 1 /* domain */; break;
4881 case getproperty_request: min_size = 2; break;
4882 case getpid_request: min_size = 2; break;
4883 case port_mapping_request: min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
4884 case addrinfo_request: min_size += sizeof(mDNSu32) + 4 /* v4/v6 */ + 1 /* hostname */; break;
4885 case send_bpf: // Same as cancel_request below
4886 case cancel_request: min_size = 0; break;
4887 case release_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4888 default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
4889 req->hdr.op, req->process_id, req->pid_name);
4890 min_size = -1; break;
4891 }
4892
4893 if ((mDNSs32)req->data_bytes < min_size)
4894 {
4895 LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
4896 req->data_bytes, req->hdr.op, min_size, req->process_id, req->pid_name);
4897 AbortUnlinkAndFree(req);
4898 return;
4899 }
4900 if (LightweightOp(req->hdr.op) && !req->terminate)
4901 {
4902 LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
4903 req->hdr.op, req->process_id, req->pid_name);
4904 AbortUnlinkAndFree(req);
4905 return;
4906 }
4907
4908 // If req->terminate is already set, this means this operation is sharing an existing connection
4909 if (req->terminate && !LightweightOp(req->hdr.op))
4910 {
4911 request_state *newreq = NewRequest();
4912 newreq->primary = req;
4913 newreq->sd = req->sd;
4914 newreq->errsd = req->errsd;
4915 newreq->uid = req->uid;
4916 newreq->hdr = req->hdr;
4917 newreq->msgbuf = req->msgbuf;
4918 newreq->msgptr = req->msgptr;
4919 newreq->msgend = req->msgend;
4920 // if the parent request is a delegate connection, copy the
4921 // relevant bits
4922 if (req->validUUID)
4923 {
4924 newreq->validUUID = mDNStrue;
4925 mDNSPlatformMemCopy(newreq->uuid, req->uuid, UUID_SIZE);
4926 }
4927 else
4928 {
4929 if (req->process_id)
4930 {
4931 newreq->process_id = req->process_id;
4932 mDNSPlatformStrLCopy(newreq->pid_name, req->pid_name, (mDNSu32)sizeof(newreq->pid_name));
4933 }
4934 else
4935 {
4936 set_peer_pid(newreq);
4937 }
4938 }
4939 req = newreq;
4940 }
4941
4942 // Check if the request wants no asynchronous replies.
4943 if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
4944
4945 // If we're shutting down, don't allow new client requests
4946 // We do allow "cancel" and "getproperty" during shutdown
4947 if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
4948 err = mStatus_ServiceNotRunning;
4949 else
4950 err = handle_client_request(req);
4951
4952 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
4953 if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
4954
4955 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
4956 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
4957 if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf && req->hdr.op != getpid_request)
4958 {
4959 const mStatus err_netorder = dnssd_htonl(err);
4960 send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
4961 if (req->errsd != req->sd)
4962 {
4963 LogDebug("%3d: Result code socket %d closed %08X %08X (%d)",
4964 req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
4965 dnssd_close(req->errsd);
4966 req->errsd = req->sd;
4967 // Also need to reset the parent's errsd, if this is a subordinate operation
4968 if (req->primary) req->primary->errsd = req->primary->sd;
4969 }
4970 }
4971
4972 // Reset ready to accept the next req on this pipe
4973 if (req->primary) req = req->primary;
4974 req->ts = t_morecoming;
4975 req->hdr_bytes = 0;
4976 req->data_bytes = 0;
4977 req->msgbuf = mDNSNULL;
4978 req->msgptr = mDNSNULL;
4979 req->msgend = 0;
4980 }
4981 }
4982
4983 mDNSlocal void connect_callback(int fd, short filter, void *info)
4984 {
4985 dnssd_sockaddr_t cliaddr;
4986 dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
4987 dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
4988 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
4989 unsigned long optval = 1;
4990 #endif
4991
4992 (void)filter; // Unused
4993 (void)info; // Unused
4994
4995 if (!dnssd_SocketValid(sd))
4996 {
4997 if (dnssd_errno != dnssd_EWOULDBLOCK)
4998 my_throttled_perror("ERROR: accept");
4999 return;
5000 }
5001
5002 #ifdef SO_NOSIGPIPE
5003 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
5004 if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
5005 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
5006 #endif
5007
5008 #if defined(_WIN32)
5009 if (ioctlsocket(sd, FIONBIO, &optval) != 0)
5010 #else
5011 if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
5012 #endif
5013 {
5014 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
5015 dnssd_close(sd);
5016 return;
5017 }
5018 else
5019 {
5020 request_state *request = NewRequest();
5021 request->ts = t_morecoming;
5022 request->sd = sd;
5023 request->errsd = sd;
5024 set_peer_pid(request);
5025 #if APPLE_OSX_mDNSResponder
5026 struct xucred x;
5027 socklen_t xucredlen = sizeof(x);
5028 if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION)
5029 request->uid = x.cr_uid; // save the effective userid of the client
5030 else
5031 my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
5032
5033 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
5034 #endif // APPLE_OSX_mDNSResponder
5035 LogDebug("%3d: connect_callback: Adding FD for uid %u", request->sd, request->uid);
5036 udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
5037 }
5038 }
5039
5040 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
5041 {
5042 #if defined(SO_NP_EXTENSIONS)
5043 struct so_np_extensions sonpx;
5044 socklen_t optlen = sizeof(struct so_np_extensions);
5045 sonpx.npx_flags = SONPX_SETOPTSHUT;
5046 sonpx.npx_mask = SONPX_SETOPTSHUT;
5047 if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
5048 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
5049 #endif
5050 #if defined(_WIN32)
5051 // SEH: do we even need to do this on windows?
5052 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
5053 u_long opt = 1;
5054 if (ioctlsocket(skt, FIONBIO, &opt) != 0)
5055 #else
5056 if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
5057 #endif
5058 {
5059 my_perror("ERROR: could not set listen socket to non-blocking mode");
5060 return mDNSfalse;
5061 }
5062
5063 if (listen(skt, LISTENQ) != 0)
5064 {
5065 my_perror("ERROR: could not listen on listen socket");
5066 return mDNSfalse;
5067 }
5068
5069 if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
5070 {
5071 my_perror("ERROR: could not add listen socket to event loop");
5072 return mDNSfalse;
5073 }
5074 else
5075 {
5076 LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
5077 mDNSStorage.uds_listener_skt = skt;
5078 }
5079 return mDNStrue;
5080 }
5081
5082 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
5083 {
5084 dnssd_sockaddr_t laddr;
5085 int ret;
5086 mDNSu32 i = 0;
5087
5088 LogInfo("udsserver_init: %d %d", _DNS_SD_H, mDNSStorage.mDNS_plat);
5089
5090 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
5091 if (PID_FILE[0])
5092 {
5093 FILE *fp = fopen(PID_FILE, "w");
5094 if (fp != NULL)
5095 {
5096 fprintf(fp, "%d\n", getpid());
5097 fclose(fp);
5098 }
5099 }
5100
5101 if (skts)
5102 {
5103 for (i = 0; i < count; i++)
5104 if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
5105 goto error;
5106 }
5107 else
5108 {
5109 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
5110 if (!dnssd_SocketValid(listenfd))
5111 {
5112 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
5113 goto error;
5114 }
5115
5116 mDNSPlatformMemZero(&laddr, sizeof(laddr));
5117
5118 #if defined(USE_TCP_LOOPBACK)
5119 {
5120 laddr.sin_family = AF_INET;
5121 laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
5122 laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
5123 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5124 if (ret < 0)
5125 {
5126 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5127 goto error;
5128 }
5129 }
5130 #else
5131 {
5132 mode_t mask = umask(0);
5133 unlink(boundPath); // OK if this fails
5134 laddr.sun_family = AF_LOCAL;
5135 #ifndef NOT_HAVE_SA_LEN
5136 // According to Stevens (section 3.2), there is no portable way to
5137 // determine whether sa_len is defined on a particular platform.
5138 laddr.sun_len = sizeof(struct sockaddr_un);
5139 #endif
5140 if (strlen(boundPath) >= sizeof(laddr.sun_path))
5141 {
5142 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
5143 goto error;
5144 }
5145 mDNSPlatformStrLCopy(laddr.sun_path, boundPath, sizeof(laddr.sun_path));
5146 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5147 umask(mask);
5148 if (ret < 0)
5149 {
5150 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5151 goto error;
5152 }
5153 }
5154 #endif
5155
5156 if (!uds_socket_setup(listenfd)) goto error;
5157 }
5158
5159 #if !defined(PLATFORM_NO_RLIMIT)
5160 {
5161 // Set maximum number of open file descriptors
5162 #define MIN_OPENFILES 10240
5163 struct rlimit maxfds, newfds;
5164
5165 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
5166 // you have to get and set rlimits once before getrlimit will return sensible values
5167 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5168 if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5169
5170 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5171 newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
5172 newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
5173 if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
5174 if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5175
5176 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5177 debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
5178 debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
5179 }
5180 #endif
5181
5182 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
5183 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
5184 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
5185 mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
5186 mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
5187
5188 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
5189 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
5190 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
5191 AddAutoBrowseDomain(0, &localdomain);
5192
5193 udsserver_handle_configchange(&mDNSStorage);
5194 return 0;
5195
5196 error:
5197
5198 my_perror("ERROR: udsserver_init");
5199 return -1;
5200 }
5201
5202 mDNSexport int udsserver_exit(void)
5203 {
5204 // Cancel all outstanding client requests
5205 while (all_requests) AbortUnlinkAndFree(all_requests);
5206
5207 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
5208 // created in udsserver_init, and others we created as a result of reading local configuration data
5209 while (LocalDomainEnumRecords)
5210 {
5211 ARListElem *rem = LocalDomainEnumRecords;
5212 LocalDomainEnumRecords = LocalDomainEnumRecords->next;
5213 mDNS_Deregister(&mDNSStorage, &rem->ar);
5214 }
5215
5216 // If the launching environment created no listening socket,
5217 // that means we created it ourselves, so we should clean it up on exit
5218 if (dnssd_SocketValid(listenfd))
5219 {
5220 dnssd_close(listenfd);
5221 #if !defined(USE_TCP_LOOPBACK)
5222 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
5223 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
5224 // It would be nice if we could find a solution to this problem
5225 if (unlink(boundPath))
5226 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
5227 #endif
5228 }
5229
5230 if (PID_FILE[0]) unlink(PID_FILE);
5231
5232 return 0;
5233 }
5234
5235 mDNSlocal void LogClientInfo(request_state *req)
5236 {
5237 char prefix[16];
5238 if (req->primary)
5239 mDNS_snprintf(prefix, sizeof(prefix), " -> ");
5240 else
5241 mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
5242
5243 if (!req->terminate)
5244 LogMsgNoIdent("%s No operation yet on this socket", prefix);
5245 else if (req->terminate == connection_termination)
5246 {
5247 int num_records = 0, num_ops = 0;
5248 const registered_record_entry *p;
5249 request_state *r;
5250 for (p = req->u.reg_recs; p; p=p->next) num_records++;
5251 for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
5252 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
5253 prefix, num_records, num_records != 1 ? "s" : "", num_ops, num_ops != 1 ? "s" : "",
5254 req->process_id, req->pid_name);
5255 for (p = req->u.reg_recs; p; p=p->next)
5256 LogMsgNoIdent(" -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
5257 req->flags, req->interfaceIndex, p->key, ARDisplayString(&mDNSStorage, p->rr), req->process_id, req->pid_name);
5258 for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(r);
5259 }
5260 else if (req->terminate == regservice_termination_callback)
5261 {
5262 service_instance *ptr;
5263 char anonstr[256];
5264 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5265 LogMsgNoIdent("%s DNSServiceRegister 0x%08X %2d %##s%s %u/%u PID[%d](%s)",
5266 (ptr == req->u.servicereg.instances) ? prefix : " ", req->flags, req->interfaceIndex, ptr->srs.RR_SRV.resrec.name->c,
5267 AnonDataToString(ptr->srs.AnonData, 0, anonstr, sizeof(anonstr)), mDNSVal16(req->u.servicereg.port),
5268 SRS_PORT(&ptr->srs), req->process_id, req->pid_name);
5269 }
5270 else if (req->terminate == browse_termination_callback)
5271 {
5272 browser_t *blist;
5273 char anonstr[256];
5274 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5275 LogMsgNoIdent("%s DNSServiceBrowse 0x%08X %2d %##s%s PID[%d](%s)",
5276 (blist == req->u.browser.browsers) ? prefix : " ", req->flags, req->interfaceIndex, blist->q.qname.c,
5277 AnonDataToString(req->u.browser.AnonData, 0, anonstr, sizeof(anonstr)), req->process_id, req->pid_name);
5278 }
5279 else if (req->terminate == resolve_termination_callback)
5280 LogMsgNoIdent("%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
5281 prefix, req->flags, req->interfaceIndex, req->u.resolve.qsrv.qname.c, req->process_id, req->pid_name);
5282 else if (req->terminate == queryrecord_termination_callback)
5283 LogMsgNoIdent("%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
5284 prefix, req->flags, req->interfaceIndex, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype), req->process_id, req->pid_name);
5285 else if (req->terminate == enum_termination_callback)
5286 LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
5287 prefix, req->flags, req->interfaceIndex, req->u.enumeration.q_all.qname.c, req->process_id, req->pid_name);
5288 else if (req->terminate == port_mapping_termination_callback)
5289 LogMsgNoIdent("%s DNSServiceNATPortMapping 0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
5290 prefix,
5291 req->flags,
5292 req->interfaceIndex,
5293 req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : " ",
5294 req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : " ",
5295 mDNSVal16(req->u.pm.NATinfo.IntPort),
5296 mDNSVal16(req->u.pm.ReqExt),
5297 &req->u.pm.NATinfo.ExternalAddress,
5298 mDNSVal16(req->u.pm.NATinfo.ExternalPort),
5299 req->u.pm.NATinfo.NATLease,
5300 req->u.pm.NATinfo.Lifetime,
5301 req->process_id, req->pid_name);
5302 else if (req->terminate == addrinfo_termination_callback)
5303 LogMsgNoIdent("%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
5304 prefix, req->flags, req->interfaceIndex,
5305 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5306 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5307 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name);
5308 else
5309 LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
5310 }
5311
5312 mDNSlocal void GetMcastClients(request_state *req)
5313 {
5314 if (req->terminate == connection_termination)
5315 {
5316 int num_records = 0, num_ops = 0;
5317 const registered_record_entry *p;
5318 request_state *r;
5319 for (p = req->u.reg_recs; p; p=p->next)
5320 num_records++;
5321 for (r = req->next; r; r=r->next)
5322 if (r->primary == req)
5323 num_ops++;
5324 for (p = req->u.reg_recs; p; p=p->next)
5325 {
5326 if (!AuthRecord_uDNS(p->rr))
5327 n_mrecords++;
5328 }
5329 for (r = req->next; r; r=r->next)
5330 if (r->primary == req)
5331 GetMcastClients(r);
5332 }
5333 else if (req->terminate == regservice_termination_callback)
5334 {
5335 service_instance *ptr;
5336 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5337 {
5338 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5339 n_mrecords++;
5340 }
5341 }
5342 else if (req->terminate == browse_termination_callback)
5343 {
5344 browser_t *blist;
5345 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5346 {
5347 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5348 n_mquests++;
5349 }
5350 }
5351 else if (req->terminate == resolve_termination_callback)
5352 {
5353 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5354 n_mquests++;
5355 }
5356 else if (req->terminate == queryrecord_termination_callback)
5357 {
5358 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5359 n_mquests++;
5360 }
5361 else if (req->terminate == addrinfo_termination_callback)
5362 {
5363 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5364 n_mquests++;
5365 }
5366 else
5367 {
5368 return;
5369 }
5370 }
5371
5372
5373 mDNSlocal void LogMcastClientInfo(request_state *req)
5374 {
5375 if (!req->terminate)
5376 LogMcastNoIdent("No operation yet on this socket");
5377 else if (req->terminate == connection_termination)
5378 {
5379 int num_records = 0, num_ops = 0;
5380 const registered_record_entry *p;
5381 request_state *r;
5382 for (p = req->u.reg_recs; p; p=p->next)
5383 num_records++;
5384 for (r = req->next; r; r=r->next)
5385 if (r->primary == req)
5386 num_ops++;
5387 for (p = req->u.reg_recs; p; p=p->next)
5388 {
5389 if (!AuthRecord_uDNS(p->rr))
5390 LogMcastNoIdent("R: -> DNSServiceRegisterRecord: %##s %s PID[%d](%s)", p->rr->resrec.name->c,
5391 DNSTypeName(p->rr->resrec.rrtype), req->process_id, req->pid_name, i_mcount++);
5392 }
5393 for (r = req->next; r; r=r->next)
5394 if (r->primary == req)
5395 LogMcastClientInfo(r);
5396 }
5397 else if (req->terminate == regservice_termination_callback)
5398 {
5399 service_instance *ptr;
5400 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5401 {
5402 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5403 LogMcastNoIdent("R: DNSServiceRegister: %##s %u/%u PID[%d](%s)", ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port),
5404 SRS_PORT(&ptr->srs), req->process_id, req->pid_name, i_mcount++);
5405 }
5406 }
5407 else if (req->terminate == browse_termination_callback)
5408 {
5409 browser_t *blist;
5410 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5411 {
5412 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5413 LogMcastNoIdent("Q: DNSServiceBrowse %##s %s PID[%d](%s)", blist->q.qname.c, DNSTypeName(blist->q.qtype),
5414 req->process_id, req->pid_name, i_mcount++);
5415 }
5416 }
5417 else if (req->terminate == resolve_termination_callback)
5418 {
5419 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5420 LogMcastNoIdent("Q: DNSServiceResolve %##s %s PID[%d](%s)", req->u.resolve.qsrv.qname.c, DNSTypeName(req->u.resolve.qsrv.qtype),
5421 req->process_id, req->pid_name, i_mcount++);
5422 }
5423 else if (req->terminate == queryrecord_termination_callback)
5424 {
5425 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5426 LogMcastNoIdent("Q: DNSServiceQueryRecord %##s %s PID[%d](%s)", req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype),
5427 req->process_id, req->pid_name, i_mcount++);
5428 }
5429 else if (req->terminate == addrinfo_termination_callback)
5430 {
5431 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5432 LogMcastNoIdent("Q: DNSServiceGetAddrInfo %s%s %##s PID[%d](%s)",
5433 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5434 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5435 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name, i_mcount++);
5436 }
5437 else
5438 {
5439 return;
5440 }
5441
5442 }
5443
5444 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
5445 {
5446 switch (rtype)
5447 {
5448 case kDNSRecordTypeUnregistered: return ("Unregistered ");
5449 case kDNSRecordTypeDeregistering: return ("Deregistering");
5450 case kDNSRecordTypeUnique: return ("Unique ");
5451 case kDNSRecordTypeAdvisory: return ("Advisory ");
5452 case kDNSRecordTypeShared: return ("Shared ");
5453 case kDNSRecordTypeVerified: return ("Verified ");
5454 case kDNSRecordTypeKnownUnique: return ("KnownUnique ");
5455 default: return("Unknown");
5456 }
5457 }
5458
5459 mDNSlocal int LogEtcHosts(mDNS *const m)
5460 {
5461 mDNSBool showheader = mDNStrue;
5462 const AuthRecord *ar;
5463 mDNSu32 slot;
5464 AuthGroup *ag;
5465 int count = 0;
5466 int authslot = 0;
5467 mDNSBool truncated = 0;
5468
5469 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5470 {
5471 if (m->rrauth.rrauth_hash[slot]) authslot++;
5472 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5473 for (ar = ag->members; ar; ar = ar->next)
5474 {
5475 if (ar->RecordCallback != FreeEtcHosts) continue;
5476 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5477
5478 // Print a maximum of 50 records
5479 if (count++ >= 50) { truncated = mDNStrue; continue; }
5480 if (ar->ARType == AuthRecordLocalOnly)
5481 {
5482 if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
5483 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5484 else
5485 {
5486 mDNSu32 scopeid = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
5487 LogMsgNoIdent(" %s %u %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
5488 }
5489 }
5490 }
5491 }
5492
5493 if (showheader) LogMsgNoIdent("<None>");
5494 else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
5495 return count;
5496 }
5497
5498 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
5499 {
5500 mDNSBool showheader = mDNStrue;
5501 const AuthRecord *ar;
5502 mDNSu32 slot;
5503 AuthGroup *ag;
5504
5505 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5506 {
5507 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5508 for (ar = ag->members; ar; ar = ar->next)
5509 {
5510 if (ar->RecordCallback == FreeEtcHosts) continue;
5511 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5512
5513 // Print a maximum of 400 records
5514 if (ar->ARType == AuthRecordLocalOnly)
5515 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5516 else if (ar->ARType == AuthRecordP2P)
5517 {
5518 if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5519 LogMsgNoIdent(" %s BLE %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5520 else
5521 LogMsgNoIdent(" %s PP %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5522 }
5523 }
5524 }
5525
5526 if (showheader) LogMsgNoIdent("<None>");
5527 }
5528
5529 mDNSlocal char *AnonInfoToString(AnonymousInfo *ai, char *anonstr, int anstrlen)
5530 {
5531 anonstr[0] = 0;
5532 if (ai && ai->AnonData)
5533 {
5534 return (AnonDataToString(ai->AnonData, ai->AnonDataLen, anonstr, anstrlen));
5535 }
5536 return anonstr;
5537 }
5538
5539 mDNSlocal void LogOneAuthRecord(const AuthRecord *ar, mDNSs32 now, const char *const ifname)
5540 {
5541 char anstr[256];
5542 if (AuthRecord_uDNS(ar))
5543 {
5544 LogMsgNoIdent("%7d %7d %7d %-7s %4d %s %s",
5545 ar->ThisAPInterval / mDNSPlatformOneSecond,
5546 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5547 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5548 "-U-",
5549 ar->state,
5550 ar->AllowRemoteQuery ? "☠" : " ",
5551 ARDisplayString(&mDNSStorage, ar));
5552 }
5553 else
5554 {
5555 LogMsgNoIdent("%7d %7d %7d %-7s 0x%02X %s %s%s",
5556 ar->ThisAPInterval / mDNSPlatformOneSecond,
5557 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5558 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5559 ifname ? ifname : "ALL",
5560 ar->resrec.RecordType,
5561 ar->AllowRemoteQuery ? "☠" : " ",
5562 ARDisplayString(&mDNSStorage, ar), AnonInfoToString(ar->resrec.AnonInfo, anstr, sizeof(anstr)));
5563 }
5564 }
5565
5566 mDNSlocal void LogAuthRecords(const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
5567 {
5568 mDNSBool showheader = mDNStrue;
5569 const AuthRecord *ar;
5570 OwnerOptData owner = zeroOwner;
5571 for (ar = ResourceRecords; ar; ar=ar->next)
5572 {
5573 const char *const ifname = InterfaceNameForID(&mDNSStorage, ar->resrec.InterfaceID);
5574 if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
5575 {
5576 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" Int Next Expire if State"); }
5577 if (proxy) (*proxy)++;
5578 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
5579 {
5580 owner = ar->WakeUp;
5581 if (owner.password.l[0])
5582 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
5583 else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
5584 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner.HMAC, &owner.IMAC, owner.seq);
5585 else
5586 LogMsgNoIdent("Proxying for %.6a seq %d", &owner.HMAC, owner.seq);
5587 }
5588 if (AuthRecord_uDNS(ar))
5589 {
5590 LogOneAuthRecord(ar, now, ifname);
5591 }
5592 else if (ar->ARType == AuthRecordLocalOnly)
5593 {
5594 LogMsgNoIdent(" LO %s", ARDisplayString(&mDNSStorage, ar));
5595 }
5596 else if (ar->ARType == AuthRecordP2P)
5597 {
5598 if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5599 LogMsgNoIdent(" BLE %s", ARDisplayString(&mDNSStorage, ar));
5600 else
5601 LogMsgNoIdent(" PP %s", ARDisplayString(&mDNSStorage, ar));
5602 }
5603 else
5604 {
5605 LogOneAuthRecord(ar, now, ifname);
5606 if (ar->resrec.AnonInfo)
5607 {
5608 ResourceRecord *nsec3 = ar->resrec.AnonInfo->nsec3RR;
5609 // We just print the values from the AuthRecord to keep it nicely aligned though
5610 // all we want here is the nsec3 information.
5611 LogMsgNoIdent("%7d %7d %7d %7s %s",
5612 ar->ThisAPInterval / mDNSPlatformOneSecond,
5613 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5614 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5615 ifname ? ifname : "ALL",
5616 RRDisplayString(&mDNSStorage, nsec3));
5617 }
5618 }
5619 }
5620 }
5621 if (showheader) LogMsgNoIdent("<None>");
5622 }
5623
5624 mDNSlocal void PrintOneCacheRecord(const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5625 {
5626 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5627 slot,
5628 cr->CRActiveQuestion ? "*" : " ",
5629 remain,
5630 ifname ? ifname : "-U-",
5631 (cr->resrec.RecordType == kDNSRecordTypePacketNegative) ? "-" :
5632 (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5633 DNSTypeName(cr->resrec.rrtype),
5634 CRDisplayString(&mDNSStorage, cr));
5635 (*CacheUsed)++;
5636 }
5637
5638 mDNSlocal void PrintCachedRecords(const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5639 {
5640 CacheRecord *nsec;
5641 CacheRecord *soa;
5642 nsec = cr->nsec;
5643
5644 // The records that are cached under the main cache record like nsec, soa don't have
5645 // their own lifetime. If the main cache record expires, they also expire.
5646 while (nsec)
5647 {
5648 PrintOneCacheRecord(nsec, slot, remain, ifname, CacheUsed);
5649 nsec = nsec->next;
5650 }
5651 soa = cr->soa;
5652 if (soa)
5653 {
5654 PrintOneCacheRecord(soa, slot, remain, ifname, CacheUsed);
5655 }
5656 if (cr->resrec.AnonInfo)
5657 {
5658 ResourceRecord *nsec3 = cr->resrec.AnonInfo->nsec3RR;
5659 // Even though it is a resource record, we print the sameway
5660 // as a cache record so that it aligns properly.
5661 if (nsec3)
5662 {
5663 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5664 slot,
5665 " ",
5666 remain,
5667 ifname ? ifname : "-U-",
5668 (nsec3->RecordType == kDNSRecordTypePacketNegative) ? "-" :
5669 (nsec3->RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5670 DNSTypeName(nsec3->rrtype),
5671 RRDisplayString(&mDNSStorage, nsec3));
5672 }
5673 }
5674 }
5675
5676 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen)
5677 {
5678 adstr[0] = 0;
5679 if (ad)
5680 {
5681 int len;
5682 char *orig = adstr;
5683
5684 // If the caller is lazy to compute the length, we do it for them.
5685 if (!adlen)
5686 len = strlen((const char *)ad);
5687 else
5688 len = adlen;
5689
5690 // Print the anondata within brackets. Hence, we need space for two
5691 // brackets and a NULL byte.
5692 if (len > (adstrlen - 3))
5693 len = adstrlen - 3;
5694
5695 *adstr++ = '(';
5696 mDNSPlatformMemCopy(adstr, ad, len);
5697 adstr[len] = ')';
5698 adstr[len+1] = 0;
5699 return orig;
5700 }
5701 return adstr;
5702 }
5703
5704 mDNSexport void LogMDNSStatistics(mDNS *const m)
5705 {
5706 LogMsgNoIdent("--- MDNS Statistics ---");
5707
5708 LogMsgNoIdent("Name Conflicts %u", m->mDNSStats.NameConflicts);
5709 LogMsgNoIdent("KnownUnique Name Conflicts %u", m->mDNSStats.KnownUniqueNameConflicts);
5710 LogMsgNoIdent("Duplicate Query Suppressions %u", m->mDNSStats.DupQuerySuppressions);
5711 LogMsgNoIdent("KA Suppressions %u", m->mDNSStats.KnownAnswerSuppressions);
5712 LogMsgNoIdent("KA Multiple Packets %u", m->mDNSStats.KnownAnswerMultiplePkts);
5713 LogMsgNoIdent("Poof Cache Deletions %u", m->mDNSStats.PoofCacheDeletions);
5714 LogMsgNoIdent("--------------------------------");
5715
5716 LogMsgNoIdent("Multicast packets Sent %u", m->MulticastPacketsSent);
5717 LogMsgNoIdent("Multicast packets Received %u", m->MPktNum);
5718 LogMsgNoIdent("Remote Subnet packets %u", m->RemoteSubnet);
5719 LogMsgNoIdent("QU questions received %u", m->mDNSStats.UnicastBitInQueries);
5720 LogMsgNoIdent("Normal multicast questions %u", m->mDNSStats.NormalQueries);
5721 LogMsgNoIdent("Answers for questions %u", m->mDNSStats.MatchingAnswersForQueries);
5722 LogMsgNoIdent("Unicast responses %u", m->mDNSStats.UnicastResponses);
5723 LogMsgNoIdent("Multicast responses %u", m->mDNSStats.MulticastResponses);
5724 LogMsgNoIdent("Unicast response Demotions %u", m->mDNSStats.UnicastDemotedToMulticast);
5725 LogMsgNoIdent("--------------------------------");
5726
5727 LogMsgNoIdent("Sleeps %u", m->mDNSStats.Sleeps);
5728 LogMsgNoIdent("Wakeups %u", m->mDNSStats.Wakes);
5729 LogMsgNoIdent("Interface UP events %u", m->mDNSStats.InterfaceUp);
5730 LogMsgNoIdent("Interface UP Flap events %u", m->mDNSStats.InterfaceUpFlap);
5731 LogMsgNoIdent("Interface Down events %u", m->mDNSStats.InterfaceDown);
5732 LogMsgNoIdent("Interface DownFlap events %u", m->mDNSStats.InterfaceDownFlap);
5733 LogMsgNoIdent("Cache refresh queries %u", m->mDNSStats.CacheRefreshQueries);
5734 LogMsgNoIdent("Cache refreshed %u", m->mDNSStats.CacheRefreshed);
5735 LogMsgNoIdent("Wakeup on Resolves %u", m->mDNSStats.WakeOnResolves);
5736 }
5737
5738 mDNSexport void udsserver_info()
5739 {
5740 mDNS *const m = &mDNSStorage;
5741 const mDNSs32 now = mDNS_TimeNow(m);
5742 mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
5743 int ProxyA = 0, ProxyD = 0;
5744 mDNSu32 groupCount = 0;
5745 mDNSu32 mcastRecordCount = 0;
5746 mDNSu32 ucastRecordCount = 0;
5747 const CacheGroup *cg;
5748 const CacheRecord *cr;
5749 const DNSQuestion *q;
5750 const DNameListElem *d;
5751 const SearchListElem *s;
5752
5753 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
5754
5755 LogMsgNoIdent("------------ Cache -------------");
5756 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
5757 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5758 {
5759 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
5760 {
5761 groupCount++; // Count one cache entity for the CacheGroup object
5762 for (cr = cg->members; cr; cr=cr->next)
5763 {
5764 const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
5765 const char *ifname;
5766 mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
5767 mDNSu32 *const countPtr = InterfaceID ? &mcastRecordCount : &ucastRecordCount;
5768 if (!InterfaceID && cr->resrec.rDNSServer && cr->resrec.rDNSServer->scoped)
5769 InterfaceID = cr->resrec.rDNSServer->interface;
5770 ifname = InterfaceNameForID(m, InterfaceID);
5771 if (cr->CRActiveQuestion) CacheActive++;
5772 PrintOneCacheRecord(cr, slot, remain, ifname, countPtr);
5773 PrintCachedRecords(cr, slot, remain, ifname, countPtr);
5774 }
5775 }
5776 }
5777
5778 CacheUsed = groupCount + mcastRecordCount + ucastRecordCount;
5779 if (m->rrcache_totalused != CacheUsed)
5780 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
5781 if (m->rrcache_active != CacheActive)
5782 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
5783 LogMsgNoIdent("Cache size %u entities; %u in use (%u group, %u multicast, %u unicast); %u referenced by active questions",
5784 m->rrcache_size, CacheUsed, groupCount, mcastRecordCount, ucastRecordCount, CacheActive);
5785
5786 LogMsgNoIdent("--------- Auth Records ---------");
5787 LogAuthRecords(now, m->ResourceRecords, mDNSNULL);
5788
5789 LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
5790 LogLocalOnlyAuthRecords(m);
5791
5792 LogMsgNoIdent("--------- /etc/hosts ---------");
5793 LogEtcHosts(m);
5794
5795 LogMsgNoIdent("------ Duplicate Records -------");
5796 LogAuthRecords(now, m->DuplicateRecords, mDNSNULL);
5797
5798 LogMsgNoIdent("----- Auth Records Proxied -----");
5799 LogAuthRecords(now, m->ResourceRecords, &ProxyA);
5800
5801 LogMsgNoIdent("-- Duplicate Records Proxied ---");
5802 LogAuthRecords(now, m->DuplicateRecords, &ProxyD);
5803
5804 LogMsgNoIdent("---------- Questions -----------");
5805 if (!m->Questions) LogMsgNoIdent("<None>");
5806 else
5807 {
5808 char anonstr[256];
5809 CacheUsed = 0;
5810 CacheActive = 0;
5811 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
5812 for (q = m->Questions; q; q=q->next)
5813 {
5814 mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
5815 mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
5816 char *ifname = InterfaceNameForID(m, q->InterfaceID);
5817 CacheUsed++;
5818 if (q->ThisQInterval) CacheActive++;
5819 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s%s",
5820 i, n,
5821 ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
5822 mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
5823 PrivateQuery(q) ? "P" : q->ValidationRequired ? "V" : q->ValidatingResponse ? "R" : " ",
5824 q->CurrentAnswers, q->validDNSServers.l[3], q->validDNSServers.l[2], q->validDNSServers.l[1],
5825 q->validDNSServers.l[0], q, q->DuplicateOf,
5826 q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c,
5827 AnonInfoToString(q->AnonInfo, anonstr, sizeof(anonstr)),
5828 q->DuplicateOf ? " (dup)" : "");
5829 }
5830 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
5831 }
5832
5833 LogMsgNoIdent("----- LocalOnly, P2P Questions -----");
5834 if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
5835 else for (q = m->LocalOnlyQuestions; q; q=q->next)
5836 LogMsgNoIdent(" %3s %5d %-6s%##s%s",
5837 q->InterfaceID == mDNSInterface_LocalOnly ? "LO ": q->InterfaceID == mDNSInterface_BLE ? "BLE": "P2P",
5838 q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
5839
5840 LogMsgNoIdent("---- Active UDS Client Requests ----");
5841 if (!all_requests) LogMsgNoIdent("<None>");
5842 else
5843 {
5844 request_state *req, *r;
5845 for (req = all_requests; req; req=req->next)
5846 {
5847 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
5848 {
5849 for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
5850 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
5851 }
5852 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
5853 LogClientInfo(req);
5854 foundparent:;
5855 }
5856 }
5857
5858 LogMsgNoIdent("-------- NAT Traversals --------");
5859 LogMsgNoIdent("ExtAddress %.4a Retry %d Interval %d",
5860 &m->ExtAddress,
5861 m->retryGetAddr ? (m->retryGetAddr - now) / mDNSPlatformOneSecond : 0,
5862 m->retryIntervalGetAddr / mDNSPlatformOneSecond);
5863 if (m->NATTraversals)
5864 {
5865 const NATTraversalInfo *nat;
5866 for (nat = m->NATTraversals; nat; nat=nat->next)
5867 {
5868 LogMsgNoIdent("%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
5869 nat,
5870 nat->Protocol ? (nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP") : "ADD",
5871 mDNSVal16(nat->IntPort),
5872 (nat->lastSuccessfulProtocol == NATTProtocolNone ? "None " :
5873 nat->lastSuccessfulProtocol == NATTProtocolNATPMP ? "NAT-PMP " :
5874 nat->lastSuccessfulProtocol == NATTProtocolUPNPIGD ? "UPnP/IGD" :
5875 nat->lastSuccessfulProtocol == NATTProtocolPCP ? "PCP " :
5876 /* else */ "Unknown " ),
5877 nat->Result,
5878 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
5879 nat->retryInterval / mDNSPlatformOneSecond,
5880 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
5881 &nat->NewAddress, mDNSVal16(nat->RequestedPort),
5882 &nat->ExternalAddress, mDNSVal16(nat->ExternalPort));
5883 }
5884 }
5885
5886 LogMsgNoIdent("--------- AuthInfoList ---------");
5887 if (!m->AuthInfoList) LogMsgNoIdent("<None>");
5888 else
5889 {
5890 const DomainAuthInfo *a;
5891 for (a = m->AuthInfoList; a; a = a->next)
5892 {
5893 LogMsgNoIdent("%##s %##s %##s %d %d %.16a%s",
5894 a->domain.c, a->keyname.c,
5895 a->hostname.c, (a->port.b[0] << 8 | a->port.b[1]),
5896 (a->deltime ? (a->deltime - now) : 0),
5897 &a->AutoTunnelInnerAddress, a->AutoTunnel ? " AutoTunnel" : "");
5898 }
5899 }
5900
5901 #if APPLE_OSX_mDNSResponder
5902 LogMsgNoIdent("--------- TunnelClients --------");
5903 if (!m->TunnelClients) LogMsgNoIdent("<None>");
5904 else
5905 {
5906 const ClientTunnel *c;
5907 for (c = m->TunnelClients; c; c = c->next)
5908 LogMsgNoIdent("%##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
5909 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);
5910 }
5911 #endif // APPLE_OSX_mDNSResponder
5912
5913 LogMsgNoIdent("---------- Misc State ----------");
5914
5915 LogMsgNoIdent("PrimaryMAC: %.6a", &m->PrimaryMAC);
5916
5917 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
5918 m->SleepState,
5919 m->SleepState == SleepState_Awake ? "Awake" :
5920 m->SleepState == SleepState_Transferring ? "Transferring" :
5921 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?",
5922 m->SleepSeqNum);
5923
5924 if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
5925 #ifndef SPC_DISABLED
5926 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
5927 #endif
5928 if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
5929 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
5930
5931 LogMsgNoIdent("------ Auto Browse Domains -----");
5932 if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
5933 else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5934
5935 LogMsgNoIdent("--- Auto Registration Domains --");
5936 if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
5937 else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
5938
5939 LogMsgNoIdent("--- Search Domains --");
5940 if (!SearchList) LogMsgNoIdent("<None>");
5941 else
5942 {
5943 for (s=SearchList; s; s=s->next)
5944 {
5945 char *ifname = InterfaceNameForID(m, s->InterfaceID);
5946 LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
5947 }
5948 }
5949 LogInfo("--- Trust Anchors ---");
5950 if (!m->TrustAnchors)
5951 {
5952 LogInfo("<None>");
5953 }
5954 else
5955 {
5956 TrustAnchor *ta;
5957 mDNSu8 fromTimeBuf[64];
5958 mDNSu8 untilTimeBuf[64];
5959
5960 for (ta=m->TrustAnchors; ta; ta=ta->next)
5961 {
5962 mDNSPlatformFormatTime((unsigned long)ta->validFrom, fromTimeBuf, sizeof(fromTimeBuf));
5963 mDNSPlatformFormatTime((unsigned long)ta->validUntil, untilTimeBuf, sizeof(untilTimeBuf));
5964 LogInfo("%##s %d %d %d %d %s %s", ta->zone.c, ta->rds.keyTag,
5965 ta->rds.alg, ta->rds.digestType, ta->digestLen, fromTimeBuf, untilTimeBuf);
5966 }
5967 }
5968
5969 LogInfo("--- DNSSEC Statistics ---");
5970
5971 LogMsgNoIdent("Unicast Cache size %u", m->rrcache_totalused_unicast);
5972 LogInfo("DNSSEC Cache size %u", m->DNSSECStats.TotalMemUsed);
5973 if (m->rrcache_totalused_unicast)
5974 LogInfo("DNSSEC usage percentage %u", ((unsigned long)(m->DNSSECStats.TotalMemUsed * 100))/m->rrcache_totalused_unicast);
5975 LogInfo("DNSSEC Extra Packets (0 to 2) %u", m->DNSSECStats.ExtraPackets0);
5976 LogInfo("DNSSEC Extra Packets (3 to 6) %u", m->DNSSECStats.ExtraPackets3);
5977 LogInfo("DNSSEC Extra Packets (7 to 9) %u", m->DNSSECStats.ExtraPackets7);
5978 LogInfo("DNSSEC Extra Packets ( >= 10) %u", m->DNSSECStats.ExtraPackets10);
5979
5980 LogInfo("DNSSEC Latency (0 to 4ms) %u", m->DNSSECStats.Latency0);
5981 LogInfo("DNSSEC Latency (4 to 9ms) %u", m->DNSSECStats.Latency5);
5982 LogInfo("DNSSEC Latency (10 to 19ms) %u", m->DNSSECStats.Latency10);
5983 LogInfo("DNSSEC Latency (20 to 49ms) %u", m->DNSSECStats.Latency20);
5984 LogInfo("DNSSEC Latency (50 to 99ms) %u", m->DNSSECStats.Latency50);
5985 LogInfo("DNSSEC Latency ( >=100ms) %u", m->DNSSECStats.Latency100);
5986
5987 LogInfo("DNSSEC Secure Status %u", m->DNSSECStats.SecureStatus);
5988 LogInfo("DNSSEC Insecure Status %u", m->DNSSECStats.InsecureStatus);
5989 LogInfo("DNSSEC Indeterminate Status %u", m->DNSSECStats.IndeterminateStatus);
5990 LogInfo("DNSSEC Bogus Status %u", m->DNSSECStats.BogusStatus);
5991 LogInfo("DNSSEC NoResponse Status %u", m->DNSSECStats.NoResponseStatus);
5992 LogInfo("DNSSEC Probes sent %u", m->DNSSECStats.NumProbesSent);
5993 LogInfo("DNSSEC Msg Size (<=1024) %u", m->DNSSECStats.MsgSize0);
5994 LogInfo("DNSSEC Msg Size (<=2048) %u", m->DNSSECStats.MsgSize1);
5995 LogInfo("DNSSEC Msg Size (> 2048) %u", m->DNSSECStats.MsgSize2);
5996
5997 LogMDNSStatistics(m);
5998
5999 LogMsgNoIdent("---- Task Scheduling Timers ----");
6000
6001 #if BONJOUR_ON_DEMAND
6002 LogMsgNoIdent("BonjourEnabled %d", m->BonjourEnabled);
6003 #endif // BONJOUR_ON_DEMAND
6004
6005 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
6006 LogMsgNoIdent("EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery);
6007 LogMsgNoIdent("DefaultToBLETriggered %d", DefaultToBLETriggered);
6008 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
6009
6010 if (!m->NewQuestions)
6011 LogMsgNoIdent("NewQuestion <NONE>");
6012 else
6013 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
6014 m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
6015 m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
6016
6017 if (!m->NewLocalOnlyQuestions)
6018 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
6019 else
6020 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
6021 m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
6022
6023 if (!m->NewLocalRecords)
6024 LogMsgNoIdent("NewLocalRecords <NONE>");
6025 else
6026 LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
6027
6028 LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
6029 LogMsgNoIdent("LocalRemoveEvents%s", m->LocalRemoveEvents ? "" : " <NONE>");
6030 LogMsgNoIdent("m->AutoTunnelRelayAddr %.16a", &m->AutoTunnelRelayAddr);
6031 LogMsgNoIdent("m->WABBrowseQueriesCount %d", m->WABBrowseQueriesCount);
6032 LogMsgNoIdent("m->WABLBrowseQueriesCount %d", m->WABLBrowseQueriesCount);
6033 LogMsgNoIdent("m->WABRegQueriesCount %d", m->WABRegQueriesCount);
6034 LogMsgNoIdent("m->AutoTargetServices %d", m->AutoTargetServices);
6035
6036 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
6037 LogMsgNoIdent("m->timenow %08X %11d", now, now);
6038 LogMsgNoIdent("m->timenow_adjust %08X %11d", m->timenow_adjust, m->timenow_adjust);
6039 LogTimer("m->NextScheduledEvent ", m->NextScheduledEvent);
6040
6041 #ifndef UNICAST_DISABLED
6042 LogTimer("m->NextuDNSEvent ", m->NextuDNSEvent);
6043 LogTimer("m->NextSRVUpdate ", m->NextSRVUpdate);
6044 LogTimer("m->NextScheduledNATOp ", m->NextScheduledNATOp);
6045 LogTimer("m->retryGetAddr ", m->retryGetAddr);
6046 #endif
6047
6048 LogTimer("m->NextCacheCheck ", m->NextCacheCheck);
6049 LogTimer("m->NextScheduledSPS ", m->NextScheduledSPS);
6050 LogTimer("m->NextScheduledKA ", m->NextScheduledKA);
6051
6052 #if BONJOUR_ON_DEMAND
6053 LogTimer("m->NextBonjourDisableTime ", m->NextBonjourDisableTime);
6054 #endif // BONJOUR_ON_DEMAND
6055
6056 LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
6057 LogTimer("m->DelaySleep ", m->DelaySleep);
6058
6059 LogTimer("m->NextScheduledQuery ", m->NextScheduledQuery);
6060 LogTimer("m->NextScheduledProbe ", m->NextScheduledProbe);
6061 LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
6062
6063 LogTimer("m->SuppressSending ", m->SuppressSending);
6064 LogTimer("m->SuppressProbes ", m->SuppressProbes);
6065 LogTimer("m->ProbeFailTime ", m->ProbeFailTime);
6066 LogTimer("m->DelaySleep ", m->DelaySleep);
6067 LogTimer("m->SleepLimit ", m->SleepLimit);
6068 LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
6069 }
6070
6071 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6072 mDNSexport void uds_validatelists(void)
6073 {
6074 const request_state *req, *p;
6075 for (req = all_requests; req; req=req->next)
6076 {
6077 if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
6078 LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
6079
6080 if (req->primary == req)
6081 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
6082
6083 if (req->primary && req->replies)
6084 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
6085 req, req->sd, req->primary && req->replies);
6086
6087 p = req->primary;
6088 if ((long)p & 3)
6089 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
6090 else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
6091 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
6092
6093 reply_state *rep;
6094 for (rep = req->replies; rep; rep=rep->next)
6095 if (rep->next == (reply_state *)~0)
6096 LogMemCorruption("UDS req->replies: %p is garbage", rep);
6097
6098 if (req->terminate == connection_termination)
6099 {
6100 registered_record_entry *r;
6101 for (r = req->u.reg_recs; r; r=r->next)
6102 if (r->next == (registered_record_entry *)~0)
6103 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
6104 }
6105 else if (req->terminate == regservice_termination_callback)
6106 {
6107 service_instance *s;
6108 for (s = req->u.servicereg.instances; s; s=s->next)
6109 if (s->next == (service_instance *)~0)
6110 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
6111 }
6112 else if (req->terminate == browse_termination_callback)
6113 {
6114 browser_t *b;
6115 for (b = req->u.browser.browsers; b; b=b->next)
6116 if (b->next == (browser_t *)~0)
6117 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
6118 }
6119 }
6120
6121 DNameListElem *d;
6122 for (d = SCPrefBrowseDomains; d; d=d->next)
6123 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6124 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6125
6126 ARListElem *b;
6127 for (b = LocalDomainEnumRecords; b; b=b->next)
6128 if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
6129 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
6130
6131 for (d = AutoBrowseDomains; d; d=d->next)
6132 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6133 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6134
6135 for (d = AutoRegistrationDomains; d; d=d->next)
6136 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6137 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
6138 }
6139 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6140
6141 mDNSlocal int send_msg(request_state *const req)
6142 {
6143 reply_state *const rep = req->replies; // Send the first waiting reply
6144 ssize_t nwriten;
6145
6146 ConvertHeaderBytes(rep->mhdr);
6147 nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
6148 ConvertHeaderBytes(rep->mhdr);
6149
6150 if (nwriten < 0)
6151 {
6152 if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
6153 else
6154 {
6155 #if !defined(PLATFORM_NO_EPIPE)
6156 if (dnssd_errno == EPIPE)
6157 return(req->ts = t_terminated);
6158 else
6159 #endif
6160 {
6161 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
6162 rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
6163 return(t_error);
6164 }
6165 }
6166 }
6167 rep->nwriten += nwriten;
6168 return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
6169 }
6170
6171 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
6172 {
6173 mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
6174 request_state **req = &all_requests;
6175
6176 while (*req)
6177 {
6178 request_state *const r = *req;
6179
6180 if (r->terminate == resolve_termination_callback)
6181 if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
6182 {
6183 r->u.resolve.ReportTime = 0;
6184 // if client received results and resolve still active
6185 if (r->u.resolve.txt && r->u.resolve.srv)
6186 LogMsgNoIdent("Client application PID[%d](%s) has received results for DNSServiceResolve(%##s) yet remains active over two minutes.", r->process_id, r->pid_name, r->u.resolve.qsrv.qname.c);
6187 }
6188
6189 // Note: Only primary req's have reply lists, not subordinate req's.
6190 while (r->replies) // Send queued replies
6191 {
6192 transfer_state result;
6193 if (r->replies->next)
6194 r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
6195 result = send_msg(r); // Returns t_morecoming if buffer full because client is not reading
6196 if (result == t_complete)
6197 {
6198 reply_state *fptr = r->replies;
6199 r->replies = r->replies->next;
6200 freeL("reply_state/udsserver_idle", fptr);
6201 r->time_blocked = 0; // reset failure counter after successful send
6202 r->unresponsiveness_reports = 0;
6203 continue;
6204 }
6205 else if (result == t_terminated)
6206 {
6207 LogInfo("%3d: Could not write data to client PID[%d](%s) because connection is terminated by the client", r->sd, r->process_id, r->pid_name);
6208 abort_request(r);
6209 }
6210 else if (result == t_error)
6211 {
6212 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r->sd, r->process_id, r->pid_name);
6213 LogClientInfo(r);
6214 abort_request(r);
6215 }
6216 break;
6217 }
6218
6219 if (r->replies) // If we failed to send everything, check our time_blocked timer
6220 {
6221 if (nextevent - now > mDNSPlatformOneSecond)
6222 nextevent = now + mDNSPlatformOneSecond;
6223
6224 if (mDNSStorage.SleepState != SleepState_Awake)
6225 r->time_blocked = 0;
6226 else if (!r->time_blocked)
6227 r->time_blocked = NonZeroTime(now);
6228 else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
6229 {
6230 int num = 0;
6231 struct reply_state *x = r->replies;
6232 while (x)
6233 {
6234 num++;
6235 x=x->next;
6236 }
6237 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
6238 r->sd, r->process_id, r->pid_name, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
6239 if (++r->unresponsiveness_reports >= 60)
6240 {
6241 LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r->sd, r->process_id, r->pid_name);
6242 LogClientInfo(r);
6243 abort_request(r);
6244 }
6245 }
6246 }
6247
6248 if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
6249 {
6250 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
6251 *req = r->next;
6252 freeL("request_state/udsserver_idle", r);
6253 }
6254 else
6255 req = &r->next;
6256 }
6257 return nextevent;
6258 }
6259
6260 struct CompileTimeAssertionChecks_uds_daemon
6261 {
6262 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
6263 // other overly-large structures instead of having a pointer to them, can inadvertently
6264 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
6265 char sizecheck_request_state [(sizeof(request_state) <= 3696) ? 1 : -1];
6266 char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <= 60) ? 1 : -1];
6267 char sizecheck_service_instance [(sizeof(service_instance) <= 6552) ? 1 : -1];
6268 char sizecheck_browser_t [(sizeof(browser_t) <= 1432) ? 1 : -1];
6269 char sizecheck_reply_hdr [(sizeof(reply_hdr) <= 12) ? 1 : -1];
6270 char sizecheck_reply_state [(sizeof(reply_state) <= 64) ? 1 : -1];
6271 };
6272
6273 #ifdef UNIT_TEST
6274 #include "../unittests/uds_daemon_ut.c"
6275 #endif // UNIT_TEST