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