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