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