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