]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSShared/uds_daemon.c
mDNSResponder-765.1.2.tar.gz
[apple/mdnsresponder.git] / mDNSShared / uds_daemon.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2003-2015 Apple 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_PEEREPID
52 #include <sys/un.h> // for LOCAL_PEEREPID
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_PEEREPID
57 //upto 16 characters of process name (defined in <sys/proc.h> but we do not want to include that file)
58 #define MAXCOMLEN 16
59
60 #if APPLE_OSX_mDNSResponder
61 #include <WebFilterDNS/WebFilterDNS.h>
62 #include "BLE.h"
63
64 #if !NO_WCF
65
66 int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
67 int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
68 int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
69
70 // Do we really need to define a macro for "if"?
71 #define CHECK_WCF_FUNCTION(X) if (X)
72 #endif // ! NO_WCF
73
74 #else
75 #define NO_WCF 1
76 #endif // APPLE_OSX_mDNSResponder
77
78 // User IDs 0-500 are system-wide processes, not actual users in the usual sense
79 // User IDs for real user accounts start at 501 and count up from there
80 #define SystemUID(X) ((X) <= 500)
81
82 #define MAX_ANONYMOUS_DATA 256
83
84 // ***************************************************************************
85 #if COMPILER_LIKES_PRAGMA_MARK
86 #pragma mark -
87 #pragma mark - Types and Data Structures
88 #endif
89
90 typedef enum
91 {
92 t_uninitialized,
93 t_morecoming,
94 t_complete,
95 t_error,
96 t_terminated
97 } transfer_state;
98
99 typedef struct request_state request_state;
100
101 typedef void (*req_termination_fn)(request_state *request);
102
103 typedef struct registered_record_entry
104 {
105 struct registered_record_entry *next;
106 mDNSu32 key;
107 client_context_t regrec_client_context;
108 request_state *request;
109 mDNSBool external_advertise;
110 mDNSInterfaceID origInterfaceID;
111 AuthRecord *rr; // Pointer to variable-sized AuthRecord (Why a pointer? Why not just embed it here?)
112 } registered_record_entry;
113
114 // A single registered service: ServiceRecordSet + bookkeeping
115 // Note that we duplicate some fields from parent service_info object
116 // to facilitate cleanup, when instances and parent may be deallocated at different times.
117 typedef struct service_instance
118 {
119 struct service_instance *next;
120 request_state *request;
121 AuthRecord *subtypes;
122 mDNSBool renameonmemfree; // Set on config change when we deregister original name
123 mDNSBool clientnotified; // Has client been notified of successful registration yet?
124 mDNSBool default_local; // is this the "local." from an empty-string registration?
125 mDNSBool external_advertise; // is this is being advertised externally?
126 domainname domain;
127 ServiceRecordSet srs; // note -- variable-sized object -- must be last field in struct
128 } service_instance;
129
130 // for multi-domain default browsing
131 typedef struct browser_t
132 {
133 struct browser_t *next;
134 domainname domain;
135 DNSQuestion q;
136 } browser_t;
137
138 #ifdef _WIN32
139 typedef unsigned int pid_t;
140 typedef unsigned int socklen_t;
141 #endif
142
143 struct request_state
144 {
145 request_state *next;
146 request_state *primary; // If this operation is on a shared socket, pointer to primary
147 // request_state for the original DNSServiceCreateConnection() operation
148 dnssd_sock_t sd;
149 pid_t process_id; // Client's PID value
150 char pid_name[MAXCOMLEN]; // Client's process name
151 char uuid[UUID_SIZE];
152 mDNSBool validUUID;
153 dnssd_sock_t errsd;
154 mDNSu32 uid;
155 void * platform_data;
156
157 // Note: On a shared connection these fields in the primary structure, including hdr, are re-used
158 // for each new request. This is because, until we've read the ipc_msg_hdr to find out what the
159 // operation is, we don't know if we're going to need to allocate a new request_state or not.
160 transfer_state ts;
161 mDNSu32 hdr_bytes; // bytes of header already read
162 ipc_msg_hdr hdr;
163 mDNSu32 data_bytes; // bytes of message data already read
164 char *msgbuf; // pointer to data storage to pass to free()
165 const char *msgptr; // pointer to data to be read from (may be modified)
166 char *msgend; // pointer to byte after last byte of message
167
168 // reply, termination, error, and client context info
169 int no_reply; // don't send asynchronous replies to client
170 mDNSs32 time_blocked; // record time of a blocked client
171 int unresponsiveness_reports;
172 struct reply_state *replies; // corresponding (active) reply list
173 req_termination_fn terminate;
174 DNSServiceFlags flags;
175 mDNSu32 interfaceIndex;
176
177 union
178 {
179 registered_record_entry *reg_recs; // list of registrations for a connection-oriented request
180 struct
181 {
182 mDNSInterfaceID interface_id;
183 mDNSBool default_domain;
184 mDNSBool ForceMCast;
185 domainname regtype;
186 browser_t *browsers;
187 const mDNSu8 *AnonData;
188 } browser;
189 struct
190 {
191 mDNSInterfaceID InterfaceID;
192 mDNSu16 txtlen;
193 void *txtdata;
194 mDNSIPPort port;
195 domainlabel name;
196 char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
197 domainname type;
198 mDNSBool default_domain;
199 domainname host;
200 mDNSBool autoname; // Set if this name is tied to the Computer Name
201 mDNSBool autorename; // Set if this client wants us to automatically rename on conflict
202 mDNSBool allowremotequery; // Respond to unicast queries from outside the local link?
203 int num_subtypes;
204 mDNSBool AnonData;
205 service_instance *instances;
206 } servicereg;
207 struct
208 {
209 mDNSInterfaceID interface_id;
210 mDNSu32 flags;
211 mDNSu32 protocol;
212 DNSQuestion q4;
213 DNSQuestion *q42;
214 DNSQuestion q6;
215 DNSQuestion *q62;
216 mDNSu8 v4ans;
217 mDNSu8 v6ans;
218 } addrinfo;
219 struct
220 {
221 mDNSIPPort ReqExt; // External port we originally requested, for logging purposes
222 NATTraversalInfo NATinfo;
223 } pm;
224 struct
225 {
226 DNSServiceFlags flags;
227 DNSQuestion q_all;
228 DNSQuestion q_default;
229 DNSQuestion q_autoall;
230 } enumeration;
231 struct
232 {
233 DNSQuestion q;
234 DNSQuestion *q2;
235 mDNSu8 ans;
236 } queryrecord;
237 struct
238 {
239 DNSQuestion qtxt;
240 DNSQuestion qsrv;
241 const ResourceRecord *txt;
242 const ResourceRecord *srv;
243 mDNSs32 ReportTime;
244 mDNSBool external_advertise;
245 } resolve;
246 } u;
247 };
248
249 // struct physically sits between ipc message header and call-specific fields in the message buffer
250 typedef struct
251 {
252 DNSServiceFlags flags; // Note: This field is in NETWORK byte order
253 mDNSu32 ifi; // Note: This field is in NETWORK byte order
254 DNSServiceErrorType error; // Note: This field is in NETWORK byte order
255 } reply_hdr;
256
257 typedef struct reply_state
258 {
259 struct reply_state *next; // If there are multiple unsent replies
260 mDNSu32 totallen;
261 mDNSu32 nwriten;
262 ipc_msg_hdr mhdr[1];
263 reply_hdr rhdr[1];
264 } reply_state;
265
266 // ***************************************************************************
267 #if COMPILER_LIKES_PRAGMA_MARK
268 #pragma mark -
269 #pragma mark - Globals
270 #endif
271
272 // globals
273 mDNSexport mDNS mDNSStorage;
274 mDNSexport const char ProgramName[] = "mDNSResponder";
275
276 #if defined(USE_TCP_LOOPBACK)
277 static char* boundPath = NULL;
278 #else
279 static char* boundPath = MDNS_UDS_SERVERPATH;
280 #endif
281 #if DEBUG
282 #define MDNS_UDS_SERVERPATH_DEBUG "/var/tmp/mDNSResponder"
283 #endif
284 static dnssd_sock_t listenfd = dnssd_InvalidSocket;
285 static request_state *all_requests = NULL;
286 #ifdef LOCAL_PEEREPID
287 struct proc_bsdshortinfo proc;
288 #endif //LOCAL_PEEREPID
289 mDNSlocal void set_peer_pid(request_state *request);
290 mDNSlocal void LogMcastClientInfo(request_state *req);
291 mDNSlocal void GetMcastClients(request_state *req);
292 static mDNSu32 mcount; // tracks the current active mcast operations for McastLogging
293 static mDNSu32 i_mcount; // sets mcount when McastLogging is enabled(PROF signal is sent)
294 static mDNSu32 n_mrecords; // tracks the current active mcast records for McastLogging
295 static mDNSu32 n_mquests; // tracks the current active mcast questions for McastLogging
296
297
298 #if TARGET_OS_EMBEDDED
299 mDNSu32 curr_num_regservices = 0;
300 mDNSu32 max_num_regservices = 0;
301 #endif
302
303
304 // Note asymmetry here between registration and browsing.
305 // For service registrations we only automatically register in domains that explicitly appear in local configuration data
306 // (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
307 // For service browsing we also learn automatic browsing domains from the network, so for that case we have:
308 // 1. SCPrefBrowseDomains (local configuration data)
309 // 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
310 // 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
311 // By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
312
313 mDNSexport DNameListElem *AutoRegistrationDomains; // Domains where we automatically register for empty-string registrations
314
315 static DNameListElem *SCPrefBrowseDomains; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
316 static ARListElem *LocalDomainEnumRecords; // List of locally-generated PTR records to augment those we learn from the network
317 mDNSexport DNameListElem *AutoBrowseDomains; // List created from those local-only PTR records plus records we get from the network
318
319 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
320 // n get_string() calls w/o buffer overrun
321 // initialization, setup/teardown functions
322
323 // If a platform specifies its own PID file name, we use that
324 #ifndef PID_FILE
325 #define PID_FILE "/var/run/mDNSResponder.pid"
326 #endif
327
328 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen);
329
330 // ***************************************************************************
331 #if COMPILER_LIKES_PRAGMA_MARK
332 #pragma mark -
333 #pragma mark - General Utility Functions
334 #endif
335
336 mDNSlocal void FatalError(char *errmsg)
337 {
338 LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
339 abort();
340 }
341
342 mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
343 {
344 mDNSu32 ret;
345 char *data = (char*) &ret;
346 put_uint32(l, &data);
347 return ret;
348 }
349
350 // hack to search-replace perror's to LogMsg's
351 mDNSlocal void my_perror(char *errmsg)
352 {
353 LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
354 }
355
356 // Throttled version of my_perror: Logs once every 250 msgs
357 mDNSlocal void my_throttled_perror(char *err_msg)
358 {
359 static int uds_throttle_count = 0;
360 if ((uds_throttle_count++ % 250) == 0)
361 my_perror(err_msg);
362 }
363
364 // LogMcastQuestion/LogMcastQ should be called after the DNSQuestion struct is initialized(especially for q->TargetQID)
365 // Hence all calls are made after mDNS_StartQuery()/mDNS_StopQuery()/mDNS_StopBrowse() is called.
366 mDNSlocal void LogMcastQuestion(mDNS *const m, const DNSQuestion *const q, request_state *req, q_state status)
367 {
368 if (mDNSOpaque16IsZero(q->TargetQID)) // Check for Mcast Query
369 {
370 mDNSBool mflag = mDNSfalse;
371 if (status == q_start)
372 {
373 if (++mcount == 1)
374 mflag = mDNStrue;
375 }
376 else
377 {
378 mcount--;
379 }
380 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Question" : "-Question", q->qname.c, DNSTypeName(q->qtype),
381 q->InterfaceID == mDNSInterface_LocalOnly ? "lo" :
382 q->InterfaceID == mDNSInterface_P2P ? "p2p" :
383 q->InterfaceID == mDNSInterface_BLE ? "BLE" :
384 q->InterfaceID == mDNSInterface_Any ? "any" : InterfaceNameForID(m, q->InterfaceID),
385 req->process_id, req->pid_name);
386 LogMcastStateInfo(m, mflag, mDNSfalse, mDNSfalse);
387 }
388 return;
389 }
390
391 // LogMcastService/LogMcastS should be called after the AuthRecord struct is initialized
392 // Hence all calls are made after mDNS_Register()/ just before mDNS_Deregister()
393 mDNSlocal void LogMcastService(mDNS *const m, const AuthRecord *const ar, request_state *req, reg_state status)
394 {
395 if (!AuthRecord_uDNS(ar)) // Check for Mcast Service
396 {
397 mDNSBool mflag = mDNSfalse;
398 if (status == reg_start)
399 {
400 if (++mcount == 1)
401 mflag = mDNStrue;
402 }
403 else
404 {
405 mcount--;
406 }
407 LogMcast("%s: %##s (%s) (%s) Client(%d)[%s]", status ? "+Service" : "-Service", ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype),
408 ar->resrec.InterfaceID == mDNSInterface_LocalOnly ? "lo" :
409 ar->resrec.InterfaceID == mDNSInterface_P2P ? "p2p" :
410 ar->resrec.InterfaceID == mDNSInterface_BLE ? "BLE" :
411 ar->resrec.InterfaceID == mDNSInterface_Any ? "all" : InterfaceNameForID(m, ar->resrec.InterfaceID),
412 req->process_id, req->pid_name);
413 LogMcastStateInfo(m, mflag, mDNSfalse, mDNSfalse);
414 }
415 return;
416 }
417
418 // For complete Mcast State Log, pass mDNStrue to mstatelog in LogMcastStateInfo()
419 mDNSexport void LogMcastStateInfo(mDNS *const m, mDNSBool mflag, mDNSBool start, mDNSBool mstatelog)
420 {
421 if (!mstatelog)
422 {
423 if (!all_requests)
424 {
425 LogMcastNoIdent("<None>");
426 }
427 else
428 {
429 request_state *req, *r;
430 for (req = all_requests; req; req=req->next)
431 {
432 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
433 {
434 for (r = all_requests; r && r != req; r=r->next)
435 if (r == req->primary)
436 goto foundpar;
437 }
438 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
439 GetMcastClients(req);
440 foundpar:;
441 }
442 LogMcastNoIdent("--- MCAST RECORDS COUNT[%d] MCAST QUESTIONS COUNT[%d] ---", n_mrecords, n_mquests);
443 n_mrecords = n_mquests = 0; // Reset the values
444 }
445 }
446 else
447 {
448 static mDNSu32 i_mpktnum;
449 i_mcount = 0;
450 if (start)
451 mcount = 0;
452 // mcount is initialized to 0 when the PROF signal is sent since mcount could have
453 // wrong value if MulticastLogging is disabled and then re-enabled
454 LogMcastNoIdent("--- START MCAST STATE LOG ---");
455 if (!all_requests)
456 {
457 mcount = 0;
458 LogMcastNoIdent("<None>");
459 }
460 else
461 {
462 request_state *req, *r;
463 for (req = all_requests; req; req=req->next)
464 {
465 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
466 {
467 for (r = all_requests; r && r != req; r=r->next)
468 if (r == req->primary)
469 goto foundparent;
470 LogMcastNoIdent("%3d: Orphan operation; parent not found in request list", req->sd);
471 }
472 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
473 LogMcastClientInfo(req);
474 foundparent:;
475 }
476 if(!mcount) // To initially set mcount
477 mcount = i_mcount;
478 }
479 if (mcount == 0)
480 {
481 i_mpktnum = m->MPktNum;
482 LogMcastNoIdent("--- MCOUNT[%d]: IMPKTNUM[%d] ---", mcount, i_mpktnum);
483 }
484 if (mflag)
485 LogMcastNoIdent("--- MCOUNT[%d]: CMPKTNUM[%d] - IMPKTNUM[%d] = [%d]PKTS ---", mcount, m->MPktNum, i_mpktnum, (m->MPktNum - i_mpktnum));
486 LogMcastNoIdent("--- END MCAST STATE LOG ---");
487 }
488 }
489
490 mDNSlocal void abort_request(request_state *req)
491 {
492 if (req->terminate == (req_termination_fn) ~0)
493 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
494
495 // First stop whatever mDNSCore operation we were doing
496 // If this is actually a shared connection operation, then its req->terminate function will scan
497 // the all_requests list and terminate any subbordinate operations sharing this file descriptor
498 if (req->terminate) req->terminate(req);
499
500 if (!dnssd_SocketValid(req->sd))
501 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req, req->sd); return; }
502
503 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
504 if (!req->primary)
505 {
506 if (req->errsd != req->sd) LogOperation("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
507 else LogOperation("%3d: Removing FD", req->sd);
508 udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data); // Note: This also closes file descriptor req->sd for us
509 if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
510
511 while (req->replies) // free pending replies
512 {
513 reply_state *ptr = req->replies;
514 req->replies = req->replies->next;
515 freeL("reply_state (abort)", ptr);
516 }
517 }
518
519 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
520 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
521 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
522 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
523 req->sd = req->errsd = -2;
524 #else
525 req->sd = req->errsd = dnssd_InvalidSocket;
526 #endif
527 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
528 req->terminate = (req_termination_fn) ~0;
529 }
530
531 #if DEBUG
532 mDNSexport void SetDebugBoundPath(void)
533 {
534 #if !defined(USE_TCP_LOOPBACK)
535 boundPath = MDNS_UDS_SERVERPATH_DEBUG;
536 #endif
537 }
538
539 mDNSexport int IsDebugSocketInUse(void)
540 {
541 #if !defined(USE_TCP_LOOPBACK)
542 return !strcmp(boundPath, MDNS_UDS_SERVERPATH_DEBUG);
543 #else
544 return mDNSfalse;
545 #endif
546 }
547 #endif
548
549 mDNSlocal void AbortUnlinkAndFree(request_state *req)
550 {
551 request_state **p = &all_requests;
552 abort_request(req);
553 while (*p && *p != req) p=&(*p)->next;
554 if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
555 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
556 }
557
558 mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
559 {
560 reply_state *reply;
561
562 if ((unsigned)datalen < sizeof(reply_hdr))
563 {
564 LogMsg("ERROR: create_reply - data length less than length of required fields");
565 return NULL;
566 }
567
568 reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
569 if (!reply) FatalError("ERROR: malloc");
570
571 reply->next = mDNSNULL;
572 reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
573 reply->nwriten = 0;
574
575 reply->mhdr->version = VERSION;
576 reply->mhdr->datalen = (mDNSu32)datalen;
577 reply->mhdr->ipc_flags = 0;
578 reply->mhdr->op = op;
579 reply->mhdr->client_context = request->hdr.client_context;
580 reply->mhdr->reg_index = 0;
581
582 return reply;
583 }
584
585 // Append a reply to the list in a request object
586 // If our request is sharing a connection, then we append our reply_state onto the primary's list
587 // If the request does not want asynchronous replies, then the reply is freed instead of being appended to any list.
588 mDNSlocal void append_reply(request_state *req, reply_state *rep)
589 {
590 request_state *r;
591 reply_state **ptr;
592
593 if (req->no_reply)
594 {
595 freeL("reply_state/append_reply", rep);
596 return;
597 }
598
599 r = req->primary ? req->primary : req;
600 ptr = &r->replies;
601 while (*ptr) ptr = &(*ptr)->next;
602 *ptr = rep;
603 rep->next = NULL;
604 }
605
606 // Generates a response message giving name, type, domain, plus interface index,
607 // suitable for a browse result or service registration result.
608 // On successful completion rep is set to point to a malloc'd reply_state struct
609 mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
610 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
611 {
612 domainlabel name;
613 domainname type, dom;
614 *rep = NULL;
615 if (!DeconstructServiceName(servicename, &name, &type, &dom))
616 return kDNSServiceErr_Invalid;
617 else
618 {
619 char namestr[MAX_DOMAIN_LABEL+1];
620 char typestr[MAX_ESCAPED_DOMAIN_NAME];
621 char domstr [MAX_ESCAPED_DOMAIN_NAME];
622 int len;
623 char *data;
624
625 ConvertDomainLabelToCString_unescaped(&name, namestr);
626 ConvertDomainNameToCString(&type, typestr);
627 ConvertDomainNameToCString(&dom, domstr);
628
629 // Calculate reply data length
630 len = sizeof(DNSServiceFlags);
631 len += sizeof(mDNSu32); // if index
632 len += sizeof(DNSServiceErrorType);
633 len += (int) (strlen(namestr) + 1);
634 len += (int) (strlen(typestr) + 1);
635 len += (int) (strlen(domstr) + 1);
636
637 // Build reply header
638 *rep = create_reply(op, len, request);
639 (*rep)->rhdr->flags = dnssd_htonl(flags);
640 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
641 (*rep)->rhdr->error = dnssd_htonl(err);
642
643 // Build reply body
644 data = (char *)&(*rep)->rhdr[1];
645 put_string(namestr, &data);
646 put_string(typestr, &data);
647 put_string(domstr, &data);
648
649 return mStatus_NoError;
650 }
651 }
652
653 mDNSlocal void GenerateBrowseReply(const domainname *const servicename, const mDNSInterfaceID id,
654 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
655 {
656 char namestr[MAX_DOMAIN_LABEL+1];
657 char typestr[MAX_ESCAPED_DOMAIN_NAME];
658 static const char domstr[] = ".";
659 int len;
660 char *data;
661
662 *rep = NULL;
663
664 // 1. Put first label in namestr
665 ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
666
667 // 2. Put second label and "local" into typestr
668 mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
669
670 // Calculate reply data length
671 len = sizeof(DNSServiceFlags);
672 len += sizeof(mDNSu32); // if index
673 len += sizeof(DNSServiceErrorType);
674 len += (int) (strlen(namestr) + 1);
675 len += (int) (strlen(typestr) + 1);
676 len += (int) (strlen(domstr) + 1);
677
678 // Build reply header
679 *rep = create_reply(op, len, request);
680 (*rep)->rhdr->flags = dnssd_htonl(flags);
681 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
682 (*rep)->rhdr->error = dnssd_htonl(err);
683
684 // Build reply body
685 data = (char *)&(*rep)->rhdr[1];
686 put_string(namestr, &data);
687 put_string(typestr, &data);
688 put_string(domstr, &data);
689 }
690
691 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
692 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
693 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
694 mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
695 {
696 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
697 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
698 char name[256];
699 int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
700 mDNSu16 type = get_uint16(&request->msgptr, request->msgend);
701 mDNSu16 class = get_uint16(&request->msgptr, request->msgend);
702 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
703 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
704 mDNSu32 ttl = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
705 size_t storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
706 AuthRecord *rr;
707 mDNSInterfaceID InterfaceID;
708 AuthRecType artype;
709
710 request->flags = flags;
711 request->interfaceIndex = interfaceIndex;
712
713 if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
714
715 if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
716
717 if (validate_flags &&
718 !((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
719 !((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
720 {
721 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
722 return NULL;
723 }
724
725 rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
726 if (!rr) FatalError("ERROR: malloc");
727
728 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
729 if (InterfaceID == mDNSInterface_LocalOnly)
730 artype = AuthRecordLocalOnly;
731 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
732 artype = AuthRecordP2P;
733 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
734 && (flags & kDNSServiceFlagsIncludeAWDL))
735 artype = AuthRecordAnyIncludeAWDLandP2P;
736 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
737 artype = AuthRecordAnyIncludeP2P;
738 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
739 artype = AuthRecordAnyIncludeAWDL;
740 else
741 artype = AuthRecordAny;
742
743 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
744 (mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
745
746 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
747 {
748 LogMsg("ERROR: bad name: %s", name);
749 freeL("AuthRecord/read_rr_from_ipc_msg", rr);
750 return NULL;
751 }
752
753 if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
754 rr->resrec.rrclass = class;
755 rr->resrec.rdlength = rdlen;
756 rr->resrec.rdata->MaxRDLength = rdlen;
757 mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
758 if (GetTTL) rr->resrec.rroriginalttl = ttl;
759 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
760 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
761 return rr;
762 }
763
764 mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
765 {
766 domainlabel n;
767 domainname d, t;
768
769 if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
770 if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
771 if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
772 if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
773 return 0;
774 }
775
776 mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
777 {
778 int n = send(s, ptr, len, 0);
779 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
780 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
781 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
782 if (n < len)
783 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
784 s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
785 }
786
787 #if 0
788 mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
789 {
790 const DNameListElem *delem = mDNSNULL;
791 int bestDelta = -1; // the delta of the best match, lower is better
792 int dLabels = 0;
793 mDNSBool allow = mDNSfalse;
794
795 if (SystemUID(request->uid)) return mDNStrue;
796
797 dLabels = CountLabels(d);
798 for (delem = doms; delem; delem = delem->next)
799 {
800 if (delem->uid)
801 {
802 int delemLabels = CountLabels(&delem->name);
803 int delta = dLabels - delemLabels;
804 if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
805 {
806 bestDelta = delta;
807 allow = (allow || (delem->uid == request->uid));
808 }
809 }
810 }
811
812 return bestDelta == -1 ? mDNStrue : allow;
813 }
814 #endif
815
816 // ***************************************************************************
817 #if COMPILER_LIKES_PRAGMA_MARK
818 #pragma mark -
819 #pragma mark - external helpers
820 #endif
821
822 mDNSexport mDNSBool callExternalHelpers(mDNSInterfaceID InterfaceID, const domainname *const domain, DNSServiceFlags flags)
823 {
824 #if APPLE_OSX_mDNSResponder
825
826 // Only call D2D layer routines if request applies to a D2D interface and the domain is "local".
827 if ( (((InterfaceID == mDNSInterface_Any) && (flags & (kDNSServiceFlagsIncludeP2P | kDNSServiceFlagsIncludeAWDL | kDNSServiceFlagsAutoTrigger)))
828 || mDNSPlatformInterfaceIsD2D(InterfaceID) || (InterfaceID == mDNSInterface_BLE))
829 && IsLocalDomain(domain))
830 {
831 return mDNStrue;
832 }
833 else
834 return mDNSfalse;
835
836 #else
837 (void) InterfaceID;
838 (void) domain;
839 (void) flags;
840
841 return mDNSfalse;
842 #endif // APPLE_OSX_mDNSResponder
843 }
844
845 mDNSlocal void external_start_advertising_helper(service_instance *const instance)
846 {
847 AuthRecord *st = instance->subtypes;
848 ExtraResourceRecord *e;
849 int i;
850
851 if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
852 {
853 LogInfo("external_start_advertising_helper: Not registering service with port number zero");
854 return;
855 }
856
857 if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
858
859 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
860 external_start_advertising_service(&st[i].resrec, instance->request->flags);
861
862 external_start_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
863 external_start_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
864
865 #if APPLE_OSX_mDNSResponder
866 if (applyToBLE(instance->srs.RR_SRV.resrec.InterfaceID, instance->request->flags))
867 {
868 start_BLE_advertise(& instance->srs, instance->srs.RR_SRV.resrec.name , instance->srs.RR_SRV.resrec.rrtype, instance->request->flags);
869 }
870 #endif // APPLE_OSX_mDNSResponder
871
872 external_start_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
873
874 for (e = instance->srs.Extras; e; e = e->next)
875 external_start_advertising_service(&e->r.resrec, instance->request->flags);
876
877 instance->external_advertise = mDNStrue;
878 }
879
880 mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
881 {
882 AuthRecord *st = instance->subtypes;
883 ExtraResourceRecord *e;
884 int i;
885
886 if (!instance->external_advertise) return;
887
888 LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
889
890 for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
891 external_stop_advertising_service(&st[i].resrec, instance->request->flags);
892
893 external_stop_advertising_service(&instance->srs.RR_PTR.resrec, instance->request->flags);
894 external_stop_advertising_service(&instance->srs.RR_SRV.resrec, instance->request->flags);
895 external_stop_advertising_service(&instance->srs.RR_TXT.resrec, instance->request->flags);
896
897 for (e = instance->srs.Extras; e; e = e->next)
898 external_stop_advertising_service(&e->r.resrec, instance->request->flags);
899
900 instance->external_advertise = mDNSfalse;
901 }
902
903 // ***************************************************************************
904 #if COMPILER_LIKES_PRAGMA_MARK
905 #pragma mark -
906 #pragma mark - DNSServiceRegister
907 #endif
908
909 mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
910 {
911 ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
912 (void)m; // Unused
913
914 if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
915
916 LogInfo(" FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
917
918 if (rr->resrec.rdata != &rr->rdatastorage)
919 freeL("Extra RData", rr->resrec.rdata);
920 freeL("ExtraResourceRecord/FreeExtraRR", extra);
921 }
922
923 mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
924 {
925 ExtraResourceRecord *e = srv->srs.Extras, *tmp;
926
927 external_stop_advertising_helper(srv);
928
929 // clear pointers from parent struct
930 if (srv->request)
931 {
932 service_instance **p = &srv->request->u.servicereg.instances;
933 while (*p)
934 {
935 if (*p == srv) { *p = (*p)->next; break; }
936 p = &(*p)->next;
937 }
938 }
939
940 while (e)
941 {
942 e->r.RecordContext = e;
943 tmp = e;
944 e = e->next;
945 FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
946 }
947
948 if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
949 freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
950
951 if (srv->subtypes)
952 {
953 freeL("ServiceSubTypes", srv->subtypes);
954 srv->subtypes = NULL;
955 }
956 if (srv->srs.AnonData)
957 {
958 freeL("Anonymous", (void *)srv->srs.AnonData);
959 srv->srs.AnonData = NULL;
960 }
961 freeL("service_instance", srv);
962 }
963
964 // Count how many other service records we have locally with the same name, but different rdata.
965 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
966 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
967 mDNSexport int CountPeerRegistrations(mDNS *const m, ServiceRecordSet *const srs)
968 {
969 int count = 0;
970 ResourceRecord *r = &srs->RR_SRV.resrec;
971 AuthRecord *rr;
972
973 for (rr = m->ResourceRecords; rr; rr=rr->next)
974 if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
975 count++;
976
977 verbosedebugf("%d peer registrations for %##s", count, r->name->c);
978 return(count);
979 }
980
981 mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
982 {
983 int count = 0;
984 AuthRecord *rr;
985 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
986 if (rr->resrec.rrtype == kDNSType_SRV &&
987 mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
988 SameDomainName(rr->resrec.name, srv))
989 count++;
990 return(count);
991 }
992
993 mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
994 {
995 reply_state *rep;
996 service_instance *instance = srs->ServiceContext;
997 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
998 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
999 else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
1000 }
1001
1002 // service registration callback performs three duties - frees memory for deregistered services,
1003 // handles name conflicts, and delivers completed registration information to the client
1004 mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
1005 {
1006 mStatus err;
1007 mDNSBool SuppressError = mDNSfalse;
1008 service_instance *instance;
1009 reply_state *rep;
1010 (void)m; // Unused
1011
1012 if (!srs) { LogMsg("regservice_callback: srs is NULL %d", result); return; }
1013
1014 instance = srs->ServiceContext;
1015 if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
1016
1017 // don't send errors up to client for wide-area, empty-string registrations
1018 if (instance->request &&
1019 instance->request->u.servicereg.default_domain &&
1020 !instance->default_local)
1021 SuppressError = mDNStrue;
1022
1023 if (mDNS_LoggingEnabled)
1024 {
1025 const char *const fmt =
1026 (result == mStatus_NoError) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
1027 (result == mStatus_MemFree) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
1028 (result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
1029 "%s DNSServiceRegister(%##s, %u) %s %d";
1030 char prefix[16] = "---:";
1031 if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
1032 LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
1033 SuppressError ? "suppressed error" : "CALLBACK", result);
1034 }
1035
1036 if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
1037
1038 if (result == mStatus_NoError)
1039 {
1040 if (instance->request->u.servicereg.allowremotequery)
1041 {
1042 ExtraResourceRecord *e;
1043 srs->RR_ADV.AllowRemoteQuery = mDNStrue;
1044 srs->RR_PTR.AllowRemoteQuery = mDNStrue;
1045 srs->RR_SRV.AllowRemoteQuery = mDNStrue;
1046 srs->RR_TXT.AllowRemoteQuery = mDNStrue;
1047 for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
1048 }
1049
1050 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
1051 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
1052 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
1053
1054 if (callExternalHelpers(instance->request->u.servicereg.InterfaceID, &instance->domain, instance->request->flags))
1055 {
1056 LogInfo("regservice_callback: calling external_start_advertising_helper()");
1057 external_start_advertising_helper(instance);
1058 }
1059 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
1060 RecordUpdatedNiceLabel(m, 0); // Successfully got new name, tell user immediately
1061 }
1062 else if (result == mStatus_MemFree)
1063 {
1064 #if TARGET_OS_EMBEDDED
1065 curr_num_regservices--;
1066 #endif
1067 if (instance->request && instance->renameonmemfree)
1068 {
1069 external_stop_advertising_helper(instance);
1070 instance->renameonmemfree = 0;
1071 err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
1072 if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
1073 // error should never happen - safest to log and continue
1074 }
1075 else
1076 unlink_and_free_service_instance(instance);
1077 }
1078 else if (result == mStatus_NameConflict)
1079 {
1080 if (instance->request->u.servicereg.autorename)
1081 {
1082 external_stop_advertising_helper(instance);
1083 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
1084 {
1085 // On conflict for an autoname service, rename and reregister *all* autoname services
1086 IncrementLabelSuffix(&m->nicelabel, mDNStrue);
1087 mDNS_ConfigChanged(m); // Will call back into udsserver_handle_configchange()
1088 }
1089 else // On conflict for a non-autoname service, rename and reregister just that one service
1090 {
1091 if (instance->clientnotified) SendServiceRemovalNotification(srs);
1092 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
1093 }
1094 }
1095 else
1096 {
1097 if (!SuppressError)
1098 {
1099 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
1100 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
1101 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
1102 }
1103 unlink_and_free_service_instance(instance);
1104 }
1105 }
1106 else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
1107 {
1108 if (!SuppressError)
1109 {
1110 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
1111 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
1112 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
1113 }
1114 }
1115 }
1116
1117 mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
1118 {
1119 (void)m; // Unused
1120 if (!rr->RecordContext) // parent struct already freed by termination callback
1121 {
1122 if (result == mStatus_NoError)
1123 LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
1124 else
1125 {
1126 if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
1127
1128 // We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
1129 // If the record has been updated, we need to free the rdata. Every time we call mDNS_Update, it calls update_callback
1130 // with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
1131 // to free the latest rdata for which the update_callback was never called with.
1132 if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
1133 freeL("AuthRecord/regrecord_callback", rr);
1134 }
1135 }
1136 else
1137 {
1138 registered_record_entry *re = rr->RecordContext;
1139 request_state *request = re->request;
1140
1141 if (mDNS_LoggingEnabled)
1142 {
1143 char *fmt = (result == mStatus_NoError) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
1144 (result == mStatus_MemFree) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
1145 (result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
1146 "%3d: DNSServiceRegisterRecord(%u %s) %d";
1147 LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
1148 }
1149
1150 if (result != mStatus_MemFree)
1151 {
1152 int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
1153 reply_state *reply = create_reply(reg_record_reply_op, len, request);
1154 reply->mhdr->client_context = re->regrec_client_context;
1155 reply->rhdr->flags = dnssd_htonl(0);
1156 reply->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
1157 reply->rhdr->error = dnssd_htonl(result);
1158 append_reply(request, reply);
1159 }
1160
1161 if (result)
1162 {
1163 // If this is a callback to a keepalive record, do not free it.
1164 if (result == mStatus_BadStateErr)
1165 {
1166 LogInfo("regrecord_callback: Callback with error code mStatus_BadStateErr - not freeing the record.");
1167 }
1168 else
1169 {
1170 // unlink from list, free memory
1171 registered_record_entry **ptr = &request->u.reg_recs;
1172 while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
1173 if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
1174 *ptr = (*ptr)->next;
1175 freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
1176 freeL("registered_record_entry regrecord_callback", re);
1177 }
1178 }
1179 else
1180 {
1181 if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
1182
1183 if (callExternalHelpers(re->origInterfaceID, &rr->namestorage, request->flags))
1184 {
1185 LogInfo("regrecord_callback: calling external_start_advertising_service");
1186 external_start_advertising_service(&rr->resrec, request->flags);
1187 re->external_advertise = mDNStrue;
1188 }
1189 }
1190 }
1191 }
1192
1193 // set_peer_pid() is called after mem is allocated for each new request in NewRequest()
1194 // This accounts for 2 places (connect_callback, request_callback)
1195 mDNSlocal void set_peer_pid(request_state *request)
1196 {
1197 pid_t p = (pid_t) -1;
1198 socklen_t len = sizeof(p);
1199 request->pid_name[0] = '\0';
1200 request->process_id = -1;
1201 #ifdef LOCAL_PEEREPID
1202 if (request->sd < 0)
1203 return;
1204 // to extract the effective pid value
1205 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &p, &len) != 0)
1206 return;
1207 // to extract the process name from the pid value
1208 if (proc_pidinfo(p, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
1209 return;
1210 mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
1211 request->process_id = p;
1212 debugf("set_peer_pid: Client PEEREPID is %d %s", p, request->pid_name);
1213 #else // !LOCAL_PEEREPID
1214 len = 0;
1215 LogInfo("set_peer_pid: Not Supported on this version of OS");
1216 if (request->sd < 0)
1217 return;
1218 #endif // LOCAL_PEEREPID
1219 }
1220
1221 mDNSlocal void connection_termination(request_state *request)
1222 {
1223 // When terminating a shared connection, we need to scan the all_requests list
1224 // and terminate any subbordinate operations sharing this file descriptor
1225 request_state **req = &all_requests;
1226
1227 LogOperation("%3d: DNSServiceCreateConnection STOP PID[%d](%s)", request->sd, request->process_id, request->pid_name);
1228
1229 while (*req)
1230 {
1231 if ((*req)->primary == request)
1232 {
1233 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1234 request_state *tmp = *req;
1235 if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp, tmp->sd);
1236 if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
1237 abort_request(tmp);
1238 *req = tmp->next;
1239 freeL("request_state/connection_termination", tmp);
1240 }
1241 else
1242 req = &(*req)->next;
1243 }
1244
1245 while (request->u.reg_recs)
1246 {
1247 registered_record_entry *ptr = request->u.reg_recs;
1248 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP PID[%d](%s)", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec), request->process_id, request->pid_name);
1249 request->u.reg_recs = request->u.reg_recs->next;
1250 ptr->rr->RecordContext = NULL;
1251 if (ptr->external_advertise)
1252 {
1253 ptr->external_advertise = mDNSfalse;
1254 external_stop_advertising_service(&ptr->rr->resrec, request->flags);
1255 }
1256 LogMcastS(&mDNSStorage, ptr->rr, request, reg_stop);
1257 mDNS_Deregister(&mDNSStorage, ptr->rr); // Will free ptr->rr for us
1258 freeL("registered_record_entry/connection_termination", ptr);
1259 }
1260 }
1261
1262 mDNSlocal void handle_cancel_request(request_state *request)
1263 {
1264 request_state **req = &all_requests;
1265 LogOperation("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
1266 while (*req)
1267 {
1268 if ((*req)->primary == request &&
1269 (*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1270 (*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
1271 {
1272 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1273 request_state *tmp = *req;
1274 abort_request(tmp);
1275 *req = tmp->next;
1276 freeL("request_state/handle_cancel_request", tmp);
1277 }
1278 else
1279 req = &(*req)->next;
1280 }
1281 }
1282
1283 mDNSlocal mStatus handle_regrecord_request(request_state *request)
1284 {
1285 mStatus err = mStatus_BadParamErr;
1286 AuthRecord *rr = read_rr_from_ipc_msg(request, 1, 1);
1287 if (rr)
1288 {
1289 registered_record_entry *re;
1290 // Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
1291 // clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
1292 if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&
1293 rr->resrec.rrclass == kDNSClass_IN && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA ||
1294 rr->resrec.rrtype == kDNSType_CNAME))
1295 {
1296 freeL("AuthRecord/handle_regrecord_request", rr);
1297 return (mStatus_BadParamErr);
1298 }
1299 // allocate registration entry, link into list
1300 re = mallocL("registered_record_entry", sizeof(registered_record_entry));
1301 if (!re)
1302 FatalError("ERROR: malloc");
1303 re->key = request->hdr.reg_index;
1304 re->rr = rr;
1305 re->regrec_client_context = request->hdr.client_context;
1306 re->request = request;
1307 re->external_advertise = mDNSfalse;
1308 rr->RecordContext = re;
1309 rr->RecordCallback = regrecord_callback;
1310
1311 re->origInterfaceID = rr->resrec.InterfaceID;
1312 if (rr->resrec.InterfaceID == mDNSInterface_P2P)
1313 rr->resrec.InterfaceID = mDNSInterface_Any;
1314 #if 0
1315 if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError);
1316 #endif
1317 if (rr->resrec.rroriginalttl == 0)
1318 rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype);
1319
1320 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) START PID[%d](%s)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec),
1321 request->process_id, request->pid_name);
1322
1323 err = mDNS_Register(&mDNSStorage, rr);
1324 if (err)
1325 {
1326 LogOperation("%3d: DNSServiceRegisterRecord(%u %s) ERROR (%d)", request->sd, re->key, RRDisplayString(&mDNSStorage, &rr->resrec), err);
1327 freeL("registered_record_entry", re);
1328 freeL("registered_record_entry/AuthRecord", rr);
1329 }
1330 else
1331 {
1332 LogMcastS(&mDNSStorage, rr, request, reg_start);
1333 re->next = request->u.reg_recs;
1334 request->u.reg_recs = re;
1335 }
1336 }
1337 return(err);
1338 }
1339
1340 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m);
1341
1342 mDNSlocal void regservice_termination_callback(request_state *request)
1343 {
1344 if (!request)
1345 {
1346 LogMsg("regservice_termination_callback context is NULL");
1347 return;
1348 }
1349 while (request->u.servicereg.instances)
1350 {
1351 service_instance *p = request->u.servicereg.instances;
1352 request->u.servicereg.instances = request->u.servicereg.instances->next;
1353 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1354 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP PID[%d](%s)", request->sd, p->srs.RR_SRV.resrec.name->c,
1355 mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port), request->process_id, request->pid_name);
1356
1357 external_stop_advertising_helper(p);
1358
1359 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1360 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1361 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1362 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1363 // because by then we might have already freed p
1364 p->request = NULL;
1365 LogMcastS(&mDNSStorage, &p->srs.RR_SRV, request, reg_stop);
1366 if (mDNS_DeregisterService(&mDNSStorage, &p->srs))
1367 {
1368 unlink_and_free_service_instance(p);
1369 // Don't touch service_instance *p after this -- it's likely to have been freed already
1370 }
1371 }
1372 if (request->u.servicereg.txtdata)
1373 {
1374 freeL("service_info txtdata", request->u.servicereg.txtdata);
1375 request->u.servicereg.txtdata = NULL;
1376 }
1377 if (request->u.servicereg.autoname)
1378 {
1379 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1380 request->u.servicereg.autoname = mDNSfalse;
1381 UpdateDeviceInfoRecord(&mDNSStorage);
1382 }
1383 }
1384
1385 mDNSlocal request_state *LocateSubordinateRequest(request_state *request)
1386 {
1387 request_state *req;
1388 for (req = all_requests; req; req = req->next)
1389 if (req->primary == request &&
1390 req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
1391 req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req);
1392 return(request);
1393 }
1394
1395 mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl)
1396 {
1397 ServiceRecordSet *srs = &instance->srs;
1398 mStatus result;
1399 mDNSu32 coreFlags = 0; // translate to corresponding mDNSCore flag definitions
1400 size_t size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1401 ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
1402 if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1403
1404 mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord)); // OK if oversized rdata not zero'd
1405 extra->r.resrec.rrtype = rrtype;
1406 extra->r.rdatastorage.MaxRDLength = (mDNSu16) size;
1407 extra->r.resrec.rdlength = rdlen;
1408 mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen);
1409 // use InterfaceID value from DNSServiceRegister() call that created the original service
1410 extra->r.resrec.InterfaceID = request->u.servicereg.InterfaceID;
1411
1412 if (request->flags & kDNSServiceFlagsIncludeP2P)
1413 coreFlags |= coreFlagIncludeP2P;
1414 if (request->flags & kDNSServiceFlagsIncludeAWDL)
1415 coreFlags |= coreFlagIncludeAWDL;
1416
1417 result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl, coreFlags);
1418 if (result)
1419 {
1420 freeL("ExtraResourceRecord/add_record_to_service", extra);
1421 return result;
1422 }
1423 LogMcastS(&mDNSStorage, &srs->RR_PTR, request, reg_start);
1424
1425 extra->ClientID = request->hdr.reg_index;
1426 if ( instance->external_advertise
1427 && callExternalHelpers(request->u.servicereg.InterfaceID, &instance->domain, request->flags))
1428 {
1429 LogInfo("add_record_to_service: calling external_start_advertising_service");
1430 external_start_advertising_service(&extra->r.resrec, request->flags);
1431 }
1432 return result;
1433 }
1434
1435 mDNSlocal mStatus handle_add_request(request_state *request)
1436 {
1437 service_instance *i;
1438 mStatus result = mStatus_UnknownErr;
1439 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend);
1440 mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend);
1441 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1442 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1443 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1444 if (!ttl) ttl = DefaultTTLforRRType(rrtype);
1445 (void)flags; // Unused
1446
1447 if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1448
1449 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1450 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1451
1452 if (request->terminate != regservice_termination_callback)
1453 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1454
1455 // For a service registered with zero port, don't allow adding records. This mostly happens due to a bug
1456 // in the application. See radar://9165807.
1457 if (mDNSIPPortIsZero(request->u.servicereg.port))
1458 { LogMsg("%3d: DNSServiceAddRecord: adding record to a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1459
1460 LogOperation("%3d: DNSServiceAddRecord(%X, %##s, %s, %d)", request->sd, flags,
1461 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen);
1462
1463 for (i = request->u.servicereg.instances; i; i = i->next)
1464 {
1465 result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl);
1466 if (result && i->default_local) break;
1467 else result = mStatus_NoError; // suppress non-local default errors
1468 }
1469
1470 return(result);
1471 }
1472
1473 mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd, mDNSu16 oldrdlen)
1474 {
1475 mDNSBool external_advertise = (rr->UpdateContext) ? *((mDNSBool *)rr->UpdateContext) : mDNSfalse;
1476 (void)m; // Unused
1477
1478 // There are three cases.
1479 //
1480 // 1. We have updated the primary TXT record of the service
1481 // 2. We have updated the TXT record that was added to the service using DNSServiceAddRecord
1482 // 3. We have updated the TXT record that was registered using DNSServiceRegisterRecord
1483 //
1484 // external_advertise is set if we have advertised at least once during the initial addition
1485 // of the record in all of the three cases above. We should have checked for InterfaceID/LocalDomain
1486 // checks during the first time and hence we don't do any checks here
1487 if (external_advertise)
1488 {
1489 ResourceRecord ext = rr->resrec;
1490 DNSServiceFlags flags = deriveD2DFlagsFromAuthRecType(rr->ARType);
1491
1492 if (ext.rdlength == oldrdlen && mDNSPlatformMemSame(&ext.rdata->u, &oldrd->u, oldrdlen)) goto exit;
1493 SetNewRData(&ext, oldrd, oldrdlen);
1494 external_stop_advertising_service(&ext, flags);
1495 LogInfo("update_callback: calling external_start_advertising_service");
1496 external_start_advertising_service(&rr->resrec, flags);
1497 }
1498 exit:
1499 if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd);
1500 }
1501
1502 mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl, const mDNSBool *const external_advertise)
1503 {
1504 mStatus result;
1505 const size_t rdsize = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
1506 RData *newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize);
1507 if (!newrd) FatalError("ERROR: malloc");
1508 newrd->MaxRDLength = (mDNSu16) rdsize;
1509 mDNSPlatformMemCopy(&newrd->u, rdata, rdlen);
1510
1511 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1512 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1513 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1514 if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; }
1515
1516 if (external_advertise) rr->UpdateContext = (void *)external_advertise;
1517
1518 result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback);
1519 if (result) { LogMsg("update_record: Error %d for %s", (int)result, ARDisplayString(&mDNSStorage, rr)); freeL("RData/update_record", newrd); }
1520 return result;
1521 }
1522
1523 mDNSlocal mStatus handle_update_request(request_state *request)
1524 {
1525 const ipc_msg_hdr *const hdr = &request->hdr;
1526 mStatus result = mStatus_BadReferenceErr;
1527 service_instance *i;
1528 AuthRecord *rr = NULL;
1529
1530 // get the message data
1531 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend); // flags unused
1532 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
1533 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
1534 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend);
1535 (void)flags; // Unused
1536
1537 if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1538
1539 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1540 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1541
1542 if (request->terminate == connection_termination)
1543 {
1544 // update an individually registered record
1545 registered_record_entry *reptr;
1546 for (reptr = request->u.reg_recs; reptr; reptr = reptr->next)
1547 {
1548 if (reptr->key == hdr->reg_index)
1549 {
1550 result = update_record(reptr->rr, rdlen, rdata, ttl, &reptr->external_advertise);
1551 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)",
1552 request->sd, reptr->rr->resrec.name->c, reptr->rr ? DNSTypeName(reptr->rr->resrec.rrtype) : "<NONE>");
1553 goto end;
1554 }
1555 }
1556 result = mStatus_BadReferenceErr;
1557 goto end;
1558 }
1559
1560 if (request->terminate != regservice_termination_callback)
1561 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1562
1563 // For a service registered with zero port, only SRV record is initialized. Don't allow any updates.
1564 if (mDNSIPPortIsZero(request->u.servicereg.port))
1565 { LogMsg("%3d: DNSServiceUpdateRecord: updating the record of a service registered with zero port", request->sd); return(mStatus_BadParamErr); }
1566
1567 // update the saved off TXT data for the service
1568 if (hdr->reg_index == TXT_RECORD_INDEX)
1569 {
1570 if (request->u.servicereg.txtdata)
1571 { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; }
1572 if (rdlen > 0)
1573 {
1574 request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen);
1575 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc");
1576 mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen);
1577 }
1578 request->u.servicereg.txtlen = rdlen;
1579 }
1580
1581 // update a record from a service record set
1582 for (i = request->u.servicereg.instances; i; i = i->next)
1583 {
1584 if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT;
1585 else
1586 {
1587 ExtraResourceRecord *e;
1588 for (e = i->srs.Extras; e; e = e->next)
1589 if (e->ClientID == hdr->reg_index) { rr = &e->r; break; }
1590 }
1591
1592 if (!rr) { result = mStatus_BadReferenceErr; goto end; }
1593 result = update_record(rr, rdlen, rdata, ttl, &i->external_advertise);
1594 if (result && i->default_local) goto end;
1595 else result = mStatus_NoError; // suppress non-local default errors
1596 }
1597
1598 end:
1599 if (request->terminate == regservice_termination_callback)
1600 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request->sd,
1601 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1602 rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>");
1603
1604 return(result);
1605 }
1606
1607 // remove a resource record registered via DNSServiceRegisterRecord()
1608 mDNSlocal mStatus remove_record(request_state *request)
1609 {
1610 mStatus err = mStatus_UnknownErr;
1611 registered_record_entry *e, **ptr = &request->u.reg_recs;
1612
1613 while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next;
1614 if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; }
1615 e = *ptr;
1616 *ptr = e->next; // unlink
1617
1618 LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request->sd, e->key, RRDisplayString(&mDNSStorage, &e->rr->resrec));
1619 e->rr->RecordContext = NULL;
1620 if (e->external_advertise)
1621 {
1622 external_stop_advertising_service(&e->rr->resrec, request->flags);
1623 e->external_advertise = mDNSfalse;
1624 }
1625 LogMcastS(&mDNSStorage, e->rr, request, reg_stop);
1626 err = mDNS_Deregister(&mDNSStorage, e->rr); // Will free e->rr for us; we're responsible for freeing e
1627 if (err)
1628 {
1629 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err);
1630 freeL("registered_record_entry AuthRecord remove_record", e->rr);
1631 }
1632 freeL("registered_record_entry remove_record", e);
1633 return err;
1634 }
1635
1636 mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype)
1637 {
1638 mStatus err = mStatus_BadReferenceErr;
1639 ExtraResourceRecord *ptr;
1640
1641 for (ptr = serv->srs.Extras; ptr; ptr = ptr->next)
1642 {
1643 if (ptr->ClientID == request->hdr.reg_index) // found match
1644 {
1645 *rrtype = ptr->r.resrec.rrtype;
1646 if (serv->external_advertise) external_stop_advertising_service(&ptr->r.resrec, request->flags);
1647 err = mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr);
1648 break;
1649 }
1650 }
1651 return err;
1652 }
1653
1654 mDNSlocal mStatus handle_removerecord_request(request_state *request)
1655 {
1656 mStatus err = mStatus_BadReferenceErr;
1657 get_flags(&request->msgptr, request->msgend); // flags unused
1658
1659 if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
1660
1661 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1662 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request);
1663
1664 if (request->terminate == connection_termination)
1665 err = remove_record(request); // remove individually registered record
1666 else if (request->terminate != regservice_termination_callback)
1667 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); }
1668 else
1669 {
1670 service_instance *i;
1671 mDNSu16 rrtype = 0;
1672 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request->sd,
1673 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL,
1674 rrtype ? DNSTypeName(rrtype) : "<NONE>");
1675 for (i = request->u.servicereg.instances; i; i = i->next)
1676 {
1677 err = remove_extra(request, i, &rrtype);
1678 if (err && i->default_local) break;
1679 else err = mStatus_NoError; // suppress non-local default errors
1680 }
1681 }
1682
1683 return(err);
1684 }
1685
1686 // If there's a comma followed by another character,
1687 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1688 // Otherwise, it returns a pointer to the final nul at the end of the string
1689 mDNSlocal char *FindFirstSubType(char *p, char **AnonData)
1690 {
1691 while (*p)
1692 {
1693 if (p[0] == '\\' && p[1])
1694 {
1695 p += 2;
1696 }
1697 else if (p[0] == ',' && p[1])
1698 {
1699 *p++ = 0;
1700 return(p);
1701 }
1702 else if (p[0] == ':' && p[1])
1703 {
1704 *p++ = 0;
1705 *AnonData = p;
1706 }
1707 else
1708 {
1709 p++;
1710 }
1711 }
1712 return(p);
1713 }
1714
1715 // If there's a comma followed by another character,
1716 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
1717 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
1718 // Otherwise, it returns a pointer to the final nul at the end of the string
1719 mDNSlocal char *FindNextSubType(char *p)
1720 {
1721 while (*p)
1722 {
1723 if (p[0] == '\\' && p[1]) // If escape character
1724 p += 2; // ignore following character
1725 else if (p[0] == ',') // If we found a comma
1726 {
1727 if (p[1]) *p++ = 0;
1728 return(p);
1729 }
1730 else if (p[0] == '.')
1731 return(mDNSNULL);
1732 else p++;
1733 }
1734 return(p);
1735 }
1736
1737 // Returns -1 if illegal subtype found
1738 mDNSexport mDNSs32 ChopSubTypes(char *regtype, char **AnonData)
1739 {
1740 mDNSs32 NumSubTypes = 0;
1741 char *stp = FindFirstSubType(regtype, AnonData);
1742 while (stp && *stp) // If we found a comma...
1743 {
1744 if (*stp == ',') return(-1);
1745 NumSubTypes++;
1746 stp = FindNextSubType(stp);
1747 }
1748 if (!stp) return(-1);
1749 return(NumSubTypes);
1750 }
1751
1752 mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p, char **AnonData)
1753 {
1754 AuthRecord *st = mDNSNULL;
1755 //
1756 // "p" is pointing at the regtype e.g., _http._tcp followed by ":<AnonData>" indicated
1757 // by AnonData being non-NULL which is in turn follwed by ",<SubTypes>" indicated by
1758 // NumSubTypes being non-zero. We need to skip the initial regtype to get to the actual
1759 // data that we want. When we come here, ChopSubTypes has null terminated like this e.g.,
1760 //
1761 // _http._tcp<NULL><AnonData><NULL><SubType1><NULL><SubType2><NULL> etc.
1762 //
1763 // 1. If we have Anonymous data and subtypes, skip the regtype (e.g., "_http._tcp")
1764 // to get the AnonData and then skip the AnonData to get to the SubType.
1765 //
1766 // 2. If we have only SubTypes, skip the regtype to get to the SubType data.
1767 //
1768 // 3. If we have only AnonData, skip the regtype to get to the AnonData.
1769 //
1770 // 4. If we don't have AnonData or NumStypes, it is a noop.
1771 //
1772 if (AnonData)
1773 {
1774 int len;
1775
1776 // Skip the regtype
1777 while (*p) p++;
1778 p++;
1779
1780 len = strlen(p) + 1;
1781 *AnonData = mallocL("Anonymous", len);
1782 if (!(*AnonData))
1783 {
1784 return (mDNSNULL);
1785 }
1786 mDNSPlatformMemCopy(*AnonData, p, len);
1787 }
1788 if (NumSubTypes)
1789 {
1790 mDNSs32 i;
1791 st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord));
1792 if (!st) return(mDNSNULL);
1793 for (i = 0; i < NumSubTypes; i++)
1794 {
1795 mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, AuthRecordAny, mDNSNULL, mDNSNULL);
1796 // First time through we skip the regtype or AnonData. Subsequently, the
1797 // previous subtype.
1798 while (*p) p++;
1799 p++;
1800 if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p))
1801 {
1802 freeL("ServiceSubTypes", st);
1803 if (AnonData && *AnonData)
1804 freeL("AnonymousData", *AnonData);
1805 return(mDNSNULL);
1806 }
1807 }
1808 }
1809 // If NumSubTypes is zero and AnonData is non-NULL, we still return NULL but AnonData has been
1810 // initialized. The caller knows how to handle this.
1811 return(st);
1812 }
1813
1814 mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain)
1815 {
1816 service_instance **ptr, *instance;
1817 size_t extra_size = (request->u.servicereg.txtlen > sizeof(RDataBody)) ? (request->u.servicereg.txtlen - sizeof(RDataBody)) : 0;
1818 const mDNSBool DomainIsLocal = SameDomainName(domain, &localdomain);
1819 mStatus result;
1820 mDNSInterfaceID interfaceID = request->u.servicereg.InterfaceID;
1821 mDNSu32 coreFlags = 0;
1822
1823 if (request->flags & kDNSServiceFlagsIncludeP2P)
1824 coreFlags |= coreFlagIncludeP2P;
1825 if (request->flags & kDNSServiceFlagsIncludeAWDL)
1826 coreFlags |= coreFlagIncludeAWDL;
1827
1828 // Client guarantees that record names are unique, so we can skip sending out initial
1829 // probe messages. Standard name conflict resolution is still done if a conflict is discovered.
1830 if (request->flags & kDNSServiceFlagsKnownUnique)
1831 coreFlags |= coreFlagKnownUnique;
1832
1833 if (request->flags & kDNSServiceFlagsWakeOnlyService)
1834 coreFlags |= coreFlagWakeOnly;
1835
1836 // If the client specified an interface, but no domain, then we honor the specified interface for the "local" (mDNS)
1837 // registration but for the wide-area registrations we don't (currently) have any concept of a wide-area unicast
1838 // registrations scoped to a specific interface, so for the automatic domains we add we must *not* specify an interface.
1839 // (Specifying an interface with an apparently wide-area domain (i.e. something other than "local")
1840 // currently forces the registration to use mDNS multicast despite the apparently wide-area domain.)
1841 if (request->u.servicereg.default_domain && !DomainIsLocal) interfaceID = mDNSInterface_Any;
1842
1843 for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next)
1844 {
1845 if (SameDomainName(&(*ptr)->domain, domain))
1846 {
1847 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
1848 domain->c, &request->u.servicereg.name, &request->u.servicereg.type);
1849 return mStatus_AlreadyRegistered;
1850 }
1851 }
1852
1853 instance = mallocL("service_instance", sizeof(*instance) + extra_size);
1854 if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; }
1855
1856 instance->next = mDNSNULL;
1857 instance->request = request;
1858 instance->renameonmemfree = 0;
1859 instance->clientnotified = mDNSfalse;
1860 instance->default_local = (request->u.servicereg.default_domain && DomainIsLocal);
1861 instance->external_advertise = mDNSfalse;
1862 AssignDomainName(&instance->domain, domain);
1863
1864 instance->srs.AnonData = mDNSNULL;
1865 if (!request->u.servicereg.AnonData)
1866 {
1867 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, mDNSNULL);
1868 }
1869 else
1870 {
1871 char *AnonData = mDNSNULL;
1872 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string, &AnonData);
1873 if (AnonData)
1874 instance->srs.AnonData = (const mDNSu8 *)AnonData;
1875 }
1876
1877 if (request->u.servicereg.num_subtypes && !instance->subtypes)
1878 {
1879 unlink_and_free_service_instance(instance);
1880 instance = NULL;
1881 FatalError("ERROR: malloc");
1882 }
1883
1884 result = mDNS_RegisterService(&mDNSStorage, &instance->srs,
1885 &request->u.servicereg.name, &request->u.servicereg.type, domain,
1886 request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL,
1887 request->u.servicereg.port,
1888 request->u.servicereg.txtdata, request->u.servicereg.txtlen,
1889 instance->subtypes, request->u.servicereg.num_subtypes,
1890 interfaceID, regservice_callback, instance, coreFlags);
1891
1892 if (!result)
1893 {
1894 *ptr = instance; // Append this to the end of our request->u.servicereg.instances list
1895 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", instance->request->sd,
1896 instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port));
1897 LogMcastS(&mDNSStorage, &instance->srs.RR_SRV, request, reg_start);
1898 }
1899 else
1900 {
1901 LogMsg("register_service_instance %#s.%##s%##s error %d",
1902 &request->u.servicereg.name, &request->u.servicereg.type, domain->c, result);
1903 unlink_and_free_service_instance(instance);
1904 }
1905
1906 return result;
1907 }
1908
1909 mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add)
1910 {
1911 request_state *request;
1912
1913 LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c);
1914 for (request = all_requests; request; request = request->next)
1915 {
1916 if (request->terminate != regservice_termination_callback) continue;
1917 if (!request->u.servicereg.default_domain) continue;
1918 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
1919 {
1920 service_instance **ptr = &request->u.servicereg.instances;
1921 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
1922 if (add)
1923 {
1924 // If we don't already have this domain in our list for this registration, add it now
1925 if (!*ptr) register_service_instance(request, &d->name);
1926 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name);
1927 }
1928 else
1929 {
1930 // Normally we should not fail to find the specified instance
1931 // One case where this can happen is if a uDNS update fails for some reason,
1932 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
1933 if (!*ptr)
1934 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
1935 &d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string);
1936 else
1937 {
1938 DNameListElem *p;
1939 for (p = AutoRegistrationDomains; p; p=p->next)
1940 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
1941 if (SameDomainName(&d->name, &p->name)) break;
1942 if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name);
1943 else
1944 {
1945 mStatus err;
1946 service_instance *si = *ptr;
1947 *ptr = si->next;
1948 if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer
1949 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
1950 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
1951 // process of completing asynchronously, the client cancels the entire operation, so
1952 // regservice_termination_callback then runs through the whole list deregistering each
1953 // instance, clearing the backpointers, and then disposing the parent request_state object.
1954 // However, because this service_instance isn't in the list any more, regservice_termination_callback
1955 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
1956 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
1957 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
1958 si->request = NULL;
1959 err = mDNS_DeregisterService(&mDNSStorage, &si->srs);
1960 if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); }
1961 }
1962 }
1963 }
1964 }
1965 }
1966 }
1967
1968 // Don't allow normal and anonymous registration to coexist.
1969 mDNSlocal mDNSBool CheckForMixedRegistrations(domainname *regtype, domainname *domain, mDNSBool AnonData)
1970 {
1971 request_state *request;
1972
1973 // We only care about local domains where the anonymous extension is
1974 // implemented.
1975 if (!SameDomainName(domain, (const domainname *) "\x5" "local"))
1976 {
1977 return mDNStrue;
1978 }
1979
1980 for (request = all_requests; request; request = request->next)
1981 {
1982 service_instance *ptr;
1983
1984 if (request->terminate != regservice_termination_callback) continue;
1985 for (ptr = request->u.servicereg.instances; ptr ; ptr = ptr->next)
1986 {
1987 if (!SameDomainName(&ptr->domain, (const domainname *)"\x5" "local") ||
1988 !SameDomainName(&request->u.servicereg.type, regtype))
1989 {
1990 continue;
1991 }
1992
1993 // If we are about to register a anonymous registraion, we dont't want to
1994 // allow the regular ones and vice versa.
1995 if (AnonData)
1996 {
1997 if (!ptr->srs.AnonData)
1998 {
1999 LogMsg("CheckForMixedRegistrations: Normal registration already exists for %##s", regtype->c);
2000 return mDNSfalse;
2001 }
2002 }
2003 else
2004 {
2005 // Allow multiple regular registrations
2006 if (ptr->srs.AnonData)
2007 {
2008 LogMsg("CheckForMixedRegistrations: Anonymous registration already exists for %##s", regtype->c);
2009 return mDNSfalse;
2010 }
2011 }
2012 }
2013 }
2014 return mDNStrue;
2015 }
2016
2017 // Returns true if the interfaceIndex value matches one of the pre-defined
2018 // special values listed in the switch statement below.
2019 mDNSlocal mDNSBool PreDefinedInterfaceIndex(mDNSu32 interfaceIndex)
2020 {
2021 switch(interfaceIndex)
2022 {
2023 case kDNSServiceInterfaceIndexAny:
2024 case kDNSServiceInterfaceIndexLocalOnly:
2025 case kDNSServiceInterfaceIndexUnicast:
2026 case kDNSServiceInterfaceIndexP2P:
2027 return mDNStrue;
2028 default:
2029 return mDNSfalse;
2030 }
2031 }
2032
2033 mDNSlocal mStatus handle_regservice_request(request_state *request)
2034 {
2035 char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
2036 char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME];
2037 char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
2038 domainname d, srv;
2039 mStatus err;
2040 char *AnonData = mDNSNULL;
2041 const char *msgTXTData;
2042
2043 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2044 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2045 mDNSInterfaceID InterfaceID;
2046
2047 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the
2048 // kDNSServiceFlagsIncludeP2P flag set.
2049 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
2050 {
2051 LogOperation("handle_regservice_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2052 flags |= kDNSServiceFlagsIncludeP2P;
2053 interfaceIndex = kDNSServiceInterfaceIndexAny;
2054 }
2055
2056 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2057
2058 // The registration is scoped to a specific interface index, but the
2059 // interface is not currently in our list.
2060 if (interfaceIndex && !InterfaceID)
2061 {
2062 // If it's one of the specially defined inteface index values, just return an error.
2063 if (PreDefinedInterfaceIndex(interfaceIndex))
2064 {
2065 LogInfo("handle_regservice_request: bad interfaceIndex %d", interfaceIndex);
2066 return(mStatus_BadParamErr);
2067 }
2068
2069 // Otherwise, use the specified interface index value and the registration will
2070 // be applied to that interface when it comes up.
2071 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2072 LogInfo("handle_regservice_request: registration pending for interface index %d", interfaceIndex);
2073 }
2074
2075 if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 ||
2076 get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2077 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2078 get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0)
2079 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2080
2081 request->flags = flags;
2082 request->interfaceIndex = interfaceIndex;
2083 request->u.servicereg.InterfaceID = InterfaceID;
2084 request->u.servicereg.instances = NULL;
2085 request->u.servicereg.txtlen = 0;
2086 request->u.servicereg.txtdata = NULL;
2087 mDNSPlatformStrLCopy(request->u.servicereg.type_as_string, type_as_string, sizeof(request->u.servicereg.type_as_string));
2088
2089 if (request->msgptr + 2 > request->msgend) request->msgptr = NULL;
2090 else
2091 {
2092 request->u.servicereg.port.b[0] = *request->msgptr++;
2093 request->u.servicereg.port.b[1] = *request->msgptr++;
2094 }
2095
2096 request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend);
2097 msgTXTData = get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen);
2098
2099 if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2100
2101 if (request->u.servicereg.txtlen)
2102 {
2103 request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen);
2104 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc");
2105 mDNSPlatformMemCopy(request->u.servicereg.txtdata, msgTXTData, request->u.servicereg.txtlen);
2106 }
2107
2108 // Check for sub-types after the service type
2109 request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
2110 if (request->u.servicereg.num_subtypes < 0)
2111 {
2112 LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string);
2113 goto bad_param;
2114 }
2115 if (AnonData)
2116 {
2117 int AnonDataLen = strlen(AnonData);
2118 if (AnonDataLen > MAX_ANONYMOUS_DATA)
2119 {
2120 LogMsg("ERROR: handle_regservice_request: AnonDataLen %d", AnonDataLen);
2121 goto bad_param;
2122 }
2123 request->u.servicereg.AnonData = mDNStrue;
2124 }
2125 else
2126 {
2127 request->u.servicereg.AnonData = mDNSfalse;
2128 }
2129
2130 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
2131 if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string))
2132 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); goto bad_param; }
2133
2134 if (!name[0])
2135 {
2136 request->u.servicereg.name = mDNSStorage.nicelabel;
2137 request->u.servicereg.autoname = mDNStrue;
2138 }
2139 else
2140 {
2141 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
2142 if ((flags & kDNSServiceFlagsNoAutoRename) == 0)
2143 {
2144 int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL);
2145 name[newlen] = 0;
2146 }
2147 if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name))
2148 { LogMsg("ERROR: handle_regservice_request - name bad %s", name); goto bad_param; }
2149 request->u.servicereg.autoname = mDNSfalse;
2150 }
2151
2152 if (*domain)
2153 {
2154 request->u.servicereg.default_domain = mDNSfalse;
2155 if (!MakeDomainNameFromDNSNameString(&d, domain))
2156 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); goto bad_param; }
2157 }
2158 else
2159 {
2160 request->u.servicereg.default_domain = mDNStrue;
2161 MakeDomainNameFromDNSNameString(&d, "local.");
2162 }
2163
2164 // We don't allow the anonymous and the regular ones to coexist
2165 if (!CheckForMixedRegistrations(&request->u.servicereg.type, &d, request->u.servicereg.AnonData)) { goto bad_param; }
2166
2167 if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d))
2168 {
2169 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
2170 request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); goto bad_param;
2171 }
2172
2173 if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host))
2174 { LogMsg("ERROR: handle_regservice_request - host bad %s", host); goto bad_param; }
2175 request->u.servicereg.autorename = (flags & kDNSServiceFlagsNoAutoRename ) == 0;
2176 request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0;
2177
2178 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
2179 // a port number of zero. When two instances of the protected client are allowed to run on one
2180 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
2181 if (!mDNSIPPortIsZero(request->u.servicereg.port))
2182 {
2183 int count = CountExistingRegistrations(&srv, request->u.servicereg.port);
2184 if (count)
2185 LogMsg("Client application[%d](%s) registered %d identical instances of service %##s port %u.", request->process_id,
2186 request->pid_name, count+1, srv.c, mDNSVal16(request->u.servicereg.port));
2187 }
2188
2189 LogOperation("%3d: DNSServiceRegister(%X, %d, \"%s\", \"%s\", \"%s\", \"%s\", %u) START PID[%d](%s)",
2190 request->sd, flags, interfaceIndex, name, request->u.servicereg.type_as_string, domain, host,
2191 mDNSVal16(request->u.servicereg.port), request->process_id, request->pid_name);
2192
2193 // We need to unconditionally set request->terminate, because even if we didn't successfully
2194 // start any registrations right now, subsequent configuration changes may cause successful
2195 // registrations to be added, and we'll need to cancel them before freeing this memory.
2196 // We also need to set request->terminate first, before adding additional service instances,
2197 // because the uds_validatelists uses the request->terminate function pointer to determine
2198 // what kind of request this is, and therefore what kind of list validation is required.
2199 request->terminate = regservice_termination_callback;
2200
2201 err = register_service_instance(request, &d);
2202
2203 #if TARGET_OS_EMBEDDED
2204 ++curr_num_regservices;
2205 if (curr_num_regservices > max_num_regservices)
2206 max_num_regservices = curr_num_regservices;
2207 #endif
2208
2209 #if 0
2210 err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError;
2211 #endif
2212 if (!err)
2213 {
2214 if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage);
2215
2216 if (!*domain)
2217 {
2218 DNameListElem *ptr;
2219 // Note that we don't report errors for non-local, non-explicit domains
2220 for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next)
2221 if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid)
2222 register_service_instance(request, &ptr->name);
2223 }
2224 }
2225
2226 return(err);
2227
2228 bad_param:
2229 freeL("handle_regservice_request (txtdata)", request->u.servicereg.txtdata);
2230 request->u.servicereg.txtdata = NULL;
2231 return mStatus_BadParamErr;
2232 }
2233
2234 // ***************************************************************************
2235 #if COMPILER_LIKES_PRAGMA_MARK
2236 #pragma mark -
2237 #pragma mark - DNSServiceBrowse
2238 #endif
2239
2240 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2241 {
2242 DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0;
2243 request_state *req = question->QuestionContext;
2244 reply_state *rep;
2245 (void)m; // Unused
2246
2247 if (answer->rrtype != kDNSType_PTR)
2248 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; }
2249
2250 if (mDNSOpaque16IsZero(question->TargetQID) && (question->BrowseThreshold > 0) && (question->CurrentAnswers >= question->BrowseThreshold))
2251 {
2252 flags |= kDNSServiceFlagsThresholdReached;
2253 }
2254
2255 // if returning a negative answer, then use question's name in reply
2256 if (answer->RecordType == kDNSRecordTypePacketNegative)
2257 {
2258 GenerateBrowseReply(&question->qname, answer->InterfaceID, req, &rep, browse_reply_op, flags, kDNSServiceErr_NoSuchRecord);
2259 goto validReply;
2260 }
2261
2262 if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError)
2263 {
2264 if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp"))
2265 {
2266 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2267 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2268 GenerateBrowseReply(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError);
2269 goto validReply;
2270 }
2271
2272 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2273 req->sd, answer->name->c, answer->rdata->u.name.c);
2274 return;
2275 }
2276
2277 validReply:
2278
2279 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
2280 req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "Add" : "Rmv",
2281 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse), RRDisplayString(m, answer));
2282
2283 append_reply(req, rep);
2284 }
2285
2286 mDNSlocal void SetQuestionPolicy(DNSQuestion *q, request_state *req)
2287 {
2288 int i;
2289 q->euid = req->uid;
2290 // The policy is either based on pid or UUID. Pass a zero pid
2291 // to the "core" if the UUID is valid. If we always pass the pid,
2292 // then the "core" needs to determine whether the uuid is valid
2293 // by examining all the 16 bytes at the time of the policy
2294 // check and also when setting the delegate socket option. Also, it
2295 // requires that we zero out the uuid wherever the question is
2296 // initialized to make sure that it is not interpreted as valid.
2297 // To prevent these intrusive changes, just pass a zero pid to indicate
2298 // that pid is not valid when uuid is valid. In future if we need the
2299 // pid in the question, we will reevaluate this strategy.
2300 if (req->validUUID)
2301 {
2302 for (i = 0; i < UUID_SIZE; i++)
2303 {
2304 q->uuid[i] = req->uuid[i];
2305 }
2306 q->pid = 0;
2307 }
2308 else
2309 {
2310 q->pid = req->process_id;
2311 }
2312
2313 //debugf("SetQuestionPolicy: q->euid[%d] q->pid[%d] uuid is valid : %s", q->euid, q->pid, req->validUUID ? "true" : "false");
2314 }
2315
2316 mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d)
2317 {
2318 browser_t *b, *p;
2319 mStatus err;
2320
2321 for (p = info->u.browser.browsers; p; p = p->next)
2322 {
2323 if (SameDomainName(&p->domain, d))
2324 { debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; }
2325 }
2326
2327 b = mallocL("browser_t", sizeof(*b));
2328 if (!b) return mStatus_NoMemoryErr;
2329 mDNSPlatformMemZero(b, sizeof(*b));
2330 AssignDomainName(&b->domain, d);
2331 SetQuestionPolicy(&b->q, info);
2332 err = mDNS_StartBrowse(&mDNSStorage, &b->q, &info->u.browser.regtype, d, info->u.browser.AnonData, info->u.browser.interface_id, info->flags,
2333 info->u.browser.ForceMCast, (info->flags & kDNSServiceFlagsBackgroundTrafficClass) != 0, FoundInstance, info);
2334 if (err)
2335 {
2336 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c);
2337 freeL("browser_t/add_domain_to_browser", b);
2338 }
2339 else
2340 {
2341 b->next = info->u.browser.browsers;
2342 info->u.browser.browsers = b;
2343 LogOperation("%3d: DNSServiceBrowse(%##s) START PID[%d](%s)", info->sd, b->q.qname.c, info->process_id,
2344 info->pid_name);
2345 LogMcastQ(&mDNSStorage, &b->q, info, q_start);
2346 if (callExternalHelpers(info->u.browser.interface_id, &b->domain, info->flags))
2347 {
2348 domainname tmp;
2349 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &b->domain);
2350 LogInfo("add_domain_to_browser: calling external_start_browsing_for_service()");
2351 external_start_browsing_for_service(info->u.browser.interface_id, &tmp, kDNSType_PTR, info->flags, &b->q);
2352 }
2353 }
2354 return err;
2355 }
2356
2357 mDNSlocal void browse_termination_callback(request_state *info)
2358 {
2359 if (info->u.browser.default_domain)
2360 {
2361 // Stop the domain enumeration queries to discover the WAB legacy browse domains
2362 LogInfo("%3d: DNSServiceBrowse Cancel WAB PID[%d](%s)", info->sd, info->process_id, info->pid_name);
2363 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2364 }
2365 if (info->u.browser.AnonData)
2366 freeL("Anonymous", (void *)info->u.browser.AnonData);
2367 while (info->u.browser.browsers)
2368 {
2369 browser_t *ptr = info->u.browser.browsers;
2370
2371 if (callExternalHelpers(ptr->q.InterfaceID, &ptr->domain, ptr->q.flags))
2372 {
2373 domainname tmp;
2374 ConstructServiceName(&tmp, NULL, &info->u.browser.regtype, &ptr->domain);
2375 LogInfo("browse_termination_callback: calling external_stop_browsing_for_service()");
2376 external_stop_browsing_for_service(ptr->q.InterfaceID, &tmp, kDNSType_PTR, ptr->q.flags);
2377 }
2378
2379 info->u.browser.browsers = ptr->next;
2380 LogOperation("%3d: DNSServiceBrowse(%##s) STOP PID[%d](%s)", info->sd, ptr->q.qname.c, info->process_id, info->pid_name);
2381 mDNS_StopBrowse(&mDNSStorage, &ptr->q); // no need to error-check result
2382 LogMcastQ(&mDNSStorage, &ptr->q, info, q_stop);
2383 freeL("browser_t/browse_termination_callback", ptr);
2384 }
2385 }
2386
2387 mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add)
2388 {
2389 request_state *request;
2390 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c);
2391
2392 for (request = all_requests; request; request = request->next)
2393 {
2394 if (request->terminate != browse_termination_callback) continue; // Not a browse operation
2395 if (!request->u.browser.default_domain) continue; // Not an auto-browse operation
2396 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid)
2397 {
2398 browser_t **ptr = &request->u.browser.browsers;
2399 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next;
2400 if (add)
2401 {
2402 // If we don't already have this domain in our list for this browse operation, add it now
2403 if (!*ptr) add_domain_to_browser(request, &d->name);
2404 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name);
2405 }
2406 else
2407 {
2408 if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name);
2409 else
2410 {
2411 DNameListElem *p;
2412 for (p = AutoBrowseDomains; p; p=p->next)
2413 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid)
2414 if (SameDomainName(&d->name, &p->name)) break;
2415 if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name);
2416 else
2417 {
2418 browser_t *rem = *ptr;
2419 *ptr = (*ptr)->next;
2420 mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
2421 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem);
2422 }
2423 }
2424 }
2425 }
2426 }
2427 }
2428
2429 mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
2430 {
2431 (void)m; // unused
2432 if (result == mStatus_MemFree)
2433 {
2434 // On shutdown, mDNS_Close automatically deregisters all records
2435 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2436 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2437 // (This should actually no longer be necessary, now that we do the proper cleanup in
2438 // udsserver_exit. To confirm this, we'll log an error message if we do find a record that
2439 // hasn't been cut from the list yet. If these messages don't appear, we can delete this code.)
2440 ARListElem **ptr = &LocalDomainEnumRecords;
2441 while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
2442 if (*ptr) { *ptr = (*ptr)->next; LogMsg("FreeARElemCallback: Have to cut %s", ARDisplayString(m, rr)); }
2443 mDNSPlatformMemFree(rr->RecordContext);
2444 }
2445 }
2446
2447 // RegisterLocalOnlyDomainEnumPTR and DeregisterLocalOnlyDomainEnumPTR largely duplicate code in
2448 // "FoundDomain" in uDNS.c for creating and destroying these special mDNSInterface_LocalOnly records.
2449 // We may want to turn the common code into a subroutine.
2450
2451 mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2452 {
2453 // allocate/register legacy and non-legacy _browse PTR record
2454 mStatus err;
2455 ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr));
2456
2457 debugf("Incrementing %s refcount for %##s",
2458 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2459 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2460 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2461
2462 mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, AuthRecordLocalOnly, FreeARElemCallback, ptr);
2463 MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]);
2464 AppendDNSNameString (&ptr->ar.namestorage, "local");
2465 AssignDomainName(&ptr->ar.resrec.rdata->u.name, d);
2466 err = mDNS_Register(m, &ptr->ar);
2467 if (err)
2468 {
2469 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err);
2470 mDNSPlatformMemFree(ptr);
2471 }
2472 else
2473 {
2474 ptr->next = LocalDomainEnumRecords;
2475 LocalDomainEnumRecords = ptr;
2476 }
2477 }
2478
2479 mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type)
2480 {
2481 ARListElem **ptr = &LocalDomainEnumRecords;
2482 domainname lhs; // left-hand side of PTR, for comparison
2483
2484 debugf("Decrementing %s refcount for %##s",
2485 (type == mDNS_DomainTypeBrowse ) ? "browse domain " :
2486 (type == mDNS_DomainTypeRegistration ) ? "registration dom" :
2487 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c);
2488
2489 MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]);
2490 AppendDNSNameString (&lhs, "local");
2491
2492 while (*ptr)
2493 {
2494 if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs))
2495 {
2496 ARListElem *rem = *ptr;
2497 *ptr = (*ptr)->next;
2498 mDNS_Deregister(m, &rem->ar);
2499 return;
2500 }
2501 else ptr = &(*ptr)->next;
2502 }
2503 }
2504
2505 mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2506 {
2507 DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem));
2508 if (!new) { LogMsg("ERROR: malloc"); return; }
2509 AssignDomainName(&new->name, name);
2510 new->uid = uid;
2511 new->next = AutoBrowseDomains;
2512 AutoBrowseDomains = new;
2513 udsserver_automatic_browse_domain_changed(new, mDNStrue);
2514 }
2515
2516 mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name)
2517 {
2518 DNameListElem **p = &AutoBrowseDomains;
2519 while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next;
2520 if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c);
2521 else
2522 {
2523 DNameListElem *ptr = *p;
2524 *p = ptr->next;
2525 udsserver_automatic_browse_domain_changed(ptr, mDNSfalse);
2526 mDNSPlatformMemFree(ptr);
2527 }
2528 }
2529
2530 mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add)
2531 {
2532 DNameListElem *d;
2533 for (d = browseDomains; d; d = d->next)
2534 {
2535 if (add)
2536 {
2537 RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2538 AddAutoBrowseDomain(d->uid, &d->name);
2539 }
2540 else
2541 {
2542 DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse);
2543 RmvAutoBrowseDomain(d->uid, &d->name);
2544 }
2545 }
2546 }
2547
2548 #if APPLE_OSX_mDNSResponder
2549
2550 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2551 {
2552 int num_autoname = 0;
2553 request_state *req;
2554
2555 // Don't need to register the device info record for kDNSServiceInterfaceIndexLocalOnly registrations.
2556 for (req = all_requests; req; req = req->next)
2557 {
2558 if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname && req->interfaceIndex != kDNSServiceInterfaceIndexLocalOnly)
2559 num_autoname++;
2560 }
2561
2562 // If DeviceInfo record is currently registered, see if we need to deregister it
2563 if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered)
2564 if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c))
2565 {
2566 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name);
2567 mDNS_Deregister(m, &m->DeviceInfo);
2568 }
2569
2570 // If DeviceInfo record is not currently registered, see if we need to register it
2571 if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
2572 if (num_autoname > 0)
2573 {
2574 mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, AuthRecordAny, mDNSNULL, mDNSNULL);
2575 ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain);
2576 m->DeviceInfo.resrec.rdlength = initializeDeviceInfoTXT(m, m->DeviceInfo.resrec.rdata->u.data);
2577 LogOperation("UpdateDeviceInfoRecord Register %##s", m->DeviceInfo.resrec.name);
2578 mDNS_Register(m, &m->DeviceInfo);
2579 }
2580 }
2581 #else // APPLE_OSX_mDNSResponder
2582 mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m)
2583 {
2584 (void)m; // unused
2585 }
2586 #endif // APPLE_OSX_mDNSResponder
2587
2588 mDNSexport void udsserver_handle_configchange(mDNS *const m)
2589 {
2590 request_state *req;
2591 service_instance *ptr;
2592 DNameListElem *RegDomains = NULL;
2593 DNameListElem *BrowseDomains = NULL;
2594 DNameListElem *p;
2595
2596 UpdateDeviceInfoRecord(m);
2597
2598 // For autoname services, see if the default service name has changed, necessitating an automatic update
2599 for (req = all_requests; req; req = req->next)
2600 if (req->terminate == regservice_termination_callback)
2601 if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c))
2602 {
2603 req->u.servicereg.name = m->nicelabel;
2604 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
2605 {
2606 ptr->renameonmemfree = 1;
2607 if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs);
2608 LogInfo("udsserver_handle_configchange: Calling deregister for Service %##s", ptr->srs.RR_PTR.resrec.name->c);
2609 if (mDNS_DeregisterService_drt(m, &ptr->srs, mDNS_Dereg_rapid))
2610 regservice_callback(m, &ptr->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
2611 }
2612 }
2613
2614 // Let the platform layer get the current DNS information
2615 mDNS_Lock(m);
2616 mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains, mDNSfalse);
2617 mDNS_Unlock(m);
2618
2619 // Any automatic registration domains are also implicitly automatic browsing domains
2620 if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue); // Add the new list first
2621 if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse); // Then clear the old list
2622
2623 // Add any new domains not already in our AutoRegistrationDomains list
2624 for (p=RegDomains; p; p=p->next)
2625 {
2626 DNameListElem **pp = &AutoRegistrationDomains;
2627 while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next;
2628 if (!*pp) // If not found in our existing list, this is a new default registration domain
2629 {
2630 RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration);
2631 udsserver_default_reg_domain_changed(p, mDNStrue);
2632 }
2633 else // else found same domainname in both old and new lists, so no change, just delete old copy
2634 {
2635 DNameListElem *del = *pp;
2636 *pp = (*pp)->next;
2637 mDNSPlatformMemFree(del);
2638 }
2639 }
2640
2641 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2642 while (AutoRegistrationDomains)
2643 {
2644 DNameListElem *del = AutoRegistrationDomains;
2645 AutoRegistrationDomains = AutoRegistrationDomains->next; // Cut record from list FIRST,
2646 DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration);
2647 udsserver_default_reg_domain_changed(del, mDNSfalse); // before calling udsserver_default_reg_domain_changed()
2648 mDNSPlatformMemFree(del);
2649 }
2650
2651 // Now we have our new updated automatic registration domain list
2652 AutoRegistrationDomains = RegDomains;
2653
2654 // Add new browse domains to internal list
2655 if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue);
2656
2657 // Remove old browse domains from internal list
2658 if (SCPrefBrowseDomains)
2659 {
2660 SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse);
2661 while (SCPrefBrowseDomains)
2662 {
2663 DNameListElem *fptr = SCPrefBrowseDomains;
2664 SCPrefBrowseDomains = SCPrefBrowseDomains->next;
2665 mDNSPlatformMemFree(fptr);
2666 }
2667 }
2668
2669 // Replace the old browse domains array with the new array
2670 SCPrefBrowseDomains = BrowseDomains;
2671 }
2672
2673 mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord)
2674 {
2675 (void)m; // unused;
2676 (void)q; // unused
2677
2678 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2679 AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c);
2680
2681 if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name);
2682 else RmvAutoBrowseDomain(0, &answer->rdata->u.name);
2683 }
2684
2685 mDNSlocal mStatus handle_browse_request(request_state *request)
2686 {
2687 char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2688 domainname typedn, d, temp;
2689 mDNSs32 NumSubTypes;
2690 char *AnonData = mDNSNULL;
2691 mStatus err = mStatus_NoError;
2692 int AnonDataLen;
2693
2694 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2695 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2696 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2697
2698 // The browse is scoped to a specific interface index, but the
2699 // interface is not currently in our list.
2700 if (interfaceIndex && !InterfaceID)
2701 {
2702 // If it's one of the specially defined inteface index values, just return an error.
2703 if (PreDefinedInterfaceIndex(interfaceIndex))
2704 {
2705 LogInfo("handle_browse_request: bad interfaceIndex %d", interfaceIndex);
2706 return(mStatus_BadParamErr);
2707 }
2708
2709 // Otherwise, use the specified interface index value and the browse will
2710 // be applied to that interface when it comes up.
2711 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2712 LogInfo("handle_browse_request: browse pending for interface index %d", interfaceIndex);
2713 }
2714
2715 if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2716 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr);
2717
2718 if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2719
2720 request->flags = flags;
2721 request->interfaceIndex = interfaceIndex;
2722 typedn.c[0] = 0;
2723 NumSubTypes = ChopSubTypes(regtype, &AnonData); // Note: Modifies regtype string to remove trailing subtypes
2724 if (NumSubTypes < 0 || NumSubTypes > 1)
2725 return(mStatus_BadParamErr);
2726 AnonDataLen = 0;
2727 if (AnonData)
2728 {
2729 AnonDataLen = strlen(AnonData);
2730 if (AnonDataLen > MAX_ANONYMOUS_DATA)
2731 {
2732 LogMsg("handle_browse_request: AnonDataLen %d", AnonDataLen);
2733 return(mStatus_BadParamErr);
2734 }
2735 // Account for the null byte
2736 AnonDataLen += 1;
2737 }
2738 if (NumSubTypes == 1)
2739 {
2740 if (!AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1 + AnonDataLen))
2741 return(mStatus_BadParamErr);
2742 }
2743
2744 if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr);
2745
2746 if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr);
2747 // For over-long service types, we only allow domain "local"
2748 if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrLCopy(domain, "local.", sizeof(domain));
2749
2750 // Set up browser info
2751 request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0;
2752 request->u.browser.interface_id = InterfaceID;
2753 AssignDomainName(&request->u.browser.regtype, &typedn);
2754 request->u.browser.default_domain = !domain[0];
2755 request->u.browser.browsers = NULL;
2756
2757 LogOperation("%3d: DNSServiceBrowse(%X, %d, \"%##s\", \"%s\") START PID[%d](%s)",
2758 request->sd, request->flags, interfaceIndex, request->u.browser.regtype.c, domain, request->process_id, request->pid_name);
2759
2760 if (request->u.browser.default_domain)
2761 {
2762 // Start the domain enumeration queries to discover the WAB browse domains
2763 LogInfo("%3d: DNSServiceBrowse Start WAB PID[%d](%s)", request->sd, request->process_id, request->pid_name);
2764 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_LBROWSE_QUERY);
2765 }
2766 request->u.browser.AnonData = mDNSNULL;
2767 if (AnonData)
2768 {
2769 int len = strlen(AnonData) + 1;
2770 request->u.browser.AnonData = mallocL("Anonymous", len);
2771 if (!request->u.browser.AnonData)
2772 return mStatus_NoMemoryErr;
2773 else
2774 mDNSPlatformMemCopy((void *)request->u.browser.AnonData, AnonData, len);
2775 }
2776 // We need to unconditionally set request->terminate, because even if we didn't successfully
2777 // start any browses right now, subsequent configuration changes may cause successful
2778 // browses to be added, and we'll need to cancel them before freeing this memory.
2779 request->terminate = browse_termination_callback;
2780
2781 if (domain[0])
2782 {
2783 if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr);
2784 err = add_domain_to_browser(request, &d);
2785 }
2786 else
2787 {
2788 DNameListElem *sdom;
2789 for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next)
2790 if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid)
2791 {
2792 err = add_domain_to_browser(request, &sdom->name);
2793 if (err)
2794 {
2795 if (SameDomainName(&sdom->name, &localdomain)) break;
2796 else err = mStatus_NoError; // suppress errors for non-local "default" domains
2797 }
2798 }
2799 }
2800
2801 return(err);
2802 }
2803
2804 // ***************************************************************************
2805 #if COMPILER_LIKES_PRAGMA_MARK
2806 #pragma mark -
2807 #pragma mark - DNSServiceResolve
2808 #endif
2809
2810 mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
2811 {
2812 size_t len = 0;
2813 char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME] = "0";
2814 char *data;
2815 reply_state *rep;
2816 request_state *req = question->QuestionContext;
2817 const DNSServiceErrorType error =
2818 (answer->RecordType == kDNSRecordTypePacketNegative) ? kDNSServiceErr_NoSuchRecord : kDNSServiceErr_NoError;
2819 (void)m; // Unused
2820
2821 LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req->sd, question->qname.c, AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
2822
2823 if (!AddRecord)
2824 {
2825 if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL;
2826 if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL;
2827 return;
2828 }
2829
2830 if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer;
2831 if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer;
2832
2833 if (!req->u.resolve.txt || !req->u.resolve.srv) return; // only deliver result to client if we have both answers
2834
2835 ConvertDomainNameToCString(answer->name, fullname);
2836
2837 if (answer->RecordType != kDNSRecordTypePacketNegative)
2838 ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target);
2839
2840 // calculate reply length
2841 len += sizeof(DNSServiceFlags);
2842 len += sizeof(mDNSu32); // interface index
2843 len += sizeof(DNSServiceErrorType);
2844 len += strlen(fullname) + 1;
2845 len += strlen(target) + 1;
2846 len += 2 * sizeof(mDNSu16); // port, txtLen
2847 len += req->u.resolve.txt->rdlength;
2848
2849 // allocate/init reply header
2850 rep = create_reply(resolve_reply_op, len, req);
2851 rep->rhdr->flags = dnssd_htonl(0);
2852 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNSfalse));
2853 rep->rhdr->error = dnssd_htonl(error);
2854
2855 data = (char *)&rep->rhdr[1];
2856
2857 // write reply data to message
2858 put_string(fullname, &data);
2859 put_string(target, &data);
2860 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[0];
2861 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[1];
2862 put_uint16(req->u.resolve.txt->rdlength, &data);
2863 put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data);
2864
2865 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port));
2866 append_reply(req, rep);
2867 }
2868
2869 mDNSlocal void resolve_termination_callback(request_state *request)
2870 {
2871 LogOperation("%3d: DNSServiceResolve(%##s) STOP PID[%d](%s)", request->sd, request->u.resolve.qtxt.qname.c, request->process_id, request->pid_name);
2872 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt);
2873 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
2874 LogMcastQ(&mDNSStorage, &request->u.resolve.qsrv, request, q_stop);
2875 if (request->u.resolve.external_advertise)
2876 external_stop_resolving_service(request->u.resolve.qsrv.InterfaceID, &request->u.resolve.qsrv.qname, request->flags);
2877 }
2878
2879 mDNSlocal mStatus handle_resolve_request(request_state *request)
2880 {
2881 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
2882 domainname fqdn;
2883 mStatus err;
2884
2885 // extract the data from the message
2886 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
2887 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
2888 mDNSInterfaceID InterfaceID;
2889
2890 // Map kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny with the kDNSServiceFlagsIncludeP2P
2891 // flag set so that the resolve will run over P2P interfaces that are not yet created.
2892 if (interfaceIndex == kDNSServiceInterfaceIndexP2P)
2893 {
2894 LogOperation("handle_resolve_request: mapping kDNSServiceInterfaceIndexP2P to kDNSServiceInterfaceIndexAny + kDNSServiceFlagsIncludeP2P");
2895 flags |= kDNSServiceFlagsIncludeP2P;
2896 interfaceIndex = kDNSServiceInterfaceIndexAny;
2897 }
2898
2899 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
2900
2901 // The operation is scoped to a specific interface index, but the
2902 // interface is not currently in our list.
2903 if (interfaceIndex && !InterfaceID)
2904 {
2905 // If it's one of the specially defined inteface index values, just return an error.
2906 if (PreDefinedInterfaceIndex(interfaceIndex))
2907 {
2908 LogInfo("handle_resolve_request: bad interfaceIndex %d", interfaceIndex);
2909 return(mStatus_BadParamErr);
2910 }
2911
2912 // Otherwise, use the specified interface index value and the operation will
2913 // be applied to that interface when it comes up.
2914 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
2915 LogInfo("handle_resolve_request: resolve pending for interface index %d", interfaceIndex);
2916 }
2917
2918 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
2919 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
2920 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
2921 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); }
2922
2923 if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
2924
2925 if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0)
2926 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); }
2927
2928 mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve));
2929
2930 request->flags = flags;
2931 request->interfaceIndex = interfaceIndex;
2932
2933 // format questions
2934 request->u.resolve.qsrv.InterfaceID = InterfaceID;
2935 request->u.resolve.qsrv.flags = flags;
2936 request->u.resolve.qsrv.Target = zeroAddr;
2937 AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn);
2938 request->u.resolve.qsrv.qtype = kDNSType_SRV;
2939 request->u.resolve.qsrv.qclass = kDNSClass_IN;
2940 request->u.resolve.qsrv.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2941 request->u.resolve.qsrv.ExpectUnique = mDNStrue;
2942 request->u.resolve.qsrv.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2943 request->u.resolve.qsrv.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2944 request->u.resolve.qsrv.SuppressUnusable = mDNSfalse;
2945 request->u.resolve.qsrv.SearchListIndex = 0;
2946 request->u.resolve.qsrv.AppendSearchDomains = 0;
2947 request->u.resolve.qsrv.RetryWithSearchDomains = mDNSfalse;
2948 request->u.resolve.qsrv.TimeoutQuestion = 0;
2949 request->u.resolve.qsrv.WakeOnResolve = (flags & kDNSServiceFlagsWakeOnResolve) != 0;
2950 request->u.resolve.qsrv.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2951 request->u.resolve.qsrv.ValidationRequired = 0;
2952 request->u.resolve.qsrv.ValidatingResponse = 0;
2953 request->u.resolve.qsrv.ProxyQuestion = 0;
2954 request->u.resolve.qsrv.qnameOrig = mDNSNULL;
2955 request->u.resolve.qsrv.AnonInfo = mDNSNULL;
2956 request->u.resolve.qsrv.pid = request->process_id;
2957 request->u.resolve.qsrv.euid = request->uid;
2958 request->u.resolve.qsrv.QuestionCallback = resolve_result_callback;
2959 request->u.resolve.qsrv.QuestionContext = request;
2960
2961 request->u.resolve.qtxt.InterfaceID = InterfaceID;
2962 request->u.resolve.qtxt.flags = flags;
2963 request->u.resolve.qtxt.Target = zeroAddr;
2964 AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn);
2965 request->u.resolve.qtxt.qtype = kDNSType_TXT;
2966 request->u.resolve.qtxt.qclass = kDNSClass_IN;
2967 request->u.resolve.qtxt.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
2968 request->u.resolve.qtxt.ExpectUnique = mDNStrue;
2969 request->u.resolve.qtxt.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
2970 request->u.resolve.qtxt.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
2971 request->u.resolve.qtxt.SuppressUnusable = mDNSfalse;
2972 request->u.resolve.qtxt.SearchListIndex = 0;
2973 request->u.resolve.qtxt.AppendSearchDomains = 0;
2974 request->u.resolve.qtxt.RetryWithSearchDomains = mDNSfalse;
2975 request->u.resolve.qtxt.TimeoutQuestion = 0;
2976 request->u.resolve.qtxt.WakeOnResolve = 0;
2977 request->u.resolve.qtxt.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
2978 request->u.resolve.qtxt.ValidationRequired = 0;
2979 request->u.resolve.qtxt.ValidatingResponse = 0;
2980 request->u.resolve.qtxt.ProxyQuestion = 0;
2981 request->u.resolve.qtxt.qnameOrig = mDNSNULL;
2982 request->u.resolve.qtxt.AnonInfo = mDNSNULL;
2983 request->u.resolve.qtxt.pid = request->process_id;
2984 request->u.resolve.qtxt.euid = request->uid;
2985 request->u.resolve.qtxt.QuestionCallback = resolve_result_callback;
2986 request->u.resolve.qtxt.QuestionContext = request;
2987
2988 request->u.resolve.ReportTime = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
2989
2990 request->u.resolve.external_advertise = mDNSfalse;
2991
2992 #if 0
2993 if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains)) return(mStatus_NoError);
2994 #endif
2995
2996 // ask the questions
2997 LogOperation("%3d: DNSServiceResolve(%X %d %##s) START PID[%d](%s)", request->sd, flags, interfaceIndex,
2998 request->u.resolve.qsrv.qname.c, request->process_id, request->pid_name);
2999 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv);
3000
3001 if (!err)
3002 {
3003 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt);
3004 if (err)
3005 {
3006 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv);
3007 }
3008 else
3009 {
3010 request->terminate = resolve_termination_callback;
3011 LogMcastQ(&mDNSStorage, &request->u.resolve.qsrv, request, q_start);
3012 if (callExternalHelpers(InterfaceID, &fqdn, flags))
3013 {
3014 request->u.resolve.external_advertise = mDNStrue;
3015 LogInfo("handle_resolve_request: calling external_start_resolving_service()");
3016 external_start_resolving_service(InterfaceID, &fqdn, flags);
3017 }
3018 }
3019 }
3020
3021 return(err);
3022 }
3023
3024 // ***************************************************************************
3025 #if COMPILER_LIKES_PRAGMA_MARK
3026 #pragma mark -
3027 #pragma mark - DNSServiceQueryRecord
3028 #endif
3029
3030 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
3031 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
3032 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
3033 // the mDNSCore operation if the client dies or closes its socket.
3034
3035 // Returns -1 to tell the caller that it should not try to reissue the query anymore
3036 // Returns 1 on successfully appending a search domain and the caller should reissue the new query
3037 // Returns 0 when there are no more search domains and the caller should reissue the query
3038 mDNSlocal int AppendNewSearchDomain(mDNS *const m, DNSQuestion *question)
3039 {
3040 domainname *sd;
3041 mStatus err;
3042
3043 // Sanity check: The caller already checks this. We use -1 to indicate that we have searched all
3044 // the domains and should try the single label query directly on the wire.
3045 if (question->SearchListIndex == -1)
3046 {
3047 LogMsg("AppendNewSearchDomain: question %##s (%s) SearchListIndex is -1", question->qname.c, DNSTypeName(question->qtype));
3048 return -1;
3049 }
3050
3051 if (!question->AppendSearchDomains)
3052 {
3053 LogMsg("AppendNewSearchDomain: question %##s (%s) AppendSearchDoamins is 0", question->qname.c, DNSTypeName(question->qtype));
3054 return -1;
3055 }
3056
3057 // Save the original name, before we modify them below.
3058 if (!question->qnameOrig)
3059 {
3060 question->qnameOrig = mallocL("AppendNewSearchDomain", sizeof(domainname));
3061 if (!question->qnameOrig) { LogMsg("AppendNewSearchDomain: ERROR!! malloc failure"); return -1; }
3062 question->qnameOrig->c[0] = 0;
3063 AssignDomainName(question->qnameOrig, &question->qname);
3064 LogInfo("AppendSearchDomain: qnameOrig %##s", question->qnameOrig->c);
3065 }
3066
3067 sd = uDNS_GetNextSearchDomain(m, question->InterfaceID, &question->SearchListIndex, !question->AppendLocalSearchDomains);
3068 // We use -1 to indicate that we have searched all the domains and should try the single label
3069 // query directly on the wire. uDNS_GetNextSearchDomain should never return a negative value
3070 if (question->SearchListIndex == -1)
3071 {
3072 LogMsg("AppendNewSearchDomain: ERROR!! uDNS_GetNextSearchDomain returned -1");
3073 return -1;
3074 }
3075
3076 // Not a common case. Perhaps, we should try the next search domain if it exceeds ?
3077 if (sd && (DomainNameLength(question->qnameOrig) + DomainNameLength(sd)) > MAX_DOMAIN_NAME)
3078 {
3079 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));
3080 return -1;
3081 }
3082
3083 // if there are no more search domains and we have already tried this question
3084 // without appending search domains, then we are done.
3085 if (!sd && !ApplySearchDomainsFirst(question))
3086 {
3087 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), not trying anymore", question->qname.c, DNSTypeName(question->qtype));
3088 return -1;
3089 }
3090
3091 // Stop the question before changing the name as negative cache entries could be pointing at this question.
3092 // Even if we don't change the question in the case of returning 0, the caller is going to restart the
3093 // question.
3094 err = mDNS_StopQuery(&mDNSStorage, question);
3095 if (err) { LogMsg("AppendNewSearchDomain: ERROR!! %##s %s mDNS_StopQuery: %d, while retrying with search domains", question->qname.c, DNSTypeName(question->qtype), (int)err); }
3096
3097 AssignDomainName(&question->qname, question->qnameOrig);
3098 if (sd)
3099 {
3100 AppendDomainName(&question->qname, sd);
3101 LogInfo("AppnedNewSearchDomain: Returning question with name %##s, SearchListIndex %d", question->qname.c, question->SearchListIndex);
3102 return 1;
3103 }
3104
3105 // Try the question as single label
3106 LogInfo("AppnedNewSearchDomain: No more search domains for question with name %##s (%s), trying one last time", question->qname.c, DNSTypeName(question->qtype));
3107 return 0;
3108 }
3109
3110 #if APPLE_OSX_mDNSResponder
3111
3112 mDNSlocal mDNSBool DomainInSearchList(const domainname *domain, mDNSBool excludeLocal)
3113 {
3114 const SearchListElem *s;
3115 int qcount, scount;
3116
3117 qcount = CountLabels(domain);
3118 for (s=SearchList; s; s=s->next)
3119 {
3120 if (excludeLocal && SameDomainName(&s->domain, &localdomain))
3121 continue;
3122 scount = CountLabels(&s->domain);
3123 if (qcount >= scount)
3124 {
3125 // Note: When qcount == scount, we do a complete match of the domain
3126 // which is expected by the callers.
3127 const domainname *d = SkipLeadingLabels(domain, (qcount - scount));
3128 if (SameDomainName(&s->domain, d))
3129 {
3130 return mDNStrue;
3131 }
3132 }
3133 }
3134 return mDNSfalse;
3135 }
3136
3137 // The caller already checks that this is a dotlocal question.
3138 mDNSlocal mDNSBool ShouldDeliverNegativeResponse(mDNS *const m, DNSQuestion *question)
3139 {
3140 mDNSu16 qtype;
3141
3142 // If the question matches the search domain exactly or the search domain is a
3143 // subdomain of the question, it is most likely a valid unicast domain and hence
3144 // don't suppress negative responses.
3145 //
3146 // If the user has configured ".local" as a search domain, we don't want
3147 // to deliver a negative response for names ending in ".local" as that would
3148 // prevent bonjour discovery. Passing mDNStrue for the last argument excludes
3149 // ".local" search domains.
3150 if (DomainInSearchList(&question->qname, mDNStrue))
3151 {
3152 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) in SearchList", question->qname.c, DNSTypeName(question->qtype));
3153 return mDNStrue;
3154 }
3155
3156 // Deliver negative response for A/AAAA if there was a positive response for AAAA/A respectively.
3157 if (question->qtype != kDNSType_A && question->qtype != kDNSType_AAAA)
3158 {
3159 LogOperation("ShouldDeliverNegativeResponse: Question %##s (%s) not answering local question with negative unicast response",
3160 question->qname.c, DNSTypeName(question->qtype));
3161 return mDNSfalse;
3162 }
3163 qtype = (question->qtype == kDNSType_A ? kDNSType_AAAA : kDNSType_A);
3164 if (!mDNS_CheckForCacheRecord(m, question, qtype))
3165 {
3166 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) not answering local question with negative unicast response"
3167 " (can't find positive record)", question->qname.c, DNSTypeName(question->qtype));
3168 return mDNSfalse;
3169 }
3170 LogOperation("ShouldDeliverNegativeResponse:Question %##s (%s) answering local with negative unicast response (found positive record)",
3171 question->qname.c, DNSTypeName(question->qtype));
3172 return mDNStrue;
3173 }
3174
3175 // Workaround for networks using Microsoft Active Directory using "local" as a private internal
3176 // top-level domain
3177 mDNSlocal mStatus SendAdditionalQuery(DNSQuestion *q, request_state *request, mStatus err)
3178 {
3179 #ifndef UNICAST_DISABLED
3180 extern domainname ActiveDirectoryPrimaryDomain;
3181 DNSQuestion **question2;
3182 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
3183 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
3184
3185 question2 = mDNSNULL;
3186 if (request->hdr.op == query_request)
3187 question2 = &request->u.queryrecord.q2;
3188 else if (request->hdr.op == addrinfo_request)
3189 {
3190 if (q->qtype == kDNSType_A)
3191 question2 = &request->u.addrinfo.q42;
3192 else if (q->qtype == kDNSType_AAAA)
3193 question2 = &request->u.addrinfo.q62;
3194 }
3195 if (!question2)
3196 {
3197 LogMsg("SendAdditionalQuery: question2 NULL for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3198 return mStatus_BadParamErr;
3199 }
3200
3201 // Sanity check: If we already sent an additonal query, we don't need to send one more.
3202 //
3203 // 1. When the application calls DNSServiceQueryRecord or DNSServiceGetAddrInfo with a .local name, this function
3204 // is called to see whether a unicast query should be sent or not.
3205 //
3206 // 2. As a result of appending search domains, the question may be end up with a .local suffix even though it
3207 // was not a .local name to start with. In that case, queryrecord_result_callback calls this function to
3208 // send the additional query.
3209 //
3210 // Thus, it should not be called more than once.
3211 if (*question2)
3212 {
3213 LogInfo("SendAdditionalQuery: question2 already sent for %##s (%s), no more q2", q->qname.c, DNSTypeName(q->qtype));
3214 return err;
3215 }
3216
3217 if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain))
3218 if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q))
3219 {
3220 DNSQuestion *q2;
3221 int labels = CountLabels(&q->qname);
3222 q2 = mallocL("DNSQuestion", sizeof(DNSQuestion));
3223 if (!q2) FatalError("ERROR: SendAdditionalQuery malloc");
3224 *question2 = q2;
3225 *q2 = *q;
3226 q2->InterfaceID = mDNSInterface_Unicast;
3227 q2->ExpectUnique = mDNStrue;
3228 // Always set the QuestionContext to indicate that this question should be stopped
3229 // before freeing. Don't rely on "q".
3230 q2->QuestionContext = request;
3231 // If the query starts as a single label e.g., somehost, and we have search domains with .local,
3232 // queryrecord_result_callback calls this function when .local is appended to "somehost".
3233 // At that time, the name in "q" is pointing at somehost.local and its qnameOrig pointing at
3234 // "somehost". We need to copy that information so that when we retry with a different search
3235 // domain e.g., mycompany.local, we get "somehost.mycompany.local".
3236 if (q->qnameOrig)
3237 {
3238 (*question2)->qnameOrig = mallocL("SendAdditionalQuery", DomainNameLength(q->qnameOrig));
3239 if (!(*question2)->qnameOrig) { LogMsg("SendAdditionalQuery: ERROR!! malloc failure"); return mStatus_NoMemoryErr; }
3240 (*question2)->qnameOrig->c[0] = 0;
3241 AssignDomainName((*question2)->qnameOrig, q->qnameOrig);
3242 LogInfo("SendAdditionalQuery: qnameOrig %##s", (*question2)->qnameOrig->c);
3243 }
3244 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
3245 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
3246 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
3247 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
3248 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
3249 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
3250 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
3251 // Note that in the "my-small-company.local" example above there will typically be an SOA record for
3252 // "my-small-company.local" but *not* for "local", which is why the "local SOA" check would fail in that case.
3253 // We need to check against both ActiveDirectoryPrimaryDomain and SearchList. If it matches against either
3254 // of those, we don't want do the SOA check for the local
3255 if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain) && !DomainInSearchList(&q->qname, mDNSfalse))
3256 {
3257 AssignDomainName(&q2->qname, &localdomain);
3258 q2->qtype = kDNSType_SOA;
3259 q2->LongLived = mDNSfalse;
3260 q2->ForceMCast = mDNSfalse;
3261 q2->ReturnIntermed = mDNStrue;
3262 // Don't append search domains for the .local SOA query
3263 q2->AppendSearchDomains = 0;
3264 q2->AppendLocalSearchDomains = 0;
3265 q2->RetryWithSearchDomains = mDNSfalse;
3266 q2->SearchListIndex = 0;
3267 q2->TimeoutQuestion = 0;
3268 q2->AnonInfo = mDNSNULL;
3269 q2->pid = request->process_id;
3270 q2->euid = request->uid;
3271 }
3272 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype));
3273 err = mDNS_StartQuery(&mDNSStorage, q2);
3274 if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err);
3275 }
3276 return(err);
3277 #else // !UNICAST_DISABLED
3278 (void) q;
3279 (void) request;
3280 (void) err;
3281
3282 return mStatus_NoError;
3283 #endif // !UNICAST_DISABLED
3284 }
3285 #endif // APPLE_OSX_mDNSResponder
3286
3287 // This function tries to append a search domain if valid and possible. If so, returns true.
3288 mDNSlocal mDNSBool RetryQuestionWithSearchDomains(mDNS *const m, DNSQuestion *question, request_state *req, QC_result AddRecord)
3289 {
3290 int result;
3291 // RetryWithSearchDomains tells the core to call us back so that we can retry with search domains if there is no
3292 // answer in the cache or /etc/hosts. In the first call back from the core, we clear RetryWithSearchDomains so
3293 // that we don't get called back repeatedly. If we got an answer from the cache or /etc/hosts, we don't touch
3294 // RetryWithSearchDomains which may or may not be set.
3295 //
3296 // If we get e.g., NXDOMAIN and the query is neither suppressed nor exhausted the domain search list and
3297 // is a valid question for appending search domains, retry by appending domains
3298
3299 if ((AddRecord != QC_suppressed) && question->SearchListIndex != -1 && question->AppendSearchDomains)
3300 {
3301 question->RetryWithSearchDomains = 0;
3302 result = AppendNewSearchDomain(m, question);
3303 // As long as the result is either zero or 1, we retry the question. If we exahaust the search
3304 // domains (result is zero) we try the original query (as it was before appending the search
3305 // domains) as such on the wire as a last resort if we have not tried them before. For queries
3306 // with more than one label, we have already tried them before appending search domains and
3307 // hence don't retry again
3308 if (result != -1)
3309 {
3310 mStatus err;
3311 err = mDNS_StartQuery(m, question);
3312 if (!err)
3313 {
3314 LogOperation("%3d: RetryQuestionWithSearchDomains(%##s, %s), retrying after appending search domain", req->sd, question->qname.c, DNSTypeName(question->qtype));
3315 // If the result was zero, it meant that there are no search domains and we just retried the question
3316 // as a single label and we should not retry with search domains anymore.
3317 if (!result) question->SearchListIndex = -1;
3318 return mDNStrue;
3319 }
3320 else
3321 {
3322 LogMsg("%3d: ERROR: RetryQuestionWithSearchDomains %##s %s mDNS_StartQuery: %d, while retrying with search domains", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3323 // We have already stopped the query and could not restart. Reset the appropriate pointers
3324 // so that we don't call stop again when the question terminates
3325 question->QuestionContext = mDNSNULL;
3326 }
3327 }
3328 }
3329 else
3330 {
3331 LogInfo("%3d: RetryQuestionWithSearchDomains: Not appending search domains - SuppressQuery %d, SearchListIndex %d, AppendSearchDomains %d", req->sd, AddRecord, question->SearchListIndex, question->AppendSearchDomains);
3332 }
3333 return mDNSfalse;
3334 }
3335
3336 mDNSlocal void queryrecord_result_reply(mDNS *const m, request_state *req, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord,
3337 DNSServiceErrorType error)
3338 {
3339 char name[MAX_ESCAPED_DOMAIN_NAME];
3340 size_t len;
3341 DNSServiceFlags flags = 0;
3342 reply_state *rep;
3343 char *data;
3344
3345 ConvertDomainNameToCString(answer->name, name);
3346
3347 LogOperation("%3d: %s(%##s, %s) %s %s", req->sd,
3348 req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
3349 question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer));
3350
3351 len = sizeof(DNSServiceFlags); // calculate reply data length
3352 len += sizeof(mDNSu32); // interface index
3353 len += sizeof(DNSServiceErrorType);
3354 len += strlen(name) + 1;
3355 len += 3 * sizeof(mDNSu16); // type, class, rdlen
3356 len += answer->rdlength;
3357 len += sizeof(mDNSu32); // TTL
3358
3359 rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req);
3360
3361 if (AddRecord)
3362 flags |= kDNSServiceFlagsAdd;
3363 if (question->ValidationStatus != 0)
3364 {
3365 error = kDNSServiceErr_NoError;
3366 if (question->ValidationRequired && question->ValidationState == DNSSECValDone)
3367 {
3368 switch (question->ValidationStatus) //Set the dnssec flags to be passed on to the Apps here
3369 {
3370 case DNSSEC_Secure:
3371 flags |= kDNSServiceFlagsSecure;
3372 break;
3373 case DNSSEC_Insecure:
3374 flags |= kDNSServiceFlagsInsecure;
3375 break;
3376 case DNSSEC_Indeterminate:
3377 flags |= kDNSServiceFlagsIndeterminate;
3378 break;
3379 case DNSSEC_Bogus:
3380 flags |= kDNSServiceFlagsBogus;
3381 break;
3382 default:
3383 LogMsg("queryrecord_result_reply unknown status %d for %##s", question->ValidationStatus, question->qname.c);
3384 }
3385 }
3386 }
3387
3388 rep->rhdr->flags = dnssd_htonl(flags);
3389 // Call mDNSPlatformInterfaceIndexfromInterfaceID, but suppressNetworkChange (last argument). Otherwise, if the
3390 // InterfaceID is not valid, then it simulates a "NetworkChanged" which in turn makes questions
3391 // to be stopped and started including *this* one. Normally the InterfaceID is valid. But when we
3392 // are using the /etc/hosts entries to answer a question, the InterfaceID may not be known to the
3393 // mDNS core . Eventually, we should remove the calls to "NetworkChanged" in
3394 // mDNSPlatformInterfaceIndexfromInterfaceID when it can't find InterfaceID as ResourceRecords
3395 // should not have existed to answer this question if the corresponding interface is not valid.
3396 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID, mDNStrue));
3397 rep->rhdr->error = dnssd_htonl(error);
3398
3399 data = (char *)&rep->rhdr[1];
3400
3401 put_string(name, &data);
3402 put_uint16(answer->rrtype, &data);
3403 put_uint16(answer->rrclass, &data);
3404 put_uint16(answer->rdlength, &data);
3405 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
3406 // function just does a blind memory copy without regard to structures that may have holes in them.
3407 if (answer->rdlength)
3408 if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer))
3409 LogMsg("queryrecord_result_reply putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data);
3410 data += answer->rdlength;
3411 put_uint32(AddRecord ? answer->rroriginalttl : 0, &data);
3412
3413 append_reply(req, rep);
3414 // Stop the question, if we just timed out
3415 if (error == kDNSServiceErr_Timeout)
3416 {
3417 mDNS_StopQuery(m, question);
3418 // Reset the pointers so that we don't call stop on termination
3419 question->QuestionContext = mDNSNULL;
3420 }
3421 else if ((AddRecord == QC_add) && req->hdr.op == addrinfo_request)
3422 {
3423 // Note: We count all answers including LocalOnly e.g., /etc/hosts. If we
3424 // exclude that, v4ans/v6ans will be zero and we would wrongly think that
3425 // we did not answer questions and setup the status to deliver triggers.
3426 if (question->qtype == kDNSType_A)
3427 req->u.addrinfo.v4ans = 1;
3428 if (question->qtype == kDNSType_AAAA)
3429 req->u.addrinfo.v6ans = 1;
3430 }
3431 else if ((AddRecord == QC_add) && req->hdr.op == query_request)
3432 {
3433 if (question->qtype == kDNSType_A || question->qtype == kDNSType_AAAA)
3434 req->u.queryrecord.ans = 1;
3435 }
3436
3437 #if APPLE_OSX_mDNSResponder
3438 #if !NO_WCF
3439 CHECK_WCF_FUNCTION(WCFIsServerRunning)
3440 {
3441 struct xucred x;
3442 socklen_t xucredlen = sizeof(x);
3443
3444 if (WCFIsServerRunning((WCFConnection *)m->WCF) && answer->rdlength != 0)
3445 {
3446 if (getsockopt(req->sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 &&
3447 (x.cr_version == XUCRED_VERSION))
3448 {
3449 struct sockaddr_storage addr;
3450 addr.ss_len = 0;
3451 if (answer->rrtype == kDNSType_A || answer->rrtype == kDNSType_AAAA)
3452 {
3453 if (answer->rrtype == kDNSType_A)
3454 {
3455 struct sockaddr_in *const sin = (struct sockaddr_in *)&addr;
3456 sin->sin_port = 0;
3457 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3458 // sin->sin_addr.s_addr = answer->rdata->u.ipv4.NotAnInteger;
3459 if (!putRData(mDNSNULL, (mDNSu8 *)&sin->sin_addr, (mDNSu8 *)(&sin->sin_addr + sizeof(mDNSv4Addr)), answer))
3460 LogMsg("queryrecord_result_reply: WCF AF_INET putRData failed");
3461 else
3462 {
3463 addr.ss_len = sizeof (struct sockaddr_in);
3464 addr.ss_family = AF_INET;
3465 }
3466 }
3467 else if (answer->rrtype == kDNSType_AAAA)
3468 {
3469 struct sockaddr_in6 *const sin6 = (struct sockaddr_in6 *)&addr;
3470 sin6->sin6_port = 0;
3471 // Instead of this stupid call to putRData it would be much simpler to just assign the value in the sensible way, like this:
3472 // sin6->sin6_addr.__u6_addr.__u6_addr32[0] = answer->rdata->u.ipv6.l[0];
3473 // sin6->sin6_addr.__u6_addr.__u6_addr32[1] = answer->rdata->u.ipv6.l[1];
3474 // sin6->sin6_addr.__u6_addr.__u6_addr32[2] = answer->rdata->u.ipv6.l[2];
3475 // sin6->sin6_addr.__u6_addr.__u6_addr32[3] = answer->rdata->u.ipv6.l[3];
3476 if (!putRData(mDNSNULL, (mDNSu8 *)&sin6->sin6_addr, (mDNSu8 *)(&sin6->sin6_addr + sizeof(mDNSv6Addr)), answer))
3477 LogMsg("queryrecord_result_reply: WCF AF_INET6 putRData failed");
3478 else
3479 {
3480 addr.ss_len = sizeof (struct sockaddr_in6);
3481 addr.ss_family = AF_INET6;
3482 }
3483 }
3484 if (addr.ss_len)
3485 {
3486 debugf("queryrecord_result_reply: Name %s, uid %u, addr length %d", name, x.cr_uid, addr.ss_len);
3487 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3488 {
3489 WCFNameResolvesToAddr(m->WCF, name, (struct sockaddr *)&addr, x.cr_uid);
3490 }
3491 }
3492 }
3493 else if (answer->rrtype == kDNSType_CNAME)
3494 {
3495 domainname cname;
3496 char cname_cstr[MAX_ESCAPED_DOMAIN_NAME];
3497 if (!putRData(mDNSNULL, cname.c, (mDNSu8 *)(cname.c + MAX_DOMAIN_NAME), answer))
3498 LogMsg("queryrecord_result_reply: WCF CNAME putRData failed");
3499 else
3500 {
3501 ConvertDomainNameToCString(&cname, cname_cstr);
3502 CHECK_WCF_FUNCTION((WCFConnection *)WCFNameResolvesToAddr)
3503 {
3504 WCFNameResolvesToName(m->WCF, name, cname_cstr, x.cr_uid);
3505 }
3506 }
3507 }
3508 }
3509 else my_perror("queryrecord_result_reply: ERROR: getsockopt LOCAL_PEERCRED");
3510 }
3511 }
3512 #endif
3513 #endif
3514 }
3515
3516 mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
3517 {
3518 request_state *req = question->QuestionContext;
3519 DNSServiceErrorType error = kDNSServiceErr_NoError;
3520 DNSQuestion *q = mDNSNULL;
3521
3522 #if APPLE_OSX_mDNSResponder
3523 {
3524 // Sanity check: QuestionContext is set to NULL after we stop the question and hence we should not
3525 // get any callbacks from the core after this.
3526 if (!req)
3527 {
3528 LogMsg("queryrecord_result_callback: ERROR!! QuestionContext NULL for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3529 return;
3530 }
3531 if (req->hdr.op == query_request && question == req->u.queryrecord.q2)
3532 q = &req->u.queryrecord.q;
3533 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q42)
3534 q = &req->u.addrinfo.q4;
3535 else if (req->hdr.op == addrinfo_request && question == req->u.addrinfo.q62)
3536 q = &req->u.addrinfo.q6;
3537
3538 if (q && question->qtype != q->qtype && !SameDomainName(&question->qname, &q->qname))
3539 {
3540 mStatus err;
3541 domainname *orig = question->qnameOrig;
3542
3543 LogInfo("queryrecord_result_callback: Stopping q2 local %##s", question->qname.c);
3544 mDNS_StopQuery(m, question);
3545 question->QuestionContext = mDNSNULL;
3546
3547 // We got a negative response for the SOA record indicating that .local does not exist.
3548 // But we might have other search domains (that does not end in .local) that can be
3549 // appended to this question. In that case, we want to retry the question. Otherwise,
3550 // we don't want to try this question as unicast.
3551 if (answer->RecordType == kDNSRecordTypePacketNegative && !q->AppendSearchDomains)
3552 {
3553 LogInfo("queryrecord_result_callback: question %##s AppendSearchDomains zero", q->qname.c);
3554 return;
3555 }
3556
3557 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
3558 //
3559 // Note: When we copy the original question, we copy everything including the AppendSearchDomains,
3560 // RetryWithSearchDomains except for qnameOrig which can be non-NULL if the original question is
3561 // e.g., somehost and then we appended e.g., ".local" and retried that question. See comment in
3562 // SendAdditionalQuery as to how qnameOrig gets initialized.
3563 *question = *q;
3564 question->InterfaceID = mDNSInterface_Unicast;
3565 question->ExpectUnique = mDNStrue;
3566 question->qnameOrig = orig;
3567
3568 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast, context %p", req->sd, question->qname.c, DNSTypeName(question->qtype), question->QuestionContext);
3569
3570 // If the original question timed out, its QuestionContext would already be set to NULL and that's what we copied above.
3571 // Hence, we need to set it explicitly here.
3572 question->QuestionContext = req;
3573 err = mDNS_StartQuery(m, question);
3574 if (err) LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err);
3575
3576 // If we got a positive response to local SOA, then try the .local question as unicast
3577 if (answer->RecordType != kDNSRecordTypePacketNegative) return;
3578
3579 // Fall through and get the next search domain. The question is pointing at .local
3580 // and we don't want to try that. Try the next search domain. Don't try with local
3581 // search domains for the unicast question anymore.
3582 //
3583 // Note: we started the question above which will be stopped immediately (never sent on the wire)
3584 // before we pick the next search domain below. RetryQuestionWithSearchDomains assumes that the
3585 // question has already started.
3586 question->AppendLocalSearchDomains = 0;
3587 }
3588
3589 if (q && AddRecord && AddRecord != QC_dnssec && (question->InterfaceID == mDNSInterface_Unicast) && !answer->rdlength)
3590 {
3591 // If we get a negative response to the unicast query that we sent above, retry after appending search domains
3592 // Note: We could have appended search domains below (where do it for regular unicast questions) instead of doing it here.
3593 // As we ignore negative unicast answers below, we would never reach the code where the search domains are appended.
3594 // To keep things simple, we handle unicast ".local" separately here.
3595 LogInfo("queryrecord_result_callback: Retrying .local question %##s (%s) as unicast after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3596 if (RetryQuestionWithSearchDomains(m, question, req, AddRecord))
3597 return;
3598 if (question->AppendSearchDomains && !question->AppendLocalSearchDomains && IsLocalDomain(&question->qname))
3599 {
3600 // If "local" is the last search domain, we need to stop the question so that we don't send the "local"
3601 // question on the wire as we got a negative response for the local SOA. But, we can't stop the question
3602 // yet as we may have to timeout the question (done by the "core") for which we need to leave the question
3603 // in the list. We leave it disabled so that it does not hit the wire.
3604 LogInfo("queryrecord_result_callback: Disabling .local question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3605 question->ThisQInterval = 0;
3606 }
3607 }
3608 // 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
3609 // domains to append for "q2". In all cases, fall through and deliver the response
3610 }
3611 #endif // APPLE_OSX_mDNSResponder
3612
3613 // If a query is being suppressed for some reason, we don't have to do any other
3614 // processing.
3615 //
3616 // Note: We don't check for "SuppressQuery" and instead use QC_suppressed because
3617 // the "core" needs to temporarily turn off SuppressQuery to answer this query.
3618 if (AddRecord == QC_suppressed)
3619 {
3620 LogInfo("queryrecord_result_callback: Suppressed question %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
3621 queryrecord_result_reply(m, req, question, answer, AddRecord, kDNSServiceErr_NoSuchRecord);
3622 return;
3623 }
3624
3625 if (answer->RecordType == kDNSRecordTypePacketNegative)
3626 {
3627 // If this question needs to be timed out and we have reached the stop time, mark
3628 // the error as timeout. It is possible that we might get a negative response from an
3629 // external DNS server at the same time when this question reaches its stop time. We
3630 // can't tell the difference as there is no indication in the callback. This should
3631 // be okay as we will be timing out this query anyway.
3632 mDNS_Lock(m);
3633 if (question->TimeoutQuestion)
3634 {
3635 if ((m->timenow - question->StopTime) >= 0)
3636 {
3637 LogInfo("queryrecord_result_callback:Question %##s (%s) timing out, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3638 error = kDNSServiceErr_Timeout;
3639 }
3640 }
3641 mDNS_Unlock(m);
3642 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
3643 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
3644 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
3645 // server is going to assert that pretty much every single multicast name doesn't exist.
3646 //
3647 // If we are timing out this query, we need to deliver the negative answer to the application
3648 if (error != kDNSServiceErr_Timeout)
3649 {
3650 if (!answer->InterfaceID && IsLocalDomain(answer->name))
3651 {
3652 // Sanity check: "q" will be set only if "question" is the .local unicast query.
3653 if (!q)
3654 {
3655 LogMsg("queryrecord_result_callback: ERROR!! answering multicast question %s with unicast cache record",
3656 RRDisplayString(m, answer));
3657 return;
3658 }
3659 #if APPLE_OSX_mDNSResponder
3660 if (!ShouldDeliverNegativeResponse(m, question))
3661 {
3662 return;
3663 }
3664 #endif // APPLE_OSX_mDNSResponder
3665 LogInfo("queryrecord_result_callback:Question %##s (%s) answering local with negative unicast response", question->qname.c,
3666 DNSTypeName(question->qtype));
3667 }
3668 error = kDNSServiceErr_NoSuchRecord;
3669 }
3670 }
3671 // If we get a negative answer, try appending search domains. Don't append search domains
3672 // - if we are timing out this question
3673 // - if the negative response was received as a result of a multicast query
3674 // - if this is an additional query (q2), we already appended search domains above (indicated by "!q" below)
3675 // - if this response is forced e.g., dnssec validation result
3676 if (error != kDNSServiceErr_Timeout)
3677 {
3678 if (!q && !answer->InterfaceID && !answer->rdlength && AddRecord && AddRecord != QC_dnssec)
3679 {
3680 // If the original question did not end in .local, we did not send an SOA query
3681 // to figure out whether we should send an additional unicast query or not. If we just
3682 // appended .local, we need to see if we need to send an additional query. This should
3683 // normally happen just once because after we append .local, we ignore all negative
3684 // responses for .local above.
3685 LogInfo("queryrecord_result_callback: Retrying question %##s (%s) after appending search domains", question->qname.c, DNSTypeName(question->qtype));
3686 if (RetryQuestionWithSearchDomains(m, question, req, AddRecord))
3687 {
3688 // Note: We need to call SendAdditionalQuery every time after appending a search domain as .local could
3689 // be anywhere in the search domain list.
3690 #if APPLE_OSX_mDNSResponder
3691 mStatus err = mStatus_NoError;
3692 err = SendAdditionalQuery(question, req, err);
3693 if (err) LogMsg("queryrecord_result_callback: Sending .local SOA query failed, after appending domains");
3694 #endif // APPLE_OSX_mDNSResponder
3695 return;
3696 }
3697 }
3698 }
3699 queryrecord_result_reply(m, req, question, answer, AddRecord, error);
3700 }
3701
3702 mDNSlocal void queryrecord_termination_callback(request_state *request)
3703 {
3704 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP PID[%d](%s)",
3705 request->sd, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype), request->process_id, request->pid_name);
3706 if (request->u.queryrecord.q.QuestionContext)
3707 {
3708 mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q); // no need to error check
3709 LogMcastQ(&mDNSStorage, &request->u.queryrecord.q, request, q_stop);
3710 request->u.queryrecord.q.QuestionContext = mDNSNULL;
3711 }
3712 else
3713 {
3714 DNSQuestion *question = &request->u.queryrecord.q;
3715 LogInfo("queryrecord_termination_callback: question %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3716 }
3717
3718 if (request->u.queryrecord.q.qnameOrig)
3719 {
3720 freeL("QueryTermination", request->u.queryrecord.q.qnameOrig);
3721 request->u.queryrecord.q.qnameOrig = mDNSNULL;
3722 }
3723
3724 if (callExternalHelpers(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->flags))
3725 {
3726 LogInfo("queryrecord_termination_callback: calling external_stop_browsing_for_service()");
3727 external_stop_browsing_for_service(request->u.queryrecord.q.InterfaceID, &request->u.queryrecord.q.qname, request->u.queryrecord.q.qtype, request->flags);
3728 }
3729 if (request->u.queryrecord.q2)
3730 {
3731 if (request->u.queryrecord.q2->QuestionContext)
3732 {
3733 LogInfo("queryrecord_termination_callback: Stopping q2 %##s", request->u.queryrecord.q2->qname.c);
3734 mDNS_StopQuery(&mDNSStorage, request->u.queryrecord.q2);
3735 LogMcastQ(&mDNSStorage, request->u.queryrecord.q2, request, q_stop);
3736 }
3737 else
3738 {
3739 DNSQuestion *question = request->u.queryrecord.q2;
3740 LogInfo("queryrecord_termination_callback: q2 %##s (%s) already stopped, InterfaceID %p", question->qname.c, DNSTypeName(question->qtype), question->InterfaceID);
3741 }
3742 if (request->u.queryrecord.q2->qnameOrig)
3743 {
3744 LogInfo("queryrecord_termination_callback: freeing q2 qnameOrig %##s", request->u.queryrecord.q2->qnameOrig->c);
3745 freeL("QueryTermination q2", request->u.queryrecord.q2->qnameOrig);
3746 request->u.queryrecord.q2->qnameOrig = mDNSNULL;
3747 }
3748 freeL("queryrecord Q2", request->u.queryrecord.q2);
3749 request->u.queryrecord.q2 = mDNSNULL;
3750 }
3751 #if APPLE_OSX_mDNSResponder
3752 {
3753 if (request->u.queryrecord.ans)
3754 {
3755 DNSQuestion *v4q, *v6q;
3756 // If we are receiving poisitive answers, provide the hint to the
3757 // upper layer.
3758 v4q = v6q = mDNSNULL;
3759 if (request->u.queryrecord.q.qtype == kDNSType_A)
3760 v4q = &request->u.queryrecord.q;
3761 else if (request->u.queryrecord.q.qtype == kDNSType_AAAA)
3762 v6q = &request->u.queryrecord.q;
3763 mDNSPlatformTriggerDNSRetry(&mDNSStorage, v4q, v6q);
3764 }
3765 }
3766 #endif // APPLE_OSX_mDNSResponder
3767 }
3768
3769 mDNSlocal mStatus handle_queryrecord_request(request_state *request)
3770 {
3771 DNSQuestion *const q = &request->u.queryrecord.q;
3772 char name[256];
3773 size_t nameLen;
3774 mDNSu16 rrtype, rrclass;
3775 mStatus err;
3776
3777 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3778 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3779 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3780
3781 // The request is scoped to a specific interface index, but the
3782 // interface is not currently in our list.
3783 if (interfaceIndex && !InterfaceID)
3784 {
3785 if (interfaceIndex > 1)
3786 LogMsg("handle_queryrecord_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
3787 interfaceIndex, request->process_id, request->pid_name);
3788 // If it's one of the specially defined inteface index values, just return an error.
3789 // Also, caller should return an error immediately if lo0 (index 1) is not configured
3790 // into the current active interfaces. See background in Radar 21967160.
3791 if (PreDefinedInterfaceIndex(interfaceIndex) || interfaceIndex == 1)
3792 {
3793 LogInfo("handle_queryrecord_request: bad interfaceIndex %d", interfaceIndex);
3794 return(mStatus_BadParamErr);
3795 }
3796
3797 // Otherwise, use the specified interface index value and the request will
3798 // be applied to that interface when it comes up.
3799 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
3800 LogInfo("handle_queryrecord_request: query pending for interface index %d", interfaceIndex);
3801 }
3802
3803 if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr);
3804 rrtype = get_uint16(&request->msgptr, request->msgend);
3805 rrclass = get_uint16(&request->msgptr, request->msgend);
3806
3807 if (!request->msgptr)
3808 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
3809
3810 request->flags = flags;
3811 request->interfaceIndex = interfaceIndex;
3812 mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord));
3813
3814 q->InterfaceID = InterfaceID;
3815 q->flags = flags;
3816 q->Target = zeroAddr;
3817 if (!MakeDomainNameFromDNSNameString(&q->qname, name)) return(mStatus_BadParamErr);
3818 #if 0
3819 if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains)) return (mStatus_NoError);
3820 #endif
3821 q->qtype = rrtype;
3822 q->qclass = rrclass;
3823 q->LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
3824 q->ExpectUnique = mDNSfalse;
3825 q->ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
3826 q->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
3827 q->SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
3828 q->TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
3829 q->WakeOnResolve = 0;
3830 q->UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
3831 if ((flags & kDNSServiceFlagsValidate) != 0)
3832 q->ValidationRequired = DNSSEC_VALIDATION_SECURE;
3833 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
3834 q->ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
3835 q->ValidatingResponse = 0;
3836 q->ProxyQuestion = 0;
3837 q->AnonInfo = mDNSNULL;
3838 q->QuestionCallback = queryrecord_result_callback;
3839 q->QuestionContext = request;
3840 q->SearchListIndex = 0;
3841
3842 q->DNSSECAuthInfo = mDNSNULL;
3843 q->DAIFreeCallback = mDNSNULL;
3844
3845 //Turn off dnssec validation for local domains and Question Types: RRSIG/ANY(ANY Type is not supported yet)
3846 if ((IsLocalDomain(&q->qname)) || (q->qtype == kDNSServiceType_RRSIG) || (q->qtype == kDNSServiceType_ANY))
3847 q->ValidationRequired = 0;
3848
3849 // Don't append search domains for fully qualified domain names including queries
3850 // such as e.g., "abc." that has only one label. We convert all names to FQDNs as internally
3851 // we only deal with FQDNs. Hence, we cannot look at qname to figure out whether we should
3852 // append search domains or not. So, we record that information in AppendSearchDomains.
3853 //
3854 // We append search domains only for queries that are a single label. If overriden using command line
3855 // argument "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
3856 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
3857
3858 nameLen = strlen(name);
3859 if ((!(q->ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(q->ValidationRequired == DNSSEC_VALIDATION_INSECURE))
3860 && (rrtype == kDNSType_A || rrtype == kDNSType_AAAA) && ((nameLen == 0) || (name[nameLen - 1] != '.')) &&
3861 (AlwaysAppendSearchDomains || CountLabels(&q->qname) == 1))
3862 {
3863 q->AppendSearchDomains = 1;
3864 q->AppendLocalSearchDomains = 1;
3865 }
3866 else
3867 {
3868 q->AppendSearchDomains = 0;
3869 q->AppendLocalSearchDomains = 0;
3870 }
3871
3872 // For single label queries that are not fully qualified, look at /etc/hosts, cache and try
3873 // search domains before trying them on the wire as a single label query. RetryWithSearchDomains
3874 // tell the core to call back into the UDS layer if there is no valid response in /etc/hosts or
3875 // the cache
3876 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
3877 q->qnameOrig = mDNSNULL;
3878 SetQuestionPolicy(q, request);
3879
3880 LogOperation("%3d: DNSServiceQueryRecord(%X, %d, %##s, %s) START PID[%d](%s)",
3881 request->sd, flags, interfaceIndex, q->qname.c, DNSTypeName(q->qtype), request->process_id, request->pid_name);
3882 err = mDNS_StartQuery(&mDNSStorage, q);
3883
3884 if (err)
3885 {
3886 LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err);
3887 }
3888 else
3889 {
3890 request->terminate = queryrecord_termination_callback;
3891 LogMcastQ(&mDNSStorage, q, request, q_start);
3892 if (callExternalHelpers(q->InterfaceID, &q->qname, flags))
3893 {
3894 LogInfo("handle_queryrecord_request: calling external_start_browsing_for_service()");
3895 external_start_browsing_for_service(q->InterfaceID, &q->qname, q->qtype, flags, q);
3896 }
3897 }
3898
3899 #if APPLE_OSX_mDNSResponder
3900 err = SendAdditionalQuery(q, request, err);
3901 #endif // APPLE_OSX_mDNSResponder
3902
3903 return(err);
3904 }
3905
3906 // ***************************************************************************
3907 #if COMPILER_LIKES_PRAGMA_MARK
3908 #pragma mark -
3909 #pragma mark - DNSServiceEnumerateDomains
3910 #endif
3911
3912 mDNSlocal reply_state *format_enumeration_reply(request_state *request,
3913 const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err)
3914 {
3915 size_t len;
3916 reply_state *reply;
3917 char *data;
3918
3919 len = sizeof(DNSServiceFlags);
3920 len += sizeof(mDNSu32);
3921 len += sizeof(DNSServiceErrorType);
3922 len += strlen(domain) + 1;
3923
3924 reply = create_reply(enumeration_reply_op, len, request);
3925 reply->rhdr->flags = dnssd_htonl(flags);
3926 reply->rhdr->ifi = dnssd_htonl(ifi);
3927 reply->rhdr->error = dnssd_htonl(err);
3928 data = (char *)&reply->rhdr[1];
3929 put_string(domain, &data);
3930 return reply;
3931 }
3932
3933 mDNSlocal void enum_termination_callback(request_state *request)
3934 {
3935 // Stop the domain enumeration queries to discover the WAB Browse/Registration domains
3936 if (request->u.enumeration.flags & kDNSServiceFlagsRegistrationDomains)
3937 {
3938 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3939 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
3940 }
3941 else
3942 {
3943 LogInfo("%3d: DNSServiceEnumeration Cancel WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
3944 uDNS_StopWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
3945 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_autoall);
3946 }
3947 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
3948 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
3949 }
3950
3951 mDNSlocal void enum_result_callback(mDNS *const m,
3952 DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord)
3953 {
3954 char domain[MAX_ESCAPED_DOMAIN_NAME];
3955 request_state *request = question->QuestionContext;
3956 DNSServiceFlags flags = 0;
3957 reply_state *reply;
3958 (void)m; // Unused
3959
3960 if (answer->rrtype != kDNSType_PTR) return;
3961
3962 #if 0
3963 if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return;
3964 #endif
3965
3966 // We only return add/remove events for the browse and registration lists
3967 // For the default browse and registration answers, we only give an "ADD" event
3968 if (question == &request->u.enumeration.q_default && !AddRecord) return;
3969
3970 if (AddRecord)
3971 {
3972 flags |= kDNSServiceFlagsAdd;
3973 if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault;
3974 }
3975
3976 ConvertDomainNameToCString(&answer->rdata->u.name, domain);
3977 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3978 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3979 // network, so we just pass kDNSServiceInterfaceIndexAny
3980 reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError);
3981 if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3982
3983 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "Add" : "Rmv", domain);
3984
3985 append_reply(request, reply);
3986 }
3987
3988 mDNSlocal mStatus handle_enum_request(request_state *request)
3989 {
3990 mStatus err;
3991 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
3992 DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains;
3993 mDNS_DomainType t_all = reg ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse;
3994 mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
3995 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
3996 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
3997 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
3998
3999 if (!request->msgptr)
4000 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4001
4002 request->flags = flags;
4003 request->interfaceIndex = interfaceIndex;
4004
4005 // mark which kind of enumeration we're doing so that we know what domain enumeration queries to stop
4006 request->u.enumeration.flags = reg;
4007
4008 // enumeration requires multiple questions, so we must link all the context pointers so that
4009 // necessary context can be reached from the callbacks
4010 request->u.enumeration.q_all.QuestionContext = request;
4011 request->u.enumeration.q_default.QuestionContext = request;
4012 if (!reg) request->u.enumeration.q_autoall.QuestionContext = request;
4013
4014 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
4015 if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly;
4016
4017 // make the calls
4018 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags,
4019 (flags & kDNSServiceFlagsBrowseDomains ) ? "kDNSServiceFlagsBrowseDomains" :
4020 (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
4021 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request);
4022 if (!err)
4023 {
4024 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request);
4025 if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
4026 else if (!reg)
4027 {
4028 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_autoall, mDNS_DomainTypeBrowseAutomatic, NULL, InterfaceID, enum_result_callback, request);
4029 if (err)
4030 {
4031 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all);
4032 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default);
4033 }
4034 }
4035 if (!err) request->terminate = enum_termination_callback;
4036 }
4037 if (!err)
4038 {
4039 // Start the domain enumeration queries to discover the WAB Browse/Registration domains
4040 if (reg)
4041 {
4042 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Registration PID[%d](%s)", request->sd, request->process_id, request->pid_name);
4043 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_REG_QUERY);
4044 }
4045 else
4046 {
4047 LogInfo("%3d: DNSServiceEnumerateDomains Start WAB Browse PID[%d](%s)", request->sd, request->process_id, request->pid_name);
4048 uDNS_StartWABQueries(&mDNSStorage, UDNS_WAB_BROWSE_QUERY | UDNS_WAB_LBROWSE_QUERY);
4049 }
4050 }
4051
4052 return(err);
4053 }
4054
4055 // ***************************************************************************
4056 #if COMPILER_LIKES_PRAGMA_MARK
4057 #pragma mark -
4058 #pragma mark - DNSServiceReconfirmRecord & Misc
4059 #endif
4060
4061 mDNSlocal mStatus handle_reconfirm_request(request_state *request)
4062 {
4063 mStatus status = mStatus_BadParamErr;
4064 AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0);
4065 if (rr)
4066 {
4067 status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec);
4068 LogOperation(
4069 (status == mStatus_NoError) ?
4070 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
4071 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
4072 request->sd, RRDisplayString(&mDNSStorage, &rr->resrec),
4073 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID, mDNSfalse), status);
4074 freeL("AuthRecord/handle_reconfirm_request", rr);
4075 }
4076 return(status);
4077 }
4078
4079 #if APPLE_OSX_mDNSResponder
4080
4081 mDNSlocal mStatus handle_release_request(request_state *request)
4082 {
4083 mStatus err = 0;
4084 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME];
4085 domainname instance;
4086
4087 // extract the data from the message
4088 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4089
4090 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 ||
4091 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
4092 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0)
4093 {
4094 LogMsg("ERROR: handle_release_request - Couldn't read name/regtype/domain");
4095 return(mStatus_BadParamErr);
4096 }
4097
4098 if (!request->msgptr)
4099 {
4100 LogMsg("%3d: PeerConnectionRelease(unreadable parameters)", request->sd);
4101 return(mStatus_BadParamErr);
4102 }
4103
4104 if (build_domainname_from_strings(&instance, name, regtype, domain) < 0)
4105 {
4106 LogMsg("ERROR: handle_release_request bad “%s” “%s” “%s”", name, regtype, domain);
4107 return(mStatus_BadParamErr);
4108 }
4109
4110 LogOperation("%3d: PeerConnectionRelease(%X %##s) START PID[%d](%s)",
4111 request->sd, flags, instance.c, request->process_id, request->pid_name);
4112
4113 external_connection_release(&instance);
4114 return(err);
4115 }
4116
4117 #else // APPLE_OSX_mDNSResponder
4118
4119 mDNSlocal mStatus handle_release_request(request_state *request)
4120 {
4121 (void) request;
4122 return mStatus_UnsupportedErr;
4123 }
4124
4125 #endif // APPLE_OSX_mDNSResponder
4126
4127 mDNSlocal mStatus handle_setdomain_request(request_state *request)
4128 {
4129 char domainstr[MAX_ESCAPED_DOMAIN_NAME];
4130 domainname domain;
4131 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4132 (void)flags; // Unused
4133 if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 ||
4134 !MakeDomainNameFromDNSNameString(&domain, domainstr))
4135 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4136
4137 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c);
4138 return(mStatus_NoError);
4139 }
4140
4141 typedef packedstruct
4142 {
4143 mStatus err;
4144 mDNSu32 len;
4145 mDNSu32 vers;
4146 } DaemonVersionReply;
4147
4148 mDNSlocal void handle_getproperty_request(request_state *request)
4149 {
4150 const mStatus BadParamErr = dnssd_htonl((mDNSu32)mStatus_BadParamErr);
4151 char prop[256];
4152 if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0)
4153 {
4154 LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop);
4155 if (!strcmp(prop, kDNSServiceProperty_DaemonVersion))
4156 {
4157 DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) };
4158 send_all(request->sd, (const char *)&x, sizeof(x));
4159 return;
4160 }
4161 }
4162
4163 // If we didn't recogize the requested property name, return BadParamErr
4164 send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr));
4165 }
4166
4167 #ifdef APPLE_OSX_mDNSResponder
4168 // The caller can specify either the pid or the uuid. If the pid is not specified,
4169 // update the effective uuid. Don't overwrite the pid which is used for debugging
4170 // purposes and initialized when the socket is opened.
4171 mDNSlocal void handle_connection_delegate_request(request_state *request)
4172 {
4173 mDNSs32 pid;
4174 socklen_t len;
4175
4176 len = 0;
4177 pid = get_uint32(&request->msgptr, request->msgend);
4178 #ifdef LOCAL_PEEREPID
4179 if (pid)
4180 {
4181 len = sizeof(pid);
4182 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREPID, &request->process_id, &len) != 0)
4183 {
4184 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREPID failed errno:%d / %s", errno, strerror(errno));
4185 return;
4186 }
4187 // to extract the process name from the pid value
4188 if (proc_pidinfo(request->process_id, PROC_PIDT_SHORTBSDINFO, 1, &proc, PROC_PIDT_SHORTBSDINFO_SIZE) == 0)
4189 return;
4190 mDNSPlatformStrLCopy(request->pid_name, proc.pbsi_comm, sizeof(request->pid_name));
4191 debugf("handle_connection_delegate_request: process id %d, name %s", request->process_id, request->pid_name);
4192 }
4193 #endif
4194 #ifdef LOCAL_PEEREUUID
4195 if (!pid)
4196 {
4197 len = UUID_SIZE;
4198 if (getsockopt(request->sd, SOL_LOCAL, LOCAL_PEEREUUID, request->uuid, &len) != 0)
4199 {
4200 LogMsg("handle_connection_delegate_request: getsockopt for LOCAL_PEEREUUID failed errno:%d / %s", errno, strerror(errno));
4201 return;
4202 }
4203 request->validUUID = mDNStrue;
4204 }
4205 #endif
4206 }
4207 #else
4208 mDNSlocal void handle_connection_delegate_request(request_state *request)
4209 {
4210 (void) request;
4211 }
4212 #endif
4213
4214 typedef packedstruct
4215 {
4216 mStatus err;
4217 mDNSs32 pid;
4218 } PIDInfo;
4219
4220 mDNSlocal void handle_getpid_request(request_state *request)
4221 {
4222 const request_state *req;
4223 mDNSs32 pid = -1;
4224 mDNSu16 srcport = get_uint16(&request->msgptr, request->msgend);
4225 const DNSQuestion *q = NULL;
4226 PIDInfo pi;
4227
4228 LogMsg("%3d: DNSServiceGetPID START", request->sd);
4229
4230 for (req = all_requests; req; req=req->next)
4231 {
4232 if (req->hdr.op == query_request)
4233 q = &req->u.queryrecord.q;
4234 else if (req->hdr.op == addrinfo_request)
4235 q = &req->u.addrinfo.q4;
4236 else if (req->hdr.op == addrinfo_request)
4237 q = &req->u.addrinfo.q6;
4238
4239 if (q && q->LocalSocket != NULL)
4240 {
4241 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4242 if (port == srcport)
4243 {
4244 pid = req->process_id;
4245 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s] question %##s", htons(srcport), pid, req->pid_name, q->qname.c);
4246 break;
4247 }
4248 }
4249 }
4250 // If we cannot find in the client requests, look to see if this was
4251 // started by mDNSResponder.
4252 if (pid == -1)
4253 {
4254 for (q = mDNSStorage.Questions; q; q = q->next)
4255 {
4256 if (q && q->LocalSocket != NULL)
4257 {
4258 mDNSu16 port = mDNSPlatformGetUDPPort(q->LocalSocket);
4259 if (port == srcport)
4260 {
4261 #if APPLE_OSX_mDNSResponder
4262 pid = getpid();
4263 #endif // APPLE_OSX_mDNSResponder
4264 LogMsg("DNSServiceGetPID: srcport %d, pid %d [%s], question %##s", htons(srcport), pid, "_mDNSResponder", q->qname.c);
4265 break;
4266 }
4267 }
4268 }
4269 }
4270
4271 pi.err = 0;
4272 pi.pid = pid;
4273 send_all(request->sd, (const char *)&pi, sizeof(PIDInfo));
4274 LogMsg("%3d: DNSServiceGetPID STOP", request->sd);
4275 }
4276
4277 // ***************************************************************************
4278 #if COMPILER_LIKES_PRAGMA_MARK
4279 #pragma mark -
4280 #pragma mark - DNSServiceNATPortMappingCreate
4281 #endif
4282
4283 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
4284
4285 mDNSlocal void port_mapping_termination_callback(request_state *request)
4286 {
4287 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP PID[%d](%s)", request->sd,
4288 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4289 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4290 request->process_id, request->pid_name);
4291 mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4292 }
4293
4294 // Called via function pointer when we get a NAT Traversal (address request or port mapping) response
4295 mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n)
4296 {
4297 request_state *request = (request_state *)n->clientContext;
4298 reply_state *rep;
4299 int replyLen;
4300 char *data;
4301
4302 if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
4303
4304 // calculate reply data length
4305 replyLen = sizeof(DNSServiceFlags);
4306 replyLen += 3 * sizeof(mDNSu32); // if index + addr + ttl
4307 replyLen += sizeof(DNSServiceErrorType);
4308 replyLen += 2 * sizeof(mDNSu16); // Internal Port + External Port
4309 replyLen += sizeof(mDNSu8); // protocol
4310
4311 rep = create_reply(port_mapping_reply_op, replyLen, request);
4312
4313 rep->rhdr->flags = dnssd_htonl(0);
4314 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID, mDNSfalse));
4315 rep->rhdr->error = dnssd_htonl(n->Result);
4316
4317 data = (char *)&rep->rhdr[1];
4318
4319 *data++ = request->u.pm.NATinfo.ExternalAddress.b[0];
4320 *data++ = request->u.pm.NATinfo.ExternalAddress.b[1];
4321 *data++ = request->u.pm.NATinfo.ExternalAddress.b[2];
4322 *data++ = request->u.pm.NATinfo.ExternalAddress.b[3];
4323 *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol);
4324 *data++ = request->u.pm.NATinfo.IntPort.b[0];
4325 *data++ = request->u.pm.NATinfo.IntPort.b[1];
4326 *data++ = request->u.pm.NATinfo.ExternalPort.b[0];
4327 *data++ = request->u.pm.NATinfo.ExternalPort.b[1];
4328 put_uint32(request->u.pm.NATinfo.Lifetime, &data);
4329
4330 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd,
4331 DNSServiceProtocol(request->u.pm.NATinfo.Protocol),
4332 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4333 &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime);
4334
4335 append_reply(request, rep);
4336 }
4337
4338 mDNSlocal mStatus handle_port_mapping_request(request_state *request)
4339 {
4340 mDNSu32 ttl = 0;
4341 mStatus err = mStatus_NoError;
4342
4343 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4344 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4345 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4346 mDNSu8 protocol = (mDNSu8)get_uint32(&request->msgptr, request->msgend);
4347 (void)flags; // Unused
4348 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr);
4349 if (request->msgptr + 8 > request->msgend) request->msgptr = NULL;
4350 else
4351 {
4352 request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++;
4353 request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++;
4354 request->u.pm.ReqExt.b[0] = *request->msgptr++;
4355 request->u.pm.ReqExt.b[1] = *request->msgptr++;
4356 ttl = get_uint32(&request->msgptr, request->msgend);
4357 }
4358
4359 if (!request->msgptr)
4360 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4361
4362 if (protocol == 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
4363 {
4364 if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr);
4365 }
4366 else
4367 {
4368 if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr);
4369 if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr);
4370 }
4371
4372 request->flags = flags;
4373 request->interfaceIndex = interfaceIndex;
4374 request->u.pm.NATinfo.Protocol = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP;
4375 // u.pm.NATinfo.IntPort = already set above
4376 request->u.pm.NATinfo.RequestedPort = request->u.pm.ReqExt;
4377 request->u.pm.NATinfo.NATLease = ttl;
4378 request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback;
4379 request->u.pm.NATinfo.clientContext = request;
4380
4381 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START PID[%d](%s)", request->sd,
4382 protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease,
4383 request->process_id, request->pid_name);
4384 err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo);
4385 if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err);
4386 else request->terminate = port_mapping_termination_callback;
4387
4388 return(err);
4389 }
4390
4391 // ***************************************************************************
4392 #if COMPILER_LIKES_PRAGMA_MARK
4393 #pragma mark -
4394 #pragma mark - DNSServiceGetAddrInfo
4395 #endif
4396
4397 mDNSlocal void addrinfo_termination_callback(request_state *request)
4398 {
4399 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) STOP PID[%d](%s)", request->sd, request->u.addrinfo.q4.qname.c,
4400 request->process_id, request->pid_name);
4401
4402 if (request->u.addrinfo.q4.QuestionContext)
4403 {
4404 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4);
4405 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q4, request, q_stop);
4406 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4407
4408 if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, request->flags))
4409 {
4410 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for kDNSServiceType_A record");
4411 external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q4.qname, kDNSServiceType_A, request->flags);
4412 }
4413 }
4414 if (request->u.addrinfo.q4.qnameOrig)
4415 {
4416 freeL("QueryTermination", request->u.addrinfo.q4.qnameOrig);
4417 request->u.addrinfo.q4.qnameOrig = mDNSNULL;
4418 }
4419 if (request->u.addrinfo.q42)
4420 {
4421 if (request->u.addrinfo.q42->QuestionContext)
4422 {
4423 LogInfo("addrinfo_termination_callback: Stopping q42 %##s", request->u.addrinfo.q42->qname.c);
4424 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q42);
4425 LogMcastQ(&mDNSStorage, request->u.addrinfo.q42, request, q_stop);
4426 }
4427 if (request->u.addrinfo.q42->qnameOrig)
4428 {
4429 LogInfo("addrinfo_termination_callback: freeing q42 qnameOrig %##s", request->u.addrinfo.q42->qnameOrig->c);
4430 freeL("QueryTermination q42", request->u.addrinfo.q42->qnameOrig);
4431 request->u.addrinfo.q42->qnameOrig = mDNSNULL;
4432 }
4433 freeL("addrinfo Q42", request->u.addrinfo.q42);
4434 request->u.addrinfo.q42 = mDNSNULL;
4435 }
4436
4437 if (request->u.addrinfo.q6.QuestionContext)
4438 {
4439 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4440 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q6, request, q_stop);
4441 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4442
4443 if (callExternalHelpers(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, request->flags))
4444 {
4445 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for kDNSServiceType_AAAA record");
4446 external_stop_browsing_for_service(request->u.addrinfo.interface_id, &request->u.addrinfo.q6.qname, kDNSServiceType_AAAA, request->flags);
4447 }
4448 }
4449 if (request->u.addrinfo.q6.qnameOrig)
4450 {
4451 freeL("QueryTermination", request->u.addrinfo.q6.qnameOrig);
4452 request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4453 }
4454 if (request->u.addrinfo.q62)
4455 {
4456 if (request->u.addrinfo.q62->QuestionContext)
4457 {
4458 LogInfo("addrinfo_termination_callback: Stopping q62 %##s", request->u.addrinfo.q62->qname.c);
4459 mDNS_StopQuery(&mDNSStorage, request->u.addrinfo.q62);
4460 LogMcastQ(&mDNSStorage, request->u.addrinfo.q62, request, q_stop);
4461 }
4462 if (request->u.addrinfo.q62->qnameOrig)
4463 {
4464 LogInfo("addrinfo_termination_callback: freeing q62 qnameOrig %##s", request->u.addrinfo.q62->qnameOrig->c);
4465 freeL("QueryTermination q62", request->u.addrinfo.q62->qnameOrig);
4466 request->u.addrinfo.q62->qnameOrig = mDNSNULL;
4467 }
4468 freeL("addrinfo Q62", request->u.addrinfo.q62);
4469 request->u.addrinfo.q62 = mDNSNULL;
4470 }
4471 #if APPLE_OSX_mDNSResponder
4472 {
4473 DNSQuestion *v4q, *v6q;
4474 v4q = v6q = mDNSNULL;
4475 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4)
4476 {
4477 // If we are not delivering answers, we may be timing out prematurely.
4478 // Note down the current state so that we know to retry when we see a
4479 // valid response again.
4480 if (request->u.addrinfo.q4.TimeoutQuestion && !request->u.addrinfo.v4ans)
4481 {
4482 mDNSPlatformUpdateDNSStatus(&mDNSStorage, &request->u.addrinfo.q4);
4483 }
4484 // If we have a v4 answer and if we timed out prematurely before, provide
4485 // a trigger to the upper layer so that it can retry questions if needed.
4486 if (request->u.addrinfo.v4ans)
4487 v4q = &request->u.addrinfo.q4;
4488 }
4489 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4490 {
4491 if (request->u.addrinfo.q6.TimeoutQuestion && !request->u.addrinfo.v6ans)
4492 {
4493 mDNSPlatformUpdateDNSStatus(&mDNSStorage, &request->u.addrinfo.q6);
4494 }
4495 if (request->u.addrinfo.v6ans)
4496 v6q = &request->u.addrinfo.q6;
4497 }
4498 mDNSPlatformTriggerDNSRetry(&mDNSStorage, v4q, v6q);
4499 }
4500 #endif // APPLE_OSX_mDNSResponder
4501 }
4502
4503 mDNSlocal mStatus handle_addrinfo_request(request_state *request)
4504 {
4505 char hostname[256];
4506 size_t hostnameLen;
4507 domainname d;
4508 mStatus err = 0;
4509 mDNSs32 serviceIndex = -1; // default unscoped value for ServiceID is -1
4510 mDNSInterfaceID InterfaceID;
4511
4512 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
4513
4514 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
4515
4516 if (flags & kDNSServiceFlagsServiceIndex)
4517 {
4518 // NOTE: kDNSServiceFlagsServiceIndex flag can only be set for DNSServiceGetAddrInfo()
4519 LogInfo("DNSServiceGetAddrInfo: kDNSServiceFlagsServiceIndex is SET by the client");
4520 // if kDNSServiceFlagsServiceIndex is SET,
4521 // interpret the interfaceID as the serviceId and set the interfaceID to 0.
4522 serviceIndex = interfaceIndex;
4523 interfaceIndex = 0;
4524 }
4525
4526 mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo));
4527
4528 InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
4529
4530 // The request is scoped to a specific interface index, but the
4531 // interface is not currently in our list.
4532 if (interfaceIndex && !InterfaceID)
4533 {
4534 if (interfaceIndex > 1)
4535 LogMsg("handle_addrinfo_request: interfaceIndex %d is currently inactive requested by client[%d][%s]",
4536 interfaceIndex, request->process_id, request->pid_name);
4537 // If it's one of the specially defined inteface index values, just return an error.
4538 if (PreDefinedInterfaceIndex(interfaceIndex))
4539 {
4540 LogInfo("handle_addrinfo_request: bad interfaceIndex %d", interfaceIndex);
4541 return(mStatus_BadParamErr);
4542 }
4543
4544 // Otherwise, use the specified interface index value and the request will
4545 // be applied to that interface when it comes up.
4546 InterfaceID = (mDNSInterfaceID)(uintptr_t)interfaceIndex;
4547 LogInfo("handle_addrinfo_request: query pending for interface index %d", interfaceIndex);
4548 }
4549
4550 request->flags = flags;
4551 request->interfaceIndex = interfaceIndex;
4552 request->u.addrinfo.interface_id = InterfaceID;
4553 request->u.addrinfo.flags = flags;
4554 request->u.addrinfo.protocol = get_uint32(&request->msgptr, request->msgend);
4555
4556 if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr);
4557
4558 if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr);
4559
4560 if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); }
4561
4562 if (!MakeDomainNameFromDNSNameString(&d, hostname))
4563 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); }
4564
4565 #if 0
4566 if (!AuthorizedDomain(request, &d, AutoBrowseDomains)) return (mStatus_NoError);
4567 #endif
4568
4569 if (!request->u.addrinfo.protocol)
4570 {
4571 flags |= kDNSServiceFlagsSuppressUnusable;
4572 request->u.addrinfo.protocol = (kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
4573 }
4574
4575 request->u.addrinfo.q4.InterfaceID = request->u.addrinfo.q6.InterfaceID = request->u.addrinfo.interface_id;
4576 request->u.addrinfo.q4.ServiceID = request->u.addrinfo.q6.ServiceID = serviceIndex;
4577 request->u.addrinfo.q4.flags = request->u.addrinfo.q6.flags = flags;
4578 request->u.addrinfo.q4.Target = request->u.addrinfo.q6.Target = zeroAddr;
4579 request->u.addrinfo.q4.qname = request->u.addrinfo.q6.qname = d;
4580 request->u.addrinfo.q4.qclass = request->u.addrinfo.q6.qclass = kDNSServiceClass_IN;
4581 request->u.addrinfo.q4.LongLived = request->u.addrinfo.q6.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0;
4582 request->u.addrinfo.q4.ExpectUnique = request->u.addrinfo.q6.ExpectUnique = mDNSfalse;
4583 request->u.addrinfo.q4.ForceMCast = request->u.addrinfo.q6.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0;
4584 request->u.addrinfo.q4.ReturnIntermed = request->u.addrinfo.q6.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
4585 request->u.addrinfo.q4.SuppressUnusable = request->u.addrinfo.q6.SuppressUnusable = (flags & kDNSServiceFlagsSuppressUnusable ) != 0;
4586 request->u.addrinfo.q4.TimeoutQuestion = request->u.addrinfo.q6.TimeoutQuestion = (flags & kDNSServiceFlagsTimeout ) != 0;
4587 request->u.addrinfo.q4.WakeOnResolve = request->u.addrinfo.q6.WakeOnResolve = 0;
4588 request->u.addrinfo.q4.UseBackgroundTrafficClass = request->u.addrinfo.q6.UseBackgroundTrafficClass = (flags & kDNSServiceFlagsBackgroundTrafficClass) != 0;
4589 if ((flags & kDNSServiceFlagsValidate) != 0)
4590 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE;
4591 else if ((flags & kDNSServiceFlagsValidateOptional) != 0)
4592 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = DNSSEC_VALIDATION_SECURE_OPTIONAL;
4593 request->u.addrinfo.q4.ValidatingResponse = request->u.addrinfo.q6.ValidatingResponse = 0;
4594 request->u.addrinfo.q4.ProxyQuestion = request->u.addrinfo.q6.ProxyQuestion = 0;
4595 request->u.addrinfo.q4.qnameOrig = request->u.addrinfo.q6.qnameOrig = mDNSNULL;
4596 request->u.addrinfo.q4.AnonInfo = request->u.addrinfo.q6.AnonInfo = mDNSNULL;
4597
4598 SetQuestionPolicy(&request->u.addrinfo.q4, request);
4599 SetQuestionPolicy(&request->u.addrinfo.q6, request);
4600
4601 request->u.addrinfo.q4.DNSSECAuthInfo = request->u.addrinfo.q6.DNSSECAuthInfo = mDNSNULL;
4602 request->u.addrinfo.q4.DAIFreeCallback = request->u.addrinfo.q6.DAIFreeCallback = mDNSNULL;
4603
4604 //Turn off dnssec validation for local domains
4605 if (IsLocalDomain(&d))
4606 request->u.addrinfo.q4.ValidationRequired = request->u.addrinfo.q6.ValidationRequired = 0;
4607
4608 hostnameLen = strlen(hostname);
4609
4610 LogOperation("%3d: DNSServiceGetAddrInfo(%X, %d, %d, %##s) START PID[%d](%s)",
4611 request->sd, flags, interfaceIndex, request->u.addrinfo.protocol, d.c, request->process_id, request->pid_name);
4612
4613 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4614 {
4615 request->u.addrinfo.q6.qtype = kDNSServiceType_AAAA;
4616 request->u.addrinfo.q6.SearchListIndex = 0;
4617 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set
4618 if ((!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q6.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4619 && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4620 {
4621 request->u.addrinfo.q6.AppendSearchDomains = 1;
4622 request->u.addrinfo.q6.AppendLocalSearchDomains = 1;
4623 }
4624 else
4625 {
4626 request->u.addrinfo.q6.AppendSearchDomains = 0;
4627 request->u.addrinfo.q6.AppendLocalSearchDomains = 0;
4628 }
4629 request->u.addrinfo.q6.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q6) ? 1 : 0);
4630 request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback;
4631 request->u.addrinfo.q6.QuestionContext = request;
4632 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6);
4633 if (err != mStatus_NoError)
4634 {
4635 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4636 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4637 }
4638 #if APPLE_OSX_mDNSResponder
4639 err = SendAdditionalQuery(&request->u.addrinfo.q6, request, err);
4640 #endif // APPLE_OSX_mDNSResponder
4641 if (!err)
4642 {
4643 request->terminate = addrinfo_termination_callback;
4644 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q6, request, q_start);
4645 if (callExternalHelpers(InterfaceID, &d, flags))
4646 {
4647 LogInfo("handle_addrinfo_request: calling external_start_browsing_for_service() for kDNSServiceType_AAAA record");
4648 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags, &request->u.addrinfo.q6);
4649 }
4650 }
4651 }
4652
4653 if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4))
4654 {
4655 request->u.addrinfo.q4.qtype = kDNSServiceType_A;
4656 request->u.addrinfo.q4.SearchListIndex = 0;
4657
4658 // We append search domains only for queries that are a single label. If overriden using cmd line arg
4659 // "AlwaysAppendSearchDomains", then we do it for any query which is not fully qualified.
4660 // For DNSSEC questions, append search domains only if kDNSServiceFlagsValidateOptional is set.
4661
4662 if ((!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_SECURE)) && (!(request->u.addrinfo.q4.ValidationRequired == DNSSEC_VALIDATION_INSECURE))
4663 && ((hostnameLen == 0) || (hostname[hostnameLen - 1] != '.')) && (AlwaysAppendSearchDomains || CountLabels(&d) == 1))
4664 {
4665 request->u.addrinfo.q4.AppendSearchDomains = 1;
4666 request->u.addrinfo.q4.AppendLocalSearchDomains = 1;
4667 }
4668 else
4669 {
4670 request->u.addrinfo.q4.AppendSearchDomains = 0;
4671 request->u.addrinfo.q4.AppendLocalSearchDomains = 0;
4672 }
4673 request->u.addrinfo.q4.RetryWithSearchDomains = (ApplySearchDomainsFirst(&request->u.addrinfo.q4) ? 1 : 0);
4674 request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback;
4675 request->u.addrinfo.q4.QuestionContext = request;
4676 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4);
4677 if (err != mStatus_NoError)
4678 {
4679 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err);
4680 request->u.addrinfo.q4.QuestionContext = mDNSNULL;
4681 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)
4682 {
4683 // If we started a query for IPv6, we need to cancel it
4684 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6);
4685 request->u.addrinfo.q6.QuestionContext = mDNSNULL;
4686
4687 if (callExternalHelpers(InterfaceID, &d, flags))
4688 {
4689 LogInfo("addrinfo_termination_callback: calling external_stop_browsing_for_service() for kDNSServiceType_AAAA record");
4690 external_stop_browsing_for_service(InterfaceID, &d, kDNSServiceType_AAAA, flags);
4691 }
4692 }
4693 }
4694 #if APPLE_OSX_mDNSResponder
4695 err = SendAdditionalQuery(&request->u.addrinfo.q4, request, err);
4696 #endif // APPLE_OSX_mDNSResponder
4697 if (!err)
4698 {
4699 request->terminate = addrinfo_termination_callback;
4700 LogMcastQ(&mDNSStorage, &request->u.addrinfo.q4, request, q_start);
4701 if (callExternalHelpers(InterfaceID, &d, flags))
4702 {
4703 LogInfo("handle_addrinfo_request: calling external_start_browsing_for_service() for kDNSServiceType_A record");
4704 external_start_browsing_for_service(InterfaceID, &d, kDNSServiceType_A, flags, &request->u.addrinfo.q4);
4705 }
4706 }
4707 }
4708
4709 return(err);
4710 }
4711
4712 // ***************************************************************************
4713 #if COMPILER_LIKES_PRAGMA_MARK
4714 #pragma mark -
4715 #pragma mark - Main Request Handler etc.
4716 #endif
4717
4718 mDNSlocal request_state *NewRequest(void)
4719 {
4720 request_state **p = &all_requests;
4721 while (*p)
4722 p=&(*p)->next;
4723 *p = mallocL("request_state", sizeof(request_state));
4724 if (!*p)
4725 FatalError("ERROR: malloc");
4726 mDNSPlatformMemZero(*p, sizeof(request_state));
4727 return(*p);
4728 }
4729
4730 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
4731 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
4732 mDNSlocal void read_msg(request_state *req)
4733 {
4734 if (req->ts == t_terminated || req->ts == t_error)
4735 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; }
4736
4737 if (req->ts == t_complete) // this must be death or something is wrong
4738 {
4739 char buf[4]; // dummy for death notification
4740 int nread = udsSupportReadFD(req->sd, buf, 4, 0, req->platform_data);
4741 if (!nread) { req->ts = t_terminated; return; }
4742 if (nread < 0) goto rerror;
4743 LogMsg("%3d: ERROR: read data from a completed request", req->sd);
4744 req->ts = t_error;
4745 return;
4746 }
4747
4748 if (req->ts != t_morecoming)
4749 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; }
4750
4751 if (req->hdr_bytes < sizeof(ipc_msg_hdr))
4752 {
4753 mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes;
4754 int nread = udsSupportReadFD(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0, req->platform_data);
4755 if (nread == 0) { req->ts = t_terminated; return; }
4756 if (nread < 0) goto rerror;
4757 req->hdr_bytes += nread;
4758 if (req->hdr_bytes > sizeof(ipc_msg_hdr))
4759 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; }
4760
4761 // only read data if header is complete
4762 if (req->hdr_bytes == sizeof(ipc_msg_hdr))
4763 {
4764 ConvertHeaderBytes(&req->hdr);
4765 if (req->hdr.version != VERSION)
4766 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; }
4767
4768 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
4769 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
4770 // for other overhead, this means any message above 70kB is definitely bogus.
4771 if (req->hdr.datalen > 70000)
4772 { LogMsg("%3d: ERROR: read_msg: hdr.datalen %u (0x%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; }
4773 req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES);
4774 if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; }
4775 req->msgptr = req->msgbuf;
4776 req->msgend = req->msgbuf + req->hdr.datalen;
4777 mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES);
4778 }
4779 }
4780
4781 // If our header is complete, but we're still needing more body data, then try to read it now
4782 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
4783 // Any time we need to get the error return socket we know we'll have at least one data byte
4784 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
4785 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen)
4786 {
4787 mDNSu32 nleft = req->hdr.datalen - req->data_bytes;
4788 int nread;
4789 #if !defined(_WIN32)
4790 struct iovec vec = { req->msgbuf + req->data_bytes, nleft }; // Tell recvmsg where we want the bytes put
4791 struct msghdr msg;
4792 struct cmsghdr *cmsg;
4793 char cbuf[CMSG_SPACE(4 * sizeof(dnssd_sock_t))];
4794 msg.msg_name = 0;
4795 msg.msg_namelen = 0;
4796 msg.msg_iov = &vec;
4797 msg.msg_iovlen = 1;
4798 msg.msg_control = cbuf;
4799 msg.msg_controllen = sizeof(cbuf);
4800 msg.msg_flags = 0;
4801 nread = recvmsg(req->sd, &msg, 0);
4802 #else
4803 nread = udsSupportReadFD(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0, req->platform_data);
4804 #endif
4805 if (nread == 0) { req->ts = t_terminated; return; }
4806 if (nread < 0) goto rerror;
4807 req->data_bytes += nread;
4808 if (req->data_bytes > req->hdr.datalen)
4809 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; }
4810 #if !defined(_WIN32)
4811 cmsg = CMSG_FIRSTHDR(&msg);
4812 #if DEBUG_64BIT_SCM_RIGHTS
4813 LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf), sizeof(cbuf), SOL_SOCKET, SCM_RIGHTS);
4814 LogMsg("%3d: Got %d %d %d %d", req->sd, msg.msg_controllen, cmsg ? cmsg->cmsg_len : -1, cmsg ? cmsg->cmsg_level : -1, cmsg ? cmsg->cmsg_type : -1);
4815 #endif // DEBUG_64BIT_SCM_RIGHTS
4816 if (cmsg && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
4817 {
4818 #if APPLE_OSX_mDNSResponder
4819 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
4820 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
4821 // and it's convenient to repurpose the existing fd-passing code here for that task
4822 if (req->hdr.op == send_bpf)
4823 {
4824 dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4825 LogOperation("%3d: Got len %d, BPF %d", req->sd, cmsg->cmsg_len, x);
4826 mDNSPlatformReceiveBPF_fd(&mDNSStorage, x);
4827 }
4828 else
4829 #endif // APPLE_OSX_mDNSResponder
4830 req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg);
4831 #if DEBUG_64BIT_SCM_RIGHTS
4832 LogMsg("%3d: read req->errsd %d", req->sd, req->errsd);
4833 #endif // DEBUG_64BIT_SCM_RIGHTS
4834 if (req->data_bytes < req->hdr.datalen)
4835 {
4836 LogMsg("%3d: Client(PID [%d](%s)) sent result code socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
4837 req->sd, req->process_id, req->pid_name, req->errsd, req->data_bytes, req->hdr.datalen);
4838 req->ts = t_error;
4839 return;
4840 }
4841 }
4842 #endif
4843 }
4844
4845 // If our header and data are both complete, see if we need to make our separate error return socket
4846 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen)
4847 {
4848 if (req->terminate && req->hdr.op != cancel_request)
4849 {
4850 dnssd_sockaddr_t cliaddr;
4851 #if defined(USE_TCP_LOOPBACK)
4852 mDNSOpaque16 port;
4853 u_long opt = 1;
4854 port.b[0] = req->msgptr[0];
4855 port.b[1] = req->msgptr[1];
4856 req->msgptr += 2;
4857 cliaddr.sin_family = AF_INET;
4858 cliaddr.sin_port = port.NotAnInteger;
4859 cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
4860 #else
4861 char ctrl_path[MAX_CTLPATH];
4862 get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH); // path is first element in message buffer
4863 mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr));
4864 cliaddr.sun_family = AF_LOCAL;
4865 mDNSPlatformStrLCopy(cliaddr.sun_path, ctrl_path, sizeof(cliaddr.sun_path));
4866 // If the error return path UDS name is empty string, that tells us
4867 // that this is a new version of the library that's going to pass us
4868 // the error return path socket via sendmsg/recvmsg
4869 if (ctrl_path[0] == 0)
4870 {
4871 if (req->errsd == req->sd)
4872 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; }
4873 goto got_errfd;
4874 }
4875 #endif
4876
4877 req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0);
4878 if (!dnssd_SocketValid(req->errsd))
4879 {
4880 my_throttled_perror("ERROR: socket");
4881 req->ts = t_error;
4882 return;
4883 }
4884
4885 if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0)
4886 {
4887 #if !defined(USE_TCP_LOOPBACK)
4888 struct stat sb;
4889 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
4890 req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4891 if (stat(cliaddr.sun_path, &sb) < 0)
4892 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno));
4893 else
4894 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);
4895 #endif
4896 req->ts = t_error;
4897 return;
4898 }
4899
4900 #if !defined(USE_TCP_LOOPBACK)
4901 got_errfd:
4902 #endif
4903 LogOperation("%3d: Result code socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]);
4904 #if defined(_WIN32)
4905 if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0)
4906 #else
4907 if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0)
4908 #endif
4909 {
4910 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
4911 req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4912 req->ts = t_error;
4913 return;
4914 }
4915 }
4916
4917 req->ts = t_complete;
4918 }
4919
4920 return;
4921
4922 rerror:
4923 if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return;
4924 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
4925 req->ts = t_error;
4926 }
4927
4928 #define RecordOrientedOp(X) \
4929 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
4930
4931 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
4932 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
4933
4934 mDNSlocal void request_callback(int fd, short filter, void *info)
4935 {
4936 mStatus err = 0;
4937 request_state *req = info;
4938 mDNSs32 min_size = sizeof(DNSServiceFlags);
4939 (void)fd; // Unused
4940 (void)filter; // Unused
4941
4942 for (;;)
4943 {
4944 read_msg(req);
4945 if (req->ts == t_morecoming)
4946 return;
4947 if (req->ts == t_terminated || req->ts == t_error)
4948 {
4949 AbortUnlinkAndFree(req);
4950 return;
4951 }
4952 if (req->ts != t_complete)
4953 {
4954 LogMsg("request_callback: req->ts %d != t_complete PID[%d][%s]", req->ts, req->process_id, req->pid_name);
4955 AbortUnlinkAndFree(req);
4956 return;
4957 }
4958 if (req->hdr.version != VERSION)
4959 {
4960 LogMsg("request_callback: ERROR: client IPC version %d incompatible with daemon IPC version %d PID[%d][%s]",
4961 req->hdr.version, VERSION, req->process_id, req->pid_name);
4962 AbortUnlinkAndFree(req);
4963 return;
4964 }
4965
4966 switch(req->hdr.op) // Interface + other data
4967 {
4968 case connection_request: min_size = 0; break;
4969 case connection_delegate_request: min_size = 4; /* pid */ break;
4970 case reg_service_request: min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
4971 case add_record_request: min_size += 4 /* type, rdlen */ + 4 /* ttl */; break;
4972 case update_record_request: min_size += 2 /* rdlen */ + 4 /* ttl */; break;
4973 case remove_record_request: break;
4974 case browse_request: min_size += sizeof(mDNSu32) + 2 /* type, domain */; break;
4975 case resolve_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4976 case query_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 4 /* type, class*/; break;
4977 case enumeration_request: min_size += sizeof(mDNSu32); break;
4978 case reg_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
4979 case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */; break;
4980 case setdomain_request: min_size += 1 /* domain */; break;
4981 case getproperty_request: min_size = 2; break;
4982 case getpid_request: min_size = 2; break;
4983 case port_mapping_request: min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
4984 case addrinfo_request: min_size += sizeof(mDNSu32) + 4 /* v4/v6 */ + 1 /* hostname */; break;
4985 case send_bpf: // Same as cancel_request below
4986 case cancel_request: min_size = 0; break;
4987 case release_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break;
4988 default: LogMsg("request_callback: ERROR: validate_message - unsupported req type: %d PID[%d][%s]",
4989 req->hdr.op, req->process_id, req->pid_name);
4990 min_size = -1; break;
4991 }
4992
4993 if ((mDNSs32)req->data_bytes < min_size)
4994 {
4995 LogMsg("request_callback: Invalid message %d bytes; min for %d is %d PID[%d][%s]",
4996 req->data_bytes, req->hdr.op, min_size, req->process_id, req->pid_name);
4997 AbortUnlinkAndFree(req);
4998 return;
4999 }
5000 if (LightweightOp(req->hdr.op) && !req->terminate)
5001 {
5002 LogMsg("request_callback: Reg/Add/Update/Remove %d require existing connection PID[%d][%s]",
5003 req->hdr.op, req->process_id, req->pid_name);
5004 AbortUnlinkAndFree(req);
5005 return;
5006 }
5007
5008 // If req->terminate is already set, this means this operation is sharing an existing connection
5009 if (req->terminate && !LightweightOp(req->hdr.op))
5010 {
5011 request_state *newreq = NewRequest();
5012 newreq->primary = req;
5013 newreq->sd = req->sd;
5014 newreq->errsd = req->errsd;
5015 newreq->uid = req->uid;
5016 newreq->hdr = req->hdr;
5017 newreq->msgbuf = req->msgbuf;
5018 newreq->msgptr = req->msgptr;
5019 newreq->msgend = req->msgend;
5020 // if the parent request is a delegate connection, copy the
5021 // relevant bits
5022 if (req->validUUID)
5023 {
5024 int i;
5025 newreq->validUUID = mDNStrue;
5026 for (i = 0; i < UUID_SIZE; i++)
5027 {
5028 newreq->uuid[i] = req->uuid[i];
5029 }
5030 }
5031 else
5032 {
5033 if (req->process_id)
5034 {
5035 newreq->process_id = req->process_id;
5036 mDNSPlatformStrLCopy(newreq->pid_name, req->pid_name, (mDNSu32)sizeof(newreq->pid_name));
5037 }
5038 else
5039 {
5040 set_peer_pid(newreq);
5041 }
5042 }
5043 req = newreq;
5044 }
5045
5046 // Check if the request wants no asynchronous replies.
5047 if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1;
5048
5049 // If we're shutting down, don't allow new client requests
5050 // We do allow "cancel" and "getproperty" during shutdown
5051 if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request)
5052 {
5053 err = mStatus_ServiceNotRunning;
5054 }
5055 else
5056 {
5057 switch(req->hdr.op)
5058 {
5059 // These are all operations that have their own first-class request_state object
5060 case connection_request:
5061 LogOperation("%3d: DNSServiceCreateConnection START PID[%d](%s)",
5062 req->sd, req->process_id, req->pid_name);
5063 req->terminate = connection_termination;
5064 break;
5065 case connection_delegate_request:
5066 LogOperation("%3d: DNSServiceCreateDelegateConnection START PID[%d](%s)",
5067 req->sd, req->process_id, req->pid_name);
5068 req->terminate = connection_termination;
5069 handle_connection_delegate_request(req);
5070 break;
5071 case resolve_request: err = handle_resolve_request (req); break;
5072 case query_request: err = handle_queryrecord_request (req); break;
5073 case browse_request: err = handle_browse_request (req); break;
5074 case reg_service_request: err = handle_regservice_request (req); break;
5075 case enumeration_request: err = handle_enum_request (req); break;
5076 case reconfirm_record_request: err = handle_reconfirm_request (req); break;
5077 case setdomain_request: err = handle_setdomain_request (req); break;
5078 case getproperty_request: handle_getproperty_request (req); break;
5079 case getpid_request: handle_getpid_request (req); break;
5080 case port_mapping_request: err = handle_port_mapping_request(req); break;
5081 case addrinfo_request: err = handle_addrinfo_request (req); break;
5082 case send_bpf: /* Do nothing for send_bpf */ break;
5083
5084 // These are all operations that work with an existing request_state object
5085 case reg_record_request: err = handle_regrecord_request (req); break;
5086 case add_record_request: err = handle_add_request (req); break;
5087 case update_record_request: err = handle_update_request (req); break;
5088 case remove_record_request: err = handle_removerecord_request(req); break;
5089 case cancel_request: handle_cancel_request (req); break;
5090 case release_request: err = handle_release_request (req); break;
5091 default: LogMsg("request_callback: %3d:ERROR: Unsupported UDS req:%d PID[%d][%s]",
5092 req->sd, req->hdr.op, req->process_id, req->pid_name); break;
5093 }
5094 }
5095 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
5096 if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf);
5097
5098 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
5099 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
5100 if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf && req->hdr.op != getpid_request)
5101 {
5102 const mStatus err_netorder = dnssd_htonl(err);
5103 send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder));
5104 if (req->errsd != req->sd)
5105 {
5106 LogOperation("%3d: Result code socket %d closed %08X %08X (%d)",
5107 req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err);
5108 dnssd_close(req->errsd);
5109 req->errsd = req->sd;
5110 // Also need to reset the parent's errsd, if this is a subordinate operation
5111 if (req->primary) req->primary->errsd = req->primary->sd;
5112 }
5113 }
5114
5115 // Reset ready to accept the next req on this pipe
5116 if (req->primary) req = req->primary;
5117 req->ts = t_morecoming;
5118 req->hdr_bytes = 0;
5119 req->data_bytes = 0;
5120 req->msgbuf = mDNSNULL;
5121 req->msgptr = mDNSNULL;
5122 req->msgend = 0;
5123 }
5124 }
5125
5126 mDNSlocal void connect_callback(int fd, short filter, void *info)
5127 {
5128 dnssd_sockaddr_t cliaddr;
5129 dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr);
5130 dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len);
5131 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
5132 unsigned long optval = 1;
5133 #endif
5134
5135 (void)filter; // Unused
5136 (void)info; // Unused
5137
5138 if (!dnssd_SocketValid(sd))
5139 {
5140 if (dnssd_errno != dnssd_EWOULDBLOCK)
5141 my_throttled_perror("ERROR: accept");
5142 return;
5143 }
5144
5145 #ifdef SO_NOSIGPIPE
5146 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
5147 if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0)
5148 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno));
5149 #endif
5150
5151 #if defined(_WIN32)
5152 if (ioctlsocket(sd, FIONBIO, &optval) != 0)
5153 #else
5154 if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0)
5155 #endif
5156 {
5157 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
5158 dnssd_close(sd);
5159 return;
5160 }
5161 else
5162 {
5163 request_state *request = NewRequest();
5164 request->ts = t_morecoming;
5165 request->sd = sd;
5166 request->errsd = sd;
5167 set_peer_pid(request);
5168 #if APPLE_OSX_mDNSResponder
5169 struct xucred x;
5170 socklen_t xucredlen = sizeof(x);
5171 if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION)
5172 request->uid = x.cr_uid; // save the effective userid of the client
5173 else
5174 my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
5175
5176 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups);
5177 #endif // APPLE_OSX_mDNSResponder
5178 LogOperation("%3d: connect_callback: Adding FD for uid %u", request->sd, request->uid);
5179 udsSupportAddFDToEventLoop(sd, request_callback, request, &request->platform_data);
5180 }
5181 }
5182
5183 mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt)
5184 {
5185 #if defined(SO_NP_EXTENSIONS)
5186 struct so_np_extensions sonpx;
5187 socklen_t optlen = sizeof(struct so_np_extensions);
5188 sonpx.npx_flags = SONPX_SETOPTSHUT;
5189 sonpx.npx_mask = SONPX_SETOPTSHUT;
5190 if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0)
5191 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
5192 #endif
5193 #if defined(_WIN32)
5194 // SEH: do we even need to do this on windows?
5195 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
5196 u_long opt = 1;
5197 if (ioctlsocket(skt, FIONBIO, &opt) != 0)
5198 #else
5199 if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0)
5200 #endif
5201 {
5202 my_perror("ERROR: could not set listen socket to non-blocking mode");
5203 return mDNSfalse;
5204 }
5205
5206 if (listen(skt, LISTENQ) != 0)
5207 {
5208 my_perror("ERROR: could not listen on listen socket");
5209 return mDNSfalse;
5210 }
5211
5212 if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL, (void **) NULL))
5213 {
5214 my_perror("ERROR: could not add listen socket to event loop");
5215 return mDNSfalse;
5216 }
5217 else
5218 {
5219 LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt);
5220 mDNSStorage.uds_listener_skt = skt;
5221 }
5222 return mDNStrue;
5223 }
5224
5225 mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count)
5226 {
5227 dnssd_sockaddr_t laddr;
5228 int ret;
5229 mDNSu32 i = 0;
5230
5231 LogInfo("udsserver_init: %d %d", _DNS_SD_H, mDNSStorage.mDNS_plat);
5232
5233 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
5234 if (PID_FILE[0])
5235 {
5236 FILE *fp = fopen(PID_FILE, "w");
5237 if (fp != NULL)
5238 {
5239 fprintf(fp, "%d\n", getpid());
5240 fclose(fp);
5241 }
5242 }
5243
5244 if (skts)
5245 {
5246 for (i = 0; i < count; i++)
5247 if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i]))
5248 goto error;
5249 }
5250 else
5251 {
5252 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0);
5253 if (!dnssd_SocketValid(listenfd))
5254 {
5255 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
5256 goto error;
5257 }
5258
5259 mDNSPlatformMemZero(&laddr, sizeof(laddr));
5260
5261 #if defined(USE_TCP_LOOPBACK)
5262 {
5263 laddr.sin_family = AF_INET;
5264 laddr.sin_port = htons(MDNS_TCP_SERVERPORT);
5265 laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR);
5266 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5267 if (ret < 0)
5268 {
5269 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5270 goto error;
5271 }
5272 }
5273 #else
5274 {
5275 mode_t mask = umask(0);
5276 unlink(boundPath); // OK if this fails
5277 laddr.sun_family = AF_LOCAL;
5278 #ifndef NOT_HAVE_SA_LEN
5279 // According to Stevens (section 3.2), there is no portable way to
5280 // determine whether sa_len is defined on a particular platform.
5281 laddr.sun_len = sizeof(struct sockaddr_un);
5282 #endif
5283 if (strlen(boundPath) >= sizeof(laddr.sun_path))
5284 {
5285 LogMsg("ERROR: MDNS_UDS_SERVERPATH must be < %d characters", (int)sizeof(laddr.sun_path));
5286 goto error;
5287 }
5288 mDNSPlatformStrLCopy(laddr.sun_path, boundPath, sizeof(laddr.sun_path));
5289 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr));
5290 umask(mask);
5291 if (ret < 0)
5292 {
5293 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
5294 goto error;
5295 }
5296 }
5297 #endif
5298
5299 if (!uds_socket_setup(listenfd)) goto error;
5300 }
5301
5302 #if !defined(PLATFORM_NO_RLIMIT)
5303 {
5304 // Set maximum number of open file descriptors
5305 #define MIN_OPENFILES 10240
5306 struct rlimit maxfds, newfds;
5307
5308 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
5309 // you have to get and set rlimits once before getrlimit will return sensible values
5310 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5311 if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5312
5313 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5314 newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES;
5315 newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES;
5316 if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur)
5317 if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
5318
5319 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
5320 debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max);
5321 debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur);
5322 }
5323 #endif
5324
5325 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
5326 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, its "FoundDomain" routine
5327 // creates a "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
5328 mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic,
5329 mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL);
5330
5331 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
5332 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration);
5333 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse);
5334 AddAutoBrowseDomain(0, &localdomain);
5335
5336 udsserver_handle_configchange(&mDNSStorage);
5337 return 0;
5338
5339 error:
5340
5341 my_perror("ERROR: udsserver_init");
5342 return -1;
5343 }
5344
5345 mDNSexport int udsserver_exit(void)
5346 {
5347 // Cancel all outstanding client requests
5348 while (all_requests) AbortUnlinkAndFree(all_requests);
5349
5350 // Clean up any special mDNSInterface_LocalOnly records we created, both the entries for "local" we
5351 // created in udsserver_init, and others we created as a result of reading local configuration data
5352 while (LocalDomainEnumRecords)
5353 {
5354 ARListElem *rem = LocalDomainEnumRecords;
5355 LocalDomainEnumRecords = LocalDomainEnumRecords->next;
5356 mDNS_Deregister(&mDNSStorage, &rem->ar);
5357 }
5358
5359 // If the launching environment created no listening socket,
5360 // that means we created it ourselves, so we should clean it up on exit
5361 if (dnssd_SocketValid(listenfd))
5362 {
5363 dnssd_close(listenfd);
5364 #if !defined(USE_TCP_LOOPBACK)
5365 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
5366 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
5367 // It would be nice if we could find a solution to this problem
5368 if (unlink(boundPath))
5369 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH);
5370 #endif
5371 }
5372
5373 if (PID_FILE[0]) unlink(PID_FILE);
5374
5375 return 0;
5376 }
5377
5378 mDNSlocal void LogClientInfo(mDNS *const m, request_state *req)
5379 {
5380 char prefix[16];
5381 if (req->primary)
5382 mDNS_snprintf(prefix, sizeof(prefix), " -> ");
5383 else
5384 mDNS_snprintf(prefix, sizeof(prefix), "%3d:", req->sd);
5385
5386 if (!req->terminate)
5387 LogMsgNoIdent("%s No operation yet on this socket", prefix);
5388 else if (req->terminate == connection_termination)
5389 {
5390 int num_records = 0, num_ops = 0;
5391 const registered_record_entry *p;
5392 request_state *r;
5393 for (p = req->u.reg_recs; p; p=p->next) num_records++;
5394 for (r = req->next; r; r=r->next) if (r->primary == req) num_ops++;
5395 LogMsgNoIdent("%s DNSServiceCreateConnection: %d registered record%s, %d kDNSServiceFlagsShareConnection operation%s PID[%d](%s)",
5396 prefix, num_records, num_records != 1 ? "s" : "", num_ops, num_ops != 1 ? "s" : "",
5397 req->process_id, req->pid_name);
5398 for (p = req->u.reg_recs; p; p=p->next)
5399 LogMsgNoIdent(" -> DNSServiceRegisterRecord 0x%08X %2d %3d %s PID[%d](%s)",
5400 req->flags, req->interfaceIndex, p->key, ARDisplayString(m, p->rr), req->process_id, req->pid_name);
5401 for (r = req->next; r; r=r->next) if (r->primary == req) LogClientInfo(m, r);
5402 }
5403 else if (req->terminate == regservice_termination_callback)
5404 {
5405 service_instance *ptr;
5406 char anonstr[256];
5407 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5408 LogMsgNoIdent("%s DNSServiceRegister 0x%08X %2d %##s%s %u/%u PID[%d](%s)",
5409 (ptr == req->u.servicereg.instances) ? prefix : " ", req->flags, req->interfaceIndex, ptr->srs.RR_SRV.resrec.name->c,
5410 AnonDataToString(ptr->srs.AnonData, 0, anonstr, sizeof(anonstr)), mDNSVal16(req->u.servicereg.port),
5411 SRS_PORT(&ptr->srs), req->process_id, req->pid_name);
5412 }
5413 else if (req->terminate == browse_termination_callback)
5414 {
5415 browser_t *blist;
5416 char anonstr[256];
5417 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5418 LogMsgNoIdent("%s DNSServiceBrowse 0x%08X %2d %##s%s PID[%d](%s)",
5419 (blist == req->u.browser.browsers) ? prefix : " ", req->flags, req->interfaceIndex, blist->q.qname.c,
5420 AnonDataToString(req->u.browser.AnonData, 0, anonstr, sizeof(anonstr)), req->process_id, req->pid_name);
5421 }
5422 else if (req->terminate == resolve_termination_callback)
5423 LogMsgNoIdent("%s DNSServiceResolve 0x%08X %2d %##s PID[%d](%s)",
5424 prefix, req->flags, req->interfaceIndex, req->u.resolve.qsrv.qname.c, req->process_id, req->pid_name);
5425 else if (req->terminate == queryrecord_termination_callback)
5426 LogMsgNoIdent("%s DNSServiceQueryRecord 0x%08X %2d %##s (%s) PID[%d](%s)",
5427 prefix, req->flags, req->interfaceIndex, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype), req->process_id, req->pid_name);
5428 else if (req->terminate == enum_termination_callback)
5429 LogMsgNoIdent("%s DNSServiceEnumerateDomains 0x%08X %2d %##s PID[%d](%s)",
5430 prefix, req->flags, req->interfaceIndex, req->u.enumeration.q_all.qname.c, req->process_id, req->pid_name);
5431 else if (req->terminate == port_mapping_termination_callback)
5432 LogMsgNoIdent("%s DNSServiceNATPortMapping 0x%08X %2d %s%s Int %5d Req %5d Ext %.4a:%5d Req TTL %5d Granted TTL %5d PID[%d](%s)",
5433 prefix,
5434 req->flags,
5435 req->interfaceIndex,
5436 req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : " ",
5437 req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : " ",
5438 mDNSVal16(req->u.pm.NATinfo.IntPort),
5439 mDNSVal16(req->u.pm.ReqExt),
5440 &req->u.pm.NATinfo.ExternalAddress,
5441 mDNSVal16(req->u.pm.NATinfo.ExternalPort),
5442 req->u.pm.NATinfo.NATLease,
5443 req->u.pm.NATinfo.Lifetime,
5444 req->process_id, req->pid_name);
5445 else if (req->terminate == addrinfo_termination_callback)
5446 LogMsgNoIdent("%s DNSServiceGetAddrInfo 0x%08X %2d %s%s %##s PID[%d](%s)",
5447 prefix, req->flags, req->interfaceIndex,
5448 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5449 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5450 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name);
5451 else
5452 LogMsgNoIdent("%s Unrecognized operation %p", prefix, req->terminate);
5453 }
5454
5455 mDNSlocal void GetMcastClients(request_state *req)
5456 {
5457 if (req->terminate == connection_termination)
5458 {
5459 int num_records = 0, num_ops = 0;
5460 const registered_record_entry *p;
5461 request_state *r;
5462 for (p = req->u.reg_recs; p; p=p->next)
5463 num_records++;
5464 for (r = req->next; r; r=r->next)
5465 if (r->primary == req)
5466 num_ops++;
5467 for (p = req->u.reg_recs; p; p=p->next)
5468 {
5469 if (!AuthRecord_uDNS(p->rr))
5470 n_mrecords++;
5471 }
5472 for (r = req->next; r; r=r->next)
5473 if (r->primary == req)
5474 GetMcastClients(r);
5475 }
5476 else if (req->terminate == regservice_termination_callback)
5477 {
5478 service_instance *ptr;
5479 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5480 {
5481 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5482 n_mrecords++;
5483 }
5484 }
5485 else if (req->terminate == browse_termination_callback)
5486 {
5487 browser_t *blist;
5488 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5489 {
5490 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5491 n_mquests++;
5492 }
5493 }
5494 else if (req->terminate == resolve_termination_callback)
5495 {
5496 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5497 n_mquests++;
5498 }
5499 else if (req->terminate == queryrecord_termination_callback)
5500 {
5501 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5502 n_mquests++;
5503 }
5504 else if (req->terminate == addrinfo_termination_callback)
5505 {
5506 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5507 n_mquests++;
5508 }
5509 else
5510 {
5511 return;
5512 }
5513 }
5514
5515
5516 mDNSlocal void LogMcastClientInfo(request_state *req)
5517 {
5518 if (!req->terminate)
5519 LogMcastNoIdent("No operation yet on this socket");
5520 else if (req->terminate == connection_termination)
5521 {
5522 int num_records = 0, num_ops = 0;
5523 const registered_record_entry *p;
5524 request_state *r;
5525 for (p = req->u.reg_recs; p; p=p->next)
5526 num_records++;
5527 for (r = req->next; r; r=r->next)
5528 if (r->primary == req)
5529 num_ops++;
5530 for (p = req->u.reg_recs; p; p=p->next)
5531 {
5532 if (!AuthRecord_uDNS(p->rr))
5533 LogMcastNoIdent("R: -> DNSServiceRegisterRecord: %##s %s PID[%d](%s)", p->rr->resrec.name->c,
5534 DNSTypeName(p->rr->resrec.rrtype), req->process_id, req->pid_name, i_mcount++);
5535 }
5536 for (r = req->next; r; r=r->next)
5537 if (r->primary == req)
5538 LogMcastClientInfo(r);
5539 }
5540 else if (req->terminate == regservice_termination_callback)
5541 {
5542 service_instance *ptr;
5543 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next)
5544 {
5545 if (!AuthRecord_uDNS(&ptr->srs.RR_SRV))
5546 LogMcastNoIdent("R: DNSServiceRegister: %##s %u/%u PID[%d](%s)", ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port),
5547 SRS_PORT(&ptr->srs), req->process_id, req->pid_name, i_mcount++);
5548 }
5549 }
5550 else if (req->terminate == browse_termination_callback)
5551 {
5552 browser_t *blist;
5553 for (blist = req->u.browser.browsers; blist; blist = blist->next)
5554 {
5555 if (mDNSOpaque16IsZero(blist->q.TargetQID))
5556 LogMcastNoIdent("Q: DNSServiceBrowse %##s %s PID[%d](%s)", blist->q.qname.c, DNSTypeName(blist->q.qtype),
5557 req->process_id, req->pid_name, i_mcount++);
5558 }
5559 }
5560 else if (req->terminate == resolve_termination_callback)
5561 {
5562 if ((mDNSOpaque16IsZero(req->u.resolve.qsrv.TargetQID)) && (req->u.resolve.qsrv.ThisQInterval > 0))
5563 LogMcastNoIdent("Q: DNSServiceResolve %##s %s PID[%d](%s)", req->u.resolve.qsrv.qname.c, DNSTypeName(req->u.resolve.qsrv.qtype),
5564 req->process_id, req->pid_name, i_mcount++);
5565 }
5566 else if (req->terminate == queryrecord_termination_callback)
5567 {
5568 if ((mDNSOpaque16IsZero(req->u.queryrecord.q.TargetQID)) && (req->u.queryrecord.q.ThisQInterval > 0))
5569 LogMcastNoIdent("Q: DNSServiceQueryRecord %##s %s PID[%d](%s)", req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype),
5570 req->process_id, req->pid_name, i_mcount++);
5571 }
5572 else if (req->terminate == addrinfo_termination_callback)
5573 {
5574 if ((mDNSOpaque16IsZero(req->u.addrinfo.q4.TargetQID)) && (req->u.addrinfo.q4.ThisQInterval > 0))
5575 LogMcastNoIdent("Q: DNSServiceGetAddrInfo %s%s %##s PID[%d](%s)",
5576 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ",
5577 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ",
5578 req->u.addrinfo.q4.qname.c, req->process_id, req->pid_name, i_mcount++);
5579 }
5580 else
5581 {
5582 return;
5583 }
5584
5585 }
5586
5587 mDNSlocal char *RecordTypeName(mDNSu8 rtype)
5588 {
5589 switch (rtype)
5590 {
5591 case kDNSRecordTypeUnregistered: return ("Unregistered ");
5592 case kDNSRecordTypeDeregistering: return ("Deregistering");
5593 case kDNSRecordTypeUnique: return ("Unique ");
5594 case kDNSRecordTypeAdvisory: return ("Advisory ");
5595 case kDNSRecordTypeShared: return ("Shared ");
5596 case kDNSRecordTypeVerified: return ("Verified ");
5597 case kDNSRecordTypeKnownUnique: return ("KnownUnique ");
5598 default: return("Unknown");
5599 }
5600 }
5601
5602 mDNSlocal void LogEtcHosts(mDNS *const m)
5603 {
5604 mDNSBool showheader = mDNStrue;
5605 const AuthRecord *ar;
5606 mDNSu32 slot;
5607 AuthGroup *ag;
5608 int count = 0;
5609 int authslot = 0;
5610 mDNSBool truncated = 0;
5611
5612 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5613 {
5614 if (m->rrauth.rrauth_hash[slot]) authslot++;
5615 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5616 for (ar = ag->members; ar; ar = ar->next)
5617 {
5618 if (ar->RecordCallback != FreeEtcHosts) continue;
5619 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5620
5621 // Print a maximum of 50 records
5622 if (count++ >= 50) { truncated = mDNStrue; continue; }
5623 if (ar->ARType == AuthRecordLocalOnly)
5624 {
5625 if (ar->resrec.InterfaceID == mDNSInterface_LocalOnly)
5626 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5627 else
5628 {
5629 mDNSu32 scopeid = (mDNSu32)(uintptr_t)ar->resrec.InterfaceID;
5630 LogMsgNoIdent(" %s %u %s", RecordTypeName(ar->resrec.RecordType), scopeid, ARDisplayString(m, ar));
5631 }
5632 }
5633 }
5634 }
5635
5636 if (showheader) LogMsgNoIdent("<None>");
5637 else if (truncated) LogMsgNoIdent("<Truncated: to 50 records, Total records %d, Total Auth Groups %d, Auth Slots %d>", count, m->rrauth.rrauth_totalused, authslot);
5638 }
5639
5640 mDNSlocal void LogLocalOnlyAuthRecords(mDNS *const m)
5641 {
5642 mDNSBool showheader = mDNStrue;
5643 const AuthRecord *ar;
5644 mDNSu32 slot;
5645 AuthGroup *ag;
5646
5647 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5648 {
5649 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5650 for (ar = ag->members; ar; ar = ar->next)
5651 {
5652 if (ar->RecordCallback == FreeEtcHosts) continue;
5653 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" State Interface"); }
5654
5655 // Print a maximum of 400 records
5656 if (ar->ARType == AuthRecordLocalOnly)
5657 LogMsgNoIdent(" %s LO %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5658 else if (ar->ARType == AuthRecordP2P)
5659 {
5660 if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5661 LogMsgNoIdent(" %s BLE %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5662 else
5663 LogMsgNoIdent(" %s PP %s", RecordTypeName(ar->resrec.RecordType), ARDisplayString(m, ar));
5664 }
5665 }
5666 }
5667
5668 if (showheader) LogMsgNoIdent("<None>");
5669 }
5670
5671 mDNSlocal char *AnonInfoToString(AnonymousInfo *ai, char *anonstr, int anstrlen)
5672 {
5673 anonstr[0] = 0;
5674 if (ai && ai->AnonData)
5675 {
5676 return (AnonDataToString(ai->AnonData, ai->AnonDataLen, anonstr, anstrlen));
5677 }
5678 return anonstr;
5679 }
5680
5681 mDNSlocal void LogOneAuthRecord(mDNS *const m, const AuthRecord *ar, mDNSs32 now, const char *const ifname)
5682 {
5683 char anstr[256];
5684 if (AuthRecord_uDNS(ar))
5685 {
5686 LogMsgNoIdent("%7d %7d %7d %-7s %4d %s %s",
5687 ar->ThisAPInterval / mDNSPlatformOneSecond,
5688 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
5689 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
5690 "-U-",
5691 ar->state,
5692 ar->AllowRemoteQuery ? "☠" : " ",
5693 ARDisplayString(m, ar));
5694 }
5695 else
5696 {
5697 LogMsgNoIdent("%7d %7d %7d %-7s 0x%02X %s %s%s",
5698 ar->ThisAPInterval / mDNSPlatformOneSecond,
5699 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5700 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5701 ifname ? ifname : "ALL",
5702 ar->resrec.RecordType,
5703 ar->AllowRemoteQuery ? "☠" : " ",
5704 ARDisplayString(m, ar), AnonInfoToString(ar->resrec.AnonInfo, anstr, sizeof(anstr)));
5705 }
5706 }
5707
5708 mDNSlocal void LogAuthRecords(mDNS *const m, const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy)
5709 {
5710 mDNSBool showheader = mDNStrue;
5711 const AuthRecord *ar;
5712 OwnerOptData owner = zeroOwner;
5713 for (ar = ResourceRecords; ar; ar=ar->next)
5714 {
5715 const char *const ifname = InterfaceNameForID(m, ar->resrec.InterfaceID);
5716 if ((ar->WakeUp.HMAC.l[0] != 0) == (proxy != mDNSNULL))
5717 {
5718 if (showheader) { showheader = mDNSfalse; LogMsgNoIdent(" Int Next Expire if State"); }
5719 if (proxy) (*proxy)++;
5720 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)))
5721 {
5722 owner = ar->WakeUp;
5723 if (owner.password.l[0])
5724 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
5725 else if (!mDNSSameEthAddress(&owner.HMAC, &owner.IMAC))
5726 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &owner.HMAC, &owner.IMAC, owner.seq);
5727 else
5728 LogMsgNoIdent("Proxying for %.6a seq %d", &owner.HMAC, owner.seq);
5729 }
5730 if (AuthRecord_uDNS(ar))
5731 {
5732 LogOneAuthRecord(m, ar, now, ifname);
5733 }
5734 else if (ar->ARType == AuthRecordLocalOnly)
5735 {
5736 LogMsgNoIdent(" LO %s", ARDisplayString(m, ar));
5737 }
5738 else if (ar->ARType == AuthRecordP2P)
5739 {
5740 if (ar->resrec.InterfaceID == mDNSInterface_BLE)
5741 LogMsgNoIdent(" BLE %s", ARDisplayString(m, ar));
5742 else
5743 LogMsgNoIdent(" PP %s", ARDisplayString(m, ar));
5744 }
5745 else
5746 {
5747 LogOneAuthRecord(m, ar, now, ifname);
5748 if (ar->resrec.AnonInfo)
5749 {
5750 ResourceRecord *nsec3 = ar->resrec.AnonInfo->nsec3RR;
5751 // We just print the values from the AuthRecord to keep it nicely aligned though
5752 // all we want here is the nsec3 information.
5753 LogMsgNoIdent("%7d %7d %7d %7s %s",
5754 ar->ThisAPInterval / mDNSPlatformOneSecond,
5755 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0,
5756 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0,
5757 ifname ? ifname : "ALL",
5758 RRDisplayString(m, nsec3));
5759 }
5760 }
5761 }
5762 }
5763 if (showheader) LogMsgNoIdent("<None>");
5764 }
5765
5766 mDNSlocal void PrintOneCacheRecord(mDNS *const m, const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5767 {
5768 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5769 slot,
5770 cr->CRActiveQuestion ? "*" : " ",
5771 remain,
5772 ifname ? ifname : "-U-",
5773 (cr->resrec.RecordType == kDNSRecordTypePacketNegative) ? "-" :
5774 (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5775 DNSTypeName(cr->resrec.rrtype),
5776 CRDisplayString(m, cr));
5777 (*CacheUsed)++;
5778 }
5779
5780 mDNSlocal void PrintCachedRecords(mDNS *const m, const CacheRecord *cr, mDNSu32 slot, const mDNSu32 remain, const char *ifname, mDNSu32 *CacheUsed)
5781 {
5782 CacheRecord *nsec;
5783 CacheRecord *soa;
5784 nsec = cr->nsec;
5785
5786 // The records that are cached under the main cache record like nsec, soa don't have
5787 // their own lifetime. If the main cache record expires, they also expire.
5788 while (nsec)
5789 {
5790 PrintOneCacheRecord(m, nsec, slot, remain, ifname, CacheUsed);
5791 nsec = nsec->next;
5792 }
5793 soa = cr->soa;
5794 if (soa)
5795 {
5796 PrintOneCacheRecord(m, soa, slot, remain, ifname, CacheUsed);
5797 }
5798 if (cr->resrec.AnonInfo)
5799 {
5800 ResourceRecord *nsec3 = cr->resrec.AnonInfo->nsec3RR;
5801 // Even though it is a resource record, we print the sameway
5802 // as a cache record so that it aligns properly.
5803 if (nsec3)
5804 {
5805 LogMsgNoIdent("%3d %s%8d %-7s%s %-6s%s",
5806 slot,
5807 " ",
5808 remain,
5809 ifname ? ifname : "-U-",
5810 (nsec3->RecordType == kDNSRecordTypePacketNegative) ? "-" :
5811 (nsec3->RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+",
5812 DNSTypeName(nsec3->rrtype),
5813 RRDisplayString(m, nsec3));
5814 }
5815 }
5816 }
5817
5818 mDNSlocal char *AnonDataToString(const mDNSu8 *ad, int adlen, char *adstr, int adstrlen)
5819 {
5820 adstr[0] = 0;
5821 if (ad)
5822 {
5823 int len;
5824 char *orig = adstr;
5825
5826 // If the caller is lazy to compute the length, we do it for them.
5827 if (!adlen)
5828 len = strlen((const char *)ad);
5829 else
5830 len = adlen;
5831
5832 // Print the anondata within brackets. Hence, we need space for two
5833 // brackets and a NULL byte.
5834 if (len > (adstrlen - 3))
5835 len = adstrlen - 3;
5836
5837 *adstr++ = '(';
5838 mDNSPlatformMemCopy(adstr, ad, len);
5839 adstr[len] = ')';
5840 adstr[len+1] = 0;
5841 return orig;
5842 }
5843 return adstr;
5844 }
5845
5846 mDNSexport void LogMDNSStatistics(mDNS *const m)
5847 {
5848 LogMsgNoIdent("--- MDNS Statistics ---");
5849
5850 LogMsgNoIdent("Name Conflicts %u", m->mDNSStats.NameConflicts);
5851 LogMsgNoIdent("KnownUnique Name Conflicts %u", m->mDNSStats.KnownUniqueNameConflicts);
5852 LogMsgNoIdent("Duplicate Query Suppressions %u", m->mDNSStats.DupQuerySuppressions);
5853 LogMsgNoIdent("KA Suppressions %u", m->mDNSStats.KnownAnswerSuppressions);
5854 LogMsgNoIdent("KA Multiple Packets %u", m->mDNSStats.KnownAnswerMultiplePkts);
5855 LogMsgNoIdent("Poof Cache Deletions %u", m->mDNSStats.PoofCacheDeletions);
5856 LogMsgNoIdent("--------------------------------");
5857
5858 LogMsgNoIdent("Multicast packets Sent %u", m->MulticastPacketsSent);
5859 LogMsgNoIdent("Multicast packets Received %u", m->MPktNum);
5860 LogMsgNoIdent("Remote Subnet packets %u", m->RemoteSubnet);
5861 LogMsgNoIdent("QU questions received %u", m->mDNSStats.UnicastBitInQueries);
5862 LogMsgNoIdent("Normal multicast questions %u", m->mDNSStats.NormalQueries);
5863 LogMsgNoIdent("Answers for questions %u", m->mDNSStats.MatchingAnswersForQueries);
5864 LogMsgNoIdent("Unicast responses %u", m->mDNSStats.UnicastResponses);
5865 LogMsgNoIdent("Multicast responses %u", m->mDNSStats.MulticastResponses);
5866 LogMsgNoIdent("Unicast response Demotions %u", m->mDNSStats.UnicastDemotedToMulticast);
5867 LogMsgNoIdent("--------------------------------");
5868
5869 LogMsgNoIdent("Sleeps %u", m->mDNSStats.Sleeps);
5870 LogMsgNoIdent("Wakeups %u", m->mDNSStats.Wakes);
5871 LogMsgNoIdent("Interface UP events %u", m->mDNSStats.InterfaceUp);
5872 LogMsgNoIdent("Interface UP Flap events %u", m->mDNSStats.InterfaceUpFlap);
5873 LogMsgNoIdent("Interface Down events %u", m->mDNSStats.InterfaceDown);
5874 LogMsgNoIdent("Interface DownFlap events %u", m->mDNSStats.InterfaceDownFlap);
5875 LogMsgNoIdent("Cache refresh queries %u", m->mDNSStats.CacheRefreshQueries);
5876 LogMsgNoIdent("Cache refreshed %u", m->mDNSStats.CacheRefreshed);
5877 LogMsgNoIdent("Wakeup on Resolves %u", m->mDNSStats.WakeOnResolves);
5878 }
5879
5880 mDNSexport void udsserver_info(mDNS *const m)
5881 {
5882 const mDNSs32 now = mDNS_TimeNow(m);
5883 mDNSu32 CacheUsed = 0, CacheActive = 0, slot;
5884 int ProxyA = 0, ProxyD = 0;
5885 const CacheGroup *cg;
5886 const CacheRecord *cr;
5887 const DNSQuestion *q;
5888 const DNameListElem *d;
5889 const SearchListElem *s;
5890
5891 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
5892
5893 LogMsgNoIdent("------------ Cache -------------");
5894 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
5895 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5896 {
5897 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
5898 {
5899 CacheUsed++; // Count one cache entity for the CacheGroup object
5900 for (cr = cg->members; cr; cr=cr->next)
5901 {
5902 const mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond;
5903 const char *ifname;
5904 mDNSInterfaceID InterfaceID = cr->resrec.InterfaceID;
5905 if (!InterfaceID && cr->resrec.rDNSServer && cr->resrec.rDNSServer->scoped)
5906 InterfaceID = cr->resrec.rDNSServer->interface;
5907 ifname = InterfaceNameForID(m, InterfaceID);
5908 if (cr->CRActiveQuestion) CacheActive++;
5909 PrintOneCacheRecord(m, cr, slot, remain, ifname, &CacheUsed);
5910 PrintCachedRecords(m, cr, slot, remain, ifname, &CacheUsed);
5911 }
5912 }
5913 }
5914
5915 if (m->rrcache_totalused != CacheUsed)
5916 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed);
5917 if (m->rrcache_active != CacheActive)
5918 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive);
5919 LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed, CacheActive);
5920
5921 LogMsgNoIdent("--------- Auth Records ---------");
5922 LogAuthRecords(m, now, m->ResourceRecords, mDNSNULL);
5923
5924 LogMsgNoIdent("--------- LocalOnly, P2P Auth Records ---------");
5925 LogLocalOnlyAuthRecords(m);
5926
5927 LogMsgNoIdent("--------- /etc/hosts ---------");
5928 LogEtcHosts(m);
5929
5930 LogMsgNoIdent("------ Duplicate Records -------");
5931 LogAuthRecords(m, now, m->DuplicateRecords, mDNSNULL);
5932
5933 LogMsgNoIdent("----- Auth Records Proxied -----");
5934 LogAuthRecords(m, now, m->ResourceRecords, &ProxyA);
5935
5936 LogMsgNoIdent("-- Duplicate Records Proxied ---");
5937 LogAuthRecords(m, now, m->DuplicateRecords, &ProxyD);
5938
5939 LogMsgNoIdent("---------- Questions -----------");
5940 if (!m->Questions) LogMsgNoIdent("<None>");
5941 else
5942 {
5943 char anonstr[256];
5944 CacheUsed = 0;
5945 CacheActive = 0;
5946 LogMsgNoIdent(" Int Next if T NumAns VDNS Qptr DupOf SU SQ Type Name");
5947 for (q = m->Questions; q; q=q->next)
5948 {
5949 mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond;
5950 mDNSs32 n = (NextQSendTime(q) - now) / mDNSPlatformOneSecond;
5951 char *ifname = InterfaceNameForID(m, q->InterfaceID);
5952 CacheUsed++;
5953 if (q->ThisQInterval) CacheActive++;
5954 LogMsgNoIdent("%6d%6d %-7s%s%s %5d 0x%x%x 0x%p 0x%p %1d %2d %-5s%##s%s%s",
5955 i, n,
5956 ifname ? ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-",
5957 mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"),
5958 PrivateQuery(q) ? "P" : q->ValidationRequired ? "V" : q->ValidatingResponse ? "R" : " ",
5959 q->CurrentAnswers, q->validDNSServers.l[1], q->validDNSServers.l[0], q, q->DuplicateOf,
5960 q->SuppressUnusable, q->SuppressQuery, DNSTypeName(q->qtype), q->qname.c,
5961 AnonInfoToString(q->AnonInfo, anonstr, sizeof(anonstr)),
5962 q->DuplicateOf ? " (dup)" : "");
5963 }
5964 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive);
5965 }
5966
5967 LogMsgNoIdent("----- LocalOnly, P2P Questions -----");
5968 if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>");
5969 else for (q = m->LocalOnlyQuestions; q; q=q->next)
5970 LogMsgNoIdent(" %3s %5d %-6s%##s%s",
5971 q->InterfaceID == mDNSInterface_LocalOnly ? "LO ": q->InterfaceID == mDNSInterface_BLE ? "BLE": "P2P",
5972 q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : "");
5973
5974 LogMsgNoIdent("---- Active UDS Client Requests ----");
5975 if (!all_requests) LogMsgNoIdent("<None>");
5976 else
5977 {
5978 request_state *req, *r;
5979 for (req = all_requests; req; req=req->next)
5980 {
5981 if (req->primary) // If this is a subbordinate operation, check that the parent is in the list
5982 {
5983 for (r = all_requests; r && r != req; r=r->next) if (r == req->primary) goto foundparent;
5984 LogMsgNoIdent("%3d: Orhpan operation %p; parent %p not found in request list", req->sd);
5985 }
5986 // For non-subbordinate operations, and subbordinate operations that have lost their parent, write out their info
5987 LogClientInfo(m, req);
5988 foundparent:;
5989 }
5990 }
5991
5992 LogMsgNoIdent("-------- NAT Traversals --------");
5993 LogMsgNoIdent("ExtAddress %.4a Retry %d Interval %d",
5994 &m->ExtAddress,
5995 m->retryGetAddr ? (m->retryGetAddr - now) / mDNSPlatformOneSecond : 0,
5996 m->retryIntervalGetAddr / mDNSPlatformOneSecond);
5997 if (m->NATTraversals)
5998 {
5999 const NATTraversalInfo *nat;
6000 for (nat = m->NATTraversals; nat; nat=nat->next)
6001 {
6002 LogMsgNoIdent("%p %s Int %5d %s Err %d Retry %5d Interval %5d Expire %5d Req %.4a:%d Ext %.4a:%d",
6003 nat,
6004 nat->Protocol ? (nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP") : "ADD",
6005 mDNSVal16(nat->IntPort),
6006 (nat->lastSuccessfulProtocol == NATTProtocolNone ? "None " :
6007 nat->lastSuccessfulProtocol == NATTProtocolNATPMP ? "NAT-PMP " :
6008 nat->lastSuccessfulProtocol == NATTProtocolUPNPIGD ? "UPnP/IGD" :
6009 nat->lastSuccessfulProtocol == NATTProtocolPCP ? "PCP " :
6010 /* else */ "Unknown " ),
6011 nat->Result,
6012 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
6013 nat->retryInterval / mDNSPlatformOneSecond,
6014 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
6015 &nat->NewAddress, mDNSVal16(nat->RequestedPort),
6016 &nat->ExternalAddress, mDNSVal16(nat->ExternalPort));
6017 }
6018 }
6019
6020 LogMsgNoIdent("--------- AuthInfoList ---------");
6021 if (!m->AuthInfoList) LogMsgNoIdent("<None>");
6022 else
6023 {
6024 const DomainAuthInfo *a;
6025 for (a = m->AuthInfoList; a; a = a->next)
6026 {
6027 LogMsgNoIdent("%##s %##s %##s %d %d %.16a%s",
6028 a->domain.c, a->keyname.c,
6029 a->hostname.c, (a->port.b[0] << 8 | a->port.b[1]),
6030 (a->deltime ? (a->deltime - now) : 0),
6031 &a->AutoTunnelInnerAddress, a->AutoTunnel ? " AutoTunnel" : "");
6032 }
6033 }
6034
6035 #if APPLE_OSX_mDNSResponder
6036 LogMsgNoIdent("--------- TunnelClients --------");
6037 if (!m->TunnelClients) LogMsgNoIdent("<None>");
6038 else
6039 {
6040 const ClientTunnel *c;
6041 for (c = m->TunnelClients; c; c = c->next)
6042 LogMsgNoIdent("%##s local %.16a %.4a %.16a remote %.16a %.4a %5d %.16a interval %d",
6043 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);
6044 }
6045 #endif // APPLE_OSX_mDNSResponder
6046
6047 LogMsgNoIdent("---------- Misc State ----------");
6048
6049 LogMsgNoIdent("PrimaryMAC: %.6a", &m->PrimaryMAC);
6050
6051 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
6052 m->SleepState,
6053 m->SleepState == SleepState_Awake ? "Awake" :
6054 m->SleepState == SleepState_Transferring ? "Transferring" :
6055 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?",
6056 m->SleepSeqNum);
6057
6058 if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service");
6059 #ifndef SPC_DISABLED
6060 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c);
6061 #endif
6062 if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD);
6063 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords);
6064
6065 LogMsgNoIdent("------ Auto Browse Domains -----");
6066 if (!AutoBrowseDomains) LogMsgNoIdent("<None>");
6067 else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
6068
6069 LogMsgNoIdent("--- Auto Registration Domains --");
6070 if (!AutoRegistrationDomains) LogMsgNoIdent("<None>");
6071 else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c);
6072
6073 LogMsgNoIdent("--- Search Domains --");
6074 if (!SearchList) LogMsgNoIdent("<None>");
6075 else
6076 {
6077 for (s=SearchList; s; s=s->next)
6078 {
6079 char *ifname = InterfaceNameForID(m, s->InterfaceID);
6080 LogMsgNoIdent("%##s %s", s->domain.c, ifname ? ifname : "");
6081 }
6082 }
6083 LogInfo("--- Trust Anchors ---");
6084 if (!m->TrustAnchors)
6085 {
6086 LogInfo("<None>");
6087 }
6088 else
6089 {
6090 TrustAnchor *ta;
6091 mDNSu8 fromTimeBuf[64];
6092 mDNSu8 untilTimeBuf[64];
6093
6094 for (ta=m->TrustAnchors; ta; ta=ta->next)
6095 {
6096 mDNSPlatformFormatTime((unsigned long)ta->validFrom, fromTimeBuf, sizeof(fromTimeBuf));
6097 mDNSPlatformFormatTime((unsigned long)ta->validUntil, untilTimeBuf, sizeof(untilTimeBuf));
6098 LogInfo("%##s %d %d %d %d %s %s", ta->zone.c, ta->rds.keyTag,
6099 ta->rds.alg, ta->rds.digestType, ta->digestLen, fromTimeBuf, untilTimeBuf);
6100 }
6101 }
6102
6103 LogInfo("--- DNSSEC Statistics ---");
6104
6105 LogInfo("Next Stats Time %u", m->NextStatLogTime - mDNSPlatformUTC());
6106 LogMsgNoIdent("Unicast Cache size %u", m->rrcache_totalused_unicast);
6107 LogInfo("DNSSEC Cache size %u", m->DNSSECStats.TotalMemUsed);
6108 if (m->rrcache_totalused_unicast)
6109 LogInfo("DNSSEC usage percentage %u", ((unsigned long)(m->DNSSECStats.TotalMemUsed * 100))/m->rrcache_totalused_unicast);
6110 LogInfo("DNSSEC Extra Packets (0 to 2) %u", m->DNSSECStats.ExtraPackets0);
6111 LogInfo("DNSSEC Extra Packets (3 to 6) %u", m->DNSSECStats.ExtraPackets3);
6112 LogInfo("DNSSEC Extra Packets (7 to 9) %u", m->DNSSECStats.ExtraPackets7);
6113 LogInfo("DNSSEC Extra Packets ( >= 10) %u", m->DNSSECStats.ExtraPackets10);
6114
6115 LogInfo("DNSSEC Latency (0 to 4ms) %u", m->DNSSECStats.Latency0);
6116 LogInfo("DNSSEC Latency (4 to 9ms) %u", m->DNSSECStats.Latency5);
6117 LogInfo("DNSSEC Latency (10 to 19ms) %u", m->DNSSECStats.Latency10);
6118 LogInfo("DNSSEC Latency (20 to 49ms) %u", m->DNSSECStats.Latency20);
6119 LogInfo("DNSSEC Latency (50 to 99ms) %u", m->DNSSECStats.Latency50);
6120 LogInfo("DNSSEC Latency ( >=100ms) %u", m->DNSSECStats.Latency100);
6121
6122 LogInfo("DNSSEC Secure Status %u", m->DNSSECStats.SecureStatus);
6123 LogInfo("DNSSEC Insecure Status %u", m->DNSSECStats.InsecureStatus);
6124 LogInfo("DNSSEC Indeterminate Status %u", m->DNSSECStats.IndeterminateStatus);
6125 LogInfo("DNSSEC Bogus Status %u", m->DNSSECStats.BogusStatus);
6126 LogInfo("DNSSEC NoResponse Status %u", m->DNSSECStats.NoResponseStatus);
6127 LogInfo("DNSSEC Probes sent %u", m->DNSSECStats.NumProbesSent);
6128 LogInfo("DNSSEC Msg Size (<=1024) %u", m->DNSSECStats.MsgSize0);
6129 LogInfo("DNSSEC Msg Size (<=2048) %u", m->DNSSECStats.MsgSize1);
6130 LogInfo("DNSSEC Msg Size (> 2048) %u", m->DNSSECStats.MsgSize2);
6131
6132 LogMDNSStatistics(m);
6133
6134 LogMsgNoIdent("---- Task Scheduling Timers ----");
6135
6136 #if BONJOUR_ON_DEMAND
6137 LogMsgNoIdent("BonjourEnabled %d", m->BonjourEnabled);
6138 #endif // BONJOUR_ON_DEMAND
6139
6140 #if APPLE_OSX_mDNSResponder
6141 LogMsgNoIdent("EnableBLEBasedDiscovery %d", EnableBLEBasedDiscovery);
6142 #endif // APPLE_OSX_mDNSResponder
6143
6144 if (!m->NewQuestions)
6145 LogMsgNoIdent("NewQuestion <NONE>");
6146 else
6147 LogMsgNoIdent("NewQuestion DelayAnswering %d %d %##s (%s)",
6148 m->NewQuestions->DelayAnswering, m->NewQuestions->DelayAnswering-now,
6149 m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
6150
6151 if (!m->NewLocalOnlyQuestions)
6152 LogMsgNoIdent("NewLocalOnlyQuestions <NONE>");
6153 else
6154 LogMsgNoIdent("NewLocalOnlyQuestions %##s (%s)",
6155 m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
6156
6157 if (!m->NewLocalRecords)
6158 LogMsgNoIdent("NewLocalRecords <NONE>");
6159 else
6160 LogMsgNoIdent("NewLocalRecords %02X %s", m->NewLocalRecords->resrec.RecordType, ARDisplayString(m, m->NewLocalRecords));
6161
6162 LogMsgNoIdent("SPSProxyListChanged%s", m->SPSProxyListChanged ? "" : " <NONE>");
6163 LogMsgNoIdent("LocalRemoveEvents%s", m->LocalRemoveEvents ? "" : " <NONE>");
6164 LogMsgNoIdent("m->AutoTunnelRelayAddr %.16a", &m->AutoTunnelRelayAddr);
6165 LogMsgNoIdent("m->WABBrowseQueriesCount %d", m->WABBrowseQueriesCount);
6166 LogMsgNoIdent("m->WABLBrowseQueriesCount %d", m->WABLBrowseQueriesCount);
6167 LogMsgNoIdent("m->WABRegQueriesCount %d", m->WABRegQueriesCount);
6168 LogMsgNoIdent("m->AutoTargetServices %d", m->AutoTargetServices);
6169
6170 LogMsgNoIdent(" ABS (hex) ABS (dec) REL (hex) REL (dec)");
6171 LogMsgNoIdent("m->timenow %08X %11d", now, now);
6172 LogMsgNoIdent("m->timenow_adjust %08X %11d", m->timenow_adjust, m->timenow_adjust);
6173 LogTimer("m->NextScheduledEvent ", m->NextScheduledEvent);
6174
6175 #ifndef UNICAST_DISABLED
6176 LogTimer("m->NextuDNSEvent ", m->NextuDNSEvent);
6177 LogTimer("m->NextSRVUpdate ", m->NextSRVUpdate);
6178 LogTimer("m->NextScheduledNATOp ", m->NextScheduledNATOp);
6179 LogTimer("m->retryGetAddr ", m->retryGetAddr);
6180 #endif
6181
6182 LogTimer("m->NextCacheCheck ", m->NextCacheCheck);
6183 LogTimer("m->NextScheduledSPS ", m->NextScheduledSPS);
6184 LogTimer("m->NextScheduledKA ", m->NextScheduledKA);
6185
6186 #if BONJOUR_ON_DEMAND
6187 LogTimer("m->NextBonjourDisableTime ", m->NextBonjourDisableTime);
6188 #endif // BONJOUR_ON_DEMAND
6189
6190 LogTimer("m->NextScheduledSPRetry ", m->NextScheduledSPRetry);
6191 LogTimer("m->DelaySleep ", m->DelaySleep);
6192
6193 LogTimer("m->NextScheduledQuery ", m->NextScheduledQuery);
6194 LogTimer("m->NextScheduledProbe ", m->NextScheduledProbe);
6195 LogTimer("m->NextScheduledResponse", m->NextScheduledResponse);
6196
6197 LogTimer("m->SuppressSending ", m->SuppressSending);
6198 LogTimer("m->SuppressProbes ", m->SuppressProbes);
6199 LogTimer("m->ProbeFailTime ", m->ProbeFailTime);
6200 LogTimer("m->DelaySleep ", m->DelaySleep);
6201 LogTimer("m->SleepLimit ", m->SleepLimit);
6202 LogTimer("m->NextScheduledStopTime ", m->NextScheduledStopTime);
6203 }
6204
6205 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6206 mDNSexport void uds_validatelists(void)
6207 {
6208 const request_state *req, *p;
6209 for (req = all_requests; req; req=req->next)
6210 {
6211 if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2))
6212 LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd);
6213
6214 if (req->primary == req)
6215 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd);
6216
6217 if (req->primary && req->replies)
6218 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
6219 req, req->sd, req->primary && req->replies);
6220
6221 p = req->primary;
6222 if ((long)p & 3)
6223 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd);
6224 else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2)))
6225 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd);
6226
6227 reply_state *rep;
6228 for (rep = req->replies; rep; rep=rep->next)
6229 if (rep->next == (reply_state *)~0)
6230 LogMemCorruption("UDS req->replies: %p is garbage", rep);
6231
6232 if (req->terminate == connection_termination)
6233 {
6234 registered_record_entry *r;
6235 for (r = req->u.reg_recs; r; r=r->next)
6236 if (r->next == (registered_record_entry *)~0)
6237 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r);
6238 }
6239 else if (req->terminate == regservice_termination_callback)
6240 {
6241 service_instance *s;
6242 for (s = req->u.servicereg.instances; s; s=s->next)
6243 if (s->next == (service_instance *)~0)
6244 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s);
6245 }
6246 else if (req->terminate == browse_termination_callback)
6247 {
6248 browser_t *b;
6249 for (b = req->u.browser.browsers; b; b=b->next)
6250 if (b->next == (browser_t *)~0)
6251 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b);
6252 }
6253 }
6254
6255 DNameListElem *d;
6256 for (d = SCPrefBrowseDomains; d; d=d->next)
6257 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6258 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6259
6260 ARListElem *b;
6261 for (b = LocalDomainEnumRecords; b; b=b->next)
6262 if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63)
6263 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]);
6264
6265 for (d = AutoBrowseDomains; d; d=d->next)
6266 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6267 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]);
6268
6269 for (d = AutoRegistrationDomains; d; d=d->next)
6270 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63)
6271 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]);
6272 }
6273 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
6274
6275 mDNSlocal int send_msg(request_state *const req)
6276 {
6277 reply_state *const rep = req->replies; // Send the first waiting reply
6278 ssize_t nwriten;
6279
6280 ConvertHeaderBytes(rep->mhdr);
6281 nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0);
6282 ConvertHeaderBytes(rep->mhdr);
6283
6284 if (nwriten < 0)
6285 {
6286 if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0;
6287 else
6288 {
6289 #if !defined(PLATFORM_NO_EPIPE)
6290 if (dnssd_errno == EPIPE)
6291 return(req->ts = t_terminated);
6292 else
6293 #endif
6294 {
6295 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
6296 rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno));
6297 return(t_error);
6298 }
6299 }
6300 }
6301 rep->nwriten += nwriten;
6302 return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming;
6303 }
6304
6305 mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent)
6306 {
6307 mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
6308 request_state **req = &all_requests;
6309
6310 while (*req)
6311 {
6312 request_state *const r = *req;
6313
6314 if (r->terminate == resolve_termination_callback)
6315 if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0)
6316 {
6317 r->u.resolve.ReportTime = 0;
6318 // if client received results and resolve still active
6319 if (r->u.resolve.txt && r->u.resolve.srv)
6320 LogMsgNoIdent("Client application PID[%d](%s) has received results for DNSServiceResolve(%##s) yet remains active over two minutes.", r->process_id, r->pid_name, r->u.resolve.qsrv.qname.c);
6321 }
6322
6323 // Note: Only primary req's have reply lists, not subordinate req's.
6324 while (r->replies) // Send queued replies
6325 {
6326 transfer_state result;
6327 if (r->replies->next)
6328 r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing);
6329 result = send_msg(r); // Returns t_morecoming if buffer full because client is not reading
6330 if (result == t_complete)
6331 {
6332 reply_state *fptr = r->replies;
6333 r->replies = r->replies->next;
6334 freeL("reply_state/udsserver_idle", fptr);
6335 r->time_blocked = 0; // reset failure counter after successful send
6336 r->unresponsiveness_reports = 0;
6337 continue;
6338 }
6339 else if (result == t_terminated)
6340 {
6341 LogInfo("%3d: Could not write data to client PID[%d](%s) because connection is terminated by the client", r->sd, r->process_id, r->pid_name);
6342 abort_request(r);
6343 }
6344 else if (result == t_error)
6345 {
6346 LogMsg("%3d: Could not write data to client PID[%d](%s) because of error - aborting connection", r->sd, r->process_id, r->pid_name);
6347 LogClientInfo(&mDNSStorage, r);
6348 abort_request(r);
6349 }
6350 break;
6351 }
6352
6353 if (r->replies) // If we failed to send everything, check our time_blocked timer
6354 {
6355 if (nextevent - now > mDNSPlatformOneSecond)
6356 nextevent = now + mDNSPlatformOneSecond;
6357
6358 if (mDNSStorage.SleepState != SleepState_Awake)
6359 r->time_blocked = 0;
6360 else if (!r->time_blocked)
6361 r->time_blocked = NonZeroTime(now);
6362 else if (now - r->time_blocked >= 10 * mDNSPlatformOneSecond * (r->unresponsiveness_reports+1))
6363 {
6364 int num = 0;
6365 struct reply_state *x = r->replies;
6366 while (x)
6367 {
6368 num++;
6369 x=x->next;
6370 }
6371 LogMsg("%3d: Could not write data to client PID[%d](%s) after %ld seconds, %d repl%s waiting",
6372 r->sd, r->process_id, r->pid_name, (now - r->time_blocked) / mDNSPlatformOneSecond, num, num == 1 ? "y" : "ies");
6373 if (++r->unresponsiveness_reports >= 60)
6374 {
6375 LogMsg("%3d: Client PID[%d](%s) unresponsive; aborting connection", r->sd, r->process_id, r->pid_name);
6376 LogClientInfo(&mDNSStorage, r);
6377 abort_request(r);
6378 }
6379 }
6380 }
6381
6382 if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory
6383 {
6384 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
6385 *req = r->next;
6386 freeL("request_state/udsserver_idle", r);
6387 }
6388 else
6389 req = &r->next;
6390 }
6391 return nextevent;
6392 }
6393
6394 struct CompileTimeAssertionChecks_uds_daemon
6395 {
6396 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
6397 // other overly-large structures instead of having a pointer to them, can inadvertently
6398 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
6399 char sizecheck_request_state [(sizeof(request_state) <= 2954) ? 1 : -1];
6400 char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <= 60) ? 1 : -1];
6401 char sizecheck_service_instance [(sizeof(service_instance) <= 6552) ? 1 : -1];
6402 char sizecheck_browser_t [(sizeof(browser_t) <= 1150) ? 1 : -1];
6403 char sizecheck_reply_hdr [(sizeof(reply_hdr) <= 12) ? 1 : -1];
6404 char sizecheck_reply_state [(sizeof(reply_state) <= 64) ? 1 : -1];
6405 };