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