]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSShared/uds_daemon.c
mDNSResponder-320.14.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 // Always set the QuestionContext to indicate that this question should be stopped
2508 // before freeing. Don't rely on "q".
2509 q2->QuestionContext = request;
2510 // If the query starts as a single label e.g., somehost, and we have search domains with .local,
2511 // queryrecord_result_callback calls this function when .local is appended to "somehost".
2512 // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
2513 // "somehost". We need to copy that information so that when we retry with a different search
2514 // domain e.g., mycompany.local, we get "somehost.mycompany.local".
2515 if (q->qnameOrig)
2516 {
2517 (*question2)->qnameOrig = mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
2518 if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!! malloc failure"); return mStatus_NoMemoryErr; }
2519 (*question2)->qnameOrig->c[0] = 0;
2520 AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
2521 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
2522 }
2523 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
2524 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
2525 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
2526 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
2527 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
2528 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
2529 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
2530 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
2531 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
2532 // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
2533 // of those, we don't want do the SOA check for the local
2534 if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname))
2535 {
2536 AssignDomainName(&q2->qname, &localdomain);
2537 q2->qtype = kDNSType_SOA;
2538 q2->LongLived = mDNSfalse;
2539 q2->ForceMCast = mDNSfalse;
2540 q2->ReturnIntermed = mDNStrue;
2541 // Don't append search domains for the .local SOA query
2542 q2->AppendSearchDomains = 0;
2543 q2->AppendLocalSearchDomains = 0;
2544 q2->RetryWithSearchDomains = mDNSfalse;
2545 q2->SearchListIndex = 0;
2546 q2->TimeoutQuestion = 0;
2547 }
2548 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
2549 err = mDNS_StartQuery(&mDNSStorage, q2);
2550 if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
2551 }
2552 return(err);
2553 }
2554 #endif // APPLE_OSX_mDNSResponder
2555
2556 // This function tries to append a search domain if valid and possible. If so, returns true.
2557 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(mDNS *const m, DNSQuestion *question, request_state *req)
2558 {
2559 int result;
2560 // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
2561 // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
2562 // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
2563 // RetryWithSearchDomains which may or may not be set.
2564 //
2565 // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
2566 // is a valid question for appending search domains, retry by appending domains
2567
2568 if (!question->SuppressQuery && question->SearchListIndex != -1 && question->AppendSearchDomains)
2569 {
2570 question->RetryWithSearchDomains = 0;
2571 result = AppendNewSearchDomain(m, question);
2572 // As long as the result is either zero or 1, we retry the question. If we exahaust the search
2573 // domains (result is zero) we try the original query (as it was before appending the search
2574 // domains) as such on the wire as a last resort if we have not tried them before. For queries
2575 // with more than one label, we have already tried them before appending search domains and
2576 // hence don't retry again
2577 if (result != -1)
2578 {
2579 mStatus err;
2580 err = mDNS_StartQuery(m, question);
2581 if (!err)
2582 {
2583 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
2584 // If the result was zero, it meant that there are no search domains and we just retried the question
2585 // as a single label and we should not retry with search domains anymore.
2586 if (!result) question->SearchListIndex = -1;
2587 return mDNStrue;
2588 }
2589 else
2590 {
2591 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
2592 // We have already stopped the query and could not restart. Reset the appropriate pointers
2593 // so that we don't call stop again when the question terminates
2594 question->QuestionContext = mDNSNULL;
2595 }
2596 }
2597 }
2598 else
2599 {
2600 LogInfo("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, question->SuppressQuery, question->SearchListIndex, question->AppendSearchDomains);
2601 }
2602 return mDNSfalse;
2603 }
2604
2605 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2606 {
2607 char name[MAX_ESCAPED_DOMAIN_NAME];
2608 request_state *req = question->QuestionContext;
2609 reply_state *rep;
2610 char *data;
2611 size_t len;
2612 DNSServiceErrorType error = kDNSServiceErr_NoError;
2613 DNSQuestion *q = mDNSNULL;
2614
2615 #if APPLE_OSX_mDNSResponder
2616 {
2617 // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
2618 // get any callbacks from the core after this.
2619 if (!req)
2620 {
2621 LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
2622 return;
2623 }
2624 if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
2625 q = &req->u.queryrecord.q;
2626 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
2627 q = &req->u.addrinfo.q4;
2628 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
2629 q = &req->u.addrinfo.q6;
2630
2631 if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
2632 {
2633 mStatus err;
2634 domainname *orig = question->qnameOrig;
2635
2636 LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
2637 mDNS_StopQuery(m, question);
2638 question->QuestionContext = mDNSNULL;
2639
2640 // We got a negative response for the SOA record indicating that .local does not exist.
2641 // But we might have other search domains (that does not end in .local) that can be
2642 // appended to this question. In that case, we want to retry the question. Otherwise,
2643 // we don't want to try this question as unicast.
2644 if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
2645 {
2646 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
2647 return;
2648 }
2649
2650 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
2651 //
2652 // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
2653 // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
2654 // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
2655 // SendAdditionalQuery as to how qnameOrig gets initialized.
2656 *question = *q;
2657 question->InterfaceID = mDNSInterface_Unicast;
2658 question->ExpectUnique = mDNStrue;
2659 question->qnameOrig = orig;
2660
2661 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
2662
2663 // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
2664 // Hence, we need to set it explicitly here.
2665 question->QuestionContext = req;
2666 err = mDNS_StartQuery(m, question);
2667 if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
2668
2669 // If we got a positive response to local SOA, then try the .local question as unicast
2670 if (answer->RecordType != kDNSRecordTypePacketNegative) return;
2671
2672 // Fall through and get the next search domain. The question is pointing at .local
2673 // and we don't want to try that. Try the next search domain. Don't try with local
2674 // search domains for the unicast question anymore.
2675 //
2676 // Note: we started the question above which will be stopped immediately (never sent on the wire)
2677 // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
2678 // question has already started.
2679 question->AppendLocalSearchDomains = 0;
2680 }
2681
2682 if (q && AddRecord && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
2683 {
2684 // If we get a negative response to the unicast query that we sent above, retry after appending search domains
2685 // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
2686 // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
2687 // To keep things simple, we handle unicast ".local" separately here.
2688 LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
2689 if (RetryQuestionWithSearchDomains(m, question, req))
2690 return;
2691 if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
2692 {
2693 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
2694 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
2695 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
2696 // in the list. We leave it disabled so that it does not hit the wire.
2697 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
2698 question->ThisQInterval = 0;
2699 }
2700 }
2701 // 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
2702 // domains to append for "q2". In all cases, fall through and deliver the response
2703 }
2704 #endif // APPLE_OSX_mDNSResponder
2705
2706 if (answer->RecordType == kDNSRecordTypePacketNegative)
2707 {
2708 // If this question needs to be timed out and we have reached the stop time, mark
2709 // the error as timeout. It is possible that we might get a negative response from an
2710 // external DNS server at the same time when this question reaches its stop time. We
2711 // can't tell the difference as there is no indication in the callback. This should
2712 // be okay as we will be timing out this query anyway.
2713 mDNS_Lock(m);
2714 if (question->TimeoutQuestion)
2715 {
2716 if ((m->timenow - question->StopTime) >= 0)
2717 {
2718 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2719 error = kDNSServiceErr_Timeout;
2720 }
2721 }
2722 mDNS_Unlock(m);
2723 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
2724 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
2725 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
2726 // server is going to assert that pretty much every single multicast name doesn't exist.
2727 //
2728 // If we are timing out this query, we need to deliver the negative answer to the application
2729 if (error != kDNSServiceErr_Timeout)
2730 {
2731 if (!answer->InterfaceID && IsLocalDomain(answer->name))
2732 {
2733 mDNSu16 qtype;
2734 // Sanity check: "q" will be set only if "question" is the .local unicast query.
2735 if (!q)
2736 {
2737 LogMsg("queryrecord_result_callback: ERROR!! answering multicast question with unicast cache record");
2738 return;
2739 }
2740 // Deliver negative response for A/AAAA if there was a positive response for AAAA/A respectively.
2741 if (question->qtype != kDNSType_A && question->qtype != kDNSType_AAAA)
2742 {
2743 LogInfo("queryrecord_result_callback:Question %##s (%s) not answering local question with negative unicast response", question->qname.c, DNSTypeName(question->qtype));
2744 return;
2745 }
2746 qtype = (question->qtype == kDNSType_A ? kDNSType_AAAA : kDNSType_A);
2747 if (!mDNS_CheckForCacheRecord(m, question, qtype))
2748 {
2749 LogInfo("queryrecord_result_callback:Question %##s (%s) not answering local question with negative unicast response (can't find positive record)", question->qname.c, DNSTypeName(question->qtype));
2750 return;
2751 }
2752 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with negative unicast response (found positive record)", question->qname.c, DNSTypeName(question->qtype));
2753 }
2754 error = kDNSServiceErr_NoSuchRecord;
2755 }
2756 AddRecord = mDNStrue;
2757 }
2758 // If we get a negative answer, try appending search domains. Don't append search domains
2759 // - if we are timing out this question
2760 // - if the negative response was received as a result of a multicast query
2761 // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
2762 if (error != kDNSServiceErr_Timeout)
2763 {
2764 if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord)
2765 {
2766 // If the original question did not end in .local, we did not send an SOA query
2767 // to figure out whether we should send an additional unicast query or not. If we just
2768 // appended .local, we need to see if we need to send an additional query. This should
2769 // normally happen just once because after we append .local, we ignore all negative
2770 // responses for .local above.
2771 LogInfo("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
2772 if (RetryQuestionWithSearchDomains(m, question, req))
2773 {
2774 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
2775 // be anywhere in the search domain list.
2776 #if APPLE_OSX_mDNSResponder
2777 mStatus err = mStatus_NoError;
2778 err = SendAdditionalQuery(question, req, err);
2779 if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
2780 #endif // APPLE_OSX_mDNSResponder
2781 return;
2782 }
2783 }
2784 }
2785
2786 ConvertDomainNameToCString(answer->name, name);
2787
2788 LogOperation("%3d: %s(%##s, %s) %s %s", req->sd,
2789 req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
2790 question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
2791
2792 len = sizeof(DNSServiceFlags); // calculate reply data length
2793 len += sizeof(mDNSu32); // interface index
2794 len += sizeof(DNSServiceErrorType);
2795 len += strlen(name) + 1;
2796 len += 3 * sizeof(mDNSu16); // type, class, rdlen
2797 len += answer->rdlength;
2798 len += sizeof(mDNSu32); // TTL
2799
2800 rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
2801
2802 rep->rhdr->flags = dnssd_htonl(AddRecord ? kDNSServiceFlagsAdd : 0);
2803 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
2804 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
2805 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
2806 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
2807 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
2808 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
2809 // should not have existed to answer this question if the corresponding interface is not valid.
2810 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
2811 rep->rhdr->error = dnssd_htonl(error);
2812
2813 data = (char *)&rep->rhdr[1];
2814
2815 put_string(name, &data);
2816 put_uint16(answer->rrtype, &data);
2817 put_uint16(answer->rrclass, &data);
2818 put_uint16(answer->rdlength, &data);
2819 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2820 // function just does a blind memory copy without regard to structures that may have holes in them.
2821 if (answer->rdlength)
2822 if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
2823 LogMsg("queryrecord_result_callback putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
2824 data += answer->rdlength;
2825 put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
2826
2827 append_reply(req, rep);
2828 // Stop the question, if we just timed out
2829 if (error == kDNSServiceErr_Timeout)
2830 {
2831 mDNS_StopQuery(m, question);
2832 // Reset the pointers so that we don't call stop on termination
2833 question->QuestionContext = mDNSNULL;
2834 }
2835 #if APPLE_OSX_mDNSResponder
2836 #if ! NO_WCF
2837 CHECK_WCF_FUNCTION(WCFIsServerRunning)
2838 {
2839 struct xucred x;
2840 socklen_t xucredlen = sizeof(x);
2841
2842 if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
2843 {
2844 if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
2845 (x.cr_version == XUCRED_VERSION))
2846 {
2847 struct sockaddr_storage addr;
2848 const RDataBody2 *const rdb = (RDataBody2 *)answer->rdata->u.data;
2849 addr.ss_len = 0;
2850 if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
2851 {
2852 if (answer->rrtype == kDNSType_A)
2853 {
2854 struct sockaddr_in *sin = (struct sockaddr_in *)&addr;
2855 sin->sin_port = 0;
2856 if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(rdb->ipv4)), answer))
2857 LogMsg("queryrecord_result_callback: WCF AF_INET putRData failed");
2858 else
2859 {
2860 addr.ss_len = sizeof (struct sockaddr_in);
2861 addr.ss_family = AF_INET;
2862 }
2863 }
2864 else if (answer->rrtype == kDNSType_AAAA)
2865 {
2866 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&addr;
2867 sin6->sin6_port = 0;
2868 if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(rdb->ipv6)), answer))
2869 LogMsg("queryrecord_result_callback: WCF AF_INET6 putRData failed");
2870 else
2871 {
2872 addr.ss_len = sizeof (struct sockaddr_in6);
2873 addr.ss_family = AF_INET6;
2874 }
2875 }
2876 if (addr.ss_len)
2877 {
2878 debugf("queryrecord_result_callback: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
2879 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
2880 {
2881 WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
2882 }
2883 }
2884 }
2885 else if (answer->rrtype == kDNSType_CNAME)
2886 {
2887 domainname cname;
2888 char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
2889 if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
2890 LogMsg("queryrecord_result_callback: WCF CNAME putRData failed");
2891 else
2892 {
2893 ConvertDomainNameToCString(&cname, cname_cstr);
2894 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
2895 {
2896 WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
2897 }
2898 }
2899 }
2900 }
2901 else my_perror("queryrecord_result_callback: ERROR: getsockopt LOCAL_PEERCRED");
2902 }
2903 }
2904 #endif
2905 #endif
2906 }
2907
2908 mDNSlocal void queryrecord_termination_callback(request_state *request)
2909 {
2910 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP",
2911 request->sd, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype));
2912 if (request->u.queryrecord.q.QuestionContext)
2913 {
2914 mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q); // no need to error check
2915 request->u.queryrecord.q.QuestionContext = mDNSNULL;
2916 }
2917 else
2918 {
2919 DNSQuestion *question = &request->u.queryrecord.q;
2920 LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2921 }
2922
2923 if (request->u.queryrecord.q.qnameOrig)
2924 {
2925 freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
2926 request->u.queryrecord.q.qnameOrig = mDNSNULL;
2927 }
2928 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)))
2929 {
2930 LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
2931 external_stop_browsing_for_service(&mDNSStorage, &request->u.queryrecord.q.qname, request->u.queryrecord.q.qtype);
2932 }
2933 if (request->u.queryrecord.q2)
2934 {
2935 if (request->u.queryrecord.q2->QuestionContext)
2936 {
2937 LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
2938 mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
2939 }
2940 else
2941 {
2942 DNSQuestion *question = request->u.queryrecord.q2;
2943 LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
2944 }
2945 if (request->u.queryrecord.q2->qnameOrig)
2946 {
2947 LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
2948 freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
2949 request->u.queryrecord.q2->qnameOrig = mDNSNULL;
2950 }
2951 freeL("queryrecord Q2", request->u.queryrecord.q2);
2952 request->u.queryrecord.q2 = mDNSNULL;
2953 }
2954 }
2955
2956 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
2957 {
2958 DNSQuestion *const q = &request->u.queryrecord.q;
2959 char name[256];
2960 mDNSu16 rrtype, rrclass;
2961 mStatus err;
2962
2963 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2964 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2965 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2966 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
2967
2968 if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
2969 rrtype = get_uint16(&request->msgptr, request->msgend);
2970 rrclass = get_uint16(&request->msgptr, request->msgend);
2971
2972 if (!request->msgptr)
2973 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2974
2975 request->flags = flags;
2976 mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
2977
2978 q->InterfaceID = InterfaceID;
2979 q->Target = zeroAddr;
2980 if (!MakeDomainNameFromDNSNameString(&q->qname, name)) return(mStatus_BadParamErr);
2981 #if 0
2982 if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains)) return (mStatus_NoError);
2983 #endif
2984 q->qtype = rrtype;
2985 q->qclass = rrclass;
2986 q->LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2987 q->ExpectUnique = mDNSfalse;
2988 q->ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2989 q->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2990 q->SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
2991 q->TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
2992 q->WakeOnResolve = 0;
2993 q->QuestionCallback = queryrecord_result_callback;
2994 q->QuestionContext = request;
2995 q->SearchListIndex = 0;
2996
2997 // Don't append search domains for fully qualified domain names including queries
2998 // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
2999 // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3000 // append search domains or not. So, we record that information in AppendSearchDomains.
3001 //
3002 // We append search domains only for queries that are a single label. If overriden using
3003 // command line argument "AlwaysAppendSearchDomains", then we do it for any query which
3004 // is not fully qualified.
3005
3006 if ((rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && name[strlen(name) - 1] != '.' &&
3007 (AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3008 {
3009 q->AppendSearchDomains = 1;
3010 q->AppendLocalSearchDomains = 1;
3011 }
3012 else
3013 {
3014 q->AppendSearchDomains = 0;
3015 q->AppendLocalSearchDomains = 0;
3016 }
3017
3018 // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3019 // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3020 // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3021 // the cache
3022 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3023 q->qnameOrig = mDNSNULL;
3024
3025 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START", request->sd, flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype));
3026 err = mDNS_StartQuery(&mDNSStorage, q);
3027 if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3028 else
3029 {
3030 request->terminate = queryrecord_termination_callback;
3031 if (q->InterfaceID == mDNSInterface_P2P || (!q->InterfaceID && SameDomainName((const domainname *)LastLabel(&q->qname), &localdomain) && (flags & kDNSServiceFlagsIncludeP2P)))
3032 {
3033 LogInfo("handle_queryrecord_request: calling external_start_browsing_for_service()");
3034 external_start_browsing_for_service(&mDNSStorage, &q->qname, q->qtype);
3035 }
3036 }
3037
3038 #if APPLE_OSX_mDNSResponder
3039 err = SendAdditionalQuery(q, request, err);
3040 #endif // APPLE_OSX_mDNSResponder
3041
3042 return(err);
3043 }
3044
3045 // ***************************************************************************
3046 #if COMPILER_LIKES_PRAGMA_MARK
3047 #pragma mark -
3048 #pragma mark - DNSServiceEnumerateDomains
3049 #endif
3050
3051 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3052 const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3053 {
3054 size_t len;
3055 reply_state *reply;
3056 char *data;
3057
3058 len = sizeof(DNSServiceFlags);
3059 len += sizeof(mDNSu32);
3060 len += sizeof(DNSServiceErrorType);
3061 len += strlen(domain) + 1;
3062
3063 reply = create_reply(enumeration_reply_op, len, request);
3064 reply->rhdr->flags = dnssd_htonl(flags);
3065 reply->rhdr->ifi = dnssd_htonl(ifi);
3066 reply->rhdr->error = dnssd_htonl(err);
3067 data = (char *)&reply->rhdr[1];
3068 put_string(domain, &data);
3069 return reply;
3070 }
3071
3072 mDNSlocal void enum_termination_callback(request_state *request)
3073 {
3074 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3075 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3076 }
3077
3078 mDNSlocal void enum_result_callback(mDNS *const m,
3079 DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3080 {
3081 char domain[MAX_ESCAPED_DOMAIN_NAME];
3082 request_state *request = question->QuestionContext;
3083 DNSServiceFlags flags = 0;
3084 reply_state *reply;
3085 (void)m; // Unused
3086
3087 if (answer->rrtype != kDNSType_PTR) return;
3088
3089 #if 0
3090 if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3091 #endif
3092
3093 // We only return add/remove events for the browse and registration lists
3094 // For the default browse and registration answers, we only give an "ADD" event
3095 if (question == &request->u.enumeration.q_default && !AddRecord) return;
3096
3097 if (AddRecord)
3098 {
3099 flags |= kDNSServiceFlagsAdd;
3100 if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3101 }
3102
3103 ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3104 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3105 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3106 // network, so we just pass kDNSServiceInterfaceIndexAny
3107 reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3108 if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3109
3110 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "Add" : "Rmv", domain);
3111
3112 append_reply(request, reply);
3113 }
3114
3115 mDNSlocal mStatus handle_enum_request(request_state *request)
3116 {
3117 mStatus err;
3118 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3119 DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3120 mDNS_DomainType t_all = reg ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse;
3121 mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3122 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3123 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3124 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3125
3126 if (!request->msgptr)
3127 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3128
3129 // allocate context structures
3130 uDNS_SetupSearchDomains(&mDNSStorage, UDNS_START_WAB_QUERY);
3131
3132 #if 0
3133 // mark which kind of enumeration we're doing so we can (de)authorize certain domains
3134 request->u.enumeration.flags = reg;
3135 #endif
3136
3137 // enumeration requires multiple questions, so we must link all the context pointers so that
3138 // necessary context can be reached from the callbacks
3139 request->u.enumeration.q_all .QuestionContext = request;
3140 request->u.enumeration.q_default.QuestionContext = request;
3141
3142 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3143 if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
3144
3145 // make the calls
3146 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
3147 (flags & kDNSServiceFlagsBrowseDomains ) ? "kDNSServiceFlagsBrowseDomains" :
3148 (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3149 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
3150 if (!err)
3151 {
3152 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
3153 if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3154 else request->terminate = enum_termination_callback;
3155 }
3156
3157 return(err);
3158 }
3159
3160 // ***************************************************************************
3161 #if COMPILER_LIKES_PRAGMA_MARK
3162 #pragma mark -
3163 #pragma mark - DNSServiceReconfirmRecord & Misc
3164 #endif
3165
3166 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
3167 {
3168 mStatus status = mStatus_BadParamErr;
3169 AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
3170 if (rr)
3171 {
3172 status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
3173 LogOperation(
3174 (status == mStatus_NoError) ?
3175 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
3176 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
3177 request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
3178 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse), status);
3179 freeL("AuthRecord/handle_reconfirm_request", rr);
3180 }
3181 return(status);
3182 }
3183
3184 mDNSlocal mStatus handle_setdomain_request(request_state *request)
3185 {
3186 char domainstr[MAX_ESCAPED_DOMAIN_NAME];
3187 domainname domain;
3188 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3189 (void)flags; // Unused
3190 if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
3191 !MakeDomainNameFromDNSNameString(&domain, domainstr))
3192 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3193
3194 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
3195 return(mStatus_NoError);
3196 }
3197
3198 typedef packedstruct
3199 {
3200 mStatus err;
3201 mDNSu32 len;
3202 mDNSu32 vers;
3203 } DaemonVersionReply;
3204
3205 mDNSlocal void handle_getproperty_request(request_state *request)
3206 {
3207 const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
3208 char prop[256];
3209 if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
3210 {
3211 LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
3212 if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
3213 {
3214 DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
3215 send_all(request->sd, (const char *)&x, sizeof(x));
3216 return;
3217 }
3218 }
3219
3220 // If we didn't recogize the requested property name, return BadParamErr
3221 send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
3222 }
3223
3224 // ***************************************************************************
3225 #if COMPILER_LIKES_PRAGMA_MARK
3226 #pragma mark -
3227 #pragma mark - DNSServiceNATPortMappingCreate
3228 #endif
3229
3230 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
3231
3232 mDNSlocal void port_mapping_termination_callback(request_state *request)
3233 {
3234 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP", request->sd,
3235 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
3236 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease);
3237 mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
3238 }
3239
3240 // Called via function pointer when we get a NAT-PMP address request or port mapping response
3241 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
3242 {
3243 request_state *request = (request_state *)n->clientContext;
3244 reply_state *rep;
3245 int replyLen;
3246 char *data;
3247
3248 if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
3249
3250 // calculate reply data length
3251 replyLen = sizeof(DNSServiceFlags);
3252 replyLen += 3 * sizeof(mDNSu32); // if index + addr + ttl
3253 replyLen += sizeof(DNSServiceErrorType);
3254 replyLen += 2 * sizeof(mDNSu16); // Internal Port + External Port
3255 replyLen += sizeof(mDNSu8); // protocol
3256
3257 rep = create_reply(port_mapping_reply_op, replyLen, request);
3258
3259 rep->rhdr->flags = dnssd_htonl(0);
3260 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
3261 rep->rhdr->error = dnssd_htonl(n->Result);
3262
3263 data = (char *)&rep->rhdr[1];
3264
3265 *data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
3266 *data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
3267 *data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
3268 *data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
3269 *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
3270 *data++ = request->u.pm.NATinfo.IntPort.b[0];
3271 *data++ = request->u.pm.NATinfo.IntPort.b[1];
3272 *data++ = request->u.pm.NATinfo.ExternalPort.b[0];
3273 *data++ = request->u.pm.NATinfo.ExternalPort.b[1];
3274 put_uint32(request->u.pm.NATinfo.Lifetime, &data);
3275
3276 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
3277 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
3278 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
3279 &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
3280
3281 append_reply(request, rep);
3282 }
3283
3284 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
3285 {
3286 mDNSu32 ttl = 0;
3287 mStatus err = mStatus_NoError;
3288
3289 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3290 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3291 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3292 mDNSu8 protocol = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
3293 (void)flags; // Unused
3294 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3295 if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
3296 else
3297 {
3298 request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
3299 request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
3300 request->u.pm.ReqExt.b[0] = *request->msgptr++;
3301 request->u.pm.ReqExt.b[1] = *request->msgptr++;
3302 ttl = get_uint32(&request->msgptr, request->msgend);
3303 }
3304
3305 if (!request->msgptr)
3306 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3307
3308 if (protocol == 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
3309 {
3310 if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
3311 }
3312 else
3313 {
3314 if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
3315 if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
3316 }
3317
3318 request->u.pm.NATinfo.Protocol = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
3319 // u.pm.NATinfo.IntPort = already set above
3320 request->u.pm.NATinfo.RequestedPort = request->u.pm.ReqExt;
3321 request->u.pm.NATinfo.NATLease = ttl;
3322 request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
3323 request->u.pm.NATinfo.clientContext = request;
3324
3325 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START", request->sd,
3326 protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease);
3327 err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
3328 if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
3329 else request->terminate = port_mapping_termination_callback;
3330
3331 return(err);
3332 }
3333
3334 // ***************************************************************************
3335 #if COMPILER_LIKES_PRAGMA_MARK
3336 #pragma mark -
3337 #pragma mark - DNSServiceGetAddrInfo
3338 #endif
3339
3340 mDNSlocal void addrinfo_termination_callback(request_state *request)
3341 {
3342 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP", request->sd, request->u.addrinfo.q4.qname.c);
3343
3344 if (request->u.addrinfo.q4.QuestionContext)
3345 {
3346 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
3347 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3348 }
3349 if (request->u.addrinfo.q4.qnameOrig)
3350 {
3351 freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
3352 request->u.addrinfo.q4.qnameOrig = mDNSNULL;
3353 }
3354 if (request->u.addrinfo.q42)
3355 {
3356 if (request->u.addrinfo.q42->QuestionContext)
3357 {
3358 LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
3359 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
3360 }
3361 if (request->u.addrinfo.q42->qnameOrig)
3362 {
3363 LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
3364 freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
3365 request->u.addrinfo.q42->qnameOrig = mDNSNULL;
3366 }
3367 freeL("addrinfo Q42", request->u.addrinfo.q42);
3368 request->u.addrinfo.q42 = mDNSNULL;
3369 }
3370
3371 if (request->u.addrinfo.q6.QuestionContext)
3372 {
3373 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
3374 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
3375 }
3376 if (request->u.addrinfo.q6.qnameOrig)
3377 {
3378 freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
3379 request->u.addrinfo.q6.qnameOrig = mDNSNULL;
3380 }
3381 if (request->u.addrinfo.q62)
3382 {
3383 if (request->u.addrinfo.q62->QuestionContext)
3384 {
3385 LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
3386 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
3387 }
3388 if (request->u.addrinfo.q62->qnameOrig)
3389 {
3390 LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
3391 freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
3392 request->u.addrinfo.q62->qnameOrig = mDNSNULL;
3393 }
3394 freeL("addrinfo Q62", request->u.addrinfo.q62);
3395 request->u.addrinfo.q62 = mDNSNULL;
3396 }
3397 }
3398
3399 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
3400 {
3401 char hostname[256];
3402 domainname d;
3403 mStatus err = 0;
3404
3405 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3406 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3407
3408 mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
3409 request->u.addrinfo.interface_id = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3410 request->u.addrinfo.flags = flags;
3411 request->u.addrinfo.protocol = get_uint32(&request->msgptr, request->msgend);
3412
3413 if (interfaceIndex && !request->u.addrinfo.interface_id) return(mStatus_BadParamErr);
3414 if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
3415
3416 if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
3417
3418 if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3419
3420 if (!MakeDomainNameFromDNSNameString(&d, hostname))
3421 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
3422
3423 #if 0
3424 if (!AuthorizedDomain(request, &d, AutoBrowseDomains)) return (mStatus_NoError);
3425 #endif
3426
3427 if (!request->u.addrinfo.protocol)
3428 {
3429 flags |= kDNSServiceFlagsSuppressUnusable;
3430 request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
3431 }
3432
3433 request->u.addrinfo.q4.InterfaceID = request->u.addrinfo.q6.InterfaceID = request->u.addrinfo.interface_id;
3434 request->u.addrinfo.q4.Target = request->u.addrinfo.q6.Target = zeroAddr;
3435 request->u.addrinfo.q4.qname = request->u.addrinfo.q6.qname = d;
3436 request->u.addrinfo.q4.qclass = request->u.addrinfo.q6.qclass = kDNSServiceClass_IN;
3437 request->u.addrinfo.q4.LongLived = request->u.addrinfo.q6.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
3438 request->u.addrinfo.q4.ExpectUnique = request->u.addrinfo.q6.ExpectUnique = mDNSfalse;
3439 request->u.addrinfo.q4.ForceMCast = request->u.addrinfo.q6.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
3440 request->u.addrinfo.q4.ReturnIntermed = request->u.addrinfo.q6.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3441 request->u.addrinfo.q4.SuppressUnusable = request->u.addrinfo.q6.SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
3442 request->u.addrinfo.q4.TimeoutQuestion = request->u.addrinfo.q6.TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
3443 request->u.addrinfo.q4.WakeOnResolve = request->u.addrinfo.q6.WakeOnResolve = 0;
3444 request->u.addrinfo.q4.qnameOrig = request->u.addrinfo.q6.qnameOrig = mDNSNULL;
3445
3446 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
3447 {
3448 request->u.addrinfo.q4.qtype = kDNSServiceType_A;
3449 request->u.addrinfo.q4.SearchListIndex = 0;
3450
3451 // We append search domains only for queries that are a single label. If overriden using
3452 // command line argument "AlwaysAppendSearchDomains", then we do it for any query which
3453 // is not fully qualified.
3454 if (hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
3455 {
3456 request->u.addrinfo.q4.AppendSearchDomains = 1;
3457 request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
3458 }
3459 else
3460 {
3461 request->u.addrinfo.q4.AppendSearchDomains = 0;
3462 request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
3463 }
3464 request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
3465 request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
3466 request->u.addrinfo.q4.QuestionContext = request;
3467 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
3468 if (err != mStatus_NoError)
3469 {
3470 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
3471 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3472 }
3473 #if APPLE_OSX_mDNSResponder
3474 err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
3475 #endif // APPLE_OSX_mDNSResponder
3476 }
3477
3478 if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6))
3479 {
3480 request->u.addrinfo.q6.qtype = kDNSServiceType_AAAA;
3481 request->u.addrinfo.q6.SearchListIndex = 0;
3482 if (hostname[strlen(hostname) - 1] != '.' && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
3483 {
3484 request->u.addrinfo.q6.AppendSearchDomains = 1;
3485 request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
3486 }
3487 else
3488 {
3489 request->u.addrinfo.q6.AppendSearchDomains = 0;
3490 request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
3491 }
3492 request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
3493 request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
3494 request->u.addrinfo.q6.QuestionContext = request;
3495 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
3496 if (err != mStatus_NoError)
3497 {
3498 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
3499 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
3500 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
3501 {
3502 // If we started a query for IPv4, we need to cancel it
3503 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
3504 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
3505 }
3506 }
3507 #if APPLE_OSX_mDNSResponder
3508 err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
3509 #endif // APPLE_OSX_mDNSResponder
3510 }
3511
3512 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START",
3513 request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c);
3514
3515 if (!err) request->terminate = addrinfo_termination_callback;
3516
3517 return(err);
3518 }
3519
3520 // ***************************************************************************
3521 #if COMPILER_LIKES_PRAGMA_MARK
3522 #pragma mark -
3523 #pragma mark - Main Request Handler etc.
3524 #endif
3525
3526 mDNSlocal request_state *NewRequest(void)
3527 {
3528 request_state **p = &all_requests;
3529 while (*p) p=&(*p)->next;
3530 *p = mallocL("request_state", sizeof(request_state));
3531 if (!*p) FatalError("ERROR: malloc");
3532 mDNSPlatformMemZero(*p, sizeof(request_state));
3533 return(*p);
3534 }
3535
3536 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
3537 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
3538 mDNSlocal void read_msg(request_state *req)
3539 {
3540 if (req->ts == t_terminated || req->ts == t_error)
3541 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
3542
3543 if (req->ts == t_complete) // this must be death or something is wrong
3544 {
3545 char buf[4]; // dummy for death notification
3546 int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
3547 if (!nread) { req->ts = t_terminated; return; }
3548 if (nread < 0) goto rerror;
3549 LogMsg("%3d: ERROR: read data from a completed request", req->sd);
3550 req->ts = t_error;
3551 return;
3552 }
3553
3554 if (req->ts != t_morecoming)
3555 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
3556
3557 if (req->hdr_bytes < sizeof(ipc_msg_hdr))
3558 {
3559 mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
3560 int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
3561 if (nread == 0) { req->ts = t_terminated; return; }
3562 if (nread < 0) goto rerror;
3563 req->hdr_bytes += nread;
3564 if (req->hdr_bytes > sizeof(ipc_msg_hdr))
3565 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
3566
3567 // only read data if header is complete
3568 if (req->hdr_bytes == sizeof(ipc_msg_hdr))
3569 {
3570 ConvertHeaderBytes(&req->hdr);
3571 if (req->hdr.version != VERSION)
3572 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
3573
3574 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
3575 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
3576 // for other overhead, this means any message above 70kB is definitely bogus.
3577 if (req->hdr.datalen > 70000)
3578 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
3579 req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
3580 if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
3581 req->msgptr = req->msgbuf;
3582 req->msgend = req->msgbuf + req->hdr.datalen;
3583 mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
3584 }
3585 }
3586
3587 // If our header is complete, but we're still needing more body data, then try to read it now
3588 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
3589 // Any time we need to get the error return socket we know we'll have at least one data byte
3590 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
3591 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
3592 {
3593 mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
3594 int nread;
3595 #if !defined(_WIN32)
3596 struct iovec vec = { req->msgbuf + req->data_bytes, nleft }; // Tell recvmsg where we want the bytes put
3597 struct msghdr msg;
3598 struct cmsghdr *cmsg;
3599 char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
3600 msg.msg_name = 0;
3601 msg.msg_namelen = 0;
3602 msg.msg_iov = &vec;
3603 msg.msg_iovlen = 1;
3604 msg.msg_control = cbuf;
3605 msg.msg_controllen = sizeof(cbuf);
3606 msg.msg_flags = 0;
3607 nread = recvmsg(req->sd, &msg, 0);
3608 #else
3609 nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
3610 #endif
3611 if (nread == 0) { req->ts = t_terminated; return; }
3612 if (nread < 0) goto rerror;
3613 req->data_bytes += nread;
3614 if (req->data_bytes > req->hdr.datalen)
3615 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
3616 #if !defined(_WIN32)
3617 cmsg = CMSG_FIRSTHDR(&msg);
3618 #if DEBUG_64BIT_SCM_RIGHTS
3619 LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf), sizeof(cbuf), SOL_SOCKET, SCM_RIGHTS);
3620 LogMsg("%3d: Got %d %d %d %d", req->sd, msg.msg_controllen, cmsg->cmsg_len, cmsg->cmsg_level, cmsg->cmsg_type);
3621 #endif // DEBUG_64BIT_SCM_RIGHTS
3622 if (msg.msg_controllen == sizeof(cbuf) &&
3623 cmsg->cmsg_len == CMSG_LEN(sizeof(dnssd_sock_t)) &&
3624 cmsg->cmsg_level == SOL_SOCKET &&
3625 cmsg->cmsg_type == SCM_RIGHTS)
3626 {
3627 #if APPLE_OSX_mDNSResponder
3628 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3629 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3630 // and it's convenient to repurpose the existing fd-passing code here for that task
3631 if (req->hdr.op == send_bpf)
3632 {
3633 dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
3634 LogOperation("%3d: Got BPF %d", req->sd, x);
3635 mDNSPlatformReceiveBPF_fd(&mDNSStorage, x);
3636 }
3637 else
3638 #endif // APPLE_OSX_mDNSResponder
3639 req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
3640 #if DEBUG_64BIT_SCM_RIGHTS
3641 LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
3642 #endif // DEBUG_64BIT_SCM_RIGHTS
3643 if (req->data_bytes < req->hdr.datalen)
3644 {
3645 LogMsg("%3d: Client sent error socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3646 req->sd, req->errsd, req->data_bytes, req->hdr.datalen);
3647 req->ts = t_error;
3648 return;
3649 }
3650 }
3651 #endif
3652 }
3653
3654 // If our header and data are both complete, see if we need to make our separate error return socket
3655 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
3656 {
3657 if (req->terminate && req->hdr.op != cancel_request)
3658 {
3659 dnssd_sockaddr_t cliaddr;
3660 #if defined(USE_TCP_LOOPBACK)
3661 mDNSOpaque16 port;
3662 u_long opt = 1;
3663 port.b[0] = req->msgptr[0];
3664 port.b[1] = req->msgptr[1];
3665 req->msgptr += 2;
3666 cliaddr.sin_family = AF_INET;
3667 cliaddr.sin_port = port.NotAnInteger;
3668 cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
3669 #else
3670 char ctrl_path[MAX_CTLPATH];
3671 get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH); // path is first element in message buffer
3672 mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
3673 cliaddr.sun_family = AF_LOCAL;
3674 mDNSPlatformStrCopy(cliaddr.sun_path, ctrl_path);
3675 // If the error return path UDS name is empty string, that tells us
3676 // that this is a new version of the library that's going to pass us
3677 // the error return path socket via sendmsg/recvmsg
3678 if (ctrl_path[0] == 0)
3679 {
3680 if (req->errsd == req->sd)
3681 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
3682 goto got_errfd;
3683 }
3684 #endif
3685
3686 req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
3687 if (!dnssd_SocketValid(req->errsd)) { my_perror("ERROR: socket"); req->ts = t_error; return; }
3688
3689 if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
3690 {
3691 #if !defined(USE_TCP_LOOPBACK)
3692 struct stat sb;
3693 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
3694 req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
3695 if (stat(cliaddr.sun_path, &sb) < 0)
3696 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
3697 else
3698 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);
3699 #endif
3700 req->ts = t_error;
3701 return;
3702 }
3703
3704 #if !defined(USE_TCP_LOOPBACK)
3705 got_errfd:
3706 #endif
3707 LogOperation("%3d: Error socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
3708 #if defined(_WIN32)
3709 if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
3710 #else
3711 if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
3712 #endif
3713 {
3714 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
3715 req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3716 req->ts = t_error;
3717 return;
3718 }
3719 }
3720
3721 req->ts = t_complete;
3722 }
3723
3724 return;
3725
3726 rerror:
3727 if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
3728 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3729 req->ts = t_error;
3730 }
3731
3732 #define RecordOrientedOp(X) \
3733 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3734
3735 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3736 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3737
3738 mDNSlocal void request_callback(int fd, short filter, void *info)
3739 {
3740 mStatus err = 0;
3741 request_state *req = info;
3742 mDNSs32 min_size = sizeof(DNSServiceFlags);
3743 (void)fd; // Unused
3744 (void)filter; // Unused
3745
3746 for (;;)
3747 {
3748 read_msg(req);
3749 if (req->ts == t_morecoming) return;
3750 if (req->ts == t_terminated || req->ts == t_error) { AbortUnlinkAndFree(req); return; }
3751 if (req->ts != t_complete) { LogMsg("req->ts %d != t_complete", req->ts); AbortUnlinkAndFree(req); return; }
3752
3753 if (req->hdr.version != VERSION)
3754 {
3755 LogMsg("ERROR: client version %d incompatible with daemon version %d", req->hdr.version, VERSION);
3756 AbortUnlinkAndFree(req);
3757 return;
3758 }
3759
3760 switch(req->hdr.op) // Interface + other data
3761 {
3762 case connection_request: min_size = 0; break;
3763 case reg_service_request: min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3764 case add_record_request: min_size += 4 /* type, rdlen */ + 4 /* ttl */; break;
3765 case update_record_request: min_size += 2 /* rdlen */ + 4 /* ttl */; break;
3766 case remove_record_request: break;
3767 case browse_request: min_size += sizeof(mDNSu32) + 2 /* type, domain */; break;
3768 case resolve_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
3769 case query_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 4 /* type, class*/; break;
3770 case enumeration_request: min_size += sizeof(mDNSu32); break;
3771 case reg_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
3772 case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */; break;
3773 case setdomain_request: min_size += 1 /* domain */; break;
3774 case getproperty_request: min_size = 2; break;
3775 case port_mapping_request: min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
3776 case addrinfo_request: min_size += sizeof(mDNSu32) + 4 /* v4/v6 */ + 1 /* hostname */; break;
3777 case send_bpf: // Same as cancel_request below
3778 case cancel_request: min_size = 0; break;
3779 default: LogMsg("ERROR: validate_message - unsupported req type: %d", req->hdr.op); min_size = -1; break;
3780 }
3781
3782 if ((mDNSs32)req->data_bytes < min_size)
3783 { LogMsg("Invalid message %d bytes; min for %d is %d", req->data_bytes, req->hdr.op, min_size); AbortUnlinkAndFree(req); return; }
3784
3785 if (LightweightOp(req->hdr.op) && !req->terminate)
3786 { LogMsg("Reg/Add/Update/Remove %d require existing connection", req->hdr.op); AbortUnlinkAndFree(req); return; }
3787
3788 // check if client wants silent operation
3789 if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
3790
3791 // If req->terminate is already set, this means this operation is sharing an existing connection
3792 if (req->terminate && !LightweightOp(req->hdr.op))
3793 {
3794 request_state *newreq = NewRequest();
3795 newreq->primary = req;
3796 newreq->sd = req->sd;
3797 newreq->errsd = req->errsd;
3798 newreq->uid = req->uid;
3799 newreq->hdr = req->hdr;
3800 newreq->msgbuf = req->msgbuf;
3801 newreq->msgptr = req->msgptr;
3802 newreq->msgend = req->msgend;
3803 req = newreq;
3804 }
3805
3806 // If we're shutting down, don't allow new client requests
3807 // We do allow "cancel" and "getproperty" during shutdown
3808 if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
3809 {
3810 err = mStatus_ServiceNotRunning;
3811 }
3812 else switch(req->hdr.op)
3813 {
3814 // These are all operations that have their own first-class request_state object
3815 case connection_request: LogOperation("%3d: DNSServiceCreateConnection START", req->sd);
3816 req->terminate = connection_termination; break;
3817 case resolve_request: err = handle_resolve_request (req); break;
3818 case query_request: err = handle_queryrecord_request (req); break;
3819 case browse_request: err = handle_browse_request (req); break;
3820 case reg_service_request: err = handle_regservice_request (req); break;
3821 case enumeration_request: err = handle_enum_request (req); break;
3822 case reconfirm_record_request: err = handle_reconfirm_request (req); break;
3823 case setdomain_request: err = handle_setdomain_request (req); break;
3824 case getproperty_request: handle_getproperty_request (req); break;
3825 case port_mapping_request: err = handle_port_mapping_request(req); break;
3826 case addrinfo_request: err = handle_addrinfo_request (req); break;
3827 case send_bpf: /* Do nothing for send_bpf */ break;
3828
3829 // These are all operations that work with an existing request_state object
3830 case reg_record_request: err = handle_regrecord_request (req); break;
3831 case add_record_request: err = handle_add_request (req); break;
3832 case update_record_request: err = handle_update_request (req); break;
3833 case remove_record_request: err = handle_removerecord_request(req); break;
3834 case cancel_request: handle_cancel_request (req); break;
3835 default: LogMsg("%3d: ERROR: Unsupported UDS req: %d", req->sd, req->hdr.op);
3836 }
3837
3838 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3839 if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
3840
3841 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3842 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3843 if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf)
3844 {
3845 const mStatus err_netorder = dnssd_htonl(err);
3846 send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
3847 if (req->errsd != req->sd)
3848 {
3849 LogOperation("%3d: Error socket %d closed %08X %08X (%d)",
3850 req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
3851 dnssd_close(req->errsd);
3852 req->errsd = req->sd;
3853 // Also need to reset the parent's errsd, if this is a subordinate operation
3854 if (req->primary) req->primary->errsd = req->primary->sd;
3855 }
3856 }
3857
3858 // Reset ready to accept the next req on this pipe
3859 if (req->primary) req = req->primary;
3860 req->ts = t_morecoming;
3861 req->hdr_bytes = 0;
3862 req->data_bytes = 0;
3863 req->msgbuf = mDNSNULL;
3864 req->msgptr = mDNSNULL;
3865 req->msgend = 0;
3866 }
3867 }
3868
3869 mDNSlocal void connect_callback(int fd, short filter, void *info)
3870 {
3871 dnssd_sockaddr_t cliaddr;
3872 dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
3873 dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
3874 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3875 unsigned long optval = 1;
3876 #endif
3877
3878 (void)filter; // Unused
3879 (void)info; // Unused
3880
3881 if (!dnssd_SocketValid(sd))
3882 {
3883 if (dnssd_errno != dnssd_EWOULDBLOCK) my_perror("ERROR: accept");
3884 return;
3885 }
3886
3887 #ifdef SO_NOSIGPIPE
3888 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3889 if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
3890 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
3891 #endif
3892
3893 #if defined(_WIN32)
3894 if (ioctlsocket(sd, FIONBIO, &optval) != 0)
3895 #else
3896 if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
3897 #endif
3898 {
3899 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3900 dnssd_close(sd);
3901 return;
3902 }
3903 else
3904 {
3905 request_state *request = NewRequest();
3906 request->ts = t_morecoming;
3907 request->sd = sd;
3908 request->errsd = sd;
3909 #if APPLE_OSX_mDNSResponder
3910 struct xucred x;
3911 socklen_t xucredlen = sizeof(x);
3912 if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION) request->uid = x.cr_uid;
3913 else my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
3914 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
3915 #endif // APPLE_OSX_mDNSResponder
3916 LogOperation("%3d: Adding FD for uid %u", request->sd, request->uid);
3917 udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
3918 }
3919 }
3920
3921 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
3922 {
3923 #if defined(SO_NP_EXTENSIONS)
3924 struct so_np_extensions sonpx;
3925 socklen_t optlen = sizeof(struct so_np_extensions);
3926 sonpx.npx_flags = SONPX_SETOPTSHUT;
3927 sonpx.npx_mask = SONPX_SETOPTSHUT;
3928 if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
3929 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
3930 #endif
3931 #if defined(_WIN32)
3932 // SEH: do we even need to do this on windows?
3933 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
3934 u_long opt = 1;
3935 if (ioctlsocket(skt, FIONBIO, &opt) != 0)
3936 #else
3937 if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
3938 #endif
3939 {
3940 my_perror("ERROR: could not set listen socket to non-blocking mode");
3941 return mDNSfalse;
3942 }
3943
3944 if (listen(skt, LISTENQ) != 0)
3945 {
3946 my_perror("ERROR: could not listen on listen socket");
3947 return mDNSfalse;
3948 }
3949
3950 if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
3951 {
3952 my_perror("ERROR: could not add listen socket to event loop");
3953 return mDNSfalse;
3954 }
3955 else LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
3956
3957 return mDNStrue;
3958 }
3959
3960 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
3961 {
3962 dnssd_sockaddr_t laddr;
3963 int ret;
3964 mDNSu32 i = 0;
3965
3966 LogInfo("udsserver_init");
3967
3968 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
3969 if (PID_FILE[0])
3970 {
3971 FILE *fp = fopen(PID_FILE, "w");
3972 if (fp != NULL)
3973 {
3974 fprintf(fp, "%d\n", getpid());
3975 fclose(fp);
3976 }
3977 }
3978
3979 if (skts)
3980 {
3981 for (i = 0; i < count; i++)
3982 if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
3983 goto error;
3984 }
3985 else
3986 {
3987 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
3988 if (!dnssd_SocketValid(listenfd))
3989 {
3990 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
3991 goto error;
3992 }
3993
3994 mDNSPlatformMemZero(&laddr, sizeof(laddr));
3995
3996 #if defined(USE_TCP_LOOPBACK)
3997 {
3998 laddr.sin_family = AF_INET;
3999 laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
4000 laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4001 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
4002 if (ret < 0)
4003 {
4004 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4005 goto error;
4006 }
4007 }
4008 #else
4009 {
4010 mode_t mask = umask(0);
4011 unlink(MDNS_UDS_SERVERPATH); // OK if this fails
4012 laddr.sun_family = AF_LOCAL;
4013 #ifndef NOT_HAVE_SA_LEN
4014 // According to Stevens (section 3.2), there is no portable way to
4015 // determine whether sa_len is defined on a particular platform.
4016 laddr.sun_len = sizeof(struct sockaddr_un);
4017 #endif
4018 mDNSPlatformStrCopy(laddr.sun_path, MDNS_UDS_SERVERPATH);
4019 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
4020 umask(mask);
4021 if (ret < 0)
4022 {
4023 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4024 goto error;
4025 }
4026 }
4027 #endif
4028
4029 if (!uds_socket_setup(listenfd)) goto error;
4030 }
4031
4032 #if !defined(PLATFORM_NO_RLIMIT)
4033 {
4034 // Set maximum number of open file descriptors
4035 #define MIN_OPENFILES 10240
4036 struct rlimit maxfds, newfds;
4037
4038 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
4039 // you have to get and set rlimits once before getrlimit will return sensible values
4040 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4041 if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4042
4043 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4044 newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
4045 newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
4046 if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
4047 if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4048
4049 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4050 debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
4051 debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
4052 }
4053 #endif
4054
4055 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
4056 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
4057 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
4058 mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
4059 mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
4060
4061 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
4062 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
4063 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
4064 AddAutoBrowseDomain(0, &localdomain);
4065
4066 udsserver_handle_configchange(&mDNSStorage);
4067 return 0;
4068
4069 error:
4070
4071 my_perror("ERROR: udsserver_init");
4072 return -1;
4073 }
4074
4075 mDNSexport int udsserver_exit(void)
4076 {
4077 // Cancel all outstanding client requests
4078 while (all_requests) AbortUnlinkAndFree(all_requests);
4079
4080 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
4081 // created in udsserver_init, and others we created as a result of reading local configuration data
4082 while (LocalDomainEnumRecords)
4083 {
4084 ARListElem *rem = LocalDomainEnumRecords;
4085 LocalDomainEnumRecords = LocalDomainEnumRecords->next;
4086 mDNS_Deregister(&mDNSStorage, &rem->ar);
4087 }
4088
4089 // If the launching environment created no listening socket,
4090 // that means we created it ourselves, so we should clean it up on exit
4091 if (dnssd_SocketValid(listenfd))
4092 {
4093 dnssd_close(listenfd);
4094 #if !defined(USE_TCP_LOOPBACK)
4095 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
4096 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
4097 // It would be nice if we could find a solution to this problem
4098 if (unlink(MDNS_UDS_SERVERPATH))
4099 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
4100 #endif
4101 }
4102
4103 if (PID_FILE[0]) unlink(PID_FILE);
4104
4105 return 0;
4106 }
4107
4108 mDNSlocal void LogClientInfo(mDNS *const m, const request_state *req)
4109 {
4110 char prefix[16];
4111 if (req->primary) mDNS_snprintf(prefix, sizeof(prefix), " -> ");
4112 else mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
4113
4114 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4115
4116 if (!req->terminate)
4117 LogMsgNoIdent("%s No operation yet on this socket", prefix);
4118 else if (req->terminate == connection_termination)
4119 {
4120 int num_records = 0, num_ops = 0;
4121 const registered_record_entry *p;
4122 const request_state *r;
4123 for (p = req->u.reg_recs; p; p=p->next) num_records++;
4124 for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
4125 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s", prefix,
4126 num_records, num_records != 1 ? "s" : "",
4127 num_ops, num_ops != 1 ? "s" : "");
4128 for (p = req->u.reg_recs; p; p=p->next)
4129 LogMsgNoIdent(" -> DNSServiceRegisterRecord %3d %s", p->key, ARDisplayString(m, p->rr));
4130 for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(m, r);
4131 }
4132 else if (req->terminate == regservice_termination_callback)
4133 {
4134 service_instance *ptr;
4135 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
4136 LogMsgNoIdent("%s DNSServiceRegister %##s %u/%u",
4137 (ptr == req->u.servicereg.instances) ? prefix : " ",
4138 ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port), SRS_PORT(&ptr->srs));
4139 }
4140 else if (req->terminate == browse_termination_callback)
4141 {
4142 browser_t *blist;
4143 for (blist = req->u.browser.browsers; blist; blist = blist->next)
4144 LogMsgNoIdent("%s DNSServiceBrowse %##s", (blist == req->u.browser.browsers) ? prefix : " ", blist->q.qname.c);
4145 }
4146 else if (req->terminate == resolve_termination_callback)
4147 LogMsgNoIdent("%s DNSServiceResolve %##s", prefix, req->u.resolve.qsrv.qname.c);
4148 else if (req->terminate == queryrecord_termination_callback)
4149 LogMsgNoIdent("%s DNSServiceQueryRecord %##s (%s)", prefix, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype));
4150 else if (req->terminate == enum_termination_callback)
4151 LogMsgNoIdent("%s DNSServiceEnumerateDomains %##s", prefix, req->u.enumeration.q_all.qname.c);
4152 else if (req->terminate == port_mapping_termination_callback)
4153 LogMsgNoIdent("%s DNSServiceNATPortMapping %.4a %s%s Int %d Req %d Ext %d Req TTL %d Granted TTL %d",
4154 prefix,
4155 &req->u.pm.NATinfo.ExternalAddress,
4156 req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : " ",
4157 req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : " ",
4158 mDNSVal16(req->u.pm.NATinfo.IntPort),
4159 mDNSVal16(req->u.pm.ReqExt),
4160 mDNSVal16(req->u.pm.NATinfo.ExternalPort),
4161 req->u.pm.NATinfo.NATLease,
4162 req->u.pm.NATinfo.Lifetime);
4163 else if (req->terminate == addrinfo_termination_callback)
4164 LogMsgNoIdent("%s DNSServiceGetAddrInfo %s%s %##s", prefix,
4165 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
4166 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
4167 req->u.addrinfo.q4.qname.c);
4168 else
4169 LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
4170 }
4171
4172 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
4173 {
4174 switch (rtype)
4175 {
4176 case kDNSRecordTypeUnregistered: return ("Unregistered ");
4177 case kDNSRecordTypeDeregistering: return ("Deregistering");
4178 case kDNSRecordTypeUnique: return ("Unique ");
4179 case kDNSRecordTypeAdvisory: return ("Advisory ");
4180 case kDNSRecordTypeShared: return ("Shared ");
4181 case kDNSRecordTypeVerified: return ("Verified ");
4182 case kDNSRecordTypeKnownUnique: return ("KnownUnique ");
4183 default: return("Unknown");
4184 }
4185 }
4186
4187 mDNSlocal void LogEtcHosts(mDNS *const m)
4188 {
4189 mDNSBool showheader = mDNStrue;
4190 const AuthRecord *ar;
4191 mDNSu32 slot;
4192 AuthGroup *ag;
4193 int count = 0;
4194 int authslot = 0;
4195 mDNSBool truncated = 0;
4196
4197 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4198 {
4199 if (m->rrauth.rrauth_hash[slot]) authslot++;
4200 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4201 for (ar = ag->members; ar; ar = ar->next)
4202 {
4203 if (ar->RecordCallback != FreeEtcHosts) continue;
4204 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
4205
4206 // Print a maximum of 50 records
4207 if (count++ >= 50) { truncated = mDNStrue; continue; }
4208 if (ar->ARType == AuthRecordLocalOnly)
4209 {
4210 if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
4211 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4212 else
4213 {
4214 mDNSu32 scopeid = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
4215 LogMsgNoIdent(" %s %u %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
4216 }
4217 }
4218 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4219 }
4220 }
4221
4222 if (showheader) LogMsgNoIdent("<None>");
4223 else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
4224 }
4225
4226 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
4227 {
4228 mDNSBool showheader = mDNStrue;
4229 const AuthRecord *ar;
4230 mDNSu32 slot;
4231 AuthGroup *ag;
4232
4233 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
4234 {
4235 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
4236 for (ar = ag->members; ar; ar = ar->next)
4237 {
4238 if (ar->RecordCallback == FreeEtcHosts) continue;
4239 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
4240
4241 // Print a maximum of 400 records
4242 if (ar->ARType == AuthRecordLocalOnly)
4243 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4244 else if (ar->ARType == AuthRecordP2P)
4245 LogMsgNoIdent(" %s PP %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
4246 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4247 }
4248 }
4249
4250 if (showheader) LogMsgNoIdent("<None>");
4251 }
4252
4253 mDNSlocal void LogAuthRecords(mDNS *const m, const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
4254 {
4255 mDNSBool showheader = mDNStrue;
4256 const AuthRecord *ar;
4257 OwnerOptData owner = zeroOwner;
4258 for (ar = ResourceRecords; ar; ar=ar->next)
4259 {
4260 const char *const ifname = InterfaceNameForID(m, ar->resrec.InterfaceID);
4261 if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
4262 {
4263 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" Int Next Expire State"); }
4264 if (proxy) (*proxy)++;
4265 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
4266 {
4267 owner = ar->WakeUp;
4268 if (owner.password.l[0])
4269 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
4270 else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
4271 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner.HMAC, &owner.IMAC, owner.seq);
4272 else
4273 LogMsgNoIdent("Proxying for %.6a seq %d", &owner.HMAC, owner.seq);
4274 }
4275 if (AuthRecord_uDNS(ar))
4276 LogMsgNoIdent("%7d %7d %7d %7d %s",
4277 ar->ThisAPInterval / mDNSPlatformOneSecond,
4278 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
4279 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
4280 ar->state, ARDisplayString(m, ar));
4281 else if (ar->ARType == AuthRecordLocalOnly)
4282 LogMsgNoIdent(" LO %s", ARDisplayString(m, ar));
4283 else if (ar->ARType == AuthRecordP2P)
4284 LogMsgNoIdent(" PP %s", ARDisplayString(m, ar));
4285 else
4286 LogMsgNoIdent("%7d %7d %7d %7s %s",
4287 ar->ThisAPInterval / mDNSPlatformOneSecond,
4288 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
4289 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
4290 ifname ? ifname : "ALL",
4291 ARDisplayString(m, ar));
4292 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4293 }
4294 }
4295 if (showheader) LogMsgNoIdent("<None>");
4296 }
4297
4298 mDNSexport void udsserver_info(mDNS *const m)
4299 {
4300 const mDNSs32 now = mDNS_TimeNow(m);
4301 mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
4302 int ProxyA = 0, ProxyD = 0;
4303 const CacheGroup *cg;
4304 const CacheRecord *cr;
4305 const DNSQuestion *q;
4306 const DNameListElem *d;
4307 const SearchListElem *s;
4308
4309 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
4310
4311 LogMsgNoIdent("------------ Cache -------------");
4312 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
4313 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4314 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
4315 {
4316 CacheUsed++; // Count one cache entity for the CacheGroup object
4317 for (cr = cg->members; cr; cr=cr->next)
4318 {
4319 const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
4320 const char *ifname;
4321 mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
4322 if (!InterfaceID && cr->resrec.rDNSServer)
4323 InterfaceID = cr->resrec.rDNSServer->interface;
4324 ifname = InterfaceNameForID(m, InterfaceID);
4325 CacheUsed++;
4326 if (cr->CRActiveQuestion) CacheActive++;
4327 LogMsgNoIdent("%3d %s%8ld %-7s%s %-6s%s",
4328 slot,
4329 cr->CRActiveQuestion ? "*" : " ",
4330 remain,
4331 ifname ? ifname : "-U-",
4332 (cr->resrec.RecordType == kDNSRecordTypePacketNegative) ? "-" :
4333 (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
4334 DNSTypeName(cr->resrec.rrtype),
4335 CRDisplayString(m, cr));
4336 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4337 }
4338 }
4339
4340 if (m->rrcache_totalused != CacheUsed)
4341 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
4342 if (m->rrcache_active != CacheActive)
4343 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
4344 LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed, CacheActive);
4345
4346 LogMsgNoIdent("--------- Auth Records ---------");
4347 LogAuthRecords(m, now, m->ResourceRecords, mDNSNULL);
4348
4349 LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
4350 LogLocalOnlyAuthRecords(m);
4351
4352 LogMsgNoIdent("--------- /etc/hosts ---------");
4353 LogEtcHosts(m);
4354
4355 LogMsgNoIdent("------ Duplicate Records -------");
4356 LogAuthRecords(m, now, m->DuplicateRecords, mDNSNULL);
4357
4358 LogMsgNoIdent("----- Auth Records Proxied -----");
4359 LogAuthRecords(m, now, m->ResourceRecords, &ProxyA);
4360
4361 LogMsgNoIdent("-- Duplicate Records Proxied ---");
4362 LogAuthRecords(m, now, m->DuplicateRecords, &ProxyD);
4363
4364 LogMsgNoIdent("---------- Questions -----------");
4365 if (!m->Questions) LogMsgNoIdent("<None>");
4366 else
4367 {
4368 CacheUsed = 0;
4369 CacheActive = 0;
4370 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
4371 for (q = m->Questions; q; q=q->next)
4372 {
4373 mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
4374 mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
4375 char *ifname = InterfaceNameForID(m, q->InterfaceID);
4376 CacheUsed++;
4377 if (q->ThisQInterval) CacheActive++;
4378 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s",
4379 i, n,
4380 ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
4381 mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
4382 PrivateQuery(q) ? "P" : " ",
4383 q->CurrentAnswers, q->validDNSServers.l[1], q->validDNSServers.l[0], q, q->DuplicateOf,
4384 q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
4385 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4386 }
4387 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
4388 }
4389
4390 LogMsgNoIdent("----- Local-Only Questions -----");
4391 if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
4392 else for (q = m->LocalOnlyQuestions; q; q=q->next)
4393 LogMsgNoIdent(" %5d %-6s%##s%s",
4394 q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
4395
4396 LogMsgNoIdent("---- Active Client Requests ----");
4397 if (!all_requests) LogMsgNoIdent("<None>");
4398 else
4399 {
4400 const request_state *req, *r;
4401 for (req = all_requests; req; req=req->next)
4402 {
4403 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
4404 {
4405 for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
4406 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
4407 }
4408 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
4409 LogClientInfo(m, req);
4410 foundparent:;
4411 }
4412 }
4413
4414 LogMsgNoIdent("-------- NAT Traversals --------");
4415 if (!m->NATTraversals) LogMsgNoIdent("<None>");
4416 else
4417 {
4418 const NATTraversalInfo *nat;
4419 for (nat = m->NATTraversals; nat; nat=nat->next)
4420 {
4421 if (nat->Protocol)
4422 LogMsgNoIdent("%p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d",
4423 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
4424 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
4425 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
4426 nat->retryInterval / mDNSPlatformOneSecond,
4427 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0);
4428 else
4429 LogMsgNoIdent("%p Address Request Retry %5d Interval %5d", nat,
4430 (m->retryGetAddr - now) / mDNSPlatformOneSecond,
4431 m->retryIntervalGetAddr / mDNSPlatformOneSecond);
4432 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000);
4433 }
4434 }
4435
4436 LogMsgNoIdent("--------- AuthInfoList ---------");
4437 if (!m->AuthInfoList) LogMsgNoIdent("<None>");
4438 else
4439 {
4440 const DomainAuthInfo *a;
4441 for (a = m->AuthInfoList; a; a = a->next)
4442 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 : "");
4443 }
4444
4445 #if APPLE_OSX_mDNSResponder
4446 LogMsgNoIdent("--------- TunnelClients --------");
4447 if (!m->TunnelClients) LogMsgNoIdent("<None>");
4448 else
4449 {
4450 const ClientTunnel *c;
4451 for (c = m->TunnelClients; c; c = c->next)
4452 LogMsgNoIdent("%s %##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
4453 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);
4454 }
4455 #endif // APPLE_OSX_mDNSResponder
4456
4457 LogMsgNoIdent("---------- Misc State ----------");
4458
4459 LogMsgNoIdent("PrimaryMAC: %.6a", &m->PrimaryMAC);
4460
4461 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
4462 m->SleepState,
4463 m->SleepState == SleepState_Awake ? "Awake" :
4464 m->SleepState == SleepState_Transferring ? "Transferring" :
4465 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?",
4466 m->SleepSeqNum);
4467
4468 if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
4469 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
4470
4471 if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
4472 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
4473
4474 LogMsgNoIdent("------ Auto Browse Domains -----");
4475 if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
4476 else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
4477
4478 LogMsgNoIdent("--- Auto Registration Domains --");
4479 if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
4480 else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
4481
4482 LogMsgNoIdent("--- Search Domains --");
4483 if (!SearchList) LogMsgNoIdent("<None>");
4484 else
4485 {
4486 for (s=SearchList; s; s=s->next)
4487 {
4488 char *ifname = InterfaceNameForID(m, s->InterfaceID);
4489 LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
4490 }
4491 }
4492
4493 LogMsgNoIdent("---- Task Scheduling Timers ----");
4494
4495 if (!m->NewQuestions)
4496 LogMsgNoIdent("NewQuestion <NONE>");
4497 else
4498 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
4499 m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
4500 m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
4501
4502 if (!m->NewLocalOnlyQuestions)
4503 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
4504 else
4505 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
4506 m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
4507
4508 if (!m->NewLocalRecords)
4509 LogMsgNoIdent("NewLocalRecords <NONE>");
4510 else
4511 LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
4512
4513 LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
4514 LogMsgNoIdent("LocalRemoveEvents%s", m->LocalRemoveEvents ? "" : " <NONE>");
4515 LogMsgNoIdent("m->RegisterAutoTunnel6 %08X", m->RegisterAutoTunnel6);
4516 LogMsgNoIdent("m->AutoTunnelRelayAddrIn %.16a", &m->AutoTunnelRelayAddrIn);
4517 LogMsgNoIdent("m->AutoTunnelRelayAddrOut %.16a", &m->AutoTunnelRelayAddrOut);
4518
4519 #define LogTimer(MSG,T) LogMsgNoIdent( MSG " %08X %11d %08X %11d", (T), (T), (T)-now, (T)-now)
4520
4521 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
4522 LogMsgNoIdent("m->timenow %08X %11d", now, now);
4523 LogMsgNoIdent("m->timenow_adjust %08X %11d", m->timenow_adjust, m->timenow_adjust);
4524 LogTimer("m->NextScheduledEvent ", m->NextScheduledEvent);
4525
4526 #ifndef UNICAST_DISABLED
4527 LogTimer("m->NextuDNSEvent ", m->NextuDNSEvent);
4528 LogTimer("m->NextSRVUpdate ", m->NextSRVUpdate);
4529 LogTimer("m->NextScheduledNATOp ", m->NextScheduledNATOp);
4530 LogTimer("m->retryGetAddr ", m->retryGetAddr);
4531 #endif
4532
4533 LogTimer("m->NextCacheCheck ", m->NextCacheCheck);
4534 LogTimer("m->NextScheduledSPS ", m->NextScheduledSPS);
4535 LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
4536 LogTimer("m->DelaySleep ", m->DelaySleep);
4537
4538 LogTimer("m->NextScheduledQuery ", m->NextScheduledQuery);
4539 LogTimer("m->NextScheduledProbe ", m->NextScheduledProbe);
4540 LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
4541
4542 LogTimer("m->SuppressSending ", m->SuppressSending);
4543 LogTimer("m->SuppressProbes ", m->SuppressProbes);
4544 LogTimer("m->ProbeFailTime ", m->ProbeFailTime);
4545 LogTimer("m->DelaySleep ", m->DelaySleep);
4546 LogTimer("m->SleepLimit ", m->SleepLimit);
4547 LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
4548 }
4549
4550 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4551 mDNSexport void uds_validatelists(void)
4552 {
4553 const request_state *req, *p;
4554 for (req = all_requests; req; req=req->next)
4555 {
4556 if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
4557 LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
4558
4559 if (req->primary == req)
4560 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
4561
4562 if (req->primary && req->replies)
4563 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
4564 req, req->sd, req->primary && req->replies);
4565
4566 p = req->primary;
4567 if ((long)p & 3)
4568 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
4569 else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
4570 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
4571
4572 reply_state *rep;
4573 for (rep = req->replies; rep; rep=rep->next)
4574 if (rep->next == (reply_state *)~0)
4575 LogMemCorruption("UDS req->replies: %p is garbage", rep);
4576
4577 if (req->terminate == connection_termination)
4578 {
4579 registered_record_entry *r;
4580 for (r = req->u.reg_recs; r; r=r->next)
4581 if (r->next == (registered_record_entry *)~0)
4582 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
4583 }
4584 else if (req->terminate == regservice_termination_callback)
4585 {
4586 service_instance *s;
4587 for (s = req->u.servicereg.instances; s; s=s->next)
4588 if (s->next == (service_instance *)~0)
4589 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
4590 }
4591 else if (req->terminate == browse_termination_callback)
4592 {
4593 browser_t *b;
4594 for (b = req->u.browser.browsers; b; b=b->next)
4595 if (b->next == (browser_t *)~0)
4596 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
4597 }
4598 }
4599
4600 DNameListElem *d;
4601 for (d = SCPrefBrowseDomains; d; d=d->next)
4602 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4603 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
4604
4605 ARListElem *b;
4606 for (b = LocalDomainEnumRecords; b; b=b->next)
4607 if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
4608 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
4609
4610 for (d = AutoBrowseDomains; d; d=d->next)
4611 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4612 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
4613
4614 for (d = AutoRegistrationDomains; d; d=d->next)
4615 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
4616 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
4617 }
4618 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4619
4620 mDNSlocal int send_msg(request_state *const req)
4621 {
4622 reply_state *const rep = req->replies; // Send the first waiting reply
4623 ssize_t nwriten;
4624 if (req->no_reply) return(t_complete);
4625
4626 ConvertHeaderBytes(rep->mhdr);
4627 nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
4628 ConvertHeaderBytes(rep->mhdr);
4629
4630 if (nwriten < 0)
4631 {
4632 if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
4633 else
4634 {
4635 #if !defined(PLATFORM_NO_EPIPE)
4636 if (dnssd_errno == EPIPE)
4637 return(req->ts = t_terminated);
4638 else
4639 #endif
4640 {
4641 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
4642 rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4643 return(t_error);
4644 }
4645 }
4646 }
4647 rep->nwriten += nwriten;
4648 return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
4649 }
4650
4651 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
4652 {
4653 mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
4654 request_state **req = &all_requests;
4655
4656 while (*req)
4657 {
4658 request_state *const r = *req;
4659
4660 if (r->terminate == resolve_termination_callback)
4661 if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
4662 {
4663 r->u.resolve.ReportTime = 0;
4664 LogMsgNoIdent("Client application bug: DNSServiceResolve(%##s) active for over two minutes. "
4665 "This places considerable burden on the network.", r->u.resolve.qsrv.qname.c);
4666 }
4667
4668 // Note: Only primary req's have reply lists, not subordinate req's.
4669 while (r->replies) // Send queued replies
4670 {
4671 transfer_state result;
4672 if (r->replies->next) r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
4673 result = send_msg(r); // Returns t_morecoming if buffer full because client is not reading
4674 if (result == t_complete)
4675 {
4676 reply_state *fptr = r->replies;
4677 r->replies = r->replies->next;
4678 freeL("reply_state/udsserver_idle", fptr);
4679 r->time_blocked = 0; // reset failure counter after successful send
4680 r->unresponsiveness_reports = 0;
4681 continue;
4682 }
4683 else if (result == t_terminated || result == t_error)
4684 {
4685 LogMsg("%3d: Could not write data to client because of error - aborting connection", r->sd);
4686 LogClientInfo(&mDNSStorage, r);
4687 abort_request(r);
4688 }
4689 break;
4690 }
4691
4692 if (r->replies) // If we failed to send everything, check our time_blocked timer
4693 {
4694 if (nextevent - now > mDNSPlatformOneSecond) nextevent = now + mDNSPlatformOneSecond;
4695
4696 if (mDNSStorage.SleepState != SleepState_Awake) r->time_blocked = 0;
4697 else if (!r->time_blocked) r->time_blocked = NonZeroTime(now);
4698 else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
4699 {
4700 int num = 0;
4701 struct reply_state *x = r->replies;
4702 while (x) { num++; x=x->next; }
4703 LogMsg("%3d: Could not write data to client after %ld seconds, %d repl%s waiting",
4704 r->sd, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
4705 if (++r->unresponsiveness_reports >= 60)
4706 {
4707 LogMsg("%3d: Client unresponsive; aborting connection", r->sd);
4708 LogClientInfo(&mDNSStorage, r);
4709 abort_request(r);
4710 }
4711 }
4712 }
4713
4714 if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
4715 {
4716 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
4717 *req = r->next;
4718 freeL("request_state/udsserver_idle", r);
4719 }
4720 else
4721 req = &r->next;
4722 }
4723 return nextevent;
4724 }
4725
4726 struct CompileTimeAssertionChecks_uds_daemon
4727 {
4728 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4729 // other overly-large structures instead of having a pointer to them, can inadvertently
4730 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
4731 char sizecheck_request_state [(sizeof(request_state) <= 1784) ? 1 : -1];
4732 char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <= 60) ? 1 : -1];
4733 char sizecheck_service_instance [(sizeof(service_instance) <= 6552) ? 1 : -1];
4734 char sizecheck_browser_t [(sizeof(browser_t) <= 1050) ? 1 : -1];
4735 char sizecheck_reply_hdr [(sizeof(reply_hdr) <= 12) ? 1 : -1];
4736 char sizecheck_reply_state [(sizeof(reply_state) <= 64) ? 1 : -1];
4737 };