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