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