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