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